text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:31 PST 2014 -->
<title>Uses of Interface java.applet.AudioClip (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface java.applet.AudioClip (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/applet/AudioClip.html" title="interface in java.applet">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/applet/class-use/AudioClip.html" target="_top">Frames</a></li>
<li><a href="AudioClip.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface java.applet.AudioClip" class="title">Uses of Interface<br>java.applet.AudioClip</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#java.applet">java.applet</a></td>
<td class="colLast">
<div class="block">Provides the classes necessary to create an applet and the classes an applet
uses to communicate with its applet context.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="java.applet">
<!-- -->
</a>
<h3>Uses of <a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a> in <a href="../../../java/applet/package-summary.html">java.applet</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../java/applet/package-summary.html">java.applet</a> that return <a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></code></td>
<td class="colLast"><span class="strong">AppletContext.</span><code><strong><a href="../../../java/applet/AppletContext.html#getAudioClip(java.net.URL)">getAudioClip</a></strong>(<a href="../../../java/net/URL.html" title="class in java.net">URL</a> url)</code>
<div class="block">Creates an audio clip.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></code></td>
<td class="colLast"><span class="strong">Applet.</span><code><strong><a href="../../../java/applet/Applet.html#getAudioClip(java.net.URL)">getAudioClip</a></strong>(<a href="../../../java/net/URL.html" title="class in java.net">URL</a> url)</code>
<div class="block">Returns the <code>AudioClip</code> object specified by the
<code>URL</code> argument.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></code></td>
<td class="colLast"><span class="strong">Applet.</span><code><strong><a href="../../../java/applet/Applet.html#getAudioClip(java.net.URL,%20java.lang.String)">getAudioClip</a></strong>(<a href="../../../java/net/URL.html" title="class in java.net">URL</a> url,
<a href="../../../java/lang/String.html" title="class in java.lang">String</a> name)</code>
<div class="block">Returns the <code>AudioClip</code> object specified by the
<code>URL</code> and <code>name</code> arguments.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../java/applet/AudioClip.html" title="interface in java.applet">AudioClip</a></code></td>
<td class="colLast"><span class="strong">Applet.</span><code><strong><a href="../../../java/applet/Applet.html#newAudioClip(java.net.URL)">newAudioClip</a></strong>(<a href="../../../java/net/URL.html" title="class in java.net">URL</a> url)</code>
<div class="block">Get an audio clip from the given URL.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/applet/AudioClip.html" title="interface in java.applet">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/applet/class-use/AudioClip.html" target="_top">Frames</a></li>
<li><a href="AudioClip.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| {'content_hash': 'b1f761e076b8798f40d9334534d04cdc', 'timestamp': '', 'source': 'github', 'line_count': 184, 'max_line_length': 596, 'avg_line_length': 46.09782608695652, 'alnum_prop': 0.6537373261023344, 'repo_name': 'fbiville/annotation-processing-ftw', 'id': '0809dcc7d99e22dfed50f19e59f95934014948aa', 'size': '8482', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/java/jdk7/java/applet/class-use/AudioClip.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '191178'}, {'name': 'HTML', 'bytes': '63904'}, {'name': 'Java', 'bytes': '107042'}, {'name': 'JavaScript', 'bytes': '246677'}]} |
<?php
class Controller_Inscricoes extends Controller_Auth
{
public $template = 'template';
public function before()
{
parent::before();
// Diretorio para guardar os comprovantes
Asset::add_path('uploads/', 'img');
if($this->request->action == 'nova')
{
if( ! Model_User::validate_profile() )
{
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-error',
'msg_content' => 'Você não possui permissão para realizar uma inscrição, preencha seu perfil primeiro.'
));
Response::redirect('home');
}
}
}
public function action_index()
{
$this->template->conteudo = View::forge('inscricoes/index');
}
public function action_visualizar($_inscricao_id = null)
{
if($_inscricao_id == null or ($_inscricao = Model_Inscricao::find($_inscricao_id)) == null)
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível encontrar esta inscrição.'
));
Response::redirect('home');
}
// Verifica se o usuário é admin ou se a inscrição a ser vista não foi feita por ele
if( ! Sentry::user()->is_admin() and $_inscricao->user->id != Sentry::user()->get('id'))
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível encontrar esta inscrição.'
));
Response::redirect('home');
}
$this->template->conteudo = View::forge('inscricoes/visualizar');
$this->template->conteudo->set('inscricao_info', $_inscricao);
$this->template->conteudo->set_global('pagina_titulo', 'Inscrições :: Visualizar - ' . $_inscricao_id);
}
public function action_buscar()
{
if(Input::method() == 'POST')
{
// TODO: Mudar esta busca para não usar ORM
if(($_inscricao = Model_Inscricao::find((int) Input::post('inscricao_numero'))) != null)
{
Response::redirect('inscricoes/visualizar/' . $_inscricao->id);
}
else
{
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-error',
'msg_content' => 'Não foi possível encontrar esta inscrição.'
));
}
}
Response::redirect('home');
}
/**
* Realiza uma nova inscrição em uma etapa anteriormente cadastrada
*
* @version 1.0
* @since 1.0
* @author Andreo Vieira <[email protected]>
*/
public function action_nova($_etapa_id = null)
{
// Verifica se a requisição foi feita usando o método alternativo de inscrição
// que está disponível ao visualizar uma etapa cadastrada e disponível para novas inscrições
if($_etapa_id != null and Input::method() == 'POST')
{
if($_etapa_id == (int) Input::post('etapa_id_verify'))
{
$_etapa = Model_Etapa::find($_etapa_id);
$_path = self::criarUploadPath($_etapa);
if(Utils::uploadComprovante($_path))
{
self::salvaInscricao($_etapa, $_path);
}
else
{
// Não conseguiu realizar o upload do comprovante
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível realizar esta inscrição! O formato do comprovante nao é válido.'
));
}
}
Response::redirect('etapas/visualizar/' . $_etapa_id);
}
else
{
// Neste ponto é o método normal de nova inscroção, invocando diretamente a action
// Verifica se existe uma etapa disponível para realização de inscrições
if(Model_Etapa::count(array('where' => array(array('inscricao_ate', '>=', time())))) < 1)
{
// não possui, manda uma mensagem e redireciona
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Atualmente não existe uma etapa disponível para inscrição no sistema.'
));
Response::redirect('home');
}
// Formulário de inscrição em uma etapa foi enviado
// Faz as validações e realiza a nova inscrição
if(Input::method() == 'POST')
{
// Pega apenas a etapa por hora
$_insc_etapa_id = Input::post('inscricao_etapa');
// Verifica se usuário já não está inscrito na etapa inserida
$_insc_existente = Model_Inscricao::find('first', array(
'where' => array(
array('user_id' => Sentry::user()->get('id')),
array('etapa_id' => $_insc_etapa_id)
)
));
// Verifica se usuário já não está inscrito na etapa inserida
if($_insc_existente != null)
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível realizar esta inscrição! Você já está cadastrado nesta etapa.'
));
}
else
{
// O usuário ainda não está inscrito
// Faz o upload do comprovante e realiza a inscrição
$_etapa = Model_Etapa::find($_insc_etapa_id);
$_path = self::criarUploadPath($_etapa);
if(Utils::uploadComprovante($_path))
{
self::salvaInscricao($_etapa, $_path);
}
else
{
// Não conseguiu realizar o upload do comprovante
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível realizar esta inscrição! O formato do comprovante nao é válido.'
));
}
}
Response::redirect('inscricoes/nova');
}
// Procura as etapas com inscrições abertas
$data_etapas = Model_Etapa::find('all', array(
'where' => array(
array('inscricao_ate', '>=', time())
),
'related' => array(
'campeonato' => array(
'order_by' => array('nome' => 'desc')
)
)
));
// Renderiza o formulário de inscrição
$this->template->conteudo = View::forge('inscricoes/nova');
$this->template->conteudo->set('etapas', $data_etapas);
}
}
/**
* Action responsável por excluir uma inscrição
* Se o usuário é o criador da inscrição de id $_inscricao_id ou é administrador do sistema a inscrição é removida
*
* @author Andreo Vieira <[email protected]>
* @version 1.0
* @since 1.0
* @param int $_inscricao_id ID da inscrição a ser excluída
*/
public function action_excluir($_inscricao_id = null)
{
// Verifica se existe uma inscrição com id $_inscricao_id
if($_inscricao_id == null || ($_inscricao = Model_Inscricao::find($_inscricao_id)) == null)
{
Response::redirect('home');
}
if(Input::method() == 'POST')
{
// Verifica se o usuário é admin do sistema ou dono da inscrição a ser excluída
if(! Sentry::user()->is_admin() && ($_inscricao->user->id != Sentry::user()->get('id')))
{
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-error',
'msg_content' => 'Você não pode excluir uma inscrição feita por outra pessoa.'
));
Response::redirect('home');
}
$comprovante = $_inscricao->comprovante;
if($_inscricao->delete())
{
if($comprovante)
{
// Deleta o comprovante
File::delete(Config::get('sysconfig.app.upload_root') . $_inscricao->comprovante);
}
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-success',
'msg_content' => 'Inscrição excluída com sucesso.'
));
}
else
{
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-error',
'msg_content' => 'Não foi possível excluir esta inscrição.'
));
}
Response::redirect('home');
}
else
{
$this->template->conteudo = View::forge('inscricoes/excluir', array('inscricao_info' => $_inscricao));
}
}
public function action_responder($_inscricao_id = null)
{
if((Input::method() == 'POST' and $_inscricao_id != null) or (Input::method() == 'POST' and Input::is_ajax()))
{
$_inscricao = Model_Inscricao::find(Input::is_ajax() ? Input::post('inscricaoID') : $_inscricao_id);
if($_inscricao != null)
{
$_nova_resposta = new Model_Resposta;
$_nova_resposta->conteudo = Input::post('inscricao_resposta');
$_nova_resposta->user = Model_User::find(Sentry::user()->get('id'));
$_nova_resposta->inscricao = $_inscricao;
if($_nova_resposta->save())
{
if(Input::is_ajax())
{
$this->response(array('valid' => true, 'msg' => 'Sua resposta foi enviada com sucesso.'));
}
else
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nSuccess',
'msg_content' => 'Sua resposta foi enviada com sucesso.'
));
Response::redirect('inscricoes/visualizar/' . $_inscricao_id);
}
}
else
{
if(Input::is_ajax())
{
$this->response(array('valid' => false, 'msg' => 'Não foi possível enviar a sua resposta.'));
}
else
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível enviar a sua resposta.'
));
Response::redirect('inscricoes/visualizar/' . $_inscricao_id);
}
}
}
}
else
{
Response::redirect('home');
}
}
public function action_download_comprovante($_inscricao_id = null)
{
if(($_inscricao = Model_Inscricao::find($_inscricao_id)) == null)
{
Response::redirect('home');
}
// Verifica se o usuário é admin do sistema ou dono da inscrição a ser excluída
if(! Sentry::user()->is_admin() && ($_inscricao->user->id != Sentry::user()->get('id')))
{
Session::set_flash('flash_msg', array(
'msg_type' => 'alert-error',
'msg_content' => 'Você não pode fazer download do comprovante de uma inscrição feita por outra pessoa.'
));
Response::redirect('home');
}
File::download(DOCROOT . Config::get('sysconfig.app.upload_root') . $_inscricao->comprovante);
}
public static function criarUploadPath($_etapa)
{
$_path = Str::lower(Inflector::friendly_title($_etapa->campeonato->nome)) . '/';
$_path .= Str::lower(Inflector::friendly_title($_etapa->nome)) . '/';
return $_path;
}
private static function salvaInscricao($_etapa, $_path)
{
// Upload realizado com sucesso, realiza o resto da inscrição
$_comprovante = Arr::get(Upload::get_files(), 0);
$_nova_inscricao = new Model_Inscricao;
$_nova_inscricao->etapa = $_etapa;
$_nova_inscricao->categoria = Input::post('inscricao_categoria');
$_nova_inscricao->observacao = Input::post('inscricao_observacao');
$_nova_inscricao->status = Model_Inscricao::INSCRICAO_PENDENTE;
$_nova_inscricao->comprovante = $_path . Arr::get($_comprovante, 'saved_as');
$_nova_inscricao->user = Model_User::find(Sentry::user()->get('id'));
// Salva a inscrição no banco de dados
if($_nova_inscricao->save())
{
Session::set_flash('flash_msg', array(
'msg_type' => 'nSuccess',
'msg_content' => 'Seu pedido de inscrição foi enviado com sucesso.'
));
}
else
{
// Não conseguiu salvar a inscrição, envia uma mensagem e redireciona
Session::set_flash('flash_msg', array(
'msg_type' => 'nFailure',
'msg_content' => 'Não foi possível realizar esta inscrição.'
));
}
Response::redirect('home');
}
// Métodos REST -----------------------
public function post_excluir()
{
if(Sentry::check())
{
$_inscricao_id = Input::post('inscricao_id');
// Verifica se existe uma inscrição com id $_inscricao_id
if($_inscricao_id == null || ($_inscricao = Model_Inscricao::find($_inscricao_id)) == null)
{
$this->response(array('valid' => false, 'msg' => 'Não foi possível encontrar esta inscrição.'), 200);
}
else
{
// Verifica se o usuário é admin do sistema ou dono da inscrição a ser excluída
if(! Sentry::user()->is_admin() && ($_inscricao->user->id != Sentry::user()->get('id')))
{
$this->response(array('valid' => false, 'msg' => 'Você não pode excluir uma inscrição feita por outra pessoa.'));
}
else
{
$comprovante = $_inscricao->comprovante;
if($_inscricao->delete())
{
if($comprovante)
{
// Deleta o comprovante
File::delete(Config::get('sysconfig.app.upload_root') . $_inscricao->comprovante);
}
$this->response(array('valid' => true, 'msg' => 'Inscrição excluída com sucesso.'), 200);
}
else
{
$this->response(array('valid' => false, 'msg' => 'Não foi possível excluir esta inscrição.'), 200);
}
}
}
}
else
{
$this->response(null, 200);
}
}
public function get_minhas_inscricoes()
{
if(Sentry::check())
{
$_inscricoesData = Model_User::find(Sentry::user()->get('id'))->inscricoes;
$_returnData = array();
foreach($_inscricoesData as $_inscricao)
{
$_acoes = Html::anchor('inscricoes/visualizar/' . $_inscricao->id, '<span class="iconb" data-icon=""></span>', array(
'class' => 'tablectrl_large bDefault tipS',
'title' => 'Visualizar Inscrição'
));
$_tableData = array(
'id' => $_inscricao->id,
'etapa' => Html::anchor('etapas/visualizar/' . $_inscricao->etapa->id, $_inscricao->etapa->nome),
'campeonato' => $_inscricao->etapa->campeonato->nome,
'status' => Utils::status2label($_inscricao->status),
'acoes' => $_acoes
);
$_returnData[] = $_tableData;
}
$this->response(array('aaData' => $_returnData));
}
else
{
$this->response(array('aaData' => null));
}
}
} | {'content_hash': '4cb2c7214b02da48543769534f4f5104', 'timestamp': '', 'source': 'github', 'line_count': 448, 'max_line_length': 142, 'avg_line_length': 37.810267857142854, 'alnum_prop': 0.4682094574650216, 'repo_name': 'andreoav/inscricoes-natura', 'id': '0cc7d183540fdd475eadd7d552ba6e1857d9866a', 'size': '17119', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fuel/app/classes/controller/inscricoes.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '450119'}, {'name': 'PHP', 'bytes': '1701737'}]} |
from django.db import models
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils.timezone import now
class TimeStamped(models.Model):
""" Provides created and updated timestamps on models. """
created = models.DateTimeField(null=True, editable=False)
updated = models.DateTimeField(null=True, editable=False)
class Meta:
abstract = True
def save(self, *args, **kwargs):
_now = now()
self.updated = _now
if not self.id:
self.created = _now
super(TimeStamped, self).save(*args, **kwargs)
class Tag(TimeStamped):
key = models.CharField(max_length=50, db_index=True)
def __unicode__(self):
return u"%s %d" % (self.key, self.pk)
def add_kv(self, key, value):
return KeyValue.objects.get_or_create(tag=self, key=key, value=value)
class KeyValue(models.Model):
tag = models.ForeignKey(Tag, related_name='kv_pairs', db_index=True)
key = models.CharField(max_length=50, db_index=True)
value = models.CharField(max_length=100)
def __unicode__(self):
return u"%s:%s" % (self.key, self.value)
class Meta:
unique_together = (('tag', 'key'),)
class TaggedItem(TimeStamped):
""" Binds tags with generic models. """
tag = models.ForeignKey(Tag, related_name='items', null=True)
object_id = models.IntegerField(db_index=True)
content_type = models.ForeignKey(ContentType)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = (('tag', 'object_id', 'content_type'),)
def __unicode__(self):
return u"%s - %s" % (self.content_object, self.tag)
| {'content_hash': '360f375ec02aea6a40d2eec4b7171910', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 77, 'avg_line_length': 30.736842105263158, 'alnum_prop': 0.6569634703196348, 'repo_name': 'ozen/django-kvtags', 'id': 'cb51203dd03cda14f158450b44dee870cf4d8bf1', 'size': '1752', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kvtags/models.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '860'}, {'name': 'Python', 'bytes': '30283'}]} |
package main // <<<<< godoc,1,1,1,1,pass
import "fmt"
func main() {
Exported()
}
func Exported() {
fmt.Println("Hello, Go")
}
type Shaper interface {
}
type Rectangle struct {
}
type square struct {
}
type circle interface {
}
type Oval struct {
}
func A() { }; func B() { }; func c() { }; func D() { }
type alpha struct { }; type Beta struct { }
| {'content_hash': '4d8a4a6b350208bd81cf8421773a0443', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 54, 'avg_line_length': 11.966666666666667, 'alnum_prop': 0.596100278551532, 'repo_name': 'steffimariya/godoctor', 'id': '502b1fd69af7b1bc3d6e9b1160efdaf111cd265d', 'size': '359', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'refactoring/testdata/godoc/010-threeOrMoreFuncLineTest/main.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '1703'}, {'name': 'Go', 'bytes': '1184774'}, {'name': 'Makefile', 'bytes': '2234'}, {'name': 'Shell', 'bytes': '1465'}, {'name': 'VimL', 'bytes': '13856'}]} |
@extends('api.master')
@section('title', 'Suyabay: All your Apps')
@endsection
@section('content')
@include('api.includes.contents.allappdetails')
@endsection | {'content_hash': '239e8cb9d216a39a3498b17770c66f0d', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 50, 'avg_line_length': 15.181818181818182, 'alnum_prop': 0.7125748502994012, 'repo_name': 'andela/suyabay', 'id': '749d9c390afd583764c917f0d1273beb36a83ba5', 'size': '167', 'binary': False, 'copies': '1', 'ref': 'refs/heads/staging', 'path': 'resources/views/api/pages/allappdetails.blade.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '29609'}, {'name': 'HTML', 'bytes': '142300'}, {'name': 'JavaScript', 'bytes': '181517'}, {'name': 'PHP', 'bytes': '301445'}]} |
"""
Tests links to external sites
"""
from django.test import TestCase
from apps.link import control as link_control
class ValidSiteLinks(TestCase):
def test_couchsurfing_com_links(self):
"""
Tests that .com urls are accepted
"""
self.assertEqual(True, link_control.valid_profile_format("https://couchsurfing.com/people/deivid_rodriguez", "COUCHSURFING"))
| {'content_hash': 'bffd4bfa9bb93e608f786ecc66798d46', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 133, 'avg_line_length': 26.4, 'alnum_prop': 0.6994949494949495, 'repo_name': 'F483/bikesurf.org', 'id': 'ec723ec41cbcdd32c83f8e23725489c604ecdd9a', 'size': '523', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apps/link/tests.py', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1950764'}, {'name': 'HTML', 'bytes': '6079063'}, {'name': 'JavaScript', 'bytes': '284942'}, {'name': 'Makefile', 'bytes': '4210'}, {'name': 'Python', 'bytes': '215658'}, {'name': 'Ruby', 'bytes': '4418'}, {'name': 'Shell', 'bytes': '553'}]} |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('zadania', '0003_auto_20201213_2140'),
]
operations = [
migrations.AddField(
model_name='zadanie',
name='notify_first_user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='zadania', to=settings.AUTH_USER_MODEL, verbose_name='wysyłać powiadomienie do: '),
),
migrations.AddField(
model_name='zadanie',
name='notify_second_user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='wysyłać powiadomienie do: '),
),
]
| {'content_hash': '35ff3019745268d2969242c4f6a3990d', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 200, 'avg_line_length': 36.96153846153846, 'alnum_prop': 0.6659729448491155, 'repo_name': 'szymanskirafal/ab', 'id': '3d7919971bdd1e2c40a9ad560b4c2a0fa524de06', 'size': '1035', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'zadania/migrations/0004_auto_20210112_2238.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '46463'}, {'name': 'HTML', 'bytes': '50595'}, {'name': 'JavaScript', 'bytes': '88987'}, {'name': 'Python', 'bytes': '119395'}]} |
local Instance = import("../Instance")
describe("instances.ObjectValue", function()
it("should instantiate", function()
local instance = Instance.new("ObjectValue")
assert.not_nil(instance)
assert.equal("Value", instance.Name)
assert.equal(nil, instance.Value)
end)
it("should set values", function()
local instance = Instance.new("ObjectValue")
instance.Value = instance
assert.equal(instance.Value, instance)
end)
end) | {'content_hash': 'fc4a3b092ae67da1c1508ab9bfeef12f', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 46, 'avg_line_length': 23.31578947368421, 'alnum_prop': 0.7268623024830699, 'repo_name': 'LPGhatguy/lemur', 'id': 'bb885e67080bd47258d34f96e2d9b13d507a78d2', 'size': '443', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/instances/ObjectValue_spec.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '190701'}, {'name': 'Shell', 'bytes': '109'}]} |
using Kernel_alpha.x86.Intrinsic;
using System;
using System.Runtime.InteropServices;
namespace Kernel_alpha.Drivers.ACPI
{
public unsafe static class misc
{
public static int Compare (string c1, byte* c2)
{
for (int i = 0; i < c1.Length; i++)
{
if (c1[i] != (char)c2[i])
return -1;
}
return 0;
}
public static int acpiCheckHeader (byte* ptr, string sig)
{
return Compare (sig, ptr);
}
// RSD
public static bool Check_RSD (uint address)
{
byte sum = 0;
byte* check = (byte*)address;
for (int i = 0; i < 20; i++)
sum += *(check++);
return (sum == 0);
}
}
/// <summary>
/// RSD Table
/// </summary>
[StructLayout (LayoutKind.Sequential, Pack = 1)]
public unsafe struct RSDPtr
{
public fixed byte Signature[8];
public byte CheckSum;
public fixed byte OemID[6];
public byte Revision;
public int RsdtAddress;
};
/// <summary>
/// FACP Table
/// </summary>
[StructLayout (LayoutKind.Sequential, Pack = 1)]
public unsafe struct FACP
{
public fixed byte Signature[4];
public int Length;
public fixed byte unneded1[40 - 8];
public int* DSDT;
public fixed byte unneded2[48 - 44];
public int* SMI_CMD;
public byte ACPI_ENABLE;
public byte ACPI_DISABLE;
public fixed byte unneded3[64 - 54];
public int* PM1a_CNT_BLK;
public int* PM1b_CNT_BLK;
public fixed byte unneded4[89 - 72];
public byte PM1_CNT_LEN;
};
}
| {'content_hash': '247a98e6eff933046e71b5bc80e940fd', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 65, 'avg_line_length': 26.114285714285714, 'alnum_prop': 0.49835886214442016, 'repo_name': 'amaneureka/AtomOS', 'id': '21dc1d3c2fc775dd7463a8a6b4d855350fe11e1a', 'size': '1830', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Kernel/Kernel_alpha/Drivers/ACPI/misc.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '262'}, {'name': 'Batchfile', 'bytes': '5394'}, {'name': 'C', 'bytes': '4993'}, {'name': 'C#', 'bytes': '1655500'}, {'name': 'Makefile', 'bytes': '357'}, {'name': 'Shell', 'bytes': '14120'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Thu Jun 18 14:08:48 EDT 2015 -->
<title>Uses of Class org.apache.cassandra.locator.SnitchProperties (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.locator.SnitchProperties (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/locator/SnitchProperties.html" title="class in org.apache.cassandra.locator">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/locator/class-use/SnitchProperties.html" target="_top">Frames</a></li>
<li><a href="SnitchProperties.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.locator.SnitchProperties" class="title">Uses of Class<br>org.apache.cassandra.locator.SnitchProperties</h2>
</div>
<div class="classUseContainer">No usage of org.apache.cassandra.locator.SnitchProperties</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/locator/SnitchProperties.html" title="class in org.apache.cassandra.locator">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/locator/class-use/SnitchProperties.html" target="_top">Frames</a></li>
<li><a href="SnitchProperties.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| {'content_hash': '4c15a089a4c2914f71a3eb6e42a3d681', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 153, 'avg_line_length': 37.80172413793103, 'alnum_prop': 0.6212086659064995, 'repo_name': 'anuragkapur/cassandra-2.1.2-ak-skynet', 'id': '861e776086b803c658b0d594d97da5a297acebbc', 'size': '4385', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apache-cassandra-2.0.16/javadoc/org/apache/cassandra/locator/class-use/SnitchProperties.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '59670'}, {'name': 'PowerShell', 'bytes': '37758'}, {'name': 'Python', 'bytes': '622552'}, {'name': 'Shell', 'bytes': '100474'}, {'name': 'Thrift', 'bytes': '78926'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hardware: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.1 / hardware - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hardware
<small>
8.8.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-07-19 14:21:56 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-19 14:21:56 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
coq 8.5.1 Formal proof management system.
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/hardware"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Hardware"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: hardware verification" "keyword: comparator circuit" "category: Computer Science/Architecture" "category: Miscellaneous/Extracted Programs/Hardware" ]
authors: [ "Solange Coupet-Grimal & Line Jakubiec" ]
bug-reports: "https://github.com/coq-contribs/hardware/issues"
dev-repo: "git+https://github.com/coq-contribs/hardware.git"
synopsis: "Verification and synthesis of hardware linear arithmetic structures"
description: """
Verification and synthesis of hardware linear arithmetic
structures. Example of a left-to-right comparator.
Three approaches are tackled :
- the usual verification of a circuit, consisting in proving that the
description satisfies the specification,
- the synthesis of a circuit from its specification using the Coq extractor,
- the same approach as above but using the Program tactic."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/hardware/archive/v8.8.0.tar.gz"
checksum: "md5=743a7712be8f333b3da803270108d76b"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hardware.8.8.0 coq.8.5.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.1).
The following dependencies couldn't be met:
- coq-hardware -> coq >= 8.8
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hardware.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '254f82a6f3502ca65214256bcf974f87', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 208, 'avg_line_length': 42.44970414201183, 'alnum_prop': 0.558265960412601, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '7814dd6f187ec2c2e65f4a2455a0d6bdeed3870b', 'size': '7176', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.05.0-2.0.6/released/8.5.1/hardware/8.8.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
package gw.internal.schema.gw.xsd.w3c.xmlschema;
/***************************************************************************/
/* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */
/* THIS CODE CAN BE REGENERATED USING 'xsd-codegen' */
/***************************************************************************/
public class Sequence extends gw.xml.XmlElement implements gw.internal.xml.IXmlGeneratedClass {
public static final javax.xml.namespace.QName $ATTRIBUTE_QNAME_Id = new javax.xml.namespace.QName( "", "id", "" );
public static final javax.xml.namespace.QName $ATTRIBUTE_QNAME_MaxOccurs = new javax.xml.namespace.QName( "", "maxOccurs", "" );
public static final javax.xml.namespace.QName $ATTRIBUTE_QNAME_MinOccurs = new javax.xml.namespace.QName( "", "minOccurs", "" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Annotation = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "annotation", "xs" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Any = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "any", "xs" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Choice = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "choice", "xs" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Element = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "element", "xs" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Group = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "group", "xs" );
public static final javax.xml.namespace.QName $ELEMENT_QNAME_Sequence = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "sequence", "xs" );
public static final javax.xml.namespace.QName $QNAME = new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "sequence", "xs" );
public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
@Override
protected gw.lang.reflect.IType init() {
return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.xmlschema.Sequence" );
}
};
private static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPEINSTANCETYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) {
@Override
protected gw.lang.reflect.IType init() {
return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup" );
}
};
public Sequence() {
this( new gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup() );
}
public Sequence( gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup typeInstance ) {
super( $QNAME, TYPE.get(), TYPEINSTANCETYPE.get(), typeInstance );
}
protected Sequence( javax.xml.namespace.QName qname, gw.lang.reflect.IType type, gw.lang.reflect.IType schemaDefinedTypeInstanceType, gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.AnyType typeInstance ) {
super( qname, type, schemaDefinedTypeInstanceType, typeInstance );
}
public gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup getTypeInstance() {
//noinspection RedundantCast
return (gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup) super.getTypeInstance();
}
public void setTypeInstance( gw.internal.schema.gw.xsd.w3c.xmlschema.types.complex.ExplicitGroup param ) {
super.setTypeInstance( param );
}
public gw.internal.schema.gw.xsd.w3c.xmlschema.Annotation Annotation() {
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Annotation) TYPE.get().getTypeInfo().getProperty( "Annotation" ).getAccessor().getValue( this );
}
public void setAnnotation$( gw.internal.schema.gw.xsd.w3c.xmlschema.Annotation param ) {
TYPE.get().getTypeInfo().getProperty( "Annotation" ).getAccessor().setValue( this, param );
}
public java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Any> Any() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Any>) TYPE.get().getTypeInfo().getProperty( "Any" ).getAccessor().getValue( this );
}
public void setAny$( java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Any> param ) {
TYPE.get().getTypeInfo().getProperty( "Any" ).getAccessor().setValue( this, param );
}
public java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Choice> Choice() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Choice>) TYPE.get().getTypeInfo().getProperty( "Choice" ).getAccessor().getValue( this );
}
public void setChoice$( java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Choice> param ) {
TYPE.get().getTypeInfo().getProperty( "Choice" ).getAccessor().setValue( this, param );
}
public java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Element> Element() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Element>) TYPE.get().getTypeInfo().getProperty( "Element" ).getAccessor().getValue( this );
}
public void setElement$( java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Element> param ) {
TYPE.get().getTypeInfo().getProperty( "Element" ).getAccessor().setValue( this, param );
}
public java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Group> Group() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Group>) TYPE.get().getTypeInfo().getProperty( "Group" ).getAccessor().getValue( this );
}
public void setGroup$( java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.anonymous.elements.ExplicitGroup_Group> param ) {
TYPE.get().getTypeInfo().getProperty( "Group" ).getAccessor().setValue( this, param );
}
public java.lang.String Id() {
return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "Id" ).getAccessor().getValue( this );
}
public void setId$( java.lang.String param ) {
TYPE.get().getTypeInfo().getProperty( "Id" ).getAccessor().setValue( this, param );
}
public java.lang.String MaxOccurs() {
return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "MaxOccurs" ).getAccessor().getValue( this );
}
public void setMaxOccurs$( java.lang.String param ) {
TYPE.get().getTypeInfo().getProperty( "MaxOccurs" ).getAccessor().setValue( this, param );
}
public java.math.BigInteger MinOccurs() {
return (java.math.BigInteger) TYPE.get().getTypeInfo().getProperty( "MinOccurs" ).getAccessor().getValue( this );
}
public void setMinOccurs$( java.math.BigInteger param ) {
TYPE.get().getTypeInfo().getProperty( "MinOccurs" ).getAccessor().setValue( this, param );
}
@SuppressWarnings( {"MethodNameSameAsClassName"} )
public java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence> Sequence() {
//noinspection unchecked
return (java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence>) TYPE.get().getTypeInfo().getProperty( "Sequence" ).getAccessor().getValue( this );
}
public void setSequence$( java.util.List<gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence> param ) {
TYPE.get().getTypeInfo().getProperty( "Sequence" ).getAccessor().setValue( this, param );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( byte[] byteArray ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( byte[].class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { byteArray } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( byte[] byteArray, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( byte[].class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { byteArray, options } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.File file ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.File.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { file } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.File file, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.File.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { file, options } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.InputStream inputStream ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.InputStream.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { inputStream } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.InputStream inputStream, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.InputStream.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { inputStream, options } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.Reader reader ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.Reader.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { reader } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.io.Reader reader, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.io.Reader.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { reader, options } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.lang.String xmlString ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.lang.String.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { xmlString } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.lang.String xmlString, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.lang.String.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { xmlString, options } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.net.URL url ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.net.URL.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { url } );
}
public static gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence parse( java.net.URL url, gw.xml.XmlParseOptions options ) {
//noinspection RedundantArrayCreation
return (gw.internal.schema.gw.xsd.w3c.xmlschema.Sequence) TYPE.get().getTypeInfo().getMethod( "parse", gw.lang.reflect.TypeSystem.get( java.net.URL.class ), gw.lang.reflect.TypeSystem.get( gw.xml.XmlParseOptions.class ) ).getCallHandler().handleCall( null, new java.lang.Object[] { url, options } );
}
@SuppressWarnings( {"UnusedDeclaration"} )
private static final long FINGERPRINT = 2110283714877373226L;
}
| {'content_hash': 'f78e6f1ba28196bf541b027171617299', 'timestamp': '', 'source': 'github', 'line_count': 204, 'max_line_length': 318, 'avg_line_length': 63.63235294117647, 'alnum_prop': 0.7262922733225483, 'repo_name': 'pdalbora/gosu-lang', 'id': '99932b62d5ae0271da9f15263a3b8277d54dbe2f', 'size': '12981', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/xmlschema/Sequence.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is subject to the terms and conditions defined in the
files 'LICENSE' and 'NOTICE', which are part of this source
code package.
-->
<forms xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/widget-form.xsd">
<!-- Temporal Expression forms -->
<form name="FindTemporalExpression" target="findTemporalExpression" type="single">
<actions>
<set field="expressionTypeList" value="${groovy:org.ofbiz.service.calendar.ExpressionUiHelper.getExpressionTypeList(uiLabelMap);}" type="List"/>
</actions>
<field name="tempExprId" title="${uiLabelMap.TemporalExpressionId}"><text-find/></field>
<field name="description" title="${uiLabelMap.CommonDescription}"><text-find/></field>
<!-- <field name="tempExprTypeId" title="${uiLabelMap.TemporalExpressionType}">
<drop-down allow-empty="true">
<list-options list-name="expressionTypeList" key-name="value" description="description"/>
</drop-down>
</field> -->
<field name="noConditionFind"><hidden value="Y"/><!-- if this isn't there then with all fields empty no query will be done --></field>
<field name="submitAction" title="${uiLabelMap.CommonFind}" widget-style="${styles.link_run_sys} ${styles.action_find}"><submit button-type="button"/></field>
</form>
<form name="BasicExpressionList" type="list"
odd-row-style="alternate-row" header-row-style="header-row-2"> <!-- orig: default-table-style=-style="basic-table hover-bar" -->
<field name="tempExprId" title="${uiLabelMap.TemporalExpressionId}" sort-field="true" widget-style="${styles.link_nav_info_id} ${styles.action_view}">
<hyperlink also-hidden="false" target-type="plain" description="${tempExprId}" target="editTemporalExpression">
<parameter param-name="tempExprId"/>
</hyperlink>
</field>
<field name="tempExprTypeId" title="${uiLabelMap.TemporalExpressionType}" sort-field="true"><display/></field>
<field name="description" sort-field="true"><display/></field>
<field name="date1" sort-field="true"><display/></field>
<field name="date2" sort-field="true"><display/></field>
<field name="integer1" sort-field="true"><display/></field>
<field name="integer2" sort-field="true"><display/></field>
<field name="string1" sort-field="true"><display/></field>
<field name="string2" sort-field="true"><display/></field>
</form>
<form name="ListTemporalExpressions" extends="BasicExpressionList" list-name="listIt" paginate="true">
<actions>
<set field="parameters.sortField" from-field="parameters.sortField" default-value="tempExprId"/>
<service service-name="performFind" result-map="result" result-map-list="listIt">
<field-map field-name="inputFields" from-field="parameters"/>
<field-map field-name="entityName" value="TemporalExpression"/>
<field-map field-name="orderBy" from-field="parameters.sortField"/>
<field-map field-name="viewIndex" from-field="viewIndex"/>
<field-map field-name="viewSize" from-field="viewSize"/>
</service>
</actions>
</form>
<form name="ListChildExpressions" extends="BasicExpressionList" list-name="childExpressionList" paginate-target="editTemporalExpression?tempExprId=${tempExprId}">
<field name="exprAssocType"><display/></field>
<field name="deleteAction" title=" " widget-style="${styles.link_run_sys} ${styles.action_remove}">
<hyperlink also-hidden="false" description="${uiLabelMap.CommonDelete}" target="deleteTemporalExpressionAssoc">
<parameter param-name="tempExprId" from-field="parameters.tempExprId"/>
<parameter param-name="fromTempExprId"/>
<parameter param-name="toTempExprId" from-field="tempExprId"/>
</hyperlink>
</field>
</form>
</forms>
| {'content_hash': '363e85da08a5eb94daa28a4fc4a5f151', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 166, 'avg_line_length': 60.8235294117647, 'alnum_prop': 0.653046421663443, 'repo_name': 'ilscipio/scipio-erp', 'id': 'c5b667536b98119c46abf66e33be3b59be10ae55', 'size': '4136', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'framework/webtools/widget/tempExprForms.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '15540'}, {'name': 'CSS', 'bytes': '533213'}, {'name': 'FreeMarker', 'bytes': '6482124'}, {'name': 'Groovy', 'bytes': '2254105'}, {'name': 'HTML', 'bytes': '4409922'}, {'name': 'Java', 'bytes': '23079876'}, {'name': 'JavaScript', 'bytes': '1106310'}, {'name': 'Ruby', 'bytes': '2377'}, {'name': 'SCSS', 'bytes': '514759'}, {'name': 'Shell', 'bytes': '66335'}, {'name': 'XSLT', 'bytes': '1712'}]} |
@interface HYBTestCell ()
@property (nonatomic, strong) UILabel *optionalAnswerLabel;
@property (nonatomic, strong) UIButton *radioButton;
@property (nonatomic, copy) NSIndexPath *indexPath;
@end
@implementation HYBTestCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.radioButton setImage:[UIImage imageNamed:@"unselect"] forState:UIControlStateNormal];
[self.radioButton setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
[self.radioButton sizeToFit];
self.radioButton.center = CGPointMake(self.radioButton.frame.size.width / 2 + 15,
self.contentView.center.y);
[self.contentView addSubview:self.radioButton];
self.radioButton.userInteractionEnabled = NO;
self.optionalAnswerLabel = [[UILabel alloc] init];
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat x = self.radioButton.frame.size.width + self.radioButton.frame.origin.x + 20;
self.optionalAnswerLabel.frame = CGRectMake(x,
0,
screenWidth - x - 15,
self.contentView.frame.size.height);
self.optionalAnswerLabel.numberOfLines = 0;
[self.contentView addSubview:self.optionalAnswerLabel];
}
return self;
}
- (void)configCellWithModel:(HYBOptionalAnswerModel *)model atIndexPath:(NSIndexPath *)indexPath {
self.indexPath = [indexPath copy];
self.radioButton.selected = model.isSelected;
self.optionalAnswerLabel.text = model.optionalAnswerSummary;
}
- (void)setCellSelected:(BOOL)selected {
self.radioButton.selected = selected;
}
@end
| {'content_hash': 'fb91c132fb61bc03f62503ec6fbee113', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 103, 'avg_line_length': 39.875, 'alnum_prop': 0.6912225705329154, 'repo_name': 'CoderJackyHuang/MultiSelectMutexDemo', 'id': 'ad0df32e1d2b82a94bf1007cc60b25e60a5665c1', 'size': '2117', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MultipleSelectMutedDemo/HYBTestCell.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '14551'}]} |
"""Test the Almond config flow."""
import asyncio
from http import HTTPStatus
from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.almond import config_flow
from homeassistant.components.almond.const import DOMAIN
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.helpers import config_entry_oauth2_flow
from tests.common import MockConfigEntry
CLIENT_ID_VALUE = "1234"
CLIENT_SECRET_VALUE = "5678"
async def test_import(hass):
"""Test that we can import a config entry."""
with patch("pyalmond.WebAlmondAPI.async_list_apps"):
assert await setup.async_setup_component(
hass,
DOMAIN,
{DOMAIN: {"type": "local", "host": "http://localhost:3000"}},
)
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert entry.data["type"] == "local"
assert entry.data["host"] == "http://localhost:3000"
async def test_import_cannot_connect(hass):
"""Test that we won't import a config entry if we cannot connect."""
with patch(
"pyalmond.WebAlmondAPI.async_list_apps", side_effect=asyncio.TimeoutError
):
assert await setup.async_setup_component(
hass,
DOMAIN,
{DOMAIN: {"type": "local", "host": "http://localhost:3000"}},
)
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 0
async def test_hassio(hass):
"""Test that Hass.io can discover this integration."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_HASSIO},
data={"addon": "Almond add-on", "host": "almond-addon", "port": "1234"},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "hassio_confirm"
with patch(
"homeassistant.components.almond.async_setup_entry", return_value=True
) as mock_setup:
result2 = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert len(mock_setup.mock_calls) == 1
assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert entry.data["type"] == "local"
assert entry.data["host"] == "http://almond-addon:1234"
async def test_abort_if_existing_entry(hass):
"""Check flow abort when an entry already exist."""
MockConfigEntry(domain=DOMAIN).add_to_hass(hass)
flow = config_flow.AlmondFlowHandler()
flow.hass = hass
result = await flow.async_step_user()
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed"
result = await flow.async_step_import({})
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed"
result = await flow.async_step_hassio({})
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "single_instance_allowed"
async def test_full_flow(
hass, hass_client_no_auth, aioclient_mock, current_request_with_host
):
"""Check full flow."""
assert await setup.async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"type": "oauth2",
CONF_CLIENT_ID: CLIENT_ID_VALUE,
CONF_CLIENT_SECRET: CLIENT_SECRET_VALUE,
},
"http": {"base_url": "https://example.com"},
},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_EXTERNAL_STEP
assert result["url"] == (
"https://almond.stanford.edu/me/api/oauth2/authorize"
f"?response_type=code&client_id={CLIENT_ID_VALUE}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}&scope=profile+user-read+user-read-results+user-exec-command"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == HTTPStatus.OK
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post(
"https://almond.stanford.edu/me/api/oauth2/token",
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with patch(
"homeassistant.components.almond.async_setup_entry", return_value=True
) as mock_setup:
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert len(mock_setup.mock_calls) == 1
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
assert entry.data["type"] == "oauth2"
assert entry.data["host"] == "https://almond.stanford.edu/me"
| {'content_hash': '0df35aa21b6e77990a40a35bdbf55beb', 'timestamp': '', 'source': 'github', 'line_count': 156, 'max_line_length': 87, 'avg_line_length': 34.82692307692308, 'alnum_prop': 0.6412663353579974, 'repo_name': 'aronsky/home-assistant', 'id': 'e0e88d0f43b803aaf27d39c48cedc54579ade49a', 'size': '5433', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'tests/components/almond/test_config_flow.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2443'}, {'name': 'Python', 'bytes': '38448521'}, {'name': 'Shell', 'bytes': '4910'}]} |
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**status_code** | **str** | | [optional]
**message** | **str** | | [optional]
**list** | [**list[Complaint]**](Complaint.md) | | [optional]
**data** | [**Complaint**](Complaint.md) | | [optional]
**records** | **int** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
| {'content_hash': 'fff72878e0487d4fa2686062f7150598', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 161, 'avg_line_length': 45.72727272727273, 'alnum_prop': 0.5228628230616302, 'repo_name': 'iEngage/python-sdk', 'id': '6ab8bdbf3dd76bc4273b5ac07bb8a65f956e4fd1', 'size': '543', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/VerveResponseComplaint.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '2373684'}, {'name': 'Shell', 'bytes': '1664'}]} |
<?php
namespace Rz\SearchBundle;
use Solarium\Core\Client\Request as SolariumRequest;
use Solarium\Core\Client\Response as SolariumResponse;
use Solarium\Core\Client\Endpoint as SolariumEndpoint;
use Solarium\Core\Plugin\Plugin as SolariumPlugin;
use Solarium\Core\Event\Events as SolariumEvents;
use Solarium\Core\Event\PreExecuteRequest as SolariumPreExecuteRequestEvent;
use Solarium\Core\Event\PostExecuteRequest as SolariumPostExecuteRequestEvent;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
class Logger extends SolariumPlugin implements DataCollectorInterface, \Serializable
{
private $data = array();
private $queries = array();
private $currentRequest;
private $currentStartTime;
private $currentEndpoint;
private $logger;
private $stopwatch;
/**
* Plugin init function
*
* Register event listeners
*/
protected function initPluginType()
{
$dispatcher = $this->client->getEventDispatcher();
$dispatcher->addListener(SolariumEvents::PRE_EXECUTE_REQUEST, array($this, 'preExecuteRequest'), 1000);
$dispatcher->addListener(SolariumEvents::POST_EXECUTE_REQUEST, array($this, 'postExecuteRequest'), -1000);
}
/**
* Set the Logger
*
* @param LoggerInterface $logger
*/
public function setLogger($logger)
{
$this->logger = $logger;
}
/**
* Set the Stopwatch
*
* @param Stopwatch $stopwatch
*/
public function setStopwatch($stopwatch)
{
$this->stopwatch = $stopwatch;
}
public function log(SolariumRequest $request, $response, SolariumEndpoint $endpoint, $duration)
{
$this->queries[] = array(
'request' => $request,
'response' => $response,
'duration' => $duration,
'base_uri' => $endpoint->getBaseUri(),
);
}
public function collect(HttpRequest $request, HttpResponse $response, \Exception $exception = null)
{
if (isset($this->currentRequest)) {
$this->failCurrentRequest();
}
$time = 0;
foreach ($this->queries as $queryStruct) {
$time += $queryStruct['duration'];
}
$this->data = array(
'queries' => $this->queries,
'total_time' => $time,
);
}
public function getName()
{
return 'solr';
}
public function getQueries()
{
return array_key_exists('queries', $this->data) ? $this->data['queries'] : array();
}
public function getQueryCount()
{
return count($this->getQueries());
}
public function getTotalTime()
{
return array_key_exists('total_time', $this->data) ? $this->data['total_time'] : 0;
}
public function preExecuteRequest(SolariumPreExecuteRequestEvent $event)
{
if (isset($this->currentRequest)) {
$this->failCurrentRequest();
}
if (null !== $this->stopwatch) {
$this->stopwatch->start('solr', 'solr');
}
$this->currentRequest = $event->getRequest();
$this->currentEndpoint = $event->getEndpoint();
if (null !== $this->logger) {
$this->logger->debug($event->getEndpoint()->getBaseUri() . $this->currentRequest->getUri());
}
$this->currentStartTime = microtime(true);
}
public function postExecuteRequest(SolariumPostExecuteRequestEvent $event)
{
$endTime = microtime(true) - $this->currentStartTime;
if (!isset($this->currentRequest)) {
throw new \RuntimeException('Request not set');
}
if ($this->currentRequest !== $event->getRequest()) {
throw new \RuntimeException('Requests differ');
}
if (null !== $this->stopwatch) {
$this->stopwatch->stop('solr');
}
$this->log($event->getRequest(), $event->getResponse(), $event->getEndpoint(), $endTime);
$this->currentRequest = null;
$this->currentStartTime = null;
$this->currentEndpoint = null;
}
public function failCurrentRequest()
{
$endTime = microtime(true) - $this->currentStartTime;
if (null !== $this->stopwatch) {
$this->stopwatch->stop('solr');
}
$this->log($this->currentRequest, null, $this->currentEndpoint, $endTime);
$this->currentRequest = null;
$this->currentStartTime = null;
$this->currentEndpoint = null;
}
public function serialize()
{
return serialize($this->data);
}
public function unserialize($data)
{
$this->data = unserialize($data);
}
}
| {'content_hash': 'eab42902a856fc3294ef57b03dc53b5f', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 114, 'avg_line_length': 28.60355029585799, 'alnum_prop': 0.6098469176665288, 'repo_name': 'rzproject/SearchBundle', 'id': '124c7d0a2b3a665d0cd7bd716da3018537fa9860', 'size': '4834', 'binary': False, 'copies': '1', 'ref': 'refs/heads/2.0.0', 'path': 'Logger.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '13400'}, {'name': 'PHP', 'bytes': '83325'}]} |
#include "kythe/cxx/verifier/souffle_interpreter.h"
#include <array>
#include <memory>
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "glog/logging.h"
#include "interpreter/Engine.h"
#include "souffle/RamTypes.h"
#include "souffle/io/IOSystem.h"
#include "third_party/souffle/parse_transform.h"
namespace kythe::verifier {
namespace {
constexpr std::array<int, 4> kInputData = {1, 2, 2, 3};
class KytheReadStream : public souffle::ReadStream {
public:
explicit KytheReadStream(
const std::map<std::string, std::string>& rw_operation,
souffle::SymbolTable& symbol_table, souffle::RecordTable& record_table)
: souffle::ReadStream(rw_operation, symbol_table, record_table) {}
protected:
souffle::Own<souffle::RamDomain[]> readNextTuple() override {
if (pos_ >= kInputData.size()) {
return nullptr;
}
auto tuple = std::make_unique<souffle::RamDomain[]>(2);
tuple[0] = kInputData[pos_++];
tuple[1] = kInputData[pos_++];
return tuple;
}
private:
int pos_ = 0;
};
class KytheReadStreamFactory : public souffle::ReadStreamFactory {
public:
souffle::Own<souffle::ReadStream> getReader(
const std::map<std::string, std::string>& rw_operation,
souffle::SymbolTable& symbol_table,
souffle::RecordTable& record_table) override {
return souffle::mk<KytheReadStream>(rw_operation, symbol_table,
record_table);
}
const std::string& getName() const override {
static const std::string name = "kythe";
return name;
}
};
class KytheWriteStream : public souffle::WriteStream {
public:
explicit KytheWriteStream(
const std::map<std::string, std::string>& rw_operation,
const souffle::SymbolTable& symbol_table,
const souffle::RecordTable& record_table,
std::vector<std::pair<int, int>>* output)
: souffle::WriteStream(rw_operation, symbol_table, record_table),
output_(output) {}
protected:
void writeNullary() override {}
void writeNextTuple(const souffle::RamDomain* tuple) override {
output_->push_back({tuple[0], tuple[1]});
}
private:
std::vector<std::pair<int, int>>* output_;
};
class KytheWriteStreamFactory : public souffle::WriteStreamFactory {
public:
souffle::Own<souffle::WriteStream> getWriter(
const std::map<std::string, std::string>& rw_operation,
const souffle::SymbolTable& symbol_table,
const souffle::RecordTable& record_table) override {
auto output = rw_operation.find("id");
CHECK(output != rw_operation.end());
size_t output_id;
CHECK(absl::SimpleAtoi(output->second, &output_id));
CHECK(output_id < outputs_.size());
return souffle::mk<KytheWriteStream>(rw_operation, symbol_table,
record_table, &outputs_[output_id]);
}
const std::string& getName() const override {
static const std::string name = "kythe";
return name;
}
size_t NewOutput() {
outputs_.push_back({});
return outputs_.size() - 1;
}
const std::vector<std::pair<int, int>>& GetOutput(size_t id) const {
return outputs_[id];
}
private:
std::vector<std::vector<std::pair<int, int>>> outputs_;
};
} // anonymous namespace
// TODO(zarko): This is a temporary hack that only demonstrates that the
// Souffle library is working. It bakes in the inputs and outputs for a
// simple example program and checks that the interpreter calculates the
// correct result. `Kythe{Write,Read}StreamFactory` will need to be moved
// to separate files and updated to accept the Datalog relations that the
// verifier -> datalog compiler produces.
SouffleResult RunSouffle(
const SymbolTable& symbol_table, const std::vector<GoalGroup>& goal_groups,
const Database& database,
const std::vector<AssertionParser::Inspection>& inspections,
std::function<bool(const AssertionParser::Inspection&)> inspect) {
SouffleResult result{};
auto write_stream_factory = std::make_shared<KytheWriteStreamFactory>();
size_t output_id = write_stream_factory->NewOutput();
souffle::IOSystem::getInstance().registerWriteStreamFactory(
write_stream_factory);
souffle::IOSystem::getInstance().registerReadStreamFactory(
std::make_shared<KytheReadStreamFactory>());
auto ram_tu = souffle::ParseTransform(absl::StrCat(R"(
.decl edge(x:number, y:number)
.input edge(IO=kythe)
.decl path(x:number, y:number)
.output path(IO=kythe, id=)",
output_id, R"()
path(x, y) :- edge(x, y).
path(x, y) :- path(x, z), edge(z, y).
)"));
if (ram_tu == nullptr) {
return result;
}
souffle::Own<souffle::interpreter::Engine> interpreter(
souffle::mk<souffle::interpreter::Engine>(*ram_tu));
interpreter->executeMain();
std::set<std::pair<int, int>> expected = {{1, 2}, {1, 3}, {2, 3}};
const auto& actual = write_stream_factory->GetOutput(output_id);
std::set<std::pair<int, int>> actual_set(actual.begin(), actual.end());
result.success = (expected == actual_set);
return result;
}
} // namespace kythe::verifier
| {'content_hash': '6349ae4b0353fef58cdb482e0b7b7e53', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 79, 'avg_line_length': 33.532467532467535, 'alnum_prop': 0.6659566227730441, 'repo_name': 'kythe/kythe', 'id': 'd652991d132dfa91622e7ed91f62c0e1c68fd45a', 'size': '5784', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'kythe/cxx/verifier/souffle_interpreter.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '4169'}, {'name': 'C++', 'bytes': '1874842'}, {'name': 'Dockerfile', 'bytes': '20694'}, {'name': 'Go', 'bytes': '1876965'}, {'name': 'HTML', 'bytes': '5148'}, {'name': 'Java', 'bytes': '844590'}, {'name': 'JavaScript', 'bytes': '3513'}, {'name': 'Lex', 'bytes': '5192'}, {'name': 'Makefile', 'bytes': '222'}, {'name': 'OCaml', 'bytes': '12652'}, {'name': 'Python', 'bytes': '10918'}, {'name': 'Ruby', 'bytes': '2543'}, {'name': 'Rust', 'bytes': '581728'}, {'name': 'SCSS', 'bytes': '10113'}, {'name': 'Shell', 'bytes': '89032'}, {'name': 'Starlark', 'bytes': '540157'}, {'name': 'TeX', 'bytes': '2455'}, {'name': 'TypeScript', 'bytes': '124204'}, {'name': 'Yacc', 'bytes': '5018'}]} |
package eu.fbk.fm.vectorize.preprocessing;
import com.google.gson.JsonObject;
import eu.fbk.fm.alignments.utils.flink.JsonObjectProcessor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.util.Collector;
/**
* Extract retweet as a separate entity from tweet if needed
*/
public class ExpandTweet implements FlatMapFunction<JsonObject, JsonObject>, JsonObjectProcessor {
private static final long serialVersionUID = 1L;
@Override
public void flatMap(JsonObject status, Collector<JsonObject> out) {
out.collect(status);
//Check if the author of the original tweet is in the list
final JsonObject retweet = get(status, JsonObject.class, "retweeted_status");
if (retweet != null ) {
out.collect(retweet);
}
}
}
| {'content_hash': '73753ac8767a3b70b4bcf7f7b81c28ba', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 98, 'avg_line_length': 32.76, 'alnum_prop': 0.7228327228327228, 'repo_name': 'Remper/sociallink', 'id': '612bf92dba55cadf1cb0431eb789966e28f75f29', 'size': '819', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'alignments/src/main/java/eu/fbk/fm/vectorize/preprocessing/ExpandTweet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'API Blueprint', 'bytes': '4327'}, {'name': 'CSS', 'bytes': '9246'}, {'name': 'HTML', 'bytes': '139729'}, {'name': 'Java', 'bytes': '784070'}, {'name': 'JavaScript', 'bytes': '1531'}, {'name': 'Python', 'bytes': '138661'}, {'name': 'TypeScript', 'bytes': '23623'}]} |
module.exports = function(RED) {
function x3gStatemachine(config) {
RED.nodes.createNode(this,config);
var node = this;
var flowContext = node.context().flow;
var x3gStatemachine_impl = require('./x3g_statemachine_impl.js')
this.on('input', function(msg) {
var thisPrinterStatus = flowContext.get(config.printerid+'_status')||{};
var thisPrinterQueue = flowContext.get(config.printerid+'_queue')||[];
//call the statemachine, whilst passing in the printerstatus and the received message
x3gStatemachine_impl.newInput(msg.payload,thisPrinterStatus,thisPrinterQueue);
flowContext.set(config.printerid+'_status',thisPrinterStatus)
if(thisPrinterStatus.payload != "")
{
msg.payload = thisPrinterStatus.payload
node.send(msg);
}
});
}
RED.nodes.registerType("X3GStatemachine",x3gStatemachine);
}
| {'content_hash': '3f0cdae20336c896e26ca5a0469e480a', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 101, 'avg_line_length': 42.30434782608695, 'alnum_prop': 0.632065775950668, 'repo_name': 'sergekeyser/x3g-nodered', 'id': 'da232c47034abf1e39607cc27c60dd28f8b5517b', 'size': '973', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'statemachine/x3g_statemachine.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5782'}, {'name': 'JavaScript', 'bytes': '18041'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<meta name="collection" content="api">
<!-- Generated by javadoc (build 1.5.0-rc) on Wed Aug 11 07:27:21 PDT 2004 -->
<TITLE>
BasicToolBarUI.ToolBarContListener (Java 2 Platform SE 5.0)
</TITLE>
<META NAME="keywords" CONTENT="javax.swing.plaf.basic.BasicToolBarUI.ToolBarContListener class">
<META NAME="keywords" CONTENT="componentAdded()">
<META NAME="keywords" CONTENT="componentRemoved()">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="BasicToolBarUI.ToolBarContListener (Java 2 Platform SE 5.0)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/BasicToolBarUI.ToolBarContListener.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Java<sup><font size=-2>TM</font></sup> 2 Platform<br>Standard Ed. 5.0</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.PropertyListener.html" title="class in javax.swing.plaf.basic"><B>PREV CLASS</B></A>
<A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.ToolBarFocusListener.html" title="class in javax.swing.plaf.basic"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="BasicToolBarUI.ToolBarContListener.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
javax.swing.plaf.basic</FONT>
<BR>
Class BasicToolBarUI.ToolBarContListener</H2>
<PRE>
<A HREF="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</A>
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>javax.swing.plaf.basic.BasicToolBarUI.ToolBarContListener</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../java/awt/event/ContainerListener.html" title="interface in java.awt.event">ContainerListener</A>, <A HREF="../../../../java/util/EventListener.html" title="interface in java.util">EventListener</A></DD>
</DL>
<DL>
<DT><B>Direct Known Subclasses:</B> <DD><A HREF="../../../../javax/swing/plaf/metal/MetalToolBarUI.MetalContainerListener.html" title="class in javax.swing.plaf.metal">MetalToolBarUI.MetalContainerListener</A></DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.html" title="class in javax.swing.plaf.basic">BasicToolBarUI</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>protected class <B>BasicToolBarUI.ToolBarContListener</B><DT>extends <A HREF="../../../../java/lang/Object.html" title="class in java.lang">Object</A><DT>implements <A HREF="../../../../java/awt/event/ContainerListener.html" title="interface in java.awt.event">ContainerListener</A></DL>
</PRE>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected </CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html#BasicToolBarUI.ToolBarContListener()">BasicToolBarUI.ToolBarContListener</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html#componentAdded(java.awt.event.ContainerEvent)">componentAdded</A></B>(<A HREF="../../../../java/awt/event/ContainerEvent.html" title="class in java.awt.event">ContainerEvent</A> e)</CODE>
<BR>
Invoked when a component has been added to the container.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html#componentRemoved(java.awt.event.ContainerEvent)">componentRemoved</A></B>(<A HREF="../../../../java/awt/event/ContainerEvent.html" title="class in java.awt.event">ContainerEvent</A> e)</CODE>
<BR>
Invoked when a component has been removed from the container.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="../../../../java/lang/Object.html" title="class in java.lang">Object</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../java/lang/Object.html#clone()">clone</A>, <A HREF="../../../../java/lang/Object.html#equals(java.lang.Object)">equals</A>, <A HREF="../../../../java/lang/Object.html#finalize()">finalize</A>, <A HREF="../../../../java/lang/Object.html#getClass()">getClass</A>, <A HREF="../../../../java/lang/Object.html#hashCode()">hashCode</A>, <A HREF="../../../../java/lang/Object.html#notify()">notify</A>, <A HREF="../../../../java/lang/Object.html#notifyAll()">notifyAll</A>, <A HREF="../../../../java/lang/Object.html#toString()">toString</A>, <A HREF="../../../../java/lang/Object.html#wait()">wait</A>, <A HREF="../../../../java/lang/Object.html#wait(long)">wait</A>, <A HREF="../../../../java/lang/Object.html#wait(long, int)">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="BasicToolBarUI.ToolBarContListener()"><!-- --></A><H3>
BasicToolBarUI.ToolBarContListener</H3>
<PRE>
protected <B>BasicToolBarUI.ToolBarContListener</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="componentAdded(java.awt.event.ContainerEvent)"><!-- --></A><H3>
componentAdded</H3>
<PRE>
public void <B>componentAdded</B>(<A HREF="../../../../java/awt/event/ContainerEvent.html" title="class in java.awt.event">ContainerEvent</A> e)</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../java/awt/event/ContainerListener.html#componentAdded(java.awt.event.ContainerEvent)">ContainerListener</A></CODE></B></DD>
<DD>Invoked when a component has been added to the container.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../java/awt/event/ContainerListener.html#componentAdded(java.awt.event.ContainerEvent)">componentAdded</A></CODE> in interface <CODE><A HREF="../../../../java/awt/event/ContainerListener.html" title="interface in java.awt.event">ContainerListener</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="componentRemoved(java.awt.event.ContainerEvent)"><!-- --></A><H3>
componentRemoved</H3>
<PRE>
public void <B>componentRemoved</B>(<A HREF="../../../../java/awt/event/ContainerEvent.html" title="class in java.awt.event">ContainerEvent</A> e)</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../java/awt/event/ContainerListener.html#componentRemoved(java.awt.event.ContainerEvent)">ContainerListener</A></CODE></B></DD>
<DD>Invoked when a component has been removed from the container.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../java/awt/event/ContainerListener.html#componentRemoved(java.awt.event.ContainerEvent)">componentRemoved</A></CODE> in interface <CODE><A HREF="../../../../java/awt/event/ContainerListener.html" title="interface in java.awt.event">ContainerListener</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/BasicToolBarUI.ToolBarContListener.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Java<sup><font size=-2>TM</font></sup> 2 Platform<br>Standard Ed. 5.0</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.PropertyListener.html" title="class in javax.swing.plaf.basic"><B>PREV CLASS</B></A>
<A HREF="../../../../javax/swing/plaf/basic/BasicToolBarUI.ToolBarFocusListener.html" title="class in javax.swing.plaf.basic"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html" target="_top"><B>FRAMES</B></A>
<A HREF="BasicToolBarUI.ToolBarContListener.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit a bug or feature</a><br>For further API reference and developer documentation, see <a href="../../../../../relnotes/devdocs-vs-specs.html">Java 2 SDK SE Developer Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. <p>Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to <a href="../../../../../relnotes/license.html">license terms</a>. Also see the <a href="http://java.sun.com/docs/redist.html">documentation redistribution policy</a>.</font>
<!-- Start SiteCatalyst code -->
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script>
<script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script>
<!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** -->
<!-- Below code will send the info to Omniture server -->
<script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script>
<!-- End SiteCatalyst code -->
</body>
</HTML>
| {'content_hash': '32c13aff2e4cfaaa48884207b3211e1d', 'timestamp': '', 'source': 'github', 'line_count': 303, 'max_line_length': 772, 'avg_line_length': 52.8943894389439, 'alnum_prop': 0.6545204966618831, 'repo_name': 'Smolations/more-dash-docsets', 'id': '965655bd4978e4d3c34f1035b21340a053bd604b', 'size': '16027', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docsets/Java 5.docset/Contents/Resources/Documents/javax/swing/plaf/basic/BasicToolBarUI.ToolBarContListener.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1456655'}, {'name': 'Emacs Lisp', 'bytes': '3680'}, {'name': 'JavaScript', 'bytes': '139712'}, {'name': 'Puppet', 'bytes': '15851'}, {'name': 'Ruby', 'bytes': '66500'}, {'name': 'Shell', 'bytes': '11437'}]} |
layout: post
title: "Welcome to Jekyll!"
date: 2016-03-29 14:56:28 -0500
categories: jekyll update
---
You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
So this works.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
Jekyll also offers powerful support for code snippets:
{% highlight ruby %}
def print_hi(name)
puts "Hi, #{name}"
end
print_hi('Tom')
#=> prints 'Hi, Tom' to STDOUT.
{% endhighlight %}
Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk].
[jekyll-docs]: http://jekyllrb.com/docs/home
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-talk]: https://talk.jekyllrb.com/
| {'content_hash': '2b3cc070fa3dda8aede09d66f5ae4c65', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 295, 'avg_line_length': 46.69230769230769, 'alnum_prop': 0.7380560131795717, 'repo_name': 'theseanything/jekyll-publish', 'id': '4f7ce19e0cae7fea1cac0249a8507e6c490b3b21', 'size': '1222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/fixtures/test-site/_posts/2016-03-29-welcome-to-jekyll.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '11232'}]} |
<?php $this->beginContent('application.modules_core.activity.views.activityLayoutMail', array('activity' => $activity, 'showSpace' => true)); ?>
<?php echo Yii::t('LikeModule.views_activities_Like', '{userDisplayName} likes {contentTitle}', array(
'{userDisplayName}' => '<strong>' . CHtml::encode($user->displayName) . '</strong>',
'{contentTitle}' => ActivityModule::formatOutput($target->getContentTitle()),
)); ?>
<?php $this->endContent(); ?>
| {'content_hash': '654491c32ed39983a7f11c41eeb1387c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 144, 'avg_line_length': 57.25, 'alnum_prop': 0.6812227074235808, 'repo_name': 'calonso-conabio/intranet', 'id': '696d90c0bd976d897c0798162f01eb2deac249b1', 'size': '458', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'protected/modules_core/like/views/activities/Like_mail.php', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '13'}, {'name': 'Batchfile', 'bytes': '1410'}, {'name': 'CSS', 'bytes': '215052'}, {'name': 'HTML', 'bytes': '31712'}, {'name': 'JavaScript', 'bytes': '657426'}, {'name': 'PHP', 'bytes': '13097099'}, {'name': 'Shell', 'bytes': '179'}]} |
<footer class="main-footer sticky footer-type-1 bottom" style="">
<div class="footer-inner">
<!-- Add your copyright text here -->
<div class="footer-text">
© 2014
<strong>Xenon</strong>
theme by <a href="http://laborator.co" target="_blank">Laborator</a>
</div>
<!-- Go to Top Link, just add rel="go-top" to any link to add this functionality -->
<div class="go-up">
<a href="#" rel="go-top">
<i class="fa-angle-up"></i>
</a>
</div>
</div>
</footer> | {'content_hash': 'a9ebc6d967727239c8dcf7f48b70985e', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 92, 'avg_line_length': 24.666666666666668, 'alnum_prop': 0.49493243243243246, 'repo_name': 'dodanghien23693/codeisfun', 'id': 'ec2ba316df0b02d2275965222c69de19af5588d9', 'size': '593', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/views/admin/layouts/_footer.blade.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3850546'}, {'name': 'JavaScript', 'bytes': '4885816'}, {'name': 'PHP', 'bytes': '1311080'}, {'name': 'Shell', 'bytes': '3031'}]} |
cask 'screens-connect' do
version '3.6_b930'
sha256 '23570864f111c8eb610f61ad6cb35ed4a9f11cd9836a7c606d89ba87daf2f01b'
# edovia.com is the official download host per the appcast feed
# Original discussion: https://github.com/caskroom/homebrew-cask/pull/8816
url "http://download.edovia.com/screensconnect/screensconnect_#{version}.dmg"
appcast 'https://screensconnect.com/sparkle/appcast.xml',
:sha256 => '7c21d5cd6f737508d8c81b809361d8daf91124918491525734cb93662dc46e32'
name 'Screens Connect'
homepage 'https://screensconnect.com'
license :gratis
pkg 'Screens Connect.pkg'
depends_on :macos => '>= :mountain_lion'
# Uninstall script can fail when trying to remove legacy PKGIDS
# Original discussion: https://github.com/caskroom/homebrew-cask/pull/8833
uninstall :script => {
:executable => 'Uninstall Screens Connect.app/Contents/Resources/sc-uninstaller.tool',
:must_succeed => false
},
:pkgutil => 'com.edovia.pkg.screens.connect.*'
end
| {'content_hash': '5657d9193bbed3cd65eb91ddb686a908', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 100, 'avg_line_length': 41.52, 'alnum_prop': 0.720616570327553, 'repo_name': 'jppelteret/homebrew-cask', 'id': 'a0d4993673d464ea80bc3ba9ea9efd5e32c55d0e', 'size': '1038', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Casks/screens-connect.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '1837155'}, {'name': 'Shell', 'bytes': '60747'}]} |
from storm.database import states
| {'content_hash': 'dfde8c817b93c8ae2b07de7fcf754770', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 33, 'avg_line_length': 34.0, 'alnum_prop': 0.8529411764705882, 'repo_name': 'GaretJax/storm-erp', 'id': 'b38f4c41ffaf89494dc18135da407d1db02866b2', 'size': '34', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'storm/database/test/test_states.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '72511'}]} |
CKEDITOR.plugins.setLang( 'div', 'cs', {
IdInputLabel: 'Id',
advisoryTitleInputLabel: 'Nápovědní titulek',
cssClassInputLabel: 'Třídy stylů',
edit: 'Změnit Div',
inlineStyleInputLabel: 'Vnitřní styly',
langDirLTRLabel: 'Zleva doprava (LTR)',
langDirLabel: 'Směr jazyka',
langDirRTLLabel: 'Zprava doleva (RTL)',
languageCodeInputLabel: ' Kód jazyka',
remove: 'Odstranit Div',
styleSelectLabel: 'Styly',
title: 'Vytvořit Div kontejner',
toolbar: 'Vytvořit Div kontejner'
} );
| {'content_hash': '2c04683e7cba5adc61991188bd41cea3', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 46, 'avg_line_length': 31.5625, 'alnum_prop': 0.7089108910891089, 'repo_name': 'Kunstmaan/BootstrapCK4-Skin', 'id': 'ddf1f2a14465cf7a176dbe063077a68b684b2c1c', 'size': '665', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugins/div/lang/cs.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '245479'}, {'name': 'JavaScript', 'bytes': '4813019'}]} |
package org.amc.game.chessserver;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import com.google.gson.Gson;
import org.amc.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.session.SessionRegistry;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class OnlinePlayerListControllerTest {
private OnlinePlayerListController controller;
private List<Object> listOfUsers;
private User userOne = new User();
private User userTwo = new User();
private Principal principal = new Principal() {
@Override
public String getName() {
return "User";
}
};
@Before
public void setUp() throws Exception {
listOfUsers = new ArrayList<>();
userOne.setUserName("adrian");
userTwo.setUserName("Sarah");
listOfUsers.add(userOne);
listOfUsers.add(userTwo);
SessionRegistry registry = mock(SessionRegistry.class);
when(registry.getAllPrincipals()).thenReturn(listOfUsers);
controller = new OnlinePlayerListController();
controller.setSessionRegistry(registry);
}
@Test
public void test() throws Exception {
Callable<String> callableResult = controller.getOnlinePlayerList();
String result = callableResult.call();
Gson gson = new Gson();
assertEquals(gson.toJson(listOfUsers), result);
}
@Test
public void getOnlinePlayerListViaSTOMP() {
OnlinePlayerListMessager messager =mock(OnlinePlayerListMessager.class);
controller.messager = messager;
controller.getOnlinePlayerListViaSTOMP(principal);
verify(messager, times(1)).sendPlayerList();
}
}
| {'content_hash': 'f8d1c81fc74da230b2d734112e3ce134', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 80, 'avg_line_length': 29.15625, 'alnum_prop': 0.6811361200428725, 'repo_name': 'subwoofer359/AMCChessGame', 'id': 'd67ba5f4c82e4049cd1520ee49236d56b36796fc', 'size': '1866', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/amc/game/chessserver/OnlinePlayerListControllerTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12706'}, {'name': 'Groovy', 'bytes': '143100'}, {'name': 'HTML', 'bytes': '29454'}, {'name': 'Java', 'bytes': '768645'}, {'name': 'JavaScript', 'bytes': '740653'}, {'name': 'TypeScript', 'bytes': '75088'}]} |
/**
*
*/
package org.itas.common.logger.support;
/**
* Copyright (c) 2004-2011 QOS.ch
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
// contributors: lizongbo: proposed special treatment of array parameter values
// Joern Huxhorn: pointed out double[] omission, suggested deep array copy
/**
* Formats messages according to very simple substitution rules. Substitutions
* can be made 1, 2 or more arguments.
*
* <p>
* For example,
*
* <pre>
* MessageFormatter.format("Hi {}.", "there")
* </pre>
*
* will return the string "Hi there.".
* <p>
* The {} pair is called the <em>formatting anchor</em>. It serves to designate
* the location where arguments need to be substituted within the message
* pattern.
* <p>
* In case your message contains the '{' or the '}' character, you do not have
* to do anything special unless the '}' character immediately follows '{'. For
* example,
*
* <pre>
* MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
* </pre>
*
* will return the string "Set {1,2,3} is not equal to 1,2.".
*
* <p>
* If for whatever reason you need to place the string "{}" in the message
* without its <em>formatting anchor</em> meaning, then you need to escape the
* '{' character with '\', that is the backslash character. Only the '{'
* character should be escaped. There is no need to escape the '}' character.
* For example,
*
* <pre>
* MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
* </pre>
*
* will return the string "Set {} is not equal to 1,2.".
*
* <p>
* The escaping behavior just described can be overridden by escaping the escape
* character '\'. Calling
*
* <pre>
* MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
* </pre>
*
* will return the string "File name is C:\file.zip".
*
* <p>
* The formatting conventions are different than those of {@link MessageFormat}
* which ships with the Java platform. This is justified by the fact that
* SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
* This local performance difference is both measurable and significant in the
* larger context of the complete logging processing chain.
*
* <p>
* See also {@link #format(String, Object)},
* {@link #format(String, Object, Object)} and
* {@link #arrayFormat(String, Object[])} methods for more details.
*
* @author Ceki Gülcü
* @author Joern Huxhorn
*/
final public class MessageFormatter {
static final char DELIM_START = '{';
static final char DELIM_STOP = '}';
static final String DELIM_STR = "{}";
private static final char ESCAPE_CHAR = '\\';
/**
* Performs single argument substitution for the 'messagePattern' passed as
* parameter.
* <p>
* For example,
*
* <pre>
* MessageFormatter.format("Hi {}.", "there");
* </pre>
*
* will return the string "Hi there.".
* <p>
*
* @param messagePattern
* The message pattern which will be parsed and formatted
* @param argument
* The argument to be substituted in place of the formatting anchor
* @return The formatted message
*/
final public static FormattingTuple format(String messagePattern, Object arg) {
return arrayFormat(messagePattern, new Object[] { arg });
}
/**
*
* Performs a two argument substitution for the 'messagePattern' passed as
* parameter.
* <p>
* For example,
*
* <pre>
* MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
* </pre>
*
* will return the string "Hi Alice. My name is Bob.".
*
* @param messagePattern
* The message pattern which will be parsed and formatted
* @param arg1
* The argument to be substituted in place of the first formatting
* anchor
* @param arg2
* The argument to be substituted in place of the second formatting
* anchor
* @return The formatted message
*/
final public static FormattingTuple format(final String messagePattern,
Object arg1, Object arg2) {
return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
}
static final Throwable getThrowableCandidate(Object[] argArray) {
if (argArray == null || argArray.length == 0) {
return null;
}
final Object lastEntry = argArray[argArray.length - 1];
if (lastEntry instanceof Throwable) {
return (Throwable) lastEntry;
}
return null;
}
/**
* Same principle as the {@link #format(String, Object)} and
* {@link #format(String, Object, Object)} methods except that any number of
* arguments can be passed in an array.
*
* @param messagePattern
* The message pattern which will be parsed and formatted
* @param argArray
* An array of arguments to be substituted in place of formatting
* anchors
* @return The formatted message
*/
final public static FormattingTuple arrayFormat(final String messagePattern,
final Object[] argArray) {
Throwable throwableCandidate = getThrowableCandidate(argArray);
if (messagePattern == null) {
return new FormattingTuple(null, argArray, throwableCandidate);
}
if (argArray == null) {
return new FormattingTuple(messagePattern);
}
int i = 0;
int j;
// use string builder for better multicore performance
StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
int L;
for (L = 0; L < argArray.length; L++) {
j = messagePattern.indexOf(DELIM_STR, i);
if (j == -1) {
// no more variables
if (i == 0) { // this is a simple string
return new FormattingTuple(messagePattern, argArray,
throwableCandidate);
} else { // add the tail string which contains no variables and return
// the result.
sbuf.append(messagePattern.substring(i, messagePattern.length()));
return new FormattingTuple(sbuf.toString(), argArray,
throwableCandidate);
}
} else {
if (isEscapedDelimeter(messagePattern, j)) {
if (!isDoubleEscaped(messagePattern, j)) {
L--; // DELIM_START was escaped, thus should not be incremented
sbuf.append(messagePattern.substring(i, j - 1));
sbuf.append(DELIM_START);
i = j + 1;
} else {
// The escape character preceding the delimiter start is
// itself escaped: "abc x:\\{}"
// we have to consume one backward slash
sbuf.append(messagePattern.substring(i, j - 1));
deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
i = j + 2;
}
} else {
// normal case
sbuf.append(messagePattern.substring(i, j));
deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
i = j + 2;
}
}
}
// append the characters following the last {} pair.
sbuf.append(messagePattern.substring(i, messagePattern.length()));
if (L < argArray.length - 1) {
return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
} else {
return new FormattingTuple(sbuf.toString(), argArray, null);
}
}
final static boolean isEscapedDelimeter(String messagePattern,
int delimeterStartIndex) {
if (delimeterStartIndex == 0) {
return false;
}
char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
if (potentialEscape == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
final static boolean isDoubleEscaped(String messagePattern,
int delimeterStartIndex) {
if (delimeterStartIndex >= 2
&& messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
// special treatment of array values was suggested by 'lizongbo'
private static void deeplyAppendParameter(StringBuilder sbuf, Object o,
Map<Object[], Object> seenMap) {
if (o == null) {
sbuf.append("null");
return;
}
if (!o.getClass().isArray()) {
safeObjectAppend(sbuf, o);
} else {
// check for primitive array types because they
// unfortunately cannot be cast to Object[]
if (o instanceof boolean[]) {
booleanArrayAppend(sbuf, (boolean[]) o);
} else if (o instanceof byte[]) {
byteArrayAppend(sbuf, (byte[]) o);
} else if (o instanceof char[]) {
charArrayAppend(sbuf, (char[]) o);
} else if (o instanceof short[]) {
shortArrayAppend(sbuf, (short[]) o);
} else if (o instanceof int[]) {
intArrayAppend(sbuf, (int[]) o);
} else if (o instanceof long[]) {
longArrayAppend(sbuf, (long[]) o);
} else if (o instanceof float[]) {
floatArrayAppend(sbuf, (float[]) o);
} else if (o instanceof double[]) {
doubleArrayAppend(sbuf, (double[]) o);
} else {
objectArrayAppend(sbuf, (Object[]) o, seenMap);
}
}
}
private static void safeObjectAppend(StringBuilder sbuf, Object o) {
try {
String oAsString = o.toString();
sbuf.append(oAsString);
} catch (Throwable t) {
System.err
.println("SLF4J: Failed toString() invocation on an object of type ["
+ o.getClass().getName() + "]");
t.printStackTrace();
sbuf.append("[FAILED toString()]");
}
}
private static void objectArrayAppend(StringBuilder sbuf, Object[] a,
Map<Object[], Object> seenMap) {
sbuf.append('[');
if (!seenMap.containsKey(a)) {
seenMap.put(a, null);
final int len = a.length;
for (int i = 0; i < len; i++) {
deeplyAppendParameter(sbuf, a[i], seenMap);
if (i != len - 1)
sbuf.append(", ");
}
// allow repeats in siblings
seenMap.remove(a);
} else {
sbuf.append("...");
}
sbuf.append(']');
}
private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void charArrayAppend(StringBuilder sbuf, char[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void intArrayAppend(StringBuilder sbuf, int[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void longArrayAppend(StringBuilder sbuf, long[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1)
sbuf.append(", ");
}
sbuf.append(']');
}
}
| {'content_hash': '5b9e15dbf5cc2444e0eba2a9e3c5150c', 'timestamp': '', 'source': 'github', 'line_count': 427, 'max_line_length': 100, 'avg_line_length': 31.59016393442623, 'alnum_prop': 0.6123508043591074, 'repo_name': 'liuxing521a/itas-core', 'id': 'c72400ae5d88842a0542b2b1b2b37abf7ea53c64', 'size': '13489', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'utils/src/main/java/org/itas/common/logger/support/MessageFormatter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1546939'}, {'name': 'Ragel in Ruby Host', 'bytes': '9540'}]} |
<?php
namespace v240\AddHtmlColumnToTickets;
class UpdateRepliesTable extends \AbstractMigration {
function up($hesk_settings) {
$this->executeQuery("ALTER TABLE `" . hesk_dbEscape($hesk_settings['db_pfix']) . "replies` ADD COLUMN `html` ENUM('0','1') NOT NULL DEFAULT '0'");
}
function down($hesk_settings) {
$this->executeQuery("ALTER TABLE `" . hesk_dbEscape($hesk_settings['db_pfix']) . "replies` DROP COLUMN `html`");
}
} | {'content_hash': '96d8c67fa4a260551d48dd3874c8e024', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 154, 'avg_line_length': 30.866666666666667, 'alnum_prop': 0.6587473002159827, 'repo_name': 'mkoch227/Mods-for-HESK', 'id': 'f9979951a547079be8ca5f6354f15f67b0202040', 'size': '463', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'install/migrations/v240/AddHtmlColumnToTickets/UpdateRepliesTable.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '55466'}, {'name': 'HTML', 'bytes': '34223'}, {'name': 'JavaScript', 'bytes': '121138'}, {'name': 'PHP', 'bytes': '1966630'}]} |
/*@internal*/
namespace ts {
export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation {
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
source?: string;
relatedInformation?: ReusableDiagnosticRelatedInformation[];
}
export interface ReusableDiagnosticRelatedInformation {
category: DiagnosticCategory;
code: number;
file: string | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | ReusableDiagnosticMessageChain;
}
export type ReusableDiagnosticMessageChain = DiagnosticMessageChain;
export interface ReusableBuilderProgramState extends ReusableBuilderState {
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile?: ReadonlyMap<readonly ReusableDiagnostic[] | readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
changedFilesSet?: ReadonlyMap<true>;
/**
* Set of affected files being iterated
*/
affectedFiles?: readonly SourceFile[] | undefined;
/**
* Current changed file for iterating over affected files
*/
currentChangedFilePath?: Path | undefined;
/**
* Map of file signatures, with key being file path, calculated while getting current changed file's affected files
* These will be committed whenever the iteration through affected files of current changed file is complete
*/
currentAffectedFilesSignatures?: ReadonlyMap<string> | undefined;
/**
* Newly computed visible to outside referencedSet
*/
currentAffectedFilesExportedModulesMap?: Readonly<BuilderState.ComputingExportedModulesMap> | undefined;
/**
* True if the semantic diagnostics were copied from the old state
*/
semanticDiagnosticsFromOldState?: Map<true>;
/**
* program corresponding to this state
*/
program?: Program | undefined;
/**
* compilerOptions for the program
*/
compilerOptions: CompilerOptions;
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit?: readonly Path[] | undefined;
/**
* Files pending to be emitted kind.
*/
affectedFilesPendingEmitKind?: ReadonlyMap<BuilderFileEmit> | undefined;
/**
* Current index to retrieve pending affected file
*/
affectedFilesPendingEmitIndex?: number | undefined;
/*
* true if semantic diagnostics are ReusableDiagnostic instead of Diagnostic
*/
hasReusableDiagnostic?: true;
}
export const enum BuilderFileEmit {
DtsOnly,
Full
}
/**
* State to store the changed files, affected files and cache semantic diagnostics
*/
// TODO: GH#18217 Properties of this interface are frequently asserted to be defined.
export interface BuilderProgramState extends BuilderState {
/**
* Cache of bind and check diagnostics for files with their Path being the key
*/
semanticDiagnosticsPerFile: Map<readonly Diagnostic[]> | undefined;
/**
* The map has key by source file's path that has been changed
*/
changedFilesSet: Map<true>;
/**
* Set of affected files being iterated
*/
affectedFiles: readonly SourceFile[] | undefined;
/**
* Current index to retrieve affected file from
*/
affectedFilesIndex: number | undefined;
/**
* Current changed file for iterating over affected files
*/
currentChangedFilePath: Path | undefined;
/**
* Map of file signatures, with key being file path, calculated while getting current changed file's affected files
* These will be committed whenever the iteration through affected files of current changed file is complete
*/
currentAffectedFilesSignatures: Map<string> | undefined;
/**
* Newly computed visible to outside referencedSet
*/
currentAffectedFilesExportedModulesMap: BuilderState.ComputingExportedModulesMap | undefined;
/**
* Already seen affected files
*/
seenAffectedFiles: Map<true> | undefined;
/**
* whether this program has cleaned semantic diagnostics cache for lib files
*/
cleanedDiagnosticsOfLibFiles?: boolean;
/**
* True if the semantic diagnostics were copied from the old state
*/
semanticDiagnosticsFromOldState?: Map<true>;
/**
* program corresponding to this state
*/
program: Program | undefined;
/**
* compilerOptions for the program
*/
compilerOptions: CompilerOptions;
/**
* Files pending to be emitted
*/
affectedFilesPendingEmit: Path[] | undefined;
/**
* Files pending to be emitted kind.
*/
affectedFilesPendingEmitKind: Map<BuilderFileEmit> | undefined;
/**
* Current index to retrieve pending affected file
*/
affectedFilesPendingEmitIndex: number | undefined;
/**
* true if build info is emitted
*/
emittedBuildInfo?: boolean;
/**
* Already seen emitted files
*/
seenEmittedFiles: Map<BuilderFileEmit> | undefined;
/**
* true if program has been emitted
*/
programEmitComplete?: true;
}
function hasSameKeys<T, U>(map1: ReadonlyMap<T> | undefined, map2: ReadonlyMap<U> | undefined): boolean {
// Has same size and every key is present in both maps
return map1 as ReadonlyMap<T | U> === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !forEachKey(map1, key => !map2.has(key));
}
/**
* Create the state so that we can iterate on changedFiles/affected files
*/
function createBuilderProgramState(newProgram: Program, getCanonicalFileName: GetCanonicalFileName, oldState?: Readonly<ReusableBuilderProgramState>): BuilderProgramState {
const state = BuilderState.create(newProgram, getCanonicalFileName, oldState) as BuilderProgramState;
state.program = newProgram;
const compilerOptions = newProgram.getCompilerOptions();
state.compilerOptions = compilerOptions;
// With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
if (!compilerOptions.outFile && !compilerOptions.out) {
state.semanticDiagnosticsPerFile = createMap<readonly Diagnostic[]>();
}
state.changedFilesSet = createMap<true>();
const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined;
const canCopySemanticDiagnostics = useOldState && oldState!.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
!compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions!);
if (useOldState) {
// Verify the sanity of old state
if (!oldState!.currentChangedFilePath) {
const affectedSignatures = oldState!.currentAffectedFilesSignatures;
Debug.assert(!oldState!.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
}
const changedFilesSet = oldState!.changedFilesSet;
if (canCopySemanticDiagnostics) {
Debug.assert(!changedFilesSet || !forEachKey(changedFilesSet, path => oldState!.semanticDiagnosticsPerFile!.has(path)), "Semantic diagnostics shouldnt be available for changed files");
}
// Copy old state's changed files set
if (changedFilesSet) {
copyEntries(changedFilesSet, state.changedFilesSet);
}
if (!compilerOptions.outFile && !compilerOptions.out && oldState!.affectedFilesPendingEmit) {
state.affectedFilesPendingEmit = oldState!.affectedFilesPendingEmit.slice();
state.affectedFilesPendingEmitKind = cloneMapOrUndefined(oldState!.affectedFilesPendingEmitKind);
state.affectedFilesPendingEmitIndex = oldState!.affectedFilesPendingEmitIndex;
state.seenAffectedFiles = createMap();
}
}
// Update changed files and copy semantic diagnostics if we can
const referencedMap = state.referencedMap;
const oldReferencedMap = useOldState ? oldState!.referencedMap : undefined;
const copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions!.skipLibCheck;
const copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions!.skipDefaultLibCheck;
state.fileInfos.forEach((info, sourceFilePath) => {
let oldInfo: Readonly<BuilderState.FileInfo> | undefined;
let newReferences: BuilderState.ReferencedSet | undefined;
// if not using old state, every file is changed
if (!useOldState ||
// File wasnt present in old state
!(oldInfo = oldState!.fileInfos.get(sourceFilePath)) ||
// versions dont match
oldInfo.version !== info.version ||
// Referenced files changed
!hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
// Referenced file was deleted in the new program
newReferences && forEachKey(newReferences, path => !state.fileInfos.has(path) && oldState!.fileInfos.has(path))) {
// Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
state.changedFilesSet.set(sourceFilePath, true);
}
else if (canCopySemanticDiagnostics) {
const sourceFile = newProgram.getSourceFileByPath(sourceFilePath as Path)!;
if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; }
if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) { return; }
// Unchanged file copy diagnostics
const diagnostics = oldState!.semanticDiagnosticsPerFile!.get(sourceFilePath);
if (diagnostics) {
state.semanticDiagnosticsPerFile!.set(sourceFilePath, oldState!.hasReusableDiagnostic ? convertToDiagnostics(diagnostics as readonly ReusableDiagnostic[], newProgram, getCanonicalFileName) : diagnostics as readonly Diagnostic[]);
if (!state.semanticDiagnosticsFromOldState) {
state.semanticDiagnosticsFromOldState = createMap<true>();
}
state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
}
}
});
// If the global file is removed, add all files as changed
if (useOldState && forEachEntry(oldState!.fileInfos, (info, sourceFilePath) => info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath))) {
BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
.forEach(file => state.changedFilesSet.set(file.resolvedPath, true));
}
else if (oldCompilerOptions && compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
// Add all files to affectedFilesPendingEmit since emit changed
newProgram.getSourceFiles().forEach(f => addToAffectedFilesPendingEmit(state, f.resolvedPath, BuilderFileEmit.Full));
Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
state.seenAffectedFiles = state.seenAffectedFiles || createMap<true>();
}
state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
return state;
}
function convertToDiagnostics(diagnostics: readonly ReusableDiagnostic[], newProgram: Program, getCanonicalFileName: GetCanonicalFileName): readonly Diagnostic[] {
if (!diagnostics.length) return emptyArray;
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions())!, newProgram.getCurrentDirectory()));
return diagnostics.map(diagnostic => {
const result: Diagnostic = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
result.source = diagnostic.source;
const { relatedInformation } = diagnostic;
result.relatedInformation = relatedInformation ?
relatedInformation.length ?
relatedInformation.map(r => convertToDiagnosticRelatedInformation(r, newProgram, toPath)) :
emptyArray :
undefined;
return result;
});
function toPath(path: string) {
return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
}
}
function convertToDiagnosticRelatedInformation(diagnostic: ReusableDiagnosticRelatedInformation, newProgram: Program, toPath: (path: string) => Path): DiagnosticRelatedInformation {
const { file } = diagnostic;
return {
...diagnostic,
file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined
};
}
/**
* Releases program and other related not needed properties
*/
function releaseCache(state: BuilderProgramState) {
BuilderState.releaseCache(state);
state.program = undefined;
}
/**
* Creates a clone of the state
*/
function cloneBuilderProgramState(state: Readonly<BuilderProgramState>): BuilderProgramState {
const newState = BuilderState.clone(state) as BuilderProgramState;
newState.semanticDiagnosticsPerFile = cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
newState.changedFilesSet = cloneMap(state.changedFilesSet);
newState.affectedFiles = state.affectedFiles;
newState.affectedFilesIndex = state.affectedFilesIndex;
newState.currentChangedFilePath = state.currentChangedFilePath;
newState.currentAffectedFilesSignatures = cloneMapOrUndefined(state.currentAffectedFilesSignatures);
newState.currentAffectedFilesExportedModulesMap = cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
newState.seenAffectedFiles = cloneMapOrUndefined(state.seenAffectedFiles);
newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
newState.semanticDiagnosticsFromOldState = cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
newState.program = state.program;
newState.compilerOptions = state.compilerOptions;
newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
newState.affectedFilesPendingEmitKind = cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
newState.seenEmittedFiles = cloneMapOrUndefined(state.seenEmittedFiles);
newState.programEmitComplete = state.programEmitComplete;
return newState;
}
/**
* Verifies that source file is ok to be used in calls that arent handled by next
*/
function assertSourceFileOkWithoutNextAffectedCall(state: BuilderProgramState, sourceFile: SourceFile | undefined) {
Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex! - 1] !== sourceFile || !state.semanticDiagnosticsPerFile!.has(sourceFile.resolvedPath));
}
/**
* This function returns the next affected file to be processed.
* Note that until doneAffected is called it would keep reporting same result
* This is to allow the callers to be able to actually remove affected file only when the operation is complete
* eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
*/
function getNextAffectedFile(state: BuilderProgramState, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash): SourceFile | Program | undefined {
while (true) {
const { affectedFiles } = state;
if (affectedFiles) {
const seenAffectedFiles = state.seenAffectedFiles!;
let affectedFilesIndex = state.affectedFilesIndex!; // TODO: GH#18217
while (affectedFilesIndex < affectedFiles.length) {
const affectedFile = affectedFiles[affectedFilesIndex];
if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
// Set the next affected file as seen and remove the cached semantic diagnostics
state.affectedFilesIndex = affectedFilesIndex;
handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
return affectedFile;
}
affectedFilesIndex++;
}
// Remove the changed file from the change set
state.changedFilesSet.delete(state.currentChangedFilePath!);
state.currentChangedFilePath = undefined;
// Commit the changes in file signature
BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures!);
state.currentAffectedFilesSignatures!.clear();
BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
state.affectedFiles = undefined;
}
// Get next changed file
const nextKey = state.changedFilesSet.keys().next();
if (nextKey.done) {
// Done
return undefined;
}
// With --out or --outFile all outputs go into single file
// so operations are performed directly on program, return program
const program = Debug.checkDefined(state.program);
const compilerOptions = program.getCompilerOptions();
if (compilerOptions.outFile || compilerOptions.out) {
Debug.assert(!state.semanticDiagnosticsPerFile);
return program;
}
// Get next batch of affected files
state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || createMap();
if (state.exportedModulesMap) {
state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || createMap<BuilderState.ReferencedSet | false>();
}
state.affectedFiles = BuilderState.getFilesAffectedBy(state, program, nextKey.value as Path, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
state.currentChangedFilePath = nextKey.value as Path;
state.affectedFilesIndex = 0;
state.seenAffectedFiles = state.seenAffectedFiles || createMap<true>();
}
}
/**
* Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
*/
function getNextAffectedFilePendingEmit(state: BuilderProgramState) {
const { affectedFilesPendingEmit } = state;
if (affectedFilesPendingEmit) {
const seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = createMap());
for (let i = state.affectedFilesPendingEmitIndex!; i < affectedFilesPendingEmit.length; i++) {
const affectedFile = Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
if (affectedFile) {
const seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
const emitKind = Debug.checkDefined(Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
if (seenKind === undefined || seenKind < emitKind) {
// emit this file
state.affectedFilesPendingEmitIndex = i;
return { affectedFile, emitKind };
}
}
}
state.affectedFilesPendingEmit = undefined;
state.affectedFilesPendingEmitKind = undefined;
state.affectedFilesPendingEmitIndex = undefined;
}
return undefined;
}
/**
* Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
* This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
*/
function handleDtsMayChangeOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash) {
removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
// If affected files is everything except default library, then nothing more to do
if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
if (!state.cleanedDiagnosticsOfLibFiles) {
state.cleanedDiagnosticsOfLibFiles = true;
const program = Debug.checkDefined(state.program);
const options = program.getCompilerOptions();
forEach(program.getSourceFiles(), f =>
program.isSourceFileDefaultLibrary(f) &&
!skipTypeChecking(f, options, program) &&
removeSemanticDiagnosticsOf(state, f.resolvedPath)
);
}
return;
}
if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, (state, path) => handleDtsMayChangeOf(state, path, cancellationToken, computeHash));
}
}
/**
* Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
* Also we need to make sure signature is updated for these files
*/
function handleDtsMayChangeOf(state: BuilderProgramState, path: Path, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash) {
removeSemanticDiagnosticsOf(state, path);
if (!state.changedFilesSet.has(path)) {
const program = Debug.checkDefined(state.program);
const sourceFile = program.getSourceFileByPath(path);
if (sourceFile) {
// Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
// we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
// This ensures that we dont later during incremental builds considering wrong signature.
// Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
BuilderState.updateShapeSignature(
state,
program,
sourceFile,
Debug.checkDefined(state.currentAffectedFilesSignatures),
cancellationToken,
computeHash,
state.currentAffectedFilesExportedModulesMap
);
// If not dts emit, nothing more to do
if (getEmitDeclarations(state.compilerOptions)) {
addToAffectedFilesPendingEmit(state, path, BuilderFileEmit.DtsOnly);
}
}
}
return false;
}
/**
* Removes semantic diagnostics for path and
* returns true if there are no more semantic diagnostics from the old state
*/
function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) {
if (!state.semanticDiagnosticsFromOldState) {
return true;
}
state.semanticDiagnosticsFromOldState.delete(path);
state.semanticDiagnosticsPerFile!.delete(path);
return !state.semanticDiagnosticsFromOldState.size;
}
function isChangedSignagure(state: BuilderProgramState, path: Path) {
const newSignature = Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
const oldSignagure = Debug.checkDefined(state.fileInfos.get(path)).signature;
return newSignature !== oldSignagure;
}
/**
* Iterate on referencing modules that export entities from affected file
*/
function forEachReferencingModulesOfExportOfAffectedFile(state: BuilderProgramState, affectedFile: SourceFile, fn: (state: BuilderProgramState, filePath: Path) => boolean) {
// If there was change in signature (dts output) for the changed file,
// then only we need to handle pending file emit
if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
return;
}
if (!isChangedSignagure(state, affectedFile.resolvedPath)) return;
// Since isolated modules dont change js files, files affected by change in signature is itself
// But we need to cleanup semantic diagnostics and queue dts emit for affected files
if (state.compilerOptions.isolatedModules) {
const seenFileNamesMap = createMap<true>();
seenFileNamesMap.set(affectedFile.resolvedPath, true);
const queue = BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
while (queue.length > 0) {
const currentPath = queue.pop()!;
if (!seenFileNamesMap.has(currentPath)) {
seenFileNamesMap.set(currentPath, true);
const result = fn(state, currentPath);
if (result && isChangedSignagure(state, currentPath)) {
const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath)!;
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
}
}
}
}
Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
const seenFileAndExportsOfFile = createMap<true>();
// Go through exported modules from cache first
// If exported modules has path, all files referencing file exported from are affected
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
exportedModules &&
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
)) {
return;
}
// If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
forEachEntry(state.exportedModulesMap, (exportedModules, exportedFromPath) =>
!state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it
exportedModules.has(affectedFile.resolvedPath) &&
forEachFilesReferencingPath(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
);
}
/**
* Iterate on files referencing referencedPath
*/
function forEachFilesReferencingPath(state: BuilderProgramState, referencedPath: Path, seenFileAndExportsOfFile: Map<true>, fn: (state: BuilderProgramState, filePath: Path) => boolean) {
return forEachEntry(state.referencedMap!, (referencesInFile, filePath) =>
referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath as Path, seenFileAndExportsOfFile, fn)
);
}
/**
* fn on file and iterate on anything that exports this file
*/
function forEachFileAndExportsOfFile(state: BuilderProgramState, filePath: Path, seenFileAndExportsOfFile: Map<true>, fn: (state: BuilderProgramState, filePath: Path) => boolean): boolean {
if (!addToSeen(seenFileAndExportsOfFile, filePath)) {
return false;
}
if (fn(state, filePath)) {
// If there are no more diagnostics from old cache, done
return true;
}
Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
// Go through exported modules from cache first
// If exported modules has path, all files referencing file exported from are affected
if (forEachEntry(state.currentAffectedFilesExportedModulesMap, (exportedModules, exportedFromPath) =>
exportedModules &&
exportedModules.has(filePath) &&
forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
)) {
return true;
}
// If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
if (forEachEntry(state.exportedModulesMap!, (exportedModules, exportedFromPath) =>
!state.currentAffectedFilesExportedModulesMap!.has(exportedFromPath) && // If we already iterated this through cache, ignore it
exportedModules.has(filePath) &&
forEachFileAndExportsOfFile(state, exportedFromPath as Path, seenFileAndExportsOfFile, fn)
)) {
return true;
}
// Remove diagnostics of files that import this file (without going to exports of referencing files)
return !!forEachEntry(state.referencedMap!, (referencesInFile, referencingFilePath) =>
referencesInFile.has(filePath) &&
!seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
fn(state, referencingFilePath as Path) // Dont add to seen since this is not yet done with the export removal
);
}
/**
* This is called after completing operation on the next affected file.
* The operations here are postponed to ensure that cancellation during the iteration is handled correctly
*/
function doneWithAffectedFile(
state: BuilderProgramState,
affected: SourceFile | Program,
emitKind?: BuilderFileEmit,
isPendingEmit?: boolean,
isBuildInfoEmit?: boolean
) {
if (isBuildInfoEmit) {
state.emittedBuildInfo = true;
}
else if (affected === state.program) {
state.changedFilesSet.clear();
state.programEmitComplete = true;
}
else {
state.seenAffectedFiles!.set((affected as SourceFile).resolvedPath, true);
if (emitKind !== undefined) {
(state.seenEmittedFiles || (state.seenEmittedFiles = createMap())).set((affected as SourceFile).resolvedPath, emitKind);
}
if (isPendingEmit) {
state.affectedFilesPendingEmitIndex!++;
}
else {
state.affectedFilesIndex!++;
}
}
}
/**
* Returns the result with affected file
*/
function toAffectedFileResult<T>(state: BuilderProgramState, result: T, affected: SourceFile | Program): AffectedFileResult<T> {
doneWithAffectedFile(state, affected);
return { result, affected };
}
/**
* Returns the result with affected file
*/
function toAffectedFileEmitResult(
state: BuilderProgramState,
result: EmitResult,
affected: SourceFile | Program,
emitKind: BuilderFileEmit,
isPendingEmit?: boolean,
isBuildInfoEmit?: boolean
): AffectedFileResult<EmitResult> {
doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
return { result, affected };
}
/**
* Gets semantic diagnostics for the file which are
* bindAndCheckDiagnostics (from cache) and program diagnostics
*/
function getSemanticDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
return concatenate(
getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken),
Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile)
);
}
/**
* Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
* Note that it is assumed that when asked about binder and checker diagnostics, the file has been taken out of affected files/changed file set
*/
function getBinderAndCheckerDiagnosticsOfFile(state: BuilderProgramState, sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
const path = sourceFile.resolvedPath;
if (state.semanticDiagnosticsPerFile) {
const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
// Report the bind and check diagnostics from the cache if we already have those diagnostics present
if (cachedDiagnostics) {
return cachedDiagnostics;
}
}
// Diagnostics werent cached, get them from program, and cache the result
const diagnostics = Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
if (state.semanticDiagnosticsPerFile) {
state.semanticDiagnosticsPerFile.set(path, diagnostics);
}
return diagnostics;
}
export type ProgramBuildInfoDiagnostic = string | [string, readonly ReusableDiagnostic[]];
export interface ProgramBuildInfo {
fileInfos: MapLike<BuilderState.FileInfo>;
options: CompilerOptions;
referencedMap?: MapLike<string[]>;
exportedModulesMap?: MapLike<string[]>;
semanticDiagnosticsPerFile?: ProgramBuildInfoDiagnostic[];
}
/**
* Gets the program information to be emitted in buildInfo so that we can use it to create new program
*/
function getProgramBuildInfo(state: Readonly<ReusableBuilderProgramState>, getCanonicalFileName: GetCanonicalFileName): ProgramBuildInfo | undefined {
if (state.compilerOptions.outFile || state.compilerOptions.out) return undefined;
const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory();
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory));
const fileInfos: MapLike<BuilderState.FileInfo> = {};
state.fileInfos.forEach((value, key) => {
const signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature, affectsGlobalScope: value.affectsGlobalScope };
});
const result: ProgramBuildInfo = {
fileInfos,
options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
};
if (state.referencedMap) {
const referencedMap: MapLike<string[]> = {};
for (const key of arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive)) {
referencedMap[relativeToBuildInfo(key)] = arrayFrom(state.referencedMap.get(key)!.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive);
}
result.referencedMap = referencedMap;
}
if (state.exportedModulesMap) {
const exportedModulesMap: MapLike<string[]> = {};
for (const key of arrayFrom(state.exportedModulesMap.keys()).sort(compareStringsCaseSensitive)) {
const newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
// Not in temporary cache, use existing value
if (newValue === undefined) exportedModulesMap[relativeToBuildInfo(key)] = arrayFrom(state.exportedModulesMap.get(key)!.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive);
// Value in cache and has updated value map, use that
else if (newValue) exportedModulesMap[relativeToBuildInfo(key)] = arrayFrom(newValue.keys(), relativeToBuildInfo).sort(compareStringsCaseSensitive);
}
result.exportedModulesMap = exportedModulesMap;
}
if (state.semanticDiagnosticsPerFile) {
const semanticDiagnosticsPerFile: ProgramBuildInfoDiagnostic[] = [];
for (const key of arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) {
const value = state.semanticDiagnosticsPerFile.get(key)!;
semanticDiagnosticsPerFile.push(
value.length ?
[
relativeToBuildInfo(key),
state.hasReusableDiagnostic ?
value as readonly ReusableDiagnostic[] :
convertToReusableDiagnostics(value as readonly Diagnostic[], relativeToBuildInfo)
] :
relativeToBuildInfo(key)
);
}
result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
}
return result;
function relativeToBuildInfoEnsuringAbsolutePath(path: string) {
return relativeToBuildInfo(getNormalizedAbsolutePath(path, currentDirectory));
}
function relativeToBuildInfo(path: string) {
return ensurePathIsNonModuleName(getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
}
}
function convertToReusableCompilerOptions(options: CompilerOptions, relativeToBuildInfo: (path: string) => string) {
const result: CompilerOptions = {};
const { optionsNameMap } = getOptionsNameMap();
for (const name in options) {
if (hasProperty(options, name)) {
result[name] = convertToReusableCompilerOptionValue(
optionsNameMap.get(name.toLowerCase()),
options[name] as CompilerOptionsValue,
relativeToBuildInfo
);
}
}
if (result.configFilePath) {
result.configFilePath = relativeToBuildInfo(result.configFilePath);
}
return result;
}
function convertToReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, relativeToBuildInfo: (path: string) => string) {
if (option) {
if (option.type === "list") {
const values = value as readonly (string | number)[];
if (option.element.isFilePath && values.length) {
return values.map(relativeToBuildInfo);
}
}
else if (option.isFilePath) {
return relativeToBuildInfo(value as string);
}
}
return value;
}
function convertToReusableDiagnostics(diagnostics: readonly Diagnostic[], relativeToBuildInfo: (path: string) => string): readonly ReusableDiagnostic[] {
Debug.assert(!!diagnostics.length);
return diagnostics.map(diagnostic => {
const result: ReusableDiagnostic = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
result.reportsUnnecessary = diagnostic.reportsUnnecessary;
result.source = diagnostic.source;
const { relatedInformation } = diagnostic;
result.relatedInformation = relatedInformation ?
relatedInformation.length ?
relatedInformation.map(r => convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo)) :
emptyArray :
undefined;
return result;
});
}
function convertToReusableDiagnosticRelatedInformation(diagnostic: DiagnosticRelatedInformation, relativeToBuildInfo: (path: string) => string): ReusableDiagnosticRelatedInformation {
const { file } = diagnostic;
return {
...diagnostic,
file: file ? relativeToBuildInfo(file.resolvedPath) : undefined
};
}
export enum BuilderProgramKind {
SemanticDiagnosticsBuilderProgram,
EmitAndSemanticDiagnosticsBuilderProgram
}
export interface BuilderCreationParameters {
newProgram: Program;
host: BuilderProgramHost;
oldProgram: BuilderProgram | undefined;
configFileParsingDiagnostics: readonly Diagnostic[];
}
export function getBuilderCreationParameters(newProgramOrRootNames: Program | readonly string[] | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: readonly Diagnostic[] | BuilderProgram, configFileParsingDiagnostics?: readonly Diagnostic[], projectReferences?: readonly ProjectReference[]): BuilderCreationParameters {
let host: BuilderProgramHost;
let newProgram: Program;
let oldProgram: BuilderProgram;
if (newProgramOrRootNames === undefined) {
Debug.assert(hostOrOptions === undefined);
host = oldProgramOrHost as CompilerHost;
oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram;
Debug.assert(!!oldProgram);
newProgram = oldProgram.getProgram();
}
else if (isArray(newProgramOrRootNames)) {
oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram;
newProgram = createProgram({
rootNames: newProgramOrRootNames,
options: hostOrOptions as CompilerOptions,
host: oldProgramOrHost as CompilerHost,
oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
configFileParsingDiagnostics,
projectReferences
});
host = oldProgramOrHost as CompilerHost;
}
else {
newProgram = newProgramOrRootNames;
host = hostOrOptions as BuilderProgramHost;
oldProgram = oldProgramOrHost as BuilderProgram;
configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram as readonly Diagnostic[];
}
return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray };
}
export function createBuilderProgram(kind: BuilderProgramKind.SemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): SemanticDiagnosticsBuilderProgram;
export function createBuilderProgram(kind: BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): EmitAndSemanticDiagnosticsBuilderProgram;
export function createBuilderProgram(kind: BuilderProgramKind, { newProgram, host, oldProgram, configFileParsingDiagnostics }: BuilderCreationParameters) {
// Return same program if underlying program doesnt change
let oldState = oldProgram && oldProgram.getState();
if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
newProgram = undefined!; // TODO: GH#18217
oldState = undefined;
return oldProgram;
}
/**
* Create the canonical file name for identity
*/
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
/**
* Computing hash to for signature verification
*/
const computeHash = host.createHash || generateDjb2Hash;
let state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
let backupState: BuilderProgramState | undefined;
newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state, getCanonicalFileName);
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined!; // TODO: GH#18217
oldProgram = undefined;
oldState = undefined;
const builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
builderProgram.getState = () => state;
builderProgram.backupState = () => {
Debug.assert(backupState === undefined);
backupState = cloneBuilderProgramState(state);
};
builderProgram.restoreState = () => {
state = Debug.checkDefined(backupState);
backupState = undefined;
};
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile);
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
builderProgram.emit = emit;
builderProgram.releaseProgram = () => {
releaseCache(state);
backupState = undefined;
};
if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
(builderProgram as SemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
}
else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
(builderProgram as EmitAndSemanticDiagnosticsBuilderProgram).getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
(builderProgram as EmitAndSemanticDiagnosticsBuilderProgram).emitNextAffectedFile = emitNextAffectedFile;
}
else {
notImplemented();
}
return builderProgram;
/**
* Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
function emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult<EmitResult> {
let affected = getNextAffectedFile(state, cancellationToken, computeHash);
let emitKind = BuilderFileEmit.Full;
let isPendingEmitFile = false;
if (!affected) {
if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
const pendingAffectedFile = getNextAffectedFilePendingEmit(state);
if (!pendingAffectedFile) {
if (state.emittedBuildInfo) {
return undefined;
}
const affected = Debug.checkDefined(state.program);
return toAffectedFileEmitResult(
state,
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
// Otherwise just affected file
affected.emitBuildInfo(writeFile || maybeBind(host, host.writeFile), cancellationToken),
affected,
/*emitKind*/ BuilderFileEmit.Full,
/*isPendingEmitFile*/ false,
/*isBuildInfoEmit*/ true
);
}
({ affectedFile: affected, emitKind } = pendingAffectedFile);
isPendingEmitFile = true;
}
else {
const program = Debug.checkDefined(state.program);
if (state.programEmitComplete) return undefined;
affected = program;
}
}
return toAffectedFileEmitResult(
state,
// When whole program is affected, do emit only once (eg when --out or --outFile is specified)
// Otherwise just affected file
Debug.checkDefined(state.program).emit(
affected === state.program ? undefined : affected as SourceFile,
writeFile || maybeBind(host, host.writeFile),
cancellationToken,
emitOnlyDtsFiles || emitKind === BuilderFileEmit.DtsOnly,
customTransformers
),
affected,
emitKind,
isPendingEmitFile,
);
}
/**
* Emits the JavaScript and declaration files.
* When targetSource file is specified, emits the files corresponding to that source file,
* otherwise for the whole program.
* In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
* it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
* it will only emit all the affected files instead of whole program
*
* The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
* in that order would be used to write the files
*/
function emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult {
if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
const result = handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
if (result) return result;
if (!targetSourceFile) {
// Emit and report any errors we ran into.
let sourceMaps: SourceMapEmitResult[] = [];
let emitSkipped = false;
let diagnostics: Diagnostic[] | undefined;
let emittedFiles: string[] = [];
let affectedEmitResult: AffectedFileResult<EmitResult>;
while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics);
emittedFiles = addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
sourceMaps = addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
}
return {
emitSkipped,
diagnostics: diagnostics || emptyArray,
emittedFiles,
sourceMaps
};
}
}
return Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
}
/**
* Return the semantic diagnostics for the next affected file or undefined if iteration is complete
* If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
*/
function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult<readonly Diagnostic[]> {
while (true) {
const affected = getNextAffectedFile(state, cancellationToken, computeHash);
if (!affected) {
// Done
return undefined;
}
else if (affected === state.program) {
// When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
return toAffectedFileResult(
state,
state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken),
affected
);
}
// Add file to affected file pending emit to handle for later emit time
if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
addToAffectedFilesPendingEmit(state, (affected as SourceFile).resolvedPath, BuilderFileEmit.Full);
}
// Get diagnostics for the affected file if its not ignored
if (ignoreSourceFile && ignoreSourceFile(affected as SourceFile)) {
// Get next affected file
doneWithAffectedFile(state, affected);
continue;
}
return toAffectedFileResult(
state,
getSemanticDiagnosticsOfFile(state, affected as SourceFile, cancellationToken),
affected
);
}
}
/**
* Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
* The semantic diagnostics are cached and managed here
* Note that it is assumed that when asked about semantic diagnostics through this API,
* the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
* In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
* it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
*/
function getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
const compilerOptions = Debug.checkDefined(state.program).getCompilerOptions();
if (compilerOptions.outFile || compilerOptions.out) {
Debug.assert(!state.semanticDiagnosticsPerFile);
// We dont need to cache the diagnostics just return them from program
return Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
}
if (sourceFile) {
return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
}
// When semantic builder asks for diagnostics of the whole program,
// ensure that all the affected files are handled
// eslint-disable-next-line no-empty
while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
}
let diagnostics: Diagnostic[] | undefined;
for (const sourceFile of Debug.checkDefined(state.program).getSourceFiles()) {
diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken));
}
return diagnostics || emptyArray;
}
}
function addToAffectedFilesPendingEmit(state: BuilderProgramState, affectedFilePendingEmit: Path, kind: BuilderFileEmit) {
if (!state.affectedFilesPendingEmit) state.affectedFilesPendingEmit = [];
if (!state.affectedFilesPendingEmitKind) state.affectedFilesPendingEmitKind = createMap();
const existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
// affectedFilesPendingEmitIndex === undefined
// - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
// so start from 0 as array would be affectedFilesPendingEmit
// else, continue to iterate from existing index, the current set is appended to existing files
if (state.affectedFilesPendingEmitIndex === undefined) {
state.affectedFilesPendingEmitIndex = 0;
}
}
function getMapOfReferencedSet(mapLike: MapLike<readonly string[]> | undefined, toPath: (path: string) => Path): ReadonlyMap<BuilderState.ReferencedSet> | undefined {
if (!mapLike) return undefined;
const map = createMap<BuilderState.ReferencedSet>();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
for (const key in mapLike) {
if (hasProperty(mapLike, key)) {
map.set(toPath(key), arrayToSet(mapLike[key], toPath));
}
}
return map;
}
export function createBuildProgramUsingProgramBuildInfo(program: ProgramBuildInfo, buildInfoPath: string, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram {
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
const fileInfos = createMap<BuilderState.FileInfo>();
for (const key in program.fileInfos) {
if (hasProperty(program.fileInfos, key)) {
fileInfos.set(toPath(key), program.fileInfos[key]);
}
}
const state: ReusableBuilderProgramState = {
fileInfos,
compilerOptions: convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toPath(isString(value) ? value : value[0]), value => isString(value) ? emptyArray : value[1]),
hasReusableDiagnostic: true
};
return {
getState: () => state,
backupState: noop,
restoreState: noop,
getProgram: notImplemented,
getProgramOrUndefined: returnUndefined,
releaseProgram: noop,
getCompilerOptions: () => state.compilerOptions,
getSourceFile: notImplemented,
getSourceFiles: notImplemented,
getOptionsDiagnostics: notImplemented,
getGlobalDiagnostics: notImplemented,
getConfigFileParsingDiagnostics: notImplemented,
getSyntacticDiagnostics: notImplemented,
getDeclarationDiagnostics: notImplemented,
getSemanticDiagnostics: notImplemented,
emit: notImplemented,
getAllDependencies: notImplemented,
getCurrentDirectory: notImplemented,
emitNextAffectedFile: notImplemented,
getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
close: noop,
};
function toPath(path: string) {
return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
}
function toAbsolutePath(path: string) {
return getNormalizedAbsolutePath(path, buildInfoDirectory);
}
}
export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram {
return {
getState: notImplemented,
backupState: noop,
restoreState: noop,
getProgram,
getProgramOrUndefined: () => state.program,
releaseProgram: () => state.program = undefined,
getCompilerOptions: () => state.compilerOptions,
getSourceFile: fileName => getProgram().getSourceFile(fileName),
getSourceFiles: () => getProgram().getSourceFiles(),
getOptionsDiagnostics: cancellationToken => getProgram().getOptionsDiagnostics(cancellationToken),
getGlobalDiagnostics: cancellationToken => getProgram().getGlobalDiagnostics(cancellationToken),
getConfigFileParsingDiagnostics: () => configFileParsingDiagnostics,
getSyntacticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken),
getDeclarationDiagnostics: (sourceFile, cancellationToken) => getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken),
getSemanticDiagnostics: (sourceFile, cancellationToken) => getProgram().getSemanticDiagnostics(sourceFile, cancellationToken),
emit: (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) => getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers),
getAllDependencies: notImplemented,
getCurrentDirectory: () => getProgram().getCurrentDirectory(),
close: noop,
};
function getProgram() {
return Debug.checkDefined(state.program);
}
}
}
| {'content_hash': '37b8365aa5be8fca3b373254efd57dcf', 'timestamp': '', 'source': 'github', 'line_count': 1207, 'max_line_length': 442, 'avg_line_length': 53.15907207953604, 'alnum_prop': 0.6438134127144928, 'repo_name': 'nojvek/TypeScript', 'id': 'd5a1e16f2f1d1c3183069b22cf8c459dd204be49', 'size': '64163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/compiler/builder.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '232'}, {'name': 'Groovy', 'bytes': '726'}, {'name': 'HTML', 'bytes': '3817'}, {'name': 'JavaScript', 'bytes': '175'}, {'name': 'PowerShell', 'bytes': '2855'}, {'name': 'Shell', 'bytes': '283'}, {'name': 'TypeScript', 'bytes': '52987420'}]} |
package ApiExamples;
// ********* THIS FILE IS AUTO PORTED *********
import org.testng.annotations.Test;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.Orientation;
import com.aspose.words.PageVerticalAlignment;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.SectionLayoutMode;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.Document;
import com.aspose.ms.System.Drawing.Printing.PrinterSettings;
import com.aspose.words.Section;
import com.aspose.words.ConvertUtil;
import com.aspose.words.TextColumnCollection;
import com.aspose.words.TextColumn;
import com.aspose.words.LineNumberRestartMode;
import org.testng.Assert;
import com.aspose.ms.System.msString;
import com.aspose.words.PageBorderDistanceFrom;
import com.aspose.words.PageBorderAppliesTo;
import com.aspose.words.Border;
import com.aspose.words.BorderType;
import com.aspose.words.LineStyle;
import java.awt.Color;
import com.aspose.ms.System.Drawing.msColor;
import com.aspose.words.NumberStyle;
import com.aspose.words.ParagraphAlignment;
import com.aspose.words.FootnotePosition;
import com.aspose.words.FootnoteNumberingRule;
import com.aspose.words.EndnotePosition;
import com.aspose.words.MultiplePagesType;
import com.aspose.words.Body;
import com.aspose.ms.NUnit.Framework.msAssert;
import com.aspose.words.Paragraph;
import com.aspose.words.FootnoteType;
@Test
public class ExPageSetup extends ApiExampleBase
{
@Test
public void clearFormatting() throws Exception
{
//ExStart
//ExFor:DocumentBuilder.PageSetup
//ExFor:DocumentBuilder.InsertBreak
//ExFor:DocumentBuilder.Document
//ExFor:PageSetup
//ExFor:PageSetup.Orientation
//ExFor:PageSetup.VerticalAlignment
//ExFor:PageSetup.ClearFormatting
//ExFor:Orientation
//ExFor:PageVerticalAlignment
//ExFor:BreakType
//ExSummary:Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults.
DocumentBuilder builder = new DocumentBuilder();
// Modify the first section in the document.
builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
builder.getPageSetup().setVerticalAlignment(PageVerticalAlignment.CENTER);
builder.writeln("Section 1, landscape oriented and text vertically centered.");
// Start a new section and reset its formatting to defaults.
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.getPageSetup().clearFormatting();
builder.writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment.");
builder.getDocument().save(getArtifactsDir() + "PageSetup.ClearFormatting.doc");
//ExEnd
}
@Test
public void differentHeaders() throws Exception
{
//ExStart
//ExFor:PageSetup.DifferentFirstPageHeaderFooter
//ExFor:PageSetup.OddAndEvenPagesHeaderFooter
//ExFor:PageSetup.LayoutMode
//ExFor:PageSetup.CharactersPerLine
//ExFor:PageSetup.LinesPerPage
//ExFor:SectionLayoutMode
//ExSummary:Creates headers and footers different for first, even and odd pages using DocumentBuilder.
DocumentBuilder builder = new DocumentBuilder();
PageSetup ps = builder.getPageSetup();
ps.setDifferentFirstPageHeaderFooter(true);
ps.setOddAndEvenPagesHeaderFooter(true);
ps.setLayoutMode(SectionLayoutMode.LINE_GRID);
ps.setCharactersPerLine(1);
ps.setLinesPerPage(1);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
builder.writeln("First page header.");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN);
builder.writeln("Even pages header.");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.writeln("Odd pages header.");
// Move back to the main story of the first section.
builder.moveToSection(0);
builder.writeln("Text page 1.");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Text page 2.");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Text page 3.");
builder.getDocument().save(getArtifactsDir() + "PageSetup.DifferentHeaders.doc");
//ExEnd
}
@Test
public void sectionStart() throws Exception
{
//ExStart
//ExFor:SectionStart
//ExFor:PageSetup.SectionStart
//ExFor:Document.Sections
//ExSummary:Specifies how the section starts, from a new page, on the same page or other.
Document doc = new Document();
doc.getSections().get(0).getPageSetup().setSectionStart(com.aspose.words.SectionStart.CONTINUOUS);
//ExEnd
}
@Test (enabled = false, description = "Run only when the printer driver is installed")
public void defaultPaperTray() throws Exception
{
//ExStart
//ExFor:PageSetup.FirstPageTray
//ExFor:PageSetup.OtherPagesTray
//ExSummary:Changes all sections in a document to use the default paper tray of the selected printer.
Document doc = new Document();
// Find the printer that will be used for printing this document. In this case it is the default printer.
// You can define a specific printer using PrinterName.
PrinterSettings settings = new PrinterSettings();
// The paper tray value stored in documents is completely printer specific. This means
// The code below resets all page tray values to use the current printers default tray.
// You can enumerate PrinterSettings.PaperSources to find the other valid paper tray values of the selected printer.
for (Section section : doc.getSections().<Section>OfType() !!Autoporter error: Undefined expression type )
{
section.getPageSetup().setFirstPageTray(settings.getDefaultPageSettings().PaperSource.RawKind);
section.getPageSetup().setOtherPagesTray(settings.getDefaultPageSettings().PaperSource.RawKind);
}
//ExEnd
}
@Test (enabled = false, description = "Run only when the printer driver is installed")
public void paperTrayForDifferentPaperType() throws Exception
{
//ExStart
//ExFor:PageSetup.FirstPageTray
//ExFor:PageSetup.OtherPagesTray
//ExSummary:Shows how to set up printing using different printer trays for different paper sizes.
Document doc = new Document();
// Choose the default printer to be used for printing this document.
PrinterSettings settings = new PrinterSettings();
// This is the tray we will use for A4 paper size. This is the first tray in the paper sources collection.
int printerTrayForA4 = settings.getPaperSources().get(0).RawKind;
// The is the tray we will use for Letter paper size. This is the second tray in the paper sources collection.
int printerTrayForLetter = settings.getPaperSources().get(1).RawKind;
// Set the page tray used for each section based off the paper size used in the section.
for (Section section : doc.getSections().<Section>OfType() !!Autoporter error: Undefined expression type )
{
if (section.getPageSetup().getPaperSize() == com.aspose.words.PaperSize.LETTER)
{
section.getPageSetup().setFirstPageTray(printerTrayForLetter);
section.getPageSetup().setOtherPagesTray(printerTrayForLetter);
}
else if (section.getPageSetup().getPaperSize() == com.aspose.words.PaperSize.A4)
{
section.getPageSetup().setFirstPageTray(printerTrayForA4);
section.getPageSetup().setOtherPagesTray(printerTrayForA4);
}
}
//ExEnd
}
@Test
public void pageMargins() throws Exception
{
//ExStart
//ExFor:ConvertUtil
//ExFor:ConvertUtil.InchToPoint
//ExFor:PaperSize
//ExFor:PageSetup.PaperSize
//ExFor:PageSetup.Orientation
//ExFor:PageSetup.TopMargin
//ExFor:PageSetup.BottomMargin
//ExFor:PageSetup.LeftMargin
//ExFor:PageSetup.RightMargin
//ExFor:PageSetup.HeaderDistance
//ExFor:PageSetup.FooterDistance
//ExSummary:Specifies paper size, orientation, margins and other settings for a section.
DocumentBuilder builder = new DocumentBuilder();
PageSetup ps = builder.getPageSetup();
ps.setPaperSize(com.aspose.words.PaperSize.LEGAL);
ps.setOrientation(Orientation.LANDSCAPE);
ps.setTopMargin(ConvertUtil.inchToPoint(1.0));
ps.setBottomMargin(ConvertUtil.inchToPoint(1.0));
ps.setLeftMargin(ConvertUtil.inchToPoint(1.5));
ps.setRightMargin(ConvertUtil.inchToPoint(1.5));
ps.setHeaderDistance(ConvertUtil.inchToPoint(0.2));
ps.setFooterDistance(ConvertUtil.inchToPoint(0.2));
builder.writeln("Hello world.");
builder.getDocument().save(getArtifactsDir() + "PageSetup.PageMargins.doc");
//ExEnd
}
@Test
public void columnsSameWidth() throws Exception
{
//ExStart
//ExFor:PageSetup.TextColumns
//ExFor:TextColumnCollection
//ExFor:TextColumnCollection.Spacing
//ExFor:TextColumnCollection.SetCount
//ExSummary:Creates multiple evenly spaced columns in a section using DocumentBuilder.
DocumentBuilder builder = new DocumentBuilder();
TextColumnCollection columns = builder.getPageSetup().getTextColumns();
// Make spacing between columns wider.
columns.setSpacing(100.0);
// This creates two columns of equal width.
columns.setCount(2);
builder.writeln("Text in column 1.");
builder.insertBreak(BreakType.COLUMN_BREAK);
builder.writeln("Text in column 2.");
builder.getDocument().save(getArtifactsDir() + "PageSetup.ColumnsSameWidth.doc");
//ExEnd
}
@Test
public void columnsCustomWidth() throws Exception
{
//ExStart
//ExFor:TextColumnCollection.LineBetween
//ExFor:TextColumnCollection.EvenlySpaced
//ExFor:TextColumnCollection.Item
//ExFor:TextColumn
//ExFor:TextColumn.Width
//ExFor:TextColumn.SpaceAfter
//ExSummary:Creates multiple columns of different widths in a section using DocumentBuilder.
DocumentBuilder builder = new DocumentBuilder();
TextColumnCollection columns = builder.getPageSetup().getTextColumns();
// Show vertical line between columns.
columns.setLineBetween(true);
// Indicate we want to create column with different widths.
columns.setEvenlySpaced(false);
// Create two columns, note they will be created with zero widths, need to set them.
columns.setCount(2);
// Set the first column to be narrow.
TextColumn c1 = columns.get(0);
c1.setWidth(100.0);
c1.setSpaceAfter(20.0);
// Set the second column to take the rest of the space available on the page.
TextColumn c2 = columns.get(1);
PageSetup ps = builder.getPageSetup();
double contentWidth = ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin();
c2.setWidth(contentWidth - c1.getWidth() - c1.getSpaceAfter());
builder.writeln("Narrow column 1.");
builder.insertBreak(BreakType.COLUMN_BREAK);
builder.writeln("Wide column 2.");
builder.getDocument().save(getArtifactsDir() + "PageSetup.ColumnsCustomWidth.doc");
//ExEnd
}
@Test
public void lineNumbers() throws Exception
{
//ExStart
//ExFor:PageSetup.LineStartingNumber
//ExFor:PageSetup.LineNumberDistanceFromText
//ExFor:PageSetup.LineNumberCountBy
//ExFor:PageSetup.LineNumberRestartMode
//ExFor:ParagraphFormat.SuppressLineNumbers
//ExFor:LineNumberRestartMode
//ExSummary:Turns on Microsoft Word line numbering for a section.
DocumentBuilder builder = new DocumentBuilder();
PageSetup ps = builder.getPageSetup();
ps.setLineStartingNumber(1);
ps.setLineNumberCountBy(5);
ps.setLineNumberRestartMode(LineNumberRestartMode.RESTART_PAGE);
ps.setLineNumberDistanceFromText(50.0d);
// The line counter will skip any paragraph with this flag set to true
Assert.assertFalse(builder.getParagraphFormat().getSuppressLineNumbers());
for (int i = 1; i <= 20; i++)
builder.writeln(msString.format("Line {0}.", i));
builder.getDocument().save(getArtifactsDir() + "PageSetup.LineNumbers.docx");
//ExEnd
}
@Test
public void pageBorderProperties() throws Exception
{
//ExStart
//ExFor:Section.PageSetup
//ExFor:PageSetup.BorderAlwaysInFront
//ExFor:PageSetup.BorderDistanceFrom
//ExFor:PageSetup.BorderAppliesTo
//ExFor:PageBorderDistanceFrom
//ExFor:PageBorderAppliesTo
//ExFor:Border.DistanceFromText
//ExSummary:Creates a page border that looks like a wide blue band at the top of the first page only.
Document doc = new Document();
PageSetup ps = doc.getSections().get(0).getPageSetup();
ps.setBorderAlwaysInFront(false);
ps.setBorderDistanceFrom(PageBorderDistanceFrom.PAGE_EDGE);
ps.setBorderAppliesTo(PageBorderAppliesTo.FIRST_PAGE);
Border border = ps.getBorders().getByBorderType(BorderType.TOP);
border.setLineStyle(LineStyle.SINGLE);
border.setLineWidth(30.0);
border.setColor(Color.BLUE);
border.setDistanceFromText(0.0);
doc.save(getArtifactsDir() + "PageSetup.PageBorderTop.doc");
//ExEnd
}
@Test
public void pageBorders() throws Exception
{
//ExStart
//ExFor:PageSetup.Borders
//ExFor:Border.Shadow
//ExFor:BorderCollection.LineStyle
//ExFor:BorderCollection.LineWidth
//ExFor:BorderCollection.Color
//ExFor:BorderCollection.DistanceFromText
//ExFor:BorderCollection.Shadow
//ExSummary:Creates a fancy looking green wavy page border with a shadow.
Document doc = new Document();
PageSetup ps = doc.getSections().get(0).getPageSetup();
ps.getBorders().setLineStyle(LineStyle.DOUBLE_WAVE);
ps.getBorders().setLineWidth(2.0);
ps.getBorders().setColor(msColor.getGreen());
ps.getBorders().setDistanceFromText(24.0);
ps.getBorders().setShadow(true);
doc.save(getArtifactsDir() + "PageSetup.PageBorders.doc");
//ExEnd
}
@Test
public void pageNumbering() throws Exception
{
//ExStart
//ExFor:PageSetup.RestartPageNumbering
//ExFor:PageSetup.PageStartingNumber
//ExFor:PageSetup.PageNumberStyle
//ExFor:DocumentBuilder.InsertField(String, String)
//ExSummary:Shows how to control page numbering per section.
// This document has two sections, but no page numbers yet.
Document doc = new Document(getMyDir() + "PageSetup.PageNumbering.doc");
// Use document builder to create a header with a page number field for the first section.
// The page number will look like "Page V".
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToSection(0);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Page ");
builder.insertField("PAGE", "");
// Set first section page numbering.
Section section = doc.getSections().get(0);
section.getPageSetup().setRestartPageNumbering(true);
section.getPageSetup().setPageStartingNumber(5);
section.getPageSetup().setPageNumberStyle(NumberStyle.UPPERCASE_ROMAN);
// Create a header for the section.
// The page number will look like " - 10 - ".
builder.moveToSection(1);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.write(" - ");
builder.insertField("PAGE", "");
builder.write(" - ");
// Set second section page numbering.
section = doc.getSections().get(1);
section.getPageSetup().setPageStartingNumber(10);
section.getPageSetup().setRestartPageNumbering(true);
section.getPageSetup().setPageNumberStyle(NumberStyle.ARABIC);
doc.save(getArtifactsDir() + "PageSetup.PageNumbering.doc");
//ExEnd
}
@Test
public void footnoteOptions() throws Exception
{
//ExStart
//ExFor:PageSetup.FootnoteOptions
//ExSummary:Shows how to set options for footnotes in current section
Document doc = new Document();
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.getFootnoteOptions().setPosition(FootnotePosition.BOTTOM_OF_PAGE);
pageSetup.getFootnoteOptions().setNumberStyle(NumberStyle.BULLET);
pageSetup.getFootnoteOptions().setStartNumber(1);
pageSetup.getFootnoteOptions().setRestartRule(FootnoteNumberingRule.RESTART_PAGE);
pageSetup.getFootnoteOptions().setColumns(0);
//ExEnd
}
@Test
public void endnoteOptions() throws Exception
{
//ExStart
//ExFor:PageSetup.EndnoteOptions
//ExSummary:Shows how to set options for endnotes in current section
Document doc = new Document();
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.getEndnoteOptions().setPosition(EndnotePosition.END_OF_SECTION);
pageSetup.getEndnoteOptions().setNumberStyle(NumberStyle.BULLET);
pageSetup.getEndnoteOptions().setStartNumber(1);
pageSetup.getEndnoteOptions().setRestartRule(FootnoteNumberingRule.RESTART_PAGE);
//ExEnd
}
@Test
public void bidi() throws Exception
{
//ExStart
//ExFor:PageSetup.Bidi
//ExSummary:Shows how to change the order of columns.
Document doc = new Document();
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.getTextColumns().setCount(3);
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Column 1.");
builder.insertBreak(BreakType.COLUMN_BREAK);
builder.write("Column 2.");
builder.insertBreak(BreakType.COLUMN_BREAK);
builder.write("Column 3.");
// Reverse the order of the columns
pageSetup.setBidi(true);
doc.save(getArtifactsDir() + "PageSetup.Bidi.docx");
//ExEnd
}
@Test
public void borderSurrounds() throws Exception
{
//ExStart
//ExFor:PageSetup.BorderSurroundsFooter
//ExFor:PageSetup.BorderSurroundsHeader
//ExSummary:Shows how to apply a border to the page and header/footer.
Document doc = new Document();
// Insert header and footer text
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Header");
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.write("Footer");
builder.moveToDocumentEnd();
// Insert a page border and set the color and line style
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.getBorders().setLineStyle(LineStyle.DOUBLE);
pageSetup.getBorders().setColor(Color.BLUE);
// By default, page borders don't surround headers and footers
// We can change that by setting these flags
pageSetup.setBorderSurroundsFooter(true);
pageSetup.setBorderSurroundsHeader(true);
doc.save(getArtifactsDir() + "PageSetup.BorderSurrounds.docx");
//ExEnd
}
@Test
public void gutter() throws Exception
{
//ExStart
//ExFor:PageSetup.Gutter
//ExFor:PageSetup.RtlGutter
//ExFor:PageSetup.MultiplePages
//ExSummary:Shows how to set gutter margins.
Document doc = new Document();
// Insert text spanning several pages
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 0; i < 6; i++)
{
builder.write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
builder.insertBreak(BreakType.PAGE_BREAK);
}
// We can access the gutter margin in the section's page options,
// which is a margin which is added to the page margin at one side of the page
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.setGutter(100.0);
// If our text is LTR, the gutter will appear on the left side of the page
// Setting this flag will move it to the right side
pageSetup.setRtlGutter(true);
// Mirroring the margins will make the gutter alternate in position from page to page
pageSetup.setMultiplePages(MultiplePagesType.MIRROR_MARGINS);
doc.save(getArtifactsDir() + "PageSetup.Gutter.docx");
//ExEnd
}
@Test
public void booklet() throws Exception
{
//ExStart
//ExFor:PageSetup.SheetsPerBooklet
//ExSummary:Shows how to create a booklet.
Document doc = new Document();
// Use a document builder to create 16 pages of content that will be compiled in a booklet
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("My Booklet:");
for (int i = 0; i < 15; i++)
{
builder.insertBreak(BreakType.PAGE_BREAK);
builder.write($"Booklet face #{i}");
}
// Set the number of sheets that will be used by the printer to create the booklet
// After being printed on both sides, the sheets can be stacked and folded down the centre
// The contents that we placed in such a way that they will be in order once the booklet is folded
// We can only specify the number of sheets in multiples of 4
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.setMultiplePages(MultiplePagesType.BOOK_FOLD_PRINTING);
pageSetup.setSheetsPerBooklet(4);
doc.save(getArtifactsDir() + "PageSetup.Booklet.docx");
//ExEnd
}
@Test
public void textOrientation() throws Exception
{
//ExStart
//ExFor:PageSetup.TextOrientation
//ExSummary:Shows how to set text orientation.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
// Setting this value will rotate the section's text 90 degrees to the right
PageSetup pageSetup = doc.getSections().get(0).getPageSetup();
pageSetup.setTextOrientation(com.aspose.words.TextOrientation.UPWARD);
doc.save(getArtifactsDir() + "PageSetup.TextOrientation.docx");
//ExEnd
}
//ExStart
//ExFor:PageSetup.SuppressEndnotes
//ExFor:Body.ParentSection
//ExSummary:Shows how to store endnotes at the end of each section instead of the document and manipulate their positions.
@Test //ExSkip
public void suppressEndnotes() throws Exception
{
// Create a new document and make it empty
Document doc = new Document();
doc.removeAllChildren();
// Normally endnotes are all stored at the end of a document, but this option lets us store them at the end of each section
doc.getEndnoteOptions().setPosition(EndnotePosition.END_OF_SECTION);
// Create 3 new sections, each having a paragraph and an endnote at the end
insertSection(doc, "Section 1", "Endnote 1, will stay in section 1");
insertSection(doc, "Section 2", "Endnote 2, will be pushed down to section 3");
insertSection(doc, "Section 3", "Endnote 3, will stay in section 3");
// Each section contains its own page setup object
// Setting this value will push this section's endnotes down to the next section
PageSetup pageSetup = doc.getSections().get(1).getPageSetup();
pageSetup.setSuppressEndnotes(true);
doc.save(getArtifactsDir() + "PageSetup.SuppressEndnotes.docx");
}
/// <summary>
/// Add a section to the end of a document, give it a body and a paragraph, then add text and an endnote to that paragraph
/// </summary>
private void insertSection(Document doc, String sectionBodyText, String endnoteText)
{
Section section = new Section(doc);
doc.appendChild(section);
Body body = new Body(doc);
section.appendChild(body);
msAssert.areEqual(section, body.getParentNode());
Paragraph para = new Paragraph(doc);
body.appendChild(para);
msAssert.areEqual(body, para.getParentNode());
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveTo(para);
builder.write(sectionBodyText);
builder.insertFootnote(FootnoteType.ENDNOTE, endnoteText);
}
//ExEnd
}
| {'content_hash': 'ebe5507272ecce41cc7dc67da71a2e68', 'timestamp': '', 'source': 'github', 'line_count': 644, 'max_line_length': 153, 'avg_line_length': 39.46894409937888, 'alnum_prop': 0.6753481784562121, 'repo_name': 'asposewords/Aspose_Words_Java', 'id': '8562f278e39f1db99d3549d3ffaeec16804f5be3', 'size': '25773', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ApiExamples/JavaPorting/ExPageSetup.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '43597'}, {'name': 'Java', 'bytes': '587567'}, {'name': 'PHP', 'bytes': '136694'}, {'name': 'Python', 'bytes': '150182'}, {'name': 'Ruby', 'bytes': '81830'}]} |
<?xml version="1.0" ?>
<srcfile name="ToolTip.java" file_path="/Users/valerio/Research/Code/Source Code Comments Classification/comments_classification/media/jfreechart/0.7.1/jfreechart-071zip/extracted/jfreechart-0.7.1/source/com/jrefinery/chart/tooltips/ToolTip.java" >
<node name="COMPILATION_UNIT" line="0" instruction_class="COMPILATION_UNIT" instruction="COMPILATION_UNIT">
<node name="PACKAGE_DECLARATION" line="0" instruction_class="KEYWORD" instruction="PACKAGE_KEYWORD">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="com" line="39" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="jrefinery" line="39" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="chart" line="39" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="tooltips" line="39" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</node>
<node name="SINGLE_TYPE_IMPORT_DECLARATION" line="0" instruction_class="KEYWORD" instruction="IMPORT_KEYWORD">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="java" line="41" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="awt" line="41" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="Shape" line="41" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</node>
<class_statement_node name="CLASS_DECLARATION" line="0" instruction_class="CLASS_DECLARATION" instruction="CLASS_KEYWORD">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="public" line="46" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="ToolTip" line="46" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="CLASS_BODY" line="0" instruction_class="CLASS_BODY" instruction="CLASS_BODY">
<statement_node name="FIELD_DECLARATION" line="0" instruction_class="FIELD_DECLARATION" instruction="FIELD_DECLARATION">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="protected" line="49" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="String" line="49" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="VARIABLE_DECLARATOR" line="0" instruction_class="VARIABLE_DECLARATOR" instruction="VARIABLE_DECLARATOR">
<node name="text" line="49" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
<statement_node name="FIELD_DECLARATION" line="0" instruction_class="FIELD_DECLARATION" instruction="FIELD_DECLARATION">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="protected" line="52" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="Shape" line="52" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="VARIABLE_DECLARATOR" line="0" instruction_class="VARIABLE_DECLARATOR" instruction="VARIABLE_DECLARATOR">
<node name="area" line="52" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
<method_statement_node name="CONSTRUCTOR_DECLARATION" line="0" instruction_class="METHOD_DECLARATION" instruction="CONSTRUCTOR_METHOD_DECLARATION">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="public" line="59" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="ToolTip" line="59" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="FORMAL_PARAMETERS" line="0" instruction_class="FORMAL_PARAMETERS" instruction="FORMAL_PARAMETERS">
<node name="FORMAL_PARAMETER" line="0" instruction_class="FORMAL_PARAMETER" instruction="FORMAL_PARAMETER">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
</node>
<node name="String" line="59" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="text" line="59" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="FORMAL_PARAMETER" line="0" instruction_class="FORMAL_PARAMETER" instruction="FORMAL_PARAMETER">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
</node>
<node name="Shape" line="59" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="area" line="59" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</node>
<statement_node name="CONSTRUCTOR_BODY" line="0" instruction_class="CONSTRUCTOR_BODY" instruction="CONSTRUCTOR_BODY">
<statement_node name="if" line="62" instruction_class="CONDITIONAL_STATEMENT" instruction="IF_STATEMENT">
<node name="==" line="62" instruction_class="OPERATOR" instruction="EQUALITY_OPERATOR">
<node name="area" line="62" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="null" line="62" instruction_class="LITERAL" instruction="NULL_LITERAL">
</node>
</node>
<statement_node name="throw" line="62" instruction_class="CONTROLFLOW_STATEMENT" instruction="EXCEPTION_THROW">
<node name="UNQUALIFIED_CLASS_INSTANCE_CREATION" line="0" instruction_class="UNQUALIFIED_CLASS_INSTANCE_CREATION" instruction="UNQUALIFIED_CLASS_INSTANCE_CREATION">
<node name="IllegalArgumentException" line="62" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="ARGUMENTS" line="0" instruction_class="ARGUMENTS" instruction="ARGUMENTS">
<node name="EXPRESSION_LIST" line="0" instruction_class="EXPRESSION_LIST" instruction="EXPRESSION_LIST">
<node name=""ToolTip(...): null area."" line="62" instruction_class="LITERAL" instruction="STRING_LITERAL">
</node>
</node>
</node>
</node>
</statement_node>
</statement_node>
<statement_node name="EXPRESSION_STATEMENT" line="0" instruction_class="EXPRESSION_STATEMENT" instruction="EXPRESSION_STATEMENT">
<node name="=" line="64" instruction_class="OPERATOR" instruction="ASSIGNEMENT_OPERATOR">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="THIS" line="0" instruction_class="THIS" instruction="THIS">
</node>
<node name="text" line="64" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="text" line="64" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
<statement_node name="EXPRESSION_STATEMENT" line="0" instruction_class="EXPRESSION_STATEMENT" instruction="EXPRESSION_STATEMENT">
<node name="=" line="65" instruction_class="OPERATOR" instruction="ASSIGNEMENT_OPERATOR">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="THIS" line="0" instruction_class="THIS" instruction="THIS">
</node>
<node name="area" line="65" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
<node name="area" line="65" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
</statement_node>
</method_statement_node>
<method_statement_node name="METHOD_DECLARATION" line="0" instruction_class="METHOD_DECLARATION" instruction="METHOD_DECLARATION">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="public" line="72" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="String" line="72" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="getText" line="72" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="FORMAL_PARAMETERS" line="0" instruction_class="FORMAL_PARAMETERS" instruction="FORMAL_PARAMETERS">
</node>
<statement_node name="METHOD_BODY" line="0" instruction_class="METHOD_BODY" instruction="METHOD_BODY">
<statement_node name="return" line="73" instruction_class="CONTROLFLOW_STATEMENT" instruction="RETURN_STATEMENT">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="THIS" line="0" instruction_class="THIS" instruction="THIS">
</node>
<node name="text" line="73" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
</statement_node>
</method_statement_node>
<method_statement_node name="METHOD_DECLARATION" line="0" instruction_class="METHOD_DECLARATION" instruction="METHOD_DECLARATION">
<node name="MODIFIERS" line="0" instruction_class="MODIFIERS" instruction="MODIFIERS">
<node name="public" line="80" instruction_class="MODIFIER" instruction="ACCESS_LEVEL_MODIFIER">
</node>
</node>
<node name="Shape" line="80" instruction_class="TYPE" instruction="CLASS_OR_INTERFACE_TYPE">
</node>
<node name="getArea" line="80" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
<node name="FORMAL_PARAMETERS" line="0" instruction_class="FORMAL_PARAMETERS" instruction="FORMAL_PARAMETERS">
</node>
<statement_node name="METHOD_BODY" line="0" instruction_class="METHOD_BODY" instruction="METHOD_BODY">
<statement_node name="return" line="81" instruction_class="CONTROLFLOW_STATEMENT" instruction="RETURN_STATEMENT">
<node name="SELECT" line="0" instruction_class="SELECT" instruction="SELECT">
<node name="THIS" line="0" instruction_class="THIS" instruction="THIS">
</node>
<node name="area" line="81" instruction_class="IDENTIFIER" instruction="IDENTIFIER">
</node>
</node>
</statement_node>
</statement_node>
</method_statement_node>
</node>
</class_statement_node>
</node>
</srcfile> | {'content_hash': 'bd38371de26b502e2440013c5be4b6c1', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 248, 'avg_line_length': 64.24043715846994, 'alnum_prop': 0.632783259612113, 'repo_name': 'leriomaggio/code-coherence-evaluation-tool', 'id': '5332628a764822cfd2d8a5f22d18fccddb544ff4', 'size': '11756', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'code_comments_coherence/media/jfreechart/0.7.1/jfreechart-071zip/xml_source_files/jfreechart-0.7.1/source/com/jrefinery/chart/tooltips/ToolTip.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '4554'}, {'name': 'GAP', 'bytes': '54356'}, {'name': 'HTML', 'bytes': '101167'}, {'name': 'Java', 'bytes': '7241060'}, {'name': 'JavaScript', 'bytes': '4644'}, {'name': 'Python', 'bytes': '1934652'}]} |
namespace protocol {
namespace net {
namespace internal_ {
namespace {
void Init_();
void Pass_();
void (*init_func_)() = Init_;
void Init_() {
setlocale(LC_ALL, "zh_TW.utf8");
init_func_ = Pass_;
}
void Pass_() {}
} // namespace
void InitIfFirst() { init_func_(); }
} // namespace internal_
} // namespace net
} // namespace protocol
| {'content_hash': '8a013187aedd0a407d6c90ac0981fc52', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 36, 'avg_line_length': 10.055555555555555, 'alnum_prop': 0.5939226519337016, 'repo_name': 'cathook/PTTArticleRecommander', 'id': '44c11afd1d580a743d11dc21c7908bc7c37bc8ad', 'size': '411', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/article_analysis/protocol/net.cc', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '147525'}, {'name': 'CMake', 'bytes': '4945'}, {'name': 'CSS', 'bytes': '574'}, {'name': 'HTML', 'bytes': '826'}, {'name': 'JavaScript', 'bytes': '8054'}, {'name': 'Python', 'bytes': '147058'}, {'name': 'Shell', 'bytes': '308'}]} |
order: 0
title:
zh-CN: 基本用法
en-US: Basic
---
## zh-CN
基本的时间轴。
## en-US
Basic timeline.
````jsx
import { Timeline } from 'igroot';
ReactDOM.render(
<Timeline>
<Timeline.Item>Create a services site 2015-09-01</Timeline.Item>
<Timeline.Item>Solve initial network problems 2015-09-01</Timeline.Item>
<Timeline.Item>Technical testing 2015-09-01</Timeline.Item>
<Timeline.Item>Network problems being solved 2015-09-01</Timeline.Item>
</Timeline>,
mountNode);
````
| {'content_hash': '35cfad2772fb9614cf30836e3dbab3ef', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 76, 'avg_line_length': 18.846153846153847, 'alnum_prop': 0.6877551020408164, 'repo_name': 'guoqn/igroot', 'id': '6da890b81792712c46829e3aa69e4d4cdc23b1a0', 'size': '516', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/timeline/demo/basic.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '417493'}, {'name': 'HTML', 'bytes': '7478'}, {'name': 'JavaScript', 'bytes': '844680'}, {'name': 'Shell', 'bytes': '430'}, {'name': 'TypeScript', 'bytes': '567750'}]} |
/**
* the DOM object
* @namespace
* @name cc.DOM
*/
cc.DOM = {};
/**
* @function
* @private
* @param node
*/
cc.DOM._addMethods = function (node) {
for (var funcs in cc.DOM.methods) {
node[funcs] = cc.DOM.methods[funcs];
}
// Redefine getter setter
cc.defineGetterSetter(node, "x", node.getPositionX, node.setPositionX);
cc.defineGetterSetter(node, "y", node.getPositionY, node.setPositionY);
cc.defineGetterSetter(node, "width", node._getWidth, node._setWidth);
cc.defineGetterSetter(node, "height", node._getHeight, node._setHeight);
cc.defineGetterSetter(node, "anchorX", node._getAnchorX, node._setAnchorX);
cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY);
cc.defineGetterSetter(node, "scale", node.getScale, node.setScale);
cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX);
cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.setScaleY);
cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation);
cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX);
cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY);
cc.defineGetterSetter(node, "visible", node.isVisible, node.setVisible);
cc.defineGetterSetter(node, "parent", node.getParent, node.setParent);
cc.defineGetterSetter(node, "opacity", node.getOpacity, node.setOpacity);
};
cc.DOM.methods = /** @lends cc.DOM# */{
/**
* Replace the set position of ccNode
* @param {cc.Point|Number} x
* @param {Number} y
*/
setPosition:function (x, y) {
if (y === undefined) {
this._position.x = x.x;
this._position.y = x.y;
} else {
this._position.x = x;
this._position.y = y;
}
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Position Y of ccNode
* @param {Number} y
*/
setPositionY:function (y) {
this._position.y = y;
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Position X of ccNode
* @param {Number} x
*/
setPositionX:function (x) {
this._position.x = x;
this.setNodeDirty();
this.dom.translates(this._position.x, -this._position.y);
},
/**
* replace set Scale of ccNode
* @param {object|Number} scale
* @param {Number} scaleY
*/
setScale:function (scale, scaleY) {
//save dirty region when before change
//this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
this._scaleX = scale;
this._scaleY = scaleY || scale;
//save dirty region when after changed
//this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set Scale X of ccNode
* @param {Number} x
*/
setScaleX:function (x) {
this._scaleX = x;
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set Scale Y of ccNode
* @param {Number} y
*/
setScaleY:function (y) {
this._scaleY = y;
this.setNodeDirty();
this.dom.resize(this._scaleX, this._scaleY);
},
/**
* replace set anchorpoint of ccNode
* @param {cc.Point|Number} point The anchor point of node or The anchor point.x of node.
* @param {Number} [y] The anchor point.y of node.
*/
setAnchorPoint:function (point, y) {
var cmd = this._renderCmd;
var locAnchorPoint = this._anchorPoint;
if (y === undefined) {
locAnchorPoint.x = point.x;
locAnchorPoint.y = point.y;
} else {
locAnchorPoint.x = point;
locAnchorPoint.y = y;
}
var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
locAPP.x = locSize.width * locAnchorPoint.x;
locAPP.y = locSize.height * locAnchorPoint.y;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
this.dom.style.marginBottom = -locAPP.y + 'px';
}
this.setNodeDirty();
},
/**
* replace set anchorpoint x of ccNode
* @param {Number} x The anchor x of node.
*/
_setAnchorX:function (x) {
var locAnchorPoint = this._anchorPoint;
var cmd = this._renderCmd;
if (x === locAnchorPoint.x)
return;
locAnchorPoint.x = x;
var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
locAPP.x = locSize.width * locAnchorPoint.x;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
}
this.setNodeDirty();
},
/**
* replace set anchorpoint y of ccNode
* @param {Number} y The anchor y of node.
*/
_setAnchorY:function (y) {
var locAnchorPoint = this._anchorPoint;
var cmd = this._renderCmd;
if (y === locAnchorPoint.y)
return;
locAnchorPoint.y = y;
var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
locAPP.y = locSize.height * locAnchorPoint.y;
this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
if (this.ignoreAnchor) {
this.dom.style.marginLeft = 0;
this.dom.style.marginBottom = 0;
} else {
this.dom.style.marginBottom = -locAPP.y + 'px';
}
this.setNodeDirty();
},
/**
* replace set ContentSize of ccNode
* @param {cc.Size|Number} size The untransformed size of the node or The untransformed size's width of the node.
* @param {Number} [height] The untransformed size's height of the node.
*/
setContentSize:function (size, height) {
var cmd = this._renderCmd;
var locContentSize = this._contentSize;
if (height === undefined) {
locContentSize.width = size.width;
locContentSize.height = size.height;
} else {
locContentSize.width = size;
locContentSize.height = height;
}
var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
locAPP.x = locContentSize.width * locAnchorPoint.x;
locAPP.y = locContentSize.height * locAnchorPoint.y;
this.dom.width = locContentSize.width;
this.dom.height = locContentSize.height;
this.setAnchorPoint(this.getAnchorPoint());
if (this.canvas) {
this.canvas.width = locContentSize.width;
this.canvas.height = locContentSize.height;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set width of ccNode
* @param {Number} width The untransformed size's width of the node.
*/
_setWidth:function (width) {
var locContentSize = this._contentSize;
var cmd = this._renderCmd;
if (width === locContentSize.width)
return;
locContentSize.width = width;
var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
locAPP.x = locContentSize.width * locAnchorPoint.x;
this.dom.width = locContentSize.width;
this.anchorX = locAnchorPoint.x;
if (this.canvas) {
this.canvas.width = locContentSize.width;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set height of ccNode
* @param {Number} height The untransformed size's height of the node.
*/
_setHeight:function (height) {
var locContentSize = this._contentSize;
var cmd = this._renderCmd;
if (height === locContentSize.height)
return;
locContentSize.height = height;
var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
locAPP.y = locContentSize.height * locAnchorPoint.y;
this.dom.height = locContentSize.height;
this.anchorY = locAnchorPoint.y;
if (this.canvas) {
this.canvas.height = locContentSize.height;
}
this.setNodeDirty();
this.redraw();
},
/**
* replace set Rotation of ccNode
* @param {Number} newRotation
*/
setRotation:function (newRotation) {
if (this._rotation === newRotation)
return;
this._rotationX = this._rotationY = newRotation;
this.setNodeDirty();
this.dom.rotate(newRotation);
},
/**
* replace set SkewX of ccNode
* @param {Number} x
*/
setSkewX:function (x) {
this._skewX = x;
this.setNodeDirty();
this.dom.setSkew(this._skewX, this._skewY);
},
/**
* replace set SkewY of ccNode
* @param {Number} y
*/
setSkewY:function (y) {
this._skewY = y;
this.setNodeDirty();
this.dom.setSkew(this._skewX, this._skewY);
},
/**
* replace set Visible of ccNode
* @param {Boolean} x
*/
setVisible:function (x) {
this._visible = x;
this.setNodeDirty();
if (this.dom)
this.dom.style.display = (x) ? 'block' : 'none';
},
_setLocalZOrder:function (z) {
this._localZOrder = z;
this.setNodeDirty();
if (this.dom)
this.dom.zIndex = z;
},
/**
* replace set Parent of ccNode
* @param {cc.Node} p
*/
setParent:function (p) {
this._parent = p;
if (p !== null) {
p.setAnchorPoint(p.getAnchorPoint());
this.setNodeDirty();
cc.DOM.parentDOM(this);
}
},
/**
* replace resume Schedule and actions of ccNode
*/
resume:function () {
this.getScheduler().resumeTarget(this);
this.getActionManager().resumeTarget(this);
cc.eventManager.resumeTarget(this);
//if dom does not have parent, but node has no parent and its running
if (this.dom && !this.dom.parentNode) {
if (!this.getParent()) {
if(this.dom.id === ""){
cc.DOM._createEGLViewDiv(this);
}else{
this.dom.appendTo(cc.container);
}
} else {
cc.DOM.parentDOM(this);
}
}
if (this.dom)
this.dom.style.visibility = "visible";
},
/**
* replace pause Schedule and Actions of ccNode
*/
pause:function () {
this.getScheduler().pauseTarget(this);
this.getActionManager().pauseTarget(this);
cc.eventManager.pauseTarget(this);
if (this.dom) {
this.dom.style.visibility = 'hidden';
}
},
/**
* replace clean up of ccNode
*/
cleanup:function () {
// actions
this.stopAllActions();
this.unscheduleAllCallbacks();
cc.eventManager.removeListeners(this);
// timers
this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
if (this.dom) {
this.dom.remove();
}
},
setOpacity:function (o) {
this._opacity = o;
this.dom.style.opacity = o / 255;
},
/**
* refresh/updates the DOM element
*/
redraw:function () {
if (this.isSprite) {
var tmp = this._children;
this._children = [];
cc.Sprite.prototype.visit.call(this, this.ctx);
this._children = tmp;
}
else {
cc.Sprite.prototype.visit.call(this, this.ctx);
}
}
};
cc.DOM._resetEGLViewDiv = function(){
var div = cc.$("#EGLViewDiv");
if(div){
var view = cc.view;
var designSize = view.getDesignResolutionSize();
var viewPortRect = view.getViewPortRect();
var screenSize = view.getFrameSize();
var pixelRatio = view.getDevicePixelRatio();
var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
if((designSize.width === 0) && (designSize.height === 0)){
designSizeWidth = screenSize.width;
designSizeHeight = screenSize.height;
}
var viewPortWidth = viewPortRect.width/pixelRatio;
if((viewPortRect.width === 0) && (viewPortRect.height === 0)){
viewPortWidth = screenSize.width;
}
div.style.position = 'absolute';
//x.dom.style.display='block';
div.style.width = designSizeWidth + "px";
div.style.maxHeight = designSizeHeight + "px";
div.style.margin = 0;
div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
if (view.getResolutionPolicy() === view._rpNoBorder) {
div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px";
div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
}
else {
div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
div.style.bottom = "0px";
}
}
};
/**
* @function
* @private
* @param x
* @return {Boolean}
*/
cc.DOM.parentDOM = function (x) {
var p = x.getParent();
//if has parent, parent need to have dom too
if (!p || !x.dom)
return false;
if (!p.dom) {
cc.DOM.placeHolder(p);
p.setParent = cc.DOM.methods.setParent;
}
//if parent have dom, attach self to parent
x.dom.appendTo(p.dom);
p.setAnchorPoint(p.getAnchorPoint());
if (p.getParent()) {
cc.DOM.parentDOM(p);
} else {
//parent has no more parent, if its running, then add it to the container
if (p.isRunning()) {
//find EGLView div
var eglViewDiv = cc.$("#EGLViewDiv");
if (eglViewDiv) {
p.dom.appendTo(eglViewDiv);
} else {
cc.DOM._createEGLViewDiv(p);
}
}
}
return true;
};
cc.DOM._createEGLViewDiv = function(p){
var div = cc.$("#EGLViewDiv");
if(!div){
div = cc.$new("div");
div.id = "EGLViewDiv";
}
var view = cc.view;
var designSize = view.getDesignResolutionSize();
var viewPortRect = view.getViewPortRect();
var screenSize = view.getFrameSize();
var pixelRatio = view.getDevicePixelRatio();
var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
if ((designSize.width === 0) && (designSize.height === 0)) {
designSizeWidth = screenSize.width;
designSizeHeight = screenSize.height;
}
var viewPortWidth = viewPortRect.width/pixelRatio;
if ((viewPortRect.width === 0) && (viewPortRect.height === 0)) {
viewPortWidth = screenSize.width;
}
div.style.position = 'absolute';
//x.dom.style.display='block';
div.style.width = designSizeWidth + "px";
div.style.maxHeight = designSizeHeight + "px";
div.style.margin = 0;
div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
if (view.getResolutionPolicy() === view._rpNoBorder) {
div.style.left = (screenSize.width - designSizeWidth)/2 + "px";
div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
}
else {
div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
div.style.bottom = "0px";
}
p.dom.appendTo(div);
div.appendTo(cc.container);
};
/**
* @function
* @private
* @param x
*/
cc.DOM.setTransform = function (x) {
if (x.ctx) {
x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y);
if (x.isSprite) {
var tmp = x._children;
x._children = [];
cc.Sprite.prototype.visit.call(x);
x._children = tmp;
}
else {
cc.Sprite.prototype.visit.call(x);
}
}
if (x.dom) {
x.dom.position.x = x.getPositionX();
x.dom.position.y = -x.getPositionY();
x.dom.rotation = x.getRotation();
x.dom.scale = {x:x.getScaleX(), y:x.getScaleY()};
x.dom.skew = {x:x.getSkewX(), y:x.getSkewY()};
if (x.setAnchorPoint)
x.setAnchorPoint(x.getAnchorPoint());
x.dom.transforms();
}
};
/**
* @function
* @private
* @param x
*/
cc.DOM.forSprite = function (x) {
x.dom = cc.$new('div');
x.canvas = cc.$new('canvas');
var locContentSize = x.getContentSize();
x.canvas.width = locContentSize.width;
x.canvas.height = locContentSize.height;
x.dom.style.position = 'absolute';
x.dom.style.bottom = 0;
x.ctx = x.canvas.getContext('2d');
x.dom.appendChild(x.canvas);
if (x.getParent()) {
cc.DOM.parentDOM(x);
}
x.isSprite = true;
};
/**
* This creates divs for parent Nodes that are related to the current node
* @function
* @private
* @param x
*/
cc.DOM.placeHolder = function (x) {
//creating a placeholder dom to simulate other ccNode in the hierachy
x.dom = cc.$new('div');
x.placeholder = true;
x.dom.style.position = 'absolute';
x.dom.style.bottom = 0;
//x.dom.style.display='block';
x.dom.style.width = (x.getContentSize().width || cc.director.getWinSize().width) + "px";
x.dom.style.maxHeight = (x.getContentSize().height || cc.director.getWinSize().height) + "px";
x.dom.style.margin = 0;
cc.DOM.setTransform(x);
x.dom.transforms();
cc.DOM._addMethods(x);
//x.dom.style.border = 'red 1px dotted';
};
/**
* Converts cc.Sprite or cc.MenuItem to DOM elements <br/>
* It currently only supports cc.Sprite and cc.MenuItem
* @function
* @param {cc.Sprite|cc.MenuItem|Array} nodeObject
* @example
* // example
* cc.DOM.convert(Sprite1, Sprite2, Menuitem);
*
* var myDOMElements = [Sprite1, Sprite2, MenuItem];
* cc.DOM.convert(myDOMElements);
*/
cc.DOM.convert = function (nodeObject) {
//if passing by list, make it an array
if (arguments.length > 1) {
cc.DOM.convert(arguments);
return;
} else if (arguments.length === 1 && !arguments[0].length) {
cc.DOM.convert([arguments[0]]);
return;
}
var args = arguments[0];
for (var i = 0; i < args.length; i++) {
//first check if its sprite
if (args[i] instanceof cc.Sprite) {
// create a canvas
if (!args[i].dom)
cc.DOM.forSprite(args[i]);
} else {
cc.log('DOM converter only supports sprite and menuitems yet');
}
cc.DOM._addMethods(args[i]);
args[i].visit = function () {
};
args[i].transform = function () {
};
cc.DOM.setTransform(args[i]);
args[i].setVisible(args[i].isVisible());
}
};
| {'content_hash': '788573aa7a64e0b0055288def8813375', 'timestamp': '', 'source': 'github', 'line_count': 630, 'max_line_length': 117, 'avg_line_length': 31.036507936507938, 'alnum_prop': 0.5712166930905743, 'repo_name': 'babestvl/FoodClash', 'id': '05dd06cd5300ccbb57f6dc0e6629c11716c0d3b3', 'size': '20888', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'frameworks/cocos2d-html5/extensions/editbox/CCdomNode.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CMake', 'bytes': '11529'}, {'name': 'HTML', 'bytes': '4292'}, {'name': 'JavaScript', 'bytes': '4636509'}]} |
#define LOG_TAG "RILC"
#include <hardware_legacy/power.h>
#include <telephony/ril.h>
#include <telephony/ril_cdma_sms.h>
#include <cutils/sockets.h>
#include <cutils/jstring.h>
#include <telephony/record_stream.h>
#include <utils/Log.h>
#include <utils/SystemClock.h>
#include <pthread.h>
#include <binder/Parcel.h>
#include <cutils/jstring.h>
#include <sys/types.h>
#include <sys/limits.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <alloca.h>
#include <sys/un.h>
#include <assert.h>
#include <netinet/in.h>
#include <cutils/properties.h>
#include <ril_event.h>
namespace android {
#define PHONE_PROCESS "radio"
#define SOCKET_NAME_RIL "rild"
#define SOCKET_NAME_RIL_DEBUG "rild-debug"
#define ANDROID_WAKE_LOCK_NAME "radio-interface"
#define PROPERTY_RIL_IMPL "gsm.version.ril-impl"
// match with constant in RIL.java
#define MAX_COMMAND_BYTES (8 * 1024)
// Basically: memset buffers that the client library
// shouldn't be using anymore in an attempt to find
// memory usage issues sooner.
#define MEMSET_FREED 1
#define NUM_ELEMS(a) (sizeof (a) / sizeof (a)[0])
#define MIN(a,b) ((a)<(b) ? (a) : (b))
/* Constants for response types */
#define RESPONSE_SOLICITED 0
#define RESPONSE_UNSOLICITED 1
/* Negative values for private RIL errno's */
#define RIL_ERRNO_INVALID_RESPONSE -1
// request, response, and unsolicited msg print macro
#define PRINTBUF_SIZE 8096
// Enable RILC log
#define RILC_LOG 0
#if RILC_LOG
#define startRequest sprintf(printBuf, "(")
#define closeRequest sprintf(printBuf, "%s)", printBuf)
#define printRequest(token, req) \
RLOGD("[%04d]> %s %s", token, requestToString(req), printBuf)
#define startResponse sprintf(printBuf, "%s {", printBuf)
#define closeResponse sprintf(printBuf, "%s}", printBuf)
#define printResponse RLOGD("%s", printBuf)
#define clearPrintBuf printBuf[0] = 0
#define removeLastChar printBuf[strlen(printBuf)-1] = 0
#define appendPrintBuf(x...) sprintf(printBuf, x)
#else
#define startRequest
#define closeRequest
#define printRequest(token, req)
#define startResponse
#define closeResponse
#define printResponse
#define clearPrintBuf
#define removeLastChar
#define appendPrintBuf(x...)
#endif
enum WakeType {DONT_WAKE, WAKE_PARTIAL};
typedef struct {
int requestNumber;
void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI);
int(*responseFunction) (Parcel &p, void *response, size_t responselen);
} CommandInfo;
typedef struct {
int requestNumber;
int (*responseFunction) (Parcel &p, void *response, size_t responselen);
WakeType wakeType;
} UnsolResponseInfo;
typedef struct RequestInfo {
int32_t token; //this is not RIL_Token
CommandInfo *pCI;
struct RequestInfo *p_next;
char cancelled;
char local; // responses to local commands do not go back to command process
} RequestInfo;
typedef struct UserCallbackInfo {
RIL_TimedCallback p_callback;
void *userParam;
struct ril_event event;
struct UserCallbackInfo *p_next;
} UserCallbackInfo;
/*******************************************************************/
RIL_RadioFunctions s_callbacks = {0, NULL, NULL, NULL, NULL, NULL};
static int s_registerCalled = 0;
static pthread_t s_tid_dispatch;
static pthread_t s_tid_reader;
static int s_started = 0;
static int s_fdListen = -1;
static int s_fdCommand = -1;
static int s_fdDebug = -1;
static int s_fdWakeupRead;
static int s_fdWakeupWrite;
static struct ril_event s_commands_event;
static struct ril_event s_wakeupfd_event;
static struct ril_event s_listen_event;
static struct ril_event s_wake_timeout_event;
static struct ril_event s_debug_event;
static const struct timeval TIMEVAL_WAKE_TIMEOUT = {1,0};
static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER;
static RequestInfo *s_pendingRequests = NULL;
static RequestInfo *s_toDispatchHead = NULL;
static RequestInfo *s_toDispatchTail = NULL;
static UserCallbackInfo *s_last_wake_timeout_info = NULL;
static void *s_lastNITZTimeData = NULL;
static size_t s_lastNITZTimeDataSize;
#if RILC_LOG
static char printBuf[PRINTBUF_SIZE];
#endif
/*******************************************************************/
static void dispatchVoid (Parcel& p, RequestInfo *pRI);
static void dispatchString (Parcel& p, RequestInfo *pRI);
static void dispatchStrings (Parcel& p, RequestInfo *pRI);
static void dispatchInts (Parcel& p, RequestInfo *pRI);
static void dispatchDial (Parcel& p, RequestInfo *pRI);
static void dispatchSIM_IO (Parcel& p, RequestInfo *pRI);
static void dispatchCallForward(Parcel& p, RequestInfo *pRI);
static void dispatchRaw(Parcel& p, RequestInfo *pRI);
static void dispatchSmsWrite (Parcel &p, RequestInfo *pRI);
static void dispatchDataCall (Parcel& p, RequestInfo *pRI);
static void dispatchVoiceRadioTech (Parcel& p, RequestInfo *pRI);
static void dispatchSetInitialAttachApn (Parcel& p, RequestInfo *pRI);
static void dispatchCdmaSubscriptionSource (Parcel& p, RequestInfo *pRI);
static void dispatchCdmaSms(Parcel &p, RequestInfo *pRI);
static void dispatchImsSms(Parcel &p, RequestInfo *pRI);
static void dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
static void dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef);
static void dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI);
static void dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI);
static void dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI);
static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI);
static int responseInts(Parcel &p, void *response, size_t responselen);
static int responseStrings(Parcel &p, void *response, size_t responselen);
static int responseString(Parcel &p, void *response, size_t responselen);
static int responseVoid(Parcel &p, void *response, size_t responselen);
static int responseCallList(Parcel &p, void *response, size_t responselen);
static int responseSMS(Parcel &p, void *response, size_t responselen);
static int responseSIM_IO(Parcel &p, void *response, size_t responselen);
static int responseCallForwards(Parcel &p, void *response, size_t responselen);
static int responseDataCallList(Parcel &p, void *response, size_t responselen);
static int responseSetupDataCall(Parcel &p, void *response, size_t responselen);
static int responseRaw(Parcel &p, void *response, size_t responselen);
static int responseSsn(Parcel &p, void *response, size_t responselen);
static int responseSimStatus(Parcel &p, void *response, size_t responselen);
static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen);
static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen);
static int responseCdmaSms(Parcel &p, void *response, size_t responselen);
static int responseCellList(Parcel &p, void *response, size_t responselen);
static int responseCdmaInformationRecords(Parcel &p,void *response, size_t responselen);
static int responseRilSignalStrength(Parcel &p,void *response, size_t responselen);
static int responseCallRing(Parcel &p, void *response, size_t responselen);
static int responseCdmaSignalInfoRecord(Parcel &p,void *response, size_t responselen);
static int responseCdmaCallWaiting(Parcel &p,void *response, size_t responselen);
static int responseSimRefresh(Parcel &p, void *response, size_t responselen);
static int responseCellInfoList(Parcel &p, void *response, size_t responselen);
static int decodeVoiceRadioTechnology (RIL_RadioState radioState);
static int decodeCdmaSubscriptionSource (RIL_RadioState radioState);
static RIL_RadioState processRadioState(RIL_RadioState newRadioState);
extern "C" const char * requestToString(int request);
extern "C" const char * failCauseToString(RIL_Errno);
extern "C" const char * callStateToString(RIL_CallState);
extern "C" const char * radioStateToString(RIL_RadioState);
#ifdef RIL_SHLIB
extern "C" void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
size_t datalen);
#endif
static UserCallbackInfo * internalRequestTimedCallback
(RIL_TimedCallback callback, void *param,
const struct timeval *relativeTime);
/** Index == requestNumber */
static CommandInfo s_commands[] = {
#include "ril_commands.h"
};
static UnsolResponseInfo s_unsolResponses[] = {
#include "ril_unsol_commands.h"
};
/* For older RILs that do not support new commands RIL_REQUEST_VOICE_RADIO_TECH and
RIL_UNSOL_VOICE_RADIO_TECH_CHANGED messages, decode the voice radio tech from
radio state message and store it. Every time there is a change in Radio State
check to see if voice radio tech changes and notify telephony
*/
int voiceRadioTech = -1;
/* For older RILs that do not support new commands RIL_REQUEST_GET_CDMA_SUBSCRIPTION_SOURCE
and RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED messages, decode the subscription
source from radio state and store it. Every time there is a change in Radio State
check to see if subscription source changed and notify telephony
*/
int cdmaSubscriptionSource = -1;
/* For older RILs that do not send RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, decode the
SIM/RUIM state from radio state and store it. Every time there is a change in Radio State,
check to see if SIM/RUIM status changed and notify telephony
*/
int simRuimStatus = -1;
static char *
strdupReadString(Parcel &p) {
size_t stringlen;
const char16_t *s16;
s16 = p.readString16Inplace(&stringlen);
return strndup16to8(s16, stringlen);
}
static void writeStringToParcel(Parcel &p, const char *s) {
char16_t *s16;
size_t s16_len;
s16 = strdup8to16(s, &s16_len);
p.writeString16(s16, s16_len);
free(s16);
}
static void
memsetString (char *s) {
if (s != NULL) {
memset (s, 0, strlen(s));
}
}
void nullParcelReleaseFunction (const uint8_t* data, size_t dataSize,
const size_t* objects, size_t objectsSize,
void* cookie) {
// do nothing -- the data reference lives longer than the Parcel object
}
/**
* To be called from dispatch thread
* Issue a single local request, ensuring that the response
* is not sent back up to the command process
*/
static void
issueLocalRequest(int request, void *data, int len) {
RequestInfo *pRI;
int ret;
pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
pRI->local = 1;
pRI->token = 0xffffffff; // token is not used in this context
pRI->pCI = &(s_commands[request]);
ret = pthread_mutex_lock(&s_pendingRequestsMutex);
assert (ret == 0);
pRI->p_next = s_pendingRequests;
s_pendingRequests = pRI;
ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
assert (ret == 0);
RLOGD("C[locl]> %s", requestToString(request));
s_callbacks.onRequest(request, data, len, pRI);
}
static int
processCommandBuffer(void *buffer, size_t buflen) {
Parcel p;
status_t status;
int32_t request;
int32_t token;
RequestInfo *pRI;
int ret;
p.setData((uint8_t *) buffer, buflen);
// status checked at end
status = p.readInt32(&request);
status = p.readInt32 (&token);
if (status != NO_ERROR) {
RLOGE("invalid request block");
return 0;
}
if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) {
RLOGE("unsupported request code %d token %d", request, token);
// FIXME this should perhaps return a response
return 0;
}
pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo));
pRI->token = token;
pRI->pCI = &(s_commands[request]);
ret = pthread_mutex_lock(&s_pendingRequestsMutex);
assert (ret == 0);
pRI->p_next = s_pendingRequests;
s_pendingRequests = pRI;
ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
assert (ret == 0);
/* sLastDispatchedToken = token; */
pRI->pCI->dispatchFunction(p, pRI);
return 0;
}
static void
invalidCommandBlock (RequestInfo *pRI) {
RLOGE("invalid command block for token %d request %s",
pRI->token, requestToString(pRI->pCI->requestNumber));
}
/** Callee expects NULL */
static void
dispatchVoid (Parcel& p, RequestInfo *pRI) {
clearPrintBuf;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, NULL, 0, pRI);
}
/** Callee expects const char * */
static void
dispatchString (Parcel& p, RequestInfo *pRI) {
status_t status;
size_t datalen;
size_t stringlen;
char *string8 = NULL;
string8 = strdupReadString(p);
startRequest;
appendPrintBuf("%s%s", printBuf, string8);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, string8,
sizeof(char *), pRI);
#ifdef MEMSET_FREED
memsetString(string8);
#endif
free(string8);
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/** Callee expects const char ** */
static void
dispatchStrings (Parcel &p, RequestInfo *pRI) {
int32_t countStrings;
status_t status;
size_t datalen;
char **pStrings;
status = p.readInt32 (&countStrings);
if (status != NO_ERROR) {
goto invalid;
}
startRequest;
if (countStrings == 0) {
// just some non-null pointer
pStrings = (char **)alloca(sizeof(char *));
datalen = 0;
} else if (((int)countStrings) == -1) {
pStrings = NULL;
datalen = 0;
} else {
datalen = sizeof(char *) * countStrings;
pStrings = (char **)alloca(datalen);
for (int i = 0 ; i < countStrings ; i++) {
pStrings[i] = strdupReadString(p);
appendPrintBuf("%s%s,", printBuf, pStrings[i]);
}
}
removeLastChar;
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, pStrings, datalen, pRI);
if (pStrings != NULL) {
for (int i = 0 ; i < countStrings ; i++) {
#ifdef MEMSET_FREED
memsetString (pStrings[i]);
#endif
free(pStrings[i]);
}
#ifdef MEMSET_FREED
memset(pStrings, 0, datalen);
#endif
}
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/** Callee expects const int * */
static void
dispatchInts (Parcel &p, RequestInfo *pRI) {
int32_t count;
status_t status;
size_t datalen;
int *pInts;
status = p.readInt32 (&count);
if (status != NO_ERROR || count == 0) {
goto invalid;
}
datalen = sizeof(int) * count;
pInts = (int *)alloca(datalen);
startRequest;
for (int i = 0 ; i < count ; i++) {
int32_t t;
status = p.readInt32(&t);
pInts[i] = (int)t;
appendPrintBuf("%s%d,", printBuf, t);
if (status != NO_ERROR) {
goto invalid;
}
}
removeLastChar;
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<int *>(pInts),
datalen, pRI);
#ifdef MEMSET_FREED
memset(pInts, 0, datalen);
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/**
* Callee expects const RIL_SMS_WriteArgs *
* Payload is:
* int32_t status
* String pdu
*/
static void
dispatchSmsWrite (Parcel &p, RequestInfo *pRI) {
RIL_SMS_WriteArgs args;
int32_t t;
status_t status;
memset (&args, 0, sizeof(args));
status = p.readInt32(&t);
args.status = (int)t;
args.pdu = strdupReadString(p);
if (status != NO_ERROR || args.pdu == NULL) {
goto invalid;
}
args.smsc = strdupReadString(p);
startRequest;
appendPrintBuf("%s%d,%s,smsc=%s", printBuf, args.status,
(char*)args.pdu, (char*)args.smsc);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, &args, sizeof(args), pRI);
#ifdef MEMSET_FREED
memsetString (args.pdu);
#endif
free (args.pdu);
#ifdef MEMSET_FREED
memset(&args, 0, sizeof(args));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/**
* Callee expects const RIL_Dial *
* Payload is:
* String address
* int32_t clir
*/
static void
dispatchDial (Parcel &p, RequestInfo *pRI) {
RIL_Dial dial;
RIL_UUS_Info uusInfo;
int32_t sizeOfDial;
int32_t t;
int32_t uusPresent;
status_t status;
memset (&dial, 0, sizeof(dial));
dial.address = strdupReadString(p);
status = p.readInt32(&t);
dial.clir = (int)t;
if (status != NO_ERROR || dial.address == NULL) {
goto invalid;
}
if (s_callbacks.version < 3) { // Remove when partners upgrade to version 3
uusPresent = 0;
sizeOfDial = sizeof(dial) - sizeof(RIL_UUS_Info *);
} else {
status = p.readInt32(&uusPresent);
if (status != NO_ERROR) {
goto invalid;
}
if (uusPresent == 0) {
dial.uusInfo = NULL;
} else {
int32_t len;
memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
status = p.readInt32(&t);
uusInfo.uusType = (RIL_UUS_Type) t;
status = p.readInt32(&t);
uusInfo.uusDcs = (RIL_UUS_DCS) t;
status = p.readInt32(&len);
if (status != NO_ERROR) {
goto invalid;
}
// The java code writes -1 for null arrays
if (((int) len) == -1) {
uusInfo.uusData = NULL;
len = 0;
} else {
uusInfo.uusData = (char*) p.readInplace(len);
}
uusInfo.uusLength = len;
dial.uusInfo = &uusInfo;
}
sizeOfDial = sizeof(dial);
}
startRequest;
appendPrintBuf("%snum=%s,clir=%d", printBuf, dial.address, dial.clir);
if (uusPresent) {
appendPrintBuf("%s,uusType=%d,uusDcs=%d,uusLen=%d", printBuf,
dial.uusInfo->uusType, dial.uusInfo->uusDcs,
dial.uusInfo->uusLength);
}
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, &dial, sizeOfDial, pRI);
#ifdef MEMSET_FREED
memsetString (dial.address);
#endif
free (dial.address);
#ifdef MEMSET_FREED
memset(&uusInfo, 0, sizeof(RIL_UUS_Info));
memset(&dial, 0, sizeof(dial));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/**
* Callee expects const RIL_SIM_IO *
* Payload is:
* int32_t command
* int32_t fileid
* String path
* int32_t p1, p2, p3
* String data
* String pin2
* String aidPtr
*/
static void
dispatchSIM_IO (Parcel &p, RequestInfo *pRI) {
union RIL_SIM_IO {
RIL_SIM_IO_v6 v6;
RIL_SIM_IO_v5 v5;
} simIO;
int32_t t;
int size;
status_t status;
memset (&simIO, 0, sizeof(simIO));
// note we only check status at the end
status = p.readInt32(&t);
simIO.v6.command = (int)t;
status = p.readInt32(&t);
simIO.v6.fileid = (int)t;
simIO.v6.path = strdupReadString(p);
status = p.readInt32(&t);
simIO.v6.p1 = (int)t;
status = p.readInt32(&t);
simIO.v6.p2 = (int)t;
status = p.readInt32(&t);
simIO.v6.p3 = (int)t;
simIO.v6.data = strdupReadString(p);
simIO.v6.pin2 = strdupReadString(p);
simIO.v6.aidPtr = strdupReadString(p);
startRequest;
appendPrintBuf("%scmd=0x%X,efid=0x%X,path=%s,%d,%d,%d,%s,pin2=%s,aid=%s", printBuf,
simIO.v6.command, simIO.v6.fileid, (char*)simIO.v6.path,
simIO.v6.p1, simIO.v6.p2, simIO.v6.p3,
(char*)simIO.v6.data, (char*)simIO.v6.pin2, simIO.v6.aidPtr);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
if (status != NO_ERROR) {
goto invalid;
}
size = (s_callbacks.version < 6) ? sizeof(simIO.v5) : sizeof(simIO.v6);
s_callbacks.onRequest(pRI->pCI->requestNumber, &simIO, size, pRI);
#ifdef MEMSET_FREED
memsetString (simIO.v6.path);
memsetString (simIO.v6.data);
memsetString (simIO.v6.pin2);
memsetString (simIO.v6.aidPtr);
#endif
free (simIO.v6.path);
free (simIO.v6.data);
free (simIO.v6.pin2);
free (simIO.v6.aidPtr);
#ifdef MEMSET_FREED
memset(&simIO, 0, sizeof(simIO));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
/**
* Callee expects const RIL_CallForwardInfo *
* Payload is:
* int32_t status/action
* int32_t reason
* int32_t serviceCode
* int32_t toa
* String number (0 length -> null)
* int32_t timeSeconds
*/
static void
dispatchCallForward(Parcel &p, RequestInfo *pRI) {
RIL_CallForwardInfo cff;
int32_t t;
status_t status;
memset (&cff, 0, sizeof(cff));
// note we only check status at the end
status = p.readInt32(&t);
cff.status = (int)t;
status = p.readInt32(&t);
cff.reason = (int)t;
status = p.readInt32(&t);
cff.serviceClass = (int)t;
status = p.readInt32(&t);
cff.toa = (int)t;
cff.number = strdupReadString(p);
status = p.readInt32(&t);
cff.timeSeconds = (int)t;
if (status != NO_ERROR) {
goto invalid;
}
// special case: number 0-length fields is null
if (cff.number != NULL && strlen (cff.number) == 0) {
cff.number = NULL;
}
startRequest;
appendPrintBuf("%sstat=%d,reason=%d,serv=%d,toa=%d,%s,tout=%d", printBuf,
cff.status, cff.reason, cff.serviceClass, cff.toa,
(char*)cff.number, cff.timeSeconds);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, &cff, sizeof(cff), pRI);
#ifdef MEMSET_FREED
memsetString(cff.number);
#endif
free (cff.number);
#ifdef MEMSET_FREED
memset(&cff, 0, sizeof(cff));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchRaw(Parcel &p, RequestInfo *pRI) {
int32_t len;
status_t status;
const void *data;
status = p.readInt32(&len);
if (status != NO_ERROR) {
goto invalid;
}
// The java code writes -1 for null arrays
if (((int)len) == -1) {
data = NULL;
len = 0;
}
data = p.readInplace(len);
startRequest;
appendPrintBuf("%sraw_size=%d", printBuf, len);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, const_cast<void *>(data), len, pRI);
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static status_t
constructCdmaSms(Parcel &p, RequestInfo *pRI, RIL_CDMA_SMS_Message& rcsm) {
int32_t t;
uint8_t ut;
status_t status;
int32_t digitCount;
int digitLimit;
memset(&rcsm, 0, sizeof(rcsm));
status = p.readInt32(&t);
rcsm.uTeleserviceID = (int) t;
status = p.read(&ut,sizeof(ut));
rcsm.bIsServicePresent = (uint8_t) ut;
status = p.readInt32(&t);
rcsm.uServicecategory = (int) t;
status = p.readInt32(&t);
rcsm.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
status = p.readInt32(&t);
rcsm.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
status = p.readInt32(&t);
rcsm.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
status = p.readInt32(&t);
rcsm.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
status = p.read(&ut,sizeof(ut));
rcsm.sAddress.number_of_digits= (uint8_t) ut;
digitLimit= MIN((rcsm.sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
status = p.read(&ut,sizeof(ut));
rcsm.sAddress.digits[digitCount] = (uint8_t) ut;
}
status = p.readInt32(&t);
rcsm.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
status = p.read(&ut,sizeof(ut));
rcsm.sSubAddress.odd = (uint8_t) ut;
status = p.read(&ut,sizeof(ut));
rcsm.sSubAddress.number_of_digits = (uint8_t) ut;
digitLimit= MIN((rcsm.sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
status = p.read(&ut,sizeof(ut));
rcsm.sSubAddress.digits[digitCount] = (uint8_t) ut;
}
status = p.readInt32(&t);
rcsm.uBearerDataLen = (int) t;
digitLimit= MIN((rcsm.uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
status = p.read(&ut, sizeof(ut));
rcsm.aBearerData[digitCount] = (uint8_t) ut;
}
if (status != NO_ERROR) {
return status;
}
startRequest;
appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
sAddress.digit_mode=%d, sAddress.Number_mode=%d, sAddress.number_type=%d, ",
printBuf, rcsm.uTeleserviceID,rcsm.bIsServicePresent,rcsm.uServicecategory,
rcsm.sAddress.digit_mode, rcsm.sAddress.number_mode,rcsm.sAddress.number_type);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
return status;
}
static void
dispatchCdmaSms(Parcel &p, RequestInfo *pRI) {
RIL_CDMA_SMS_Message rcsm;
ALOGD("dispatchCdmaSms");
if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
goto invalid;
}
s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm),pRI);
#ifdef MEMSET_FREED
memset(&rcsm, 0, sizeof(rcsm));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchImsCdmaSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
RIL_IMS_SMS_Message rism;
RIL_CDMA_SMS_Message rcsm;
ALOGD("dispatchImsCdmaSms: retry=%d, messageRef=%d", retry, messageRef);
if (NO_ERROR != constructCdmaSms(p, pRI, rcsm)) {
goto invalid;
}
memset(&rism, 0, sizeof(rism));
rism.tech = RADIO_TECH_3GPP2;
rism.retry = retry;
rism.messageRef = messageRef;
rism.message.cdmaMessage = &rcsm;
s_callbacks.onRequest(pRI->pCI->requestNumber, &rism,
sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
+sizeof(rcsm),pRI);
#ifdef MEMSET_FREED
memset(&rcsm, 0, sizeof(rcsm));
memset(&rism, 0, sizeof(rism));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchImsGsmSms(Parcel &p, RequestInfo *pRI, uint8_t retry, int32_t messageRef) {
RIL_IMS_SMS_Message rism;
int32_t countStrings;
status_t status;
size_t datalen;
char **pStrings;
ALOGD("dispatchImsGsmSms: retry=%d, messageRef=%d", retry, messageRef);
status = p.readInt32 (&countStrings);
if (status != NO_ERROR) {
goto invalid;
}
memset(&rism, 0, sizeof(rism));
rism.tech = RADIO_TECH_3GPP;
rism.retry = retry;
rism.messageRef = messageRef;
startRequest;
appendPrintBuf("%sformat=%d,", printBuf, rism.format);
if (countStrings == 0) {
// just some non-null pointer
pStrings = (char **)alloca(sizeof(char *));
datalen = 0;
} else if (((int)countStrings) == -1) {
pStrings = NULL;
datalen = 0;
} else {
datalen = sizeof(char *) * countStrings;
pStrings = (char **)alloca(datalen);
for (int i = 0 ; i < countStrings ; i++) {
pStrings[i] = strdupReadString(p);
appendPrintBuf("%s%s,", printBuf, pStrings[i]);
}
}
removeLastChar;
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
rism.message.gsmMessage = pStrings;
s_callbacks.onRequest(pRI->pCI->requestNumber, &rism,
sizeof(RIL_RadioTechnologyFamily)+sizeof(uint8_t)+sizeof(int32_t)
+datalen, pRI);
if (pStrings != NULL) {
for (int i = 0 ; i < countStrings ; i++) {
#ifdef MEMSET_FREED
memsetString (pStrings[i]);
#endif
free(pStrings[i]);
}
#ifdef MEMSET_FREED
memset(pStrings, 0, datalen);
#endif
}
#ifdef MEMSET_FREED
memset(&rism, 0, sizeof(rism));
#endif
return;
invalid:
ALOGE("dispatchImsGsmSms invalid block");
invalidCommandBlock(pRI);
return;
}
static void
dispatchImsSms(Parcel &p, RequestInfo *pRI) {
int32_t t;
status_t status = p.readInt32(&t);
RIL_RadioTechnologyFamily format;
uint8_t retry;
int32_t messageRef;
ALOGD("dispatchImsSms");
if (status != NO_ERROR) {
goto invalid;
}
format = (RIL_RadioTechnologyFamily) t;
// read retry field
status = p.read(&retry,sizeof(retry));
if (status != NO_ERROR) {
goto invalid;
}
// read messageRef field
status = p.read(&messageRef,sizeof(messageRef));
if (status != NO_ERROR) {
goto invalid;
}
if (RADIO_TECH_3GPP == format) {
dispatchImsGsmSms(p, pRI, retry, messageRef);
} else if (RADIO_TECH_3GPP2 == format) {
dispatchImsCdmaSms(p, pRI, retry, messageRef);
} else {
ALOGE("requestImsSendSMS invalid format value =%d", format);
}
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchCdmaSmsAck(Parcel &p, RequestInfo *pRI) {
RIL_CDMA_SMS_Ack rcsa;
int32_t t;
status_t status;
int32_t digitCount;
memset(&rcsa, 0, sizeof(rcsa));
status = p.readInt32(&t);
rcsa.uErrorClass = (RIL_CDMA_SMS_ErrorClass) t;
status = p.readInt32(&t);
rcsa.uSMSCauseCode = (int) t;
if (status != NO_ERROR) {
goto invalid;
}
startRequest;
appendPrintBuf("%suErrorClass=%d, uTLStatus=%d, ",
printBuf, rcsa.uErrorClass, rcsa.uSMSCauseCode);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa),pRI);
#ifdef MEMSET_FREED
memset(&rcsa, 0, sizeof(rcsa));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchGsmBrSmsCnf(Parcel &p, RequestInfo *pRI) {
int32_t t;
status_t status;
int32_t num;
status = p.readInt32(&num);
if (status != NO_ERROR) {
goto invalid;
}
{
RIL_GSM_BroadcastSmsConfigInfo gsmBci[num];
RIL_GSM_BroadcastSmsConfigInfo *gsmBciPtrs[num];
startRequest;
for (int i = 0 ; i < num ; i++ ) {
gsmBciPtrs[i] = &gsmBci[i];
status = p.readInt32(&t);
gsmBci[i].fromServiceId = (int) t;
status = p.readInt32(&t);
gsmBci[i].toServiceId = (int) t;
status = p.readInt32(&t);
gsmBci[i].fromCodeScheme = (int) t;
status = p.readInt32(&t);
gsmBci[i].toCodeScheme = (int) t;
status = p.readInt32(&t);
gsmBci[i].selected = (uint8_t) t;
appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId =%d, \
fromCodeScheme=%d, toCodeScheme=%d, selected =%d]", printBuf, i,
gsmBci[i].fromServiceId, gsmBci[i].toServiceId,
gsmBci[i].fromCodeScheme, gsmBci[i].toCodeScheme,
gsmBci[i].selected);
}
closeRequest;
if (status != NO_ERROR) {
goto invalid;
}
s_callbacks.onRequest(pRI->pCI->requestNumber,
gsmBciPtrs,
num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *),
pRI);
#ifdef MEMSET_FREED
memset(gsmBci, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo));
memset(gsmBciPtrs, 0, num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *));
#endif
}
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void
dispatchCdmaBrSmsCnf(Parcel &p, RequestInfo *pRI) {
int32_t t;
status_t status;
int32_t num;
status = p.readInt32(&num);
if (status != NO_ERROR) {
goto invalid;
}
{
RIL_CDMA_BroadcastSmsConfigInfo cdmaBci[num];
RIL_CDMA_BroadcastSmsConfigInfo *cdmaBciPtrs[num];
startRequest;
for (int i = 0 ; i < num ; i++ ) {
cdmaBciPtrs[i] = &cdmaBci[i];
status = p.readInt32(&t);
cdmaBci[i].service_category = (int) t;
status = p.readInt32(&t);
cdmaBci[i].language = (int) t;
status = p.readInt32(&t);
cdmaBci[i].selected = (uint8_t) t;
appendPrintBuf("%s [%d: service_category=%d, language =%d, \
entries.bSelected =%d]", printBuf, i, cdmaBci[i].service_category,
cdmaBci[i].language, cdmaBci[i].selected);
}
closeRequest;
if (status != NO_ERROR) {
goto invalid;
}
s_callbacks.onRequest(pRI->pCI->requestNumber,
cdmaBciPtrs,
num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *),
pRI);
#ifdef MEMSET_FREED
memset(cdmaBci, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo));
memset(cdmaBciPtrs, 0, num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *));
#endif
}
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static void dispatchRilCdmaSmsWriteArgs(Parcel &p, RequestInfo *pRI) {
RIL_CDMA_SMS_WriteArgs rcsw;
int32_t t;
uint32_t ut;
uint8_t uct;
status_t status;
int32_t digitCount;
memset(&rcsw, 0, sizeof(rcsw));
status = p.readInt32(&t);
rcsw.status = t;
status = p.readInt32(&t);
rcsw.message.uTeleserviceID = (int) t;
status = p.read(&uct,sizeof(uct));
rcsw.message.bIsServicePresent = (uint8_t) uct;
status = p.readInt32(&t);
rcsw.message.uServicecategory = (int) t;
status = p.readInt32(&t);
rcsw.message.sAddress.digit_mode = (RIL_CDMA_SMS_DigitMode) t;
status = p.readInt32(&t);
rcsw.message.sAddress.number_mode = (RIL_CDMA_SMS_NumberMode) t;
status = p.readInt32(&t);
rcsw.message.sAddress.number_type = (RIL_CDMA_SMS_NumberType) t;
status = p.readInt32(&t);
rcsw.message.sAddress.number_plan = (RIL_CDMA_SMS_NumberPlan) t;
status = p.read(&uct,sizeof(uct));
rcsw.message.sAddress.number_of_digits = (uint8_t) uct;
for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_ADDRESS_MAX; digitCount ++) {
status = p.read(&uct,sizeof(uct));
rcsw.message.sAddress.digits[digitCount] = (uint8_t) uct;
}
status = p.readInt32(&t);
rcsw.message.sSubAddress.subaddressType = (RIL_CDMA_SMS_SubaddressType) t;
status = p.read(&uct,sizeof(uct));
rcsw.message.sSubAddress.odd = (uint8_t) uct;
status = p.read(&uct,sizeof(uct));
rcsw.message.sSubAddress.number_of_digits = (uint8_t) uct;
for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_SUBADDRESS_MAX; digitCount ++) {
status = p.read(&uct,sizeof(uct));
rcsw.message.sSubAddress.digits[digitCount] = (uint8_t) uct;
}
status = p.readInt32(&t);
rcsw.message.uBearerDataLen = (int) t;
for(digitCount = 0 ; digitCount < RIL_CDMA_SMS_BEARER_DATA_MAX; digitCount ++) {
status = p.read(&uct, sizeof(uct));
rcsw.message.aBearerData[digitCount] = (uint8_t) uct;
}
if (status != NO_ERROR) {
goto invalid;
}
startRequest;
appendPrintBuf("%sstatus=%d, message.uTeleserviceID=%d, message.bIsServicePresent=%d, \
message.uServicecategory=%d, message.sAddress.digit_mode=%d, \
message.sAddress.number_mode=%d, \
message.sAddress.number_type=%d, ",
printBuf, rcsw.status, rcsw.message.uTeleserviceID, rcsw.message.bIsServicePresent,
rcsw.message.uServicecategory, rcsw.message.sAddress.digit_mode,
rcsw.message.sAddress.number_mode,
rcsw.message.sAddress.number_type);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
s_callbacks.onRequest(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw),pRI);
#ifdef MEMSET_FREED
memset(&rcsw, 0, sizeof(rcsw));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
// For backwards compatibility in RIL_REQUEST_SETUP_DATA_CALL.
// Version 4 of the RIL interface adds a new PDP type parameter to support
// IPv6 and dual-stack PDP contexts. When dealing with a previous version of
// RIL, remove the parameter from the request.
static void dispatchDataCall(Parcel& p, RequestInfo *pRI) {
// In RIL v3, REQUEST_SETUP_DATA_CALL takes 6 parameters.
const int numParamsRilV3 = 6;
// The first bytes of the RIL parcel contain the request number and the
// serial number - see processCommandBuffer(). Copy them over too.
int pos = p.dataPosition();
int numParams = p.readInt32();
if (s_callbacks.version < 4 && numParams > numParamsRilV3) {
Parcel p2;
p2.appendFrom(&p, 0, pos);
p2.writeInt32(numParamsRilV3);
for(int i = 0; i < numParamsRilV3; i++) {
p2.writeString16(p.readString16());
}
p2.setDataPosition(pos);
dispatchStrings(p2, pRI);
} else {
p.setDataPosition(pos);
dispatchStrings(p, pRI);
}
}
// For backwards compatibility with RILs that dont support RIL_REQUEST_VOICE_RADIO_TECH.
// When all RILs handle this request, this function can be removed and
// the request can be sent directly to the RIL using dispatchVoid.
static void dispatchVoiceRadioTech(Parcel& p, RequestInfo *pRI) {
RIL_RadioState state = s_callbacks.onStateRequest();
if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
}
// RILs that support RADIO_STATE_ON should support this request.
if (RADIO_STATE_ON == state) {
dispatchVoid(p, pRI);
return;
}
// For Older RILs, that do not support RADIO_STATE_ON, assume that they
// will not support this new request either and decode Voice Radio Technology
// from Radio State
voiceRadioTech = decodeVoiceRadioTechnology(state);
if (voiceRadioTech < 0)
RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
else
RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &voiceRadioTech, sizeof(int));
}
// For backwards compatibility in RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE:.
// When all RILs handle this request, this function can be removed and
// the request can be sent directly to the RIL using dispatchVoid.
static void dispatchCdmaSubscriptionSource(Parcel& p, RequestInfo *pRI) {
RIL_RadioState state = s_callbacks.onStateRequest();
if ((RADIO_STATE_UNAVAILABLE == state) || (RADIO_STATE_OFF == state)) {
RIL_onRequestComplete(pRI, RIL_E_RADIO_NOT_AVAILABLE, NULL, 0);
}
// RILs that support RADIO_STATE_ON should support this request.
if (RADIO_STATE_ON == state) {
dispatchVoid(p, pRI);
return;
}
// For Older RILs, that do not support RADIO_STATE_ON, assume that they
// will not support this new request either and decode CDMA Subscription Source
// from Radio State
cdmaSubscriptionSource = decodeCdmaSubscriptionSource(state);
if (cdmaSubscriptionSource < 0)
RIL_onRequestComplete(pRI, RIL_E_GENERIC_FAILURE, NULL, 0);
else
RIL_onRequestComplete(pRI, RIL_E_SUCCESS, &cdmaSubscriptionSource, sizeof(int));
}
static void dispatchSetInitialAttachApn(Parcel &p, RequestInfo *pRI)
{
RIL_InitialAttachApn pf;
int32_t t;
status_t status;
memset(&pf, 0, sizeof(pf));
pf.apn = strdupReadString(p);
pf.protocol = strdupReadString(p);
status = p.readInt32(&t);
pf.authtype = (int) t;
pf.username = strdupReadString(p);
pf.password = strdupReadString(p);
startRequest;
appendPrintBuf("%sapn=%s, protocol=%s, auth_type=%d, username=%s, password=%s",
printBuf, pf.apn, pf.protocol, pf.auth_type, pf.username, pf.password);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
if (status != NO_ERROR) {
goto invalid;
}
s_callbacks.onRequest(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI);
#ifdef MEMSET_FREED
memsetString(pf.apn);
memsetString(pf.protocol);
memsetString(pf.username);
memsetString(pf.password);
#endif
free(pf.apn);
free(pf.protocol);
free(pf.username);
free(pf.password);
#ifdef MEMSET_FREED
memset(&pf, 0, sizeof(pf));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
static int
blockingWrite(int fd, const void *buffer, size_t len) {
size_t writeOffset = 0;
const uint8_t *toWrite;
toWrite = (const uint8_t *)buffer;
while (writeOffset < len) {
ssize_t written;
do {
written = write (fd, toWrite + writeOffset,
len - writeOffset);
} while (written < 0 && ((errno == EINTR) || (errno == EAGAIN)));
if (written >= 0) {
writeOffset += written;
} else { // written < 0
RLOGE ("RIL Response: unexpected error on write errno:%d", errno);
close(fd);
return -1;
}
}
return 0;
}
static int
sendResponseRaw (const void *data, size_t dataSize) {
int fd = s_fdCommand;
int ret;
uint32_t header;
if (s_fdCommand < 0) {
return -1;
}
if (dataSize > MAX_COMMAND_BYTES) {
RLOGE("RIL: packet larger than %u (%u)",
MAX_COMMAND_BYTES, (unsigned int )dataSize);
return -1;
}
pthread_mutex_lock(&s_writeMutex);
header = htonl(dataSize);
ret = blockingWrite(fd, (void *)&header, sizeof(header));
if (ret < 0) {
pthread_mutex_unlock(&s_writeMutex);
return ret;
}
ret = blockingWrite(fd, data, dataSize);
if (ret < 0) {
pthread_mutex_unlock(&s_writeMutex);
return ret;
}
pthread_mutex_unlock(&s_writeMutex);
return 0;
}
static int
sendResponse (Parcel &p) {
printResponse;
return sendResponseRaw(p.data(), p.dataSize());
}
/** response is an int* pointing to an array of ints*/
static int
responseInts(Parcel &p, void *response, size_t responselen) {
int numInts;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(int) != 0) {
RLOGE("invalid response length %d expected multiple of %d\n",
(int)responselen, (int)sizeof(int));
return RIL_ERRNO_INVALID_RESPONSE;
}
int *p_int = (int *) response;
numInts = responselen / sizeof(int *);
p.writeInt32 (numInts);
/* each int*/
startResponse;
for (int i = 0 ; i < numInts ; i++) {
appendPrintBuf("%s%d,", printBuf, p_int[i]);
p.writeInt32(p_int[i]);
}
removeLastChar;
closeResponse;
return 0;
}
/** response is a char **, pointing to an array of char *'s
The parcel will begin with the version */
static int responseStringsWithVersion(int version, Parcel &p, void *response, size_t responselen) {
p.writeInt32(version);
return responseStrings(p, response, responselen);
}
/** response is a char **, pointing to an array of char *'s */
static int responseStrings(Parcel &p, void *response, size_t responselen) {
int numStrings;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(char *) != 0) {
RLOGE("invalid response length %d expected multiple of %d\n",
(int)responselen, (int)sizeof(char *));
return RIL_ERRNO_INVALID_RESPONSE;
}
if (response == NULL) {
p.writeInt32 (0);
} else {
char **p_cur = (char **) response;
numStrings = responselen / sizeof(char *);
p.writeInt32 (numStrings);
/* each string*/
startResponse;
for (int i = 0 ; i < numStrings ; i++) {
appendPrintBuf("%s%s,", printBuf, (char*)p_cur[i]);
writeStringToParcel (p, p_cur[i]);
}
removeLastChar;
closeResponse;
}
return 0;
}
/**
* NULL strings are accepted
* FIXME currently ignores responselen
*/
static int responseString(Parcel &p, void *response, size_t responselen) {
/* one string only */
startResponse;
appendPrintBuf("%s%s", printBuf, (char*)response);
closeResponse;
writeStringToParcel(p, (const char *)response);
return 0;
}
static int responseVoid(Parcel &p, void *response, size_t responselen) {
startResponse;
removeLastChar;
return 0;
}
static int responseCallList(Parcel &p, void *response, size_t responselen) {
int num;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof (RIL_Call *) != 0) {
RLOGE("invalid response length %d expected multiple of %d\n",
(int)responselen, (int)sizeof (RIL_Call *));
return RIL_ERRNO_INVALID_RESPONSE;
}
startResponse;
/* number of call info's */
num = responselen / sizeof(RIL_Call *);
p.writeInt32(num);
for (int i = 0 ; i < num ; i++) {
RIL_Call *p_cur = ((RIL_Call **) response)[i];
/* each call info */
p.writeInt32(p_cur->state);
p.writeInt32(p_cur->index);
p.writeInt32(p_cur->toa);
p.writeInt32(p_cur->isMpty);
p.writeInt32(p_cur->isMT);
p.writeInt32(p_cur->als);
p.writeInt32(p_cur->isVoice);
p.writeInt32(p_cur->isVoicePrivacy);
writeStringToParcel(p, p_cur->number);
p.writeInt32(p_cur->numberPresentation);
writeStringToParcel(p, p_cur->name);
p.writeInt32(p_cur->namePresentation);
// Remove when partners upgrade to version 3
if ((s_callbacks.version < 3) || (p_cur->uusInfo == NULL || p_cur->uusInfo->uusData == NULL)) {
p.writeInt32(0); /* UUS Information is absent */
} else {
RIL_UUS_Info *uusInfo = p_cur->uusInfo;
p.writeInt32(1); /* UUS Information is present */
p.writeInt32(uusInfo->uusType);
p.writeInt32(uusInfo->uusDcs);
p.writeInt32(uusInfo->uusLength);
p.write(uusInfo->uusData, uusInfo->uusLength);
}
appendPrintBuf("%s[id=%d,%s,toa=%d,",
printBuf,
p_cur->index,
callStateToString(p_cur->state),
p_cur->toa);
appendPrintBuf("%s%s,%s,als=%d,%s,%s,",
printBuf,
(p_cur->isMpty)?"conf":"norm",
(p_cur->isMT)?"mt":"mo",
p_cur->als,
(p_cur->isVoice)?"voc":"nonvoc",
(p_cur->isVoicePrivacy)?"evp":"noevp");
appendPrintBuf("%s%s,cli=%d,name='%s',%d]",
printBuf,
p_cur->number,
p_cur->numberPresentation,
p_cur->name,
p_cur->namePresentation);
}
removeLastChar;
closeResponse;
return 0;
}
static int responseSMS(Parcel &p, void *response, size_t responselen) {
if (response == NULL) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof (RIL_SMS_Response) ) {
RLOGE("invalid response length %d expected %d",
(int)responselen, (int)sizeof (RIL_SMS_Response));
return RIL_ERRNO_INVALID_RESPONSE;
}
RIL_SMS_Response *p_cur = (RIL_SMS_Response *) response;
p.writeInt32(p_cur->messageRef);
writeStringToParcel(p, p_cur->ackPDU);
p.writeInt32(p_cur->errorCode);
startResponse;
appendPrintBuf("%s%d,%s,%d", printBuf, p_cur->messageRef,
(char*)p_cur->ackPDU, p_cur->errorCode);
closeResponse;
return 0;
}
static int responseDataCallListV4(Parcel &p, void *response, size_t responselen)
{
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(RIL_Data_Call_Response_v4) != 0) {
RLOGE("invalid response length %d expected multiple of %d",
(int)responselen, (int)sizeof(RIL_Data_Call_Response_v4));
return RIL_ERRNO_INVALID_RESPONSE;
}
int num = responselen / sizeof(RIL_Data_Call_Response_v4);
p.writeInt32(num);
RIL_Data_Call_Response_v4 *p_cur = (RIL_Data_Call_Response_v4 *) response;
startResponse;
int i;
for (i = 0; i < num; i++) {
p.writeInt32(p_cur[i].cid);
p.writeInt32(p_cur[i].active);
writeStringToParcel(p, p_cur[i].type);
// apn is not used, so don't send.
writeStringToParcel(p, p_cur[i].address);
appendPrintBuf("%s[cid=%d,%s,%s,%s],", printBuf,
p_cur[i].cid,
(p_cur[i].active==0)?"down":"up",
(char*)p_cur[i].type,
(char*)p_cur[i].address);
}
removeLastChar;
closeResponse;
return 0;
}
static int responseDataCallList(Parcel &p, void *response, size_t responselen)
{
// Write version
p.writeInt32(s_callbacks.version);
if (s_callbacks.version < 5) {
return responseDataCallListV4(p, response, responselen);
} else {
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(RIL_Data_Call_Response_v6) != 0) {
RLOGE("invalid response length %d expected multiple of %d",
(int)responselen, (int)sizeof(RIL_Data_Call_Response_v6));
return RIL_ERRNO_INVALID_RESPONSE;
}
int num = responselen / sizeof(RIL_Data_Call_Response_v6);
p.writeInt32(num);
RIL_Data_Call_Response_v6 *p_cur = (RIL_Data_Call_Response_v6 *) response;
startResponse;
int i;
for (i = 0; i < num; i++) {
p.writeInt32((int)p_cur[i].status);
p.writeInt32(p_cur[i].suggestedRetryTime);
p.writeInt32(p_cur[i].cid);
p.writeInt32(p_cur[i].active);
writeStringToParcel(p, p_cur[i].type);
writeStringToParcel(p, p_cur[i].ifname);
writeStringToParcel(p, p_cur[i].addresses);
writeStringToParcel(p, p_cur[i].dnses);
writeStringToParcel(p, p_cur[i].gateways);
appendPrintBuf("%s[status=%d,retry=%d,cid=%d,%s,%s,%s,%s,%s,%s],", printBuf,
p_cur[i].status,
p_cur[i].suggestedRetryTime,
p_cur[i].cid,
(p_cur[i].active==0)?"down":"up",
(char*)p_cur[i].type,
(char*)p_cur[i].ifname,
(char*)p_cur[i].addresses,
(char*)p_cur[i].dnses,
(char*)p_cur[i].gateways);
}
removeLastChar;
closeResponse;
}
return 0;
}
static int responseSetupDataCall(Parcel &p, void *response, size_t responselen)
{
if (s_callbacks.version < 5) {
return responseStringsWithVersion(s_callbacks.version, p, response, responselen);
} else {
return responseDataCallList(p, response, responselen);
}
}
static int responseRaw(Parcel &p, void *response, size_t responselen) {
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL with responselen != 0");
return RIL_ERRNO_INVALID_RESPONSE;
}
// The java code reads -1 size as null byte array
if (response == NULL) {
p.writeInt32(-1);
} else {
p.writeInt32(responselen);
p.write(response, responselen);
}
return 0;
}
static int responseSIM_IO(Parcel &p, void *response, size_t responselen) {
if (response == NULL) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof (RIL_SIM_IO_Response) ) {
RLOGE("invalid response length was %d expected %d",
(int)responselen, (int)sizeof (RIL_SIM_IO_Response));
return RIL_ERRNO_INVALID_RESPONSE;
}
RIL_SIM_IO_Response *p_cur = (RIL_SIM_IO_Response *) response;
p.writeInt32(p_cur->sw1);
p.writeInt32(p_cur->sw2);
writeStringToParcel(p, p_cur->simResponse);
startResponse;
appendPrintBuf("%ssw1=0x%X,sw2=0x%X,%s", printBuf, p_cur->sw1, p_cur->sw2,
(char*)p_cur->simResponse);
closeResponse;
return 0;
}
static int responseCallForwards(Parcel &p, void *response, size_t responselen) {
int num;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(RIL_CallForwardInfo *) != 0) {
RLOGE("invalid response length %d expected multiple of %d",
(int)responselen, (int)sizeof(RIL_CallForwardInfo *));
return RIL_ERRNO_INVALID_RESPONSE;
}
/* number of call info's */
num = responselen / sizeof(RIL_CallForwardInfo *);
p.writeInt32(num);
startResponse;
for (int i = 0 ; i < num ; i++) {
RIL_CallForwardInfo *p_cur = ((RIL_CallForwardInfo **) response)[i];
p.writeInt32(p_cur->status);
p.writeInt32(p_cur->reason);
p.writeInt32(p_cur->serviceClass);
p.writeInt32(p_cur->toa);
writeStringToParcel(p, p_cur->number);
p.writeInt32(p_cur->timeSeconds);
appendPrintBuf("%s[%s,reason=%d,cls=%d,toa=%d,%s,tout=%d],", printBuf,
(p_cur->status==1)?"enable":"disable",
p_cur->reason, p_cur->serviceClass, p_cur->toa,
(char*)p_cur->number,
p_cur->timeSeconds);
}
removeLastChar;
closeResponse;
return 0;
}
static int responseSsn(Parcel &p, void *response, size_t responselen) {
if (response == NULL) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof(RIL_SuppSvcNotification)) {
RLOGE("invalid response length was %d expected %d",
(int)responselen, (int)sizeof (RIL_SuppSvcNotification));
return RIL_ERRNO_INVALID_RESPONSE;
}
RIL_SuppSvcNotification *p_cur = (RIL_SuppSvcNotification *) response;
p.writeInt32(p_cur->notificationType);
p.writeInt32(p_cur->code);
p.writeInt32(p_cur->index);
p.writeInt32(p_cur->type);
writeStringToParcel(p, p_cur->number);
startResponse;
appendPrintBuf("%s%s,code=%d,id=%d,type=%d,%s", printBuf,
(p_cur->notificationType==0)?"mo":"mt",
p_cur->code, p_cur->index, p_cur->type,
(char*)p_cur->number);
closeResponse;
return 0;
}
static int responseCellList(Parcel &p, void *response, size_t responselen) {
int num;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof (RIL_NeighboringCell *) != 0) {
RLOGE("invalid response length %d expected multiple of %d\n",
(int)responselen, (int)sizeof (RIL_NeighboringCell *));
return RIL_ERRNO_INVALID_RESPONSE;
}
startResponse;
/* number of records */
num = responselen / sizeof(RIL_NeighboringCell *);
p.writeInt32(num);
for (int i = 0 ; i < num ; i++) {
RIL_NeighboringCell *p_cur = ((RIL_NeighboringCell **) response)[i];
p.writeInt32(p_cur->rssi);
writeStringToParcel (p, p_cur->cid);
appendPrintBuf("%s[cid=%s,rssi=%d],", printBuf,
p_cur->cid, p_cur->rssi);
}
removeLastChar;
closeResponse;
return 0;
}
/**
* Marshall the signalInfoRecord into the parcel if it exists.
*/
static void marshallSignalInfoRecord(Parcel &p,
RIL_CDMA_SignalInfoRecord &p_signalInfoRecord) {
p.writeInt32(p_signalInfoRecord.isPresent);
p.writeInt32(p_signalInfoRecord.signalType);
p.writeInt32(p_signalInfoRecord.alertPitch);
p.writeInt32(p_signalInfoRecord.signal);
}
static int responseCdmaInformationRecords(Parcel &p,
void *response, size_t responselen) {
int num;
char* string8 = NULL;
int buffer_lenght;
RIL_CDMA_InformationRecord *infoRec;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof (RIL_CDMA_InformationRecords)) {
RLOGE("invalid response length %d expected multiple of %d\n",
(int)responselen, (int)sizeof (RIL_CDMA_InformationRecords *));
return RIL_ERRNO_INVALID_RESPONSE;
}
RIL_CDMA_InformationRecords *p_cur =
(RIL_CDMA_InformationRecords *) response;
num = MIN(p_cur->numberOfInfoRecs, RIL_CDMA_MAX_NUMBER_OF_INFO_RECS);
startResponse;
p.writeInt32(num);
for (int i = 0 ; i < num ; i++) {
infoRec = &p_cur->infoRec[i];
p.writeInt32(infoRec->name);
switch (infoRec->name) {
case RIL_CDMA_DISPLAY_INFO_REC:
case RIL_CDMA_EXTENDED_DISPLAY_INFO_REC:
if (infoRec->rec.display.alpha_len >
CDMA_ALPHA_INFO_BUFFER_LENGTH) {
RLOGE("invalid display info response length %d \
expected not more than %d\n",
(int)infoRec->rec.display.alpha_len,
CDMA_ALPHA_INFO_BUFFER_LENGTH);
return RIL_ERRNO_INVALID_RESPONSE;
}
string8 = (char*) malloc((infoRec->rec.display.alpha_len + 1)
* sizeof(char) );
for (int i = 0 ; i < infoRec->rec.display.alpha_len ; i++) {
string8[i] = infoRec->rec.display.alpha_buf[i];
}
string8[(int)infoRec->rec.display.alpha_len] = '\0';
writeStringToParcel(p, (const char*)string8);
free(string8);
string8 = NULL;
break;
case RIL_CDMA_CALLED_PARTY_NUMBER_INFO_REC:
case RIL_CDMA_CALLING_PARTY_NUMBER_INFO_REC:
case RIL_CDMA_CONNECTED_NUMBER_INFO_REC:
if (infoRec->rec.number.len > CDMA_NUMBER_INFO_BUFFER_LENGTH) {
RLOGE("invalid display info response length %d \
expected not more than %d\n",
(int)infoRec->rec.number.len,
CDMA_NUMBER_INFO_BUFFER_LENGTH);
return RIL_ERRNO_INVALID_RESPONSE;
}
string8 = (char*) malloc((infoRec->rec.number.len + 1)
* sizeof(char) );
for (int i = 0 ; i < infoRec->rec.number.len; i++) {
string8[i] = infoRec->rec.number.buf[i];
}
string8[(int)infoRec->rec.number.len] = '\0';
writeStringToParcel(p, (const char*)string8);
free(string8);
string8 = NULL;
p.writeInt32(infoRec->rec.number.number_type);
p.writeInt32(infoRec->rec.number.number_plan);
p.writeInt32(infoRec->rec.number.pi);
p.writeInt32(infoRec->rec.number.si);
break;
case RIL_CDMA_SIGNAL_INFO_REC:
p.writeInt32(infoRec->rec.signal.isPresent);
p.writeInt32(infoRec->rec.signal.signalType);
p.writeInt32(infoRec->rec.signal.alertPitch);
p.writeInt32(infoRec->rec.signal.signal);
appendPrintBuf("%sisPresent=%X, signalType=%X, \
alertPitch=%X, signal=%X, ",
printBuf, (int)infoRec->rec.signal.isPresent,
(int)infoRec->rec.signal.signalType,
(int)infoRec->rec.signal.alertPitch,
(int)infoRec->rec.signal.signal);
removeLastChar;
break;
case RIL_CDMA_REDIRECTING_NUMBER_INFO_REC:
if (infoRec->rec.redir.redirectingNumber.len >
CDMA_NUMBER_INFO_BUFFER_LENGTH) {
RLOGE("invalid display info response length %d \
expected not more than %d\n",
(int)infoRec->rec.redir.redirectingNumber.len,
CDMA_NUMBER_INFO_BUFFER_LENGTH);
return RIL_ERRNO_INVALID_RESPONSE;
}
string8 = (char*) malloc((infoRec->rec.redir.redirectingNumber
.len + 1) * sizeof(char) );
for (int i = 0;
i < infoRec->rec.redir.redirectingNumber.len;
i++) {
string8[i] = infoRec->rec.redir.redirectingNumber.buf[i];
}
string8[(int)infoRec->rec.redir.redirectingNumber.len] = '\0';
writeStringToParcel(p, (const char*)string8);
free(string8);
string8 = NULL;
p.writeInt32(infoRec->rec.redir.redirectingNumber.number_type);
p.writeInt32(infoRec->rec.redir.redirectingNumber.number_plan);
p.writeInt32(infoRec->rec.redir.redirectingNumber.pi);
p.writeInt32(infoRec->rec.redir.redirectingNumber.si);
p.writeInt32(infoRec->rec.redir.redirectingReason);
break;
case RIL_CDMA_LINE_CONTROL_INFO_REC:
p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPolarityIncluded);
p.writeInt32(infoRec->rec.lineCtrl.lineCtrlToggle);
p.writeInt32(infoRec->rec.lineCtrl.lineCtrlReverse);
p.writeInt32(infoRec->rec.lineCtrl.lineCtrlPowerDenial);
appendPrintBuf("%slineCtrlPolarityIncluded=%d, \
lineCtrlToggle=%d, lineCtrlReverse=%d, \
lineCtrlPowerDenial=%d, ", printBuf,
(int)infoRec->rec.lineCtrl.lineCtrlPolarityIncluded,
(int)infoRec->rec.lineCtrl.lineCtrlToggle,
(int)infoRec->rec.lineCtrl.lineCtrlReverse,
(int)infoRec->rec.lineCtrl.lineCtrlPowerDenial);
removeLastChar;
break;
case RIL_CDMA_T53_CLIR_INFO_REC:
p.writeInt32((int)(infoRec->rec.clir.cause));
appendPrintBuf("%scause%d", printBuf, infoRec->rec.clir.cause);
removeLastChar;
break;
case RIL_CDMA_T53_AUDIO_CONTROL_INFO_REC:
p.writeInt32(infoRec->rec.audioCtrl.upLink);
p.writeInt32(infoRec->rec.audioCtrl.downLink);
appendPrintBuf("%supLink=%d, downLink=%d, ", printBuf,
infoRec->rec.audioCtrl.upLink,
infoRec->rec.audioCtrl.downLink);
removeLastChar;
break;
case RIL_CDMA_T53_RELEASE_INFO_REC:
// TODO(Moto): See David Krause, he has the answer:)
RLOGE("RIL_CDMA_T53_RELEASE_INFO_REC: return INVALID_RESPONSE");
return RIL_ERRNO_INVALID_RESPONSE;
default:
RLOGE("Incorrect name value");
return RIL_ERRNO_INVALID_RESPONSE;
}
}
closeResponse;
return 0;
}
static int responseRilSignalStrength(Parcel &p,
void *response, size_t responselen) {
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen >= sizeof (RIL_SignalStrength_v5)) {
RIL_SignalStrength_v6 *p_cur = ((RIL_SignalStrength_v6 *) response);
p.writeInt32(p_cur->GW_SignalStrength.signalStrength);
p.writeInt32(p_cur->GW_SignalStrength.bitErrorRate);
p.writeInt32(p_cur->CDMA_SignalStrength.dbm);
p.writeInt32(p_cur->CDMA_SignalStrength.ecio);
p.writeInt32(p_cur->EVDO_SignalStrength.dbm);
p.writeInt32(p_cur->EVDO_SignalStrength.ecio);
p.writeInt32(p_cur->EVDO_SignalStrength.signalNoiseRatio);
if (responselen >= sizeof (RIL_SignalStrength_v6)) {
/*
* Fixup LTE for backwards compatibility
*/
if (s_callbacks.version <= 6) {
// signalStrength: -1 -> 99
if (p_cur->LTE_SignalStrength.signalStrength == -1) {
p_cur->LTE_SignalStrength.signalStrength = 99;
}
// rsrp: -1 -> INT_MAX all other negative value to positive.
// So remap here
if (p_cur->LTE_SignalStrength.rsrp == -1) {
p_cur->LTE_SignalStrength.rsrp = INT_MAX;
} else if (p_cur->LTE_SignalStrength.rsrp < -1) {
p_cur->LTE_SignalStrength.rsrp = -p_cur->LTE_SignalStrength.rsrp;
}
// rsrq: -1 -> INT_MAX
if (p_cur->LTE_SignalStrength.rsrq == -1) {
p_cur->LTE_SignalStrength.rsrq = INT_MAX;
}
// Not remapping rssnr is already using INT_MAX
// cqi: -1 -> INT_MAX
if (p_cur->LTE_SignalStrength.cqi == -1) {
p_cur->LTE_SignalStrength.cqi = INT_MAX;
}
}
p.writeInt32(p_cur->LTE_SignalStrength.signalStrength);
p.writeInt32(p_cur->LTE_SignalStrength.rsrp);
p.writeInt32(p_cur->LTE_SignalStrength.rsrq);
p.writeInt32(p_cur->LTE_SignalStrength.rssnr);
p.writeInt32(p_cur->LTE_SignalStrength.cqi);
} else {
p.writeInt32(99);
p.writeInt32(INT_MAX);
p.writeInt32(INT_MAX);
p.writeInt32(INT_MAX);
p.writeInt32(INT_MAX);
}
startResponse;
appendPrintBuf("%s[signalStrength=%d,bitErrorRate=%d,\
CDMA_SS.dbm=%d,CDMA_SSecio=%d,\
EVDO_SS.dbm=%d,EVDO_SS.ecio=%d,\
EVDO_SS.signalNoiseRatio=%d,\
LTE_SS.signalStrength=%d,LTE_SS.rsrp=%d,LTE_SS.rsrq=%d,\
LTE_SS.rssnr=%d,LTE_SS.cqi=%d]",
printBuf,
p_cur->GW_SignalStrength.signalStrength,
p_cur->GW_SignalStrength.bitErrorRate,
p_cur->CDMA_SignalStrength.dbm,
p_cur->CDMA_SignalStrength.ecio,
p_cur->EVDO_SignalStrength.dbm,
p_cur->EVDO_SignalStrength.ecio,
p_cur->EVDO_SignalStrength.signalNoiseRatio,
p_cur->LTE_SignalStrength.signalStrength,
p_cur->LTE_SignalStrength.rsrp,
p_cur->LTE_SignalStrength.rsrq,
p_cur->LTE_SignalStrength.rssnr,
p_cur->LTE_SignalStrength.cqi);
closeResponse;
} else {
RLOGE("invalid response length");
return RIL_ERRNO_INVALID_RESPONSE;
}
return 0;
}
static int responseCallRing(Parcel &p, void *response, size_t responselen) {
if ((response == NULL) || (responselen == 0)) {
return responseVoid(p, response, responselen);
} else {
return responseCdmaSignalInfoRecord(p, response, responselen);
}
}
static int responseCdmaSignalInfoRecord(Parcel &p, void *response, size_t responselen) {
if (response == NULL || responselen == 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof (RIL_CDMA_SignalInfoRecord)) {
RLOGE("invalid response length %d expected sizeof (RIL_CDMA_SignalInfoRecord) of %d\n",
(int)responselen, (int)sizeof (RIL_CDMA_SignalInfoRecord));
return RIL_ERRNO_INVALID_RESPONSE;
}
startResponse;
RIL_CDMA_SignalInfoRecord *p_cur = ((RIL_CDMA_SignalInfoRecord *) response);
marshallSignalInfoRecord(p, *p_cur);
appendPrintBuf("%s[isPresent=%d,signalType=%d,alertPitch=%d\
signal=%d]",
printBuf,
p_cur->isPresent,
p_cur->signalType,
p_cur->alertPitch,
p_cur->signal);
closeResponse;
return 0;
}
static int responseCdmaCallWaiting(Parcel &p, void *response,
size_t responselen) {
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen < sizeof(RIL_CDMA_CallWaiting_v6)) {
RLOGW("Upgrade to ril version %d\n", RIL_VERSION);
}
RIL_CDMA_CallWaiting_v6 *p_cur = ((RIL_CDMA_CallWaiting_v6 *) response);
writeStringToParcel(p, p_cur->number);
p.writeInt32(p_cur->numberPresentation);
writeStringToParcel(p, p_cur->name);
marshallSignalInfoRecord(p, p_cur->signalInfoRecord);
if (responselen >= sizeof(RIL_CDMA_CallWaiting_v6)) {
p.writeInt32(p_cur->number_type);
p.writeInt32(p_cur->number_plan);
} else {
p.writeInt32(0);
p.writeInt32(0);
}
startResponse;
appendPrintBuf("%snumber=%s,numberPresentation=%d, name=%s,\
signalInfoRecord[isPresent=%d,signalType=%d,alertPitch=%d\
signal=%d,number_type=%d,number_plan=%d]",
printBuf,
p_cur->number,
p_cur->numberPresentation,
p_cur->name,
p_cur->signalInfoRecord.isPresent,
p_cur->signalInfoRecord.signalType,
p_cur->signalInfoRecord.alertPitch,
p_cur->signalInfoRecord.signal,
p_cur->number_type,
p_cur->number_plan);
closeResponse;
return 0;
}
static int responseSimRefresh(Parcel &p, void *response, size_t responselen) {
if (response == NULL && responselen != 0) {
RLOGE("responseSimRefresh: invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
startResponse;
if (s_callbacks.version == 7) {
RIL_SimRefreshResponse_v7 *p_cur = ((RIL_SimRefreshResponse_v7 *) response);
p.writeInt32(p_cur->result);
p.writeInt32(p_cur->ef_id);
writeStringToParcel(p, p_cur->aid);
appendPrintBuf("%sresult=%d, ef_id=%d, aid=%s",
printBuf,
p_cur->result,
p_cur->ef_id,
p_cur->aid);
} else {
int *p_cur = ((int *) response);
p.writeInt32(p_cur[0]);
p.writeInt32(p_cur[1]);
writeStringToParcel(p, NULL);
appendPrintBuf("%sresult=%d, ef_id=%d",
printBuf,
p_cur[0],
p_cur[1]);
}
closeResponse;
return 0;
}
static int responseCellInfoList(Parcel &p, void *response, size_t responselen)
{
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen % sizeof(RIL_CellInfo) != 0) {
RLOGE("invalid response length %d expected multiple of %d",
(int)responselen, (int)sizeof(RIL_CellInfo));
return RIL_ERRNO_INVALID_RESPONSE;
}
int num = responselen / sizeof(RIL_CellInfo);
p.writeInt32(num);
RIL_CellInfo *p_cur = (RIL_CellInfo *) response;
startResponse;
int i;
for (i = 0; i < num; i++) {
appendPrintBuf("%s[%d: type=%d,registered=%d,timeStampType=%d,timeStamp=%lld", printBuf, i,
p_cur->cellInfoType, p_cur->registered, p_cur->timeStampType, p_cur->timeStamp);
p.writeInt32((int)p_cur->cellInfoType);
p.writeInt32(p_cur->registered);
p.writeInt32(p_cur->timeStampType);
p.writeInt64(p_cur->timeStamp);
switch(p_cur->cellInfoType) {
case RIL_CELL_INFO_TYPE_GSM: {
appendPrintBuf("%s GSM id: mcc=%d,mnc=%d,lac=%d,cid=%d,", printBuf,
p_cur->CellInfo.gsm.cellIdentityGsm.mcc,
p_cur->CellInfo.gsm.cellIdentityGsm.mnc,
p_cur->CellInfo.gsm.cellIdentityGsm.lac,
p_cur->CellInfo.gsm.cellIdentityGsm.cid);
appendPrintBuf("%s gsmSS: ss=%d,ber=%d],", printBuf,
p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength,
p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mcc);
p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.mnc);
p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.lac);
p.writeInt32(p_cur->CellInfo.gsm.cellIdentityGsm.cid);
p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.signalStrength);
p.writeInt32(p_cur->CellInfo.gsm.signalStrengthGsm.bitErrorRate);
break;
}
case RIL_CELL_INFO_TYPE_WCDMA: {
appendPrintBuf("%s WCDMA id: mcc=%d,mnc=%d,lac=%d,cid=%d,psc=%d,", printBuf,
p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc,
p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc,
p_cur->CellInfo.wcdma.cellIdentityWcdma.lac,
p_cur->CellInfo.wcdma.cellIdentityWcdma.cid,
p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
appendPrintBuf("%s wcdmaSS: ss=%d,ber=%d],", printBuf,
p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength,
p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mcc);
p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.mnc);
p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.lac);
p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.cid);
p.writeInt32(p_cur->CellInfo.wcdma.cellIdentityWcdma.psc);
p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.signalStrength);
p.writeInt32(p_cur->CellInfo.wcdma.signalStrengthWcdma.bitErrorRate);
break;
}
case RIL_CELL_INFO_TYPE_CDMA: {
appendPrintBuf("%s CDMA id: nId=%d,sId=%d,bsId=%d,long=%d,lat=%d", printBuf,
p_cur->CellInfo.cdma.cellIdentityCdma.networkId,
p_cur->CellInfo.cdma.cellIdentityCdma.systemId,
p_cur->CellInfo.cdma.cellIdentityCdma.basestationId,
p_cur->CellInfo.cdma.cellIdentityCdma.longitude,
p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.networkId);
p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.systemId);
p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.basestationId);
p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.longitude);
p.writeInt32(p_cur->CellInfo.cdma.cellIdentityCdma.latitude);
appendPrintBuf("%s cdmaSS: dbm=%d ecio=%d evdoSS: dbm=%d,ecio=%d,snr=%d", printBuf,
p_cur->CellInfo.cdma.signalStrengthCdma.dbm,
p_cur->CellInfo.cdma.signalStrengthCdma.ecio,
p_cur->CellInfo.cdma.signalStrengthEvdo.dbm,
p_cur->CellInfo.cdma.signalStrengthEvdo.ecio,
p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.dbm);
p.writeInt32(p_cur->CellInfo.cdma.signalStrengthCdma.ecio);
p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.dbm);
p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.ecio);
p.writeInt32(p_cur->CellInfo.cdma.signalStrengthEvdo.signalNoiseRatio);
break;
}
case RIL_CELL_INFO_TYPE_LTE: {
appendPrintBuf("%s LTE id: mcc=%d,mnc=%d,ci=%d,pci=%d,tac=%d", printBuf,
p_cur->CellInfo.lte.cellIdentityLte.mcc,
p_cur->CellInfo.lte.cellIdentityLte.mnc,
p_cur->CellInfo.lte.cellIdentityLte.ci,
p_cur->CellInfo.lte.cellIdentityLte.pci,
p_cur->CellInfo.lte.cellIdentityLte.tac);
p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mcc);
p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.mnc);
p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.ci);
p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.pci);
p.writeInt32(p_cur->CellInfo.lte.cellIdentityLte.tac);
appendPrintBuf("%s lteSS: ss=%d,rsrp=%d,rsrq=%d,rssnr=%d,cqi=%d,ta=%d", printBuf,
p_cur->CellInfo.lte.signalStrengthLte.signalStrength,
p_cur->CellInfo.lte.signalStrengthLte.rsrp,
p_cur->CellInfo.lte.signalStrengthLte.rsrq,
p_cur->CellInfo.lte.signalStrengthLte.rssnr,
p_cur->CellInfo.lte.signalStrengthLte.cqi,
p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.signalStrength);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrp);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rsrq);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.rssnr);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.cqi);
p.writeInt32(p_cur->CellInfo.lte.signalStrengthLte.timingAdvance);
break;
}
}
p_cur += 1;
}
removeLastChar;
closeResponse;
return 0;
}
static void triggerEvLoop() {
int ret;
if (!pthread_equal(pthread_self(), s_tid_dispatch)) {
/* trigger event loop to wakeup. No reason to do this,
* if we're in the event loop thread */
do {
ret = write (s_fdWakeupWrite, " ", 1);
} while (ret < 0 && errno == EINTR);
}
}
static void rilEventAddWakeup(struct ril_event *ev) {
ril_event_add(ev);
triggerEvLoop();
}
static void sendSimStatusAppInfo(Parcel &p, int num_apps, RIL_AppStatus appStatus[]) {
p.writeInt32(num_apps);
startResponse;
for (int i = 0; i < num_apps; i++) {
p.writeInt32(appStatus[i].app_type);
p.writeInt32(appStatus[i].app_state);
p.writeInt32(appStatus[i].perso_substate);
writeStringToParcel(p, (const char*)(appStatus[i].aid_ptr));
writeStringToParcel(p, (const char*)
(appStatus[i].app_label_ptr));
p.writeInt32(appStatus[i].pin1_replaced);
p.writeInt32(appStatus[i].pin1);
p.writeInt32(appStatus[i].pin2);
appendPrintBuf("%s[app_type=%d,app_state=%d,perso_substate=%d,\
aid_ptr=%s,app_label_ptr=%s,pin1_replaced=%d,pin1=%d,pin2=%d],",
printBuf,
appStatus[i].app_type,
appStatus[i].app_state,
appStatus[i].perso_substate,
appStatus[i].aid_ptr,
appStatus[i].app_label_ptr,
appStatus[i].pin1_replaced,
appStatus[i].pin1,
appStatus[i].pin2);
}
closeResponse;
}
static int responseSimStatus(Parcel &p, void *response, size_t responselen) {
int i;
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen == sizeof (RIL_CardStatus_v6)) {
RIL_CardStatus_v6 *p_cur = ((RIL_CardStatus_v6 *) response);
p.writeInt32(p_cur->card_state);
p.writeInt32(p_cur->universal_pin_state);
p.writeInt32(p_cur->gsm_umts_subscription_app_index);
p.writeInt32(p_cur->cdma_subscription_app_index);
p.writeInt32(p_cur->ims_subscription_app_index);
sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
} else if (responselen == sizeof (RIL_CardStatus_v5)) {
RIL_CardStatus_v5 *p_cur = ((RIL_CardStatus_v5 *) response);
p.writeInt32(p_cur->card_state);
p.writeInt32(p_cur->universal_pin_state);
p.writeInt32(p_cur->gsm_umts_subscription_app_index);
p.writeInt32(p_cur->cdma_subscription_app_index);
p.writeInt32(-1);
sendSimStatusAppInfo(p, p_cur->num_applications, p_cur->applications);
} else {
RLOGE("responseSimStatus: A RilCardStatus_v6 or _v5 expected\n");
return RIL_ERRNO_INVALID_RESPONSE;
}
return 0;
}
static int responseGsmBrSmsCnf(Parcel &p, void *response, size_t responselen) {
int num = responselen / sizeof(RIL_GSM_BroadcastSmsConfigInfo *);
p.writeInt32(num);
startResponse;
RIL_GSM_BroadcastSmsConfigInfo **p_cur =
(RIL_GSM_BroadcastSmsConfigInfo **) response;
for (int i = 0; i < num; i++) {
p.writeInt32(p_cur[i]->fromServiceId);
p.writeInt32(p_cur[i]->toServiceId);
p.writeInt32(p_cur[i]->fromCodeScheme);
p.writeInt32(p_cur[i]->toCodeScheme);
p.writeInt32(p_cur[i]->selected);
appendPrintBuf("%s [%d: fromServiceId=%d, toServiceId=%d, \
fromCodeScheme=%d, toCodeScheme=%d, selected =%d]",
printBuf, i, p_cur[i]->fromServiceId, p_cur[i]->toServiceId,
p_cur[i]->fromCodeScheme, p_cur[i]->toCodeScheme,
p_cur[i]->selected);
}
closeResponse;
return 0;
}
static int responseCdmaBrSmsCnf(Parcel &p, void *response, size_t responselen) {
RIL_CDMA_BroadcastSmsConfigInfo **p_cur =
(RIL_CDMA_BroadcastSmsConfigInfo **) response;
int num = responselen / sizeof (RIL_CDMA_BroadcastSmsConfigInfo *);
p.writeInt32(num);
startResponse;
for (int i = 0 ; i < num ; i++ ) {
p.writeInt32(p_cur[i]->service_category);
p.writeInt32(p_cur[i]->language);
p.writeInt32(p_cur[i]->selected);
appendPrintBuf("%s [%d: srvice_category=%d, language =%d, \
selected =%d], ",
printBuf, i, p_cur[i]->service_category, p_cur[i]->language,
p_cur[i]->selected);
}
closeResponse;
return 0;
}
static int responseCdmaSms(Parcel &p, void *response, size_t responselen) {
int num;
int digitCount;
int digitLimit;
uint8_t uct;
void* dest;
RLOGD("Inside responseCdmaSms");
if (response == NULL && responselen != 0) {
RLOGE("invalid response: NULL");
return RIL_ERRNO_INVALID_RESPONSE;
}
if (responselen != sizeof(RIL_CDMA_SMS_Message)) {
RLOGE("invalid response length was %d expected %d",
(int)responselen, (int)sizeof(RIL_CDMA_SMS_Message));
return RIL_ERRNO_INVALID_RESPONSE;
}
RIL_CDMA_SMS_Message *p_cur = (RIL_CDMA_SMS_Message *) response;
p.writeInt32(p_cur->uTeleserviceID);
p.write(&(p_cur->bIsServicePresent),sizeof(uct));
p.writeInt32(p_cur->uServicecategory);
p.writeInt32(p_cur->sAddress.digit_mode);
p.writeInt32(p_cur->sAddress.number_mode);
p.writeInt32(p_cur->sAddress.number_type);
p.writeInt32(p_cur->sAddress.number_plan);
p.write(&(p_cur->sAddress.number_of_digits), sizeof(uct));
digitLimit= MIN((p_cur->sAddress.number_of_digits), RIL_CDMA_SMS_ADDRESS_MAX);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
p.write(&(p_cur->sAddress.digits[digitCount]),sizeof(uct));
}
p.writeInt32(p_cur->sSubAddress.subaddressType);
p.write(&(p_cur->sSubAddress.odd),sizeof(uct));
p.write(&(p_cur->sSubAddress.number_of_digits),sizeof(uct));
digitLimit= MIN((p_cur->sSubAddress.number_of_digits), RIL_CDMA_SMS_SUBADDRESS_MAX);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
p.write(&(p_cur->sSubAddress.digits[digitCount]),sizeof(uct));
}
digitLimit= MIN((p_cur->uBearerDataLen), RIL_CDMA_SMS_BEARER_DATA_MAX);
p.writeInt32(p_cur->uBearerDataLen);
for(digitCount =0 ; digitCount < digitLimit; digitCount ++) {
p.write(&(p_cur->aBearerData[digitCount]), sizeof(uct));
}
startResponse;
appendPrintBuf("%suTeleserviceID=%d, bIsServicePresent=%d, uServicecategory=%d, \
sAddress.digit_mode=%d, sAddress.number_mode=%d, sAddress.number_type=%d, ",
printBuf, p_cur->uTeleserviceID,p_cur->bIsServicePresent,p_cur->uServicecategory,
p_cur->sAddress.digit_mode, p_cur->sAddress.number_mode,p_cur->sAddress.number_type);
closeResponse;
return 0;
}
/**
* A write on the wakeup fd is done just to pop us out of select()
* We empty the buffer here and then ril_event will reset the timers on the
* way back down
*/
static void processWakeupCallback(int fd, short flags, void *param) {
char buff[16];
int ret;
RLOGV("processWakeupCallback");
/* empty our wakeup socket out */
do {
ret = read(s_fdWakeupRead, &buff, sizeof(buff));
} while (ret > 0 || (ret < 0 && errno == EINTR));
}
static void onCommandsSocketClosed() {
int ret;
RequestInfo *p_cur;
/* mark pending requests as "cancelled" so we dont report responses */
ret = pthread_mutex_lock(&s_pendingRequestsMutex);
assert (ret == 0);
p_cur = s_pendingRequests;
for (p_cur = s_pendingRequests
; p_cur != NULL
; p_cur = p_cur->p_next
) {
p_cur->cancelled = 1;
}
ret = pthread_mutex_unlock(&s_pendingRequestsMutex);
assert (ret == 0);
}
static void processCommandsCallback(int fd, short flags, void *param) {
RecordStream *p_rs;
void *p_record;
size_t recordlen;
int ret;
assert(fd == s_fdCommand);
p_rs = (RecordStream *)param;
for (;;) {
/* loop until EAGAIN/EINTR, end of stream, or other error */
ret = record_stream_get_next(p_rs, &p_record, &recordlen);
if (ret == 0 && p_record == NULL) {
/* end-of-stream */
break;
} else if (ret < 0) {
break;
} else if (ret == 0) { /* && p_record != NULL */
processCommandBuffer(p_record, recordlen);
}
}
if (ret == 0 || !(errno == EAGAIN || errno == EINTR)) {
/* fatal error or end-of-stream */
if (ret != 0) {
RLOGE("error on reading command socket errno:%d\n", errno);
} else {
RLOGW("EOS. Closing command socket.");
}
close(s_fdCommand);
s_fdCommand = -1;
ril_event_del(&s_commands_event);
record_stream_free(p_rs);
/* start listening for new connections again */
rilEventAddWakeup(&s_listen_event);
onCommandsSocketClosed();
}
}
static void onNewCommandConnect() {
// Inform we are connected and the ril version
int rilVer = s_callbacks.version;
RIL_onUnsolicitedResponse(RIL_UNSOL_RIL_CONNECTED,
&rilVer, sizeof(rilVer));
// implicit radio state changed
RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED,
NULL, 0);
// Send last NITZ time data, in case it was missed
if (s_lastNITZTimeData != NULL) {
sendResponseRaw(s_lastNITZTimeData, s_lastNITZTimeDataSize);
free(s_lastNITZTimeData);
s_lastNITZTimeData = NULL;
}
// Get version string
if (s_callbacks.getVersion != NULL) {
const char *version;
version = s_callbacks.getVersion();
RLOGI("RIL Daemon version: %s\n", version);
property_set(PROPERTY_RIL_IMPL, version);
} else {
RLOGI("RIL Daemon version: unavailable\n");
property_set(PROPERTY_RIL_IMPL, "unavailable");
}
}
static void listenCallback (int fd, short flags, void *param) {
int ret;
int err;
int is_phone_socket;
RecordStream *p_rs;
struct sockaddr_un peeraddr;
socklen_t socklen = sizeof (peeraddr);
struct ucred creds;
socklen_t szCreds = sizeof(creds);
struct passwd *pwd = NULL;
assert (s_fdCommand < 0);
assert (fd == s_fdListen);
s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen);
if (s_fdCommand < 0 ) {
RLOGE("Error on accept() errno:%d", errno);
/* start listening for new connections again */
rilEventAddWakeup(&s_listen_event);
return;
}
/* check the credential of the other side and only accept socket from
* phone process
*/
errno = 0;
is_phone_socket = 0;
err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds);
if (err == 0 && szCreds > 0) {
errno = 0;
pwd = getpwuid(creds.uid);
if (pwd != NULL) {
if (strcmp(pwd->pw_name, PHONE_PROCESS) == 0) {
is_phone_socket = 1;
} else {
RLOGE("RILD can't accept socket from process %s", pwd->pw_name);
}
} else {
RLOGE("Error on getpwuid() errno: %d", errno);
}
} else {
RLOGD("Error on getsockopt() errno: %d", errno);
}
if ( !is_phone_socket ) {
RLOGE("RILD must accept socket from %s", PHONE_PROCESS);
close(s_fdCommand);
s_fdCommand = -1;
onCommandsSocketClosed();
/* start listening for new connections again */
rilEventAddWakeup(&s_listen_event);
return;
}
ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK);
if (ret < 0) {
RLOGE ("Error setting O_NONBLOCK errno:%d", errno);
}
RLOGI("libril: new connection");
p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES);
ril_event_set (&s_commands_event, s_fdCommand, 1,
processCommandsCallback, p_rs);
rilEventAddWakeup (&s_commands_event);
onNewCommandConnect();
}
static void freeDebugCallbackArgs(int number, char **args) {
for (int i = 0; i < number; i++) {
if (args[i] != NULL) {
free(args[i]);
}
}
free(args);
}
static void debugCallback (int fd, short flags, void *param) {
int acceptFD, option;
struct sockaddr_un peeraddr;
socklen_t socklen = sizeof (peeraddr);
int data;
unsigned int qxdm_data[6];
const char *deactData[1] = {"1"};
char *actData[1];
RIL_Dial dialData;
int hangupData[1] = {1};
int number;
char **args;
acceptFD = accept (fd, (sockaddr *) &peeraddr, &socklen);
if (acceptFD < 0) {
RLOGE ("error accepting on debug port: %d\n", errno);
return;
}
if (recv(acceptFD, &number, sizeof(int), 0) != sizeof(int)) {
RLOGE ("error reading on socket: number of Args: \n");
return;
}
args = (char **) malloc(sizeof(char*) * number);
for (int i = 0; i < number; i++) {
int len;
if (recv(acceptFD, &len, sizeof(int), 0) != sizeof(int)) {
RLOGE ("error reading on socket: Len of Args: \n");
freeDebugCallbackArgs(i, args);
return;
}
// +1 for null-term
args[i] = (char *) malloc((sizeof(char) * len) + 1);
if (recv(acceptFD, args[i], sizeof(char) * len, 0)
!= (int)sizeof(char) * len) {
RLOGE ("error reading on socket: Args[%d] \n", i);
freeDebugCallbackArgs(i, args);
return;
}
char * buf = args[i];
buf[len] = 0;
}
switch (atoi(args[0])) {
case 0:
RLOGI ("Connection on debug port: issuing reset.");
issueLocalRequest(RIL_REQUEST_RESET_RADIO, NULL, 0);
break;
case 1:
RLOGI ("Connection on debug port: issuing radio power off.");
data = 0;
issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
// Close the socket
close(s_fdCommand);
s_fdCommand = -1;
break;
case 2:
RLOGI ("Debug port: issuing unsolicited voice network change.");
RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED,
NULL, 0);
break;
case 3:
RLOGI ("Debug port: QXDM log enable.");
qxdm_data[0] = 65536; // head.func_tag
qxdm_data[1] = 16; // head.len
qxdm_data[2] = 1; // mode: 1 for 'start logging'
qxdm_data[3] = 32; // log_file_size: 32megabytes
qxdm_data[4] = 0; // log_mask
qxdm_data[5] = 8; // log_max_fileindex
issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
6 * sizeof(int));
break;
case 4:
RLOGI ("Debug port: QXDM log disable.");
qxdm_data[0] = 65536;
qxdm_data[1] = 16;
qxdm_data[2] = 0; // mode: 0 for 'stop logging'
qxdm_data[3] = 32;
qxdm_data[4] = 0;
qxdm_data[5] = 8;
issueLocalRequest(RIL_REQUEST_OEM_HOOK_RAW, qxdm_data,
6 * sizeof(int));
break;
case 5:
RLOGI("Debug port: Radio On");
data = 1;
issueLocalRequest(RIL_REQUEST_RADIO_POWER, &data, sizeof(int));
sleep(2);
// Set network selection automatic.
issueLocalRequest(RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, NULL, 0);
break;
case 6:
RLOGI("Debug port: Setup Data Call, Apn :%s\n", args[1]);
actData[0] = args[1];
issueLocalRequest(RIL_REQUEST_SETUP_DATA_CALL, &actData,
sizeof(actData));
break;
case 7:
RLOGI("Debug port: Deactivate Data Call");
issueLocalRequest(RIL_REQUEST_DEACTIVATE_DATA_CALL, &deactData,
sizeof(deactData));
break;
case 8:
RLOGI("Debug port: Dial Call");
dialData.clir = 0;
dialData.address = args[1];
issueLocalRequest(RIL_REQUEST_DIAL, &dialData, sizeof(dialData));
break;
case 9:
RLOGI("Debug port: Answer Call");
issueLocalRequest(RIL_REQUEST_ANSWER, NULL, 0);
break;
case 10:
RLOGI("Debug port: End Call");
issueLocalRequest(RIL_REQUEST_HANGUP, &hangupData,
sizeof(hangupData));
break;
default:
RLOGE ("Invalid request");
break;
}
freeDebugCallbackArgs(number, args);
close(acceptFD);
}
static void userTimerCallback (int fd, short flags, void *param) {
UserCallbackInfo *p_info;
p_info = (UserCallbackInfo *)param;
p_info->p_callback(p_info->userParam);
// FIXME generalize this...there should be a cancel mechanism
if (s_last_wake_timeout_info != NULL && s_last_wake_timeout_info == p_info) {
s_last_wake_timeout_info = NULL;
}
free(p_info);
}
static void *
eventLoop(void *param) {
int ret;
int filedes[2];
ril_event_init();
pthread_mutex_lock(&s_startupMutex);
s_started = 1;
pthread_cond_broadcast(&s_startupCond);
pthread_mutex_unlock(&s_startupMutex);
ret = pipe(filedes);
if (ret < 0) {
RLOGE("Error in pipe() errno:%d", errno);
return NULL;
}
s_fdWakeupRead = filedes[0];
s_fdWakeupWrite = filedes[1];
fcntl(s_fdWakeupRead, F_SETFL, O_NONBLOCK);
ril_event_set (&s_wakeupfd_event, s_fdWakeupRead, true,
processWakeupCallback, NULL);
rilEventAddWakeup (&s_wakeupfd_event);
// Only returns on error
ril_event_loop();
RLOGE ("error in event_loop_base errno:%d", errno);
// kill self to restart on error
kill(0, SIGKILL);
return NULL;
}
extern "C" void
RIL_startEventLoop(void) {
int ret;
pthread_attr_t attr;
/* spin up eventLoop thread and wait for it to get started */
s_started = 0;
pthread_mutex_lock(&s_startupMutex);
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL);
while (s_started == 0) {
pthread_cond_wait(&s_startupCond, &s_startupMutex);
}
pthread_mutex_unlock(&s_startupMutex);
if (ret < 0) {
RLOGE("Failed to create dispatch thread errno:%d", errno);
return;
}
}
// Used for testing purpose only.
extern "C" void RIL_setcallbacks (const RIL_RadioFunctions *callbacks) {
memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
}
extern "C" void
RIL_register (const RIL_RadioFunctions *callbacks) {
int ret;
int flags;
if (callbacks == NULL) {
RLOGE("RIL_register: RIL_RadioFunctions * null");
return;
}
if (callbacks->version < RIL_VERSION_MIN) {
RLOGE("RIL_register: version %d is to old, min version is %d",
callbacks->version, RIL_VERSION_MIN);
return;
}
if (callbacks->version > RIL_VERSION) {
RLOGE("RIL_register: version %d is too new, max version is %d",
callbacks->version, RIL_VERSION);
return;
}
RLOGE("RIL_register: RIL version %d", callbacks->version);
if (s_registerCalled > 0) {
RLOGE("RIL_register has been called more than once. "
"Subsequent call ignored");
return;
}
memcpy(&s_callbacks, callbacks, sizeof (RIL_RadioFunctions));
s_registerCalled = 1;
// Little self-check
for (int i = 0; i < (int)NUM_ELEMS(s_commands); i++) {
assert(i == s_commands[i].requestNumber);
}
for (int i = 0; i < (int)NUM_ELEMS(s_unsolResponses); i++) {
assert(i + RIL_UNSOL_RESPONSE_BASE
== s_unsolResponses[i].requestNumber);
}
// New rild impl calls RIL_startEventLoop() first
// old standalone impl wants it here.
if (s_started == 0) {
RIL_startEventLoop();
}
// start listen socket
#if 0
ret = socket_local_server (SOCKET_NAME_RIL,
ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
if (ret < 0) {
RLOGE("Unable to bind socket errno:%d", errno);
exit (-1);
}
s_fdListen = ret;
#else
s_fdListen = android_get_control_socket(SOCKET_NAME_RIL);
if (s_fdListen < 0) {
RLOGE("Failed to get socket '" SOCKET_NAME_RIL "'");
exit(-1);
}
ret = listen(s_fdListen, 4);
if (ret < 0) {
RLOGE("Failed to listen on control socket '%d': %s",
s_fdListen, strerror(errno));
exit(-1);
}
#endif
/* note: non-persistent so we can accept only one connection at a time */
ril_event_set (&s_listen_event, s_fdListen, false,
listenCallback, NULL);
rilEventAddWakeup (&s_listen_event);
#if 1
// start debug interface socket
s_fdDebug = android_get_control_socket(SOCKET_NAME_RIL_DEBUG);
if (s_fdDebug < 0) {
RLOGE("Failed to get socket '" SOCKET_NAME_RIL_DEBUG "' errno:%d", errno);
exit(-1);
}
ret = listen(s_fdDebug, 4);
if (ret < 0) {
RLOGE("Failed to listen on ril debug socket '%d': %s",
s_fdDebug, strerror(errno));
exit(-1);
}
ril_event_set (&s_debug_event, s_fdDebug, true,
debugCallback, NULL);
rilEventAddWakeup (&s_debug_event);
#endif
}
static int
checkAndDequeueRequestInfo(struct RequestInfo *pRI) {
int ret = 0;
if (pRI == NULL) {
return 0;
}
pthread_mutex_lock(&s_pendingRequestsMutex);
for(RequestInfo **ppCur = &s_pendingRequests
; *ppCur != NULL
; ppCur = &((*ppCur)->p_next)
) {
if (pRI == *ppCur) {
ret = 1;
*ppCur = (*ppCur)->p_next;
break;
}
}
pthread_mutex_unlock(&s_pendingRequestsMutex);
return ret;
}
extern "C" void
RIL_onRequestComplete(RIL_Token t, RIL_Errno e, void *response, size_t responselen) {
RequestInfo *pRI;
int ret;
size_t errorOffset;
pRI = (RequestInfo *)t;
if (!checkAndDequeueRequestInfo(pRI)) {
RLOGE ("RIL_onRequestComplete: invalid RIL_Token");
return;
}
if (pRI->local > 0) {
// Locally issued command...void only!
// response does not go back up the command socket
RLOGD("C[locl]< %s", requestToString(pRI->pCI->requestNumber));
goto done;
}
appendPrintBuf("[%04d]< %s",
pRI->token, requestToString(pRI->pCI->requestNumber));
if (pRI->cancelled == 0) {
Parcel p;
p.writeInt32 (RESPONSE_SOLICITED);
p.writeInt32 (pRI->token);
errorOffset = p.dataPosition();
p.writeInt32 (e);
if (response != NULL) {
// there is a response payload, no matter success or not.
ret = pRI->pCI->responseFunction(p, response, responselen);
/* if an error occurred, rewind and mark it */
if (ret != 0) {
p.setDataPosition(errorOffset);
p.writeInt32 (ret);
}
}
if (e != RIL_E_SUCCESS) {
appendPrintBuf("%s fails by %s", printBuf, failCauseToString(e));
}
if (s_fdCommand < 0) {
RLOGD ("RIL onRequestComplete: Command channel closed");
}
sendResponse(p);
}
done:
free(pRI);
}
static void
grabPartialWakeLock() {
acquire_wake_lock(PARTIAL_WAKE_LOCK, ANDROID_WAKE_LOCK_NAME);
}
static void
releaseWakeLock() {
release_wake_lock(ANDROID_WAKE_LOCK_NAME);
}
/**
* Timer callback to put us back to sleep before the default timeout
*/
static void
wakeTimeoutCallback (void *param) {
// We're using "param != NULL" as a cancellation mechanism
if (param == NULL) {
//RLOGD("wakeTimeout: releasing wake lock");
releaseWakeLock();
} else {
//RLOGD("wakeTimeout: releasing wake lock CANCELLED");
}
}
static int
decodeVoiceRadioTechnology (RIL_RadioState radioState) {
switch (radioState) {
case RADIO_STATE_SIM_NOT_READY:
case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
case RADIO_STATE_SIM_READY:
return RADIO_TECH_UMTS;
case RADIO_STATE_RUIM_NOT_READY:
case RADIO_STATE_RUIM_READY:
case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
case RADIO_STATE_NV_NOT_READY:
case RADIO_STATE_NV_READY:
return RADIO_TECH_1xRTT;
default:
RLOGD("decodeVoiceRadioTechnology: Invoked with incorrect RadioState");
return -1;
}
}
static int
decodeCdmaSubscriptionSource (RIL_RadioState radioState) {
switch (radioState) {
case RADIO_STATE_SIM_NOT_READY:
case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
case RADIO_STATE_SIM_READY:
case RADIO_STATE_RUIM_NOT_READY:
case RADIO_STATE_RUIM_READY:
case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
return CDMA_SUBSCRIPTION_SOURCE_RUIM_SIM;
case RADIO_STATE_NV_NOT_READY:
case RADIO_STATE_NV_READY:
return CDMA_SUBSCRIPTION_SOURCE_NV;
default:
RLOGD("decodeCdmaSubscriptionSource: Invoked with incorrect RadioState");
return -1;
}
}
static int
decodeSimStatus (RIL_RadioState radioState) {
switch (radioState) {
case RADIO_STATE_SIM_NOT_READY:
case RADIO_STATE_RUIM_NOT_READY:
case RADIO_STATE_NV_NOT_READY:
case RADIO_STATE_NV_READY:
return -1;
case RADIO_STATE_SIM_LOCKED_OR_ABSENT:
case RADIO_STATE_SIM_READY:
case RADIO_STATE_RUIM_READY:
case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:
return radioState;
default:
RLOGD("decodeSimStatus: Invoked with incorrect RadioState");
return -1;
}
}
static bool is3gpp2(int radioTech) {
switch (radioTech) {
case RADIO_TECH_IS95A:
case RADIO_TECH_IS95B:
case RADIO_TECH_1xRTT:
case RADIO_TECH_EVDO_0:
case RADIO_TECH_EVDO_A:
case RADIO_TECH_EVDO_B:
case RADIO_TECH_EHRPD:
return true;
default:
return false;
}
}
/* If RIL sends SIM states or RUIM states, store the voice radio
* technology and subscription source information so that they can be
* returned when telephony framework requests them
*/
static RIL_RadioState
processRadioState(RIL_RadioState newRadioState) {
if((newRadioState > RADIO_STATE_UNAVAILABLE) && (newRadioState < RADIO_STATE_ON)) {
int newVoiceRadioTech;
int newCdmaSubscriptionSource;
int newSimStatus;
/* This is old RIL. Decode Subscription source and Voice Radio Technology
from Radio State and send change notifications if there has been a change */
newVoiceRadioTech = decodeVoiceRadioTechnology(newRadioState);
if(newVoiceRadioTech != voiceRadioTech) {
voiceRadioTech = newVoiceRadioTech;
RIL_onUnsolicitedResponse (RIL_UNSOL_VOICE_RADIO_TECH_CHANGED,
&voiceRadioTech, sizeof(voiceRadioTech));
}
if(is3gpp2(newVoiceRadioTech)) {
newCdmaSubscriptionSource = decodeCdmaSubscriptionSource(newRadioState);
if(newCdmaSubscriptionSource != cdmaSubscriptionSource) {
cdmaSubscriptionSource = newCdmaSubscriptionSource;
RIL_onUnsolicitedResponse (RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED,
&cdmaSubscriptionSource, sizeof(cdmaSubscriptionSource));
}
}
newSimStatus = decodeSimStatus(newRadioState);
if(newSimStatus != simRuimStatus) {
simRuimStatus = newSimStatus;
RIL_onUnsolicitedResponse(RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED, NULL, 0);
}
/* Send RADIO_ON to telephony */
newRadioState = RADIO_STATE_ON;
}
return newRadioState;
}
extern "C"
void RIL_onUnsolicitedResponse(int unsolResponse, void *data,
size_t datalen)
{
int unsolResponseIndex;
int ret;
int64_t timeReceived = 0;
bool shouldScheduleTimeout = false;
RIL_RadioState newState;
if (s_registerCalled == 0) {
// Ignore RIL_onUnsolicitedResponse before RIL_register
RLOGW("RIL_onUnsolicitedResponse called before RIL_register");
return;
}
unsolResponseIndex = unsolResponse - RIL_UNSOL_RESPONSE_BASE;
if ((unsolResponseIndex < 0)
|| (unsolResponseIndex >= (int32_t)NUM_ELEMS(s_unsolResponses))) {
RLOGE("unsupported unsolicited response code %d", unsolResponse);
return;
}
// Grab a wake lock if needed for this reponse,
// as we exit we'll either release it immediately
// or set a timer to release it later.
switch (s_unsolResponses[unsolResponseIndex].wakeType) {
case WAKE_PARTIAL:
grabPartialWakeLock();
shouldScheduleTimeout = true;
break;
case DONT_WAKE:
default:
// No wake lock is grabed so don't set timeout
shouldScheduleTimeout = false;
break;
}
// Mark the time this was received, doing this
// after grabing the wakelock incase getting
// the elapsedRealTime might cause us to goto
// sleep.
if (unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
timeReceived = elapsedRealtime();
}
appendPrintBuf("[UNSL]< %s", requestToString(unsolResponse));
Parcel p;
p.writeInt32 (RESPONSE_UNSOLICITED);
p.writeInt32 (unsolResponse);
ret = s_unsolResponses[unsolResponseIndex]
.responseFunction(p, data, datalen);
if (ret != 0) {
// Problem with the response. Don't continue;
goto error_exit;
}
// some things get more payload
switch(unsolResponse) {
case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED:
newState = processRadioState(s_callbacks.onStateRequest());
p.writeInt32(newState);
appendPrintBuf("%s {%s}", printBuf,
radioStateToString(s_callbacks.onStateRequest()));
break;
case RIL_UNSOL_NITZ_TIME_RECEIVED:
// Store the time that this was received so the
// handler of this message can account for
// the time it takes to arrive and process. In
// particular the system has been known to sleep
// before this message can be processed.
p.writeInt64(timeReceived);
break;
}
ret = sendResponse(p);
if (ret != 0 && unsolResponse == RIL_UNSOL_NITZ_TIME_RECEIVED) {
// Unfortunately, NITZ time is not poll/update like everything
// else in the system. So, if the upstream client isn't connected,
// keep a copy of the last NITZ response (with receive time noted
// above) around so we can deliver it when it is connected
if (s_lastNITZTimeData != NULL) {
free (s_lastNITZTimeData);
s_lastNITZTimeData = NULL;
}
s_lastNITZTimeData = malloc(p.dataSize());
s_lastNITZTimeDataSize = p.dataSize();
memcpy(s_lastNITZTimeData, p.data(), p.dataSize());
}
// For now, we automatically go back to sleep after TIMEVAL_WAKE_TIMEOUT
// FIXME The java code should handshake here to release wake lock
if (shouldScheduleTimeout) {
// Cancel the previous request
if (s_last_wake_timeout_info != NULL) {
s_last_wake_timeout_info->userParam = (void *)1;
}
s_last_wake_timeout_info
= internalRequestTimedCallback(wakeTimeoutCallback, NULL,
&TIMEVAL_WAKE_TIMEOUT);
}
// Normal exit
return;
error_exit:
if (shouldScheduleTimeout) {
releaseWakeLock();
}
}
/** FIXME generalize this if you track UserCAllbackInfo, clear it
when the callback occurs
*/
static UserCallbackInfo *
internalRequestTimedCallback (RIL_TimedCallback callback, void *param,
const struct timeval *relativeTime)
{
struct timeval myRelativeTime;
UserCallbackInfo *p_info;
p_info = (UserCallbackInfo *) malloc (sizeof(UserCallbackInfo));
p_info->p_callback = callback;
p_info->userParam = param;
if (relativeTime == NULL) {
/* treat null parameter as a 0 relative time */
memset (&myRelativeTime, 0, sizeof(myRelativeTime));
} else {
/* FIXME I think event_add's tv param is really const anyway */
memcpy (&myRelativeTime, relativeTime, sizeof(myRelativeTime));
}
ril_event_set(&(p_info->event), -1, false, userTimerCallback, p_info);
ril_timer_add(&(p_info->event), &myRelativeTime);
triggerEvLoop();
return p_info;
}
extern "C" void
RIL_requestTimedCallback (RIL_TimedCallback callback, void *param,
const struct timeval *relativeTime) {
internalRequestTimedCallback (callback, param, relativeTime);
}
const char *
failCauseToString(RIL_Errno e) {
switch(e) {
case RIL_E_SUCCESS: return "E_SUCCESS";
case RIL_E_RADIO_NOT_AVAILABLE: return "E_RADIO_NOT_AVAILABLE";
case RIL_E_GENERIC_FAILURE: return "E_GENERIC_FAILURE";
case RIL_E_PASSWORD_INCORRECT: return "E_PASSWORD_INCORRECT";
case RIL_E_SIM_PIN2: return "E_SIM_PIN2";
case RIL_E_SIM_PUK2: return "E_SIM_PUK2";
case RIL_E_REQUEST_NOT_SUPPORTED: return "E_REQUEST_NOT_SUPPORTED";
case RIL_E_CANCELLED: return "E_CANCELLED";
case RIL_E_OP_NOT_ALLOWED_DURING_VOICE_CALL: return "E_OP_NOT_ALLOWED_DURING_VOICE_CALL";
case RIL_E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW: return "E_OP_NOT_ALLOWED_BEFORE_REG_TO_NW";
case RIL_E_SMS_SEND_FAIL_RETRY: return "E_SMS_SEND_FAIL_RETRY";
case RIL_E_SIM_ABSENT:return "E_SIM_ABSENT";
case RIL_E_ILLEGAL_SIM_OR_ME:return "E_ILLEGAL_SIM_OR_ME";
#ifdef FEATURE_MULTIMODE_ANDROID
case RIL_E_SUBSCRIPTION_NOT_AVAILABLE:return "E_SUBSCRIPTION_NOT_AVAILABLE";
case RIL_E_MODE_NOT_SUPPORTED:return "E_MODE_NOT_SUPPORTED";
#endif
default: return "<unknown error>";
}
}
const char *
radioStateToString(RIL_RadioState s) {
switch(s) {
case RADIO_STATE_OFF: return "RADIO_OFF";
case RADIO_STATE_UNAVAILABLE: return "RADIO_UNAVAILABLE";
case RADIO_STATE_SIM_NOT_READY: return "RADIO_SIM_NOT_READY";
case RADIO_STATE_SIM_LOCKED_OR_ABSENT: return "RADIO_SIM_LOCKED_OR_ABSENT";
case RADIO_STATE_SIM_READY: return "RADIO_SIM_READY";
case RADIO_STATE_RUIM_NOT_READY:return"RADIO_RUIM_NOT_READY";
case RADIO_STATE_RUIM_READY:return"RADIO_RUIM_READY";
case RADIO_STATE_RUIM_LOCKED_OR_ABSENT:return"RADIO_RUIM_LOCKED_OR_ABSENT";
case RADIO_STATE_NV_NOT_READY:return"RADIO_NV_NOT_READY";
case RADIO_STATE_NV_READY:return"RADIO_NV_READY";
case RADIO_STATE_ON:return"RADIO_ON";
default: return "<unknown state>";
}
}
const char *
callStateToString(RIL_CallState s) {
switch(s) {
case RIL_CALL_ACTIVE : return "ACTIVE";
case RIL_CALL_HOLDING: return "HOLDING";
case RIL_CALL_DIALING: return "DIALING";
case RIL_CALL_ALERTING: return "ALERTING";
case RIL_CALL_INCOMING: return "INCOMING";
case RIL_CALL_WAITING: return "WAITING";
default: return "<unknown state>";
}
}
const char *
requestToString(int request) {
/*
cat libs/telephony/ril_commands.h \
| egrep "^ *{RIL_" \
| sed -re 's/\{RIL_([^,]+),[^,]+,([^}]+).+/case RIL_\1: return "\1";/'
cat libs/telephony/ril_unsol_commands.h \
| egrep "^ *{RIL_" \
| sed -re 's/\{RIL_([^,]+),([^}]+).+/case RIL_\1: return "\1";/'
*/
switch(request) {
case RIL_REQUEST_GET_SIM_STATUS: return "GET_SIM_STATUS";
case RIL_REQUEST_ENTER_SIM_PIN: return "ENTER_SIM_PIN";
case RIL_REQUEST_ENTER_SIM_PUK: return "ENTER_SIM_PUK";
case RIL_REQUEST_ENTER_SIM_PIN2: return "ENTER_SIM_PIN2";
case RIL_REQUEST_ENTER_SIM_PUK2: return "ENTER_SIM_PUK2";
case RIL_REQUEST_CHANGE_SIM_PIN: return "CHANGE_SIM_PIN";
case RIL_REQUEST_CHANGE_SIM_PIN2: return "CHANGE_SIM_PIN2";
case RIL_REQUEST_ENTER_NETWORK_DEPERSONALIZATION: return "ENTER_NETWORK_DEPERSONALIZATION";
case RIL_REQUEST_GET_CURRENT_CALLS: return "GET_CURRENT_CALLS";
case RIL_REQUEST_DIAL: return "DIAL";
case RIL_REQUEST_GET_IMSI: return "GET_IMSI";
case RIL_REQUEST_HANGUP: return "HANGUP";
case RIL_REQUEST_HANGUP_WAITING_OR_BACKGROUND: return "HANGUP_WAITING_OR_BACKGROUND";
case RIL_REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND: return "HANGUP_FOREGROUND_RESUME_BACKGROUND";
case RIL_REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE: return "SWITCH_WAITING_OR_HOLDING_AND_ACTIVE";
case RIL_REQUEST_CONFERENCE: return "CONFERENCE";
case RIL_REQUEST_UDUB: return "UDUB";
case RIL_REQUEST_LAST_CALL_FAIL_CAUSE: return "LAST_CALL_FAIL_CAUSE";
case RIL_REQUEST_SIGNAL_STRENGTH: return "SIGNAL_STRENGTH";
case RIL_REQUEST_VOICE_REGISTRATION_STATE: return "VOICE_REGISTRATION_STATE";
case RIL_REQUEST_DATA_REGISTRATION_STATE: return "DATA_REGISTRATION_STATE";
case RIL_REQUEST_OPERATOR: return "OPERATOR";
case RIL_REQUEST_RADIO_POWER: return "RADIO_POWER";
case RIL_REQUEST_DTMF: return "DTMF";
case RIL_REQUEST_SEND_SMS: return "SEND_SMS";
case RIL_REQUEST_SEND_SMS_EXPECT_MORE: return "SEND_SMS_EXPECT_MORE";
case RIL_REQUEST_SETUP_DATA_CALL: return "SETUP_DATA_CALL";
case RIL_REQUEST_SIM_IO: return "SIM_IO";
case RIL_REQUEST_SEND_USSD: return "SEND_USSD";
case RIL_REQUEST_CANCEL_USSD: return "CANCEL_USSD";
case RIL_REQUEST_GET_CLIR: return "GET_CLIR";
case RIL_REQUEST_SET_CLIR: return "SET_CLIR";
case RIL_REQUEST_QUERY_CALL_FORWARD_STATUS: return "QUERY_CALL_FORWARD_STATUS";
case RIL_REQUEST_SET_CALL_FORWARD: return "SET_CALL_FORWARD";
case RIL_REQUEST_QUERY_CALL_WAITING: return "QUERY_CALL_WAITING";
case RIL_REQUEST_SET_CALL_WAITING: return "SET_CALL_WAITING";
case RIL_REQUEST_SMS_ACKNOWLEDGE: return "SMS_ACKNOWLEDGE";
case RIL_REQUEST_GET_IMEI: return "GET_IMEI";
case RIL_REQUEST_GET_IMEISV: return "GET_IMEISV";
case RIL_REQUEST_ANSWER: return "ANSWER";
case RIL_REQUEST_DEACTIVATE_DATA_CALL: return "DEACTIVATE_DATA_CALL";
case RIL_REQUEST_QUERY_FACILITY_LOCK: return "QUERY_FACILITY_LOCK";
case RIL_REQUEST_SET_FACILITY_LOCK: return "SET_FACILITY_LOCK";
case RIL_REQUEST_CHANGE_BARRING_PASSWORD: return "CHANGE_BARRING_PASSWORD";
case RIL_REQUEST_QUERY_NETWORK_SELECTION_MODE: return "QUERY_NETWORK_SELECTION_MODE";
case RIL_REQUEST_SET_NETWORK_SELECTION_AUTOMATIC: return "SET_NETWORK_SELECTION_AUTOMATIC";
case RIL_REQUEST_SET_NETWORK_SELECTION_MANUAL: return "SET_NETWORK_SELECTION_MANUAL";
case RIL_REQUEST_QUERY_AVAILABLE_NETWORKS : return "QUERY_AVAILABLE_NETWORKS ";
case RIL_REQUEST_DTMF_START: return "DTMF_START";
case RIL_REQUEST_DTMF_STOP: return "DTMF_STOP";
case RIL_REQUEST_BASEBAND_VERSION: return "BASEBAND_VERSION";
case RIL_REQUEST_SEPARATE_CONNECTION: return "SEPARATE_CONNECTION";
case RIL_REQUEST_SET_PREFERRED_NETWORK_TYPE: return "SET_PREFERRED_NETWORK_TYPE";
case RIL_REQUEST_GET_PREFERRED_NETWORK_TYPE: return "GET_PREFERRED_NETWORK_TYPE";
case RIL_REQUEST_GET_NEIGHBORING_CELL_IDS: return "GET_NEIGHBORING_CELL_IDS";
case RIL_REQUEST_SET_MUTE: return "SET_MUTE";
case RIL_REQUEST_GET_MUTE: return "GET_MUTE";
case RIL_REQUEST_QUERY_CLIP: return "QUERY_CLIP";
case RIL_REQUEST_LAST_DATA_CALL_FAIL_CAUSE: return "LAST_DATA_CALL_FAIL_CAUSE";
case RIL_REQUEST_DATA_CALL_LIST: return "DATA_CALL_LIST";
case RIL_REQUEST_RESET_RADIO: return "RESET_RADIO";
case RIL_REQUEST_OEM_HOOK_RAW: return "OEM_HOOK_RAW";
case RIL_REQUEST_OEM_HOOK_STRINGS: return "OEM_HOOK_STRINGS";
case RIL_REQUEST_SET_BAND_MODE: return "SET_BAND_MODE";
case RIL_REQUEST_QUERY_AVAILABLE_BAND_MODE: return "QUERY_AVAILABLE_BAND_MODE";
case RIL_REQUEST_STK_GET_PROFILE: return "STK_GET_PROFILE";
case RIL_REQUEST_STK_SET_PROFILE: return "STK_SET_PROFILE";
case RIL_REQUEST_STK_SEND_ENVELOPE_COMMAND: return "STK_SEND_ENVELOPE_COMMAND";
case RIL_REQUEST_STK_SEND_TERMINAL_RESPONSE: return "STK_SEND_TERMINAL_RESPONSE";
case RIL_REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM: return "STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM";
case RIL_REQUEST_SCREEN_STATE: return "SCREEN_STATE";
case RIL_REQUEST_EXPLICIT_CALL_TRANSFER: return "EXPLICIT_CALL_TRANSFER";
case RIL_REQUEST_SET_LOCATION_UPDATES: return "SET_LOCATION_UPDATES";
case RIL_REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE:return"CDMA_SET_SUBSCRIPTION_SOURCE";
case RIL_REQUEST_CDMA_SET_ROAMING_PREFERENCE:return"CDMA_SET_ROAMING_PREFERENCE";
case RIL_REQUEST_CDMA_QUERY_ROAMING_PREFERENCE:return"CDMA_QUERY_ROAMING_PREFERENCE";
case RIL_REQUEST_SET_TTY_MODE:return"SET_TTY_MODE";
case RIL_REQUEST_QUERY_TTY_MODE:return"QUERY_TTY_MODE";
case RIL_REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE";
case RIL_REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE:return"CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE";
case RIL_REQUEST_CDMA_FLASH:return"CDMA_FLASH";
case RIL_REQUEST_CDMA_BURST_DTMF:return"CDMA_BURST_DTMF";
case RIL_REQUEST_CDMA_SEND_SMS:return"CDMA_SEND_SMS";
case RIL_REQUEST_CDMA_SMS_ACKNOWLEDGE:return"CDMA_SMS_ACKNOWLEDGE";
case RIL_REQUEST_GSM_GET_BROADCAST_SMS_CONFIG:return"GSM_GET_BROADCAST_SMS_CONFIG";
case RIL_REQUEST_GSM_SET_BROADCAST_SMS_CONFIG:return"GSM_SET_BROADCAST_SMS_CONFIG";
case RIL_REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG:return "CDMA_GET_BROADCAST_SMS_CONFIG";
case RIL_REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG:return "CDMA_SET_BROADCAST_SMS_CONFIG";
case RIL_REQUEST_CDMA_SMS_BROADCAST_ACTIVATION:return "CDMA_SMS_BROADCAST_ACTIVATION";
case RIL_REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY: return"CDMA_VALIDATE_AND_WRITE_AKEY";
case RIL_REQUEST_CDMA_SUBSCRIPTION: return"CDMA_SUBSCRIPTION";
case RIL_REQUEST_CDMA_WRITE_SMS_TO_RUIM: return "CDMA_WRITE_SMS_TO_RUIM";
case RIL_REQUEST_CDMA_DELETE_SMS_ON_RUIM: return "CDMA_DELETE_SMS_ON_RUIM";
case RIL_REQUEST_DEVICE_IDENTITY: return "DEVICE_IDENTITY";
case RIL_REQUEST_EXIT_EMERGENCY_CALLBACK_MODE: return "EXIT_EMERGENCY_CALLBACK_MODE";
case RIL_REQUEST_GET_SMSC_ADDRESS: return "GET_SMSC_ADDRESS";
case RIL_REQUEST_SET_SMSC_ADDRESS: return "SET_SMSC_ADDRESS";
case RIL_REQUEST_REPORT_SMS_MEMORY_STATUS: return "REPORT_SMS_MEMORY_STATUS";
case RIL_REQUEST_REPORT_STK_SERVICE_IS_RUNNING: return "REPORT_STK_SERVICE_IS_RUNNING";
case RIL_REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE: return "CDMA_GET_SUBSCRIPTION_SOURCE";
case RIL_REQUEST_ISIM_AUTHENTICATION: return "ISIM_AUTHENTICATION";
case RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU: return "RIL_REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU";
case RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS: return "RIL_REQUEST_STK_SEND_ENVELOPE_WITH_STATUS";
case RIL_REQUEST_VOICE_RADIO_TECH: return "VOICE_RADIO_TECH";
case RIL_REQUEST_GET_CELL_INFO_LIST: return"GET_CELL_INFO_LIST";
case RIL_REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE: return"SET_UNSOL_CELL_INFO_LIST_RATE";
case RIL_REQUEST_SET_INITIAL_ATTACH_APN: return "RIL_REQUEST_SET_INITIAL_ATTACH_APN";
case RIL_REQUEST_IMS_REGISTRATION_STATE: return "IMS_REGISTRATION_STATE";
case RIL_REQUEST_IMS_SEND_SMS: return "IMS_SEND_SMS";
case RIL_UNSOL_RESPONSE_RADIO_STATE_CHANGED: return "UNSOL_RESPONSE_RADIO_STATE_CHANGED";
case RIL_UNSOL_RESPONSE_CALL_STATE_CHANGED: return "UNSOL_RESPONSE_CALL_STATE_CHANGED";
case RIL_UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED: return "UNSOL_RESPONSE_VOICE_NETWORK_STATE_CHANGED";
case RIL_UNSOL_RESPONSE_NEW_SMS: return "UNSOL_RESPONSE_NEW_SMS";
case RIL_UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT: return "UNSOL_RESPONSE_NEW_SMS_STATUS_REPORT";
case RIL_UNSOL_RESPONSE_NEW_SMS_ON_SIM: return "UNSOL_RESPONSE_NEW_SMS_ON_SIM";
case RIL_UNSOL_ON_USSD: return "UNSOL_ON_USSD";
case RIL_UNSOL_ON_USSD_REQUEST: return "UNSOL_ON_USSD_REQUEST(obsolete)";
case RIL_UNSOL_NITZ_TIME_RECEIVED: return "UNSOL_NITZ_TIME_RECEIVED";
case RIL_UNSOL_SIGNAL_STRENGTH: return "UNSOL_SIGNAL_STRENGTH";
case RIL_UNSOL_STK_SESSION_END: return "UNSOL_STK_SESSION_END";
case RIL_UNSOL_STK_PROACTIVE_COMMAND: return "UNSOL_STK_PROACTIVE_COMMAND";
case RIL_UNSOL_STK_EVENT_NOTIFY: return "UNSOL_STK_EVENT_NOTIFY";
case RIL_UNSOL_STK_CALL_SETUP: return "UNSOL_STK_CALL_SETUP";
case RIL_UNSOL_SIM_SMS_STORAGE_FULL: return "UNSOL_SIM_SMS_STORAGE_FUL";
case RIL_UNSOL_SIM_REFRESH: return "UNSOL_SIM_REFRESH";
case RIL_UNSOL_DATA_CALL_LIST_CHANGED: return "UNSOL_DATA_CALL_LIST_CHANGED";
case RIL_UNSOL_CALL_RING: return "UNSOL_CALL_RING";
case RIL_UNSOL_RESPONSE_SIM_STATUS_CHANGED: return "UNSOL_RESPONSE_SIM_STATUS_CHANGED";
case RIL_UNSOL_RESPONSE_CDMA_NEW_SMS: return "UNSOL_NEW_CDMA_SMS";
case RIL_UNSOL_RESPONSE_NEW_BROADCAST_SMS: return "UNSOL_NEW_BROADCAST_SMS";
case RIL_UNSOL_CDMA_RUIM_SMS_STORAGE_FULL: return "UNSOL_CDMA_RUIM_SMS_STORAGE_FULL";
case RIL_UNSOL_RESTRICTED_STATE_CHANGED: return "UNSOL_RESTRICTED_STATE_CHANGED";
case RIL_UNSOL_ENTER_EMERGENCY_CALLBACK_MODE: return "UNSOL_ENTER_EMERGENCY_CALLBACK_MODE";
case RIL_UNSOL_CDMA_CALL_WAITING: return "UNSOL_CDMA_CALL_WAITING";
case RIL_UNSOL_CDMA_OTA_PROVISION_STATUS: return "UNSOL_CDMA_OTA_PROVISION_STATUS";
case RIL_UNSOL_CDMA_INFO_REC: return "UNSOL_CDMA_INFO_REC";
case RIL_UNSOL_OEM_HOOK_RAW: return "UNSOL_OEM_HOOK_RAW";
case RIL_UNSOL_RINGBACK_TONE: return "UNSOL_RINGBACK_TONE";
case RIL_UNSOL_RESEND_INCALL_MUTE: return "UNSOL_RESEND_INCALL_MUTE";
case RIL_UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED: return "UNSOL_CDMA_SUBSCRIPTION_SOURCE_CHANGED";
case RIL_UNSOL_CDMA_PRL_CHANGED: return "UNSOL_CDMA_PRL_CHANGED";
case RIL_UNSOL_EXIT_EMERGENCY_CALLBACK_MODE: return "UNSOL_EXIT_EMERGENCY_CALLBACK_MODE";
case RIL_UNSOL_RIL_CONNECTED: return "UNSOL_RIL_CONNECTED";
case RIL_UNSOL_VOICE_RADIO_TECH_CHANGED: return "UNSOL_VOICE_RADIO_TECH_CHANGED";
case RIL_UNSOL_CELL_INFO_LIST: return "UNSOL_CELL_INFO_LIST";
case RIL_UNSOL_RESPONSE_IMS_NETWORK_STATE_CHANGED: return "RESPONSE_IMS_NETWORK_STATE_CHANGED";
default: return "<unknown request>";
}
}
} /* namespace android */
| {'content_hash': '0dad8962e4af9c81cfc90c5c743b4f6a', 'timestamp': '', 'source': 'github', 'line_count': 3841, 'max_line_length': 123, 'avg_line_length': 32.84118719083572, 'alnum_prop': 0.6112348683636825, 'repo_name': 'indashnet/InDashNet.Open.UN2000', 'id': '19579393e1c550d4aae23bebf13d96dd558ba799', 'size': '126792', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'android/hardware/ril/libril/ril.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?php
class FriendlyMVC {
var $controller;
function FriendlyMVC() {
// Handle routing
$this->route();
// Get model classes and include them
$this->load_models();
// Run the controller
$this->request();
// Run display
$this->display();
}
function route() {
global $cfg;
// Derive route from REQUEST_URI if not already set
// Allows for support for _GET[route], i.e. backward compatibility with Friendly 0.x
if(!$_GET['route']) {
$_GET['route'] =& $_SERVER['REQUEST_URI'];
$_GET['route'] = preg_replace("/^\/(.*)$/","$1",$_GET['route']);
}
if(preg_match("/\?/",$_GET['route'])) {
$offset = strpos($_GET['route'],"?");
$_GET['route'] = substr($_GET['route'],0,$offset);
}
// Break URI into route array
$_GET['route'] = explode("/",$_GET['route']);
$route =& $_GET['route'];
// Now attempt to correct for subfolder
if($_SERVER['PHP_SELF'] != '/_index.php') {
// Turn filesytem path into an array
$file_path = explode("/",$_SERVER['PHP_SELF']);
array_shift($file_path); // Correcting for leading slash
// Downshifting the filesytem and URL paths together until we
// catch up with the _index file
while($file_path[0] != '_index.php') {
$_base_path[] = $file_path[0];
array_shift($route);
array_shift($file_path);
}
$GLOBALS['base_path'] = implode("/",$_base_path);
}
$_protocol = $_SERVER['HTTPS'] == 'on' ? "https" : "http";
# Set default environment var for the base url
$GLOBALS['http_host'] = "{$_protocol}://".$_SERVER['SERVER_NAME']."/";
$GLOBALS['base_url'] = $GLOBALS['http_host'].$GLOBALS['base_path'].($GLOBALS['base_path'] ? "/" : "");
$GLOBALS['cfg']['base_url'] =& $GLOBALS['base_url'];
define('BASE_URL',$GLOBALS['base_url']);
// EXPERIMENTAL: RegEx-based URL remapping
load_file(FRIENDLY_ROOT."/config/routes.inc.php");
# Default parameter naming
if(is_dir($app_space = FRIENDLY_APP_PATH."{$route[0]}/")) {
$routing_map = array('route' => 'app_space/controller/action/id');
$_params = array(
'app_space' => $route[0],
'controller' => 'home',
'action' => 'index'
);
}
else {
$routing_map = array('route' =>"controller/action/id");
$_params = array(
'controller' => 'home',
'action' => 'index'
);
}
$request_uri = implode("/",$route);
foreach($GLOBALS['routes'] as $_regex => $_map) {
if(preg_match($_regex,$request_uri)) {
$routing_map = $_map;
break;
}
}
$routing_map_names = explode("/",$routing_map['route']);
$y = 0;
for($x = 0; $route[$x]; $x++) {
if($routing_map_names[$x])
$_params[$routing_map_names[$x]] = $route[$x];
$_params['params'][$x] = $route[$x];
}
$_params = array_merge($_params, $routing_map);
$_REQUEST = array_merge($_REQUEST, $_params);
# Set FRIENDLY_APP_SPACE constant to shift into a different set of app folders
if($_REQUEST['app_space'] && file_exists($app_space = FRIENDLY_APP_PATH."{$_REQUEST['app_space']}/")) {
define("FRIENDLY_APP_SPACE",$_REQUEST['app_space']);
$_GET['app'] =& $_REQUEST['app_space'];
array_shift($route);
}
// Assign _GETs incl. default values
$_GET['c'] =& $_REQUEST['controller'];
$_GET['a'] =& $_REQUEST['action'];
$_GET['x'] = $route[2];
$_GET['y'] = $route[3];
$_GET['z'] = $route[4];
$GLOBALS['controller'] = array(
'controller_name' => $_REQUEST['controller'],
'action_name' => $_REQUEST['action'],
);
// Populate _GET[params]
for($x = 2; $_thisParam = $route[$x]; $x++) {
$_GET['params'][$x - 1] = $_thisParam;
}
}
function request() {
global $cfg;
# Normalize our controller & action names.
$c =& $_GET['c'];
$a =& $_GET['a'];
// Global before filters from the config file ## DEPRECATED in 1.0x ##
if($GLOBALS['cfg']['before_filters']) {
$filters = explode(",",$GLOBALS['cfg']['before_filters']);
foreach($filters as $function)
if(function_exists($function)) $function();
}
// Set up path to app folders based on whether we're in the root or an app space
// E.g.: app/controllers vs. app/admin/controllers
if(defined("FRIENDLY_APP_SPACE"))
$_app_path = FRIENDLY_APP_PATH.FRIENDLY_APP_SPACE."/";
else
$_app_path = FRIENDLY_APP_PATH;
// Find and run controller & action
if(file_exists($controlFile = $_app_path."controllers/{$_GET['c']}_controller.php")) {
load_file($controlFile);
if(class_exists($cU = camelize($c)."Controller")) {
$this->controller = new $cU();
}
}
else {
$this->controller = new ApplicationController;
}
// Run _setups
if(method_exists($this->controller,"_globalsetup"))
$this->controller->_globalsetup();
if(method_exists($this->controller,"_setup"))
$this->controller->_setup();
// Run _init to commit any setup changes relevant to Magic Controllers
if(method_exists($this->controller,"_init"))
$this->controller->_init();
// Running before filters as specified in the _setups
if(method_exists($this->controller,"_bootstrap"))
$this->controller->_bootstrap();
// Run action method $a
if(method_exists($this->controller,$a)){
$this->controller->$a();
}
# Filter out internal stuff and send instance vars to Smarty
$this->template_vars = get_object_vars($this->controller);
foreach($this->template_vars as $_k => $_v) {
if($_k[0] == "_")
unset($this->template_vars[$_k]);
}
// Running after filters as specified in the _setups
if(method_exists($this->controller,"_teardown"))
$this->controller->_teardown();
// User-level cleanup function?
if(method_exists($this->controller,"_cleanup"))
$this->controller->_cleanup();
}
function load_models() {
global $cfg;
if(file_exists($env_file = $cfg['basedir']."/config/environment.inc.php"))
load_file($env_file);
if(file_exists($model_dir = "./app/models")) {
$d = dir($dp = $model_dir);
while($f = $d->read()) {
$f = "{$dp}/{$f}";
if(is_file($f) && preg_match("/\.model\.php$/",$f))
load_file($f);
}
$d->close();
}
}
function display() {
global $cfg;
global $smarty;
if($_SESSION['flash']) {
smarty_assign('flash', $_SESSION['flash']['text']);
smarty_assign('flash_class', $_SESSION['flash']['class']);
smarty_assign('problems',$_SESSION['flash']['problems']);
unset($_SESSION['flash']);
}
if($cfg->template_engine == 'smarty') {
if(!is_writeable($smarty->compile_dir))
raise("The compile directory <code>$smarty->compile_dir</code> is not writeable.");
smarty_assign_array($this->template_vars);
}
$smarty->assign('session',$_SESSION);
$smarty->assign('cfg',$cfg);
$smarty->assign('globals',$GLOBALS);
$smarty->assign('controller',$GLOBALS['controller']);
# Set up path to app folders based on whether we're in the root or an app space
# E.g.: app/controllers vs. app/admin/controllers
if(defined("FRIENDLY_APP_SPACE"))
$smarty->template_dir = FRIENDLY_APP_PATH.FRIENDLY_APP_SPACE."/views/";
$controller_name = strtolower($GLOBALS['controller']['controller_name']);
# Allow for ability to set template file in controller
if($this->controller->_template_file) {
$template_file = $this->controller->_template_file;
}
else {
$template_folder = $controller_name;
$template_file = $template_folder."/".$GLOBALS['controller']['action_name'];
}
# Absolute path to template
$path_to_template = $smarty->template_dir . $template_file;
# Find and render action template
$this->render_action($path_to_template,$template_file);
# Find and render layout
if(isset($this->controller->_layout) && $this->controller->_layout)
if(file_exists($smarty->template_dir . ($layoutFile = "_layouts/{$this->controller->_layout}.html") )){
$smarty->clear_compiled_tpl($layoutFile);
$smarty->display($layoutFile);
}
elseif(file_exists($smarty->template_dir . ($layoutFile = "_layouts/{$controller_name}.html") )) {
$smarty->clear_compiled_tpl($layoutFile);
$smarty->display($layoutFile);
}
else
raise("The layout <code>$layoutFile</code> could not be found.");
elseif(file_exists($smarty->template_dir . ($layoutFile = "_layouts/default.html") )) {
$smarty->clear_compiled_tpl($layoutFile);
$smarty->display($layoutFile);
}
else
echo $content_for_layout;
}
function render_action($path_to_template,$template_file){
global $cfg;
global $smarty;
if(file_exists($path_to_template)) {
$smarty->clear_compiled_tpl($template_file);
$content_for_layout = $smarty->fetch($template_file);
$smarty->assign('content_for_layout',$content_for_layout);
}
elseif(file_exists($_t_path = $path_to_template.".php")) {
ob_start();
foreach($this->template_vars as $_k => $_v){
if(!eval("\$this->{$_k}")){
eval("\$this->{$_k} = \$_v;");
}
}
eval("?>".file_get_contents($_t_path));
$content_for_layout = ob_get_contents();
ob_end_clean();
$smarty->assign('content_for_layout',$content_for_layout);
}
elseif(file_exists($path_to_template.".html")) {
$smarty->clear_compiled_tpl($template_file.".html");
$content_for_layout = $smarty->fetch($template_file.".html");
$smarty->assign('content_for_layout',$content_for_layout);
}
elseif(file_exists($file = $path_to_template.".textile")) {
$content_for_layout = textile($smarty->fetch($file));
$smarty->assign('content_for_layout',$content_for_layout);
}
elseif(file_exists($file = $path_to_template.".markdown")) {
$content_for_layout = Markdown($smarty->fetch($file));
$smarty->assign('content_for_layout',$content_for_layout);
}
else {
raise("No template for the action <code>{$_GET['a']}</code>.");
}
}
}
?> | {'content_hash': '0fa6838b2cf09584dece46bf559b54f2', 'timestamp': '', 'source': 'github', 'line_count': 351, 'max_line_length': 108, 'avg_line_length': 28.037037037037038, 'alnum_prop': 0.6024794228228838, 'repo_name': 'ddemaree/friendly-php', 'id': '980c274d8609e5dafbd6e29458730eff25ff002d', 'size': '9841', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_friendly/core/mvc/mvc.class.php', 'mode': '33188', 'license': 'mit', 'language': []} |
<a href="http://github.com/angular/angular.js/edit/master/docs/content/cookbook/buzz.ngdoc" class="improve-docs btn btn-primary"><i class="icon-edit"> </i> Improve this doc</a><h1><code ng:non-bindable=""></code>
<div><span class="hint"></span>
</div>
</h1>
<div><div class="cookbook-page cookbook-resources-buzz-page"><p>External resources are URLs that provide JSON data, which are then rendered with the help of
templates. Angular has a resource factory that can be used to give names to the URLs and then
attach behavior to them. For example you can use the
<a href="http://code.google.com/apis/buzz/v1/getting_started.html#background-operations|">Google Buzz API</a>
to retrieve Buzz activity and comments.</p>
<h3 id="source">Source</h3>
<div source-edit="" source-edit-deps="angular.js script.js" source-edit-html="index.html-178" source-edit-css="" source-edit-js="script.js-177" source-edit-json="" source-edit-unit="" source-edit-scenario="scenario.js-179"></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-178" ng-html-wrap=" angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-178">
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div class="buzz" ng-repeat="item in activities.data.items">
<h2 style="font-size: 15px;" id="-expand-replies-{{itemlinksreplies[0]count}}-">
<img ng-src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a ng-href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">
Expand replies: {{item.links.replies[0].count}}
</a>
</h2>
{{item.object.content | html}}
<div class="reply" ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img ng-src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a ng-href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>:
{{reply.content | html}}
</div>
</div>
</div>
</script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-177"></pre>
<script type="text/ng-template" id="script.js-177">
BuzzController.$inject = ['$scope', '$resource'];
function BuzzController($scope, $resource) {
$scope.userId = 'googlebuzz';
$scope.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt: 'json', callback: 'JSON_CALLBACK'},
{ get: {method: 'JSONP', params: {visibility: '@self'}},
replies: {method: 'JSONP', params: {visibility: '@self', comments: '@comments'}}
});
$scope.fetch = function() {
$scope.activities = $scope.Activity.get({userId:this.userId});
}
$scope.expandReplies = function(activity) {
activity.replies = $scope.Activity.replies({userId: this.userId, activityId: activity.id});
}
};
</script>
</div>
<div class="tab-pane" title="End to end test">
<pre class="prettyprint linenums" ng-set-text="scenario.js-179"></pre>
<script type="text/ng-template" id="scenario.js-179">
xit('fetch buzz and expand', function() {
element(':button:contains(fetch)').click();
expect(repeater('div.buzz').count()).toBeGreaterThan(0);
element('.buzz a:contains(Expand replies):first').click();
expect(repeater('div.reply').count()).toBeGreaterThan(0);
});
</script>
</div>
</div><h3 id="-expand-replies-{{itemlinksreplies[0]count}}-_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="" ng-set-html="index.html-178" ng-eval-javascript="script.js-177"></div>
</div></div>
| {'content_hash': 'a990472b60b19abd4bf0e0e6b5669bd8', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 229, 'avg_line_length': 51.67567567567568, 'alnum_prop': 0.6644874476987448, 'repo_name': 'SekibOmazic/angularjs-modal-bs3', 'id': '279c98c201e8c3d3daa85e4d87091080f91235cc', 'size': '3824', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'vendor/angular-1.2.3/docs/partials/cookbook/buzz.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '12605'}]} |
package com.google.ads.googleads.v11.services;
import com.google.ads.googleads.v11.services.stub.AccountLinkServiceStubSettings;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link AccountLinkServiceClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (googleads.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of createAccountLink to 30 seconds:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* AccountLinkServiceSettings.Builder accountLinkServiceSettingsBuilder =
* AccountLinkServiceSettings.newBuilder();
* accountLinkServiceSettingsBuilder
* .createAccountLinkSettings()
* .setRetrySettings(
* accountLinkServiceSettingsBuilder
* .createAccountLinkSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* AccountLinkServiceSettings accountLinkServiceSettings =
* accountLinkServiceSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class AccountLinkServiceSettings extends ClientSettings<AccountLinkServiceSettings> {
/** Returns the object with the settings used for calls to createAccountLink. */
public UnaryCallSettings<CreateAccountLinkRequest, CreateAccountLinkResponse>
createAccountLinkSettings() {
return ((AccountLinkServiceStubSettings) getStubSettings()).createAccountLinkSettings();
}
/** Returns the object with the settings used for calls to mutateAccountLink. */
public UnaryCallSettings<MutateAccountLinkRequest, MutateAccountLinkResponse>
mutateAccountLinkSettings() {
return ((AccountLinkServiceStubSettings) getStubSettings()).mutateAccountLinkSettings();
}
public static final AccountLinkServiceSettings create(AccountLinkServiceStubSettings stub)
throws IOException {
return new AccountLinkServiceSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return AccountLinkServiceStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return AccountLinkServiceStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return AccountLinkServiceStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return AccountLinkServiceStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return AccountLinkServiceStubSettings.defaultGrpcTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return AccountLinkServiceStubSettings.defaultTransportChannelProvider();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return AccountLinkServiceStubSettings.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected AccountLinkServiceSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
}
/** Builder for AccountLinkServiceSettings. */
public static class Builder extends ClientSettings.Builder<AccountLinkServiceSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(AccountLinkServiceStubSettings.newBuilder(clientContext));
}
protected Builder(AccountLinkServiceSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(AccountLinkServiceStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(AccountLinkServiceStubSettings.newBuilder());
}
public AccountLinkServiceStubSettings.Builder getStubSettingsBuilder() {
return ((AccountLinkServiceStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to createAccountLink. */
public UnaryCallSettings.Builder<CreateAccountLinkRequest, CreateAccountLinkResponse>
createAccountLinkSettings() {
return getStubSettingsBuilder().createAccountLinkSettings();
}
/** Returns the builder for the settings used for calls to mutateAccountLink. */
public UnaryCallSettings.Builder<MutateAccountLinkRequest, MutateAccountLinkResponse>
mutateAccountLinkSettings() {
return getStubSettingsBuilder().mutateAccountLinkSettings();
}
@Override
public AccountLinkServiceSettings build() throws IOException {
return new AccountLinkServiceSettings(this);
}
}
}
| {'content_hash': 'e1ddde3980617aaae87727689084d840', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 99, 'avg_line_length': 40.56382978723404, 'alnum_prop': 0.7644899029635458, 'repo_name': 'googleads/google-ads-java', 'id': '29913edc597c4792d1c2c686497e6576ebf89c9b', 'size': '8221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'google-ads-stubs-v11/src/main/java/com/google/ads/googleads/v11/services/AccountLinkServiceSettings.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '28701198'}]} |
import re
from migrate.changeset import UniqueConstraint
import sqlalchemy
from sqlalchemy import Boolean
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy.engine import reflection
from sqlalchemy.ext.compiler import compiles
from sqlalchemy import func
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy.sql.expression import literal_column
from sqlalchemy.sql.expression import UpdateBase
from sqlalchemy.sql import select
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy.types import NullType
from heat.openstack.common.gettextutils import _
from heat.openstack.common import log as logging
from heat.openstack.common import timeutils
LOG = logging.getLogger(__name__)
_DBURL_REGEX = re.compile(r"[^:]+://([^:]+):([^@]+)@.+")
def sanitize_db_url(url):
match = _DBURL_REGEX.match(url)
if match:
return '%s****:****%s' % (url[:match.start(1)], url[match.end(2):])
return url
class InvalidSortKey(Exception):
message = _("Sort key supplied was not valid.")
# copy from glance/db/sqlalchemy/api.py
def paginate_query(query, model, limit, sort_keys, marker=None,
sort_dir=None, sort_dirs=None):
"""Returns a query with sorting / pagination criteria added.
Pagination works by requiring a unique sort_key, specified by sort_keys.
(If sort_keys is not unique, then we risk looping through values.)
We use the last row in the previous page as the 'marker' for pagination.
So we must return values that follow the passed marker in the order.
With a single-valued sort_key, this would be easy: sort_key > X.
With a compound-values sort_key, (k1, k2, k3) we must do this to repeat
the lexicographical ordering:
(k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3)
We also have to cope with different sort_directions.
Typically, the id of the last row is used as the client-facing pagination
marker, then the actual marker object must be fetched from the db and
passed in to us as marker.
:param query: the query object to which we should add paging/sorting
:param model: the ORM model class
:param limit: maximum number of items to return
:param sort_keys: array of attributes by which results should be sorted
:param marker: the last item of the previous page; we returns the next
results after this value.
:param sort_dir: direction in which results should be sorted (asc, desc)
:param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys
:rtype: sqlalchemy.orm.query.Query
:return: The query with sorting/pagination added.
"""
if 'id' not in sort_keys:
# TODO(justinsb): If this ever gives a false-positive, check
# the actual primary key, rather than assuming its id
LOG.warning(_('Id not in sort_keys; is sort_keys unique?'))
assert(not (sort_dir and sort_dirs))
# Default the sort direction to ascending
if sort_dirs is None and sort_dir is None:
sort_dir = 'asc'
# Ensure a per-column sort direction
if sort_dirs is None:
sort_dirs = [sort_dir for _sort_key in sort_keys]
assert(len(sort_dirs) == len(sort_keys))
# Add sorting
for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs):
try:
sort_dir_func = {
'asc': sqlalchemy.asc,
'desc': sqlalchemy.desc,
}[current_sort_dir]
except KeyError:
raise ValueError(_("Unknown sort direction, "
"must be 'desc' or 'asc'"))
try:
sort_key_attr = getattr(model, current_sort_key)
except AttributeError:
raise InvalidSortKey()
query = query.order_by(sort_dir_func(sort_key_attr))
# Add pagination
if marker is not None:
marker_values = []
for sort_key in sort_keys:
v = getattr(marker, sort_key)
marker_values.append(v)
# Build up an array of sort criteria as in the docstring
criteria_list = []
for i in range(len(sort_keys)):
crit_attrs = []
for j in range(i):
model_attr = getattr(model, sort_keys[j])
crit_attrs.append((model_attr == marker_values[j]))
model_attr = getattr(model, sort_keys[i])
if sort_dirs[i] == 'desc':
crit_attrs.append((model_attr < marker_values[i]))
else:
crit_attrs.append((model_attr > marker_values[i]))
criteria = sqlalchemy.sql.and_(*crit_attrs)
criteria_list.append(criteria)
f = sqlalchemy.sql.or_(*criteria_list)
query = query.filter(f)
if limit is not None:
query = query.limit(limit)
return query
def get_table(engine, name):
"""Returns an sqlalchemy table dynamically from db.
Needed because the models don't work for us in migrations
as models will be far out of sync with the current data.
"""
metadata = MetaData()
metadata.bind = engine
return Table(name, metadata, autoload=True)
class InsertFromSelect(UpdateBase):
"""Form the base for `INSERT INTO table (SELECT ... )` statement."""
def __init__(self, table, select):
self.table = table
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
"""Form the `INSERT INTO table (SELECT ... )` statement."""
return "INSERT INTO %s %s" % (
compiler.process(element.table, asfrom=True),
compiler.process(element.select))
class ColumnError(Exception):
"""Error raised when no column or an invalid column is found."""
def _get_not_supported_column(col_name_col_instance, column_name):
try:
column = col_name_col_instance[column_name]
except KeyError:
msg = _("Please specify column %s in col_name_col_instance "
"param. It is required because column has unsupported "
"type by sqlite).")
raise ColumnError(msg % column_name)
if not isinstance(column, Column):
msg = _("col_name_col_instance param has wrong type of "
"column instance for column %s It should be instance "
"of sqlalchemy.Column.")
raise ColumnError(msg % column_name)
return column
def drop_unique_constraint(migrate_engine, table_name, uc_name, *columns,
**col_name_col_instance):
"""Drop unique constraint from table.
This method drops UC from table and works for mysql, postgresql and sqlite.
In mysql and postgresql we are able to use "alter table" construction.
Sqlalchemy doesn't support some sqlite column types and replaces their
type with NullType in metadata. We process these columns and replace
NullType with the correct column type.
:param migrate_engine: sqlalchemy engine
:param table_name: name of table that contains uniq constraint.
:param uc_name: name of uniq constraint that will be dropped.
:param columns: columns that are in uniq constraint.
:param col_name_col_instance: contains pair column_name=column_instance.
column_instance is instance of Column. These params
are required only for columns that have unsupported
types by sqlite. For example BigInteger.
"""
meta = MetaData()
meta.bind = migrate_engine
t = Table(table_name, meta, autoload=True)
if migrate_engine.name == "sqlite":
override_cols = [
_get_not_supported_column(col_name_col_instance, col.name)
for col in t.columns
if isinstance(col.type, NullType)
]
for col in override_cols:
t.columns.replace(col)
uc = UniqueConstraint(*columns, table=t, name=uc_name)
uc.drop()
def drop_old_duplicate_entries_from_table(migrate_engine, table_name,
use_soft_delete, *uc_column_names):
"""Drop all old rows having the same values for columns in uc_columns.
This method drop (or mark ad `deleted` if use_soft_delete is True) old
duplicate rows form table with name `table_name`.
:param migrate_engine: Sqlalchemy engine
:param table_name: Table with duplicates
:param use_soft_delete: If True - values will be marked as `deleted`,
if False - values will be removed from table
:param uc_column_names: Unique constraint columns
"""
meta = MetaData()
meta.bind = migrate_engine
table = Table(table_name, meta, autoload=True)
columns_for_group_by = [table.c[name] for name in uc_column_names]
columns_for_select = [func.max(table.c.id)]
columns_for_select.extend(columns_for_group_by)
duplicated_rows_select = select(columns_for_select,
group_by=columns_for_group_by,
having=func.count(table.c.id) > 1)
for row in migrate_engine.execute(duplicated_rows_select):
# NOTE(boris-42): Do not remove row that has the biggest ID.
delete_condition = table.c.id != row[0]
is_none = None # workaround for pyflakes
delete_condition &= table.c.deleted_at == is_none
for name in uc_column_names:
delete_condition &= table.c[name] == row[name]
rows_to_delete_select = select([table.c.id]).where(delete_condition)
for row in migrate_engine.execute(rows_to_delete_select).fetchall():
LOG.info(_("Deleting duplicated row with id: %(id)s from table: "
"%(table)s") % dict(id=row[0], table=table_name))
if use_soft_delete:
delete_statement = table.update().\
where(delete_condition).\
values({
'deleted': literal_column('id'),
'updated_at': literal_column('updated_at'),
'deleted_at': timeutils.utcnow()
})
else:
delete_statement = table.delete().where(delete_condition)
migrate_engine.execute(delete_statement)
def _get_default_deleted_value(table):
if isinstance(table.c.id.type, Integer):
return 0
if isinstance(table.c.id.type, String):
return ""
raise ColumnError(_("Unsupported id columns type"))
def _restore_indexes_on_deleted_columns(migrate_engine, table_name, indexes):
table = get_table(migrate_engine, table_name)
insp = reflection.Inspector.from_engine(migrate_engine)
real_indexes = insp.get_indexes(table_name)
existing_index_names = dict(
[(index['name'], index['column_names']) for index in real_indexes])
# NOTE(boris-42): Restore indexes on `deleted` column
for index in indexes:
if 'deleted' not in index['column_names']:
continue
name = index['name']
if name in existing_index_names:
column_names = [table.c[c] for c in existing_index_names[name]]
old_index = Index(name, *column_names, unique=index["unique"])
old_index.drop(migrate_engine)
column_names = [table.c[c] for c in index['column_names']]
new_index = Index(index["name"], *column_names, unique=index["unique"])
new_index.create(migrate_engine)
def change_deleted_column_type_to_boolean(migrate_engine, table_name,
**col_name_col_instance):
if migrate_engine.name == "sqlite":
return _change_deleted_column_type_to_boolean_sqlite(
migrate_engine, table_name, **col_name_col_instance)
insp = reflection.Inspector.from_engine(migrate_engine)
indexes = insp.get_indexes(table_name)
table = get_table(migrate_engine, table_name)
old_deleted = Column('old_deleted', Boolean, default=False)
old_deleted.create(table, populate_default=False)
table.update().\
where(table.c.deleted == table.c.id).\
values(old_deleted=True).\
execute()
table.c.deleted.drop()
table.c.old_deleted.alter(name="deleted")
_restore_indexes_on_deleted_columns(migrate_engine, table_name, indexes)
def _change_deleted_column_type_to_boolean_sqlite(migrate_engine, table_name,
**col_name_col_instance):
insp = reflection.Inspector.from_engine(migrate_engine)
table = get_table(migrate_engine, table_name)
columns = []
for column in table.columns:
column_copy = None
if column.name != "deleted":
if isinstance(column.type, NullType):
column_copy = _get_not_supported_column(col_name_col_instance,
column.name)
else:
column_copy = column.copy()
else:
column_copy = Column('deleted', Boolean, default=0)
columns.append(column_copy)
constraints = [constraint.copy() for constraint in table.constraints]
meta = table.metadata
new_table = Table(table_name + "__tmp__", meta,
*(columns + constraints))
new_table.create()
indexes = []
for index in insp.get_indexes(table_name):
column_names = [new_table.c[c] for c in index['column_names']]
indexes.append(Index(index["name"], *column_names,
unique=index["unique"]))
c_select = []
for c in table.c:
if c.name != "deleted":
c_select.append(c)
else:
c_select.append(table.c.deleted == table.c.id)
ins = InsertFromSelect(new_table, select(c_select))
migrate_engine.execute(ins)
table.drop()
[index.create(migrate_engine) for index in indexes]
new_table.rename(table_name)
new_table.update().\
where(new_table.c.deleted == new_table.c.id).\
values(deleted=True).\
execute()
def change_deleted_column_type_to_id_type(migrate_engine, table_name,
**col_name_col_instance):
if migrate_engine.name == "sqlite":
return _change_deleted_column_type_to_id_type_sqlite(
migrate_engine, table_name, **col_name_col_instance)
insp = reflection.Inspector.from_engine(migrate_engine)
indexes = insp.get_indexes(table_name)
table = get_table(migrate_engine, table_name)
new_deleted = Column('new_deleted', table.c.id.type,
default=_get_default_deleted_value(table))
new_deleted.create(table, populate_default=True)
deleted = True # workaround for pyflakes
table.update().\
where(table.c.deleted == deleted).\
values(new_deleted=table.c.id).\
execute()
table.c.deleted.drop()
table.c.new_deleted.alter(name="deleted")
_restore_indexes_on_deleted_columns(migrate_engine, table_name, indexes)
def _change_deleted_column_type_to_id_type_sqlite(migrate_engine, table_name,
**col_name_col_instance):
# NOTE(boris-42): sqlaclhemy-migrate can't drop column with check
# constraints in sqlite DB and our `deleted` column has
# 2 check constraints. So there is only one way to remove
# these constraints:
# 1) Create new table with the same columns, constraints
# and indexes. (except deleted column).
# 2) Copy all data from old to new table.
# 3) Drop old table.
# 4) Rename new table to old table name.
insp = reflection.Inspector.from_engine(migrate_engine)
meta = MetaData(bind=migrate_engine)
table = Table(table_name, meta, autoload=True)
default_deleted_value = _get_default_deleted_value(table)
columns = []
for column in table.columns:
column_copy = None
if column.name != "deleted":
if isinstance(column.type, NullType):
column_copy = _get_not_supported_column(col_name_col_instance,
column.name)
else:
column_copy = column.copy()
else:
column_copy = Column('deleted', table.c.id.type,
default=default_deleted_value)
columns.append(column_copy)
def is_deleted_column_constraint(constraint):
# NOTE(boris-42): There is no other way to check is CheckConstraint
# associated with deleted column.
if not isinstance(constraint, CheckConstraint):
return False
sqltext = str(constraint.sqltext)
return (sqltext.endswith("deleted in (0, 1)") or
sqltext.endswith("deleted IN (:deleted_1, :deleted_2)"))
constraints = []
for constraint in table.constraints:
if not is_deleted_column_constraint(constraint):
constraints.append(constraint.copy())
new_table = Table(table_name + "__tmp__", meta,
*(columns + constraints))
new_table.create()
indexes = []
for index in insp.get_indexes(table_name):
column_names = [new_table.c[c] for c in index['column_names']]
indexes.append(Index(index["name"], *column_names,
unique=index["unique"]))
ins = InsertFromSelect(new_table, table.select())
migrate_engine.execute(ins)
table.drop()
[index.create(migrate_engine) for index in indexes]
new_table.rename(table_name)
deleted = True # workaround for pyflakes
new_table.update().\
where(new_table.c.deleted == deleted).\
values(deleted=new_table.c.id).\
execute()
# NOTE(boris-42): Fix value of deleted column: False -> "" or 0.
deleted = False # workaround for pyflakes
new_table.update().\
where(new_table.c.deleted == deleted).\
values(deleted=default_deleted_value).\
execute()
| {'content_hash': '27fe7a142e5084aa4f2cdaa690cf55db', 'timestamp': '', 'source': 'github', 'line_count': 481, 'max_line_length': 79, 'avg_line_length': 37.725571725571726, 'alnum_prop': 0.6178772181196958, 'repo_name': 'NeCTAR-RC/heat', 'id': 'b322bc08ec8a70a4be657b0128fbb81c5bb7b8a4', 'size': '18960', 'binary': False, 'copies': '2', 'ref': 'refs/heads/nectar/icehouse', 'path': 'heat/openstack/common/db/sqlalchemy/utils.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Makefile', 'bytes': '5565'}, {'name': 'Python', 'bytes': '4229675'}, {'name': 'Shell', 'bytes': '25339'}]} |
Writing sensor documentation {#documentation}
=====================
It is highly encouraged to provide at least some basic documentation for the
sensors that you want to add to UPM:
- If you don't add documentation, the code review will take very long and
your contribution could be rejected.
- Try to have no warnings in doxygen, this is generally fairly easy.
- Have the specific sensor manufacturer/model & version that you used, if you
support multiple versions please list.
- Simple comments do not need full stops.
- Stick to <80 chars per line even in comments.
- No text is allowed on the same line as the start or end of a comment /** */.
####The sensor block
This is added just before the class declaration in your header(.h) file and has
mandatory fields. For single sensor libraries, this block will actually
follow immediately after the library block. If you have multiple physical
sensors, add this to every one.
Here's an example (disregard the "@verbatim" tags in your actual code):
```
@verbatim
/**
* @library <lib-name>
* @sensor <chip-id>
* @comname <component-name>
* @altname <alt-name>
* @type <component-category>
* @man <component-manufacturer>
* @web <component-weblinks>
* @con <connection-type>
* @kit <component-kit>
*
* @brief Short class/sensor description
*
* Then add a longer
* description here.
*
* @image html <component-img.jpeg>
* @snippet <example-name.cxx> Interesting
*/
@endverbatim
```
- `<lib-name>` When adding to an existing library this needs to match that
library's "@defgroup", otherwise this is a new library name, generally the
same as chip id. *Mandatory*
- `<chip-id>` Usually the chip number used by the sensor. When this is not
available or relevant, use a unique descriptor that makes sense. *Mandatory*
- `<component-name>` A short name for your sensor, can include manufacturer
name. *Mandatory*
- `<alt-name>` Alternative names or chip-ids that your sensor driver might
have or support respectively. *Optional*
- `<component-category>` Mention one or more categories the sensor fits in. Can
be 'other'. *Mandatory*
- `<component-manufacturer>` Sensor manufacturer. Can be 'generic'. *Mandatory*
- `<component-weblinks>` Links to vendors or data-sheets. *Optional*
- `<connection-type>` Specifies how does the sensor connect to the board
*Mandatory*
- `<component-kit>` Specifies if the sensor is part of a kit. *Optional*
Existing groups that can be used for the manufacturer, connection, category and
kit tags are found in the src/upm.h file.
Optionally, a small representative image can be placed in the "docs/images"
subfolder and linked with the "@image" tag.
**Please do not use existing, copyrighted images with your sensors!**
The example should have an 'Interesting' section which will be highlighted as
a code sample in doxygen. Everything in between such tags will show up in the
class documentation when "@snippet" is added at the end of a class docstring.
Tags use this format (in "example-name.cxx"):
```
@verbatim
//! [Interesting]
...example code here...
//! [Interesting]
@endverbatim
```
For more examples take a look at the existing headers in our github repository.
####The library block
New libraries must have the "@brief", "@defgroup" and "@ingroup" tags in one
block. This usually follows the namespace and it is common to have one sensor
per library.
You should end up with something like this:
```
@verbatim
/**
* @brief Short description for entire library
*
* Optional longer description.
*
* @defgroup <lib-name> libupm-<lib-name>
* @ingroup <manufacturer> <connection> <category> (<kit>)
*/
@endverbatim
```
In "@defgroup" use the same `<lib-name>` used in the sensor block. Multiple
sensors can be added to the same library this way.
For "@ingroup" add the same values as in the sensor block for manufacturer,
category, connection type and kit. If you have multiple classes or sensors
per library, only use the "@ingroup" tags that are common for all of them.
| {'content_hash': 'c97685570ccdd72b0a3ca67690366ce0', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 80, 'avg_line_length': 35.49122807017544, 'alnum_prop': 0.7310924369747899, 'repo_name': 'izard/upm', 'id': '44435c223f25f6d6090a249fad630695c334b1df', 'size': '4046', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/documentation.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '124666'}, {'name': 'C++', 'bytes': '906667'}, {'name': 'CMake', 'bytes': '42459'}, {'name': 'Python', 'bytes': '15324'}]} |
/*************************************************************************/
/* test_geometry_2d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef TEST_GEOMETRY_2D_H
#define TEST_GEOMETRY_2D_H
#include "core/math/geometry_2d.h"
#include "thirdparty/doctest/doctest.h"
namespace TestGeometry2D {
TEST_CASE("[Geometry2D] Point in circle") {
CHECK(Geometry2D::is_point_in_circle(Vector2(0, 0), Vector2(0, 0), 1.0));
CHECK(Geometry2D::is_point_in_circle(Vector2(0, 0), Vector2(11.99, 0), 12));
CHECK(Geometry2D::is_point_in_circle(Vector2(-11.99, 0), Vector2(0, 0), 12));
CHECK_FALSE(Geometry2D::is_point_in_circle(Vector2(0, 0), Vector2(12.01, 0), 12));
CHECK_FALSE(Geometry2D::is_point_in_circle(Vector2(-12.01, 0), Vector2(0, 0), 12));
CHECK(Geometry2D::is_point_in_circle(Vector2(7, -42), Vector2(4, -40), 3.7));
CHECK_FALSE(Geometry2D::is_point_in_circle(Vector2(7, -42), Vector2(4, -40), 3.5));
// This tests points on the edge of the circle. They are treated as being inside the circle.
CHECK(Geometry2D::is_point_in_circle(Vector2(1.0, 0.0), Vector2(0, 0), 1.0));
CHECK(Geometry2D::is_point_in_circle(Vector2(0.0, -1.0), Vector2(0, 0), 1.0));
}
TEST_CASE("[Geometry2D] Point in triangle") {
CHECK(Geometry2D::is_point_in_triangle(Vector2(0, 0), Vector2(-1, 1), Vector2(0, -1), Vector2(1, 1)));
CHECK_FALSE(Geometry2D::is_point_in_triangle(Vector2(-1.01, 1.0), Vector2(-1, 1), Vector2(0, -1), Vector2(1, 1)));
CHECK(Geometry2D::is_point_in_triangle(Vector2(3, 2.5), Vector2(1, 4), Vector2(3, 2), Vector2(5, 4)));
CHECK(Geometry2D::is_point_in_triangle(Vector2(-3, -2.5), Vector2(-1, -4), Vector2(-3, -2), Vector2(-5, -4)));
CHECK_FALSE(Geometry2D::is_point_in_triangle(Vector2(0, 0), Vector2(1, 4), Vector2(3, 2), Vector2(5, 4)));
// This tests points on the edge of the triangle. They are treated as being outside the triangle.
// In `is_point_in_circle` and `is_point_in_polygon` they are treated as being inside, so in order the make
// the behaviour consistent this may change in the future (see issue #44717 and PR #44274).
CHECK_FALSE(Geometry2D::is_point_in_triangle(Vector2(1, 1), Vector2(-1, 1), Vector2(0, -1), Vector2(1, 1)));
CHECK_FALSE(Geometry2D::is_point_in_triangle(Vector2(0, 1), Vector2(-1, 1), Vector2(0, -1), Vector2(1, 1)));
}
TEST_CASE("[Geometry2D] Point in polygon") {
Vector<Vector2> p;
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(0, 0), p));
p.push_back(Vector2(-88, 120));
p.push_back(Vector2(-74, -38));
p.push_back(Vector2(135, -145));
p.push_back(Vector2(425, 70));
p.push_back(Vector2(68, 112));
p.push_back(Vector2(-120, 370));
p.push_back(Vector2(-323, -145));
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(-350, 0), p));
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(-110, 60), p));
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(412, 96), p));
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(83, 130), p));
CHECK_FALSE(Geometry2D::is_point_in_polygon(Vector2(-320, -153), p));
CHECK(Geometry2D::is_point_in_polygon(Vector2(0, 0), p));
CHECK(Geometry2D::is_point_in_polygon(Vector2(-230, 0), p));
CHECK(Geometry2D::is_point_in_polygon(Vector2(130, -110), p));
CHECK(Geometry2D::is_point_in_polygon(Vector2(370, 55), p));
CHECK(Geometry2D::is_point_in_polygon(Vector2(-160, 190), p));
// This tests points on the edge of the polygon. They are treated as being inside the polygon.
int c = p.size();
for (int i = 0; i < c; i++) {
const Vector2 &p1 = p[i];
CHECK(Geometry2D::is_point_in_polygon(p1, p));
const Vector2 &p2 = p[(i + 1) % c];
Vector2 midpoint((p1 + p2) * 0.5);
CHECK(Geometry2D::is_point_in_polygon(midpoint, p));
}
}
TEST_CASE("[Geometry2D] Polygon clockwise") {
Vector<Vector2> p;
CHECK_FALSE(Geometry2D::is_polygon_clockwise(p));
p.push_back(Vector2(5, -5));
p.push_back(Vector2(-1, -5));
p.push_back(Vector2(-5, -1));
p.push_back(Vector2(-1, 3));
p.push_back(Vector2(1, 5));
CHECK(Geometry2D::is_polygon_clockwise(p));
p.reverse();
CHECK_FALSE(Geometry2D::is_polygon_clockwise(p));
}
TEST_CASE("[Geometry2D] Line intersection") {
Vector2 r;
CHECK(Geometry2D::line_intersects_line(Vector2(2, 0), Vector2(0, 1), Vector2(0, 2), Vector2(1, 0), r));
CHECK(r.is_equal_approx(Vector2(2, 2)));
CHECK(Geometry2D::line_intersects_line(Vector2(-1, 1), Vector2(1, -1), Vector2(4, 1), Vector2(-1, -1), r));
CHECK(r.is_equal_approx(Vector2(1.5, -1.5)));
CHECK(Geometry2D::line_intersects_line(Vector2(-1, 0), Vector2(-1, -1), Vector2(1, 0), Vector2(1, -1), r));
CHECK(r.is_equal_approx(Vector2(0, 1)));
CHECK_FALSE_MESSAGE(
Geometry2D::line_intersects_line(Vector2(-1, 1), Vector2(1, -1), Vector2(0, 1), Vector2(1, -1), r),
"Parallel lines should not intersect.");
}
TEST_CASE("[Geometry2D] Segment intersection.") {
Vector2 r;
CHECK(Geometry2D::segment_intersects_segment(Vector2(-1, 1), Vector2(1, -1), Vector2(1, 1), Vector2(-1, -1), &r));
CHECK(r.is_equal_approx(Vector2(0, 0)));
CHECK_FALSE(Geometry2D::segment_intersects_segment(Vector2(-1, 1), Vector2(1, -1), Vector2(1, 1), Vector2(0.1, 0.1), &r));
CHECK_FALSE(Geometry2D::segment_intersects_segment(Vector2(-1, 1), Vector2(1, -1), Vector2(0.1, 0.1), Vector2(1, 1), &r));
CHECK_FALSE_MESSAGE(
Geometry2D::segment_intersects_segment(Vector2(-1, 1), Vector2(1, -1), Vector2(0, 1), Vector2(2, -1), &r),
"Parallel segments should not intersect.");
CHECK_MESSAGE(
Geometry2D::segment_intersects_segment(Vector2(0, 0), Vector2(0, 1), Vector2(0, 0), Vector2(1, 0), &r),
"Touching segments should intersect.");
CHECK(r.is_equal_approx(Vector2(0, 0)));
CHECK_MESSAGE(
Geometry2D::segment_intersects_segment(Vector2(0, 1), Vector2(0, 0), Vector2(0, 0), Vector2(1, 0), &r),
"Touching segments should intersect.");
CHECK(r.is_equal_approx(Vector2(0, 0)));
}
TEST_CASE("[Geometry2D] Closest point to segment") {
Vector2 s[] = { Vector2(-4, -4), Vector2(4, 4) };
CHECK(Geometry2D::get_closest_point_to_segment(Vector2(4.1, 4.1), s).is_equal_approx(Vector2(4, 4)));
CHECK(Geometry2D::get_closest_point_to_segment(Vector2(-4.1, -4.1), s).is_equal_approx(Vector2(-4, -4)));
CHECK(Geometry2D::get_closest_point_to_segment(Vector2(-1, 1), s).is_equal_approx(Vector2(0, 0)));
}
TEST_CASE("[Geometry2D] Closest point to uncapped segment") {
Vector2 s[] = { Vector2(-4, -4), Vector2(4, 4) };
CHECK(Geometry2D::get_closest_point_to_segment_uncapped(Vector2(-1, 1), s).is_equal_approx(Vector2(0, 0)));
CHECK(Geometry2D::get_closest_point_to_segment_uncapped(Vector2(-4, -6), s).is_equal_approx(Vector2(-5, -5)));
CHECK(Geometry2D::get_closest_point_to_segment_uncapped(Vector2(4, 6), s).is_equal_approx(Vector2(5, 5)));
}
TEST_CASE("[Geometry2D] Closest points between segments") {
Vector2 c1, c2;
Geometry2D::get_closest_points_between_segments(Vector2(2, 2), Vector2(3, 3), Vector2(4, 4), Vector2(4, 5), c1, c2);
CHECK(c1.is_equal_approx(Vector2(3, 3)));
CHECK(c2.is_equal_approx(Vector2(4, 4)));
Geometry2D::get_closest_points_between_segments(Vector2(0, 1), Vector2(-2, -1), Vector2(0, 0), Vector2(2, -2), c1, c2);
CHECK(c1.is_equal_approx(Vector2(-0.5, 0.5)));
CHECK(c2.is_equal_approx(Vector2(0, 0)));
Geometry2D::get_closest_points_between_segments(Vector2(-1, 1), Vector2(1, -1), Vector2(1, 1), Vector2(-1, -1), c1, c2);
CHECK(c1.is_equal_approx(Vector2(0, 0)));
CHECK(c2.is_equal_approx(Vector2(0, 0)));
}
TEST_CASE("[Geometry2D] Make atlas") {
Vector<Point2i> result;
Size2i size;
Vector<Size2i> r;
r.push_back(Size2i(2, 2));
Geometry2D::make_atlas(r, result, size);
CHECK(size == Size2i(2, 2));
CHECK(result.size() == r.size());
r.clear();
result.clear();
r.push_back(Size2i(1, 2));
r.push_back(Size2i(3, 4));
r.push_back(Size2i(5, 6));
r.push_back(Size2i(7, 8));
Geometry2D::make_atlas(r, result, size);
CHECK(result.size() == r.size());
}
TEST_CASE("[Geometry2D] Polygon intersection") {
Vector<Point2> a;
Vector<Point2> b;
Vector<Vector<Point2>> r;
a.push_back(Point2(30, 60));
a.push_back(Point2(70, 5));
a.push_back(Point2(200, 40));
a.push_back(Point2(80, 200));
SUBCASE("[Geometry2D] Both polygons are empty") {
r = Geometry2D::intersect_polygons(Vector<Point2>(), Vector<Point2>());
CHECK_MESSAGE(r.is_empty(), "Both polygons are empty. The intersection should also be empty.");
}
SUBCASE("[Geometry2D] One polygon is empty") {
r = Geometry2D::intersect_polygons(a, b);
REQUIRE_MESSAGE(r.is_empty(), "One polygon is empty. The intersection should also be empty.");
}
SUBCASE("[Geometry2D] Basic intersection") {
b.push_back(Point2(200, 300));
b.push_back(Point2(90, 200));
b.push_back(Point2(50, 100));
b.push_back(Point2(200, 90));
r = Geometry2D::intersect_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "The polygons should intersect each other with 1 resulting intersection polygon.");
REQUIRE_MESSAGE(r[0].size() == 3, "The resulting intersection polygon should have 3 vertices.");
CHECK(r[0][0].is_equal_approx(Point2(86.52174, 191.30436)));
CHECK(r[0][1].is_equal_approx(Point2(50, 100)));
CHECK(r[0][2].is_equal_approx(Point2(160.52632, 92.63157)));
}
SUBCASE("[Geometry2D] Intersection with one polygon being completely inside the other polygon") {
b.push_back(Point2(80, 100));
b.push_back(Point2(50, 50));
b.push_back(Point2(150, 50));
r = Geometry2D::intersect_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "The polygons should intersect each other with 1 resulting intersection polygon.");
REQUIRE_MESSAGE(r[0].size() == 3, "The resulting intersection polygon should have 3 vertices.");
CHECK(r[0][0].is_equal_approx(b[0]));
CHECK(r[0][1].is_equal_approx(b[1]));
CHECK(r[0][2].is_equal_approx(b[2]));
}
SUBCASE("[Geometry2D] No intersection with 2 non-empty polygons") {
b.push_back(Point2(150, 150));
b.push_back(Point2(250, 100));
b.push_back(Point2(300, 200));
r = Geometry2D::intersect_polygons(a, b);
REQUIRE_MESSAGE(r.is_empty(), "The polygons should not intersect each other.");
}
SUBCASE("[Geometry2D] Intersection with 2 resulting polygons") {
a.clear();
a.push_back(Point2(70, 5));
a.push_back(Point2(140, 7));
a.push_back(Point2(100, 52));
a.push_back(Point2(170, 50));
a.push_back(Point2(60, 125));
b.push_back(Point2(70, 105));
b.push_back(Point2(115, 55));
b.push_back(Point2(90, 15));
b.push_back(Point2(160, 50));
r = Geometry2D::intersect_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 2, "The polygons should intersect each other with 2 resulting intersection polygons.");
REQUIRE_MESSAGE(r[0].size() == 4, "The resulting intersection polygon should have 4 vertices.");
CHECK(r[0][0].is_equal_approx(Point2(70, 105)));
CHECK(r[0][1].is_equal_approx(Point2(115, 55)));
CHECK(r[0][2].is_equal_approx(Point2(112.894737, 51.63158)));
CHECK(r[0][3].is_equal_approx(Point2(159.509537, 50.299728)));
REQUIRE_MESSAGE(r[1].size() == 3, "The intersection polygon should have 3 vertices.");
CHECK(r[1][0].is_equal_approx(Point2(119.692307, 29.846149)));
CHECK(r[1][1].is_equal_approx(Point2(107.706421, 43.33028)));
CHECK(r[1][2].is_equal_approx(Point2(90, 15)));
}
}
TEST_CASE("[Geometry2D] Merge polygons") {
Vector<Point2> a;
Vector<Point2> b;
Vector<Vector<Point2>> r;
a.push_back(Point2(225, 180));
a.push_back(Point2(160, 230));
a.push_back(Point2(20, 212));
a.push_back(Point2(50, 115));
SUBCASE("[Geometry2D] Both polygons are empty") {
r = Geometry2D::merge_polygons(Vector<Point2>(), Vector<Point2>());
REQUIRE_MESSAGE(r.is_empty(), "Both polygons are empty. The union should also be empty.");
}
SUBCASE("[Geometry2D] One polygon is empty") {
r = Geometry2D::merge_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "One polygon is non-empty. There should be 1 resulting merged polygon.");
REQUIRE_MESSAGE(r[0].size() == 4, "The resulting merged polygon should have 4 vertices.");
CHECK(r[0][0].is_equal_approx(a[0]));
CHECK(r[0][1].is_equal_approx(a[1]));
CHECK(r[0][2].is_equal_approx(a[2]));
CHECK(r[0][3].is_equal_approx(a[3]));
}
SUBCASE("[Geometry2D] Basic merge with 2 polygons") {
b.push_back(Point2(180, 190));
b.push_back(Point2(60, 140));
b.push_back(Point2(160, 80));
r = Geometry2D::merge_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "The merged polygons should result in 1 polygon.");
REQUIRE_MESSAGE(r[0].size() == 7, "The resulting merged polygon should have 7 vertices.");
CHECK(r[0][0].is_equal_approx(Point2(174.791077, 161.350967)));
CHECK(r[0][1].is_equal_approx(Point2(225, 180)));
CHECK(r[0][2].is_equal_approx(Point2(160, 230)));
CHECK(r[0][3].is_equal_approx(Point2(20, 212)));
CHECK(r[0][4].is_equal_approx(Point2(50, 115)));
CHECK(r[0][5].is_equal_approx(Point2(81.911758, 126.852943)));
CHECK(r[0][6].is_equal_approx(Point2(160, 80)));
}
SUBCASE("[Geometry2D] Merge with 2 resulting merged polygons (outline and hole)") {
b.push_back(Point2(180, 190));
b.push_back(Point2(140, 125));
b.push_back(Point2(60, 140));
b.push_back(Point2(160, 80));
r = Geometry2D::merge_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 2, "The merged polygons should result in 2 polygons.");
REQUIRE_MESSAGE(!Geometry2D::is_polygon_clockwise(r[0]), "The merged polygon (outline) should be counter-clockwise.");
REQUIRE_MESSAGE(r[0].size() == 7, "The resulting merged polygon (outline) should have 7 vertices.");
CHECK(r[0][0].is_equal_approx(Point2(174.791077, 161.350967)));
CHECK(r[0][1].is_equal_approx(Point2(225, 180)));
CHECK(r[0][2].is_equal_approx(Point2(160, 230)));
CHECK(r[0][3].is_equal_approx(Point2(20, 212)));
CHECK(r[0][4].is_equal_approx(Point2(50, 115)));
CHECK(r[0][5].is_equal_approx(Point2(81.911758, 126.852943)));
CHECK(r[0][6].is_equal_approx(Point2(160, 80)));
REQUIRE_MESSAGE(Geometry2D::is_polygon_clockwise(r[1]), "The resulting merged polygon (hole) should be clockwise.");
REQUIRE_MESSAGE(r[1].size() == 3, "The resulting merged polygon (hole) should have 3 vertices.");
CHECK(r[1][0].is_equal_approx(Point2(98.083069, 132.859421)));
CHECK(r[1][1].is_equal_approx(Point2(158.689453, 155.370377)));
CHECK(r[1][2].is_equal_approx(Point2(140, 125)));
}
}
TEST_CASE("[Geometry2D] Clip polygons") {
Vector<Point2> a;
Vector<Point2> b;
Vector<Vector<Point2>> r;
a.push_back(Point2(225, 180));
a.push_back(Point2(160, 230));
a.push_back(Point2(20, 212));
a.push_back(Point2(50, 115));
SUBCASE("[Geometry2D] Both polygons are empty") {
r = Geometry2D::clip_polygons(Vector<Point2>(), Vector<Point2>());
CHECK_MESSAGE(r.is_empty(), "Both polygons are empty. The clip should also be empty.");
}
SUBCASE("[Geometry2D] Basic clip with one result polygon") {
b.push_back(Point2(250, 170));
b.push_back(Point2(175, 270));
b.push_back(Point2(120, 260));
b.push_back(Point2(25, 80));
r = Geometry2D::clip_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "The clipped polygons should result in 1 polygon.");
REQUIRE_MESSAGE(r[0].size() == 3, "The resulting clipped polygon should have 3 vertices.");
CHECK(r[0][0].is_equal_approx(Point2(100.102173, 222.298843)));
CHECK(r[0][1].is_equal_approx(Point2(20, 212)));
CHECK(r[0][2].is_equal_approx(Point2(47.588089, 122.798492)));
}
SUBCASE("[Geometry2D] Polygon b completely overlaps polygon a") {
b.push_back(Point2(250, 170));
b.push_back(Point2(175, 270));
b.push_back(Point2(10, 210));
b.push_back(Point2(55, 80));
r = Geometry2D::clip_polygons(a, b);
CHECK_MESSAGE(r.is_empty(), "Polygon 'b' completely overlaps polygon 'a'. This should result in no clipped polygons.");
}
SUBCASE("[Geometry2D] Polygon a completely overlaps polygon b") {
b.push_back(Point2(150, 200));
b.push_back(Point2(65, 190));
b.push_back(Point2(80, 140));
r = Geometry2D::clip_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 2, "Polygon 'a' completely overlaps polygon 'b'. This should result in 2 clipped polygons.");
REQUIRE_MESSAGE(r[0].size() == 4, "The resulting clipped polygon should have 4 vertices.");
REQUIRE_MESSAGE(!Geometry2D::is_polygon_clockwise(r[0]), "The resulting clipped polygon (outline) should be counter-clockwise.");
CHECK(r[0][0].is_equal_approx(a[0]));
CHECK(r[0][1].is_equal_approx(a[1]));
CHECK(r[0][2].is_equal_approx(a[2]));
CHECK(r[0][3].is_equal_approx(a[3]));
REQUIRE_MESSAGE(r[1].size() == 3, "The resulting clipped polygon should have 3 vertices.");
REQUIRE_MESSAGE(Geometry2D::is_polygon_clockwise(r[1]), "The resulting clipped polygon (hole) should be clockwise.");
CHECK(r[1][0].is_equal_approx(b[1]));
CHECK(r[1][1].is_equal_approx(b[0]));
CHECK(r[1][2].is_equal_approx(b[2]));
}
}
TEST_CASE("[Geometry2D] Exclude polygons") {
Vector<Point2> a;
Vector<Point2> b;
Vector<Vector<Point2>> r;
a.push_back(Point2(225, 180));
a.push_back(Point2(160, 230));
a.push_back(Point2(20, 212));
a.push_back(Point2(50, 115));
SUBCASE("[Geometry2D] Both polygons are empty") {
r = Geometry2D::exclude_polygons(Vector<Point2>(), Vector<Point2>());
CHECK_MESSAGE(r.is_empty(), "Both polygons are empty. The excluded polygon should also be empty.");
}
SUBCASE("[Geometry2D] One polygon is empty") {
r = Geometry2D::exclude_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 1, "One polygon is non-empty. There should be 1 resulting excluded polygon.");
REQUIRE_MESSAGE(r[0].size() == 4, "The resulting excluded polygon should have 4 vertices.");
CHECK(r[0][0].is_equal_approx(a[0]));
CHECK(r[0][1].is_equal_approx(a[1]));
CHECK(r[0][2].is_equal_approx(a[2]));
CHECK(r[0][3].is_equal_approx(a[3]));
}
SUBCASE("[Geometry2D] Exclude with 2 resulting polygons (outline and hole)") {
b.push_back(Point2(140, 160));
b.push_back(Point2(150, 220));
b.push_back(Point2(40, 200));
b.push_back(Point2(60, 140));
r = Geometry2D::exclude_polygons(a, b);
REQUIRE_MESSAGE(r.size() == 2, "There should be 2 resulting excluded polygons (outline and hole).");
REQUIRE_MESSAGE(r[0].size() == 4, "The resulting excluded polygon should have 4 vertices.");
REQUIRE_MESSAGE(!Geometry2D::is_polygon_clockwise(r[0]), "The resulting excluded polygon (outline) should be counter-clockwise.");
CHECK(r[0][0].is_equal_approx(a[0]));
CHECK(r[0][1].is_equal_approx(a[1]));
CHECK(r[0][2].is_equal_approx(a[2]));
CHECK(r[0][3].is_equal_approx(a[3]));
REQUIRE_MESSAGE(r[1].size() == 4, "The resulting excluded polygon should have 4 vertices.");
REQUIRE_MESSAGE(Geometry2D::is_polygon_clockwise(r[1]), "The resulting excluded polygon (hole) should be clockwise.");
CHECK(r[1][0].is_equal_approx(Point2(40, 200)));
CHECK(r[1][1].is_equal_approx(Point2(150, 220)));
CHECK(r[1][2].is_equal_approx(Point2(140, 160)));
CHECK(r[1][3].is_equal_approx(Point2(60, 140)));
}
}
TEST_CASE("[Geometry2D] Intersect polyline with polygon") {
Vector<Vector2> l;
Vector<Vector2> p;
Vector<Vector<Point2>> r;
l.push_back(Vector2(100, 90));
l.push_back(Vector2(120, 250));
p.push_back(Vector2(225, 180));
p.push_back(Vector2(160, 230));
p.push_back(Vector2(20, 212));
p.push_back(Vector2(50, 115));
SUBCASE("[Geometry2D] Both line and polygon are empty") {
r = Geometry2D::intersect_polyline_with_polygon(Vector<Vector2>(), Vector<Vector2>());
CHECK_MESSAGE(r.is_empty(), "Both line and polygon are empty. The intersection line should also be empty.");
}
SUBCASE("[Geometry2D] Line is non-empty and polygon is empty") {
r = Geometry2D::intersect_polyline_with_polygon(l, Vector<Vector2>());
CHECK_MESSAGE(r.is_empty(), "The polygon is empty while the line is non-empty. The intersection line should be empty.");
}
SUBCASE("[Geometry2D] Basic intersection with 1 resulting intersection line") {
r = Geometry2D::intersect_polyline_with_polygon(l, p);
REQUIRE_MESSAGE(r.size() == 1, "There should be 1 resulting intersection line.");
REQUIRE_MESSAGE(r[0].size() == 2, "The resulting intersection line should have 2 vertices.");
CHECK(r[0][0].is_equal_approx(Vector2(105.711609, 135.692886)));
CHECK(r[0][1].is_equal_approx(Vector2(116.805809, 224.446457)));
}
SUBCASE("[Geometry2D] Complex intersection with 2 resulting intersection lines") {
l.clear();
l.push_back(Vector2(100, 90));
l.push_back(Vector2(190, 255));
l.push_back(Vector2(135, 260));
l.push_back(Vector2(57, 200));
l.push_back(Vector2(50, 170));
l.push_back(Vector2(15, 155));
r = Geometry2D::intersect_polyline_with_polygon(l, p);
REQUIRE_MESSAGE(r.size() == 2, "There should be 2 resulting intersection lines.");
REQUIRE_MESSAGE(r[0].size() == 2, "The resulting intersection line should have 2 vertices.");
CHECK(r[0][0].is_equal_approx(Vector2(129.804565, 144.641693)));
CHECK(r[0][1].is_equal_approx(Vector2(171.527084, 221.132996)));
REQUIRE_MESSAGE(r[1].size() == 4, "The resulting intersection line should have 4 vertices.");
CHECK(r[1][0].is_equal_approx(Vector2(83.15609, 220.120087)));
CHECK(r[1][1].is_equal_approx(Vector2(57, 200)));
CHECK(r[1][2].is_equal_approx(Vector2(50, 170)));
CHECK(r[1][3].is_equal_approx(Vector2(34.980492, 163.563065)));
}
}
TEST_CASE("[Geometry2D] Clip polyline with polygon") {
Vector<Vector2> l;
Vector<Vector2> p;
Vector<Vector<Point2>> r;
l.push_back(Vector2(70, 140));
l.push_back(Vector2(160, 320));
p.push_back(Vector2(225, 180));
p.push_back(Vector2(160, 230));
p.push_back(Vector2(20, 212));
p.push_back(Vector2(50, 115));
SUBCASE("[Geometry2D] Both line and polygon are empty") {
r = Geometry2D::clip_polyline_with_polygon(Vector<Vector2>(), Vector<Vector2>());
CHECK_MESSAGE(r.is_empty(), "Both line and polygon are empty. The clipped line should also be empty.");
}
SUBCASE("[Geometry2D] Polygon is empty and line is non-empty") {
r = Geometry2D::clip_polyline_with_polygon(l, Vector<Vector2>());
REQUIRE_MESSAGE(r.size() == 1, "There should be 1 resulting clipped line.");
REQUIRE_MESSAGE(r[0].size() == 2, "The resulting clipped line should have 2 vertices.");
CHECK(r[0][0].is_equal_approx(l[0]));
CHECK(r[0][1].is_equal_approx(l[1]));
}
SUBCASE("[Geometry2D] Basic clip with 1 resulting clipped line") {
r = Geometry2D::clip_polyline_with_polygon(l, p);
REQUIRE_MESSAGE(r.size() == 1, "There should be 1 resulting clipped line.");
REQUIRE_MESSAGE(r[0].size() == 2, "The resulting clipped line should have 2 vertices.");
CHECK(r[0][0].is_equal_approx(Vector2(111.908401, 223.816803)));
CHECK(r[0][1].is_equal_approx(Vector2(160, 320)));
}
SUBCASE("[Geometry2D] Complex clip with 2 resulting clipped lines") {
l.clear();
l.push_back(Vector2(55, 70));
l.push_back(Vector2(50, 190));
l.push_back(Vector2(120, 165));
l.push_back(Vector2(122, 250));
l.push_back(Vector2(160, 320));
r = Geometry2D::clip_polyline_with_polygon(l, p);
REQUIRE_MESSAGE(r.size() == 2, "There should be 2 resulting clipped lines.");
REQUIRE_MESSAGE(r[0].size() == 3, "The resulting clipped line should have 3 vertices.");
CHECK(r[0][0].is_equal_approx(Vector2(160, 320)));
CHECK(r[0][1].is_equal_approx(Vector2(122, 250)));
CHECK(r[0][2].is_equal_approx(Vector2(121.412682, 225.038757)));
REQUIRE_MESSAGE(r[1].size() == 2, "The resulting clipped line should have 2 vertices.");
CHECK(r[1][0].is_equal_approx(Vector2(53.07737, 116.143021)));
CHECK(r[1][1].is_equal_approx(Vector2(55, 70)));
}
}
} // namespace TestGeometry2D
#endif // TEST_GEOMETRY_2D_H
| {'content_hash': '96bdda8d1fe046b1071097755498bf26', 'timestamp': '', 'source': 'github', 'line_count': 567, 'max_line_length': 132, 'avg_line_length': 44.74603174603175, 'alnum_prop': 0.6569705569350833, 'repo_name': 'Faless/godot', 'id': '3487e4d7e821ba7166917da8cb61794ab185ca45', 'size': '25371', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/core/math/test_geometry_2d.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AIDL', 'bytes': '1633'}, {'name': 'C', 'bytes': '820090'}, {'name': 'C#', 'bytes': '954253'}, {'name': 'C++', 'bytes': '36679303'}, {'name': 'CMake', 'bytes': '538'}, {'name': 'GAP', 'bytes': '62'}, {'name': 'GDScript', 'bytes': '59146'}, {'name': 'GLSL', 'bytes': '802565'}, {'name': 'Java', 'bytes': '512268'}, {'name': 'JavaScript', 'bytes': '184665'}, {'name': 'Kotlin', 'bytes': '16172'}, {'name': 'Makefile', 'bytes': '1421'}, {'name': 'Objective-C', 'bytes': '20550'}, {'name': 'Objective-C++', 'bytes': '315906'}, {'name': 'PowerShell', 'bytes': '2713'}, {'name': 'Python', 'bytes': '427946'}, {'name': 'Shell', 'bytes': '27482'}]} |
#include "ab_filter.h"
#include "sensor.h"
/**
* Sonstige benoetigten Header-Dateien
**/
/*
* Sensor, Filter, Ringpuffer, ... anlegen
*/
/*
* Rinpuffer implementieren
*/
int main(void) {
/**
* Filter, Sensor, Rinpuffer... initialisieren
**/
while(1) { /* Solange Sensor Daten liefert... */
/**
* Bis Rinpuffer voll: Ringpuffer mit Sensordaten füllen
*/
/*
* Falls Rinpuffer voll: Alle Werte filtern und gefilterte
* Werte ausgeben, ggf. mit gnuplot oder so betrachten
*/
}
return 0;
}
| {'content_hash': '28a80059093b96b50d250f6178d638ce', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 62, 'avg_line_length': 12.906976744186046, 'alnum_prop': 0.6, 'repo_name': 'MingjianLiu/vezs', 'id': 'f087ea3bd573f39d6f16d16302efc029d161d060', 'size': '556', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '07_Astree/src/main.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '45402'}, {'name': 'C', 'bytes': '1169277'}, {'name': 'C++', 'bytes': '1002347'}, {'name': 'CMake', 'bytes': '210851'}, {'name': 'GDB', 'bytes': '39'}, {'name': 'Makefile', 'bytes': '908009'}, {'name': 'Objective-C', 'bytes': '3840'}, {'name': 'PHP', 'bytes': '3210'}, {'name': 'Perl', 'bytes': '1212'}, {'name': 'Python', 'bytes': '8032'}, {'name': 'Roff', 'bytes': '16248'}, {'name': 'Shell', 'bytes': '19772'}, {'name': 'Tcl', 'bytes': '1249'}]} |
package user
import (
"time"
"github.com/go-kit/kit/log"
)
type logService struct {
logger log.Logger
next Service
}
// LogMiddleware gien a Logger wraps the next Service with logging capabilities.
func LogMiddleware(logger log.Logger, store string) ServiceMiddleware {
return func(next Service) Service {
logger = log.With(
logger,
"service", "user",
"store", store,
)
return &logService{logger: logger, next: next}
}
}
func (s *logService) Count(ns string, opts QueryOptions) (count int, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"count", count,
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Count",
"namespace", ns,
"opts", opts,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Count(ns, opts)
}
func (s *logService) Put(ns string, input *User) (output *User, err error) {
defer func(begin time.Time) {
// Sanitize passwords
if input != nil {
input.Password = ""
}
if output != nil {
output.Password = ""
}
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Put",
"namespace", ns,
"user_input", input,
"user_output", output,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Put(ns, input)
}
func (s *logService) PutLastRead(
ns string,
userID uint64,
ts time.Time,
) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"lastread_utc", ts.UTC(),
"method", "PutLastRead",
"namespace", ns,
"user_id", userID,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.PutLastRead(ns, userID, ts)
}
func (s *logService) Query(ns string, opts QueryOptions) (list List, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Query",
"namespace", ns,
"query_len", len(list),
"user_query_opts", opts,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Query(ns, opts)
}
func (s *logService) Search(
ns string,
opts QueryOptions,
) (list List, err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Search",
"namespace", ns,
"query_len", len(list),
"user_query_opts", opts,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Search(ns, opts)
}
func (s *logService) Setup(ns string) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Setup",
"namespace", ns,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Setup(ns)
}
func (s *logService) Teardown(ns string) (err error) {
defer func(begin time.Time) {
ps := []interface{}{
"duration_ns", time.Since(begin).Nanoseconds(),
"method", "Teardown",
"namespace", ns,
}
if err != nil {
ps = append(ps, "err", err)
}
_ = s.logger.Log(ps...)
}(time.Now())
return s.next.Teardown(ns)
}
| {'content_hash': 'bed35177069c98ecf9c417981a438747', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 81, 'avg_line_length': 18.824858757062145, 'alnum_prop': 0.5981392557022809, 'repo_name': 'tapglue/snaas', 'id': '05ca7d91befdef1243016f8c3142adc9dd7d93dc', 'size': '3332', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'service/user/logging.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '280074'}, {'name': 'Elm', 'bytes': '67090'}, {'name': 'Go', 'bytes': '3927390'}, {'name': 'HCL', 'bytes': '41611'}, {'name': 'JavaScript', 'bytes': '1712'}, {'name': 'Makefile', 'bytes': '713'}, {'name': 'Shell', 'bytes': '9342'}]} |
package com.mps.deepviolet.api;
import java.io.IOException;
import java.math.BigInteger;
import java.net.UnknownHostException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import javax.net.ssl.SSLHandshakeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of IDVX509Certificate specification
* @author Milton Smith
* @see com.mps.deepviolet.api.IDVX509Certificate
*/
class DVX509Certificate implements IDVX509Certificate {
private static final Logger logger = LoggerFactory.getLogger("com.mps.deepviolet.api.DVX509Certificate");
private final String EOL = System.getProperty("line.separator");
private X509Certificate cert;
private X509Certificate[] chain;
private DVX509Certificate[] dvChain;
private IDVEng eng;
private String signingAlgorithm;
private String signingAlgorithmOID;
private BigInteger certificateSerialNumber;
private int iCertificateVersion;
private String notValidBefore;
private String notValidAfter;
private ValidState iValidityState;
private String subjectDN;
private String issuerDN;
private TrustState iTrustState;
private boolean bSelfSignedCertificate;
private boolean bJavaRootCertificate;
private String certificateFingerPrint;
private HashMap<String,String> nonCritOidMap = new HashMap<String,String>();
private HashMap<String,String> critOidMap = new HashMap<String,String>();
/**
* CTOR
* @param cert X509Certificate to initialize
* @throws DVException Thrown on trouble
*/
DVX509Certificate( IDVEng eng, X509Certificate cert ) throws DVException {
try {
this.cert = cert;
this.eng = eng;
signingAlgorithm = cert.getSigAlgName();
notValidBefore = cert.getNotBefore().toString();
notValidAfter = cert.getNotAfter().toString();
certificateSerialNumber = cert.getSerialNumber();
subjectDN = cert.getSubjectDN().toString();
issuerDN = cert.getIssuerDN().toString();
signingAlgorithmOID = cert.getSigAlgOID();
iCertificateVersion = cert.getVersion();
iTrustState = TrustState.UNKNOWN; //default
//TODO: Signature algorithm is different than a digest algorithm. Need to understand
// if parsing SHA256withRSA into SHA256 will work consistently.
byte[] encx509 = cert.getEncoded();
String sa = signingAlgorithm.substring(0,signingAlgorithm.indexOf("with"));
certificateFingerPrint = CipherSuiteUtil.signerFingerprint(encx509,sa);
//Check certificate validity, start < now < expiration.
try {
try {
cert.checkValidity();
iValidityState = ValidState.VALID;
} catch (CertificateNotYetValidException e) {
iValidityState = ValidState.NOT_YET_VALID;
}
} catch(CertificateExpiredException c) {
iValidityState = ValidState.EXPIRED;
}
// Gather non-critical OIDs
Set<String> oids = cert.getNonCriticalExtensionOIDs();
if (oids != null) {
assignOIDs(nonCritOidMap,oids);
}
// Gather critical OIDs
oids = cert.getCriticalExtensionOIDs();
if (oids != null) {
assignOIDs(critOidMap,oids);
}
// Self-signed or not.
bSelfSignedCertificate = CipherSuiteUtil.isSelfSignedCertificate(cert);
// At this point we have printed all certs returned by the server
// (via getServerCertificateChain()). Note the server does NOT
// return the root CA cert to us. However, we can infer the
// root by checking IssuerDN of the last Intermediate CA and
// the AuthorityKeyIdentifier (if present).
bJavaRootCertificate = CipherSuiteUtil.isJavaRootCertificateDN(cert.getIssuerDN().getName());
// Initialize online only activities. Easy to override in child.
onlineInitializationOnly();
} catch( Exception e ) {
throw new DVException(e);
}
}
/**
* Convience method to allow initialization of some features we don't want to
* execute in offline version. Allows subclasses to easily override and
* block execution of these features.
* @throws DVException Thrown on problems.
*/
void onlineInitializationOnly() throws DVException{
// Assign cert chain
assignCertificateChain();
// Assign the trust state, trusted, untrusted, unknown to the cert
assignTrustState();
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getSigningAlgorithm()
*/
public String getSigningAlgorithm() {
return signingAlgorithm;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCertificateSerialNumber()
*/
public BigInteger getCertificateSerialNumber() {
return certificateSerialNumber;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getSigningAlgorithmOID()
*/
public String getSigningAlgorithmOID(){
return signingAlgorithmOID;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCertificateVersion()
*/
public int getCertificateVersion(){
return iCertificateVersion;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getNotValidBefore()
*/
public String getNotValidBefore(){
return notValidBefore;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getNotValidAfter()
*/
public String getNotValidAfter(){
return notValidAfter;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getValidityState()
*/
public ValidState getValidityState(){
return iValidityState;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getSubjectDN()
*/
public String getSubjectDN(){
return subjectDN;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getIssuerDN()
*/
public String getIssuerDN(){
return issuerDN;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getTrustState()
*/
public TrustState getTrustState(){
return iTrustState;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.isSelfSignedCertificate()
*/
public boolean isSelfSignedCertificate(){
return bSelfSignedCertificate;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.isJavaRootCertificate()
*/
public boolean isJavaRootCertificate(){
return bJavaRootCertificate;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCertificateFingerPrint()
*/
public String getCertificateFingerPrint(){
return certificateFingerPrint;
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getNonCritOIDProperties()
*/
public String[] getNonCritOIDProperties() {
Set<String> oids = nonCritOidMap.keySet();
return oids.toArray(new String[0]);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getNonCritPropertyValue(String)
*/
public String getNonCritPropertyValue(String key) {
if( key==null || !nonCritOidMap.containsKey(key) ) return null;
return nonCritOidMap.get(key);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCritPropertyValue()
*/
public String[] getCritOIDProperties() {
Set<String> oids = critOidMap.keySet();
return oids.toArray(new String[0]);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCritPropertyValue(String)
*/
public String getCritPropertyValue(String key) {
if( key==null || !critOidMap.containsKey(key) ) return null;
return critOidMap.get(key);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.isContainsNonCritPropertyKey()
*/
public boolean isContainsNonCritPropertyKey(String key) {
return nonCritOidMap.containsKey(key);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.isContainsCritPropertyKey()
*/
public boolean isContainsCritPropertyKey(String key) {
return critOidMap.containsKey(key);
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.getCertificateChain()
*/
public synchronized IDVX509Certificate[] getCertificateChain() throws DVException {
if( dvChain != null ) return dvChain;
ArrayList<DVX509Certificate> list = new ArrayList<DVX509Certificate>();
for (X509Certificate lcert : chain ) {
list.add(new DVX509Certificate(eng, lcert));
}
dvChain = list.toArray(new DVX509Certificate[0]);
return dvChain;
}
/**
* Assign OIDs to the key/value store.
* @param lmap Map to insert OIDs
* @param OIDs Set of OIDs to assign.
*/
private void assignOIDs(HashMap<String, String> lmap, Set<String> OIDs) {
for (String oid : OIDs) {
//TODO unsupported oids should be found in logs and improved over time.
String value = UNSUPPORTED_OID;
try {
value = CipherSuiteUtil.getExtensionValue(cert, oid);
} catch (IOException e) {
logger.error("Can't print ASN.1 value", e);
}
lmap.put(CipherSuiteUtil.getOIDKeyName(oid), value);
}
}
/**
* Assign the certificate chain to this certificate.
* @throws DVException Thrown on problems
*/
private void assignCertificateChain() throws DVException {
try {
chain = CipherSuiteUtil.getServerCertificateChain(eng.getDVSession().getURL());
} catch (SSLHandshakeException e ) {
if( e.getMessage().indexOf("PKIX") > 0 ) {
String msg = "Certificate chain failed validation. err=" + e.getMessage();
logger.error(msg,e);
throw new DVException(msg,e);
}else{
String msg = "SSLHandshakeException. err=" + e.getMessage();
logger.error(msg,e);
throw new DVException(msg,e);
}
} catch (Exception e) {
String msg = "Problem fetching certificates. err=" + e.getMessage();
logger.error(msg,e);
throw new DVException(msg,e);
}
}
/**
* The utility of this method is that we don't have the URL of the server
* that this certificate came from. Scenario is we read from file. To check trust
* we need a connection to the server. Here we try to create a host based upon
* some assumptions. If we could check trust without the signing algorithm in
* checkTrustedCertificate( X509Certificate[] certs, URL url) then all this URL finding
* could be eliminated. Need to look into this more. All this is only a best effort to
* establish the trust relationship while offline (e.g., --serverurl not specified).
*/
private void assignTrustState() throws DVException {
try {
//todo should look at a differnt way to do this later
boolean bTrusted = CipherSuiteUtil.checkTrustedCertificate( chain, eng.getDVSession().getURL() );
if( bTrusted ) {
iTrustState = TrustState.TRUSTED;
} else {
iTrustState = TrustState.UNTRUSTED;
}
} catch( KeyStoreException e ) {
iTrustState = TrustState.UNKNOWN;
throw new DVException("Problem accessing keystore, err=" + e.getMessage(),e);
} catch( NoSuchAlgorithmException e ) {
iTrustState = TrustState.UNKNOWN;
throw new DVException("No ciphersuite available, err=" + e.getMessage(),e);
} catch( UnknownHostException e ) {
iTrustState = TrustState.UNKNOWN;
throw new DVException("Unknown host, err=" + e.getMessage(),e);
} catch( IOException e ) {
throw new DVException("File system problem, err=" + e.getMessage(),e);
}
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.toString()
*/
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append(super.toString());
buff.append(EOL);
buff.append("SUBJECTDN");
buff.append('=');
buff.append(subjectDN);
buff.append(EOL);
buff.append("SIGNING_ALGORITHM");
buff.append('=');
buff.append(signingAlgorithm);
buff.append(EOL);
buff.append("CERTIFICATE_FINGERPRINT");
buff.append('=');
buff.append(certificateFingerPrint);
buff.append(EOL);
buff.append("ISSUERDN");
buff.append('=');
buff.append(issuerDN);
buff.append(EOL);
buff.append("VALIDITY_STATE");
buff.append('=');
String state = "<ERROR>";
if( iValidityState == ValidState.EXPIRED ) {
state = "EXPIRED";
} else if ( iValidityState == ValidState.VALID ) {
state = "VALID";
} else if ( iValidityState == ValidState.NOT_YET_VALID ) {
state = "NOT_YET_VALID";
}
buff.append(state);
buff.append(EOL);
buff.append("TRUST_STATE");
buff.append('=');
state = "<ERROR>";
if( iTrustState == TrustState.TRUSTED ) {
state = "TRUSTED";
} else if ( iTrustState == TrustState.UNKNOWN ) {
state = "UNKNOWN";
} else if ( iTrustState == TrustState.UNTRUSTED ) {
state = "UNTRUSTED";
}
buff.append(state);
buff.append(EOL);
buff.append("VALIDITY_NOT_VALID_BEFORE");
buff.append('=');
buff.append(notValidBefore);
buff.append(EOL);
buff.append("VALIDITY_NOT_VALID_AFTER");
buff.append('=');
buff.append(notValidAfter);
buff.append(EOL);
buff.append("CERTIFICATE_SERIAL_NUMBER");
buff.append('=');
buff.append(certificateSerialNumber);
buff.append(EOL);
buff.append("CERTIFICATE_VERSION");
buff.append('=');
buff.append(Integer.toString(iCertificateVersion));
buff.append(EOL);
buff.append("SELF_SIGNED_CERTIFICATE");
buff.append('=');
buff.append(Boolean.toString(bSelfSignedCertificate));
buff.append(EOL);
buff.append("JAVA_ROOT_CERTIFICATE");
buff.append('=');
buff.append(Boolean.toString(bJavaRootCertificate));
buff.append(EOL);
buff.append("SIGNING_ALGORITHM_OID");
buff.append('=');
buff.append(signingAlgorithmOID);
buff.append(EOL);
// Non-crit-OIDs
buff.append("CRIT_OIDS[");
boolean fi = true;
for (String key : critOidMap.keySet()) {
String value = critOidMap.get(key);
if(!fi) {
buff.append(", ");
}
buff.append(key);
buff.append('=');
buff.append(value);
fi=false;
}
buff.append("]");
buff.append(EOL);
// Non-crit-OIDs
buff.append("NON_CRIT_OIDS[");
fi = true;
for (String key : nonCritOidMap.keySet()) {
String value = nonCritOidMap.get(key);
if(!fi) buff.append(", ");
buff.append(key);
buff.append('=');
buff.append(value);
fi=false;
}
buff.append("]");
buff.append(EOL);
return buff.toString();
}
/* (non-Javadoc)
* @see com.mps.deepviolet.api.IDVX509Certificate.equals(Object)
*/
public boolean equals( Object obj ) {
boolean o1=false;
boolean o2=false;
boolean o3=false;
boolean o4=false;
boolean o5=false;
boolean o6=false;
boolean o7=false;
boolean o8=false;
boolean o9=false;
boolean o10=false;
boolean o11=false;
boolean o12=false;
boolean o13=false;
boolean o14=false;
boolean o15=false;
if( obj != null ) {
if( obj instanceof IDVX509Certificate ) {
IDVX509Certificate c = (IDVX509Certificate)obj;
o1 = signingAlgorithm.equals(c.getSigningAlgorithm());
o2 = signingAlgorithmOID.equals(c.getSigningAlgorithmOID());
o3 = iCertificateVersion == c.getCertificateVersion();
o4 = notValidBefore.equals(c.getNotValidBefore());
o5 = notValidAfter.equals(c.getNotValidAfter());
o6 = iValidityState == c.getValidityState();
o7 = subjectDN.equals(c.getSubjectDN());
o8 = issuerDN.equals(c.getIssuerDN());
o9 = iTrustState == c.getTrustState();
o10 = bSelfSignedCertificate;
o11 = bJavaRootCertificate;
o12 = certificateFingerPrint.equals(c.getCertificateFingerPrint());
o13 = true;
for(String key : nonCritOidMap.keySet()) {
if( c.isContainsNonCritPropertyKey(key) ) {
o13 = false;
break;
}
}
o14 = true;
for(String key : critOidMap.keySet()) {
if (c.isContainsCritPropertyKey(key)) {
o14 = false;
break;
}
}
o15 = certificateSerialNumber.equals(c.getCertificateSerialNumber());
}
}
return (o1 && o2 && o3 && o4 && o5 && o6 && o7 && o8 && o9 && o10 && o11 && o12 && o13 && o14 && o15);
}
}
| {'content_hash': '9a7d5d8952edd8cb2a3f10a8b1de65d9', 'timestamp': '', 'source': 'github', 'line_count': 551, 'max_line_length': 116, 'avg_line_length': 29.477313974591652, 'alnum_prop': 0.6902475064647211, 'repo_name': 'spoofzu/DeepViolet', 'id': '0f0234046419be6fb6b8e80af4febd75a85577f7', 'size': '16242', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/mps/deepviolet/api/DVX509Certificate.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '8912'}, {'name': 'Java', 'bytes': '141647'}, {'name': 'Shell', 'bytes': '3528'}]} |
import numpy_eigen
import sm
# Import the the C++ exports from your package library.
from libaslam_backend_python import *
# Import other files in the directory
# from mypyfile import *
class TransformationDv(object):
def __init__(self, transformation, rotationActive=True, translationActive=True ):
if not type(transformation) == sm.Transformation:
raise RuntimeError("The transformation must be an sm transformation")
self.initail_T = transformation
self.q = RotationQuaternionDv(transformation.q())
self.q.setActive(rotationActive)
self.t = EuclideanPointDv(transformation.t())
self.t.setActive(translationActive)
self.basic_dv = TransformationBasicDv(self.q.toExpression(), self.t.toExpression())
self.expression = self.basic_dv.toExpression()
def toExpression(self):
return self.expression
def numDesignVariables(self):
return 2
def designVariable(self, i):
return self.getDesignVariable(i)
def getDesignVariable(self, i):
if i == 0:
return self.q
elif i == 1:
return self.t
else:
raise RuntimeError("Index out of bounds: %d >= 2" % i)
def T(self):
return self.expression.toTransformationMatrix()
| {'content_hash': 'e3d30b2f5807c20ca8f42bccc5ac383f', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 91, 'avg_line_length': 38.11764705882353, 'alnum_prop': 0.6674382716049383, 'repo_name': 'udrg/kalibr', 'id': '62a59a79f687461ccad2140f0ec1272a99745646', 'size': '1341', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'aslam_optimizer/aslam_backend_python/python/aslam_backend/__init__.py', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Arduino', 'bytes': '810'}, {'name': 'C', 'bytes': '8974'}, {'name': 'C++', 'bytes': '3821284'}, {'name': 'CMake', 'bytes': '71612'}, {'name': 'EmberScript', 'bytes': '7049'}, {'name': 'HTML', 'bytes': '1839'}, {'name': 'Makefile', 'bytes': '41'}, {'name': 'Matlab', 'bytes': '5072'}, {'name': 'Objective-C', 'bytes': '546'}, {'name': 'Python', 'bytes': '579615'}, {'name': 'TeX', 'bytes': '306601'}]} |
from bluebottle.bb_donations.models import BaseDonation
from bluebottle.utils.utils import StatusDefinition
GROUP_PERMS = {
'Staff': {
'perms': (
'add_donation', 'change_donation', 'delete_donation',
)
}
}
class Donation(BaseDonation):
def __unicode__(self):
return u'{} for {}'.format(self.amount, self.project)
def get_payment_method(self):
order_payment = self.order.get_latest_order_payment()
if not order_payment:
return '?'
if order_payment.status == StatusDefinition.PLEDGED:
return 'pledge'
if not hasattr(order_payment, 'payment'):
return '?'
return order_payment.payment.method_name
from .signals import *
| {'content_hash': '6e56c5fbd11bb1e1adac9b7a09dd18cd', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 65, 'avg_line_length': 26.785714285714285, 'alnum_prop': 0.616, 'repo_name': 'jfterpstra/bluebottle', 'id': '9d1310d4dee99f35b363ea2d34eae541d761eeb2', 'size': '750', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'bluebottle/donations/models.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '16556'}, {'name': 'HTML', 'bytes': '173443'}, {'name': 'JavaScript', 'bytes': '434'}, {'name': 'PostScript', 'bytes': '2927'}, {'name': 'Python', 'bytes': '1694079'}, {'name': 'Shell', 'bytes': '2951'}, {'name': 'Smarty', 'bytes': '4317'}]} |
// ----------------------------------------------------------------------
// Adaptive music composition engine implementation for interactive systems.
//
// Copyright 2014 Alper Gungormusler. All rights reserved.
//
// ------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using BarelyAPI;
public class NoiseMaker : MonoBehaviour
{
public Texture2D pixel;
public int size;
Musician musician;
float[,] noises;
void Start()
{
musician = FindObjectOfType<Musician>();
musician.Sequencer.AddBeatListener(OnNextBeat);
noises = new float[Screen.width / size + 1, Screen.height / size + 1];
}
void OnGUI()
{
if (musician.IsPlaying || musician.IsPaused)
{
GUI.depth = -100;
Color color = Color.black;
for (int x = 0; x < noises.GetLength(0); ++x)
{
for (int y = 0; y < noises.GetLength(1); ++y)
{
color.a = noises[x, y];
GUI.color = color;
GUI.DrawTexture(new Rect(x * size, y * size, size, size), pixel);
}
}
}
}
void OnNextBeat(Sequencer sequencer)
{
for (int x = 0; x < noises.GetLength(0); ++x)
{
for (int y = 0; y < noises.GetLength(1); ++y)
{
noises[x, y] = RandomNumber.NextFloat(musician.Stress * 0.25f, musician.Stress * 0.25f + musician.Energy * 0.15f + 0.1f);
}
}
}
} | {'content_hash': 'e22ca369d653aaa036ae6f0c5edd6670', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 137, 'avg_line_length': 26.6, 'alnum_prop': 0.47368421052631576, 'repo_name': 'anokta/barelyMusician', 'id': 'dd0ed788a44ab249f9da28b3b91f61f510888faf', 'size': '1598', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dissertation', 'path': 'Assets/barelyMusician/Demo/DemoScene/Scripts/NoiseMaker.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '153278'}]} |
'use strict';
var expect = require('chai').expect;
var utils = require('../lib/utils.js');
function fnCall() {
return utils.fnCall(arguments);
}
describe('utils', function () {
function echoArgs() {
var k, len = arguments.length;
var result = [];
for (k = 0; k < len; ++k) {
result.push(arguments[k]);
}
return result;
}
describe('fnCall', function () {
it('should enable making a function call from an arguments object', function () {
expect(function () {
fnCall();
}).to.throw(TypeError);
expect(fnCall(echoArgs)).to.deep.equal([]);
expect(fnCall(echoArgs, 1)).to.deep.equal([ 1 ]);
expect(fnCall(echoArgs, 1, 2)).to.deep.equal([ 1, 2 ]);
expect(fnCall(echoArgs, 1, 2, 3)).to.deep.equal([ 1, 2, 3 ]);
expect(fnCall(echoArgs, 1, 2, 3, 4)).to.deep.equal([ 1, 2, 3, 4 ]);
expect(fnCall(echoArgs, 1, 2, 3, 4, 5)).to.deep.equal([ 1, 2, 3, 4, 5 ]);
});
it('should enable making an object method call from an arguments object', function () {
var obj = {
echoArgs: function () {
var k, len = arguments.length;
var result = [ this ];
for (k = 0; k < len; ++k) {
result.push(arguments[k]);
}
return result;
}
};
expect(function () {
fnCall(obj);
}).to.throw(TypeError);
expect(fnCall(obj, obj.echoArgs)[0]).to.equal(obj);
expect(fnCall(obj, obj.echoArgs, 1).slice(1)).to.deep.equal([ 1 ]);
expect(fnCall(obj, obj.echoArgs, 1, 2).slice(1)).to.deep.equal([ 1, 2 ]);
expect(fnCall(obj, obj.echoArgs, 1, 2, 3).slice(1)).to.deep.equal([ 1, 2, 3 ]);
expect(fnCall(obj, obj.echoArgs, 1, 2, 3, 4).slice(1)).to.deep.equal([ 1, 2, 3, 4 ]);
expect(fnCall(obj, obj.echoArgs, 1, 2, 3, 4, 5).slice(1)).to.deep.equal([ 1, 2, 3, 4, 5 ]);
expect(fnCall(obj, 'echoArgs')[0]).to.equal(obj);
expect(fnCall(obj, 'echoArgs', 1).slice(1)).to.deep.equal([ 1 ]);
expect(fnCall(obj, 'echoArgs', 1, 2).slice(1)).to.deep.equal([ 1, 2 ]);
expect(fnCall(obj, 'echoArgs', 1, 2, 3).slice(1)).to.deep.equal([ 1, 2, 3 ]);
expect(fnCall(obj, 'echoArgs', 1, 2, 3, 4).slice(1)).to.deep.equal([ 1, 2, 3, 4 ]);
expect(fnCall(obj, 'echoArgs', 1, 2, 3, 4, 5).slice(1)).to.deep.equal([ 1, 2, 3, 4, 5 ]);
});
});
describe('invoke', function () {
it('requires at least 1 element in the arg parameter', function () {
expect(function () {
utils.invoke([]);
}).to.throw(TypeError);
});
it('requires a callback as second parameter', function () {
expect(function () {
utils.invoke([ function () {} ]);
}).to.throw(TypeError);
});
});
describe('objectInvoke', function () {
it('requires at least 1 element in the arg parameter', function () {
expect(function () {
utils.objectInvoke([]);
}).to.throw(TypeError);
});
it('requires a callback as second parameter', function () {
expect(function () {
utils.objectInvoke([ {} ]);
}).to.throw(TypeError);
expect(function () {
utils.objectInvoke([ {}, 42 ]);
}).to.throw(TypeError);
});
it('requires a valid method to be passed', function () {
expect(function () {
utils.objectInvoke([ {}, 42 ], function () {});
}).to.throw(TypeError);
});
});
});
| {'content_hash': '07c63126e7083e381eddb2aa544a38dc', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 103, 'avg_line_length': 41.03191489361702, 'alnum_prop': 0.4835364272750843, 'repo_name': 'brian-murray35/node-sap-promise', 'id': '136f8a4165d3563e24a63b67b587353c8fcafbce', 'size': '3857', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/utils.spec.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '174274'}]} |
package cli_test
import (
"flag"
"testing"
"time"
"github.com/austinpray/bump-bedrock/Godeps/_workspace/src/github.com/codegangsta/cli"
)
func TestNewContext(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("myflag", 12, "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Int("myflag", 42, "doc")
command := cli.Command{Name: "mycommand"}
c := cli.NewContext(nil, set, globalSet)
c.Command = command
expect(t, c.Int("myflag"), 12)
expect(t, c.GlobalInt("myflag"), 42)
expect(t, c.Command.Name, "mycommand")
}
func TestContext_Int(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("myflag", 12, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Int("myflag"), 12)
}
func TestContext_Duration(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Duration("myflag", time.Duration(12*time.Second), "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Duration("myflag"), time.Duration(12*time.Second))
}
func TestContext_String(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.String("myflag", "hello world", "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.String("myflag"), "hello world")
}
func TestContext_Bool(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Bool("myflag"), false)
}
func TestContext_BoolT(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", true, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.BoolT("myflag"), true)
}
func TestContext_Args(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
c := cli.NewContext(nil, set, set)
set.Parse([]string{"--myflag", "bat", "baz"})
expect(t, len(c.Args()), 2)
expect(t, c.Bool("myflag"), true)
}
func TestContext_IsSet(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
set.String("otherflag", "hello world", "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Bool("myflagGlobal", true, "doc")
c := cli.NewContext(nil, set, globalSet)
set.Parse([]string{"--myflag", "bat", "baz"})
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
expect(t, c.IsSet("myflag"), true)
expect(t, c.IsSet("otherflag"), false)
expect(t, c.IsSet("bogusflag"), false)
expect(t, c.IsSet("myflagGlobal"), false)
}
func TestContext_GlobalIsSet(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
set.String("otherflag", "hello world", "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Bool("myflagGlobal", true, "doc")
globalSet.Bool("myflagGlobalUnset", true, "doc")
c := cli.NewContext(nil, set, globalSet)
set.Parse([]string{"--myflag", "bat", "baz"})
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
expect(t, c.GlobalIsSet("myflag"), false)
expect(t, c.GlobalIsSet("otherflag"), false)
expect(t, c.GlobalIsSet("bogusflag"), false)
expect(t, c.GlobalIsSet("myflagGlobal"), true)
expect(t, c.GlobalIsSet("myflagGlobalUnset"), false)
expect(t, c.GlobalIsSet("bogusGlobal"), false)
}
func TestContext_NumFlags(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
set.String("otherflag", "hello world", "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Bool("myflagGlobal", true, "doc")
c := cli.NewContext(nil, set, globalSet)
set.Parse([]string{"--myflag", "--otherflag=foo"})
globalSet.Parse([]string{"--myflagGlobal"})
expect(t, c.NumFlags(), 2)
}
| {'content_hash': '8de844ea8a10691dbd76c86b9c44fbec', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 86, 'avg_line_length': 31.34234234234234, 'alnum_prop': 0.6651336590974418, 'repo_name': 'austinpray/bump-bedrock', 'id': 'd2a26895a097db3659922d67b886b82d6f6293ec', 'size': '3479', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Godeps/_workspace/src/github.com/codegangsta/cli/context_test.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '10762'}, {'name': 'Makefile', 'bytes': '562'}]} |
title: " "
layout: splash
author_profile: false
hide_title: true
header:
image: /assets/images/bonsai-lettering.svg
overlay_color: "#5e616c"
cta_label: "<i class='fa fa-download'></i> Install Now"
cta_url: /docs/articles/installation.html
cta_image: /assets/images/bonsai-banner.svg
gallery:
- url: /assets/images/fishtracking.jpg
image_path: /assets/images/fishtracking-th.jpg
title: "Small animal tracking"
- url: https://www.youtube.com/watch?v=mJDV07ptQFk
image_path: /assets/images/vr-th.jpg
title: "Exploring Neural Data in VR"
- url: https://www.youtube.com/watch?v=srcqJXd6Vz4&t=12m30s
image_path: /assets/images/servoing-th.jpg
title: "Visual servoing"
---
<section id="highlights">
<div style="width: 100%;text-align: center;">
<a href="#reactive" class="btn btn--inverse padded"><img src="/assets/images/icon-reactive.svg" /><br>Reactive Algebra</a>
<a href="#run-and-visualize" class="btn btn--inverse padded"><img src="/assets/images/icon-visualizer.svg" /><br>Run and Visualize</a>
<a href="#community" class="btn btn--inverse padded"><img src="/assets/images/icon-community.svg" /><br>Open Community</a>
<a href="#extensions" class="btn btn--inverse padded"><img src="/assets/images/icon-extensions.svg" /><br>Extensions</a>
</div>
</section>
<section id="reactive">
<div class="splash-header">
<div class="splash-image">
<img src="/assets/images/sampleframe.svg" />
</div>
<div class="splash-block">
<h2>Visual programming language</h2>
<p>Naturally orchestrate complex networks of sensors and express temporal logic seamlessly. Assemble interactive systems using a solid visual algebra built on reactive programming.</p>
</div>
</div>
</section>
<section id="run-and-visualize">
<div class="splash-header">
<div class="splash-block">
<h2>Easy to compile, run, and visualize</h2>
<p>Compile and run high-performant workflows instantly, and inspect the results in real-time. Integrate your systems with other languages and frameworks through sockets and C#, or batch execute from the command-line.</p>
</div>
<div class="splash-image">
<img src="/assets/images/subtraction.png" />
</div>
</div>
</section>
<section id="community">
<div class="splash-header">
<div class="splash-image">
<img src="/assets/images/bonsai-packages.svg" />
</div>
<div class="splash-block">
<h2>Join an open community</h2>
<p>Bonsai is powering thousands of experiments around the world. Join a community of scientists passionate about making and understanding their own tools.</p>
</div>
</div>
</section>
<section id="extensions">
<div class="splash-header">
<div class="splash-block">
<h2>Extensible toolbox</h2>
<p>Install new packages to interface directly with the next-generation open-hardware tools in neuroscience. Add your own support for cameras, microcontrollers, and algorithms with built-in scripting and extensibility support.</p>
</div>
<div class="splash-image">
<img src="/assets/images/devices.jpg" />
</div>
</div>
</section>
| {'content_hash': 'f2247ea79d796a59a570faa2ca080632', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 235, 'avg_line_length': 40.41025641025641, 'alnum_prop': 0.6925761421319797, 'repo_name': 'bonsai-rx/bonsai-rx.github.io', 'id': '99ac5ae201e9709a46363a04a93852446c301002', 'size': '3156', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '14472'}, {'name': 'JavaScript', 'bytes': '638'}, {'name': 'Ruby', 'bytes': '2157'}, {'name': 'SCSS', 'bytes': '1985'}]} |
<?php
namespace spec\Pegasus\Application\VagrantTransient;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EnvironmentsSpec extends ObjectBehavior
{
function it_is_initializable()
{
$this->shouldHaveType('Pegasus\Application\VagrantTransient\Environments');
}
}
| {'content_hash': '6789666921f44cc38caa38daa566f076', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 83, 'avg_line_length': 21.0, 'alnum_prop': 0.7619047619047619, 'repo_name': 'philelson/VagrantTransient', 'id': '46e6969fa46c1ae3b97a91ccbce471ad2b93c84f', 'size': '294', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/src/spec/Pegasus/Application/VagrantTransient/EnvironmentsSpec.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '55021'}, {'name': 'Shell', 'bytes': '778'}]} |
package org.hl7.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for COCT_MT300000UV04.SupplyOrder complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="COCT_MT300000UV04.SupplyOrder">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{urn:hl7-org:v3}InfrastructureRootElements"/>
* <element name="effectiveTime" type="{urn:hl7-org:v3}IVL_TS" minOccurs="0"/>
* <element name="repeatNumber" type="{urn:hl7-org:v3}IVL_INT" minOccurs="0"/>
* </sequence>
* <attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/>
* <attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" />
* <attribute name="classCode" use="required" type="{urn:hl7-org:v3}ActClassSupply" />
* <attribute name="moodCode" use="required" type="{urn:hl7-org:v3}ActMood" fixed="RQO" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "COCT_MT300000UV04.SupplyOrder", propOrder = {
"realmCode",
"typeId",
"templateId",
"effectiveTime",
"repeatNumber"
})
public class COCTMT300000UV04SupplyOrder {
protected List<CS> realmCode;
protected II typeId;
protected List<II> templateId;
protected IVLTS effectiveTime;
protected IVLINT repeatNumber;
@XmlAttribute(name = "nullFlavor")
protected List<String> nullFlavor;
@XmlAttribute(name = "classCode", required = true)
protected ActClassSupply classCode;
@XmlAttribute(name = "moodCode", required = true)
protected List<String> moodCode;
/**
* Gets the value of the realmCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the realmCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRealmCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CS }
*
*
*/
public List<CS> getRealmCode() {
if (realmCode == null) {
realmCode = new ArrayList<CS>();
}
return this.realmCode;
}
/**
* Gets the value of the typeId property.
*
* @return
* possible object is
* {@link II }
*
*/
public II getTypeId() {
return typeId;
}
/**
* Sets the value of the typeId property.
*
* @param value
* allowed object is
* {@link II }
*
*/
public void setTypeId(II value) {
this.typeId = value;
}
/**
* Gets the value of the templateId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the templateId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTemplateId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link II }
*
*
*/
public List<II> getTemplateId() {
if (templateId == null) {
templateId = new ArrayList<II>();
}
return this.templateId;
}
/**
* Gets the value of the effectiveTime property.
*
* @return
* possible object is
* {@link IVLTS }
*
*/
public IVLTS getEffectiveTime() {
return effectiveTime;
}
/**
* Sets the value of the effectiveTime property.
*
* @param value
* allowed object is
* {@link IVLTS }
*
*/
public void setEffectiveTime(IVLTS value) {
this.effectiveTime = value;
}
/**
* Gets the value of the repeatNumber property.
*
* @return
* possible object is
* {@link IVLINT }
*
*/
public IVLINT getRepeatNumber() {
return repeatNumber;
}
/**
* Sets the value of the repeatNumber property.
*
* @param value
* allowed object is
* {@link IVLINT }
*
*/
public void setRepeatNumber(IVLINT value) {
this.repeatNumber = value;
}
/**
* Gets the value of the nullFlavor property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nullFlavor property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNullFlavor().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNullFlavor() {
if (nullFlavor == null) {
nullFlavor = new ArrayList<String>();
}
return this.nullFlavor;
}
/**
* Gets the value of the classCode property.
*
* @return
* possible object is
* {@link ActClassSupply }
*
*/
public ActClassSupply getClassCode() {
return classCode;
}
/**
* Sets the value of the classCode property.
*
* @param value
* allowed object is
* {@link ActClassSupply }
*
*/
public void setClassCode(ActClassSupply value) {
this.classCode = value;
}
/**
* Gets the value of the moodCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the moodCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMoodCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getMoodCode() {
if (moodCode == null) {
moodCode = new ArrayList<String>();
}
return this.moodCode;
}
}
| {'content_hash': 'eed3e9c9dbbbe0bf64f53b884b6afaff', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 99, 'avg_line_length': 27.273062730627306, 'alnum_prop': 0.5514815315924774, 'repo_name': 'KRMAssociatesInc/eHMP', 'id': '6b43d7a082705df2617dcd4b96a6ca5f1e2cb67b', 'size': '7391', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/mvi/org/hl7/v3/COCTMT300000UV04SupplyOrder.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '10075'}, {'name': 'CSS', 'bytes': '1228354'}, {'name': 'CoffeeScript', 'bytes': '30627'}, {'name': 'FreeMarker', 'bytes': '12950'}, {'name': 'Genshi', 'bytes': '6980967'}, {'name': 'Gherkin', 'bytes': '2803173'}, {'name': 'Groovy', 'bytes': '27170'}, {'name': 'HTML', 'bytes': '2911048'}, {'name': 'Java', 'bytes': '15034883'}, {'name': 'JavaScript', 'bytes': '14292592'}, {'name': 'M', 'bytes': '771002'}, {'name': 'PHP', 'bytes': '3146'}, {'name': 'Pascal', 'bytes': '1280773'}, {'name': 'Python', 'bytes': '4483'}, {'name': 'Ruby', 'bytes': '2310218'}, {'name': 'Shell', 'bytes': '39641'}, {'name': 'XSLT', 'bytes': '327236'}]} |
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createServerRender, createClientRender } from 'test/utils';
import Portal from './Portal';
describe('<Portal />', () => {
const serverRender = createServerRender();
const render = createClientRender();
describe('server-side', () => {
before(function beforeHook() {
// Only run the test on node.
if (!/jsdom/.test(window.navigator.userAgent)) {
this.skip();
}
});
it('render nothing on the server', () => {
const markup1 = serverRender(<div>Bar</div>);
expect(markup1.text()).to.equal('Bar');
let markup2;
expect(() => {
markup2 = serverRender(
<Portal>
<div>Bar</div>
</Portal>,
);
}).toErrorDev(
// Known issue due to using SSR APIs in a browser environment.
// We use 2x useLayoutEffect in the component.
[
'Warning: useLayoutEffect does nothing on the server',
'Warning: useLayoutEffect does nothing on the server',
],
);
expect(markup2.text()).to.equal('');
});
});
describe('ref', () => {
it('should have access to the mountNode when disabledPortal={false}', () => {
const refSpy = spy();
const { unmount } = render(
<Portal ref={refSpy}>
<h1>Foo</h1>
</Portal>,
);
expect(refSpy.args).to.deep.equal([[document.body]]);
unmount();
expect(refSpy.args).to.deep.equal([[document.body], [null]]);
});
it('should have access to the mountNode when disabledPortal={true}', () => {
const refSpy = spy();
const { unmount } = render(
<Portal disablePortal ref={refSpy}>
<h1 className="woofPortal">Foo</h1>
</Portal>,
);
const mountNode = document.querySelector('.woofPortal');
expect(refSpy.args).to.deep.equal([[mountNode]]);
unmount();
expect(refSpy.args).to.deep.equal([[mountNode], [null]]);
});
it('should have access to the mountNode when switching disabledPortal', () => {
const refSpy = spy();
const { setProps, unmount } = render(
<Portal disablePortal ref={refSpy}>
<h1 className="woofPortal">Foo</h1>
</Portal>,
);
const mountNode = document.querySelector('.woofPortal');
expect(refSpy.args).to.deep.equal([[mountNode]]);
setProps({
disablePortal: false,
ref: refSpy,
});
expect(refSpy.args).to.deep.equal([[mountNode], [null], [document.body]]);
unmount();
expect(refSpy.args).to.deep.equal([[mountNode], [null], [document.body], [null]]);
});
});
it('should render in a different node', () => {
render(
<div id="test1">
<h1 className="woofPortal1">Foo</h1>
<Portal>
<h1 className="woofPortal2">Foo</h1>
</Portal>
</div>,
);
const rootElement = document.querySelector('#test1');
expect(rootElement.contains(document.querySelector('.woofPortal1'))).to.equal(true);
expect(rootElement.contains(document.querySelector('.woofPortal2'))).to.equal(false);
});
it('should unmount when parent unmounts', () => {
function Child() {
const containerRef = React.useRef();
return (
<div>
<div ref={containerRef} />
<Portal container={() => containerRef.current}>
<div id="test1" />
</Portal>
</div>
);
}
function Parent(props) {
const { show = true } = props;
return <div>{show ? <Child /> : null}</div>;
}
const { setProps } = render(<Parent />);
expect(document.querySelectorAll('#test1').length).to.equal(1);
setProps({ show: false });
expect(document.querySelectorAll('#test1').length).to.equal(0);
});
it('should render overlay into container (document)', () => {
render(
<Portal>
<div className="test2" />
<div className="test2" />
</Portal>,
);
expect(document.querySelectorAll('.test2').length).to.equal(2);
});
it('should render overlay into container (DOMNode)', () => {
const container = document.createElement('div');
render(
<Portal container={container}>
<div id="test2" />
</Portal>,
);
expect(container.querySelectorAll('#test2').length).to.equal(1);
});
it('should change container on prop change', () => {
function ContainerTest(props) {
const { containerElement = false, disablePortal = true } = props;
const containerRef = React.useRef();
const container = React.useCallback(() => (containerElement ? containerRef.current : null), [
containerElement,
]);
return (
<span>
<strong ref={containerRef} />
<Portal disablePortal={disablePortal} container={container}>
<div id="test3" />
</Portal>
</span>
);
}
const { setProps } = render(<ContainerTest />);
expect(document.querySelector('#test3').parentElement.nodeName).to.equal('SPAN');
setProps({
containerElement: true,
disablePortal: true,
});
expect(document.querySelector('#test3').parentElement.nodeName).to.equal('SPAN');
setProps({
containerElement: true,
disablePortal: false,
});
expect(document.querySelector('#test3').parentElement.nodeName).to.equal('STRONG');
setProps({
containerElement: false,
disablePortal: false,
});
expect(document.querySelector('#test3').parentElement.nodeName).to.equal('BODY');
});
it('should call ref after child effect', () => {
const callOrder = [];
const handleRef = (node) => {
if (node) {
callOrder.push('ref');
}
};
const updateFunction = () => {
callOrder.push('effect');
};
function Test(props) {
const { container } = props;
React.useEffect(() => {
updateFunction();
}, [container]);
return (
<Portal ref={handleRef} container={container}>
<div />
</Portal>
);
}
const { setProps } = render(<Test container={document.createElement('div')} />);
setProps({ container: null });
setProps({ container: document.createElement('div') });
setProps({ container: null });
expect(callOrder).to.deep.equal([
'effect',
'ref',
'effect',
'ref',
'effect',
'ref',
'effect',
'ref',
]);
});
});
| {'content_hash': 'b883cb1ba9a09bb064766ed7c9cbcca0', 'timestamp': '', 'source': 'github', 'line_count': 224, 'max_line_length': 99, 'avg_line_length': 29.147321428571427, 'alnum_prop': 0.5688466840251187, 'repo_name': 'callemall/material-ui', 'id': 'd1fa9ec7f60199c4896adf04956c16d7101cabc0', 'size': '6529', 'binary': False, 'copies': '1', 'ref': 'refs/heads/next', 'path': 'packages/material-ui-unstyled/src/Portal/Portal.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '302'}, {'name': 'JavaScript', 'bytes': '1758519'}, {'name': 'Shell', 'bytes': '144'}, {'name': 'TypeScript', 'bytes': '27469'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Thu Feb 27 18:45:00 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.irian.ankor.servlet.polling (Ankor - Project 0.1 API)</title>
<meta name="date" content="2014-02-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../at/irian/ankor/servlet/polling/package-summary.html" target="classFrame">at.irian.ankor.servlet.polling</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="RequestFinishedEvent.Listener.html" title="interface in at.irian.ankor.servlet.polling" target="classFrame"><i>RequestFinishedEvent.Listener</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AnkorServlet.html" title="class in at.irian.ankor.servlet.polling" target="classFrame">AnkorServlet</a></li>
<li><a href="AnkorServletContextListener.html" title="class in at.irian.ankor.servlet.polling" target="classFrame">AnkorServletContextListener</a></li>
<li><a href="RequestFinishedEvent.html" title="class in at.irian.ankor.servlet.polling" target="classFrame">RequestFinishedEvent</a></li>
<li><a href="ServletMessageBus.html" title="class in at.irian.ankor.servlet.polling" target="classFrame">ServletMessageBus</a></li>
</ul>
</div>
</body>
</html>
| {'content_hash': '930ac5d5dd53c762241be0858aa9b5d4', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 166, 'avg_line_length': 57.666666666666664, 'alnum_prop': 0.7167630057803468, 'repo_name': 'ankor-io/ankor-framework', 'id': 'a3123d6ab4729aa3617ff2fed174a707f090aaf7', 'size': '1557', 'binary': False, 'copies': '1', 'ref': 'refs/heads/stable', 'path': 'website/ankorsite/static/javadoc/apidocs-0.1/at/irian/ankor/servlet/polling/package-frame.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '526'}, {'name': 'C', 'bytes': '12173'}, {'name': 'C#', 'bytes': '157078'}, {'name': 'CSS', 'bytes': '10636'}, {'name': 'CoffeeScript', 'bytes': '48194'}, {'name': 'HTML', 'bytes': '17806'}, {'name': 'Java', 'bytes': '751745'}, {'name': 'JavaScript', 'bytes': '290740'}, {'name': 'Makefile', 'bytes': '811'}, {'name': 'Objective-C', 'bytes': '114772'}, {'name': 'PowerShell', 'bytes': '3261'}, {'name': 'Python', 'bytes': '17835'}, {'name': 'Shell', 'bytes': '36'}]} |
package com.allanbank.mongodb.demo.coordination.group;
/**
* GroupListener provides notification of changes to the members of a group.
*
* @copyright 2013, Allanbank Consulting, Inc., All Rights Reserved
*/
public interface GroupListener {
/**
* Notification that a member has been added. The {@code context} includes
* the root context string.
*
* @param context
* The context of the member added.
*/
public void memberAdded(String context);
/**
* Notification that a member has been removed. The {@code context} includes
* the root context string.
*
* @param context
* The context of the member removed.
*/
public void memberRemoved(String context);
}
| {'content_hash': '06c7a01984c53e22144dde69ace0eec4', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 80, 'avg_line_length': 28.22222222222222, 'alnum_prop': 0.6469816272965879, 'repo_name': 'allanbank/mongodb-tricks', 'id': '892610d68d1e7e92d3eac07c2a20c05192fab41e', 'size': '1382', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/allanbank/mongodb/demo/coordination/group/GroupListener.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '41683'}, {'name': 'Shell', 'bytes': '7169'}]} |
class WebDataServiceBackend;
class WebDataRequestManager;
namespace content {
class BrowserContext;
}
namespace tracked_objects {
class Location;
}
class WDTypedResult;
class WebDataServiceConsumer;
////////////////////////////////////////////////////////////////////////////////
//
// WebDatabaseService defines the interface to a generic data repository
// responsible for controlling access to the web database (metadata associated
// with web pages).
//
////////////////////////////////////////////////////////////////////////////////
class WEBDATA_EXPORT WebDatabaseService
: public base::RefCountedThreadSafe<
WebDatabaseService,
content::BrowserThread::DeleteOnUIThread> {
public:
typedef base::Callback<scoped_ptr<WDTypedResult>(WebDatabase*)> ReadTask;
typedef base::Callback<WebDatabase::State(WebDatabase*)> WriteTask;
typedef base::Callback<void(sql::InitStatus)> InitCallback;
// Takes the path to the WebDatabase file.
explicit WebDatabaseService(const base::FilePath& path);
// Adds |table| as a WebDatabaseTable that will participate in
// managing the database, transferring ownership. All calls to this
// method must be made before |LoadDatabase| is called.
virtual void AddTable(scoped_ptr<WebDatabaseTable> table);
// Initializes the web database service. Takes a callback which will return
// the status of the DB after the init.
virtual void LoadDatabase(const InitCallback& callback);
// Unloads the database without actually shutting down the service. This can
// be used to temporarily reduce the browser process' memory footprint.
virtual void UnloadDatabase();
// Unloads database and will not reload.
virtual void ShutdownDatabase();
// Gets a ptr to the WebDatabase (owned by WebDatabaseService).
// TODO(caitkp): remove this method once SyncServices no longer depend on it.
virtual WebDatabase* GetDatabaseOnDB() const;
// Schedule an update/write task on the DB thread.
virtual void ScheduleDBTask(
const tracked_objects::Location& from_here,
const WriteTask& task);
// Schedule a read task on the DB thread.
virtual WebDataServiceBase::Handle ScheduleDBTaskWithResult(
const tracked_objects::Location& from_here,
const ReadTask& task,
WebDataServiceConsumer* consumer);
// Cancel an existing request for a task on the DB thread.
// TODO(caitkp): Think about moving the definition of the Handle type to
// somewhere else.
virtual void CancelRequest(WebDataServiceBase::Handle h);
private:
friend struct content::BrowserThread::DeleteOnThread<
content::BrowserThread::UI>;
friend class base::DeleteHelper<WebDatabaseService>;
// We have to friend RCTS<> so WIN shared-lib build is happy (crbug/112250).
friend class base::RefCountedThreadSafe<WebDatabaseService,
content::BrowserThread::DeleteOnUIThread>;
virtual ~WebDatabaseService();
base::FilePath path_;
// The primary owner is |WebDatabaseService| but is refcounted because
// PostTask on DB thread may outlive us.
scoped_refptr<WebDataServiceBackend> wds_backend_;
};
#endif // COMPONENTS_WEBDATA_COMMON_WEB_DATABASE_SERVICE_H_
| {'content_hash': 'c2e5fdc74e61cb25c72e44726f49be7a', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 80, 'avg_line_length': 35.73033707865169, 'alnum_prop': 0.7172955974842767, 'repo_name': 'codenote/chromium-test', 'id': '624660d0d88f914d71168f897c9dd3c9107bee31', 'size': '4019', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/webdata/common/web_database_service.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
Store multiple files in one file.
Metafile library allows you to read\write\modify multiple independent byte streams in any order, storing them in one file.
| {'content_hash': 'cf875e2b00eea0481c227d1e4c71ca24', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 125, 'avg_line_length': 53.666666666666664, 'alnum_prop': 0.7950310559006211, 'repo_name': 'Light-Keeper/metafile', 'id': '53eef9c86d242e93e9396f7dd3e2a550c3a54948', 'size': '172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '33089'}]} |
package kmeans;
import datamodel.*;
import java.util.Random;
import java.util.ArrayList;
public class SampleGenerator {
public static ArrayList<DataPoint> generate() {
String[] firstlabels = {"a", "b", "c"};
String[] secondlabels = {"0", "1", "2"};
ArrayList<DataPoint> datapoints = new ArrayList<DataPoint>();
int counter = 0;
Random dice = new Random();
for (int i = 0; i < 11; ++i) {
int firstidx = i % 3;
for (int j = 0; j < 11; ++j) {
int secondidx = j % 3;
String label = Integer.toString(counter) + firstlabels[firstidx] + secondlabels[secondidx];
counter += 1;
double[] vector = new double[11];
for (int k = 0; k < 11; ++k) {
double value = (double) dice.nextInt(10);
int kdex = k % 3;
if (kdex == secondidx) value = value + 5;
if (kdex == firstidx) value = value * 2;
if (k == secondidx + 3) value = value + 10;
if (k == firstidx) value = value + 10;
vector[k] = value;
}
DataPoint newPoint = new DataPoint(label, vector);
datapoints.add(newPoint);
}
}
return datapoints;
}
}
| {'content_hash': '9c25881a5c94083b0350cd0d6f115e92', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 95, 'avg_line_length': 28.605263157894736, 'alnum_prop': 0.5970561177552898, 'repo_name': 'tedunderwood/GenreProject', 'id': '7b2468b68892ceee9ba6236fda8f758178af1c92', 'size': '1087', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Java/kmeans/SampleGenerator.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '187389'}, {'name': 'Python', 'bytes': '645172'}, {'name': 'R', 'bytes': '34870'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'cc8d685e10d8b971ae9501ddf6811914', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '9db9cec23c224c24f308b6c748018ce68bf7a188', 'size': '176', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex gayana/ Syn. Carex diclina/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
import React, { Component } from 'react'
import Dropzone from 'react-dropzone'
import { AddItemColor, FlexGrid, Content, Image } from 'components'
import { ITEM_TYPE_WIDE, ITEM_TYPE_FULL } from 'constants'
import { uploadImages } from 'helpers'
import s from './SpecialSetup.sass'
export default class SpecialSetup extends Component {
state = {wide_preview: '', full_preview: '', isFetching: false, isError: false};
onColorChange = color => {
this.onChange({color})
};
onTypeChange = type => () => {
this.onChange({type});
};
onDrop = type => __file => {
const file = __file[0];
const isFull = type === ITEM_TYPE_FULL;
this.setState({
[isFull ? 'full_preview' : 'wide_preview']: file.preview
});
this.saveImage(file).then(image => {
const data = {
[isFull ? 'full_image' : 'wide_image']: image
};
this.onChange(data);
})
};
saveImage = image => {
let images = [image];
this.setFetching(true);
return new Promise((resolve, reject) => {
uploadImages(images, null, 'special')
.then(data => {
resolve(data[0]);
this.setFetching(false);
})
.catch(err => {
reject(err);
this.setError(err);
})
})
};
setFetching = isFetching => this.setState({isFetching});
setError = isError => this.setState({isError, isFetching: false});
onChange = data => {
if (this.props.onChange) {
this.props.onChange(data);
}
};
render() {
const { onColorChange, onTypeChange, onDrop } = this;
const { type, wide_image, full_image, content } = this.props.data;
const { wide_preview, full_preview, isFetching, isError } = this.state;
const isFullActive = type === ITEM_TYPE_FULL;
return (
<div className={s.special}>
<AddItemColor className={s.color} onChange={onColorChange}
name="Акция" color="#fc3775"/>
<FlexGrid align="start" justify="start">
<div className={s.zone__wrapper}>
<Content className={s.title} gray={isFullActive}
onClick={onTypeChange(ITEM_TYPE_WIDE)}
regular size="5">1x</Content>
<Dropzone onDrop={onDrop(ITEM_TYPE_WIDE)} className={s.zone}>
<Image noHost={!!wide_preview} className={s.img} src={wide_preview || wide_image}/>
</Dropzone>
</div>
<div className={s.zone__wrapper}>
<Content className={s.title} gray={!isFullActive}
onClick={onTypeChange(ITEM_TYPE_FULL)}
regular size="5">2x</Content>
<Dropzone onDrop={onDrop(ITEM_TYPE_FULL)} className={s.zone}>
<Image noHost={!!full_preview} className={s.img} src={full_preview || full_image}/>
</Dropzone>
</div>
</FlexGrid>
<Content size="5">
{isFetching && 'Загрузка, ждите'}
{isError && `Ошибка: ${JSON.stringify(isError)}`}
</Content>
</div>
)
}
}
| {'content_hash': 'b4917a40b3f5e495956982d3d8c0ed16', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 97, 'avg_line_length': 30.7979797979798, 'alnum_prop': 0.5680551000327977, 'repo_name': 'expdevelop/d812', 'id': '86a7bd82e550fe1c570680a7a93f5645e70446a0', 'size': '3073', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/components/SpecialSetup/SpecialSetup.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '94491'}, {'name': 'HTML', 'bytes': '1457'}, {'name': 'JavaScript', 'bytes': '729010'}, {'name': 'Shell', 'bytes': '2297'}]} |
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('qStat.services',[]).
value('version', '0.1').
factory('Players', function ($resource) {
return $resource('data/players.json', {
}, {
query: {
method: 'GET',
isArray: true
}
});
}).
factory('Games', function ($resource) {
return $resource('data/games.json', {
},
{
query: {
method: 'GET',
isArray: true
}
});
}).
factory('Teams', function ($resource) {
return $resource('data/teams.json', {
},
{
query: {
method: 'GET',
isArray: true
}
});
}).
factory('Positions', function ($resource) {
return $resource('data/positions.json', {
},
{
query: {
method: 'GET',
isArray: true
}
});
}).
factory('Statistics', function ($resource) {
return $resource('data/statistics.json', {
},
{
query: {
method: 'GET',
isArray: true
}
});
});
| {'content_hash': '8ea30814596639e19a7e1f910923a7c2', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 46, 'avg_line_length': 19.53448275862069, 'alnum_prop': 0.4801412180052957, 'repo_name': 'helrond/qstat', 'id': 'e24f426886dc95b0566d632e6c67e1c997f13c57', 'size': '1133', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/js/services.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '562'}, {'name': 'CSS', 'bytes': '3473'}, {'name': 'HTML', 'bytes': '42573'}, {'name': 'JavaScript', 'bytes': '366570'}, {'name': 'Ruby', 'bytes': '503'}, {'name': 'Shell', 'bytes': '2036'}]} |
<bill session="115" type="h" number="135" updated="2017-06-19T20:30:29Z">
<state datetime="2017-01-03">REFERRED</state>
<status>
<introduced datetime="2017-01-03"/>
</status>
<introduced datetime="2017-01-03"/>
<titles>
<title type="short" as="introduced">Cyber Privacy Fortification Act of 2017</title>
<title type="short" as="introduced">Cyber Privacy Fortification Act of 2017</title>
<title type="official" as="introduced">To protect cyber privacy, and for other purposes.</title>
<title type="display">Cyber Privacy Fortification Act of 2017</title>
</titles>
<sponsor bioguide_id="C000714"/>
<cosponsors>
<cosponsor bioguide_id="J000288" joined="2017-01-03"/>
</cosponsors>
<actions>
<action datetime="2017-01-03">
<text>Introduced in House</text>
</action>
<action datetime="2017-01-03" state="REFERRED">
<text>Referred to the House Committee on the Judiciary.</text>
</action>
<action datetime="2017-01-12">
<text>Referred to the Subcommittee on Crime, Terrorism, Homeland Security, and Investigations.</text>
</action>
<action datetime="2017-01-12">
<text>Referred to the Subcommittee on Regulatory Reform, Commercial And Antitrust Law.</text>
</action>
</actions>
<committees>
<committee subcommittee="" code="HSJU" name="House Judiciary" activity="Referral"/>
<committee subcommittee="Regulatory Reform, Commercial And Antitrust Law" code="HSJU05" name="House Judiciary" activity="Referral"/>
<committee subcommittee="Crime, Terrorism, Homeland Security, and Investigations" code="HSJU08" name="House Judiciary" activity="Referral"/>
</committees>
<relatedbills/>
<subjects>
<term name="Science, technology, communications"/>
<term name="Administrative law and regulatory procedures"/>
<term name="Business records"/>
<term name="Civil actions and liability"/>
<term name="Computer security and identity theft"/>
<term name="Computers and information technology"/>
<term name="Congressional oversight"/>
<term name="Consumer affairs"/>
<term name="Consumer credit"/>
<term name="Criminal justice information and records"/>
<term name="Government information and archives"/>
<term name="Health information and medical records"/>
<term name="Judicial review and appeals"/>
<term name="Right of privacy"/>
</subjects>
<amendments/>
<summary date="2017-01-03T05:00:00Z" status="Introduced in House">Cyber Privacy Fortification Act of 2017
This bill amends the federal criminal code to provide criminal penalties for intentional failures to provide required notices regarding security breaches of computerized data that there is reason to believe resulted in improper access to specified sensitive personally identifiable information that is electronic or digital.
A person who owns or possesses data in electronic form containing a means of identification, and who has knowledge of a major security breach of the system containing such data, must notify the U.S. Secret Service or the Federal Bureau of Investigation.
A "major security breach" involves: (1) a means of identification pertaining to at least 10,000 individuals that is reasonably believed to have been acquired, (2) databases owned by the federal government, or (3) a means of identification of federal employees or contractors involved in national security matters or law enforcement.
The Department of Justice and state attorneys general may bring civil actions and obtain injunctive relief for violations of federal laws relating to data security.
Federal agencies must prepare and make available to the public privacy impact assessments that describe the impact of certain proposed and final agency rules on the privacy of individuals. Agencies may waive or delay certain privacy impact assessment requirements for emergencies and national security reasons.
Federal agencies must: (1) periodically review promulgated rules that have a significant privacy impact on individuals or a privacy impact on a substantial number of individuals, and (2) consider whether each such rule can be amended or rescinded in a manner that minimizes any such impact while remaining in accordance with applicable statutes.
The bill provides access to judicial review to individuals adversely affected or aggrieved by final agency action on any such rule.</summary>
<committee-reports/>
</bill>
| {'content_hash': '0dba25901850b76060e50e688fe83250', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 345, 'avg_line_length': 63.48571428571429, 'alnum_prop': 0.7556255625562557, 'repo_name': 'peter765/power-polls', 'id': 'b5317d3bf8c25076a0478df8404ef4c834ac1598', 'size': '4444', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/bills/hr/hr135/data.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '58567'}, {'name': 'JavaScript', 'bytes': '7370'}, {'name': 'Python', 'bytes': '22988'}]} |
import collections
from supriya import CalculationRate
from supriya.ugens.BEQSuite import BEQSuite
class BLowCut(BEQSuite):
"""
A low-cut filter.
::
>>> source = supriya.ugens.In.ar(0)
>>> blow_cut = supriya.ugens.BLowCut.ar(
... frequency=1200,
... max_order=5,
... order=2,
... source=source,
... )
>>> blow_cut
BLowCut.ar()
"""
### CLASS VARIABLES ###
_ordered_input_names = collections.OrderedDict(
[("source", None), ("frequency", 1200), ("order", 2), ("max_order", 5)]
)
_valid_calculation_rates = (CalculationRate.AUDIO,)
| {'content_hash': 'ed32913d81f903f9aa1c36f02064337d', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 79, 'avg_line_length': 21.612903225806452, 'alnum_prop': 0.5358208955223881, 'repo_name': 'Pulgama/supriya', 'id': '0b87c53ed2be77806f6caaad9bbe1b7b8c3262d4', 'size': '670', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'supriya/ugens/BLowCut.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '6712'}, {'name': 'CSS', 'bytes': '446'}, {'name': 'HTML', 'bytes': '1083'}, {'name': 'JavaScript', 'bytes': '6163'}, {'name': 'Makefile', 'bytes': '6775'}, {'name': 'Python', 'bytes': '2790612'}, {'name': 'Shell', 'bytes': '569'}]} |
export { default } from 'ui-base-theme/components/demo--ui-button-group';
| {'content_hash': '224c38b19255ae1e9a63db968248b06b', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 73, 'avg_line_length': 74.0, 'alnum_prop': 0.7432432432432432, 'repo_name': 'prototypal-io/ui-base-theme', 'id': 'd259eb9a24da26ffb338a4e829ae35d77154cf25', 'size': '74', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/components/demo--ui-button-group.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '32298'}, {'name': 'HTML', 'bytes': '44842'}, {'name': 'JavaScript', 'bytes': '54117'}]} |
ActiveRecord::Schema.define(version: 20170531151758) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.integer "user_id"
t.string "slug", default: ""
t.string "short_id", default: ""
t.string "friendly_id", default: ""
t.string "title", default: ""
t.text "raw_intro"
t.text "intro"
t.text "raw_content"
t.text "content"
t.string "editor_type", default: "ckeditor"
t.string "view_layout", default: ""
t.string "view_template", default: ""
t.integer "view_counter", default: 0
t.string "state", default: "draft"
t.string "access_token", default: ""
t.datetime "published_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "credentials", force: :cascade do |t|
t.bigint "user_id"
t.string "provider"
t.string "uid"
t.string "expires_at"
t.text "access_token"
t.text "access_token_secret"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_credentials_on_user_id"
end
create_table "email_registration_requests", force: :cascade do |t|
t.string "uid", default: ""
t.string "email", default: ""
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "onetime_login_links", force: :cascade do |t|
t.string "uid", default: ""
t.string "email", default: ""
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "login", default: ""
t.string "username", default: ""
t.text "raw_about"
t.text "about"
t.string "vk_addr", default: ""
t.string "ok_addr", default: ""
t.string "tw_addr", default: ""
t.string "fb_addr", default: ""
t.string "gp_addr", default: ""
t.string "ig_addr", default: ""
t.string "pt_addr", default: ""
t.string "yt_addr", default: ""
t.string "vm_addr", default: ""
t.string "sh_addr", default: ""
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
| {'content_hash': 'd10e5da8a2bf0f10fc8ca0fb5115ba8c', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 95, 'avg_line_length': 34.193548387096776, 'alnum_prop': 0.6396226415094339, 'repo_name': 'TheOpenCMS/TheOpenCMS', 'id': '364461a8fe5996f49069a3a078347a61a2a8de87', 'size': '3903', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/schema.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '93894'}, {'name': 'CoffeeScript', 'bytes': '21905'}, {'name': 'HTML', 'bytes': '79979'}, {'name': 'JavaScript', 'bytes': '61212'}, {'name': 'Ruby', 'bytes': '340615'}, {'name': 'Shell', 'bytes': '13140'}]} |
package polyite.util
import java.util.logging.Logger
import org.junit.Assert.assertTrue
import org.junit.Test
class EchelonFormTest {
@Test
def test {
val matrix : Array[Array[Rat]] = Array(
Array(Rat(1), Rat(1), Rat(1)),
Array(Rat(1), Rat(0), Rat(1)),
Array(Rat(0), Rat(1), Rat(1)),
Array(Rat(0), Rat(2), Rat(2)))
val echelonMatrix : Array[Array[Rat]] = Util.calcRowEchelonForm(matrix, 4, 3)
println(echelonMatrix.map(_.mkString(", ")).mkString("\n"))
assertTrue(Util.calcRowRank(echelonMatrix) == 3)
}
} | {'content_hash': '3ac0d070fd3236e70de459adbb8cb50a', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 81, 'avg_line_length': 26.428571428571427, 'alnum_prop': 0.6432432432432432, 'repo_name': 'stganser/polyite', 'id': '6b86607d00ddb03a0cc4570ea2434a7c895e8f92', 'size': '555', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/polyite/util/EchelonFormTest.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '2788'}, {'name': 'Scala', 'bytes': '796230'}, {'name': 'Shell', 'bytes': '43469'}, {'name': 'TeX', 'bytes': '20618'}]} |
<?php
declare(strict_types=1);
namespace App\Model;
use App\Entity\Event;
use App\Entity\Payment;
use App\Entity\Ticket;
use App\Entity\TicketCost;
use App\Entity\User;
/**
* EventStateData.
*/
class EventStateData
{
/** @var Event */
private $event;
/** @var Payment|null */
private $pendingPayment;
/** @var string|null */
private $mob = null;
/** @var Ticket|null */
private $ticket;
/** @var string */
private $position;
/** @var TicketCost|null */
private $ticketCost;
/** @var User|null */
private $user;
/** @var string|null */
private $forced;
/**
* @param Event $event
* @param string $position
* @param TicketCost|null $ticketCost
* @param string|null $forced
*/
public function __construct(Event $event, string $position, ?TicketCost $ticketCost, ?string $forced)
{
$this->event = $event;
$this->position = $position;
$this->ticketCost = $ticketCost;
$this->mob = \in_array($position, ['event_fix_header_mob', 'price_block_mob']) ? '_mob' : null;
$this->forced = $forced;
}
/**
* @return Event
*/
public function getEvent(): Event
{
return $this->event;
}
/**
* @param Event $event
*
* @return $this
*/
public function setEvent(Event $event): self
{
$this->event = $event;
return $this;
}
/**
* @return Payment|null
*/
public function getPendingPayment(): ?Payment
{
return $this->pendingPayment;
}
/**
* @param Payment|null $pendingPayment
*
* @return $this
*/
public function setPendingPayment(?Payment $pendingPayment): self
{
$this->pendingPayment = $pendingPayment;
return $this;
}
/**
* @return string|null
*/
public function getMob(): ?string
{
return $this->mob;
}
/**
* @param string|null $mob
*
* @return $this
*/
public function setMob(?string $mob): self
{
$this->mob = $mob;
return $this;
}
/**
* @return Ticket|null
*/
public function getTicket(): ?Ticket
{
return $this->ticket;
}
/**
* @param Ticket|null $ticket
*
* @return $this
*/
public function setTicket(?Ticket $ticket): self
{
$this->ticket = $ticket;
return $this;
}
/**
* @return string
*/
public function getPosition(): string
{
return $this->position;
}
/**
* @param string $position
*
* @return $this
*/
public function setPosition(string $position): self
{
$this->position = $position;
return $this;
}
/**
* @return TicketCost|null
*/
public function getTicketCost(): ?TicketCost
{
return $this->ticketCost;
}
/**
* @param TicketCost|null $ticketCost
*
* @return $this
*/
public function setTicketCost(?TicketCost $ticketCost): self
{
$this->ticketCost = $ticketCost;
return $this;
}
/**
* @return User|null
*/
public function getUser(): ?User
{
return $this->user;
}
/**
* @param User|null $user
*
* @return $this
*/
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
/**
* @return bool
*/
public function canDownloadTicket(): bool
{
return $this->event->isActiveAndFuture() && $this->ticketIsPaid();
}
/**
* @param string|null $type
*
* @return bool
*/
public function canDownloadCertificate(?string $type): bool
{
return
\is_string($type) &&
$this->ticketIsPaid() &&
null !== $this->event->findCertificateFileForType($type)
;
}
/**
* @return string|null
*/
public function getForced(): ?string
{
return $this->forced;
}
/**
* @param string|null $forced
*
* @return $this
*/
public function setForced(?string $forced)
{
$this->forced = $forced;
return $this;
}
/**
* @return bool
*/
private function ticketIsPaid(): bool
{
return $this->ticket instanceof Ticket && $this->ticket->isPaid();
}
}
| {'content_hash': '1bb0f9e9976ba2c30f9367b79dbbb66b', 'timestamp': '', 'source': 'github', 'line_count': 246, 'max_line_length': 105, 'avg_line_length': 18.17479674796748, 'alnum_prop': 0.5171102661596958, 'repo_name': 'stfalcon/fwdays', 'id': '3e16e67e80cf9a9a2e0cf439e44f3bd1636c097b', 'size': '4471', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Model/EventStateData.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '59606'}, {'name': 'Dockerfile', 'bytes': '4459'}, {'name': 'HTML', 'bytes': '743032'}, {'name': 'JavaScript', 'bytes': '400833'}, {'name': 'PHP', 'bytes': '1138660'}, {'name': 'SCSS', 'bytes': '205362'}, {'name': 'Shell', 'bytes': '3401'}, {'name': 'Twig', 'bytes': '211574'}]} |
<?php
namespace TheliaEmailManager\Model;
use TheliaEmailManager\Model\Base\EmailManagerTraceQuery as BaseEmailManagerTraceQuery;
/**
* Skeleton subclass for performing query and update operations on the 'email_manager_trace' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class EmailManagerTraceQuery extends BaseEmailManagerTraceQuery
{
} // EmailManagerTraceQuery
| {'content_hash': '5cd2839d256a1ea7260c3f4d365f5d78', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 99, 'avg_line_length': 25.761904761904763, 'alnum_prop': 0.7874306839186691, 'repo_name': 'gillesbourgeat/TheliaEmailManager', 'id': 'eadfe4089a35e0b9eb24c1d3b15dd081d6275e2f', 'size': '541', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Model/EmailManagerTraceQuery.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '61774'}, {'name': 'PHP', 'bytes': '754162'}]} |
package com.sun.max.ve.guk;
import com.sun.max.annotate.*;
import com.sun.max.unsafe.*;
import com.sun.max.vm.*;
import com.sun.max.vm.actor.holder.ClassActor;
import com.sun.max.vm.classfile.constant.SymbolTable;
import com.sun.max.vm.compiler.*;
import com.sun.max.vm.reference.*;
import com.sun.max.vm.runtime.*;
import com.sun.max.vm.type.SignatureDescriptor;
/**
* Interface to Guest VM microkernel (GUK).
*
* This is the single point of contact with the Guest VM microkernel.
* All calls to GUK must pass through this class. Note that most of the methods
* in this class are not public as other classes in this package,
* e.g. @see GUKScheduler, provide a Java-centric interface
* to the microkernel, using Java naming conventions and
* possibly modified names (in case the GUK name is non-intuitive).
* Those methods call the corresponding native methods in this class whose
* name matches the GUK C symbol.
* A few methods are not C_FUNCTIONs as they may block, i.e they
* are standard JNI methods.
*
* @author Mick Jordan
*
*/
public final class GUK {
static {
new CriticalMethod(GUK.class, "initialize", SignatureDescriptor.create(void.class));
new CriticalMethod(GUK.class, "is_crashing", SignatureDescriptor.create(void.class));
new CriticalNativeMethod(GUK.class, "guk_register_is_crashing_method");
new CriticalNativeMethod(GUK.class, "guk_schedule");
new CriticalNativeMethod(GUK.class, "guk_preempt_schedule");
new CriticalNativeMethod(GUK.class, "guk_wait_completion");
new CriticalNativeMethod(GUK.class, "guk_watch_memory_target");
new CriticalNativeMethod(GUK.class, "guk_current");
new CriticalNativeMethod(GUK.class, "guk_block");
new CriticalNativeMethod(GUK.class, "guk_wake");
new CriticalNativeMethod(GUK.class, "guk_attach_to_appsched");
new CriticalNativeMethod(GUK.class, "guk_detach_from_appsched");
new CriticalNativeMethod(GUK.class, "guk_create_spin_lock");
new CriticalNativeMethod(GUK.class, "guk_delete_spin_lock");
new CriticalNativeMethod(GUK.class, "guk_create_timer");
new CriticalNativeMethod(GUK.class, "guk_delete_timer");
new CriticalNativeMethod(GUK.class, "guk_add_timer");
new CriticalNativeMethod(GUK.class, "guk_remove_timer");
new CriticalNativeMethod(GUK.class, "guk_spin_lock");
new CriticalNativeMethod(GUK.class, "guk_spin_unlock");
new CriticalNativeMethod(GUK.class, "guk_spin_lock_irqsave");
new CriticalNativeMethod(GUK.class, "guk_spin_unlock_irqrestore");
new CriticalNativeMethod(GUK.class, "guk_local_irqsave");
new CriticalNativeMethod(GUK.class, "guk_local_irqrestore");
new CriticalNativeMethod(GUK.class, "guk_create_completion");
new CriticalNativeMethod(GUK.class, "guk_delete_completion");
new CriticalNativeMethod(GUK.class, "guk_complete");
new CriticalNativeMethod(GUK.class, "guk_print_runqueue");
new CriticalNativeMethod(GUK.class, "guk_register_upcalls");
new CriticalNativeMethod(GUK.class, "guk_sched_num_cpus");
new CriticalNativeMethod(GUK.class, "guk_smp_cpu_state");
new CriticalNativeMethod(GUK.class, "guk_kick_cpu");
new CriticalNativeMethod(GUK.class, "guk_crash_exit_msg");
new CriticalNativeMethod(GUK.class, "guk_set_timeslice");
new CriticalNativeMethod(GUK.class, "guk_allocate_pages");
new CriticalNativeMethod(GUK.class, "guk_page_pool_start");
new CriticalNativeMethod(GUK.class, "guk_page_pool_end");
new CriticalNativeMethod(GUK.class, "guk_page_pool_bitmap");
new CriticalNativeMethod(GUK.class, "guk_machine_page_pool_bitmap");
new CriticalNativeMethod(GUK.class, "guk_total_free_pages");
new CriticalNativeMethod(GUK.class, "guk_bulk_free_pages");
new CriticalNativeMethod(GUK.class, "guk_dump_page_pool_state");
new CriticalNativeMethod(GUK.class, "guk_increase_page_pool");
new CriticalNativeMethod(GUK.class, "guk_decrease_page_pool");
new CriticalNativeMethod(GUK.class, "guk_decreaseable_page_pool");
new CriticalNativeMethod(GUK.class, "guk_current_reservation");
new CriticalNativeMethod(GUK.class, "guk_maximum_reservation");
new CriticalNativeMethod(GUK.class, "guk_maximum_ram_page");
new CriticalNativeMethod(GUK.class, "guk_mfn_to_pfn");
new CriticalNativeMethod(GUK.class, "guk_pfn_to_mfn");
new CriticalNativeMethod(GUK.class, "guk_pagetable_base");
new CriticalNativeMethod(GUK.class, "guk_allocate_2mb_machine_pages");
new CriticalNativeMethod(GUK.class, "guk_netfront_xmit");
new CriticalNativeMethod(GUK.class, "guk_ttprintk0");
new CriticalNativeMethod(GUK.class, "guk_ttprintk1");
new CriticalNativeMethod(GUK.class, "guk_ttprintk2");
new CriticalNativeMethod(GUK.class, "guk_ttprintk3");
new CriticalNativeMethod(GUK.class, "guk_ttprintk4");
new CriticalNativeMethod(GUK.class, "guk_ttprintk5");
new CriticalNativeMethod(GUK.class, "guk_set_trace_state");
new CriticalNativeMethod(GUK.class, "guk_get_trace_state");
new CriticalNativeMethod(GUK.class, "guk_exec_create");
new CriticalNativeMethod(GUK.class, "guk_exec_wait");
new CriticalNativeMethod(GUK.class, "guk_exec_close");
new CriticalNativeMethod(GUK.class, "guk_exec_read_bytes");
new CriticalNativeMethod(GUK.class, "guk_exec_destroy");
new CriticalNativeMethod(GUK.class, "guk_domain_id");
new CriticalNativeMethod(GUK.class, "guk_get_cpu_running_time");
new CriticalNativeMethod(GUK.class, "guk_nano_time");
}
private GUK() {
}
/**
* The offset of the byte array data from the byte array object's origin.
*/
private static final Offset _dataOffset = VMConfiguration.vmConfig().layoutScheme().byteArrayLayout.getElementOffsetFromOrigin(0);
@INLINE
public static void crash(byte[] msg) {
guk_crash_exit_msg(Reference.fromJava(msg).toOrigin().plus(_dataOffset));
}
public static void initialize() {
final Word isCrashingMethodAddress = CompilationScheme.Static.getCurrentTargetMethod(ClassActor.fromJava(GUK.class).findLocalStaticMethodActor(SymbolTable.makeSymbol("is_crashing"))).getEntryPoint(CallEntryPoint.C_ENTRY_POINT);
guk_register_is_crashing_method(isCrashingMethodAddress);
}
@INLINE
public static long nanoTime() {
return guk_nano_time();
}
/**
* This function is called when GUK is crashing; it's main purpose is to permit a breakpoint
* to be set here and catch the crash when running under the Inspector.
*/
@VM_ENTRY_POINT
private static void is_crashing() {
}
/*
* The actual native methods exported by GUK
*
*/
// Functions that may block
static native void guk_schedule();
static native void guk_preempt_schedule();
static native void guk_wait_completion(Pointer comp);
static native long guk_watch_memory_target();
static native int guk_exec_create(Pointer prog, Pointer args, int argc, Pointer dir);
static native int guk_exec_wait(int pid);
static native int guk_exec_close(int pid);
static native int guk_exec_read_bytes(int pid, Pointer bytes, int length, long fileOffset);
static native int guk_exec_write_bytes(int pid, Pointer bytes, int length, long fileOffset);
static native int guk_exec_destroy(int pid);
// C_FUNCTIONs
@C_FUNCTION
static native void guk_register_is_crashing_method(Word method);
@C_FUNCTION
static native Pointer guk_current();
@C_FUNCTION
static native void guk_block(Word thread);
@C_FUNCTION
static native void guk_wake(Word thread);
@C_FUNCTION
static native void guk_attach_to_appsched(Word thread, int id);
@C_FUNCTION
static native void guk_detach_from_appsched(Word thread);
@C_FUNCTION
static native Pointer guk_create_spin_lock();
@C_FUNCTION
static native void guk_delete_spin_lock(Pointer lock);
@C_FUNCTION
static native Pointer guk_create_timer();
@C_FUNCTION
static native void guk_delete_timer(Pointer lock);
@C_FUNCTION
static native void guk_add_timer(Pointer timer, long timeout);
@C_FUNCTION
static native int guk_remove_timer(Pointer timer);
@C_FUNCTION
public static native void guk_spin_lock(Pointer lock);
@C_FUNCTION
public static native void guk_spin_unlock(Pointer lock);
@C_FUNCTION
static native long guk_spin_lock_irqsave(Pointer lock);
@C_FUNCTION
static native void guk_spin_unlock_irqrestore(Pointer lock, long flags);
@C_FUNCTION
static native long guk_local_irqsave();
@C_FUNCTION
static native void guk_local_irqrestore(long flags);
@C_FUNCTION
static native Pointer guk_create_completion();
@C_FUNCTION
static native void guk_delete_completion(Pointer completion);
@C_FUNCTION //(isInterruptHandler = true)
static native void guk_complete(Pointer comp);
@C_FUNCTION
static native void guk_print_runqueue();
@C_FUNCTION
static native int guk_register_upcalls(Address scheduleCall, Address descheduleCall, Address wakeCall,
Address blockCall, Address attachCall, Address detachCall, Address pickCpuCall, Address runnableUpcall);
@C_FUNCTION
static native int guk_sched_num_cpus();
@C_FUNCTION
static native int guk_smp_cpu_state(int cpu);
@C_FUNCTION
static native int guk_kick_cpu(int cpu);
@C_FUNCTION
static native void guk_crash_exit_msg(Pointer msg);
@C_FUNCTION
static native int guk_set_timeslice(Word thread, int t);
@C_FUNCTION
static native Pointer guk_allocate_pages(int n, int type);
@C_FUNCTION
static native long guk_page_pool_start();
@C_FUNCTION
static native long guk_page_pool_end();
@C_FUNCTION
static native Pointer guk_page_pool_bitmap();
@C_FUNCTION
static native Pointer guk_machine_page_pool_bitmap();
@C_FUNCTION
static native long guk_total_free_pages();
@C_FUNCTION
static native long guk_bulk_free_pages();
@C_FUNCTION
static native long guk_dump_page_pool_state();
@C_FUNCTION
static native long guk_increase_page_pool(long pages);
@C_FUNCTION
static native long guk_decrease_page_pool(long pages);
@C_FUNCTION
static native long guk_decreaseable_page_pool();
@C_FUNCTION
static native long guk_current_reservation();
@C_FUNCTION
static native long guk_maximum_reservation();
@C_FUNCTION
static native long guk_maximum_ram_page();
@C_FUNCTION
static native long guk_mfn_to_pfn(long mfn);
@C_FUNCTION
static native long guk_pfn_to_mfn(long pfn);
@C_FUNCTION
static native long guk_pagetable_base();
@C_FUNCTION
static native long guk_allocate_2mb_machine_pages(int n, int type);
@C_FUNCTION
public static native int guk_domain_id();
@C_FUNCTION
public static native void guk_netfront_xmit(Address buffer, int len);
@C_FUNCTION
static native int guk_get_cpu_running_time(int cpu);
@C_FUNCTION
static native long guk_nano_time();
@C_FUNCTION
static native void guk_ttprintk0(Pointer msg);
@C_FUNCTION
static native void guk_ttprintk1(Pointer msg, long arg);
@C_FUNCTION
static native void guk_ttprintk2(Pointer msg, long arg1, long arg2);
@C_FUNCTION
static native void guk_ttprintk3(Pointer msg, long arg1, long arg2, long arg3);
@C_FUNCTION
static native void guk_ttprintk4(Pointer msg, long arg1, long arg2, long arg3, long arg4);
@C_FUNCTION
static native void guk_ttprintk5(Pointer msg, long arg1, long arg2, long arg3, long arg4, long arg5);
@C_FUNCTION
static native int guk_set_trace_state(int var, int value);
@C_FUNCTION
static native int guk_get_trace_state(int var);
}
| {'content_hash': '038e338b45265ea03127176cf3ca8721', 'timestamp': '', 'source': 'github', 'line_count': 277, 'max_line_length': 235, 'avg_line_length': 43.458483754512635, 'alnum_prop': 0.7001162983884366, 'repo_name': 'SnakeDoc/GuestVM', 'id': '288066d4c545e2b37160cf623ad52dc599c54903', 'size': '13094', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'guestvm~guestvm/com.oracle.max.ve/src/com/sun/max/ve/guk/GUK.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '11166'}, {'name': 'C', 'bytes': '1075736'}, {'name': 'C++', 'bytes': '10736'}, {'name': 'D', 'bytes': '342918'}, {'name': 'Java', 'bytes': '4421381'}, {'name': 'Logos', 'bytes': '33960'}, {'name': 'Python', 'bytes': '1218'}, {'name': 'Shell', 'bytes': '3388'}]} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SecureCommunicationComponent")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("SecureCommunicationComponent")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("adb88895-4e78-4827-a6ed-97e69e19a1f9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {'content_hash': '0d236ea134a53e1d6768d254e3beb767', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 40.52777777777778, 'alnum_prop': 0.7546264564770391, 'repo_name': 'rnemtz/programming.net', 'id': '74d89852d4bcc30f6dfbc895e0a12e5111cf2c2f', 'size': '1462', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'E33RMARTINEZHW0/SecureCommunicationComponent/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '992198'}]} |
<?php
require "/Users/joehobson/Documents/navNorth/OET/LearningReg/src/LRphpLib/LearningRegistry/src/Bencode/LearningRegistryBencodeEncoder.php";
use LearningRegistryBencodeEncoder;
$startJSON = 'abcdefghijklmnopqrstuvwxyz0123456789';
$hashedText = hash('SHA256', $startJSON);
$hashedText = hash('SHA256', $startJSON);
$bencoder = new LearningRegistryBencodeEncoder($hashedText);
$bencodedText = $bencoder->encodeData($hashedText);
#hashedText = hashlib.sha256(startJSON.encode("utf-8")).hexdigest()
#hashedUTF8 = hashlib.sha256(startJSON).hexdigest()
#encoded = bencode(hashedUTF8)
# Print it
fwrite(STDOUT, "Straight is :" . $hashedText);
fwrite(STDOUT, "UTF8 is :" . $utf8_encode($hashedText));
fwrite(STDOUT, "Encoded is :" . $bencodedText);
?> | {'content_hash': 'd67fb8bfad306e8022c879d28e3f3217', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 139, 'avg_line_length': 32.82608695652174, 'alnum_prop': 0.7655629139072848, 'repo_name': 'LearningRegistry/LRSignature', 'id': 'c1c15b75d63f84c4fbb42ae55b6e401ed02b463f', 'size': '786', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/LRSignature/encode-test.php', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '10805'}, {'name': 'PHP', 'bytes': '786'}, {'name': 'Python', 'bytes': '100060'}]} |
package net.rushhourgame.managedbean;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import net.rushhourgame.RushHourResourceBundle;
import net.rushhourgame.RushHourSession;
import net.rushhourgame.controller.AssistanceController;
import net.rushhourgame.controller.PlayerController;
import net.rushhourgame.controller.RailController;
import net.rushhourgame.controller.StationController;
import net.rushhourgame.controller.TrainController;
import net.rushhourgame.entity.Player;
import net.rushhourgame.entity.Pointable;
import net.rushhourgame.entity.RailEdge;
import net.rushhourgame.entity.RailNode;
import net.rushhourgame.entity.SimplePoint;
import net.rushhourgame.entity.Station;
import net.rushhourgame.entity.Train;
import net.rushhourgame.entity.TrainDeployed;
import net.rushhourgame.exception.RushHourException;
import org.primefaces.PrimeFaces;
/**
*
* @author yasshi2525 (https://twitter.com/yasshi2525)
*/
@Named(value = "menu")
@ViewScoped
public class ClickMenuBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(ClickMenuBean.class.getName());
@PersistenceContext
EntityManager em;
@Inject
protected RushHourSession session;
protected Player player;
protected List<RailEdge> clickedEdges;
protected Station clickedStation;
protected TrainDeployed clickedTrain;
@Inject
protected PlayerController pCon;
@Inject
protected RailController rCon;
@Inject
protected StationController stCon;
@Inject
protected TrainController tCon;
@Inject
protected AssistanceController aCon;
@Inject
protected RushHourResourceBundle msg;
protected Pointable click;
protected double scale;
protected Comparator<RailNode> neighborSearcher
= (n1, n2) -> {
if (n1.distTo(click) > n2.distTo(click)) {
return 1;
} else if (n1.distTo(click) < n2.distTo(click)) {
return -1;
}
return 0;
};
@PostConstruct
public void init() {
LOG.log(Level.FINE, "{0}#init", ClickMenuBean.class);
player = pCon.findByToken(session.getToken());
click = new SimplePoint(
Double.parseDouble(getRequestMap().get("clickX")),
Double.parseDouble(getRequestMap().get("clickY"))
);
scale = Double.parseDouble(getRequestMap().get("scale"));
String e1id = getRequestMap().get("clickedEdge1");
String e2id = getRequestMap().get("clickedEdge2");
if (e1id != null && e2id != null) {
try {
clickedEdges = rCon.findEdge(player, Long.parseLong(e1id), Long.parseLong(e2id));
} catch (RushHourException ex) {
Logger.getLogger(ClickMenuBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
List<Station> nearStations = stCon.findIn(player, click, scale - 3);
clickedStation = nearStations.isEmpty() ? null : nearStations.get(0);
List<Train> nearTrains = tCon.findIn(player, click, scale - 3);
clickedTrain = nearTrains.isEmpty() ? null : nearTrains.get(0).getDeployed();
}
public boolean isDisplayCreateRail() {
return rCon.findNodeIn(player, click, scale - 4).isEmpty();
}
@Transactional
public void createRail() throws RushHourException {
getDialog().closeDynamic(new OperationBean.RailCreation(
aCon.startWithStation(player, click, session.getLocale())));
}
public boolean isDisplayExtendRail() {
return !rCon.findNodeIn(player, click, scale - 3).isEmpty();
}
public void extendRail() {
getDialog().closeDynamic(new OperationBean.RailExtension(
rCon.findNodeIn(player, click, scale - 3).stream().min(neighborSearcher).get()));
}
public boolean isDisplayRemoveRail() {
return clickedEdges != null;
}
@Transactional
public boolean isEnableRemoveRail() throws RushHourException {
if (clickedEdges == null) {
return false;
} else {
clickedEdges = clickedEdges.stream().map((e) -> em.merge(e)).collect(Collectors.toList());
return rCon.canRemove(player, clickedEdges);
}
}
public void removeRail() {
getDialog().closeDynamic(new OperationBean.RailDeletion());
}
public boolean isDisplayRemoveStation() {
return clickedStation != null;
}
public void removeStation() {
getDialog().closeDynamic(new OperationBean.StationDeletion(clickedStation));
}
public boolean isDisplayUndeployTrain() {
return clickedTrain != null;
}
public void undeployTrain() {
getDialog().closeDynamic(new OperationBean.TrainUndeploy(clickedTrain));
}
protected FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
protected PrimeFaces.Dialog getDialog() {
return PrimeFaces.current().dialog();
}
protected Map<String, String> getRequestMap() {
return getFacesContext().getExternalContext().getRequestParameterMap();
}
}
| {'content_hash': '7987437017b2338fc4a96118f8fc999f', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 102, 'avg_line_length': 31.804469273743017, 'alnum_prop': 0.6847005093975057, 'repo_name': 'yasshi2525/rushhourgame', 'id': '8213f2b095ed762d3bca3dd00fd37c1c48b63919', 'size': '6859', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/net/rushhourgame/managedbean/ClickMenuBean.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2897'}, {'name': 'Dockerfile', 'bytes': '18167'}, {'name': 'HTML', 'bytes': '26772'}, {'name': 'Java', 'bytes': '1042762'}, {'name': 'JavaScript', 'bytes': '74057'}]} |
$def with (session, form, msg=None, msgerr=None)
$var username: $session.username.nombre1.lower().capitalize() $session.username.apellido1.lower().capitalize()
<h2>Agregar Vehículos</h2>
$if not form.valid: <p class="notifi">Intenta de Nuevo</p>
$if msgerr and form.valid: <p class="notifi">Intenta de Nuevo</p>
<form id="myform" method="post">
$:form.render()
<input class="boton" type="submit" value="Guardar"/>
</form>
<div class="error">
$if msgerr:
<p>Error:</p>
<p>$msgerr</p>
</div>
<p class="notifi">$msg</p>
<script>
jQuery(document).ready(function(){
jQuery('#gps_id').css('display', 'none');
var newElement = [];
var newElement1 = [];
jQuery.ajax({
url : '/admin/listgspjson',
type : 'GET',
dataType : 'json',
success : function(json){
jQuery.each(json, function(index, obj){
newElement1.push('<option value=' + obj[0] + '>' + obj[1] + '</option>');
newElement.push('<li id="gps_id_chzn_o_'+ ++index + ' class="active-result">' + obj[1] + '</li>');
});
jQuery('#gps_id').find(':first').after(newElement1.join(''));
$$('#gps_id_chzn ul').find(':first').after(newElement.join(''));
},
/*error : function(jqXHR, status, error){
console.log("Se produjo un error: " + error);
},*/
complete : function(jqXHR, status){
jQuery('#gps_id').chosen();
}
});
jQuery("#marca_id").chosen();
jQuery("#clase_id").chosen();
jQuery("#combustible_id").chosen();
jQuery("#carroceria_id").chosen();
jQuery("#linea_id").chosen();
jQuery("#color_id").chosen();
jQuery("#servicio_id").chosen();
function resetForm($$form) {
$$form.find('input:text, input:password, input:file, select, textarea').val('');
$$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
resetForm($$('#myform'));
});
</script>
| {'content_hash': 'ad3ba94af9f4d59e3e13c448215c068a', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 118, 'avg_line_length': 39.61818181818182, 'alnum_prop': 0.52088113813676, 'repo_name': 'jolth/CowFleet', 'id': '3aa856d71be346649b3ced0218ea4f59a53b9adf', 'size': '2179', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'templates/admin/addvehicle.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '143079'}, {'name': 'Python', 'bytes': '41845'}]} |
FROM ubuntu:14.04
MAINTAINER Björn A. Grüning, Dave Bouvier
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get -qq update && apt-get install --no-install-recommends -y apt-transport-https software-properties-common && \
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9 && \
apt-get update -qq && apt-get upgrade -y && \
apt-get purge -y software-properties-common && \
apt-get install --no-install-recommends -y autoconf automake build-essential gfortran cmake \
git-core libatlas-base-dev libblas-dev liblapack-dev openssl \
openjdk-7-jre-headless python-dev python-setuptools \
python-virtualenv zlib1g-dev libyaml-dev subversion pkg-config && \
apt-get autoremove -y && apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
git clone --branch 1.2 https://github.com/samtools/htslib.git && \
git clone --branch 1.2 https://github.com/samtools/bcftools.git && \
make -C bcftools && cp bcftools/bcftools /usr/bin && \
rm -rf bcftools htslib
| {'content_hash': '2ced1bb2f106666ec12514c93c79b990', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 120, 'avg_line_length': 55.78947368421053, 'alnum_prop': 0.7113207547169811, 'repo_name': 'galaxyproject/docker-galaxy-requirements', 'id': '4441f1f321fe72bc600cbd42be30092a4e396560', 'size': '1186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Dockerfile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '1186'}]} |
<HTML><HEAD>
<TITLE>Review for Deconstructing Harry (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0118954">Deconstructing Harry (1997)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Harvey+S.+Karten">Harvey S. Karten</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>DECONSTRUCTING HARRY</PRE>
<P> By Harvey Karten, Ph.D.
Fine Line Features
Director: Woody Allen
Writer: Woody Allen
Cast: Caroline Aaron, Woody Allen, Kirstie Alley, Bob
Balaban, Richard Benjamin, Eric Bogosian, Billy Crystal, Judy
Davis, Hazelle Goodman, Mariel Hemingway, Amy Irving,
Julie Kavner, Eric Lloyd, Julia Louis-Dreyfus, Tobey Maguire,
Demi Moore, Elisabeth Shue, Stanley Tucci, Robin Williams,
Annette Arnold, Philip Bosco, Stephanie Roth, Gene Saks</P>
<P> "I'm the worst person in the world," moans Woody Allen's
character, Harry Block, in Mr. Allen's latest exploration of the
psyche, "Deconstructing Harry." When challenged by the
view that Hitler was worse, Block thinks it over briefly and
retorts, "Well, yes, after Hitler, Goebbels and Goering--I'm the
fourth worst person in the world." That one-liner, one of the
many laughs in this briskly paced dark comedy about a guy
who never grew up, raises the tantalizing issue: Just how
much of the movie is art, and how much is Woody's own life?
The point is exploited by the issue of "Time Out" magazine,
which hit the newsstands one week before the opening of the
film. While Allen does mull over some real-life events in
"Harry"--his many divorces and plethora of psychiatrists--we
want to know: is this guy who has so frequently turned
nebbishness into entertainment really so down on himself? It
appears so, that is, if you believe another gem from the lips of
Harry Block, "Writing and entertaining people is not enough." </P>
<P> Backed up by a stellar cast made up largely of Friends of
Woody, "Deconstructing Harry" examines the tribulations of a
fifty-something guy (Allen is himself 62) who is as obsessed
with sex as a teenager with a library of Playboys. He simply
cannot pass an attractive woman without imagining what
physical intimacy would be like with her. He is so consumed
by its fires that he has writers' block--a point made doubly
clear by her very name. Still, he has churned out some
decent manuscripts in the past and so the college he
attended decades earlier has decided to honor him. No
matter that the university expelled him at one point for giving
the dean an enema. Harry Block has become its golden boy
and now, despite his many conquests, he seems unable to
find someone to join him socially on that day. Ultimately he
digs up a motley crew made up of his son Hilly (Eric Lloyd
whom he has "kidnapped" because the boy's mom Joan
(Kirstie Alley) will not permit him to go; his friend Richard (Bob
Balaban); and a hooker, Cookie (Hazelle Goodman) with
whom he had spent the previous night. Off goes Harry Block
in his car in a theme that brings to mind "Wild Strawberries,"
Ingmar Bergman's 1957 drama about a Stockholm professor
who reviews his life's disappointments while traveling to a
university to receive honors.</P>
<P> As in Luigi Pirandello's "Six Characters in Search of an
Author," Woody Allen's latest movie features a continuous
interplay of real-life people with fictional folks created by Harry
Block in his novels. It's no wonder, then, that we see the
author as a younger person in the fanciful Ken (Richard
Benjamin), who grabs another man's wife during a Sunday
barbeque and has a quick round of sex with her in the
kitchen, just meters away from the woman's husband. (In one
of the movie's more hilarious scenes the blind grandma
suddenly enters the room while the couple are in flagrante
and misinterprets Ken's rapturous outbursts as agreements
with some of her statements.) Harry proceeds to take us
around and around the block to introduce others in his life,
others who are so thinly disguised that he is confronted by a
furious and comically seething Lucy (Judy Davis), one of the
author's flames, who goes ballistic at the author for revealing
all.</P>
<P> "I create my own universe," says Block, and "I make
everybody suffer and turn it into literature." And we the
audience profit mightily from the writer's own dysfunctional life
as he lays on invention after delightful fabrication to entertain
his loyal followers in their theater seats. Lacerating others
and himself alike, he torments his sister Doris (Caroline
Aaron), whom he visits after a four-year hiatus, spoofing her
decision to become a truly practicing Jew--saving some prize
comments for her Orthodox husband Burt (Eric Bogosian).
Block, whose deity is science, exclaims, "Between Pope and
air conditioning, I'll take air conditioning." To his old friend
Larry (Billy Crystal), who steals Block's girl friend Fay
(Elisabeth Shue), he offers the fires of hell--which the camera
displays to us in all its incendiary splendor.</P>
<P> "Deconstructing Harry" features some particularly strong
roles for women, with Kirstie Alley coming across with
exquisite humor as a former wife, a psychoanalyst, who
frequently interrupts a session with a client to verbally abuse
the poor Block and throw him out of the house.</P>
<P> We learn the meaning of the title only as the story comes to
a close, as one appreciative woman who shows up for the
college honors ceremony advises Block, "Your stories are
sad, but I like to deconstruct them because they're happy
underneath." Does this mean that Woody Allen himself, who
in real life has been on the couch for decades, has a glimmer
of awareness that underneath it all he really is a happy man?
It must might be that he finally accepts the counsel of another
dignitary that "to be alive is to be happy."</P>
<P> "Deconstructing Harry" emphasizes Susan E. Morse's sharp
editing. Morse flashes backwards and forwards seamlessly,
making the story line absolutely clear, and not infrequently
interrupts jump-cuts a scene to underscore the title
character's uneven emotional life. Allen is in his typical role
as the confused, unhappy nerd, though he seems to succeed
in the sexual area--a point which unfortunately undercuts any
criticism of his immaturity. Robin Williams performs well as
one of Block's alter egos, a guy who is literally out of focus
(Carlo Di Palma's camera makes the man authentically
blurred), with Judy Davis and Kirstie Alley standing out as
exceptionally whimsical. </P>
<P> One day after screening the movie I happened to listen to
Gary Null's talk show on WBAI-FM. Null laced into those of
us who insist on being martyrs, people who refuse to believe
that life is within their control. "We see Woody Allen movies
about dysfunctional people as though there would be
something wrong with watching a happy family at work,"
complains the show's host. Sorry, Mr. Null, but the
sophisticated among us who love anything touched by Woody
Allen are no longer amused by stories of the Brady family.
Humor derives to a great extent from the suffering of others.
We laugh at entertainers who slip in banana peels, not at
those who walk calmly down the street without a care in the
world. "Deconstructing Harry," brimming with oddball, often
hilariously damaged people, should convince Mr. Allen that
writing and entertaining us with such humanity is absolutely
enough. Rated R. Running Time: 98 minutes. (C) 1997
Harvey Karten</P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {'content_hash': '50cb57942ed68bdb6c2185eee0c7ca8b', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 214, 'avg_line_length': 57.92465753424658, 'alnum_prop': 0.7658744235544519, 'repo_name': 'xianjunzhengbackup/code', 'id': 'e83b93d2c38b9749faccb281aa6535b595c0bb21', 'size': '8457', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'data science/machine_learning_for_the_web/chapter_4/movie/10071.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'BitBake', 'bytes': '113'}, {'name': 'BlitzBasic', 'bytes': '256'}, {'name': 'CSS', 'bytes': '49827'}, {'name': 'HTML', 'bytes': '157006325'}, {'name': 'JavaScript', 'bytes': '14029'}, {'name': 'Jupyter Notebook', 'bytes': '4875399'}, {'name': 'Mako', 'bytes': '2060'}, {'name': 'Perl', 'bytes': '716'}, {'name': 'Python', 'bytes': '874414'}, {'name': 'R', 'bytes': '454'}, {'name': 'Shell', 'bytes': '3984'}]} |
module Hotcell
class Error < StandardError
end
class ParseError < Error
def initialize value, line, column
@value, @line, @column = value, line, column
super(compose_message)
end
end
class UnexpectedSymbol < ParseError
def compose_message
"Unexpected symbol `#{@value}` at #{@line}:#{@column}"
end
end
class UnterminatedString < ParseError
def compose_message
"Unterminated string `#{@value}` starting at #{@line}:#{@column}"
end
end
# class UnterminatedRegexp < ParseError
# def compose_message
# "Unterminated regexp `#{@value}` starting at #{@line}:#{@column}"
# end
# end
class SyntaxError < Error
def initialize value, line, column
@value, @line, @column = value, line, column
super(compose_message)
end
def compose_message
"#{@value} at #{@line}:#{@column}"
end
end
class UnexpectedLexem < ParseError
def compose_message
"Unexpected #{@value} at #{@line}:#{@column}"
end
end
class BlockError < SyntaxError
end
class ArgumentError < SyntaxError
end
end
| {'content_hash': 'a4356e36aef50d82ecaefd7a0bfd0a5e', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 73, 'avg_line_length': 21.403846153846153, 'alnum_prop': 0.6397124887690926, 'repo_name': 'pyromaniac/hotcell', 'id': 'a4281d8fd4e2593f3547a275d09cae211ed476c4', 'size': '1113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/hotcell/errors.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '21767'}, {'name': 'Ragel in Ruby Host', 'bytes': '6893'}, {'name': 'Ruby', 'bytes': '190717'}]} |
/**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.cloudera.impala.thrift;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TDropTableOrViewParams implements org.apache.thrift.TBase<TDropTableOrViewParams, TDropTableOrViewParams._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TDropTableOrViewParams");
private static final org.apache.thrift.protocol.TField TABLE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("table_name", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final org.apache.thrift.protocol.TField IF_EXISTS_FIELD_DESC = new org.apache.thrift.protocol.TField("if_exists", org.apache.thrift.protocol.TType.BOOL, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new TDropTableOrViewParamsStandardSchemeFactory());
schemes.put(TupleScheme.class, new TDropTableOrViewParamsTupleSchemeFactory());
}
public com.cloudera.impala.thrift.TTableName table_name; // required
public boolean if_exists; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TABLE_NAME((short)1, "table_name"),
IF_EXISTS((short)2, "if_exists");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TABLE_NAME
return TABLE_NAME;
case 2: // IF_EXISTS
return IF_EXISTS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __IF_EXISTS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TABLE_NAME, new org.apache.thrift.meta_data.FieldMetaData("table_name", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, com.cloudera.impala.thrift.TTableName.class)));
tmpMap.put(_Fields.IF_EXISTS, new org.apache.thrift.meta_data.FieldMetaData("if_exists", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TDropTableOrViewParams.class, metaDataMap);
}
public TDropTableOrViewParams() {
}
public TDropTableOrViewParams(
com.cloudera.impala.thrift.TTableName table_name,
boolean if_exists)
{
this();
this.table_name = table_name;
this.if_exists = if_exists;
setIf_existsIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public TDropTableOrViewParams(TDropTableOrViewParams other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetTable_name()) {
this.table_name = new com.cloudera.impala.thrift.TTableName(other.table_name);
}
this.if_exists = other.if_exists;
}
public TDropTableOrViewParams deepCopy() {
return new TDropTableOrViewParams(this);
}
@Override
public void clear() {
this.table_name = null;
setIf_existsIsSet(false);
this.if_exists = false;
}
public com.cloudera.impala.thrift.TTableName getTable_name() {
return this.table_name;
}
public TDropTableOrViewParams setTable_name(com.cloudera.impala.thrift.TTableName table_name) {
this.table_name = table_name;
return this;
}
public void unsetTable_name() {
this.table_name = null;
}
/** Returns true if field table_name is set (has been assigned a value) and false otherwise */
public boolean isSetTable_name() {
return this.table_name != null;
}
public void setTable_nameIsSet(boolean value) {
if (!value) {
this.table_name = null;
}
}
public boolean isIf_exists() {
return this.if_exists;
}
public TDropTableOrViewParams setIf_exists(boolean if_exists) {
this.if_exists = if_exists;
setIf_existsIsSet(true);
return this;
}
public void unsetIf_exists() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __IF_EXISTS_ISSET_ID);
}
/** Returns true if field if_exists is set (has been assigned a value) and false otherwise */
public boolean isSetIf_exists() {
return EncodingUtils.testBit(__isset_bitfield, __IF_EXISTS_ISSET_ID);
}
public void setIf_existsIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __IF_EXISTS_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TABLE_NAME:
if (value == null) {
unsetTable_name();
} else {
setTable_name((com.cloudera.impala.thrift.TTableName)value);
}
break;
case IF_EXISTS:
if (value == null) {
unsetIf_exists();
} else {
setIf_exists((Boolean)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TABLE_NAME:
return getTable_name();
case IF_EXISTS:
return Boolean.valueOf(isIf_exists());
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TABLE_NAME:
return isSetTable_name();
case IF_EXISTS:
return isSetIf_exists();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof TDropTableOrViewParams)
return this.equals((TDropTableOrViewParams)that);
return false;
}
public boolean equals(TDropTableOrViewParams that) {
if (that == null)
return false;
boolean this_present_table_name = true && this.isSetTable_name();
boolean that_present_table_name = true && that.isSetTable_name();
if (this_present_table_name || that_present_table_name) {
if (!(this_present_table_name && that_present_table_name))
return false;
if (!this.table_name.equals(that.table_name))
return false;
}
boolean this_present_if_exists = true;
boolean that_present_if_exists = true;
if (this_present_if_exists || that_present_if_exists) {
if (!(this_present_if_exists && that_present_if_exists))
return false;
if (this.if_exists != that.if_exists)
return false;
}
return true;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
boolean present_table_name = true && (isSetTable_name());
builder.append(present_table_name);
if (present_table_name)
builder.append(table_name);
boolean present_if_exists = true;
builder.append(present_if_exists);
if (present_if_exists)
builder.append(if_exists);
return builder.toHashCode();
}
public int compareTo(TDropTableOrViewParams other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
TDropTableOrViewParams typedOther = (TDropTableOrViewParams)other;
lastComparison = Boolean.valueOf(isSetTable_name()).compareTo(typedOther.isSetTable_name());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetTable_name()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.table_name, typedOther.table_name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetIf_exists()).compareTo(typedOther.isSetIf_exists());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetIf_exists()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.if_exists, typedOther.if_exists);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TDropTableOrViewParams(");
boolean first = true;
sb.append("table_name:");
if (this.table_name == null) {
sb.append("null");
} else {
sb.append(this.table_name);
}
first = false;
if (!first) sb.append(", ");
sb.append("if_exists:");
sb.append(this.if_exists);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (table_name == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'table_name' was not present! Struct: " + toString());
}
// alas, we cannot check 'if_exists' because it's a primitive and you chose the non-beans generator.
// check for sub-struct validity
if (table_name != null) {
table_name.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class TDropTableOrViewParamsStandardSchemeFactory implements SchemeFactory {
public TDropTableOrViewParamsStandardScheme getScheme() {
return new TDropTableOrViewParamsStandardScheme();
}
}
private static class TDropTableOrViewParamsStandardScheme extends StandardScheme<TDropTableOrViewParams> {
public void read(org.apache.thrift.protocol.TProtocol iprot, TDropTableOrViewParams struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TABLE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.table_name = new com.cloudera.impala.thrift.TTableName();
struct.table_name.read(iprot);
struct.setTable_nameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // IF_EXISTS
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.if_exists = iprot.readBool();
struct.setIf_existsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
if (!struct.isSetIf_exists()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'if_exists' was not found in serialized data! Struct: " + toString());
}
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, TDropTableOrViewParams struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.table_name != null) {
oprot.writeFieldBegin(TABLE_NAME_FIELD_DESC);
struct.table_name.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(IF_EXISTS_FIELD_DESC);
oprot.writeBool(struct.if_exists);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class TDropTableOrViewParamsTupleSchemeFactory implements SchemeFactory {
public TDropTableOrViewParamsTupleScheme getScheme() {
return new TDropTableOrViewParamsTupleScheme();
}
}
private static class TDropTableOrViewParamsTupleScheme extends TupleScheme<TDropTableOrViewParams> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, TDropTableOrViewParams struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
struct.table_name.write(oprot);
oprot.writeBool(struct.if_exists);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, TDropTableOrViewParams struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.table_name = new com.cloudera.impala.thrift.TTableName();
struct.table_name.read(iprot);
struct.setTable_nameIsSet(true);
struct.if_exists = iprot.readBool();
struct.setIf_existsIsSet(true);
}
}
}
| {'content_hash': '5ab383e28dfeb579801032e33771b248', 'timestamp': '', 'source': 'github', 'line_count': 492, 'max_line_length': 184, 'avg_line_length': 33.24593495934959, 'alnum_prop': 0.6838662346396038, 'repo_name': 'dayutianfei/impala-Q', 'id': 'a29d7faff4e8870feb58b3b4f5a70ade1841849d', 'size': '16357', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fe/generated-sources/gen-java/com/cloudera/impala/thrift/TDropTableOrViewParams.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '15836'}, {'name': 'C++', 'bytes': '5750170'}, {'name': 'CMake', 'bytes': '90614'}, {'name': 'CSS', 'bytes': '86925'}, {'name': 'HTML', 'bytes': '56'}, {'name': 'Java', 'bytes': '3897527'}, {'name': 'Lex', 'bytes': '21323'}, {'name': 'Python', 'bytes': '1228318'}, {'name': 'Shell', 'bytes': '131062'}, {'name': 'Thrift', 'bytes': '241288'}, {'name': 'Yacc', 'bytes': '80074'}]} |
<?php
namespace Cloudtek\DynamoDM\Test\Functional;
use Cloudtek\DynamoDM\Mapping\Annotation as ODM;
/**
* Test the orphan removal on embedded documents that contain references with cascade operations.
*/
class OrphanRemovalEmbedTest extends \Cloudtek\DynamoDM\Test\BaseTest
{
/**
* Test unsetting an embedOne relationship
*/
public function testUnsettingEmbedOne()
{
$profile = new OrphanRemovalCascadeProfile();
$address = new OrphanRemovalCascadeAddress();
$user = new OrphanRemovalCascadeUser();
$profile->address = $address;
$user->profile = $profile;
$this->dm->persist($user);
$this->dm->flush();
$user->profile = null;
$this->dm->flush();
$this->dm->clear();
$this->assertNull($this->getAddressRepository()->find($address->id), 'Should have removed the address');
}
/**
* Test Collection::remove() method on an embedMany relationship
*/
public function testRemoveEmbedMany()
{
$profile1 = new OrphanRemovalCascadeProfile();
$address1 = new OrphanRemovalCascadeAddress();
$profile1->address = $address1;
$profile2 = new OrphanRemovalCascadeProfile();
$address2 = new OrphanRemovalCascadeAddress();
$profile2->address = $address2;
$user = new OrphanRemovalCascadeUser();
$user->profileMany[] = $profile1;
$user->profileMany[] = $profile2;
$this->dm->persist($user);
$this->dm->flush();
$this->assertNotNull($this->getAddressRepository()->find($address1->id), 'Should have cascaded persist to address 1');
$this->assertNotNull($this->getAddressRepository()->find($address2->id), 'Should have cascaded persist to address 2');
$user->profileMany->removeElement($profile1);
$this->dm->flush();
$this->dm->clear($user);
$user = $this->getUserRepository()->find($user->id);
$this->assertNotNull($user, 'Should retrieve user');
$this->assertFalse($user->profileMany->contains($profile1), 'Should not contain profile 1');
$this->assertNull($this->getAddressRepository()->find($address1->id), 'Should have removed address 1');
$this->assertTrue($user->profileMany->contains($profile2), 'Should contain profile 2');
$this->assertNotNull($this->getAddressRepository()->find($address2->id), 'Should have kept address 2');
}
/**
* Test Collection::clear() method on an embedMany relationship
*/
public function testClearEmbedMany()
{
$profile1 = new OrphanRemovalCascadeProfile();
$address1 = new OrphanRemovalCascadeAddress();
$profile1->address = $address1;
$profile2 = new OrphanRemovalCascadeProfile();
$address2 = new OrphanRemovalCascadeAddress();
$profile2->address = $address2;
$user = new OrphanRemovalCascadeUser();
$user->profileMany[] = $profile1;
$user->profileMany[] = $profile2;
$this->dm->persist($user);
$this->dm->flush();
$user->profileMany->clear();
$this->dm->flush();
$this->dm->clear($user);
$this->assertNull($this->getAddressRepository()->find($address1->id), 'Should have removed address 1');
$this->assertNull($this->getAddressRepository()->find($address2->id), 'Should have removed address 2');
}
/**
* Test clearing and adding on an embedMany relationship
*/
public function testClearAndAddEmbedMany()
{
$profile1 = new OrphanRemovalCascadeProfile();
$address1 = new OrphanRemovalCascadeAddress();
$profile1->address = $address1;
$profile2 = new OrphanRemovalCascadeProfile();
$address2 = new OrphanRemovalCascadeAddress();
$profile2->address = $address2;
$profile3 = new OrphanRemovalCascadeProfile();
$address3 = new OrphanRemovalCascadeAddress();
$profile3->address = $address3;
$user = new OrphanRemovalCascadeUser();
$user->profileMany[] = $profile1;
$user->profileMany[] = $profile2;
$this->dm->persist($user);
$this->dm->flush();
$user->profileMany->clear();
$user->profileMany->add($profile3);
$this->dm->flush();
$this->dm->clear($user);
$user = $this->getUserRepository()->find($user->id);
$this->assertNotNull($user, 'Should retrieve user');
$this->assertFalse($user->profileMany->contains($profile1), 'Should not contain profile 1');
$this->assertNull($this->getAddressRepository()->find($address1->id), 'Should have removed address 1');
$this->assertFalse($user->profileMany->contains($profile2), 'Should not contain profile 2');
$this->assertNull($this->getAddressRepository()->find($address2->id), 'Should have removed address 2');
$this->assertTrue($user->profileMany->contains($profile3), 'Should contain profile 3');
$this->assertNotNull($this->getAddressRepository()->find($address3->id), 'Should have added address 3');
}
/**
* @return \Cloudtek\DynamoDM\DocumentRepository
*/
private function getUserRepository()
{
return $this->dm->getRepository('Cloudtek\DynamoDM\Test\Functional\OrphanRemovalCascadeUser');
}
/**
* @return \Cloudtek\DynamoDM\DocumentRepository
*/
private function getAddressRepository()
{
return $this->dm->getRepository('Cloudtek\DynamoDM\Test\Functional\OrphanRemovalCascadeAddress');
}
}
/** @ODM\Document */
class OrphanRemovalCascadeUser
{
/**
* @ODM\Attribute(type="string")
* @ODM\HashKey
* @ODM\GeneratedValue(strategy="uuid")
*/
public $id;
/** @ODM\EmbedOne(targetDocument=OrphanRemovalCascadeProfile::class) */
public $profile;
/** @ODM\EmbedMany(targetDocument=OrphanRemovalCascadeProfile::class) */
public $profileMany = array();
}
/** @ODM\EmbeddedDocument */
class OrphanRemovalCascadeProfile
{
/**
* @ODM\Attribute(type="string")
* @ODM\HashKey
* @ODM\GeneratedValue(strategy="uuid")
*/
public $id;
/** @ODM\Attribute(type="string") */
public $name;
/** @ODM\ReferenceOne(targetDocument=OrphanRemovalCascadeAddress::class, orphanRemoval=true, cascade={"all"}) */
public $address;
/** @ODM\ReferenceMany(targetDocument=OrphanRemovalCascadeAddress::class, orphanRemoval=true, cascade={"all"}) */
public $addressMany;
}
/** @ODM\Document */
class OrphanRemovalCascadeAddress
{
/**
* @ODM\Attribute(type="string")
* @ODM\HashKey
* @ODM\GeneratedValue(strategy="uuid")
*/
public $id;
/** @ODM\Attribute(type="string") */
public $name;
}
| {'content_hash': '393327123dfbd1646b2ffdbe3a4cf05e', 'timestamp': '', 'source': 'github', 'line_count': 205, 'max_line_length': 126, 'avg_line_length': 32.9609756097561, 'alnum_prop': 0.6365250850969365, 'repo_name': 'cloudtek/dynamodb-odm', 'id': 'b2dbc197261625fa2ef6744d2f4a07327e5b9364', 'size': '6757', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Cloudtek/DynamoDM/Test/Functional/OrphanRemovalEmbedTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '1870519'}]} |
/**
* Licensed Materials - Property of IBM
* © Copyright IBM Corp. 2015-2018
*/
var Kafka = require('node-rdkafka');
var ProducerLoop = require('./producerLoop.js');
var ConsumerLoop = require('./consumerLoop.js');
var fs = require('fs');
var opts = {};
var topicName = 'kafka-nodejs-console-sample-topic';
var runProducer = true;
var runConsumer = true;
var producer, consumer, admin;
var services;
if (process.env.VCAP_SERVICES) {
console.log("Using VCAP_SERVICES to find credentials.");
services = JSON.parse(process.env.VCAP_SERVICES);
if (services.hasOwnProperty('instance_id')) {
opts.brokers = services.kafka_brokers_sasl;
opts.api_key = services.api_key;
} else {
for (var key in services) {
if (key.lastIndexOf('messagehub', 0) === 0) {
eventStreamsService = services[key][0];
opts.brokers = eventStreamsService.credentials.kafka_brokers_sasl;
opts.api_key = eventStreamsService.credentials.api_key;
}
}
}
opts.calocation = '/etc/ssl/certs';
} else {
// Running locally on development machine
console.log("Using command line arguments to find credentials.");
if (process.argv.length < 5) {
console.log('ERROR: It appears the application is running is running without VCAP_SERVICES but the arguments are incorrect for local mode.');
console.log('\nUsage:\n' +
'node ' + process.argv[1] + ' <kafka_brokers_sasl> <api_key> <cert_location> [ -consumer | -producer ]\n');
process.exit(-1);
}
opts.brokers = process.argv[2];
var apiKey = process.argv[3];
if (apiKey.indexOf(":") != -1) {
var credentialArray = apiKey.split(":");
opts.api_key = credentialArray[1];
} else {
opts.api_key = apiKey;
}
// IBM Cloud/Ubuntu: '/etc/ssl/certs'
// Red Hat: '/etc/pki/tls/cert.pem',
// macOS: '/usr/local/etc/openssl/cert.pem' from openssl installed by brew
opts.calocation = process.argv[4];
if (! fs.existsSync(opts.calocation)) {
console.error('Error - Failed to access <cert_location> : ' + opts.calocation);
process.exit(-1);
}
// In local mode the app can run only the producer or only the consumer
if (process.argv.length === 6) {
if ('-consumer' === process.argv[5])
runProducer = false;
if ('-producer' === process.argv[5])
runConsumer = false;
}
}
console.log("Kafka Endpoints: " + opts.brokers);
if (!opts.hasOwnProperty('brokers') || !opts.hasOwnProperty('api_key') || !opts.hasOwnProperty('calocation')) {
console.error('Error - Failed to retrieve options. Check that app is bound to an Event Streams service or that command line options are correct.');
process.exit(-1);
}
// Shutdown hook
function shutdown(retcode) {
if (admin) { // admin.isConnected() not present
admin.disconnect();
}
if (producer && producer.isConnected()) {
producer.disconnect();
}
if (consumer && consumer.isConnected()) {
consumer.disconnect();
}
clearInterval(ConsumerLoop.consumerLoop);
// ideally we should wait on completion of the async calls
process.exit(retcode);
}
process.on('SIGTERM', function() {
console.log('Shutdown received.');
shutdown(0);
});
process.on('SIGINT', function() {
console.log('Shutdown received.');
shutdown(0);
});
// Config options common to all clients
var driver_options = {
//'debug': 'all',
'metadata.broker.list': opts.brokers,
'security.protocol': 'sasl_ssl',
'ssl.ca.location': opts.calocation,
'sasl.mechanisms': 'PLAIN',
'sasl.username': 'token',
'sasl.password': opts.api_key,
'broker.version.fallback': '0.10.2.1', // still needed with librdkafka 0.11.5
'log.connection.close' : false
};
var admin_opts = {
'client.id': 'kafka-nodejs-console-sample-admin',
};
// Add the common options to client and producer
for (var key in driver_options) {
admin_opts[key] = driver_options[key];
}
// Use the AdminClient API to create the topic
// with 1 partition and a retention period of 24 hours.
console.log('Creating the topic ' + topicName + ' with AdminClient');
admin = Kafka.AdminClient.create(admin_opts);
admin.connect();
console.log("AdminClient connected");
admin.createTopic({
topic: topicName,
num_partitions: 1,
replication_factor: 3,
config: { 'retention.ms': (24*60*60*1000).toString() }
},
function(err) {
if(err) {
console.log(err);
} else {
console.log('Topic ' + topicName + ' created');
}
// carry on if topic created or topic already exists (code 36)
if (!err || err.code == 36) {
runLoops();
console.log("This sample app will run until interrupted.");
admin.disconnect();
} else {
shutdown(-1);
}
}
);
// Build and start the producer/consumer
function runLoops() {
var consumer_opts = {
'client.id': 'kafka-nodejs-console-sample-consumer',
'group.id': 'kafka-nodejs-console-sample-group'
};
var producer_opts = {
'client.id': 'kafka-nodejs-console-sample-producer',
'dr_msg_cb': true // Enable delivery reports with message payload
};
// Add the common options to client and producer
for (var key in driver_options) {
consumer_opts[key] = driver_options[key];
producer_opts[key] = driver_options[key];
}
// Start the clients
if (runConsumer) {
consumer = ConsumerLoop.buildConsumer(Kafka, consumer_opts, topicName, shutdown);
consumer.connect();
}
if (runProducer) {
producer = ProducerLoop.buildProducer(Kafka, producer_opts, topicName, shutdown);
producer.connect();
}
};
| {'content_hash': 'ebd014d1953719d8e64b4b9200836929', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 151, 'avg_line_length': 31.329787234042552, 'alnum_prop': 0.6207130730050934, 'repo_name': 'ibm-messaging/message-hub-samples', 'id': '74d3f34c4ac2ab22f531bfa4b7b865ab2efec456', 'size': '6487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kafka-nodejs-console-sample/app.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2643'}, {'name': 'Dockerfile', 'bytes': '1811'}, {'name': 'HTML', 'bytes': '2186'}, {'name': 'Java', 'bytes': '59292'}, {'name': 'JavaScript', 'bytes': '18123'}, {'name': 'Python', 'bytes': '11702'}]} |
<?php
include "PersistenceInterface.php";
class Mem Implements PersistenceInterface{
protected $type;//type of object
protected $prototype;
protected $search;
protected $buf;
public function __construct($item){
$this->type = gettype($item);
$this->prototype = $item;
$this->buf [$item->Asin]= $item;
}
public function Count() {
return count($this->buf);
}
public function Create($item){
$this->buf[$item->Asin] = $item;
}
public function Read($id) {
$target = $this->prototype.Search($id, $this->buf);
return $target;
}
public function ReadAll() {
return $this->buf;
}
public function Update($id, $values) {
}
public function Delete($id) {
unset($this->buf[$id]);
}
} | {'content_hash': '01f95581aa81dfc758b6f73db17148ad', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 59, 'avg_line_length': 18.31111111111111, 'alnum_prop': 0.566747572815534, 'repo_name': 'sushi0977/Assignment-4', 'id': 'b97e5e881c2dc0aebd0288227e0118c465643973', 'size': '824', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Mem.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '8069'}]} |
__author__ = "Can Ozbek Arnav"
import pandas as pd
import numpy as np
import pylab
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import sys
# sys.path.append("/Users/ahmetcanozbek/Desktop/EE660/660Project/Code_Final_Used/functions")
import ml_aux_functions as ml_aux
import crop_rock
import pickle
#PREPROCESSING
#Read the files
df_full = pd.read_pickle("msd_train_t5.pkl") # 80%
print "DEBUG: file read."
#Get rid of the rows that have missing values (nan) and UNCAT
df_full = df_full[ df_full["Genre"] != "UNCAT" ]
df_full = df_full.dropna()
y_full = df_full["Genre"]
X_full = df_full.drop(["Genre", "Track ID", "Year"], axis=1)
#Split the 80% of data to 70% Training and 30% Validation Data
from sklearn.cross_validation import train_test_split
X_train, X_validation, y_train, y_validation = \
train_test_split(X_full, y_full, train_size=0.7, random_state=42)
print "DEBUG: Data splitted"
df_train_toCrop = pd.concat([y_train, X_train], axis=1, join='inner')
#Crop the dataset
maxval = crop_rock.find_second_max_value(df_train_toCrop)
df_cropped = crop_rock.drop_excess_rows(df_train_toCrop, maxval)
y_cropped = df_cropped["Genre"]
X_cropped = df_cropped.drop(["Genre"], axis=1)
# # Start LDA Classification
# print "Performing LDA Classification:"
# from sklearn.lda import LDA
# clf = LDA(solver='svd', shrinkage=None, n_components=None).fit(X_cropped, np.ravel(y_cropped[:]))
#
# #Use X_cropped to get best model
# y_train_predicted = clf.predict(X_train)
# print "Error rate for LDA on Training: ", ml_aux.get_error_rate(y_train,y_train_predicted)
# # ml_aux.plot_confusion_matrix(y_cropped, predicted, "CM on LDA cropped")
# # plt.show()
#
# y_validation_predicted = clf.predict(X_validation)
# print "Error rate for LDA on Validation: ", ml_aux.get_error_rate(y_validation,y_validation_predicted)
# # ml_aux.plot_confusion_matrix(y_validation, y_validation_predicted, "CM on LDA validation (t1)")
# # plt.show()
#
#
#
# # Start Adaboost Classification
# from sklearn.ensemble import AdaBoostClassifier
# adaboost_model = AdaBoostClassifier(n_estimators=50)
# adaboost_model = adaboost_model.fit(X_cropped,y_cropped)
# # predicted = adaboost_model.predict(X_cropped)
# # print "Error rate for LDA on Cropped: ", ml_aux.get_error_rate(y_cropped,predicted)
# # ml_aux.plot_confusion_matrix(y_cropped, predicted, "CM on LDA cropped")
# # plt.show()
#
# y_validation_predicted = adaboost_model.predict(X_validation)
# print "Error rate for Adaboost on Validation: ", ml_aux.get_error_rate(y_validation,y_validation_predicted)
# # ml_aux.plot_confusion_matrix(y_validation, y_validation_predicted, "CM on Adaboost validation (t1)")
# # plt.show()
#
#
# # Start QDA Classification
# print "Performing QDA Classification:"
# from sklearn.qda import QDA
# clf = QDA(priors=None, reg_param=0.001).fit(X_cropped, np.ravel(y_cropped[:]))
# y_validation_predicted = clf.predict(X_validation)
# print "Error rate for QDA (Validation): ", ml_aux.get_error_rate(y_validation,y_validation_predicted)
# Start Random Forest Classification
print "Performing Random Classification:"
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=500)
forest = forest.fit(X_cropped, np.ravel(y_cropped[:]))
y_validation_predicted = forest.predict(X_validation)
print "Error rate for Random Forest (Validation): ", ml_aux.get_error_rate(y_validation,y_validation_predicted)
# ml_aux.plot_confusion_matrix(y_validation, y_validation_predicted, "CM Random Forest (t1)")
# plt.show()
pickle.dump(forest,open('t5_random_forest.pkl','wb'))
# # Start k nearest neighbor Classification
# print "Performing kNN Classification:"
# from sklearn import neighbors
# knn_model = neighbors.KNeighborsClassifier(n_neighbors=2, algorithm='auto',leaf_size=15)
# knn_model.fit(X_cropped, y_cropped)
# # y_train_predicted = knn_model.predict(X_train)
# # print "Error Rate for kNN (Cropped): ", ml_aux.get_error_rate(y_train, y_train_predicted)
#
# y_validation_predicted = knn_model.predict(X_validation)
# print "Error Rate for kNN on Validation (t1): ", ml_aux.get_error_rate(y_validation, y_validation_predicted)
#
#
# # Start Naive Bayes Classification
# print "Performing Naive Bayes Classification:"
# from sklearn.naive_bayes import GaussianNB
# naivebayes_model = GaussianNB()
# naivebayes_model.fit(X_cropped, y_cropped)
# y_validation_predicted = naivebayes_model.predict(X_validation)
# print "Naive Bayes Error Rate on Validation (t1): ", ml_aux.get_error_rate(y_validation, y_validation_predicted)
#
#
# # Start SVM Classification
# print "Performing SVM Classification:"
# from sklearn.svm import SVC
# svm_model = SVC(kernel='rbf' ,probability=True, max_iter=1000)
# svm_model.fit(X_cropped, y_cropped)
# y_train_predicted = svm_model.predict(X_train)
# print "SVM Error rate on training data (t1): ", ml_aux.get_error_rate(y_train, y_train_predicted)
# # ml_aux.plot_confusion_matrix(y_train, y_train_predicted, "CM SVM Training (t1)")
# # plt.show()
#
# y_validation_predicted = svm_model.predict(X_validation)
# print "SVM Error rate on validation (t1): ", ml_aux.get_error_rate(y_validation, y_validation_predicted)
#
#
# # Start k nearest Centroid Classification
# print "Performing kNC Classification:"
# from sklearn.neighbors.nearest_centroid import NearestCentroid
# knnc_model = NearestCentroid()
# knnc_model.fit(X_cropped, y_cropped)
# y_validation_predicted = knnc_model.predict(X_validation)
# print "Error Rate on kNNC (t1) Validation: ", ml_aux.get_error_rate(y_validation, y_validation_predicted)
#
# # Start Bagging Classification
# print "Performing Bagging Classification:"
# # Bagging
# from sklearn.ensemble import BaggingClassifier
# from sklearn.neighbors import KNeighborsClassifier
#
# # Bagging
# bagging1 = BaggingClassifier(KNeighborsClassifier(n_neighbors=2),max_samples=1.0, max_features=0.1)
# bagging1.fit(X_cropped, y_cropped)
# y_validation_predicted = bagging1.predict(X_validation)
# print "Error Rate kNN with Baggging Validation: ", ml_aux.get_error_rate(y_validation, y_validation_predicted)
#
| {'content_hash': '542b8aec9749e4c95968723f4521270f', 'timestamp': '', 'source': 'github', 'line_count': 149, 'max_line_length': 114, 'avg_line_length': 41.12751677852349, 'alnum_prop': 0.7405352480417755, 'repo_name': 'nishantnath/MusicPredictiveAnalysis_EE660_USCFall2015', 'id': 'd8814ae44e73b67a21a3d5a9a03b3a3f025c92af', 'size': '6128', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Code/Machine_Learning_Algos/training_t5.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Matlab', 'bytes': '4276'}, {'name': 'Python', 'bytes': '255461'}]} |
namespace clotho {
namespace genetics {
template < class AlleleSpace, class BlockType, unsigned char P >
class weight_accumulator< AlleleSpace, association_matrix< BlockType, row_grouped< P > > > {
public:
typedef AlleleSpace allele_type;
typedef association_matrix< BlockType, row_grouped< P > > association_type;
typedef typename allele_type::weight_type weight_type;
typedef typename allele_type::weight_pointer weight_pointer;
typedef typename association_type::block_type block_type;
typedef typename association_type::raw_block_pointer block_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
void operator()( allele_type & alls, association_type & seqs, weight_pointer res, size_t trait_count ) {
size_t M = seqs.row_count();
size_t i = 0;
while( i < M ) {
block_pointer start = seqs.begin_row( i );
block_pointer end = seqs.end_row(i);
size_t j = 0;
while( start != end ) {
block_type b = *start;
while( b ) {
size_t b_idx = j + bit_walker_type::unset_next_index( b );
weight_pointer t_start = alls.begin_trait_weight( b_idx );
weight_pointer t_end = alls.end_trait_weight( b_idx );
size_t a = i * trait_count;
while( t_start != t_end ) {
res[ a++ ] += *t_start++;
}
}
start += row_grouped< P >::GROUP_SIZE;
j += association_type::bit_helper_type::BITS_PER_BLOCK;
}
++i;
}
}
};
template < class AlleleSpace, class BlockType >
class weight_accumulator< AlleleSpace, association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef AlleleSpace allele_type;
typedef association_matrix< BlockType, row_grouped< 1 > > association_type;
typedef typename allele_type::weight_type weight_type;
typedef typename allele_type::weight_pointer weight_pointer;
typedef typename association_type::block_type block_type;
typedef typename association_type::raw_block_pointer block_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
void operator()( allele_type & alls, association_type & seqs, weight_pointer res, size_t trait_count ) {
size_t M = seqs.row_count();
size_t i = 0;
while( i < M ) {
block_pointer start = seqs.begin_row( i );
block_pointer end = seqs.end_row(i);
size_t j = 0;
while( start != end ) {
block_type b = *start++;
while( b ) {
size_t b_idx = j + bit_walker_type::unset_next_index( b );
weight_pointer t_start = alls.begin_trait_weight( b_idx );
weight_pointer t_end = alls.end_trait_weight( b_idx );
size_t a = i * trait_count;
while( t_start != t_end ) {
res[ a++ ] += *t_start++;
}
}
j += association_type::bit_helper_type::BITS_PER_BLOCK;
}
++i;
}
}
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_ROW_GROUPED_WEIGHT_ACCUMULATOR_HPP_
| {'content_hash': '655e5cc94404cd00dd3bf047cd8a7b68', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 108, 'avg_line_length': 34.67619047619048, 'alnum_prop': 0.517165613842351, 'repo_name': 'putnampp/clotho', 'id': '93d855f73dc57c0fa15a630e7f1ac41c1b5d3121', 'size': '4511', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/clotho/data_spaces/phenotype_evaluator/row_grouped_weight_accumulator.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '2235'}, {'name': 'C++', 'bytes': '1925404'}, {'name': 'CMake', 'bytes': '30518'}, {'name': 'Cuda', 'bytes': '65398'}, {'name': 'Makefile', 'bytes': '331'}, {'name': 'Python', 'bytes': '8217'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/1"/>
<open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/1">
<file>file:/Users/berjan/NetBeansProjects/bruens_internal/test.php</file>
</open-files>
</project-private>
| {'content_hash': 'd9039909ed24c5f685ae394b9c686023', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 81, 'avg_line_length': 54.57142857142857, 'alnum_prop': 0.7068062827225131, 'repo_name': 'berjan/br_intern', 'id': '150e6518e9588f24fe33c601b1a0337c2178a4c4', 'size': '382', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'nbproject/private/private.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '64238'}]} |
package org.onosproject.incubator.net.virtual.impl.provider;
import com.google.common.collect.Sets;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.packet.Ethernet;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.incubator.net.virtual.NetworkId;
import org.onosproject.incubator.net.virtual.TenantId;
import org.onosproject.incubator.net.virtual.VirtualDevice;
import org.onosproject.incubator.net.virtual.VirtualNetwork;
import org.onosproject.incubator.net.virtual.VirtualNetworkAdminService;
import org.onosproject.incubator.net.virtual.VirtualNetworkEvent;
import org.onosproject.incubator.net.virtual.VirtualNetworkListener;
import org.onosproject.incubator.net.virtual.VirtualPacketContext;
import org.onosproject.incubator.net.virtual.VirtualPort;
import org.onosproject.incubator.net.virtual.provider.AbstractVirtualProvider;
import org.onosproject.incubator.net.virtual.provider.VirtualPacketProvider;
import org.onosproject.incubator.net.virtual.provider.VirtualPacketProviderService;
import org.onosproject.incubator.net.virtual.provider.VirtualProviderRegistryService;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.instructions.Instruction;
import org.onosproject.net.flow.instructions.Instructions;
import org.onosproject.net.packet.DefaultInboundPacket;
import org.onosproject.net.packet.DefaultOutboundPacket;
import org.onosproject.net.packet.InboundPacket;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.provider.ProviderId;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import java.nio.ByteBuffer;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static org.slf4j.LoggerFactory.getLogger;
@Component(immediate = true)
public class DefaultVirtualPacketProvider extends AbstractVirtualProvider
implements VirtualPacketProvider {
private static final int PACKET_PROCESSOR_PRIORITY = 1;
private static final PacketPriority VIRTUAL_PACKET_PRIORITY = PacketPriority.REACTIVE;
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected PacketService packetService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected VirtualNetworkAdminService vnaService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected VirtualProviderRegistryService providerRegistryService;
private final VirtualNetworkListener virtualNetListener = new InternalVirtualNetworkListener();
private InternalPacketProcessor processor = null;
private Set<NetworkId> networkIdSet = Sets.newConcurrentHashSet();
private ApplicationId appId;
/**
* Creates a provider with the supplied identifier.
*/
public DefaultVirtualPacketProvider() {
super(new ProviderId("virtual-packet", "org.onosproject.virtual.virtual-packet"));
}
@Activate
public void activate() {
appId = coreService.registerApplication("org.onosproject.virtual.virtual-packet");
providerRegistryService.registerProvider(this);
vnaService.addListener(virtualNetListener);
log.info("Started");
}
@Deactivate
public void deactivate() {
providerRegistryService.unregisterProvider(this);
vnaService.removeListener(virtualNetListener);
log.info("Stopped");
}
@Modified
protected void modified(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
}
@Override
public void emit(NetworkId networkId, OutboundPacket packet) {
devirtualize(networkId, packet)
.forEach(outboundPacket -> packetService.emit(outboundPacket));
}
/**
* Just for test.
*/
protected void startPacketHandling() {
processor = new InternalPacketProcessor();
packetService.addProcessor(processor, PACKET_PROCESSOR_PRIORITY);
}
/**
* Send the outbound packet of a virtual context.
* This method is designed to support Context's send() method that invoked
* by applications.
* See {@link org.onosproject.net.packet.PacketContext}
*
* @param virtualPacketContext virtual packet context
*/
protected void send(VirtualPacketContext virtualPacketContext) {
devirtualizeContext(virtualPacketContext)
.forEach(outboundPacket -> packetService.emit(outboundPacket));
}
/**
* Translate the requested physical PacketContext into a virtual PacketContext.
* See {@link org.onosproject.net.packet.PacketContext}
*
* @param context A physical PacketContext be translated
* @return A translated virtual PacketContext
*/
private VirtualPacketContext virtualize(PacketContext context) {
VirtualPort vPort = getMappedVirtualPort(context.inPacket().receivedFrom());
if (vPort != null) {
ConnectPoint cp = new ConnectPoint(vPort.element().id(),
vPort.number());
Ethernet eth = context.inPacket().parsed();
eth.setVlanID(Ethernet.VLAN_UNTAGGED);
InboundPacket inPacket =
new DefaultInboundPacket(cp, eth,
ByteBuffer.wrap(eth.serialize()));
DefaultOutboundPacket outPkt =
new DefaultOutboundPacket(cp.deviceId(),
DefaultTrafficTreatment.builder().build(),
ByteBuffer.wrap(eth.serialize()));
VirtualPacketContext vContext =
new DefaultVirtualPacketContext(context.time(), inPacket, outPkt,
false, vPort.networkId(),
this);
return vContext;
} else {
return null;
}
}
/**
* Find the corresponding virtual port with the physical port.
*
* @param cp the connect point for the physical network
* @return a virtual port
*/
private VirtualPort getMappedVirtualPort(ConnectPoint cp) {
Set<TenantId> tIds = vnaService.getTenantIds();
Set<VirtualNetwork> vNetworks = new HashSet<>();
tIds.forEach(tid -> vNetworks.addAll(vnaService.getVirtualNetworks(tid)));
for (VirtualNetwork vNet : vNetworks) {
Set<VirtualDevice> vDevices = vnaService.getVirtualDevices(vNet.id());
Set<VirtualPort> vPorts = new HashSet<>();
vDevices.forEach(dev -> vPorts
.addAll(vnaService.getVirtualPorts(dev.networkId(), dev.id())));
VirtualPort vPort = vPorts.stream()
.filter(vp -> vp.realizedBy().equals(cp))
.findFirst().orElse(null);
if (vPort != null) {
return vPort;
}
}
return null;
}
/**
* Translate the requested virtual outbound packet into
* a set of physical OutboundPacket.
* See {@link org.onosproject.net.packet.OutboundPacket}
*
* @param packet an OutboundPacket to be translated
* @return a set of de-virtualized (physical) OutboundPacket
*/
private Set<OutboundPacket> devirtualize(NetworkId networkId, OutboundPacket packet) {
Set<OutboundPacket> outboundPackets = new HashSet<>();
Set<VirtualPort> vPorts = vnaService
.getVirtualPorts(networkId, packet.sendThrough());
TrafficTreatment.Builder commonTreatmentBuilder
= DefaultTrafficTreatment.builder();
packet.treatment().allInstructions().stream()
.filter(i -> i.type() != Instruction.Type.OUTPUT)
.forEach(i -> commonTreatmentBuilder.add(i));
TrafficTreatment commonTreatment = commonTreatmentBuilder.build();
PortNumber vOutPortNum = packet.treatment().allInstructions().stream()
.filter(i -> i.type() == Instruction.Type.OUTPUT)
.map(i -> ((Instructions.OutputInstruction) i).port())
.findFirst().get();
if (!vOutPortNum.isLogical()) {
Optional<ConnectPoint> optionalCpOut = vPorts.stream()
.filter(v -> v.number().equals(vOutPortNum))
.map(v -> v.realizedBy())
.findFirst();
if (!optionalCpOut.isPresent()) {
log.warn("Port {} is not realized yet, in Network {}, Device {}",
vOutPortNum, networkId, packet.sendThrough());
return outboundPackets;
}
ConnectPoint egressPoint = optionalCpOut.get();
TrafficTreatment treatment = DefaultTrafficTreatment
.builder(commonTreatment)
.setOutput(egressPoint.port()).build();
OutboundPacket outboundPacket = new DefaultOutboundPacket(
egressPoint.deviceId(), treatment, packet.data());
outboundPackets.add(outboundPacket);
} else {
if (vOutPortNum == PortNumber.FLOOD) {
for (VirtualPort outPort : vPorts) {
ConnectPoint cpOut = outPort.realizedBy();
if (cpOut != null) {
TrafficTreatment treatment = DefaultTrafficTreatment
.builder(commonTreatment)
.setOutput(cpOut.port()).build();
OutboundPacket outboundPacket = new DefaultOutboundPacket(
cpOut.deviceId(), treatment, packet.data());
outboundPackets.add(outboundPacket);
} else {
log.warn("Port {} is not realized yet, in Network {}, Device {}",
outPort.number(), networkId, packet.sendThrough());
}
}
}
}
return outboundPackets;
}
/**
* Translate the requested virtual packet context into
* a set of physical outbound packets.
*
* @param context A handled virtual packet context
*/
private Set<OutboundPacket> devirtualizeContext(VirtualPacketContext context) {
Set<OutboundPacket> outboundPackets = new HashSet<>();
NetworkId networkId = context.networkId();
TrafficTreatment vTreatment = context.treatmentBuilder().build();
DeviceId sendThrough = context.outPacket().sendThrough();
Set<VirtualPort> vPorts = vnaService
.getVirtualPorts(networkId, sendThrough);
PortNumber vOutPortNum = vTreatment.allInstructions().stream()
.filter(i -> i.type() == Instruction.Type.OUTPUT)
.map(i -> ((Instructions.OutputInstruction) i).port())
.findFirst().get();
TrafficTreatment.Builder commonTreatmentBuilder
= DefaultTrafficTreatment.builder();
vTreatment.allInstructions().stream()
.filter(i -> i.type() != Instruction.Type.OUTPUT)
.forEach(i -> commonTreatmentBuilder.add(i));
TrafficTreatment commonTreatment = commonTreatmentBuilder.build();
if (!vOutPortNum.isLogical()) {
Optional<ConnectPoint> optionalCpOut = vPorts.stream()
.filter(v -> v.number().equals(vOutPortNum))
.map(v -> v.realizedBy())
.findFirst();
if (!optionalCpOut.isPresent()) {
log.warn("Port {} is not realized yet, in Network {}, Device {}",
vOutPortNum, networkId, sendThrough);
return outboundPackets;
}
ConnectPoint egressPoint = optionalCpOut.get();
TrafficTreatment treatment = DefaultTrafficTreatment
.builder(commonTreatment)
.setOutput(egressPoint.port()).build();
OutboundPacket outboundPacket = new DefaultOutboundPacket(
egressPoint.deviceId(), treatment, context.outPacket().data());
outboundPackets.add(outboundPacket);
} else {
if (vOutPortNum == PortNumber.FLOOD) {
Set<VirtualPort> outPorts = vPorts.stream()
.filter(vp -> !vp.number().isLogical())
.filter(vp -> vp.number() !=
context.inPacket().receivedFrom().port())
.collect(Collectors.toSet());
for (VirtualPort outPort : outPorts) {
ConnectPoint cpOut = outPort.realizedBy();
if (cpOut != null) {
TrafficTreatment treatment = DefaultTrafficTreatment
.builder(commonTreatment)
.setOutput(cpOut.port()).build();
OutboundPacket outboundPacket = new DefaultOutboundPacket(
cpOut.deviceId(), treatment, context.outPacket().data());
outboundPackets.add(outboundPacket);
} else {
log.warn("Port {} is not realized yet, in Network {}, Device {}",
outPort.number(), networkId, sendThrough);
}
}
}
}
return outboundPackets;
}
private final class InternalPacketProcessor implements PacketProcessor {
@Override
public void process(PacketContext context) {
if (context.isHandled()) {
return;
}
VirtualPacketContext vContexts = virtualize(context);
if (vContexts == null) {
return;
}
VirtualPacketProviderService service =
(VirtualPacketProviderService) providerRegistryService
.getProviderService(vContexts.networkId(),
VirtualPacketProvider.class);
if (service != null) {
service.processPacket(vContexts);
}
}
}
private class InternalVirtualNetworkListener implements VirtualNetworkListener {
@Override
public void event(VirtualNetworkEvent event) {
switch (event.type()) {
case NETWORK_ADDED:
if (networkIdSet.isEmpty()) {
processor = new InternalPacketProcessor();
packetService.addProcessor(processor, PACKET_PROCESSOR_PRIORITY);
log.info("Packet processor {} for virtual network is added.", processor.getClass().getName());
}
networkIdSet.add(event.subject());
break;
case NETWORK_REMOVED:
networkIdSet.remove(event.subject());
if (networkIdSet.isEmpty()) {
packetService.removeProcessor(processor);
log.info("Packet processor {} for virtual network is removed.", processor.getClass().getName());
processor = null;
}
break;
default:
// do nothing
break;
}
}
}
}
| {'content_hash': 'a7fb4d3a6109a493a83647bf02b4d3a3', 'timestamp': '', 'source': 'github', 'line_count': 407, 'max_line_length': 120, 'avg_line_length': 40.21867321867322, 'alnum_prop': 0.6174476143930601, 'repo_name': 'osinstom/onos', 'id': '2d01774f9d2e1224b9edf9bff1cf3358168a10fb', 'size': '16986', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'incubator/net/src/main/java/org/onosproject/incubator/net/virtual/impl/provider/DefaultVirtualPacketProvider.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '233181'}, {'name': 'HTML', 'bytes': '119665'}, {'name': 'Java', 'bytes': '38529527'}, {'name': 'JavaScript', 'bytes': '3930281'}, {'name': 'Makefile', 'bytes': '1058'}, {'name': 'P4', 'bytes': '78664'}, {'name': 'Python', 'bytes': '227209'}, {'name': 'Shell', 'bytes': '4841'}]} |
import types = require("utils/types");
import fs = require("file-system");
import definition = require("image-source");
import common = require("./image-source-common");
import enums = require("ui/enums");
import utils = require("utils/utils");
global.moduleMerge(common, exports);
export class ImageSource implements definition.ImageSource {
public android: android.graphics.Bitmap;
public ios: UIImage;
public loadFromResource(name: string): boolean {
this.android = null;
var res = utils.ad.getApplicationContext().getResources();
if (res) {
var identifier: number = res.getIdentifier(name, 'drawable', utils.ad.getApplication().getPackageName());
if (0 < identifier) {
// Load BitmapDrawable with getDrawable to make use of Android internal caching
var bitmapDrawable = <android.graphics.drawable.BitmapDrawable>res.getDrawable(identifier);
if (bitmapDrawable && bitmapDrawable.getBitmap) {
this.android = bitmapDrawable.getBitmap();
}
}
}
return this.android != null;
}
public loadFromFile(path: string): boolean {
var fileName = types.isString(path) ? path.trim() : "";
if (fileName.indexOf("~/") === 0) {
fileName = fs.path.join(fs.knownFolders.currentApp().path, fileName.replace("~/", ""));
}
this.android = android.graphics.BitmapFactory.decodeFile(fileName, null);
return this.android != null;
}
public loadFromData(data: any): boolean {
this.android = android.graphics.BitmapFactory.decodeStream(data);
return this.android != null;
}
public loadFromBase64(source: string): boolean {
if (types.isString(source)) {
var bytes = android.util.Base64.decode(source, android.util.Base64.DEFAULT);
this.android = android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.length)
}
return this.android != null;
}
public setNativeSource(source: any): boolean {
this.android = source;
return source != null;
}
public saveToFile(path: string, format: string, quality = 100): boolean {
if (!this.android) {
return false;
}
var targetFormat = getTargetFromat(format);
// TODO add exception handling
var outputStream = new java.io.BufferedOutputStream(new java.io.FileOutputStream(path));
var res = this.android.compress(targetFormat, quality, outputStream);
outputStream.close();
return res;
}
public toBase64String(format: string, quality = 100): string {
if (!this.android) {
return null;;
}
var targetFormat = getTargetFromat(format);
var outputStream = new java.io.ByteArrayOutputStream();
var base64Stream = new android.util.Base64OutputStream(outputStream, android.util.Base64.NO_WRAP);
this.android.compress(targetFormat, quality, base64Stream);
base64Stream.close();
outputStream.close();
return outputStream.toString();
}
get height(): number {
if (this.android) {
return this.android.getHeight();
}
return NaN;
}
get width(): number {
if (this.android) {
return this.android.getWidth();
}
return NaN;
}
}
function getTargetFromat(format: string): android.graphics.Bitmap.CompressFormat {
switch (format) {
case enums.ImageFormat.jpeg:
return android.graphics.Bitmap.CompressFormat.JPEG;
default:
return android.graphics.Bitmap.CompressFormat.PNG;
}
}
| {'content_hash': '56d5335299dc89e15a4df990513e5a9a', 'timestamp': '', 'source': 'github', 'line_count': 117, 'max_line_length': 117, 'avg_line_length': 31.99145299145299, 'alnum_prop': 0.6235639861074005, 'repo_name': 'hdeshev/NativeScript', 'id': '50506e2a7196d6bf5efb3261c8de0da9666ec173', 'size': '3745', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'image-source/image-source.android.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '4777'}, {'name': 'HTML', 'bytes': '358'}, {'name': 'JavaScript', 'bytes': '120390'}, {'name': 'TypeScript', 'bytes': '2034804'}]} |
<!doctype html>
<html>
<head>
<title>{% block title %}Pastebong!{% endblock title %}</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
{% include '_menu.html' with title='Foo' %}
{% block content %}
{% endblock content %}
</body>
</html>
| {'content_hash': '346015de42e5b8b60893bd9eabc8833b', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 91, 'avg_line_length': 27.076923076923077, 'alnum_prop': 0.5454545454545454, 'repo_name': 'alanjds/pastebong', 'id': 'bc7998a792fe6a6c4581fe88a412c85c8a1a1ada', 'size': '352', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'texts/templates/base.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '18057'}]} |
class SchedulesController < ApplicationController
def index
if params[:domain_name]
@domain_name = params[:domain_name]
else
@domain_name = ''
end
@filter = sanitize_for_tsm(@domain_name).upcase
@columns = ['schedule_name','starttime','duration','durunits','dayofweek']
@select = tsmdb_select(@columns, 'client_schedules', "domain_name like \'%#{@filter}%\'")
@nodes = @select['output'].split(/\n/)
result_json = Hash.new
result_csv = CSV.new(@columns.join(',') + "\n" + @select['output'], :headers => true, :header_converters => :symbol, :converters => :all)
result_json['schedules'] = result_csv.to_a.map {|row| row.to_hash }
result_json['exit_status'] = @select['exit_status']
respond_to do |format|
format.json { render :json => result_json.to_json }
end
end
def list_by_node
if params[:node_name]
@node_name = params[:node_name]
else
@node_name = ''
end
@filter = sanitize_for_tsm(@node_name).upcase
@columns = ['schedule_name']
@select = tsmdb_select(@columns, 'associations', "node_name = \'#{@filter}\'")
@nodes = @select['output'].split(/\n/)
result_json = Hash.new
result_csv = CSV.new(@columns.join(',') + "\n" + @select['output'], :headers => true, :header_converters => :symbol, :converters => :all)
result_json['schedules'] = result_csv.to_a.map {|row| row.to_hash }
result_json['exit_status'] = @select['exit_status']
respond_to do |format|
format.json { render :json => result_json.to_json }
end
end
def update
unless params[:node_name].nil? or params[:domain_name].nil? or params[:schedule_name].nil? or params[:association].nil?
node_name = sanitize_for_tsm(params[:node_name]).upcase
domain_name = sanitize_for_tsm(params[:domain_name]).upcase
schedule_name = sanitize_for_tsm(params[:schedule_name]).upcase
if params[:association] == 'true'
result = qtsm("define association #{domain_name} #{schedule_name} #{node_name}")
else
result = qtsm("delete association #{domain_name} #{schedule_name} #{node_name}")
end
respond_to do |format|
format.json { render :json => result.to_json }
end
end
end
end
| {'content_hash': 'fb47836ecec13dbdfb9401efdc68954f', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 141, 'avg_line_length': 35.328125, 'alnum_prop': 0.6209641751437417, 'repo_name': 'Lowouik/eztsm', 'id': '4ee56863c262f62a9df37502c837107f33bb4444', 'size': '2261', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'eztsm/app/controllers/schedules_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3123'}, {'name': 'CoffeeScript', 'bytes': '1899'}, {'name': 'HTML', 'bytes': '21644'}, {'name': 'JavaScript', 'bytes': '27569'}, {'name': 'Ruby', 'bytes': '58665'}, {'name': 'Shell', 'bytes': '6135'}]} |
package org.apache.ode.scheduler.simple;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.dao.scheduler.Task;
import org.apache.ode.utils.stl.CollectionsX;
import org.apache.ode.utils.stl.MemberOfFunction;
/**
* Implements the "todo" queue and prioritized scheduling mechanism.
*
* @author mszefler
* @author Maciej Szefler ( m s z e f l e r @ g m a i l . c o m )
*
*/
class SchedulerThread implements Runnable {
private static final Log __log = LogFactory.getLog(SchedulerThread.class);
private static final int TODO_QUEUE_INITIAL_CAPACITY = 200;
/** Jobs ready for immediate execution. */
private PriorityBlockingQueue<Task> _todo;
/** Lock for managing the queue */
private ReentrantLock _lock = new ReentrantLock();
private Condition _activity = _lock.newCondition();
private volatile boolean _done;
private TaskRunner _taskrunner;
private Thread _thread;
SchedulerThread(TaskRunner runner) {
_todo = new PriorityBlockingQueue<Task>(TODO_QUEUE_INITIAL_CAPACITY,
new JobComparatorByDate());
_taskrunner = runner;
}
void start() {
if (_thread != null)
return;
_done = false;
_thread = new Thread(this, "OdeScheduler");
_thread.start();
}
/**
* Shutdown the thread.
*/
void stop() {
if (_thread == null)
return;
_done = true;
_lock.lock();
try {
_activity.signal();
} finally {
_lock.unlock();
}
while (_thread != null)
try {
_thread.join();
_thread = null;
} catch (InterruptedException e) {
;
}
}
/**
* Add a job to the todo queue.
*
* @param job
*/
void enqueue(Task task) {
_lock.lock();
try {
_todo.add(task);
_activity.signal();
} finally {
_lock.unlock();
}
}
/**
* Remove a job to the todo queue.
*
* @param job
*/
void dequeue(Task task) {
_lock.lock();
try {
_todo.remove(task);
_activity.signal();
} finally {
_lock.unlock();
}
}
/**
* Get the size of the todo queue.
*
* @return
*/
public int size() {
return _todo.size();
}
/**
* Pop items off the todo queue, and send them to the task runner for processing.
*/
public void run() {
while (!_done) {
_lock.lock();
try {
long nextjob;
while ((nextjob = nextJobTime()) > 0 && !_done)
_activity.await(nextjob, TimeUnit.MILLISECONDS);
if (!_done && nextjob == 0) {
Task task = _todo.take();
_taskrunner.runTask(task);
}
} catch (InterruptedException ex) {
; // ignore
} finally {
_lock.unlock();
}
}
}
/**
* Calculate the time until the next available job.
*
* @return time until next job, 0 if one is one is scheduled to go, and some
* really large number if there are no jobs to speak of
*/
private long nextJobTime() {
assert _lock.isLocked();
Task job = _todo.peek();
if (job == null)
return Long.MAX_VALUE;
return Math.max(0, job.getScheduledDate() - System.currentTimeMillis());
}
/**
* Remove the tasks of a given type from the list.
* @param tasktype type of task
*/
public void clearTasks(final Class<? extends Task> tasktype) {
_lock.lock();
try {
CollectionsX.remove_if(_todo, new MemberOfFunction<Task>() {
@Override
public boolean isMember(Task o) {
return tasktype.isAssignableFrom(o.getClass());
}
});
} finally {
_lock.unlock();
}
}
}
| {'content_hash': 'b36dc0bcd98a2954986922621f525952', 'timestamp': '', 'source': 'github', 'line_count': 181, 'max_line_length': 85, 'avg_line_length': 24.154696132596683, 'alnum_prop': 0.5258462946020128, 'repo_name': 'riftsaw/riftsaw-ode', 'id': '6da87a5f65369e4e0286aab40623a9f22c8b2905', 'size': '5180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scheduler-simple/src/main/java/org/apache/ode/scheduler/simple/SchedulerThread.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '14386'}, {'name': 'Java', 'bytes': '3864567'}, {'name': 'XSLT', 'bytes': '4334'}]} |
package jbomberman.network.server;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public class ServerSender {
private static final String EXCHANGE_NAME = "Bomberman_Exchange";
private Channel channel;
public ServerSender(Connection connection) throws IOException {
channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true);
}
public void send(byte[] message) throws IOException {
channel.basicPublish(EXCHANGE_NAME, "", null, message);
}
public void close() throws IOException, TimeoutException {
channel.close();
}
}
| {'content_hash': '872eafefcd4e1b7c0e02b384158402f4', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 66, 'avg_line_length': 25.296296296296298, 'alnum_prop': 0.7701317715959004, 'repo_name': 'HSR-SE2Proj/JBomberman', 'id': '480bc54b02589853e167dbfa187e99d38df265e1', 'size': '683', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/jbomberman/network/server/ServerSender.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '142708'}]} |
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.rules.objc;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.rules.objc.BundleableFile.BUNDLED_FIELD;
import static com.google.devtools.build.lib.rules.objc.BundleableFile.BUNDLE_PATH_FIELD;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ObjectArrays;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.rules.apple.AppleToolchain;
import com.google.devtools.build.lib.rules.apple.DottedVersion;
import com.google.devtools.build.lib.rules.objc.ObjcCommandLineOptions.ObjcCrosstoolMode;
import com.google.devtools.build.lib.syntax.SkylarkDict;
import com.google.devtools.build.lib.syntax.SkylarkNestedSet;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for Skylark interaction with the objc_* rules.
*/
@RunWith(JUnit4.class)
public class ObjcSkylarkTest extends ObjcRuleTestCase {
@Override
protected void useConfiguration(String... args) throws Exception {
// Do not test crosstool for skylark tests.
useConfiguration(ObjcCrosstoolMode.OFF, args);
}
@Test
public void testSkylarkRuleCanDependOnNativeAppleRule() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" return struct(",
" found_libs = dep.objc.library,",
" found_hdrs = dep.objc.header,",
" )",
"my_rule = rule(implementation = my_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False, providers = ['objc']),",
"})");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'my_rule')",
"my_rule(",
" name = 'my_target',",
" deps = [':lib'],",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" hdrs = ['b.h']",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
SkylarkNestedSet skylarkLibraries =
(SkylarkNestedSet) skylarkTarget.get("found_libs");
SkylarkNestedSet skylarkHdrs =
(SkylarkNestedSet) skylarkTarget.get("found_hdrs");
assertThat(ActionsTestUtil.baseArtifactNames(skylarkLibraries.getSet(Artifact.class)))
.contains("liblib.a");
assertThat(ActionsTestUtil.baseArtifactNames(skylarkHdrs.getSet(Artifact.class)))
.contains("b.h");
}
@Test
public void testSkylarkProviderRetrievalNoneIfNoProvider() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" objc_provider = dep.objc",
" return struct()",
"my_rule = rule(implementation = my_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False),",
"})");
scratch.file("examples/apple_skylark/a.cc");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'my_rule')",
"my_rule(",
" name = 'my_target',",
" deps = [':lib'],",
")",
"cc_library(",
" name = 'lib',",
" srcs = ['a.cc'],",
" hdrs = ['b.h']",
")");
try {
getConfiguredTarget("//examples/apple_skylark:my_target");
fail("Should throw assertion error");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains("File \"/workspace/examples/apple_skylark/BUILD\", line 3");
assertThat(e).hasMessageThat().contains("my_rule(name = 'my_target')");
assertThat(e)
.hasMessageThat()
.contains("File \"/workspace/examples/rule/apple_rules.bzl\", line 3, in my_rule_impl");
assertThat(e).hasMessageThat().contains("dep.objc");
assertThat(e)
.hasMessageThat()
.contains("<target //examples/apple_skylark:lib> (rule 'cc_library') "
+ "doesn't have provider 'objc'");
}
}
@Test
public void testSkylarkProviderCanCheckForExistanceOfObjcProvider() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" cc_has_provider = hasattr(ctx.attr.deps[0], 'objc')",
" objc_has_provider = hasattr(ctx.attr.deps[1], 'objc')",
" return struct(cc_has_provider=cc_has_provider, objc_has_provider=objc_has_provider)",
"my_rule = rule(implementation = my_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False),",
"})");
scratch.file("examples/apple_skylark/a.cc");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'my_rule')",
"my_rule(",
" name = 'my_target',",
" deps = [':cc_lib', ':objc_lib'],",
")",
"objc_library(",
" name = 'objc_lib',",
" srcs = ['a.m'],",
")",
"cc_library(",
" name = 'cc_lib',",
" srcs = ['a.cc'],",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
boolean ccResult =
(boolean) skylarkTarget.get("cc_has_provider");
boolean objcResult =
(boolean) skylarkTarget.get("objc_has_provider");
assertThat(ccResult).isFalse();
assertThat(objcResult).isTrue();
}
@Test
public void testSkylarkExportsObjcProviderToNativeRule() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" objc_provider = dep.objc",
" return struct(objc=objc_provider)",
"swift_library = rule(implementation = my_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False, providers = ['objc'])",
"})");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'swift_library')",
"swift_library(",
" name='my_target',",
" deps=[':lib'],",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" defines = ['mock_define']",
")",
"objc_binary(",
" name = 'bin',",
" deps = [':my_target']",
")");
ConfiguredTarget binaryTarget = getConfiguredTarget("//examples/apple_skylark:bin");
ObjcProvider objcProvider = binaryTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR);
assertThat(Artifact.toRootRelativePaths(objcProvider.get(ObjcProvider.LIBRARY)))
.contains("examples/apple_skylark/liblib.a");
assertThat(objcProvider.get(ObjcProvider.DEFINE)).contains("mock_define");
}
@Test
public void testObjcRuleCanDependOnArbitrarySkylarkRuleThatProvidesObjc() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" objc_provider = apple_common.new_objc_provider(define=depset(['mock_define']))",
" return struct(objc=objc_provider)",
"my_rule = rule(implementation = my_rule_impl,",
" attrs = {})");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'my_rule')",
"my_rule(",
" name='my_target'",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" deps = [':my_target']",
")",
"objc_binary(",
" name = 'bin',",
" deps = [':lib']",
")");
ConfiguredTarget binaryTarget = getConfiguredTarget("//examples/apple_skylark:bin");
ObjcProvider objcProvider = binaryTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR);
assertThat(objcProvider.get(ObjcProvider.DEFINE)).contains("mock_define");
}
@Test
public void testSkylarkCanAccessAppleConfiguration() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def swift_binary_impl(ctx):",
" cpu = ctx.fragments.apple.ios_cpu()",
" platform = ctx.fragments.apple.ios_cpu_platform()",
" env = ctx.fragments.apple.target_apple_env(platform)",
" xcode_version = ctx.fragments.apple.xcode_version()",
" sdk_version = ctx.fragments.apple.sdk_version_for_platform(platform)",
" single_arch_platform = ctx.fragments.apple.single_arch_platform",
" single_arch_cpu = ctx.fragments.apple.single_arch_cpu",
" platform_type = single_arch_platform.platform_type",
" bitcode_mode = ctx.fragments.apple.bitcode_mode",
" return struct(",
" cpu=cpu,",
" env=env,",
" xcode_version=str(xcode_version),",
" sdk_version=str(sdk_version),",
" single_arch_platform=str(single_arch_platform),",
" single_arch_cpu=str(single_arch_cpu),",
" platform_type=str(platform_type),",
" bitcode_mode=str(bitcode_mode)",
" )",
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"fragments = ['apple']",
")");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
")");
useConfiguration("--cpu=ios_i386", "--xcode_version=7.1");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Object iosCpu = skylarkTarget.get("cpu");
@SuppressWarnings("unchecked")
SkylarkDict<String, String> env =
(SkylarkDict<String, String>) skylarkTarget.get("env");
Object sdkVersion = skylarkTarget.get("sdk_version");
assertThat(iosCpu).isEqualTo("i386");
assertThat(env).containsEntry("APPLE_SDK_PLATFORM", "iPhoneSimulator");
assertThat(env).containsEntry("APPLE_SDK_VERSION_OVERRIDE", "8.4");
assertThat(sdkVersion).isEqualTo("8.4");
assertThat(skylarkTarget.get("xcode_version")).isEqualTo("7.1");
assertThat(skylarkTarget.get("single_arch_platform")).isEqualTo("IOS_SIMULATOR");
assertThat(skylarkTarget.get("single_arch_cpu")).isEqualTo("i386");
assertThat(skylarkTarget.get("platform_type")).isEqualTo("ios");
assertThat(skylarkTarget.get("bitcode_mode")).isEqualTo("none");
}
@Test
public void testSkylarkCanAccessApplePlatformNames() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" platform = ctx.fragments.apple.ios_cpu_platform()",
" return struct(",
" name=platform.name_in_plist,",
" )",
"test_rule = rule(",
"implementation = _test_rule_impl,",
"fragments = ['apple']",
")");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name='my_target',",
")");
useConfiguration("--cpu=ios_i386");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Object name = skylarkTarget.get("name");
assertThat(name).isEqualTo("iPhoneSimulator");
}
@Test
public void testSkylarkCanAccessAppleToolchain() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def swift_binary_impl(ctx):",
" apple_toolchain = apple_common.apple_toolchain()",
" sdk_dir = apple_toolchain.sdk_dir()",
" platform_developer_framework_dir = \\",
" apple_toolchain.platform_developer_framework_dir(ctx.fragments.apple)",
" return struct(",
" platform_developer_framework_dir=platform_developer_framework_dir,",
" sdk_dir=sdk_dir,",
" )",
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"fragments = ['apple']",
")");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
")");
useConfiguration("--cpu=ios_i386");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
String platformDevFrameworksDir =
(String)
skylarkTarget.get("platform_developer_framework_dir");
String sdkDir = (String) skylarkTarget.get("sdk_dir");
assertThat(platformDevFrameworksDir)
.isEqualTo(
AppleToolchain.developerDir()
+ "/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks");
assertThat(sdkDir).isEqualTo(AppleToolchain.sdkDir());
}
@Test
public void testSkylarkCanAccessSdkAndMinimumOs() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def swift_binary_impl(ctx):",
" ios_sdk_version = ctx.fragments.apple.sdk_version_for_platform\\",
"(apple_common.platform.ios_device)",
" watchos_sdk_version = ctx.fragments.apple.sdk_version_for_platform\\",
"(apple_common.platform.watchos_device)",
" tvos_sdk_version = ctx.fragments.apple.sdk_version_for_platform\\",
"(apple_common.platform.tvos_device)",
" macos_sdk_version = ctx.fragments.apple.sdk_version_for_platform\\",
"(apple_common.platform.macos)",
" ios_minimum_os = ctx.fragments.apple.minimum_os_for_platform_type\\",
"(apple_common.platform_type.ios)",
" watchos_minimum_os = ctx.fragments.apple.minimum_os_for_platform_type\\",
"(apple_common.platform_type.watchos)",
" tvos_minimum_os = ctx.fragments.apple.minimum_os_for_platform_type\\",
"(apple_common.platform_type.tvos)",
" return struct(",
" ios_sdk_version=str(ios_sdk_version),",
" watchos_sdk_version=str(watchos_sdk_version),",
" tvos_sdk_version=str(tvos_sdk_version),",
" macos_sdk_version=str(macos_sdk_version),",
" ios_minimum_os=str(ios_minimum_os),",
" watchos_minimum_os=str(watchos_minimum_os),",
" tvos_minimum_os=str(tvos_minimum_os)",
" )",
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"fragments = ['apple']",
")");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
")");
useConfiguration("--ios_sdk_version=1.1", "--ios_minimum_os=1.0",
"--watchos_sdk_version=2.1", "--watchos_minimum_os=2.0",
"--tvos_sdk_version=3.1", "--tvos_minimum_os=3.0",
"--macos_sdk_version=4.1");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
assertThat(skylarkTarget.get("ios_sdk_version")).isEqualTo("1.1");
assertThat(skylarkTarget.get("ios_minimum_os")).isEqualTo("1.0");
assertThat(skylarkTarget.get("watchos_sdk_version")).isEqualTo("2.1");
assertThat(skylarkTarget.get("watchos_minimum_os")).isEqualTo("2.0");
assertThat(skylarkTarget.get("tvos_sdk_version")).isEqualTo("3.1");
assertThat(skylarkTarget.get("tvos_minimum_os")).isEqualTo("3.0");
assertThat(skylarkTarget.get("macos_sdk_version")).isEqualTo("4.1");
useConfiguration("--ios_sdk_version=1.1",
"--watchos_sdk_version=2.1",
"--tvos_sdk_version=3.1",
"--macos_sdk_version=4.1");
skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
assertThat(skylarkTarget.get("ios_sdk_version")).isEqualTo("1.1");
assertThat(skylarkTarget.get("ios_minimum_os")).isEqualTo("1.1");
assertThat(skylarkTarget.get("watchos_sdk_version")).isEqualTo("2.1");
assertThat(skylarkTarget.get("watchos_minimum_os")).isEqualTo("2.1");
assertThat(skylarkTarget.get("tvos_sdk_version")).isEqualTo("3.1");
assertThat(skylarkTarget.get("tvos_minimum_os")).isEqualTo("3.1");
assertThat(skylarkTarget.get("macos_sdk_version")).isEqualTo("4.1");
}
@Test
public void testSkylarkCanAccessObjcConfiguration() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/objc_rules.bzl",
"def swift_binary_impl(ctx):",
" copts = ctx.fragments.objc.copts",
" compilation_mode_copts = ctx.fragments.objc.copts_for_current_compilation_mode",
" ios_simulator_device = ctx.fragments.objc.ios_simulator_device",
" ios_simulator_version = ctx.fragments.objc.ios_simulator_version",
" signing_certificate_name = ctx.fragments.objc.signing_certificate_name",
" generate_dsym = ctx.fragments.objc.generate_dsym",
" return struct(",
" copts=copts,",
" compilation_mode_copts=compilation_mode_copts,",
" ios_simulator_device=ios_simulator_device,",
" ios_simulator_version=str(ios_simulator_version),",
" signing_certificate_name=signing_certificate_name,",
" generate_dsym=generate_dsym,",
" )",
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"fragments = ['objc']",
")");
scratch.file("examples/objc_skylark/a.m");
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
")");
useConfiguration(
"--compilation_mode=opt",
"--objccopt=-DTestObjcCopt",
"--ios_simulator_device='iPhone 6'",
"--ios_simulator_version=8.4",
"--ios_signing_cert_name='Apple Developer'",
"--apple_generate_dsym");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/objc_skylark:my_target");
@SuppressWarnings("unchecked")
List<String> copts = (List<String>) skylarkTarget.get("copts");
@SuppressWarnings("unchecked")
List<String> compilationModeCopts = (List<String>) skylarkTarget.get("compilation_mode_copts");
Object iosSimulatorDevice = skylarkTarget.get("ios_simulator_device");
Object iosSimulatorVersion = skylarkTarget.get("ios_simulator_version");
Object signingCertificateName = skylarkTarget.get("signing_certificate_name");
Boolean generateDsym = (Boolean) skylarkTarget.get("generate_dsym");
assertThat(copts).contains("-DTestObjcCopt");
assertThat(compilationModeCopts).containsExactlyElementsIn(ObjcConfiguration.OPT_COPTS);
assertThat(iosSimulatorDevice).isEqualTo("'iPhone 6'");
assertThat(iosSimulatorVersion).isEqualTo("8.4");
assertThat(signingCertificateName).isEqualTo("'Apple Developer'");
assertThat(generateDsym).isTrue();
}
@Test
public void testSigningCertificateNameCanReturnNone() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/objc_rules.bzl",
"def my_rule_impl(ctx):",
" signing_certificate_name = ctx.fragments.objc.signing_certificate_name",
" return struct(",
" signing_certificate_name=str(signing_certificate_name),",
" )",
"my_rule = rule(",
"implementation = my_rule_impl,",
"fragments = ['objc']",
")");
scratch.file("examples/objc_skylark/a.m");
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'my_rule')",
"my_rule(",
" name='my_target',",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/objc_skylark:my_target");
Object signingCertificateName = skylarkTarget.get("signing_certificate_name");
assertThat(signingCertificateName).isEqualTo("None");
}
@Test
public void testUsesDebugEntitlementsIsTrueIfCompilationModeIsNotOpt() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/objc_rules.bzl",
"def test_rule_impl(ctx):",
" uses_device_debug_entitlements = ctx.fragments.objc.uses_device_debug_entitlements",
" return struct(",
" uses_device_debug_entitlements=uses_device_debug_entitlements,",
" )",
"test_rule = rule(",
"implementation = test_rule_impl,",
"fragments = ['objc']",
")");
scratch.file("examples/objc_skylark/a.m");
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'test_rule')",
"test_rule(",
" name='my_target',",
")");
useConfiguration("--compilation_mode=dbg");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/objc_skylark:my_target");
boolean usesDeviceDebugEntitlements = (boolean) skylarkTarget
.get("uses_device_debug_entitlements");
assertThat(usesDeviceDebugEntitlements).isTrue();
}
@Test
public void testUsesDebugEntitlementsIsFalseIfFlagIsExplicitlyFalse() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/objc_rules.bzl",
"def test_rule_impl(ctx):",
" uses_device_debug_entitlements = ctx.fragments.objc.uses_device_debug_entitlements",
" return struct(",
" uses_device_debug_entitlements=uses_device_debug_entitlements,",
" )",
"test_rule = rule(",
"implementation = test_rule_impl,",
"fragments = ['objc']",
")");
scratch.file("examples/objc_skylark/a.m");
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'test_rule')",
"test_rule(",
" name='my_target',",
")");
useConfiguration(
"--compilation_mode=dbg",
"--nodevice_debug_entitlements");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/objc_skylark:my_target");
boolean usesDeviceDebugEntitlements = (boolean) skylarkTarget
.get("uses_device_debug_entitlements");
assertThat(usesDeviceDebugEntitlements).isFalse();
}
@Test
public void testUsesDebugEntitlementsIsFalseIfCompilationModeIsOpt() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/objc_rules.bzl",
"def test_rule_impl(ctx):",
" uses_device_debug_entitlements = ctx.fragments.objc.uses_device_debug_entitlements",
" return struct(",
" uses_device_debug_entitlements=uses_device_debug_entitlements,",
" )",
"test_rule = rule(",
"implementation = test_rule_impl,",
"fragments = ['objc']",
")");
scratch.file("examples/objc_skylark/a.m");
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'test_rule')",
"test_rule(",
" name='my_target',",
")");
useConfiguration("--compilation_mode=opt");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/objc_skylark:my_target");
boolean usesDeviceDebugEntitlements = (boolean) skylarkTarget
.get("uses_device_debug_entitlements");
assertThat(usesDeviceDebugEntitlements).isFalse();
}
private ConfiguredTarget createObjcProviderSkylarkTarget(String... implLines) throws Exception {
String[] impl =
ObjectArrays.concat(
ObjectArrays.concat("def swift_binary_impl(ctx):", implLines),
new String[] {
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"attrs = {",
" 'deps': attr.label_list(",
"allow_files = False, mandatory = False, providers = ['objc'])",
"})"
},
String.class);
scratch.file("examples/rule/BUILD");
scratch.file("examples/rule/objc_rules.bzl", impl);
scratch.file(
"examples/objc_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/objc_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
" deps=[':lib'],",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" defines = ['define_from_dep']",
")");
return getConfiguredTarget("//examples/objc_skylark:my_target");
}
@Test
public void testSkylarkCanCreateObjcProviderFromScratch() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" defines = depset(['define1', 'define2'])",
" linkopts = depset(['somelinkopt'])",
" created_provider = apple_common.new_objc_provider\\",
"(define=defines, linkopt=linkopts)",
" return struct(objc=created_provider)");
Iterable<String> foundLinkopts =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).get(ObjcProvider.LINKOPT);
Iterable<String> foundDefines =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).get(ObjcProvider.DEFINE);
boolean usesSwift =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).is(ObjcProvider.Flag.USES_SWIFT);
assertThat(foundLinkopts).containsExactly("somelinkopt");
assertThat(foundDefines).containsExactly("define1", "define2");
assertThat(usesSwift).isFalse();
}
@Test
public void testSkylarkCanPassLinkInputsInObjcProvider() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" file = ctx.actions.declare_file('foo.ast')",
" ctx.actions.run_shell(outputs=[file], command='echo')",
" link_inputs = depset([file])",
" created_provider = apple_common.new_objc_provider\\",
"(link_inputs=link_inputs)",
" return struct(objc=created_provider)");
Iterable<Artifact> foundLinkInputs =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).get(ObjcProvider.LINK_INPUTS);
assertThat(ActionsTestUtil.baseArtifactNames(foundLinkInputs)).contains("foo.ast");
}
@Test
public void testSkylarkCanPassUsesSwiftFlag() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(uses_swift=True)",
" return struct(objc=created_provider)");
boolean usesSwift =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).is(ObjcProvider.Flag.USES_SWIFT);
assertThat(usesSwift).isTrue();
}
@Test
public void testSkylarkCanCreateObjcProviderWithPathFragments() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" includes = depset(['path1', 'path_dir/path2', 'path_dir1/path_dir2/path3'])",
" created_provider = apple_common.new_objc_provider\\",
"(include=includes)",
" return struct(objc=created_provider)");
Iterable<PathFragment> foundIncludes =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).get(ObjcProvider.INCLUDE);
assertThat(foundIncludes)
.containsExactly(
PathFragment.create("path1"),
PathFragment.create("path_dir/path2"),
PathFragment.create("path_dir1/path_dir2/path3"));
}
@Test
public void testSkylarkCanCreateObjcProviderWithStrictDeps() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" strict_includes = depset(['path1'])",
" propagated_includes = depset(['path2'])",
" strict_provider = apple_common.new_objc_provider\\",
"(include=strict_includes)",
" created_provider = apple_common.new_objc_provider\\",
"(include=propagated_includes, direct_dep_providers=[strict_provider])",
" return struct(objc=created_provider)");
ObjcProvider skylarkProvider = skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR);
ObjcProvider skylarkProviderDirectDepender =
new ObjcProvider.Builder().addTransitiveAndPropagate(skylarkProvider).build();
ObjcProvider skylarkProviderIndirectDepender =
new ObjcProvider.Builder().addTransitiveAndPropagate(skylarkProviderDirectDepender).build();
assertThat(skylarkProvider.get(ObjcProvider.INCLUDE))
.containsExactly(PathFragment.create("path1"), PathFragment.create("path2"));
assertThat(skylarkProviderDirectDepender.get(ObjcProvider.INCLUDE))
.containsExactly(PathFragment.create("path1"), PathFragment.create("path2"));
assertThat(skylarkProviderIndirectDepender.get(ObjcProvider.INCLUDE))
.containsExactly(PathFragment.create("path2"));
}
@Test
public void testSkylarkCanCreateObjcProviderFromObjcProvider() throws Exception {
ConfiguredTarget skylarkTarget =
createObjcProviderSkylarkTarget(
" dep = ctx.attr.deps[0]",
" define = depset(['define_from_impl'])",
" created_provider = apple_common.new_objc_provider\\",
"(providers=[dep.objc], define=define)",
" return struct(objc=created_provider)");
Iterable<String> foundStrings =
skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR).get(ObjcProvider.DEFINE);
assertThat(foundStrings).containsExactly("define_from_dep", "define_from_impl");
}
@Test
public void testSkylarkErrorOnBadObjcProviderInputKey() throws Exception {
try {
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(foo=depset(['bar']))",
" return struct(objc=created_provider)");
fail("Should throw AssertionError");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains(String.format(AppleSkylarkCommon.BAD_KEY_ERROR, "foo"));
}
}
@Test
public void testSkylarkErrorOnNonSetObjcProviderInputValue() throws Exception {
try {
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(library='bar')",
" return struct(objc=created_provider)");
fail("Should throw AssertionError");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains(String.format(AppleSkylarkCommon.NOT_SET_ERROR, "library", "string"));
}
}
@Test
public void testSkylarkErrorOnObjcProviderInputValueWrongSetType() throws Exception {
try {
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(library=depset(['bar']))",
" return struct(objc=created_provider)");
fail("Should throw AssertionError");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains(
String.format(AppleSkylarkCommon.BAD_SET_TYPE_ERROR, "library", "File", "string"));
}
}
@Test
public void testSkylarkErrorOnNonIterableObjcProviderProviderValue() throws Exception {
try {
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(providers='bar')",
" return struct(objc=created_provider)");
fail("Should throw AssertionError");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains(String.format(AppleSkylarkCommon.BAD_PROVIDERS_ITER_ERROR, "string"));
}
}
@Test
public void testSkylarkErrorOnBadIterableObjcProviderProviderValue() throws Exception {
try {
createObjcProviderSkylarkTarget(
" created_provider = apple_common.new_objc_provider(providers=['bar'])",
" return struct(objc=created_provider)");
fail("Should throw AssertionError");
} catch (AssertionError e) {
assertThat(e)
.hasMessageThat()
.contains(String.format(AppleSkylarkCommon.BAD_PROVIDERS_ELEM_ERROR, "string"));
}
}
@Test
public void testEmptyObjcProviderKeysArePresent() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def swift_binary_impl(ctx):",
" objc_provider = ctx.attr.deps[0].objc",
" return struct(",
" empty_value=objc_provider.include,",
" )",
"swift_binary = rule(",
"implementation = swift_binary_impl,",
"fragments = ['apple'],",
"attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False, providers = ['objc'])",
"})");
scratch.file("examples/apple_skylark/a.m");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'swift_binary')",
"swift_binary(",
" name='my_target',",
" deps=[':lib'],",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
SkylarkNestedSet emptyValue =
(SkylarkNestedSet)
skylarkTarget.get("empty_value");
assertThat(emptyValue.toCollection()).isEmpty();
}
@Test
public void testSkylarkCanAccessProvidedBundleFiles() throws Exception {
// Since the collections of structs with Artifact values are extremely difficult to test with
// Truth, we fudge them in the Skylark side to return easily comparable dictionaries instead.
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _simplify_bundle_file(bf):",
" return {'file': bf.file.path, 'bundle_path': bf.bundle_path}",
"def _test_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" objc_provider = dep.objc",
" bundle_file = [_simplify_bundle_file(bf) for bf in list(objc_provider.bundle_file)]",
" return struct(",
" bundle_file=bundle_file,",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False, providers = ['objc'])",
"})");
scratch.file("examples/apple_skylark/a.m");
scratch.file("examples/apple_skylark/flattened/a/a.txt");
scratch.file("examples/apple_skylark/flattened/b.lproj/b.txt");
scratch.file("examples/apple_skylark/structured/c/c.txt");
scratch.file("examples/apple_skylark/structured/d/d.txt");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" resources = glob(['flattened/**']),",
" structured_resources = glob(['structured/**']),",
")",
"test_rule(",
" name = 'my_target',",
" deps = [':lib'],",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Iterable<?> bundleFiles = (Iterable<?>)
skylarkTarget.get("bundle_file");
assertThat(bundleFiles).containsAllOf(ImmutableMap.of(
BUNDLE_PATH_FIELD, "a.txt",
BUNDLED_FIELD, "examples/apple_skylark/flattened/a/a.txt"
), ImmutableMap.of(
BUNDLE_PATH_FIELD, "b.lproj/b.txt",
BUNDLED_FIELD, "examples/apple_skylark/flattened/b.lproj/b.txt"
), ImmutableMap.of(
BUNDLE_PATH_FIELD, "structured/c/c.txt",
BUNDLED_FIELD, "examples/apple_skylark/structured/c/c.txt"
), ImmutableMap.of(
BUNDLE_PATH_FIELD, "structured/d/d.txt",
BUNDLED_FIELD, "examples/apple_skylark/structured/d/d.txt"
));
}
@Test
public void testSkylarkCanAccessSdkFrameworks() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" objc_provider = dep.objc",
" return struct(",
" sdk_frameworks=objc_provider.sdk_framework,",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False, providers = ['objc'])",
"})");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" sdk_frameworks = ['Accelerate', 'GLKit'],",
")",
"test_rule(",
" name = 'my_target',",
" deps = [':lib'],",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
SkylarkNestedSet sdkFrameworks = (SkylarkNestedSet)
skylarkTarget.get("sdk_frameworks");
assertThat(sdkFrameworks.toCollection()).containsAllOf("Accelerate", "GLKit");
}
@Test
public void testSkylarkCanAccessAndUseApplePlatformTypes() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" apple = ctx.fragments.apple",
" ios_platform = apple.multi_arch_platform(apple_common.platform_type.ios)",
" watchos_platform = apple.multi_arch_platform(apple_common.platform_type.watchos)",
" tvos_platform = apple.multi_arch_platform(apple_common.platform_type.tvos)",
" return struct(",
" ios_platform=str(ios_platform),",
" watchos_platform=str(watchos_platform),",
" tvos_platform=str(tvos_platform),",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" fragments = ['apple'])");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
useConfiguration(
"--ios_multi_cpus=arm64,armv7",
"--watchos_cpus=armv7k",
"--tvos_cpus=arm64");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Object iosPlatform =
skylarkTarget.get("ios_platform");
Object watchosPlatform =
skylarkTarget.get("watchos_platform");
Object tvosPlatform =
skylarkTarget.get("tvos_platform");
assertThat(iosPlatform).isEqualTo("IOS_DEVICE");
assertThat(watchosPlatform).isEqualTo("WATCHOS_DEVICE");
assertThat(tvosPlatform).isEqualTo("TVOS_DEVICE");
}
@Test
public void testPlatformIsDeviceReturnsTrueForDevicePlatforms() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" apple = ctx.fragments.apple",
" platform = apple.multi_arch_platform(apple_common.platform_type.ios)",
" return struct(",
" is_device=platform.is_device,",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" fragments = ['apple'])");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
useConfiguration(
"--ios_multi_cpus=arm64,armv7");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Boolean isDevice =
(Boolean) skylarkTarget.get("is_device");
assertThat(isDevice).isTrue();
}
@Test
public void testPlatformIsDeviceReturnsFalseForSimulatorPlatforms() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" apple = ctx.fragments.apple",
" platform = apple.multi_arch_platform(apple_common.platform_type.ios)",
" return struct(",
" is_device=platform.is_device,",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" fragments = ['apple'])");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
Boolean isDevice =
(Boolean) skylarkTarget.get("is_device");
assertThat(isDevice).isFalse();
}
@Test
public void testXcTestAppProviderCanBeCreated() throws Exception {
scratch.file("examples/rule/BUILD",
"exports_files(['test_artifact'])");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" artifact = list(ctx.attr.test_artifact.files)[0]",
" objc_provider = apple_common.new_objc_provider(define=depset(['TEST_DEFINE']))",
" xctest_app_provider = apple_common.new_xctest_app_provider(",
" bundle_loader=artifact, ipa=artifact, objc_provider=objc_provider)",
" return struct(",
" xctest_app=xctest_app_provider,",
" )",
"test_rule = rule(implementation = _test_rule_impl,",
" attrs = {",
" 'test_artifact': attr.label(",
" allow_single_file=True,",
" default=Label('//examples/rule:test_artifact')),",
" })");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
XcTestAppProvider xcTestAppProvider = skylarkTarget.get(XcTestAppProvider.SKYLARK_CONSTRUCTOR);
assertThat(xcTestAppProvider.getBundleLoader().getRootRelativePathString())
.isEqualTo("examples/rule/test_artifact");
assertThat(xcTestAppProvider.getIpa().getRootRelativePathString())
.isEqualTo("examples/rule/test_artifact");
assertThat(xcTestAppProvider.getObjcProvider().get(ObjcProvider.DEFINE))
.containsExactly("TEST_DEFINE");
}
@Test
public void testSkylarkWithRunMemleaksEnabled() throws Exception {
useConfiguration("--ios_memleaks");
checkSkylarkRunMemleaksWithExpectedValue(true);
}
@Test
public void testSkylarkWithRunMemleaksDisabled() throws Exception {
checkSkylarkRunMemleaksWithExpectedValue(false);
}
@Test
public void testDottedVersion() throws Exception {
scratch.file("examples/rule/BUILD",
"exports_files(['test_artifact'])");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" version = apple_common.dotted_version('5.4')",
" return struct(",
" version=version",
" )",
"test_rule = rule(implementation = _test_rule_impl)");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
DottedVersion version = (DottedVersion) skylarkTarget.get("version");
assertThat(version).isEqualTo(DottedVersion.fromString("5.4"));
}
@Test
public void testDottedVersion_invalid() throws Exception {
scratch.file("examples/rule/BUILD",
"exports_files(['test_artifact'])");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" version = apple_common.dotted_version('hello')",
" return struct(",
" version=version",
" )",
"test_rule = rule(implementation = _test_rule_impl)");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
try {
getConfiguredTarget("//examples/apple_skylark:my_target");
fail("Expected an error to be thrown for invalid dotted version string");
} catch (AssertionError e) {
assertThat(e).hasMessageThat().contains("illegal argument in call to dotted_version");
assertThat(e).hasMessageThat().contains("Dotted version components must all be of the form");
}
}
/**
* This test verifies that its possible to use the skylark constructor of ObjcProvider as a
* provider key to obtain the provider. This test only needs to exist as long as there are
* two methods of retrieving ObjcProvider (which is true for legacy reasons). This is the
* 'new' method of retrieving ObjcProvider.
*/
@Test
public void testObjcProviderSkylarkConstructor() throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def my_rule_impl(ctx):",
" dep = ctx.attr.deps[0]",
" objc_provider = dep[apple_common.Objc]",
" return struct(objc=objc_provider)",
"my_rule = rule(implementation = my_rule_impl,",
" attrs = {",
" 'deps': attr.label_list(allow_files = False, mandatory = False),",
"})");
scratch.file("examples/apple_skylark/a.cc");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'my_rule')",
"my_rule(",
" name = 'my_target',",
" deps = [':lib'],",
")",
"objc_library(",
" name = 'lib',",
" srcs = ['a.m'],",
" hdrs = ['a.h']",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
assertThat(skylarkTarget.get(ObjcProvider.SKYLARK_CONSTRUCTOR)).isNotNull();
}
private void checkSkylarkRunMemleaksWithExpectedValue(boolean expectedValue) throws Exception {
scratch.file("examples/rule/BUILD");
scratch.file(
"examples/rule/apple_rules.bzl",
"def _test_rule_impl(ctx):",
" return struct(run_memleaks = ctx.fragments.objc.run_memleaks)",
"test_rule = rule(implementation = _test_rule_impl,",
" fragments = ['objc'],",
" attrs = {},",
")");
scratch.file(
"examples/apple_skylark/BUILD",
"package(default_visibility = ['//visibility:public'])",
"load('/examples/rule/apple_rules', 'test_rule')",
"test_rule(",
" name = 'my_target',",
")");
ConfiguredTarget skylarkTarget = getConfiguredTarget("//examples/apple_skylark:my_target");
boolean runMemleaks = (boolean) skylarkTarget.get("run_memleaks");
assertThat(runMemleaks).isEqualTo(expectedValue);
}
}
| {'content_hash': 'cc3fb40bc01cfdf1fca6a0da82b75862', 'timestamp': '', 'source': 'github', 'line_count': 1273, 'max_line_length': 100, 'avg_line_length': 39.49646504320503, 'alnum_prop': 0.6204379562043796, 'repo_name': 'variac/bazel', 'id': '11d36332da1ba0199a876eb9e5d2f0ec486c11a1', 'size': '50279', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/google/devtools/build/lib/rules/objc/ObjcSkylarkTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '24765'}, {'name': 'C++', 'bytes': '796910'}, {'name': 'HTML', 'bytes': '18128'}, {'name': 'Java', 'bytes': '20748121'}, {'name': 'JavaScript', 'bytes': '5159'}, {'name': 'Makefile', 'bytes': '248'}, {'name': 'PowerShell', 'bytes': '7559'}, {'name': 'Protocol Buffer', 'bytes': '118764'}, {'name': 'Python', 'bytes': '290195'}, {'name': 'Shell', 'bytes': '753627'}]} |
package org.gradle.test.performance.mediummonolithicjavaproject.p266;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test5330 {
Production5330 objectUnderTest = new Production5330();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | {'content_hash': '42b7ef674a3169a1496ced7c312d45e7', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 69, 'avg_line_length': 26.72151898734177, 'alnum_prop': 0.6447181430601611, 'repo_name': 'oehme/analysing-gradle-performance', 'id': 'a0121e24c3de6e4bff5e24df0421fb92d2a489e2', 'size': '2111', 'binary': False, 'copies': '1', 'ref': 'refs/heads/before', 'path': 'my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p266/Test5330.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '40770723'}]} |
FROM balenalib/jetson-nano-debian:bullseye-run
ENV NODE_VERSION 14.16.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "2b78771550f8a3e6e990d8e60e9ade82c7a9e2738b6222e92198bcd5ea857ea6 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.16.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {'content_hash': '4635d3c9496fbea6c5f736f4eb4c9c20', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 694, 'avg_line_length': 64.93333333333334, 'alnum_prop': 0.704312114989733, 'repo_name': 'nghiant2710/base-images', 'id': '4da253abf931e32cbc9171106f0d4ec5020c337c', 'size': '2943', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/node/jetson-nano/debian/bullseye/14.16.0/run/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]} |
class CreateCmsArticles < ActiveRecord::Migration
def change
create_table :cms_articles do |t|
t.integer :user_id, null: false
t.integer :tid, null:false
t.string :lang, null: false, limit:5
t.string :logo
t.string :title, null: false
t.string :summary
t.text :body, null: false
t.integer :visits, null: false, default: 0
t.datetime :last_edit, null: false
t.datetime :created, null: false
t.integer :version, null: false, default: 0
end
add_index :cms_articles, :lang
end
end
| {'content_hash': 'f9c49896ca40677fb1177520f88f6f90', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 49, 'avg_line_length': 31.055555555555557, 'alnum_prop': 0.6368515205724508, 'repo_name': 'chonglou/portal', 'id': 'a0aca5c19b44155ceeb2d3c7feaa0af47ef14a64', 'size': '559', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/migrate/20140505004819_create_cms_articles.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '271'}, {'name': 'JavaScript', 'bytes': '248'}, {'name': 'Ruby', 'bytes': '79228'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc (1.8.0_66-internal) on Wed Jan 06 11:49:35 CET 2016 -->
<title>Uses of Class org.homedrop.PluginPermissions</title>
<meta name="date" content="2016-01-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.homedrop.PluginPermissions";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/homedrop/class-use/PluginPermissions.html" target="_top">Frames</a></li>
<li><a href="PluginPermissions.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.homedrop.PluginPermissions" class="title">Uses of Class<br>org.homedrop.PluginPermissions</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">PluginPermissions</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.homedrop">org.homedrop</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.homedrop">
<!-- -->
</a>
<h3>Uses of <a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">PluginPermissions</a> in <a href="../../../org/homedrop/package-summary.html">org.homedrop</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../org/homedrop/package-summary.html">org.homedrop</a> that return <a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">PluginPermissions</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">PluginPermissions</a></code></td>
<td class="colLast"><span class="typeNameLabel">PluginPermissions.</span><code><span class="memberNameLink"><a href="../../../org/homedrop/PluginPermissions.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">PluginPermissions</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">PluginPermissions.</span><code><span class="memberNameLink"><a href="../../../org/homedrop/PluginPermissions.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../org/homedrop/PluginPermissions.html" title="enum in org.homedrop">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/homedrop/class-use/PluginPermissions.html" target="_top">Frames</a></li>
<li><a href="PluginPermissions.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {'content_hash': 'cf76b6361f3727b1240bea0bf06eb50d', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 264, 'avg_line_length': 38.75722543352601, 'alnum_prop': 0.6499627143922446, 'repo_name': 'm87/homedrop', 'id': '740aa9256aea5fdb86bed629c1335d9475a3eaf3', 'size': '6705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/org/homedrop/class-use/PluginPermissions.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '97'}, {'name': 'Java', 'bytes': '190457'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.10.27 - v0.10.28: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.10.27 - v0.10.28
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_heap_statistics.html">HeapStatistics</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">v8::HeapStatistics Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>heap_size_limit</b>() (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>HeapStatistics</b>() (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>total_heap_size</b>() (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>total_heap_size_executable</b>() (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>used_heap_size</b>() (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>V8</b> (defined in <a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a>)</td><td class="entry"><a class="el" href="classv8_1_1_heap_statistics.html">v8::HeapStatistics</a></td><td class="entry"><span class="mlabel">friend</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:45:14 for V8 API Reference Guide for node.js v0.10.27 - v0.10.28 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| {'content_hash': '17a9419c4ae1c4ccd15e4d497b0f1705', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 335, 'avg_line_length': 57.5625, 'alnum_prop': 0.656429346983093, 'repo_name': 'v8-dox/v8-dox.github.io', 'id': '087da5ef85f831d83c855f6c23d160de408bb491', 'size': '6447', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '3f3a71e/html/classv8_1_1_heap_statistics-members.html', 'mode': '33188', 'license': 'mit', 'language': []} |
/*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DocumentSet = undefined;
var _assert = require('../util/assert');
var _sorted_map = require('../util/sorted_map');
var _collections = require('./collections');
var _document_key = require('./document_key');
/**
* DocumentSet is an immutable (copy-on-write) collection that holds documents
* in order specified by the provided comparator. We always add a document key
* comparator on top of what is provided to guarantee document equality based on
* the key.
*/
/**
* Copyright 2017 Google Inc.
*
* 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.
*/
var DocumentSet = /** @class */function () {
/** The default ordering is by key if the comparator is omitted */
function DocumentSet(comp) {
// We are adding document key comparator to the end as it's the only
// guaranteed unique property of a document.
if (comp) {
this.comparator = function (d1, d2) {
return comp(d1, d2) || _document_key.DocumentKey.comparator(d1.key, d2.key);
};
} else {
this.comparator = function (d1, d2) {
return _document_key.DocumentKey.comparator(d1.key, d2.key);
};
}
this.keyedMap = (0, _collections.documentMap)();
this.sortedSet = new _sorted_map.SortedMap(this.comparator);
}
/**
* Returns an empty copy of the existing DocumentSet, using the same
* comparator.
*/
DocumentSet.emptySet = function (oldSet) {
return new DocumentSet(oldSet.comparator);
};
DocumentSet.prototype.has = function (key) {
return this.keyedMap.get(key) != null;
};
DocumentSet.prototype.get = function (key) {
return this.keyedMap.get(key);
};
DocumentSet.prototype.first = function () {
return this.sortedSet.minKey();
};
DocumentSet.prototype.last = function () {
return this.sortedSet.maxKey();
};
DocumentSet.prototype.isEmpty = function () {
return this.sortedSet.isEmpty();
};
/**
* Returns previous document or null if it's a first doc.
*
* @param key A key that MUST be present in the DocumentSet.
*/
DocumentSet.prototype.prevDoc = function (key) {
(0, _assert.assert)(this.has(key), 'Trying to get a previous document to non-existing key: ' + key);
var doc = this.keyedMap.get(key);
return this.sortedSet.getPredecessorKey(doc);
};
/**
* Returns the index of the provided key in the document set, or -1 if the
* document key is not present in the set;
*/
DocumentSet.prototype.indexOf = function (key) {
var doc = this.keyedMap.get(key);
return doc ? this.sortedSet.indexOf(doc) : -1;
};
Object.defineProperty(DocumentSet.prototype, "size", {
get: function get() {
return this.sortedSet.size;
},
enumerable: true,
configurable: true
});
/** Iterates documents in order defined by "comparator" */
DocumentSet.prototype.forEach = function (cb) {
this.sortedSet.inorderTraversal(function (k, v) {
cb(k);
return false;
});
};
/** Inserts or updates a document with the same key */
DocumentSet.prototype.add = function (doc) {
// First remove the element if we have it.
var set = this.delete(doc.key);
return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));
};
/** Deletes a document with a given key */
DocumentSet.prototype.delete = function (key) {
var doc = this.get(key);
if (!doc) {
return this;
}
return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));
};
DocumentSet.prototype.equals = function (other) {
if (!(other instanceof DocumentSet)) return false;
if (this.size !== other.size) return false;
var thisIt = this.sortedSet.getIterator();
var otherIt = other.sortedSet.getIterator();
while (thisIt.hasNext()) {
var thisDoc = thisIt.getNext().key;
var otherDoc = otherIt.getNext().key;
if (!thisDoc.equals(otherDoc)) return false;
}
return true;
};
DocumentSet.prototype.toString = function () {
var docStrings = [];
this.forEach(function (doc) {
docStrings.push(doc.toString());
});
if (docStrings.length === 0) {
return 'DocumentSet ()';
} else {
return 'DocumentSet (\n ' + docStrings.join(' \n') + '\n)';
}
};
DocumentSet.prototype.copy = function (keyedMap, sortedSet) {
var newSet = new DocumentSet();
newSet.comparator = this.comparator;
newSet.keyedMap = keyedMap;
newSet.sortedSet = sortedSet;
return newSet;
};
return DocumentSet;
}();
exports.DocumentSet = DocumentSet;
//# sourceMappingURL=document_set.js.map
| {'content_hash': '2319fded13fef0300be7ec59ed721dc3', 'timestamp': '', 'source': 'github', 'line_count': 159, 'max_line_length': 108, 'avg_line_length': 35.515723270440255, 'alnum_prop': 0.6187356118292899, 'repo_name': 'tupamba/kardex', 'id': '7244b440b2874cda9239df61edc562e16c859bed', 'size': '5647', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/firebase/firestore/model/document_set.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '650309'}, {'name': 'HTML', 'bytes': '99328'}, {'name': 'JavaScript', 'bytes': '6168965'}, {'name': 'TypeScript', 'bytes': '70529'}]} |
function openSystemInformation(){
//We have to wait for page to load, if the site is slow
cy.get('[data-element="global-help"]').should('be.visible').click();
cy.get('.umb-help-list-item').last().should('be.visible').click();
cy.get('.umb-drawer-content').scrollTo('bottom', {ensureScrollable : false});
}
context('System Information', () => {
beforeEach(() => {
//arrange
cy.umbracoLogin(Cypress.env('username'), Cypress.env('password'));
cy.umbracoSetCurrentUserLanguage('en-US');
});
afterEach(() => {
cy.umbracoSetCurrentUserLanguage('en-US');
});
it('Check System Info Displays', () => {
openSystemInformation();
cy.get('.table').find('tr').should('have.length', 10);
cy.contains('Current Culture').parent().should('contain', 'en-US');
cy.contains('Current UI Culture').parent().should('contain', 'en-US');
});
it('Checks language displays correctly after switching', () => {
//Navigate to edit user and change language
cy.umbracoGlobalUser().click();
cy.get('[alias="editUser"]').click();
cy.get('[name="culture"]').select('string:da-DK', { force: true});
cy.umbracoButtonByLabelKey('buttons_save').click({force: true});
cy.umbracoSuccessNotification().should('be.visible');
openSystemInformation();
//Assert
cy.contains('Current Culture').parent().should('contain', 'da-DK');
cy.contains('Current UI Culture').parent().should('contain', 'da-DK');
cy.get('.umb-button__content').last().click();
//Clean
cy.umbracoSetCurrentUserLanguage('en-US');
});
});
| {'content_hash': 'be315f84c285f05d60b41bb0fbcb4502', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 81, 'avg_line_length': 39.116279069767444, 'alnum_prop': 0.6046373365041617, 'repo_name': 'JimBobSquarePants/Umbraco-CMS', 'id': '363244e12f6d92da3042e6944d2c949ffa4fc167', 'size': '1717', 'binary': False, 'copies': '1', 'ref': 'refs/heads/v9/contrib', 'path': 'tests/Umbraco.Tests.AcceptanceTest/cypress/integration/HelpPanel/systemInformation.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '15925308'}, {'name': 'CSS', 'bytes': '13049'}, {'name': 'Dockerfile', 'bytes': '2352'}, {'name': 'HTML', 'bytes': '1236051'}, {'name': 'JavaScript', 'bytes': '4518767'}, {'name': 'Less', 'bytes': '543715'}, {'name': 'PowerShell', 'bytes': '23312'}, {'name': 'Shell', 'bytes': '3572'}, {'name': 'TSQL', 'bytes': '371'}, {'name': 'TypeScript', 'bytes': '117460'}]} |
package org.camunda.bpm.tasklist;
/**
* The tasklist application. Provides access to the tasklist core services.
*
* @author Roman Smirnov
*
*/
public class Tasklist {
/**
* The {@link TasklistRuntimeDelegate} is an delegate that will be
* initialized by bootstrapping camunda admin with an specific
* instance
*/
protected static TasklistRuntimeDelegate TASKLIST_RUNTIME_DELEGATE;
/**
* Returns an instance of {@link TasklistRuntimeDelegate}
*
* @return
*/
public static TasklistRuntimeDelegate getRuntimeDelegate() {
return TASKLIST_RUNTIME_DELEGATE;
}
/**
* A setter to set the {@link TasklistRuntimeDelegate}.
* @param tasklistRuntimeDelegate
*/
public static void setTasklistRuntimeDelegate(TasklistRuntimeDelegate tasklistRuntimeDelegate) {
TASKLIST_RUNTIME_DELEGATE = tasklistRuntimeDelegate;
}
}
| {'content_hash': '486c42ecbae1243bce2b5ee38cdb5633', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 98, 'avg_line_length': 24.885714285714286, 'alnum_prop': 0.7313432835820896, 'repo_name': 'camunda/camunda-bpm-platform', 'id': '9346b87ef2243a916a12e12f5bae09beceffeb4f', 'size': '1678', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'webapps/src/main/java/org/camunda/bpm/tasklist/Tasklist.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '8608'}, {'name': 'CSS', 'bytes': '5486'}, {'name': 'Fluent', 'bytes': '3111'}, {'name': 'FreeMarker', 'bytes': '1443842'}, {'name': 'Groovy', 'bytes': '1904'}, {'name': 'HTML', 'bytes': '961289'}, {'name': 'Handlebars', 'bytes': '759'}, {'name': 'Java', 'bytes': '44079665'}, {'name': 'JavaScript', 'bytes': '3064086'}, {'name': 'Less', 'bytes': '154956'}, {'name': 'Python', 'bytes': '192'}, {'name': 'Ruby', 'bytes': '60'}, {'name': 'SQLPL', 'bytes': '44180'}, {'name': 'Shell', 'bytes': '11634'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.