branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>ryzhman/mockProject<file_sep>/src/com/go2it/Main.java
package com.go2it;
/**
* @author <NAME>
*/
public class Main {
public static int sum(int i, int j) {
return i + j;
}
public static int divideAlex(int i, int j) {
return i / j;
}
/**@adding two functions by Olga**/
//public static boolean modulusDivision(int i, int j){
// return i%j==0;
// here
//}
/*end of Olga's code*/
public static void main(String[] args) {
sum(1, 2);
System.out.println(modulusDiv(10,3));
}
public static boolean modulusDiv(int firstInt, int secondInt) {
if (firstInt % secondInt == 0) {
return true;
}
return false;
}
public static boolean modulusDivision(int i,int j){
return i%j==0;
}
}
|
67ba422ef50c57a1478a485421c840d0b75fd976
|
[
"Java"
] | 1
|
Java
|
ryzhman/mockProject
|
2058a8edf1f1b9f210b6366a07b6878d1b9b1602
|
d63e845525d62ca3436ddad38250ec293a965ac9
|
refs/heads/master
|
<repo_name>squallcheese/airbnb_assessment<file_sep>/app/controllers/tags.rb
get '/tags' do
@properties = []
session[:tags].each do |tag|
@tag = Tag.find_by tag_text: tag_text
@tag.properties.each do |property|
@properties << property
end
end
erb :index
end
post '/tags' do
arr_tags = []
tags = params[:tags]
tags.each do |tag|
arr_tags << tag
end
session[:tags] = arr_tags
redirect to('/tags')
end<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_many :properties
def self.check_duplicate(email)
duplicate = self.find_by email: email
if duplicate == nil
true
else
false
end
end
def self.authenticate(email, password)
check = self.find_by email: email, password: <PASSWORD>
if check == nil
false
else
true
end
end
end<file_sep>/app/models/property.rb
class Property < ActiveRecord::Base
has_many :property_tags
has_many :tags, through: :property_tags
belongs_to :user
end<file_sep>/app/controllers/index.rb
#if database is all empty, first time launch index page, how to pass?
get '/' do
@property = Property.all
#redirect to '/' if @property.nil?
erb :index
end
#if property database for user is all empty, how to pass?
post '/user_page' do
if session[:user_id]
@user = User.find(session[:user_id])
erb :user_page
# elsif
# @property.nil? redirect to '/user_page'
else
redirect to '/sign_in'
end
end<file_sep>/app/controllers/properties.rb
#Lists all user's properties
get '/user_page' do
current_user
@user = User.find_by id: session[:user_id]
@properties = @user.properties
erb :user_page
end
#Creating new property post
get '/user_page/new' do
erb :user_page_new
end
#Need to validate that certain fields(with asterisk) cannot be empty
#Message prompt for Properties created
post '/user_page/new' do
current_user
@property_name = params[:property_name]
@property_type = params[:property_type]
@room_type = params[:room_type]
@location = params[:location]
@pax = params[:pax]
@price = params[:price]
@rating = params[:rating]
@property_text = params[:property_text]
@tags = params[:tag_text].split(", ")
@property_new = Property.new(property_name: @property_name,property_type: @property_type, room_type: @room_type, location: @location, pax: @pax, price: @price, rating: @rating, property_text: @property_text)
#Adding tags to properties
@tags.each do |tag|
@tag = Tag.find_or_create_by(tag_text: tag)
@tag.properties << @property_new
end
@current_user.properties << @property_new
@property_new.save
redirect to '/user_page'
end
#Editing and Deleting property post
get '/user_page/edit/:id' do
current_user
@property = Property.find(params[:id])
erb :user_page_edit
end
#Need to validate that certain fields(with asterisk) cannot be empty
#Message prompt for Properties edited and deleted
post '/user_page/edit/:id' do
current_user
@property = Property.find(params[:id])
@property.property_name = params[:property_name]
@property.property_type = params[:property_type]
@property.room_type = params[:room_type]
@property.location = params[:location]
@property.pax = params[:pax]
@property.price = params[:price]
@property.rating = params[:rating]
@property.property_text = params[:property_text]
@tags = params[:tag_text].split(", ")
@tags.each do |tag|
@tag = Tag.find_or_create_by(tag_text: tag)
@tag.properties << @property
end
@property.save
# #old_tag = PropertyTag.where(property_id: params[:id])
# #old_tag.each {|tag| tag.delete}
# #new_tag.each_key do |tag|
# # @tag.Tag.find_by tag_text: tag
# # @tag.properties << current_property
redirect to '/user_page'
end
post '/user_page/delete/:id' do
@property = Property.find(params[:id])
@property.destroy
redirect to '/user_page'
end
<file_sep>/app/controllers/users.rb
#Registering a new user
get '/register' do
erb :register
end
post '/register' do
@username = params[:username]
@email = params[:email]
@password = params[:password]
#Future: To do Register prompt errors, ie. "Email has been registered",etc...
#User is able to register with blank fields, how to check?
#Validation for username(unique), email(format) and password strength
if User.check_duplicate(@email) == false #cheated, to check functionality
redirect to '/register'
else
@user = User.create(username: @username, email: @email, password: @password)
erb :index
end
end
#Logging in for existing user
get '/sign_in' do
erb :sign_in
end
post '/sign_in' do
@email = params[:email]
@password = params[:<PASSWORD>]
#Future: To do Sign in prompt errors, ie. "Password error",etc...
if User.authenticate(@email, @password)
@user = User.find_by email: @email
session[:user_id] = @user.id
redirect to '/user_page'
else
redirect to '/'
end
end
get '/logout' do
session.clear
redirect to '/'
end<file_sep>/app/models/property_tag.rb
class PropertyTag < ActiveRecord::Base
belongs_to :properties
belongs_to :tags
end
|
32579132aa591e7f180a1ba51bce480ce869f6ea
|
[
"Ruby"
] | 7
|
Ruby
|
squallcheese/airbnb_assessment
|
474ded97fbf4419f2d9937c09f121d9f24f18062
|
5ef98f8c187a8d9d1dde2ff78543526553086155
|
refs/heads/master
|
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Aula Controller
*
* @property \App\Model\Table\AulaTable $Aula
*/
class CalendarioController extends AppController{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->loadModel('Turma');
}
public function index()
{
$this->paginate = [
'conditions'=>['ativo'=>true],
'contain'=>['Curso']
];
$this->set('turma', $this->paginate($this->Turma));
$this->set('_serialize', ['curso']);
}
public function calendario($turma_id, $mes = null, $ano = null){
$turma = $this->Turma->get($turma_id);
if(is_null($mes) or is_null($ano)){
$mes = (int) date('m');
$ano = date('Y');
}elseif($mes==0){
$mes = 12;
$ano = $ano - 1;
}elseif($mes==13){
$mes = 1;
$ano = $ano + 1;
}
if($this->request->is('post')){
$fieldCalendario = json_decode($this->request->data['fieldCalendar']);
foreach ($fieldCalendario as $cal) {
$calendario = $this->Calendario->newEntity();
$calendario->data = mktime(0, 0, 0, $cal->mes, $cal->dia, $cal->ano);
$calendario->turma_id = $turma_id;
$calendario->letivo = $cal->letivo;
$this->Calendario->saveCalendario($calendario);
}
}
$dataTime = mktime(0,0,0, $mes, 1, $ano);
$first_day = getdate($dataTime);
$last_day = date('t', $dataTime);
$dataTimeLast = mktime(0,0,0, $mes, $last_day, $ano);
$calendario_mensal = $this->Calendario->find()
->where([
'data >='=>date('Y-m-d', $dataTime),
'data <='=>date('Y-m-d', $dataTimeLast),
'turma_id'=>$turma_id
])->toArray();
$cal_mes = array();
foreach ($calendario_mensal as $data) {
$cal_mes[(int) $data->data->i18nFormat('dd')] = $data->letivo;
}
$this->set('meses', $this->meses);
$this->set(compact('mes','ano', 'first_day', 'last_day', 'turma', 'cal_mes'));
}
}
<file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3><?=$curso->descricao?> </h3>
<h3><span class="label label-default"> <?=$curso->sigla?></span></h3>
<h3><span class="label label-default"> <?=$curso->modalidade->descricao?></span></h3>
</div>
<div class="panel-footer"><?=$this->Html->link('Editar', ['action'=>'edit', $curso->id])?></div>
</div>
<?php if (!empty($curso->turma)): ?>
<div class="panel panel-default">
<div class="panel-heading">Turmas relacionadas</div>
<div class="panel-body">
<table class="table table-striped">
<tr>
<th><?= __('Nome') ?></th>
<th><?= __('Ano') ?></th>
<th><?= __('Turno') ?></th>
<th><?= __('Ativo') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
<?php foreach ($curso->turma as $turma): ?>
<tr>
<td><?= h($turma->nome) ?></td>
<td><?= h($turma->ano) ?></td>
<td><?= h($turnos[$turma->turno]) ?></td>
<td><?= h($turma->ativo) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['controller' => 'Turma', 'action' => 'view', $turma->id]) ?>
<?= $this->Html->link(__('Edit'), ['controller' => 'Turma', 'action' => 'edit', $turma->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
</div>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
/**
* Eixo Entity.
*/
class Eixo extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'descricao' => true,
'professor' => true,
];
}
<file_sep><div class="panel panel-default">
<div class="panel-heading">Turmas</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Descrição</th>
</tr>
</thead>
<tbody>
<?php foreach ($grade as $grade): ?>
<tr>
<td><?= h($grade->turma->nome) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<file_sep><?=$this->element('menuLateralProf')?>
<file_sep><div class="panel panel-default">
<div class="panel-heading">Nova senha para <strong><?=$usuario->nome?></strong></div>
<div class="panel-body">
<?= $this->Form->create($usuario) ?>
<div class="form-group">
<?=$this->Form->password('<PASSWORD>', ['div'=>false, 'class'=>'form-control', 'value'=>'']);?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
<?= $this->Form->end() ?>
</div>
</div><file_sep><div class="panel panel-default">
<div class="panel-heading">Faltas por turma</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Turma</th>
<th>Quantidade</th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($turma as $turma): ?>
<tr>
<td><?= h($turma->calendario->turma->nome) ?></td>
<td><?= h($turma->qt) ?></td>
<td class="actions">
<?= $this->Html->link(__('Detalhe'), ['action' => 'viewFaltas', $turma->calendario->turma->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<file_sep><script type="text/javascript">
var randomnb = function(){ return Math.round(Math.random()*300)};
$(function(){
$('#modalGrafico').modal('hide');
$('#modalGraficoRadar').modal('hide');
});
function exibirGrafico(aulas, ministradas){
options = [];
var data = [
{
value: (aulas-ministradas),
color:"#00BB55",
highlight: "red",
label: "Pendentes"
},
{
value: ministradas,
color: "#46BFBD",
highlight: "#00115E",
label: "Ministradas"
},
]
var ctx = $("#myChart").get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx).Doughnut(data,options);
$('#modalGrafico').modal('show');
}
function exibirGraficoDisciplinas(){
var options = [];
var $labels = [];
var $carga_horaria = [];
var $ministrada = [];
$('#disciplinasTable').find('tr').each(function(key, val){
$labels[key] = $(this).find('td').eq(0).text();
$carga_horaria[key] = $(this).find('td').eq(2).text();
$ministrada[key] = $(this).find('td').eq(3).text();
});
//console.log(labels);
var data = {
labels: $labels,
datasets: [
{
label: "Carga Horária",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: $carga_horaria
},
{
label: "Ministrada",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [6, 0]
}
]
};
var ctx = $("#myChartRadar").get(0).getContext("2d");
ctx.canvas.width = 500;
ctx.canvas.height = 500;
var RadarChart = new Chart(ctx).Radar(data, options);
$('#modalGraficoRadar').modal('show');
}
</script>
<style type="text/css">
#canvas-holder {
width: 100%;
}
</style>
<div class="panel panel-default">
<div class="panel-heading">Minhas disciplinas</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th><?= h('Disciplina'); ?></th>
<th><?= h('Turma'); ?></th>
<th><?= h('Carga (Aulas)'); ?></th>
<th><?= h('Ministrada (Aulas)'); ?></th>
<th class="actions"><?= __('Ações')?></th>
</tr>
</thead>
<tbody id="disciplinasTable">
<?php foreach ($disciplinas as $grade): ?>
<tr>
<?php
$totalAulas = ($grade->carga_horaria*60)/$grade->turma->curso->modalidade->tempoAula;
$ministrada = $grade->ministrada['qt'] > 0 ? $grade->ministrada['qt'] : 0 ;
?>
<td><?=$grade->disciplina->nome?></td>
<td><?=$grade->turma->nome."/".$grade->turma->curso->sigla?></td>
<td><?=$totalAulas?></td>
<td><?=$ministrada ?></td>
<td>
<a href="#" onclick="exibirGrafico(<?=$totalAulas?>, <?=$ministrada?>);">
<span class="glyphicon glyphicon-tasks"></span>
</a>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
<div class="panel-foot">
<a href="#" onclick="exibirGraficoDisciplinas();">
<?=$this->Html->image('grafico.jpg', ['style'=>'width:50px;'])?>
</a>
</div>
<div class="modal fade" id="modalGrafico" tabindex="-1" role="dialog" aria-labelledby="Modal Grafico">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalDisciplinaLabel">Situação da disciplina</h4>
</div>
<div class="modal-body">
<div style="width:400px;" class="chartDiv">
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modalGraficoRadar" tabindex="-1" role="dialog" aria-labelledby="Modal Grafico">
<div class="modal-dialog" role="document" >
<div class="modal-content" style="height: 600px; width:600px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalDisciplinasLabel">Minhas Disciplinas</h4>
</div>
<div class="modal-body">
<div id="canvas-holder">
<canvas id="myChartRadar"></canvas>
</div>
</div>
</div>
</div>
</div><file_sep><?php
namespace App\Controller\Coordenador;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Professor Controller
*
* @property \App\Model\Table\ProfessorTable $Professor
*/
class ProfessorController extends AppController
{
/**
* Index method
*
* @return void
*/
private $professor = null;
public function beforeFilter(Event $event){
parent::beforeFilter($event);
$this->professor = $this->Professor->findByUsuarioId($this->Auth->user('id'))->first();
}
public function index()
{
$this->paginate = [
'contain' => ['Usuario', 'Eixo'],
'conditions'=>[
'NOT'=>[
'Professor.id'=>$this->professor->id
],
'Eixo.id'=>$this->professor->eixo_id
]
];
$this->set('professor', $this->paginate($this->Professor));
$this->set('_serialize', ['professor']);
}
/**
* View method
*
* @param string|null $id Professor id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$id = is_null($id) ? $this->professor->id : $id;
$professor = $this->Professor->get($id, [
'contain' => ['Usuario', 'Eixo'],
'conditions'=>[
'Eixo.id'=>$this->professor->eixo_id
]
]);
$this->set('professor', $professor);
$this->set('_serialize', ['professor']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$professor = $this->Professor->newEntity();
if ($this->request->is('post')) {
$professor = $this->Professor->patchEntity($professor, $this->request->data, [
'associated'=>'Usuario'
]);
$professor->usuario->senha = $professor->usuario->matricula;
$professor->usuario->ativo = true;
$professor->coordenador = false;
$professor->eixo_id = $this->professor->eixo_id;
if ($this->Professor->save($professor)) {
$this->Flash->success(__('The professor has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The professor could not be saved. Please, try again.'));
}
}
$usuario = $this->Professor->Usuario->find('list', ['limit' => 200]);
$eixo = $this->Professor->Eixo->find('list', ['limit' => 200]);
$this->set(compact('professor', 'usuario', 'eixo'));
$this->set('_serialize', ['professor']);
}
/**
* Edit method
*
* @param string|null $id Professor id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$professor = $this->Professor->get($id, [
'contain' => ['Usuario']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$professor = $this->Professor->patchEntity($professor, $this->request->data, [
'associated'=>'Usuario'
]);
if ($this->Professor->save($professor)) {
$this->Flash->success(__('The professor has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The professor could not be saved. Please, try again.'));
}
}
$usuario = $this->Professor->Usuario->find('list', ['limit' => 200]);
$eixo = $this->Professor->Eixo->find('list', ['limit' => 200]);
$this->set(compact('professor', 'usuario', 'eixo'));
$this->set('_serialize', ['professor']);
}
/**
* Delete method
*
* @param string|null $id Professor id.
* @return void Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$professor = $this->Professor->get($id);
if ($this->Professor->delete($professor)) {
$this->Flash->success(__('The professor has been deleted.'));
} else {
$this->Flash->error(__('The professor could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep><nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<input type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">TCC</a>
</div>
<?php
if($usuarioLogado['coordenador']){
echo $this->element('menuCoordenador');
}elseif($usuarioLogado['professor']){
echo $this->element('menuProfessor');
}else{
echo $this->element('menu');
}
?>
</div><!-- /.container-fluid -->
</nav><file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Administrador Controller
*
* @property \App\Model\Table\AdministradorTable $Administrador
*/
class IndexController extends AppController
{
public function index(){
}
}
<file_sep><script type="text/javascript">
$(function(){
$('#fieldCalendar').hide();
$(":button" ).click(function(){
var classe = $(this).attr('class');
if(classe=='btn btn-primary'){
$(this).removeClass();
$(this).addClass('btn btn-danger');
}else if(classe=='btn btn-danger'){
$(this).removeClass();
$(this).addClass('btn btn-primary');
}
});
$('#saveCalendar').click(function(){
if(confirm('Deseja salvar as alterações?')){
var calendario = new Array();
$( "button" ).each(function( index, element ) {
classe = $( element ).attr('class')
if(classe=='btn btn-primary' || classe=='btn btn-danger'){
//console.log($( element ).attr('value'));
var obj= new Object();
obj.dia = $( element ).attr('value');
if(classe=='btn btn-primary')
obj.letivo = true;
else
obj.letivo = false;
obj.ano = <?=@$ano?>;
obj.mes = <?=@$mes?>
calendario .push(obj);
}
});
$('#fieldCalendar').val(JSON.stringify(calendario));
}else{
return false;
}
});
});
</script>
<table class="table table-bordered" style="width: 400px;" id="calendar">
<caption>Calendário Letivo - <?=@$ano?></caption>
<thead>
<tr>
<th colspan="7">
<?=$this->Html->link(__("<<"), ['action'=>'calendario', $turma->id, $mes-1, $ano])?>
<?=$meses[$mes]?>
<?=$this->Html->link(__(">>"), ['action'=>'calendario', $turma->id, $mes+1, $ano])?>
</th>
</tr>
<tr>
<th>DOM</th>
<th>SEG</th>
<th>TER</th>
<th>QUA</th>
<th>QUI</th>
<th>SEX</th>
<th>SAB</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$dia_semana = 0;
for($i=0;$i<$first_day['wday'];$i++){
echo "<td></td>";
$dia_semana++;
}
$dia = 1;
while($dia<=$last_day){
if($dia_semana==7){
echo "</tr>";
echo "<tr>";
$dia_semana = 0;
}
$dataTime = mktime(0,0,0, $mes, $dia, $ano);
$nowTime = mktime(0,0,0, date('m'), date('d'), date('Y'));
$data_dia = getdate($dataTime);
if(@$cal_mes[$dia]){
echo "<td><button class='btn btn-primary' value='$dia' style='width: 60px;'>".$dia."</button></td>";
}elseif(@$cal_mes[$dia]==false){
echo "<td><button class='btn btn-danger' value='$dia' style='width: 60px;'>".$dia."</button></td>";
}
$dia++;
$dia_semana++;
}
echo "</tr>";
?>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="7">
<?=$this->Form->create()?>
<textarea id="fieldCalendar" name="fieldCalendar">
</textarea>
<button class="btn btn-info" id="saveCalendar" type="submit">
Salvar Calendario
</button>
</form>
</td>
</tr>
</tfoot>
</table><file_sep><div class="panel panel-default">
<div class="panel-heading">Cadastro de Administradores</div>
<div class="panel-body">
<?= $this->Form->create($administrador) ?>
<div class="form-group">
<?=$this->Form->input('usuario.nome', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('usuario.email', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('usuario.matricula', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('cargo', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('setor', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
<?= $this->Form->end() ?>
</div>
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Aula Controller
*
* @property \App\Model\Table\AulaTable $Aula
*/
class AulaController extends AppController
{
/**
* Index method
*
* @return void
*/
public function verFaltas()
{
$this->loadModel('Usuario');
$usuario = $this->Usuario->get($this->Auth->user('id'), [
'contain'=>['Professor']
]);
$faltas = $usuario->professor->faltas;
$this->set(compact('faltas'));
}
public function getAulas($data=null, $turma_id=null){
$this->layout = 'ajax';
$dt = explode("-", $data);
$dataTime = mktime(0,0,0, $dt[1], $dt[2], $dt[0]);
$dia = getdate($dataTime);
$this->loadModel('Horario');
$usuario = $this->Usuario->get($this->Auth->user('id'), ['contain'=>'Professor']);
$horario['horario']= $this->Horario->find()
->where([
'dia'=>$dia['wday'],
'GradeCurricular.professor_id'=>$usuario->professor->id,
'GradeCurricular.turma_id'=>$turma_id
])
->contain(['GradeCurricular'=>['Disciplina']])
->order(['aula'])
->toArray();
echo json_encode($horario);
}
}
<file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\Horario;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Event\Event;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
/**
* Horario Model
*
* @property \Cake\ORM\Association\BelongsTo $GradeCurricular
*/
class HorarioTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('horario');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('GradeCurricular', [
'foreignKey' => 'grade_curricular_id',
'joinType' => 'INNER'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('dia', 'valid', ['rule' => 'numeric'])
->requirePresence('dia', 'create')
->notEmpty('dia');
$validator
->add('aula', 'valid', ['rule' => 'numeric'])
->requirePresence('aula', 'create')
->notEmpty('aula');
$validator
->add('hora_inicio', 'valid', ['rule' => 'time'])
->requirePresence('hora_inicio', 'create')
->notEmpty('hora_inicio');
$validator
->add('hora_termino', 'valid', ['rule' => 'time'])
->requirePresence('hora_termino', 'create')
->notEmpty('hora_termino');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['grade_curricular_id'], 'GradeCurricular'));
return $rules;
}
}
<file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\ReposicaoAntecipacao;
use App\Model\Entity\Calendario;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Datasource\ConnectionManager;
/**
* ReposicaoAntecipacao Model
*
* @property \Cake\ORM\Association\BelongsToMany $Aula
*/
class ReposicaoAntecipacaoTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('reposicao_antecipacao');
$this->displayField('id');
$this->primaryKey('id');
$this->hasMany('AulaReposicaoAntecipacao');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->requirePresence('justificativa', 'create')
->notEmpty('justificativa');
$validator
->allowEmpty('observacao');
$validator
->add('dataReposicao', 'valid', ['rule' => 'date'])
->requirePresence('dataReposicao', 'create')
->notEmpty('dataReposicao');
return $validator;
}
public function saveAntecipacao(ReposicaoAntecipacao $reposicao, array $antecipacoes, Calendario $cal){
$aulas = $this->AulaReposicaoAntecipacao->Aula->find()
->where([
'calendario_id'=>$cal->id,
'aula IN '=>$antecipacoes
]);
$tudoCerto = true;
// $this->connection()->transactional(function () use ($reposicao, $aulas, $tudoCerto) {
$conn = ConnectionManager::get('default');
$conn->begin();
$this->save($reposicao);
foreach ($aulas as $aula) {
$aulaReposicaoAntecipacao = $this->AulaReposicaoAntecipacao->newEntity([
'aula_repor'=>$aula->aula,
'reposicao_antecipacao_id'=>$reposicao->id,
'aula_id'=>$aula->id,
'status'=>'C'
]);
//pr($)
if(!$this->AulaReposicaoAntecipacao->save($aulaReposicaoAntecipacao)){
$tudoCerto = false;
}
}
if($tudoCerto == true){
$conn->commit();
return true;
}
$conn->rollback();
return false;
}
}
<file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Descrição: <?=$modalidade->descricao?> </h3>
<h3><span class="label label-default"> <?=$modalidade->tempoAula." Minutos"?></span></h3>
</div>
<div class="panel-footer"><?=$this->Html->link('Editar', ['action'=>'edit', $modalidade->id])?></div>
</div>
<?php if (!empty($modalidade->curso)): ?>
<div class="panel panel-default">
<div class="panel-heading">Cursos relacionados</div>
<div class="panel-body">
<table class="table table-striped">
<tr>
<th><?= __('Descricao') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
<?php foreach ($modalidade->curso as $curso): ?>
<tr>
<td><?= h($curso->descricao) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['controller' => 'Curso', 'action' => 'view', $curso->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
</div>
<?php endif; ?>
<file_sep><?php
namespace App\Controller\Coordenador;
use App\Controller\AppController;
/**
* ReposicaoAntecipacao Controller
*
* @property \App\Model\Table\ReposicaoAntecipacaoTable $ReposicaoAntecipacao
*/
class ReposicaoAntecipacaoController extends AppController
{
public function index()
{
$this->loadModel('Professor');
$this->loadModel('Coordenador');
$coordenador = $this->Coordenador->find()
->contain(['Professor'])
->where(['Professor.usuario_id'=>$this->Auth->user('id')])
->first();
$this->set(compact('coordenador'));
}
public function view($id){
$reposicaoAntecipacao = $this->ReposicaoAntecipacao->get($id, [
'contain'=>[
'AulaReposicaoAntecipacao'=>[
'Aula'=>[
'Calendario'=>[
'Turma'=>['Curso']
]
]
]
]
]);
if($this->request->is(['post', 'put'])){
$reposicaoAntecipacao = $this->ReposicaoAntecipacao->patchEntity($reposicaoAntecipacao, $this->request->data);
if ($this->ReposicaoAntecipacao->save($reposicaoAntecipacao)) {
$this->Flash->success('Reposição atualizada com sucesso.');
return $this->redirect(['action' => 'index']);
}else{
$this->Flash->error('Reposição atualizada com sucesso.');
}
}
$this->set(compact('reposicaoAntecipacao'));
$this->set('_serialize', [$reposicaoAntecipacao]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Professor Controller
*
* @property \App\Model\Table\ProfessorTable $Professor
*/
class ProfessorController extends AppController
{
/**
* Index method
*
* @return void
*/
private $professor = null;
public function beforeFilter(Event $event){
parent::beforeFilter($event);
$this->professor = $this->Professor->findByUsuarioId($this->Auth->user('id'))->first();
}
public function index()
{
}
/**
* View method
*
* @param string|null $id Professor id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view()
{
$professor = $this->Professor->get($this->professor->id, [
'contain' => ['Usuario', 'Eixo']
]);
$this->set('professor', $professor);
$this->set('_serialize', ['professor']);
}
/**
* Edit method
*
* @param string|null $id Professor id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit()
{
$professor = $this->Professor->get($this->professor->id, [
'contain' => ['Usuario', 'Eixo']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$professor = $this->Professor->patchEntity($professor, $this->request->data);
if ($this->Professor->save($professor)) {
$this->Flash->success(__('The professor has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The professor could not be saved. Please, try again.'));
}
}
$usuario = $this->Professor->Usuario->find('list', ['limit' => 200]);
$eixo = $this->Professor->Eixo->find('list', ['limit' => 200]);
$this->set(compact('professor', 'usuario', 'eixo'));
$this->set('_serialize', ['professor']);
}
public function minhasDisciplinas(){
$this->loadModel('GradeCurricular');
$disciplinas = $this->GradeCurricular->find()
->where([
'Turma.ativo'=>true,
'Professor.usuario_id'=>$this->Auth->user('id')
])
->contain(['Turma'=>['Curso'=>['Modalidade']], 'Professor', 'Disciplina']);
$this->set(compact('disciplinas'));
}
}
<file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Nome: <?=$turma->nome?> </h3>
<h3>Ano: <?=$turma->ano?> </h3>
<h3>Turno: <?=$turnos[$turma->turno]?> </h3>
<h3>Curso: <?=$turma->curso->descricao?> </h3>
<h3>Sala: <?=$turma->sala->nome?> </h3>
</div>
<div class="panel-footer"><?=$this->Html->link('Editar', ['action'=>'edit', $turma->id])?>
</div>
</div>
<file_sep><script type="text/javascript">
$(function(){
$('#btnAprovar').click(function(){
if(confirm('Aprovar reposição?')){
$('#status').val('A');
$('#reposicaoForm').submit();
}
});
$('#btnRejeitar').click(function(){
if(confirm('Rejeitar reposição?')){
$('#status').val('R');
$('#reposicaoForm').submit();
}
});
});
</script>
<div class="panel panel-default">
<div class="panel-heading">Reposição pendente/ <?=$reposicaoAntecipacao->aula['professor']?></div>
<div class="panel-body">
<?=$this->Form->create($reposicaoAntecipacao, ['id'=>'reposicaoForm'])?>
<?php //pr($reposicaoAntecipacao);?>
<?=$this->Form->input('id');?>
<?=$this->Form->input('status', ['type'=>'hidden', 'id'=>'status']);?>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<?=$this->Form->input('justificativa', ['div'=>false, 'class'=>'form-control', 'label'=>'justificativa', 'disabled'=>true]);?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<?=$this->Form->input('dataReposicao', ['type'=>'text', 'div'=>false, 'class'=>'form-control', 'label'=>'Repor em', 'disabled'=>true]);?>
</div>
</div>
</div>
<h4>Aulas</h4>
<hr>
<table class="table table-striped">
<thead>
<tr>
<th>Turma</th>
<th>Data</th>
<th>Aula</th>
<th>Reposicao</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($reposicaoAntecipacao->aula_reposicao_antecipacao as $key => $aula): ?>
<tr>
<td><?=$aula->aula->calendario->turma->nome."/".$aula->aula->calendario->turma->curso->sigla?></td>
<td><?=$aula->aula->calendario->data?></td>
<td><?=$aula->aula->aula?></td>
<td><?=$aula->aula_repor?></td>
<td><?=$aula->status == 'C' ? 'Criada' : ($aula->status =='M' ? 'Ministrada' : 'Faltou')?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<hr>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<?=$this->Form->input('observacao', ['div'=>false, 'class'=>'form-control', 'label'=>'Observação']);?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<div class="form-group">
<a href="#" class="btn btn-success" id="btnAprovar">Aprovar</a>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<a href="#" class="btn btn-danger" id="btnRejeitar">Rejeitar</a>
</div>
</div>
</div>
<?=$this->Form->end();?>
</div>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\I18n\Time;
/**
* Turma Entity.
*/
class Turma extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = ['*'=>true];
public function getReposicoes($dat){
$connection = ConnectionManager::get('default');
$sql = "SELECT ara.id, ara.aula_repor, ara.aula_id, ra.dataReposicao, ara.status, d.nome as disciplina,
u.nome as professor
FROM turma as t inner join
grade_curricular as gc on t.id = gc.turma_id inner join
disciplina as d on gc.disciplina_id = d.id inner join
professor as p on gc.professor_id = p.id inner join
usuario as u on p.usuario_id = u.id inner join
calendario as c on t.id = c.turma_id inner join
aula as a on c.id = a.calendario_id and d.id = a.disciplina_id inner join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id inner join
reposicao_antecipacao as ra on ara.reposicao_antecipacao_id = ra.id
WHERE (t.id = ".$this->id.") and (ra.dataReposicao = '".$dat."')
AND (NOT coalesce(ra.status,'') IN('RC', 'AC'))";
return $connection->execute($sql)->fetchall('assoc');
}
public function getAulasDia($dat){
$connection = ConnectionManager::get('default');
$data = new Time($dat);//Time::now();
$dataTime = mktime(0,0,0, $data->month, $data->day, $data->year);
$data_dia = getdate($dataTime);
$sql = "SELECT h.id, h.aula, d.nome as disciplina, u.nome professor,
CASE WHEN a.status IS NULL THEN 'P' ELSE a.status END as status,
ara.status as ministrou_antecipacao
FROM horario as h inner join
grade_curricular as gc on h.grade_curricular_id = gc.id inner join
turma as t on t.id = gc.turma_id inner join
calendario as c on c.turma_id = t.id inner join
disciplina as d on gc.disciplina_id = d.id inner join
professor as p on gc.professor_id = p.id inner join
usuario as u on p.usuario_id = u.id left outer join
aula as a on a.calendario_id = c.id and a.aula = h.aula left outer join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id
WHERE c.data = '".$data->i18nFormat('yyyy-MM-dd')."' and c.letivo = true
and h.dia = ".$data_dia['wday'] . " and t.id = ".$this->id.
" order by t.turno, h.aula";
return $connection->execute($sql)->fetchall('assoc');
}
}
<file_sep><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home <span class="sr-only">(current)</span></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Listagem <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?= $this->Html->link(__('Modalidades'), ['prefix'=>'admin', 'controller'=>'modalidade', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Cursos'), ['prefix'=>'admin', 'controller'=>'curso', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Salas'), ['prefix'=>'admin', 'controller'=>'sala', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Turmas'), ['prefix'=>'admin', 'controller'=>'turma', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Eixos'), ['prefix'=>'admin', 'controller'=>'eixo', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Disciplinas'), ['prefix'=>'admin', 'controller'=>'disciplina', 'action' => 'index']) ?></li>
<li role="separator" class="divider"></li>
<li><?= $this->Html->link(__('Coordenador'), ['prefix'=>'admin', 'controller'=>'coordenador', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Professor'), ['prefix'=>'admin', 'controller'=>'professor', 'action' => 'index']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Cadastros <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?= $this->Html->link(__('Modalidades'), ['prefix'=>'admin', 'controller'=>'modalidade', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Cursos'), ['prefix'=>'admin', 'controller'=>'curso', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Salas'), ['prefix'=>'admin', 'controller'=>'sala', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Turmas'), ['prefix'=>'admin', 'controller'=>'turma', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Eixos'), ['prefix'=>'admin', 'controller'=>'eixo', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Disciplinas'), ['prefix'=>'admin', 'controller'=>'disciplina', 'action' => 'add']) ?></li>
<li role="separator" class="divider"></li>
<li><?= $this->Html->link(__('Coordenador'), ['prefix'=>'admin', 'controller'=>'coordenador', 'action' => 'add']) ?></li>
<li><?= $this->Html->link(__('Professor'), ['prefix'=>'admin', 'controller'=>'professor', 'action' => 'add']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Grade <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?=$this->Html->link(__('Nova'), ['prefix'=>'admin', 'controller'=>'gradeCurricular', 'action' => 'add']) ?></li>
<li><?=$this->Html->link(__('Listar'), ['prefix'=>'admin', 'controller'=>'gradeCurricular', 'action' => 'index']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Horario <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?=$this->Html->link(__('Listar'), ['prefix'=>'admin','controller'=>'horario', 'action' => 'index']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Registro <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?=$this->Html->link(__('Calendario'), ['prefix'=>'admin','controller'=>'calendario', 'action' => 'index']) ?></li>
<li><?=$this->Html->link(__('Aula'), ['prefix'=>'admin','controller'=>'aula', 'action' => 'index']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Relatórios <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?=$this->Html->link(__('Turmas sem grade'), ['controller'=>'gradeCurricular', 'action' => 'turmaSemGrade']) ?></li>
<li><?=$this->Html->link(__('Faltas por turma'), ['controller'=>'aula', 'action' => 'faltaTurma']) ?></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><?=$usuarioLogado['nome']?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<?=$this->Html->link('Meu perfil', ['prefix'=>false, 'controller'=>'usuario', 'action'=>'view'])?>
</li>
<li role="separator" class="divider"></li>
<li><?= $this->Html->link(__('Sair'), ['prefix'=>false, 'controller'=>'usuario', 'action' => 'logout']) ?></li>
</ul>
</li>
</ul>
</div><file_sep><div class="panel panel-default">
<div class="panel-heading">Cadastro de curso</div>
<div class="panel-body">
<?= $this->Form->create($curso) ?>
<div class="form-group">
<?=$this->Form->input('descricao', ['div'=>false, 'class'=>'form-control', 'label'=>'Descrição']);?>
</div>
<div class="form-group">
<?=$this->Form->input('sigla', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('modalidade_id', ['options'=>$modalidade, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('eixo_id', ['options'=>$eixo, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
<?= $this->Form->end() ?>
</div>
</div>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
/**
* Professor Entity.
*/
class Professor extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = ['*' => true,];
protected function _getUsuarios()
{
$usuario = TableRegistry::get('Usuario');
return $usuario->findById($this->usuario_id)->first();
}
protected function _getFaltas()
{
$connection = ConnectionManager::get('default');
$sql = "select a.id, a.aula, c.data, t.nome as turma, d.nome as disciplina, cs.sigla
from grade_curricular as g inner join
turma as t on g.turma_id = t.id inner join
curso as cs on t.curso_id = cs.id inner join
calendario as c on t.id = c.turma_id inner join
aula as a on c.id = a.calendario_id and a.disciplina_id = g.disciplina_id inner join
disciplina as d on g.disciplina_id = d.id left outer join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id left outer join
reposicao_antecipacao as ra on ra.id = ara.reposicao_antecipacao_id
where professor_id = ".$this->id." and a.status = 'F' and (ra.id is null or ara.status <> 'M') ;";
return $connection->execute($sql)->fetchAll('assoc');
}
protected function _getFaltasWithoutSolicitacaoReposicao()
{
$connection = ConnectionManager::get('default');
$sql = "select a.id, a.aula, c.data, t.nome as turma, d.nome as disciplina, cs.sigla
from grade_curricular as g inner join
turma as t on g.turma_id = t.id inner join
curso as cs on t.curso_id = cs.id inner join
calendario as c on t.id = c.turma_id inner join
aula as a on c.id = a.calendario_id and a.disciplina_id = g.disciplina_id inner join
disciplina as d on g.disciplina_id = d.id left outer join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id left outer join
reposicao_antecipacao as ra on ra.id = ara.reposicao_antecipacao_id
where professor_id = ".$this->id." and a.status = 'F' and (ra.id is null or NOT ara.status IN ('M', 'C')) ;";
return $connection->execute($sql)->fetchAll('assoc');
}
public function _getTurmas(){
$grade = TableRegistry::get('GradeCurricular');
return $grade->find('list', [
'keyField'=>'turma.id',
'valueField'=>'turma.nome',
])
->where(['professor_id'=>$this->id, 'Turma.ativo'=>true])
->contain(['Turma'])
->toArray();
}
public function _getReposicoes(){
$connection = ConnectionManager::get('default');
$sql = "select ra.* from aula a inner join
calendario as c on a.calendario_id = c.id inner join
disciplina d on a.disciplina_id = d.id inner join
turma as t on c.turma_id = t.id inner join
grade_curricular as gc on gc.disciplina_id = d.id and gc.turma_id = t.id inner join
professor as p on gc.professor_id = p.id inner join
usuario as u on p.usuario_id = u.id inner join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id inner join
reposicao_antecipacao as ra on ra.id = ara.reposicao_antecipacao_id
where (coalesce(ra.status,'')<>'RC') and (p.id = ".$this->id.");";
return $connection->execute($sql)->fetchAll('assoc');
}
}
<file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\Calendario;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Event\Event;
use Cake\ORM\Entity;
/**
* Calendario Model
*
* @property \Cake\ORM\Association\BelongsTo $Turma
* @property \Cake\ORM\Association\HasMany $Aula
*/
class CalendarioTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('calendario');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('Turma', [
'foreignKey' => 'turma_id',
'joinType' => 'INNER'
]);
$this->hasMany('Aula', [
'foreignKey' => 'calendario_id'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('data', 'valid', ['rule' => 'date'])
->requirePresence('data', 'create')
->notEmpty('data');
$validator
->add('letivo', 'valid', ['rule' => 'boolean'])
->allowEmpty('letivo');
$validator
->allowEmpty('observacao');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['turma_id'], 'Turma'));
$rules->add($rules->isUnique(['turma_id', 'data']));
$check = function($calendario) {
return strtotime($calendario->data) >= strtotime(date('Y-m-d'));
};
$rules->addUpdate($check, [
'errorField' => 'Alterar data',
'message' => 'Não pode alterar calendário retroativo!'
]);
return $rules;
}
public function saveCalendario(Entity $calendario){
$dia = getdate($calendario->data);
if(!(($dia['wday']==6 or $dia['wday']==0) and ($calendario->letivo==false))){
$calendario->data = date('Y-m-d', $calendario->data);
$calend = $this->find()
->where(['data'=>$calendario->data, 'turma_id'=>$calendario->turma_id]);
if($calend->count()>0){
$calendario->id = $calend->first()->id;
}
$this->save($calendario);
}
}
}
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Collection\Collection;
/**
* Horario Controller
*
* @property \App\Model\Table\HorarioTable $Horario
*/
class HorarioController extends AppController
{
public function index()
{
$this->loadModel('Turma');
$this->paginate = [
'conditions'=>['ativo'=>true],
'contain'=>['Curso']
];
$this->set('turma', $this->paginate($this->Turma));
$this->set('_serialize', ['curso']);
}
public function edit($turma_id = null){
$this->loadModel('Turma');
$this->loadModel('GradeCurricular');
$turma = $this->Turma->get($turma_id, [
'contain' => ['Curso', 'GradeCurricular'],
]);
$disciplinas = $this->GradeCurricular->find('list',[
'keyField'=>'disciplina_id',
'valueField'=>'disciplina.nome',
])
->contain(['Disciplina'])
->where(['turma_id'=>$turma_id]);
$disciplinas = $disciplinas->toArray();
$disciplinas[0] = 'Vago';
$disciplinas = (object) $disciplinas;
$lista = $this->Horario->find('all')
->where(['GradeCurricular.turma_id'=>$turma_id])
->contain(['GradeCurricular'])
->order(['Horario.dia', 'Horario.aula'])->toArray();
$lista = (new Collection($lista))->combine('dia', 'grade_curricular.disciplina_id', 'aula')->toArray();
$horario = $this->Horario->newEntity();
if($this->request->is('post')){
$dis = $this->request->data['disciplina_id'];
foreach ($dis as $dia=>$aula_disc) {
$dia++;
foreach ($aula_disc as $aula => $disciplina) {
$aula++;
if($disciplina>0){
$grade = $this->GradeCurricular->find()
->where(['turma_id'=>$turma_id, 'disciplina_id'=>$disciplina])
->first();
}
$hr = $this->Horario->find()
->contain(['GradeCurricular'=>['Turma']])
->where(['dia'=>$dia, 'aula'=>$aula, 'Turma.id'=>$turma->id])
->first();
if($hr){
if($disciplina>0){
$hr->grade_curricular_id = $grade->id;
$this->Horario->save($hr);
}else{
$this->Horario->delete($hr);
}
}else{
if($disciplina>0){
$horario = $this->Horario->newEntity();
$horario->dia = $dia;
$horario->aula = $aula;
$horario->grade_curricular_id = $grade->id;
$this->Horario->save($horario);
}
}
}
}
$this->redirect(['action'=>'verHorario', $turma->id]);
}
$this->set(compact('disciplinas', 'turma', 'horario', 'lista'));
$this->set('_serialize', ['horario']);
}
public function verHorario($turma_id = null){
$this->loadModel('Turma');
$this->loadModel('Disciplina');
$turma = $this->Turma->get($turma_id, [
'contain'=>['Curso']
]);
$disciplinas = $this->Disciplina->find('list')->toArray();
$gradeCurricular = $this->Horario->GradeCurricular->find('list',[
'conditions'=>[
'GradeCurricular.turma_id'=>$turma_id
],
]);
$grade = $this->Horario->GradeCurricular->find('list',[
'keyField'=>'id',
'valueField'=>'disciplina_id',
'conditions'=>[
'GradeCurricular.turma_id'=>$turma_id
],
])->toArray();
$hr = $this->Horario->find('all')
->where(['Horario.grade_curricular_id IN'=>$gradeCurricular])
->order(['Horario.dia', 'Horario.aula']);
$hr = $hr->toArray();
$horario = (new Collection($hr))->combine('dia', 'grade_curricular_id', 'aula');
$this->set(compact('disciplinas', 'turma', 'horario', 'grade'));
}
}
<file_sep><script type="text/javascript">
$(function(){
$('#eixo').change(function(){
$.getJSON('../professor/getProfessores/'+$(this).val(), function( professores ) {
var opcoes = '<option value>Escolha um professor</option>';
$.each( professores, function( i, item ) {
opcoes += '<option value='+item.id+'>'+item.usuario.nome+'</option>';
});
$('#professores').html(opcoes).show();
//$('#turmasId').html();
});
});
});
</script>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Coordenador</div>
<div class="panel-body">
<?=$this->Form->create($coordenador)?>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('eixo_id', ['class'=>'form-control', 'options'=>$eixo, 'empty'=>'Escolha um eixo', 'id'=>'eixo']);?>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('modalidade_id', ['class'=>'form-control', 'options'=>$modalidade, 'empty'=>'Escolha uma modalidade', 'id'=>'modalidade', 'label'=>'Modalidade']);?>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('professor_id', ['class'=>'form-control', 'options'=>[], 'empty'=>'Escolha um professor', 'id'=>'professores', 'type'=>'select']);?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-ok"><i> Confirmar</i></span>
</button>
</div>
</div>
</div>
<?=$this->Form->end()?>
</div>
</div>
</div><file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Nome: <?= h($professor->usuario->nome)?> </h3>
<h3>Eixo: <?=$professor->eixo->descricao?> </h3>
<h3>Coordenador: <?=$professor->coordenador ? 'Sim' : 'Não'?> </h3>
</div>
<div class="panel-footer">
<?=$this->Html->link('Editar', ['action'=>'edit', $professor->id])?> |
<?=$this->Html->link('Nova senha', ['controller'=>'usuario', 'action'=>'novaSenha', $professor->usuario->id])?> |
<?=$this->Html->link('Minhas disciplinas', ['controller'=>'disciplina', 'action'=>'index'])?>
</div>
</div>
</div>
<file_sep><script type="text/javascript">
$(function(){
$('#data').datepicker({
format: 'dd/mm/yyyy',
autoclose: true,
});
});
</script>
<div class="panel panel-default">
<div class="panel-heading">Solicitação de reposição</div>
<div class="panel-body">
<?= $this->Form->create($reposicaoAntecipacao) ?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<?=$this->Form->input('justificativa', ['div'=>false, 'class'=>'form-control']);?>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<?=$this->Form->input('dataReposicao', ['div'=>false, 'class'=>'form-control', 'id'=>'data', 'type'=>'text']);?>
</div>
</div>
</div>
<div class="row">
<?=$this->Form->label('aulaReposicaoAntecipacao.reposicao_antecipacao_id');?>
<table class="table">
<thead>
<tr>
<th>Data</th>
<th>Turma</th>
<th>Aula</th>
<th>Aula Reposição</th>
<th>Repor</th>
</tr>
</thead>
<tbody>
<?=$this->Form->create($reposicaoAntecipacao)?>
<?php foreach ($usuario->professor->faltasWithoutSolicitacaoReposicao as $key=>$falta): ?>
<?=$this->Form->hidden('aulaReposicaoAntecipacao.'.$key.'.aula_id', ['value'=>$falta['id']]);?>
<tr>
<td><?=$falta['data']?></td>
<td><?=$falta['turma']."/".$falta['sigla']?></td>
<td><?=$falta['aula']?></td>
<td width="50px">
<?=$this->Form->input('aulaReposicaoAntecipacao.'.$key.'.aula_repor', ['div'=>false, 'label'=>false, 'class'=>'form-control', 'type'=>'number', 'style'=>'size:10px;']);?>
</td>
<td><?=$this->Form->checkbox('aulaReposicaoAntecipacao.'.$key.'.repor', ['hiddenField' => false]);?></td>
</tr>
<?php endforeach ?>
<?=$this->Form->end()?>
<tfoot>
<tr>
<td colspan="6">
<div class="form-group">
<button class="btn btn-success" type="submit">
<span class="glyphicon glyphicon-ok"> Salvar</i></span>
</button>
<a href="../turma" class="btn btn-default" >
<span class="glyphicon glyphicon-off"> Cancelar</span>
</a>
</div>
</td>
</tr>
</tfoot>
</tbody>
</table>
</div>
<?=$this->Form->end()?>
</div>
</div><file_sep><script type="text/javascript">
$(function(){
$('#data').hide();
$('#formAntecipacao').submit(function(){
if($('#data').val()==''){
alert('Escolha um dia no calendario!');
return false;
}
if($("input:checkbox:checked").length<=0){
alert('Marque ao menos uma aula!');
return false;
}
});
});
function classe(objeto){
$('button').attr('class', 'btn btn-danger');
$(objeto).attr("class", 'btn btn-primary');
}
function diasLetivosController($scope, $http) {
$scope.reposicao = {};
$scope.change = function(){
$scope.dias = [];
$http.get("../turma/getDiasLetivos/"+$scope.turmaSelecionada)
.success(function(response) {
$scope.dias = response.dias;
}
);
}
$scope.aulasDoDia = function(data){
$scope.dataMaxima = data;
$http.get("../aula/getAulas/"+data+"/"+$scope.turmaSelecionada)
.success(function(response) {
$scope.horario = response.horario;
}
);
}
}
</script>
<div class="panel panel-default" ng-app='calendarioApp'>
<div class="panel-heading">Solicitar antecipação</div>
<div class="panel-body" ng-controller="diasLetivosController">
<?= $this->Form->create($reposicaoAntecipacao, ['id'=>'formAntecipacao']) ?>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('turma', ['div'=>false, 'class'=>'form-control','id'=>'turma', 'options'=>$turma, 'empty'=>'Escolha uma turma', 'ng-model'=>'turmaSelecionada', 'ng-change'=>'change()', 'required'])?>
</div>
</div>
<div class="col-md-8" >
<div class="alert alert-warning">
Dias letivos:
<span ng-repeat="dia in dias">
<button class="btn btn-danger" ng-click="aulasDoDia(dia.ano+'-'+dia.mes+'-'+dia.dia, this)" onclick="classe(this);">
{{ dia.dia }}/{{ dia.mes }}
</button>
</span>
</div>
<br />
</div>
</div>
<table class="table table-striped">
<thead>
<th>Aula</th>
<th>Disciplina</th>
<th>Antecipar?</th>
</thead>
<tbody id="aulasDia">
<tr ng-repeat="h in horario">
<td>{{ h.aula }}</td>
<td>{{ h.grade_curricular.disciplina.nome }}</td>
<td>
<input type="checkbox" name="antecipar[]" value="{{ h.aula }}" class="clsAntecipar" />
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-md-4">
<label for="dataReposicao">Data:</label>
<input type="date" id="dataReposicao" name="dataReposicao" ng-model="dataReposicao" placeholder="yyyy-MM-dd" min="<?=date('Y-m-d')?>" max="{{ dataMaxima }}" class="form-control" required />
</div>
<div class="col-md-8">
<label for="justificativa" >Justificativa:</label>
<?=$this->Form->input('justificativa', ['class'=>'form-control', 'label'=>false])?>
</div>
</div>
<hr />
<div class="row">
<div class="col-md-2">
<input type="submit" value="Confirmar" class="btn btn-success" />
</div>
<input type="text" name="data" id="data" class="form-control" value="{{ dataMaxima }}"/>
</div>
<?=$this->Form->end()?>
</div>
</div><file_sep><?php
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
/**
* GradeCurricularFixture
*
*/
class GradeCurricularFixture extends TestFixture
{
/**
* Table name
*
* @var string
*/
public $table = 'grade_curricular';
/**
* Fields
*
* @var array
*/
// @codingStandardsIgnoreStart
public $fields = [
'id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
'carga_horaria' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'obrigatorio' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => '1', 'comment' => '', 'precision' => null],
'disciplina_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'professor_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'turma_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'_indexes' => [
'fk_grade_curricular_disciplina1_idx' => ['type' => 'index', 'columns' => ['disciplina_id'], 'length' => []],
'fk_grade_curricular_professor1_idx' => ['type' => 'index', 'columns' => ['professor_id'], 'length' => []],
'fk_grade_curricular_turma1_idx' => ['type' => 'index', 'columns' => ['turma_id'], 'length' => []],
],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
'fk_grade_curricular_disciplina1' => ['type' => 'foreign', 'columns' => ['disciplina_id'], 'references' => ['disciplina', 'id'], 'update' => 'noAction', 'delete' => 'noAction', 'length' => []],
'fk_grade_curricular_professor1' => ['type' => 'foreign', 'columns' => ['professor_id'], 'references' => ['professor', 'id'], 'update' => 'noAction', 'delete' => 'noAction', 'length' => []],
'fk_grade_curricular_turma1' => ['type' => 'foreign', 'columns' => ['turma_id'], 'references' => ['turma', 'id'], 'update' => 'noAction', 'delete' => 'noAction', 'length' => []],
],
'_options' => [
'engine' => 'InnoDB',
'collation' => 'utf8_general_ci'
],
];
// @codingStandardsIgnoreEnd
/**
* Records
*
* @var array
*/
public $records = [
[
'id' => 1,
'carga_horaria' => 1,
'obrigatorio' => 1,
'disciplina_id' => 1,
'professor_id' => 1,
'turma_id' => 1
],
];
}
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
/**
* AulaReposicaoAntecipacao Controller
*
* @property \App\Model\Table\AulaReposicaoAntecipacaoTable $AulaReposicaoAntecipacao
*/
class AulaReposicaoAntecipacaoController extends AppController
{
public function view($reposicao_id = null)
{
$aulaReposicaoAntecipacao = $this->AulaReposicaoAntecipacao->find()
->where(['ReposicaoAntecipacao.id'=>$reposicao_id])
->contain(['ReposicaoAntecipacao', 'Aula'=>['Calendario'=>['Turma'=>['Curso']]]]);
$this->set('aulaReposicaoAntecipacao', $aulaReposicaoAntecipacao);
$this->set('_serialize', ['aulaReposicaoAntecipacao']);
}
}
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Calendario Entity.
*/
class Calendario extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'data' => true,
'letivo' => true,
'observacao' => true,
'turma_id' => true,
'turma' => true,
'aula' => true,
];
}
<file_sep><script type="text/javascript">
$(function(){
$('#formGrade').submit(function(){
$('#modalDisciplina').modal('hide');
var dados = $("#formGrade").serialize();
if($('#id').val()==""){
$.ajax({
url: "../save",
data: dados,
type: "post",
success: function(data){
if(data){
alert('salvo com sucesso');
refreshList();
}else{
alert('Error!');
}
},
});
}else{
$.ajax({
url: "../edit",
data: dados,
type: "post",
success: function(data){
if(data){
alert('salvo com sucesso');
refreshList();
}else{
alert('Error!');
}
},
});
}
return false;
});
$('#btnNewDisciplina').click(function(){
var turma = $('#turma-id').val();
$(':input','#formGrade').val('')
$('#turma-id').val(turma);
$('#modalDisciplina').modal('show');
});
});
function excluir(handler, id){
if(confirm('Deseja realmente excluir essa linha?')){
$.ajax({
type: 'GET',
url: '../deleteGrade/'+id,
success: function(retorno){
if(retorno==true){
var tr = $(handler).closest('tr');
tr.remove();
}else{
alert('Impossivel excluir!');
}
}
});
};
};
function editar(gradeCurricularId){
$.getJSON('../getGrade/'+gradeCurricularId, function( grade ) {
$('#id').val(grade.id);
$('#disciplina_id').val(grade.disciplina_id);
$('#cargaHoraria').val(grade.carga_horaria);
$('#professor_id').val(grade.professor_id);
if(grade.obrigatorio){
$('#obrigatorio').attr('checked', true);
}
$('#modalDisciplina').modal();
});
}
function refreshList(){
$("#grade > tr").remove();
$.getJSON('../getGradeTurma/'+<?=$turma->id?>, function( grade ) {
var gradeTurma = $('#grade');
$.each(grade, function(i, item){
var obrigatorio = item.obrigatorio ? 'SIM' : 'NAO';
var linkRemove = "<a href = '#' class='btn btn-danger' onClick=remove(this, "+item.id+");><span class='glyphicon glyphicon-remove'> Excluir</span></a>";
var linkEditar = "<a href = '#' class='btn btn-primary' onClick=editar("+item.id+");><span class='glyphicon glyphicon-edit'> Editar</span></a>";
gradeTurma.append('<tr><td>'+item.disciplina+'</td><td>'+item.carga_horaria+'</td><td>'+item.professor+'</td><td>'+obrigatorio+'</td><td>'+linkRemove+" "+linkEditar+'</td></tr>');
});
});
}
</script>
<div class="panel panel-default">
<div class="panel-heading">Grade curricular: <?=$turma->nome?> / <?=$turma->ano?></div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Disciplina</th>
<th>Carga Horária</th>
<th>Professor</th>
<th>Obrigatória</th>
<th><?=__('Actions')?></th>
</tr>
</thead>
<tbody class='grade' id="grade">
<?php foreach ($grade as $key=>$gradeCurricular): ?>
<tr>
<td>
<?= $gradeCurricular->disciplina->nome?>
</td>
<td>
<?= $gradeCurricular->carga_horaria?>
</td>
<td>
<?= $gradeCurricular->professor->usuarios->nome?>
</td>
<td>
<?=$gradeCurricular->obrigatorio ? 'SIM' : 'NAO' ?>
</td>
<td>
<a href="#" class="btn btn-danger" onclick="excluir(this, <?=$gradeCurricular->id?>);">
<span class="glyphicon glyphicon-remove"> Excluir</span>
</a>
<a href="#" class="btn btn-primary" onclick="editar(<?=$gradeCurricular->id?>);">
<span class="glyphicon glyphicon-edit"> Editar</span>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<a href="#" class="btn btn-success" id="btnNewDisciplina">
<span class="glyphicon glyphicon-plus"> Disciplina</span>
</a>
</div>
</div>
<div class="modal fade" id="modalDisciplina" tabindex="-1" role="dialog" aria-labelledby="Modal disciplina">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalDisciplinaLabel">Incluir disciplina</h4>
</div>
<div class="modal-body">
<?=$this->Form->create('GradeCurricular', ['id'=>'formGrade'])?>
<?=$this->Form->input('id', ['label'=>false, 'class'=>'form-control', 'id'=>'id' ,'type'=>'hidden'])?>
<?=$this->Form->input('turma_id', ['type'=>'hidden', 'value'=>$turma->id])?>
<div class="form-group">
<label class="control-label">Disciplina</label>
<?=$this->Form->input('disciplina_id', ['label'=>false, 'class'=>'form-control', 'id'=>'disciplina_id'])?>
</div>
<div class="form-group">
<label class="control-label">Carga Horária</label>
<?=$this->Form->input('carga_horaria', ['type'=>'number','label'=>false, 'class'=>'form-control', 'id'=>'cargaHoraria'])?>
</div>
<div class="form-group">
<label class="control-label">Professor</label>
<?=$this->Form->input('professor_id', ['label'=>false, 'class'=>'form-control', 'options'=>$professores, 'id'=>'professor_id'])?>
</div>
<div class="form-group">
<label class="control-label">Obrigatoria</label>
<?=$this->Form->checkbox('obrigatorio', ['hiddenField' => false, 'label'=>false, 'class'=>'form-control', 'id'=>'obrigatorio']);?>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-floppy-save"> Salvar</span>
</button>
</div>
</form>
</div>
</div>
</div><file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Descrição: <?=$eixo->descricao?> </h3>
</div>
<div class="panel-footer"><?=$this->Html->link('Editar', ['action'=>'edit', $eixo->id])?></div>
</div>
<?php if (!empty($eixo->professor)): ?>
<div class="panel panel-default">
<div class="panel-heading">Professores relacionados</div>
<div class="panel-body">
<table class="table table-striped">
<tr>
<th><?= __('Coordenador') ?></th>
<th><?= __('Usuario Id') ?></th>
<th><?= __('Eixo Id') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
<?php foreach ($eixo->professor as $professor): ?>
<tr>
<td><?= h($professor->coordenador ? 'Sim' : 'Não') ?></td>
<td><?= h($professor->usuario_id) ?></td>
<td><?= h($professor->eixo_id) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['controller' => 'Professor', 'action' => 'view', $professor->id]) ?>
<?= $this->Html->link(__('Edit'), ['controller' => 'Professor', 'action' => 'edit', $professor->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
</div>
<file_sep><div class="panel panel-default">
<div class="panel-heading">Cadastro de modalidade</div>
<div class="panel-body">
<?= $this->Form->create($modalidade) ?>
<div class="form-group">
<?=$this->Form->input('descricao', ['div'=>false, 'class'=>'form-control', 'label'=>'Descrição']);?>
</div>
<div class="form-group">
<?=$this->Form->input('tempoAula', ['options'=>$CHs, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
<?= $this->Form->end() ?>
</div>
</div>
<div class="modalidade form large-10 medium-9 columns">
</div>
<file_sep><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home <span class="sr-only">(current)</span></a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Listagem <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?= $this->Html->link(__('Turmas'), ['controller'=>'turma', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Faltas'), ['controller'=>'aula', 'action' => 'verFaltas']) ?></li>
<li><?= $this->Html->link(__('Reposições'), ['controller'=>'ReposicaoAntecipacao', 'action' => 'index']) ?></li>
<li><?= $this->Html->link(__('Disciplinas'), ['controller'=>'professor', 'action' => 'minhasDisciplinas']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Solicitar <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><?= $this->Html->link(__('Reposição'), ['prefix'=>false, 'controller'=>'ReposicaoAntecipacao', 'action' => 'solicitarReposicao']) ?></li>
<li><?= $this->Html->link(__('Antecipação'), ['prefix'=>false, 'controller'=>'ReposicaoAntecipacao', 'action' => 'solicitarAntecipacao']) ?></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Relatórios <span class="caret"></span></a>
<ul class="dropdown-menu">
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><?=$usuarioLogado['nome']?> <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<?=$this->Html->link('Meu perfil', ['prefix'=>false, 'controller'=>'usuario', 'action'=>'view'])?>
</li>
<li role="separator" class="divider"></li>
<li><?= $this->Html->link(__('Sair'), ['prefix'=>false, 'controller'=>'usuario', 'action' => 'logout']) ?></li>
</ul>
</li>
</ul>
</div><file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
/**
* Professor Controller
*
* @property \App\Model\Table\ProfessorTable $Professor
*/
class ProfessorController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->loadModel('Coordenador');
$this->paginate = [
'contain' => ['Usuario', 'Eixo']
];
$coordenadores = $this->Coordenador->find('list', [
'keyField'=>['professor_id'],
])->toArray();
$this->set('professor', $this->paginate($this->Professor));
$this->set('coordenadores', $coordenadores);
$this->set('_serialize', ['professor']);
}
/**
* View method
*
* @param string|null $id Professor id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$professor = $this->Professor->get($id, [
'contain' => ['Usuario', 'Eixo']
]);
$this->set('professor', $professor);
$this->set('_serialize', ['professor']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$professor = $this->Professor->newEntity();
if ($this->request->is('post')) {
$professor = $this->Professor->patchEntity($professor, $this->request->data, [
'associated'=>'Usuario'
]);
$professor->usuario->ativo = true;
$professor->usuario->senha = $professor->usuario->matricula;
if ($this->Professor->save($professor)) {
$this->Flash->success(__('The professor has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The professor could not be saved. Please, try again.'));
}
}
$usuario = $this->Professor->Usuario->find('list', ['limit' => 200]);
$eixo = $this->Professor->Eixo->find('list', ['limit' => 200]);
$this->set(compact('professor', 'usuario', 'eixo'));
$this->set('_serialize', ['professor']);
}
/**
* Edit method
*
* @param string|null $id Professor id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$professor = $this->Professor->get($id, [
'contain' => ['Usuario']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$professor = $this->Professor->patchEntity($professor, $this->request->data, [
'associated'=>'Usuario'
]);
if ($this->Professor->save($professor)) {
$this->Flash->success(__('The professor has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The professor could not be saved. Please, try again.'));
}
}
$usuario = $this->Professor->Usuario->find('list', ['limit' => 200]);
$eixo = $this->Professor->Eixo->find('list', ['limit' => 200]);
$this->set(compact('professor', 'usuario', 'eixo'));
$this->set('_serialize', ['professor']);
}
public function getProfessores($eixo_id=null){
$this->layout = 'ajax';
$this->autoRender = FALSE;
echo json_encode($this->Professor->find()->contain(['Usuario'])->where(['eixo_id'=>$eixo_id])->toArray());
}
}
<file_sep><table class="table table-striped">
<thead>
<tr>
<th><?= $this->Paginator->sort('eixo') ?></th>
<th><?= $this->Paginator->sort('modalidade') ?></th>
<th><?= $this->Paginator->sort('professor') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($coordenador as $coordenador): ?>
<tr>
<td>
<?= $coordenador->has('professor') ? $this->Html->link($coordenador->professor->eixo->descricao, ['controller' => 'Eixo', 'action' => 'view', $coordenador->professor->eixo->id]) : '' ?>
</td>
<td>
<?= $coordenador->has('modalidade') ? $this->Html->link($coordenador->modalidade->descricao, ['controller' => 'Modalidade', 'action' => 'view', $coordenador->modalidade->id]) : '' ?>
</td>
<td>
<?=$coordenador->has('professor') ? h($coordenador->professor->usuario->nome) : '' ?>
</td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $coordenador->professor_id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $coordenador->professor_id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div><file_sep><div class="actions columns large-2 medium-3">
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li><?= $this->Html->link(__('Edit Coordenador'), ['action' => 'edit', $coordenador->professor_id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Coordenador'), ['action' => 'delete', $coordenador->professor_id], ['confirm' => __('Are you sure you want to delete # {0}?', $coordenador->professor_id)]) ?> </li>
<li><?= $this->Html->link(__('List Coordenador'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Coordenador'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Modalidade'), ['controller' => 'Modalidade', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Modalidade'), ['controller' => 'Modalidade', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Professor'), ['controller' => 'Professor', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Professor'), ['controller' => 'Professor', 'action' => 'add']) ?> </li>
</ul>
</div>
<div class="coordenador view large-10 medium-9 columns">
<h2><?= h($coordenador->professor_id) ?></h2>
<div class="row">
<div class="large-5 columns strings">
<h6 class="subheader"><?= __('Professor') ?></h6>
<p><?= $coordenador->has('professor') ? $this->Html->link($coordenador->professor->nome, ['controller' => 'Professor', 'action' => 'view', $coordenador->professor->id]) : '' ?></p>
<h6 class="subheader"><?= __('Modalidade') ?></h6>
<p><?= $coordenador->has('modalidade') ? $this->Html->link($coordenador->modalidade->descricao, ['controller' => 'Modalidade', 'action' => 'view', $coordenador->modalidade->id]) : '' ?></p>
</div>
</div>
</div>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
/**
* Coordenador Entity.
*/
class Coordenador extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'*'=>true,
];
protected function _getReposicoesPendentes(){
$connection = ConnectionManager::get('default');
$professor = TableRegistry::get('Professor');
$professor = $professor->get($this->professor_id);
$sql = "select ra.id, a.id as aula_id, u.nome, c.data, t.nome as turma,
ra.dataReposicao as data_reposicao, ra.justificativa
from grade_curricular as g inner join
turma as t on g.turma_id = t.id inner join
curso as cs on t.curso_id = cs.id inner join
calendario as c on t.id = c.turma_id inner join
aula as a on c.id = a.calendario_id and a.disciplina_id = g.disciplina_id inner join
disciplina as d on g.disciplina_id = d.id inner join
aula_reposicao_antecipacao as ara on ara.aula_id = a.id inner join
reposicao_antecipacao as ra on ra.id = ara.reposicao_antecipacao_id inner join
professor as p on p.id = g.professor_id inner join
usuario as u on p.usuario_id = u.id
where p.eixo_id = ".$professor->eixo_id." and cs.modalidade_id = ".$this->modalidade_id."
and a.status = 'F' and (NOT coalesce(ra.status,'') in('A', 'R', 'C'));";
return $connection->execute($sql)->fetchAll('assoc');
}
}
<file_sep><div class="panel panel-default">
<div class="panel-heading">Cadastro de Turma</div>
<div class="panel-body">
<?= $this->Form->create($turma) ?>
<div class="form-group">
<?=$this->Form->input('nome', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('ano', ['options'=>$anos, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('turno', ['options'=>$turnos, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('curso_id', ['options'=>$curso, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('sala_id', ['options'=>$sala, 'div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('ativo', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
<?= $this->Form->end() ?>
</div>
<file_sep><?=$this->element('menuLateral')?>
<div class="gradeCurricular view large-10 medium-9 columns">
<h2><?= h($gradeCurricular->id) ?></h2>
<div class="row">
<div class="large-5 columns strings">
<h6 class="subheader"><?= __('Disciplina') ?></h6>
<p><?= $gradeCurricular->has('disciplina') ? $this->Html->link($gradeCurricular->disciplina->id, ['controller' => 'Disciplina', 'action' => 'view', $gradeCurricular->disciplina->id]) : '' ?></p>
<h6 class="subheader"><?= __('Professor') ?></h6>
<p><?= $gradeCurricular->has('professor') ? $this->Html->link($gradeCurricular->professor->id, ['controller' => 'Professor', 'action' => 'view', $gradeCurricular->professor->id]) : '' ?></p>
</div>
<div class="large-2 columns numbers end">
<h6 class="subheader"><?= __('Id') ?></h6>
<p><?= $this->Number->format($gradeCurricular->id) ?></p>
<h6 class="subheader"><?= __('Carga Horaria') ?></h6>
<p><?= $this->Number->format($gradeCurricular->carga_horaria) ?></p>
<h6 class="subheader"><?= __('Turma Id') ?></h6>
<p><?= $this->Number->format($gradeCurricular->turma_id) ?></p>
</div>
<div class="large-2 columns booleans end">
<h6 class="subheader"><?= __('Obrigatorio') ?></h6>
<p><?= $gradeCurricular->obrigatorio ? __('Yes') : __('No'); ?></p>
</div>
</div>
</div>
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Usuario Controller
*
* @property \App\Model\Table\UsuarioTable $Usuario
*/
class IndexController extends AppController
{
public function index(){
}
}
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Aula Controller
*
* @property \App\Model\Table\AulaTable $Aula
*/
class TurmaController extends AppController
{
public function index(){
$this->loadModel('Usuario');
$usuario = $this->Usuario->get($this->Auth->user('id'), [
'contain'=>['Professor']
]);
$grade = $this->Turma->GradeCurricular->find()
->distinct(['turma_id'])
->contain(['Turma'])
->where(['professor_id'=>$usuario->professor->id]);
$this->set('grade', $grade);
$this->set('_serialize', ['grade']);
}
public function getDiasLetivos($turma_id=null, $limite=9){
$this->layout= 'ajax';
$this->loadModel('Calendario');
$this->loadModel('Horario');
$this->loadModel('Usuario');
$usuario=$this->Usuario->get($this->Auth->user('id'), ['contain'=>'Professor']);
$dias = $this->Horario->find('list', [
'keyField'=>'id',
'valueField'=>'dia'
])
->where([
'GradeCurricular.professor_id'=>$usuario->professor->id,
'GradeCurricular.turma_id'=>$turma_id
])
->contain(['GradeCurricular'])
->toArray();
foreach ($dias as $key => $dia) {
$dias[$key] = $dia+1;
}
$datas['dias'] = $this->Calendario->find()
->select([
'dia'=>"extract(DAY FROM data)",
'mes'=>"extract(MONTH FROM data)",
'ano'=>"extract(YEAR FROM data)"
])
->where([
'turma_id'=>$turma_id,
'letivo'=>true,
'data >'=>date('Y-m-d'),
'DAYOFWEEK(data) in'=>$dias
])
->limit($limite)
->toArray();
echo json_encode($datas);
}
}
<file_sep><table class="table table-striped">
<thead>
<tr>
<th>Numero</th>
<th>Professor</th>
<th>data falta</th>
<th>Turma</th>
<th>Data reposição</th>
<th>Justificativa</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php foreach ($coordenador->reposicoesPendentes as $reposição): ?>
<tr>
<td><?=$reposição['id']?></td>
<td><?=$reposição['nome']?></td>
<td><?=$reposição['data']?></td>
<td><?=$reposição['turma']?></td>
<td><?=$reposição['data_reposicao']?></td>
<td><?=$reposição['justificativa']?></td>
<td>
<a href="/tcc/coordenador/reposicao_antecipacao/view/3">
<?=$this->Html->link('<span class="glyphicon glyphicon-search"></span>', ['action'=>'view', $reposição['id']], ['escape'=>false]);?>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table><file_sep><?=$this->element('menuLateralProf')?>
<div class="professor form large-10 medium-9 columns">
<?= $this->Form->create($professor) ?>
<fieldset>
<legend><?= __('Edit Professor') ?></legend>
<?php
echo $this->Form->input('usuario.nome');
echo $this->Form->input('usuario.email');
echo $this->Form->input('usuario.matricula');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
<file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\Coordenador;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* Coordenador Model
*
* @property \Cake\ORM\Association\BelongsTo $Professor
* @property \Cake\ORM\Association\BelongsTo $Modalidade
*/
class CoordenadorTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('coordenador');
$this->displayField('professor_id');
$this->primaryKey('professor_id');
$this->hasOne('Professor', [
'foreignKey' => 'id',
'joinType' => 'INNER'
]);
$this->BelongsTo('Modalidade', [
'foreignKey' => 'modalidade_id',
'joinType' => 'INNER'
]);
}
public function validationDefault(Validator $validator)
{
$validator->add('professor_id', 'custom', [
'rule' => [$this, 'validaEixo'],
'message'=>'Eixo modalidade já possui coordenador'
]);
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['professor_id'], 'Professor'));
$rules->add($rules->existsIn(['modalidade_id'], 'Modalidade'));
return $rules;
}
public function validaEixo($value, $context){
$professor = TableRegistry::get('Professor');
$professor = $professor->get($context['data']['professor_id']);
$existe = $this->find()
->contain(['Professor'])
->where([
'Professor.eixo_id'=>$professor->eixo_id,
'modalidade_id'=>$context['data']['modalidade_id']
])->count();
return $existe <= 0 ;
}
}
<file_sep><div class="panel panel-default">
<div class="panel-heading">Listagem de Modalidades</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th><?= $this->Paginator->sort('descrição') ?></th>
<th><?= $this->Paginator->sort('Hora/aula') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($modalidade as $modalidade): ?>
<tr>
<td><?= h($modalidade->descricao) ?></td>
<td><?= $CHs[$modalidade->tempoAula] ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $modalidade->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $modalidade->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
</div>
<file_sep><table class="table table-bordered">
<caption><?=$turma->nome."/".$turma->curso->descricao?></caption>
<thead>
<tr>
<th>Aula</th>
<th>Seg</th>
<th>Ter</th>
<th>Qua</th>
<th>Qui</th>
<th>Sex</th>
<th>Sab</th>
</tr>
</thead>
<tbody>
<?php $horario = $horario->toArray();?>
<?php for($i=1;$turma->turno!='I' ? $i<=6 : $i<10;$i++):?>
<tr>
<td><?=$i?></td>
<?php
for($j=1;$turma->turno!='I' ? $j<=6 : $j<=10;$j++){
if(@$horario[$i][$j]){
echo "<td>".$disciplinas[$grade[$horario[$i][$j]]]."</td>";
}else{
echo "<td>Vago</td>";
}
}
?>
</tr>
<?php endfor;?>
</tbody>
<tfoot>
<tr>
<td colspan="7" align="right">
<a class="btn btn-primary" href="../edit/<?=$turma->id?>">
<span class="glyphicon glyphicon-edit"> Editar</span>
</a>
</td>
</tr>
</tfoot>
</table><file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Usuario Controller
*
* @property \App\Model\Table\UsuarioTable $Usuario
*/
class UsuarioController extends AppController
{
/**
* Index method
*
* @return void
*/
public function beforeFilter(Event $event){
parent::beforeFilter($event);
$this->loadModel('Administrador');
$this->loadModel('Professor');
$this->Auth->allow('login');
}
/**
* View method
*
* @param string|null $id Usuario id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view()
{
$usuario = $this->Usuario->get($this->Auth->user('id'), [
'contain' => []
]);
$professor = $this->Professor->findByUsuarioId($usuario->id);
if($professor->isEmpty()){
$admin = $this->Administrador->findByUsuarioId($usuario->id)->first();
return $this->redirect([
'prefix'=>'admin',
'controller'=>'administrador',
'action'=>'view', $admin->id]);
}else{
$professor = $professor->first();
return $this->redirect([
'prefix'=>$professor->coordenador ? 'coordenador' : false,
'controller'=>'professor',
'action'=>'view']);
}
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
/**
* Edit method
*
* @param string|null $id Usuario id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$usuario = $this->Usuario->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$usuario = $this->Usuario->patchEntity($usuario, $this->request->data);
if ($this->Usuario->save($usuario)) {
$this->Flash->success(__('The usuario has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The usuario could not be saved. Please, try again.'));
}
}
$this->set(compact('usuario'));
$this->set('_serialize', ['usuario']);
}
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$admin = $this->Administrador->findByUsuarioId($user['id']);
if($admin->isEmpty()){
$professor = $this->Professor->findByUsuarioId($user['id'])->first();
if ($professor->coordenador){
return $this->redirect(['prefix'=>'coordenador', 'controller'=>'professor']);
}else{
return $this->redirect(['prefix'=>false, 'controller'=>'professor', 'action'=>'minhasDisciplinas']);
}
}else{
return $this->redirect(['prefix'=>'admin', 'controller'=>'aula']);
}
}
$this->Flash->error(__('Invalid username or password, try again'), [
'key' => 'auth',
]);
}elseif($this->Auth->user()){
$this->redirect(['action'=>'logout']);
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function novaSenha(){
$usuario = $this->Usuario->get($this->Auth->user('id'), [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$usuario = $this->Usuario->patchEntity($usuario, $this->request->data);
if ($this->Usuario->save($usuario)) {
$this->Flash->success(__('The usuario has been saved.'));
return $this->redirect(['controller'=>'index', 'action' => 'index']);
} else {
$this->Flash->error(__('The usuario could not be saved. Please, try again.'));
}
}
$this->set(compact('usuario'));
$this->set('_serialize', ['usuario']);
}
}
<file_sep><!DOCTYPE html>
<html lang="pt-BR" ng-app>
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $this->fetch('title') ?>
</title>
<?= $this->Html->meta('icon') ?>
<?= $this->Html->script(['jquery.min','datepicker/bootstrap-datepicker','chart.min', 'bootstrap3-typeahead.min', 'angular-1.0.1.min']) ?>
<!--<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>-->
<?= $this->Html->css(['bootstrap/bootstrap.min', 'datepicker/datepicker']) ?>
<?= $this->Html->css('customize') ?>
<?= $this->fetch('meta') ?>
<?= $this->fetch('css') ?>
<?= $this->fetch('script') ?>
</head>
<body>
<?php if($usuarioLogado):?>
<?=$this->element('cabecalho');?>
<?php endif;?>
<div class="container">
<div id="content">
<?= $this->Flash->render() ?>
<div class="row">
<?= $this->fetch('content') ?>
</div>
</div>
<?= $this->Html->script('bootstrap/bootstrap.min') ?>
</div>
</body>
</html>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Horario Entity.
*/
class Horario extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'dia' => true,
'aula' => true,
'hora_inicio' => true,
'hora_termino' => true,
'grade_curricular_id' => true,
'grade_curricular' => true,
];
}
<file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\Aula;
use App\Model\Entity\Calendario;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Aula Model
*
* @property \Cake\ORM\Association\BelongsTo $Disciplina
* @property \Cake\ORM\Association\BelongsTo $Calendario
* @property \Cake\ORM\Association\BelongsToMany $ReposicaoAntecipacao
*/
class AulaTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('aula');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Disciplina', [
'foreignKey' => 'disciplina_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Calendario', [
'foreignKey' => 'calendario_id',
'joinType' => 'INNER'
]);
$this->hasMany('AulaReposicaoAntecipacao');
$this->hasMany('Horario');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->requirePresence('status', 'create')
->notEmpty('status');
$validator
->add('aula', 'valid', ['rule' => 'numeric'])
->requirePresence('aula', 'create')
->notEmpty('aula');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['disciplina_id'], 'Disciplina'));
$rules->add($rules->existsIn(['calendario_id'], 'Calendario'));
$rules->add($rules->isUnique(['aula', 'disciplina_id', 'calendario_id']));
return $rules;
}
public function saveAulaAntecipacao(Calendario $cal, array $aulas){
$dataTime = mktime(0,0,0, $cal->data->month, $cal->data->day, $cal->data->year);
$dia = getdate($dataTime);
$horario = $this->Horario->find('list', [
'keyField'=>'aula',
'valueField'=>'grade_curricular.disciplina_id'
])
->where([
'GradeCurricular.turma_id'=>$cal->turma_id,
'dia'=>$dia['wday'],
'aula IN'=>$aulas
])
->contain(['GradeCurricular']);
foreach ($horario as $aula=>$disciplina_id) {
$aula = $this->newEntity([
'status'=>'A',
'aula'=>$aula,
'disciplina_id'=>$disciplina_id,
'calendario_id'=>$cal->id
]);
$this->save($aula);
}
}
}
<file_sep><?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller
{
/**
* Initialization hook method.
*
* Use this method to add common initialization code like loading components.
*
* @return void
*/
protected $CHs = [50=>'50 Minutos', 60=>'60 Minutos'];
protected $turnos = ['M'=>'Manhã', 'T'=>'Tarde', 'N'=>'Noite', 'I'=>'Integral'];
protected $meses = [
1=>'Janeiro', 2=>'Fevereiro', 3=>'Março', 4=>'Abril',
5=>'Maio', 6=>'Junho', 7=>'Julho', 8=>'Agosto',
9=>'Setembro', 10=>'Outubro', 11=>'Novembro', 12=>'Dezembro',
];
protected $statusReposicao = [
'A'=>'Aprovada',
'C'=>'Criada',
'R'=>'Rejeitada',
'M'=>'Ministrada'
];
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
$this->loadComponent('Csrf');
$this->loadComponent('Auth', [
'authorize' => 'Controller',
'authenticate' => [
'Form' => [
'userModel'=>'Usuario',
'fields' => ['username' => 'email', 'password' => '<PASSWORD>']
]
],
'authError' => 'Acesso negado!',
'loginAction' => [
'controller' => 'usuario',
'action' => 'login',
'prefix'=>false
],
'logoutRedirect' => [
'controller' => 'usuario',
'action' => 'login',
]
]);
}
public function beforeFilter(Event $event){
$this->layout = 'bootstrap';
$this->set('CHs', $this->CHs);
$this->set('turnos', $this->turnos);
$this->set('meses', $this->meses);
$this->set('statusReposicao', $this->statusReposicao);
$this->loadModel('Administrador');
$this->loadModel('Professor');
$this->loadModel('Usuario');
$usuarioLogado = $this->Auth->user();
$user = $this->Usuario->find()
->where(['Usuario.id'=>$usuarioLogado['id']])
->contain(['Professor'=>['Coordenador'], 'Administrador'])
->first();
if(isset($usuarioLogado)){
$usuarioLogado['coordenador'] = @$user->professor->coordenador;
$usuarioLogado['professor'] = (bool) $user->professor;
}
$this->set('usuarioLogado', $usuarioLogado);
}
public function isAuthorized($user = null)
{
$admin = $this->Administrador->find('all', [
'conditions'=>['usuario_id'=>$user['id']]
])->first();
$professor = $this->Professor->find('all', [
'contain'=>['Coordenador'],
'conditions'=>['usuario_id'=>$user['id']]
])->first();
if (empty($this->request->params['prefix'])) {
return true;
}
if ($this->request->params['prefix'] === 'coordenador') {
return (bool)(@$professor->coordenador->modalidade_id);
}
// Only admins can access admin functions
if ($this->request->params['prefix'] === 'admin') {
return (bool)($admin);
}
return false;
}
}
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
/**
* Administrador Entity.
*/
class Administrador extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'*'=>true,
'senha'=>false
];
protected function _getUsuarios()
{
$usuario = TableRegistry::get('Usuario');
return $usuario->findById($this->usuario_id)->first();
}
}
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Disciplina Entity.
*/
class Disciplina extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'nome' => true,
'grade_curricular' => true,
];
}
<file_sep><div class="panel panel-default">
<div class="panel-heading">Reposição</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th><?=h('Data falta')?></th>
<th><?=h('Turma')?></th>
<th><?=h('Aula')?></th>
<th><?=h('Repor na')?></th>
<th><?=h('status')?></th>
</tr>
</thead>
<tbody>
<?php foreach ($aulaReposicaoAntecipacao as $aula): ?>
<tr>
<td><?=$aula->aula->calendario->data?></td>
<td><?=$aula->aula->calendario->turma->nome."/".$aula->aula->calendario->turma->curso->sigla?></td>
<td><?=$aula->aula->aula?></td>
<td><?=$aula->aula_repor?></td>
<td><?=$aula->status?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\Table;
/**
* ReposicaoAntecipacao Controller
*
* @property \App\Model\Table\ReposicaoAntecipacaoTable $ReposicaoAntecipacao
*/
class ReposicaoAntecipacaoController extends AppController
{
public function index(){
$this->loadModel('Professor');
$professor = $this->Professor->findByUsuarioId($this->Auth->user('id'))->first();
$this->set('reposicaoAntecipacao', $professor->reposicoes);
}
public function solicitarReposicao()
{
$usuario = $this->Usuario->get($this->Auth->user('id'), [
'contain'=>['Professor']
]);
$reposicaoAntecipacao = $this->ReposicaoAntecipacao->newEntity();
$this->loadModel('AulaReposicaoAntecipacao');
if($this->request->is('post')){
$this->request->data['dataReposicao'] = implode("-", array_reverse(explode("/", $this->request->data['dataReposicao'])));
$data = $this->request->data['aulaReposicaoAntecipacao'];
unset($this->request->data['aulaReposicaoAntecipacao']);
$reposicaoAntecipacao = $this->ReposicaoAntecipacao->newEntity($this->request->data);
$reposicaoAntecipacao->created = date('Y-m-d');
if($this->ReposicaoAntecipacao->save($reposicaoAntecipacao)){
$dados = [];
foreach ( $data as $key => $valor) {
if(@$valor['repor']==true){
$dados[] = [
'aula_repor'=> $valor['aula_repor'],
'reposicao_antecipacao_id' => $reposicaoAntecipacao->id,
'aula_id' => $valor['aula_id'],
'status'=>'C'
];
}
}
$aulas = $this->AulaReposicaoAntecipacao->newEntities($dados);
$solicitou = true;
$this->AulaReposicaoAntecipacao->connection()->transactional(function () use ($aulas, &$solicitou) {
foreach ($aulas as $entity) {
if(!$this->AulaReposicaoAntecipacao->save($entity)){
$solicitou = false;
break;
}
}
});
if($solicitou){
$this->Flash->success(__('Solicitação efetuada com sucesso!'));
}else{
$reposicaoAntecipacao->status = 'RC';
$this->ReposicaoAntecipacao->save($reposicaoAntecipacao);
$this->Flash->error(__('Impossivel gravar aula para reposicao!'));
}
return $this->redirect(['action'=>'solicitarReposicao']);
}
}
$this->set(compact('usuario', 'reposicaoAntecipacao'));
$this->set('_serialize', ['reposicaoAntecipacao']);
}
public function solicitarAntecipacao(){
$this->loadModel('Turma');
$usuario = $this->Usuario->get($this->Auth->user('id'), ['contain'=>'Professor']);
$turma = $usuario->professor->turmas;
$reposicaoAntecipacao = $this->ReposicaoAntecipacao->newEntity();
if($this->request->is('post')){
$this->loadModel('Calendario');
$this->loadModel('Horario');
$this->loadModel('Aula');
$this->loadModel('AulaReposicaoAntecipacao');
$calendario = $this->Calendario->findByDataAndTurmaId(
$this->request->data['data'],
$this->request->data['turma']
)->first();
$this->Aula->saveAulaAntecipacao($calendario, $this->request->data['antecipar']);
$reposicao = $this->ReposicaoAntecipacao->newEntity();
$reposicao->set([
'justificativa'=>$this->request->data['justificativa'],
'dataReposicao'=>$this->request->data['dataReposicao'],
]);
if($this->ReposicaoAntecipacao->saveAntecipacao($reposicao, $this->request->data['antecipar'], $calendario)){
$this->Flash->success(__('Solicitação efetuada com sucesso!'));
//$this->redirect(['controller'=>'professor','action'=>'minhasDisciplinas']);
}else{
$this->Flash->error(__('Solicitação não efetuada!'));
}
}
$this->set(compact('turma', 'reposicaoAntecipacao'));
$this->set('_serialize', ['reposicaoAntecipacao']);
}
}
<file_sep><?php
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
/**
* CoordenadorFixture
*
*/
class CoordenadorFixture extends TestFixture
{
/**
* Table name
*
* @var string
*/
public $table = 'coordenador';
/**
* Fields
*
* @var array
*/
// @codingStandardsIgnoreStart
public $fields = [
'professor_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'modalidade_id' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'_indexes' => [
'fk_coordenador_modalidade1_idx' => ['type' => 'index', 'columns' => ['modalidade_id'], 'length' => []],
],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['professor_id'], 'length' => []],
'fk_coordenador_modalidade1' => ['type' => 'foreign', 'columns' => ['modalidade_id'], 'references' => ['modalidade', 'id'], 'update' => 'noAction', 'delete' => 'noAction', 'length' => []],
'fk_coordenador_professor1' => ['type' => 'foreign', 'columns' => ['professor_id'], 'references' => ['professor', 'id'], 'update' => 'noAction', 'delete' => 'noAction', 'length' => []],
],
'_options' => [
'engine' => 'InnoDB',
'collation' => 'utf8_general_ci'
],
];
// @codingStandardsIgnoreEnd
/**
* Records
*
* @var array
*/
public $records = [
[
'professor_id' => 1,
'modalidade_id' => 1
],
];
}
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
/**
* Aula Entity.
*/
class Aula extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = [
'status' => true,
'aula' => true,
'disciplina_id' => true,
'calendario_id' => true,
'disciplina' => true,
'calendario' => true,
];
protected function _getGradeCurricular(){
$calendario = TableRegistry::get('Calendario');
$grade = TableRegistry::get('GradeCurricular');
$cal = $calendario->get($this->calendario_id);
$gradeCurricular = $grade->find()
->contain(['Professor'=>['Usuario']])
->where(['turma_id'=>$cal->turma_id, 'disciplina_id'=>$this->disciplina_id])
->first();
return $gradeCurricular;
}
}
<file_sep><script type="text/javascript">
$(function(){
$('#cursoId').change(function(){
$.getJSON('../turma/getTurmas/'+$(this).val(), function( turmas ) {
var opcoes = '<option value>Escolha uma turma</option>';
$.each( turmas, function( i, item ) {
opcoes += '<option value='+item.id+'>'+item.nome+'</option>';
});
$('#turmasId').html(opcoes).show();
//$('#turmasId').html();
});
});
});
</script>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Turmas</div>
<div class="panel-body">
<?=$this->Form->create($gradeCurricular)?>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('curso', ['class'=>'form-control', 'options'=>$cursos, 'empty'=>'Escolha um curso', 'id'=>'cursoId']);?>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<?=$this->Form->input('turma', ['class'=>'form-control', 'options'=>[], 'empty'=>'Escolha uma turma', 'id'=>'turmasId']);?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<?= $this->Form->select('disciplina_id', $disciplinas, ['multiple' => true, 'class'=>'form-control', 'style'=>'height:300px;']);?>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-plus"><i> Grade</i></span>
</button>
</div>
</div>
</div>
<?=$this->Form->end()?>
</div>
</div>
</div><file_sep><div class="panel panel-default">
<div class="panel-heading">Relatorio de faltas da turma: <?=$turma->nome?></div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Data</th>
<th>Aula</th>
<th>Disciplina</th>
<th>Professor</th>
</tr>
</thead>
<tbody>
<?php foreach ($faltas as $falta): ?>
<tr>
<td><?=$falta->calendario->data?></td>
<td><?=$falta->aula?></td>
<td><?=$falta->disciplina->nome?></td>
<td><?=$falta->gradeCurricular->professor->usuario->nome?></td>
</tr>
<?php endforeach ?>
<tr></tr>
</tbody>
</table><file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\Professor;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Professor Model
*
* @property \Cake\ORM\Association\BelongsTo $Usuario
* @property \Cake\ORM\Association\BelongsTo $Eixo
* @property \Cake\ORM\Association\HasMany $GradeCurricular
*/
class ProfessorTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('professor');
$this->displayField('nome');
$this->primaryKey('id');
$this->belongsTo('Usuario', [
'foreignKey' => 'usuario_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Eixo', [
'foreignKey' => 'eixo_id',
'joinType' => 'INNER'
]);
$this->hasOne('Coordenador');
$this->hasMany('GradeCurricular', [
'foreignKey' => 'professor_id'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->requirePresence('qualificacao', 'create')
->notEmpty('qualificacao');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['usuario_id'], 'Usuario'));
$rules->add($rules->existsIn(['eixo_id'], 'Eixo'));
return $rules;
}
public function getList()
{
$professores = $this->find('all', ['contain'=>'Usuario']);
$retorno = array();
foreach ($professores as $professor) {
$retorno[$professor->id] = $professor->usuario->nome;
}
return $retorno;
}
}
<file_sep><div class="login col-md-4">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create('usuario', ['class'=>"form-signin"]) ?>
<div class="form-group">
<?=$this->Form->input('email', ['div'=>false, 'class'=>'form-control']);?>
</div>
<div class="form-group">
<?=$this->Form->input('senha', ['div'=>false, 'class'=>'form-control', 'type'=>'password']);?>
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block" type="submit">Entrar</button>
</div>
<?= $this->Form->end() ?>
</div>
</div>
</div>
</div><file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Nome: <?= h($administrador->usuario->nome)?> </h3>
<h3>Cargo: <?=$administrador->cargo?> </h3>
<h3>Setor: <?=$administrador->setor?> </h3>
</div>
<div class="panel-footer">
<?=$this->Html->link('Editar', ['action'=>'edit', $administrador->id])?> |
<?=$this->Html->link('Nova senha', ['controller'=>'usuario', 'action'=>'novaSenha', $administrador->usuario->id])?>
</div>
</div>
</div>
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* Turma Controller
*
* @property \App\Model\Table\TurmaTable $Turma
*/
class TurmaController extends AppController
{
/**
* Index method
*
* @return void
*/
public function beforeFilter(Event $event){
parent::beforeFilter($event);
$anos = range(date('Y')-2, date('Y')+1);
foreach ($anos as $key => $ano) {
unset($anos[$key]);
$anos[$ano] = $ano;
}
$this->set('anos', $anos);
}
public function index()
{
$this->paginate = [
'contain' => ['Curso', 'Sala'],
];
$this->set('turma', $this->paginate($this->Turma));
$this->set('_serialize', ['turma']);
}
/**
* View method
*
* @param string|null $id Turma id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$turma = $this->Turma->get($id, [
'contain' => ['Curso', 'Sala']
]);
$this->set('turma', $turma);
$this->set('_serialize', ['turma']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$turma = $this->Turma->newEntity();
if ($this->request->is('post')) {
$turma = $this->Turma->patchEntity($turma, $this->request->data);
$turma->ativo = false;
if ($this->Turma->save($turma)) {
$this->Flash->success(__('The turma has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The turma could not be saved. Please, try again.'));
}
}
$curso = $this->Turma->Curso->find('list', ['limit' => 200]);
$sala = $this->Turma->Sala->find('list', ['limit' => 200]);
$this->set(compact('turma', 'curso', 'sala'));
$this->set('_serialize', ['turma']);
}
/**
* Edit method
*
* @param string|null $id Turma id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$turma = $this->Turma->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$turma = $this->Turma->patchEntity($turma, $this->request->data);
if ($this->Turma->save($turma)) {
$this->Flash->success(__('The turma has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The turma could not be saved. Please, try again.'));
}
}
$curso = $this->Turma->Curso->find('list', ['limit' => 200]);
$sala = $this->Turma->Sala->find('list', ['limit' => 200]);
$this->set(compact('turma', 'curso', 'sala'));
$this->set('_serialize', ['turma']);
}
public function verTurmas($curso_id = null){
$this->paginate = [
'contain' => ['Curso', 'Sala'],
'conditions'=>['ativo'=>true, 'Curso.id'=>$curso_id]
];
$this->set('turma', $this->paginate($this->Turma));
$this->set('_serialize', ['turma']);
}
public function getTurmas($curso_id=null){
$this->layout = 'ajax';
$this->autoRender = FALSE;
echo json_encode($this->Turma->findByCursoIdAndAtivo($curso_id, false)->toArray());
}
public function ativar($id = null, $ativo = true){
$this->request->allowMethod(['post', 'ativar']);
$turma = $this->Turma->get($id);
$turma->ativo = $ativo;
if ($this->Turma->save($turma)) {
$this->Flash->success(__('Turma atualizada com sucesso!'));
return $this->redirect(['action' => 'index']);
}
}
}
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Event\Event;
/**
* GradeCurricular Controller
*
* @property \App\Model\Table\GradeCurricularTable $GradeCurricular
*/
class GradeCurricularController extends AppController
{
public function index()
{
$this->loadModel('Turma');
$this->paginate = [
'contain'=>['Curso']
];
$this->set('turma', $this->paginate($this->Turma));
$this->set('_serialize', ['curso']);
}
/**
* View method
*
* @param string|null $id Grade Curricular id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$curso = $this->GradeCurricular->Disciplina->find('list', ['limit' => 200]);
$gradeCurricular = $this->GradeCurricular->get($id, [
'contain' => ['Disciplina', 'Professor', 'Turma']
]);
$this->set('gradeCurricular', $gradeCurricular);
$this->set('_serialize', ['gradeCurricular']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$this->loadModel('Curso');
$this->loadModel('Disciplina');
$professor = $this->Professor->find('all', [
'contain' => ['Usuario'],
'order'=>['Usuario.nome']
])->first();
$gradeCurricular = $this->GradeCurricular->newEntity();
if ($this->request->is('post')) {
foreach ($this->request->data['disciplina_id'] as $disciplina) {
$gradeCurricular = $this->GradeCurricular->newEntity();
$gradeCurricular->cargaHoraria = 0;
$gradeCurricular->obrigatorio = false;
$gradeCurricular->professor_id = $professor->id;
$gradeCurricular->turma_id = $this->request->data['turma'];
$gradeCurricular->disciplina_id = $disciplina;
$this->GradeCurricular->save($gradeCurricular);
}
$this->redirect(['action'=>'editarGrade', $gradeCurricular->turma_id]);
}
$cursos = $this->Curso->find('list');
$disciplinas = $this->Disciplina->find('list');
$this->set(compact('cursos', 'disciplinas', 'gradeCurricular'));
}
public function save(){
$this->layout = 'ajax';
$grade = $this->GradeCurricular->newEntity();
$grade = $this->GradeCurricular->patchEntity($grade, $this->request->data);
$grade->obrigatorio = isset($this->request->data['obrigatorio']) ? 1 : 0;
if ($this->GradeCurricular->save($grade)) {
echo true;
} else {
echo false;
}
}
public function edit(){
$this->layout = 'ajax';
if($this->request->is('post')){
$grade = $this->GradeCurricular->get($this->request->data['id'], [
'contain' => []
]);
$grade = $this->GradeCurricular->patchEntity($grade, $this->request->data);
$grade->obrigatorio = isset($this->request->data['obrigatorio']) ? 1 : 0;
if ($this->GradeCurricular->save($grade)) {
echo true;
} else {
echo false;
}
}
}
public function verGrade($turma_id = null){
$turma = $this->GradeCurricular->Turma->get($turma_id);
$this->paginate = [
'contain' => ['Disciplina', 'Professor', 'Turma'],
'conditions'=>['Turma.id'=>$turma_id]
];
$this->set('gradeCurricular', $this->paginate($this->GradeCurricular));
$this->set(compact('turma'));
$this->set('_serialize', ['gradeCurricular']);
}
public function editarGrade($turma_id = null){
$this->loadModel('Professor');
if ($this->request->is(['patch', 'post', 'put'])) {
}
$grade = $this->GradeCurricular->find('all', [
'conditions'=>[
'turma_id'=>$turma_id,
],
'contain'=>['Disciplina', 'Professor', 'Turma']
]);
$disciplinas = $this->GradeCurricular->Disciplina->find('list');
$turma = $this->GradeCurricular->Turma->get($turma_id);
$professores = $this->Professor->getList();
$this->set(compact('grade', 'disciplinas', 'professores', 'turma'));
$this->set('_serialize', ['grade']);
}
public function getGrade($id=null){
$this->layout = 'ajax';
$this->autoRender = FALSE;
echo json_encode($this->GradeCurricular->get($id)->toArray());
}
public function getGradeTurma($turma_id=null){
$this->layout = 'ajax';
$this->autoRender = FALSE;
$grades = $this->GradeCurricular->find()->contain([
'Disciplina',
'Professor'
])->where([
'turma_id'=>$turma_id
])->toArray();
$gradeDis = array();
//pr($grades);
foreach ($grades as $key => $grade) {
$gradeDis[$key]['id'] = $grade->id;
$gradeDis[$key]['disciplina'] = $grade->disciplina->nome;
$gradeDis[$key]['professor'] = $grade->professor->usuarios->nome;
$gradeDis[$key]['obrigatorio'] = $grade->obrigatorio;
$gradeDis[$key]['carga_horaria'] = $grade->carga_horaria;
//pr();
}
echo json_encode($gradeDis);
}
public function deleteGrade($id=null){
$this->layout = 'ajax';
$this->autoRender = FALSE;
$grade = $this->GradeCurricular->get($id);
if ($this->GradeCurricular->delete($grade)) {
echo true;
}else{
echo false;
}
}
public function turmaSemGrade(){
$turmasComGrade = $this->GradeCurricular->find('list', [
'keyField'=>'turma.id',
'valueField'=>'turma.nome',
'contain'=>['Turma'],
'conditions'=>[
'ativo'=>true,
]
])->toArray();
$turma = $this->GradeCurricular->Turma->find()
->contain(['Curso'])
->where([
'Turma.ativo'=>true,
'Turma.id NOT IN'=>array_keys($turmasComGrade)
]);
$this->set(compact('turma'));
}
}<file_sep><table class="table table-bordered" align="center">
<caption><?=$turma->descricao?></caption>
<thead>
<tr>
<th>Aula</th>
<th>Seg</th>
<th>Ter</th>
<th>Qua</th>
<th>Qui</th>
<th>Sex</th>
<th>Sab</th>
</tr>
</thead>
<tbody>
<?=$this->Form->create($horario)?>
<?php for($i=0;$turma->turno!='I' ? $i<6 : $i<10;$i++):?>
<tr>
<td><?=$i+1?></td>
<?php
for($j=0;$turma->turno!='I' ? $j<6 : $j<10;$j++){
if(@$lista[$i+1][$j+1]){
echo "<td>".$this->Form->select('disciplina_id.'.$j.'.'.$i, $disciplinas, ['class'=>'form-control', 'value'=>$lista[$i+1][$j+1]])."</td>";
}else{
echo "<td>".$this->Form->select('disciplina_id.'.$j.'.'.$i, $disciplinas, ['class'=>'form-control', 'value'=>0])."</td>";
}
}
?>
</tr>
<?php endfor;?>
</tbody>
<tfoot>
<tr>
<td colspan="7" align="right">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-edit"> Save</span>
</button>
</td>
</tr>
</tfoot>
<?=$this->Form->end()?>
</table><file_sep><?php
namespace App\Model\Table;
use App\Model\Entity\AulaReposicaoAntecipacao;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\I18n\Time;
/**
* AulaReposicaoAntecipacao Model
*
* @property \Cake\ORM\Association\BelongsTo $ReposicaoAntecipacao
* @property \Cake\ORM\Association\BelongsTo $Aula
*/
class AulaReposicaoAntecipacaoTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('aula_reposicao_antecipacao');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsTo('ReposicaoAntecipacao', [
'foreignKey' => 'reposicao_antecipacao_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Aula', [
'foreignKey' => 'aula_id',
'joinType' => 'INNER'
]);
}
public function validationDefault(Validator $validator)
{
$validator->add('status', 'custom', [
'rule' => [$this, 'validaConfronto'],
'message'=>'Confronto de aulas!'
]);
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['reposicao_antecipacao_id'], 'ReposicaoAntecipacao'));
$rules->add($rules->existsIn(['aula_id'], 'Aula'));
return $rules;
}
public function validaConfronto($status, $context){
$repo = TableRegistry::get('ReposicaoAntecipacao');
$aula = TableRegistry::get('Aula');
$reposicao = $repo->get($context['data']['reposicao_antecipacao_id']);
$aula = $aula->find()
->where(['Aula.id'=>$context['data']['aula_id']])
->contain(['Calendario'])
->first();
// echo $aula->calendario->turma_id;
$now = Time::parse($reposicao->dataReposicao);
$data = $now->i18nFormat('YYYY-MM-dd');
$connection = ConnectionManager::get('default');
$sql = "SELECT count(*) as qt
FROM reposicao_antecipacao as ra inner join
aula_reposicao_antecipacao as ara on ra.id = ara.reposicao_antecipacao_id inner join
aula as a on ara.aula_id = a.id inner join
calendario as c on a.calendario_id = c.id
WHERE ra.dataReposicao = '".$data."' and
c.turma_id = ".$aula->calendario->turma_id." and ara.aula_repor = ".$context['data']['aula_repor'];
$confronto = $connection->execute($sql)->fetch('assoc');
return $confronto['qt']<=0;
}
}<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
/**
* GradeCurricular Entity.
*/
class GradeCurricular extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* @var array
*/
protected $_accessible = ['*'=>true];
protected function _getMinistrada(){
$connection = ConnectionManager::get('default');
$sql = "SELECT count(*) as qt, m.tempoAula
FROM grade_curricular as gc inner join
turma as t on t.id = gc.turma_id inner join
curso as cs on t.curso_id = cs.id inner join
modalidade as m on cs.modalidade_id = m.id inner join
calendario as c on t.id = c.turma_id inner join
aula as a on a.calendario_id = c.id and a.disciplina_id = gc.disciplina_id left outer join
aula_reposicao_antecipacao as ara on a.id = ara.aula_id
where (a.status = 'M' or ara.status = 'M') and (gc.id = ".$this->id.")
group by tempoAula";
return $connection->execute($sql)->fetch('assoc');
}
}
<file_sep><script type="text/javascript">
function escondeBody(turma){
if($('#visivel'+turma).val()=='1'){
$('#id'+turma).fadeOut('slow');
$('#headReposicao'+turma).fadeOut('slow');
$('#bodyReposicao'+turma).fadeOut('slow');
$('#visivel'+turma).val('0');
}else{
$('#id'+turma).fadeIn('slow');
$('#headReposicao'+turma).fadeIn('slow');
$('#bodyReposicao'+turma).fadeIn('slow');
$('#visivel'+turma).val('1');
}
}
function filtroController($scope) {
console.log($scope.data);
}
</script>
<div class="panel panel-default" ng-app='Filtro-App' >
<div class="panel-heading" ng-controller="filtroController">Data - <?=$dataBase?></div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
<input type="date" name="data" ng-model="data" placeholder="yyyy-MM-dd"
max="<?=date('Y-m-d')?>" class="form-control">
</div>
<div class="col-md-1">
<?=$this->Html->link('<span class="glyphicon glyphicon-search"> Filtrar</span>', ['action'=>'index/{{data}}'], ['class'=>'btn btn-default', 'escape'=>false]);?>
</a>
</div>
</div>
</div>
</div>
<?php foreach ($turmas as $key=>$turma): ?>
<div class="panel panel-default">
<input type="hidden" id="visivel<?=$key?>" value="1">
<div class="panel-heading" onclick="escondeBody(<?=$key?>)">Turma: <?=$turma->nome?></div>
<div class="panel-body" id="id<?=$key?>">
<table class="table">
<thead>
<tr>
<th>Horario</th>
<th>Disciplina</th>
<th>Professor</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php
$aulasDia = $turma->getAulasDia($dataBase);
?>
<?php foreach (@$aulasDia as $aula): ?>
<?php
$classe = '';
$exibirBtn = true;
if($aula['status']!='P'){
if($aula['status']=='A'){
if($aula['ministrou_antecipacao']=='M'){
$classe = "success";
$exibirBtn = false;
}else{
$classe = "danger";
}
}else{
$classe = $aula['status']=='F' ? 'danger' : 'success';
}
}
?>
<tr class="<?=$classe?>">
<td><?=$aula['aula']?></td>
<td><?=$aula['disciplina']?></td>
<td><?=$aula['professor']?></td>
<td>
<?php
if($exibirBtn){
echo $this->Form->postLink(__('Faltou'),['action' => 'confirmar', $aula['id'], $dataBase, true], ['confirm'=>'Deseja aplicar essa falta?', 'class'=>'btn btn-danger']);
echo $this->Form->postLink(__('Ministrou'),['action' => 'confirmar', $aula['id'], $dataBase], ['confirm'=>'Confirmar presença?', 'class'=>'btn btn-success']);
}
?>
</td>
</tr>
<?php endforeach ?>
<tr>
</tr>
</tbody>
</table>
</div>
<div class="panel-heading" id="headReposicao<?=$key?>">Reposições/Antecipações marcadas</div>
<div class="panel-body" id="bodyReposicao<?=$key?>">
<table class="table">
<?php $reposicoes = $turma->getReposicoes($dataBase);?>
<?php foreach ($reposicoes as $reposicao): ?>
<?php
$classe = '';
if($reposicao['status']!='C')
$classe = $reposicao['status']=='M' ? 'success' : 'danger';
?>
<tr class="<?=$classe?>">
<td><?=$reposicao['aula_repor']?></td>
<td><?=$reposicao['disciplina']?></td>
<td><?=$reposicao['professor']?></td>
<td>
<?php
echo $this->Form->postLink(__('Faltou'),['action' => 'confirmarReposicao', $reposicao['id'], true], ['confirm'=>'Deseja aplicar essa falta?', 'class'=>'btn btn-danger']);
?>
<?php
echo $this->Form->postLink(__('Ministrou'),['action' => 'confirmarReposicao', $reposicao['id']], ['confirm'=>'Deseja aplicar essa falta?', 'class'=>'btn btn-success']);
?>
</td>
</tr>
<?php endforeach ?>
</table>
</div>
</div>
<?php endforeach ?><file_sep><div class="panel panel-primary">
<div class="panel-heading">Detalhes</div>
<div class="panel-body">
<h3>Descrição: <?=$disciplina->nome?> </h3>
</div>
<div class="panel-footer">
<?=$this->Html->link('Editar', ['action'=>'edit', $disciplina->id])?>
</div>
</div>
<file_sep><table class="table table-striped">
<thead>
<tr>
<th>Turma</th>
<th>Disciplina</th>
<th>Aula</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<?php foreach ($faltas as $falta): ?>
<tr>
<td><?= $falta['turma']?></td>
<td><?= $falta['disciplina']?></td>
<td><?= $falta['aula']?></td>
<td><?= $falta['data']?></td>
</tr>
<?php endforeach ?>
</tbody>
</table><file_sep><div class="panel panel-default">
<div class="panel-heading">Listagem de reposições</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>numero</th>
<th>data</th>
<th>data reposição</th>
<th>status</th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($reposicaoAntecipacao as $reposicaoAntecipacao): ?>
<tr>
<td><?=$reposicaoAntecipacao['id']?></td>
<td><?=$reposicaoAntecipacao['created']?></td>
<td><?=$reposicaoAntecipacao['dataReposicao']?></td>
<td><?=$reposicaoAntecipacao['status']?></td>
<td><?=$this->Html->link('<span class="glyphicon glyphicon-search"></span>', ['controller'=>'AulaReposicaoAntecipacao', 'action'=>'view', $reposicaoAntecipacao['id']], ['escape'=>false]);?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
<file_sep><?php
namespace App\Controller\Coordenador;
use App\Controller\AppController;
/**
* Usuario Controller
*
* @property \App\Model\Table\UsuarioTable $Usuario
*/
class UsuarioController extends AppController
{
public function novaSenha($id = null){
$usuario = $this->Usuario->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$usuario = $this->Usuario->patchEntity($usuario, $this->request->data);
if ($this->Usuario->save($usuario)) {
$this->Flash->success(__('The usuario has been saved.'));
return $this->redirect(['controller'=>'professor', 'action' => 'index']);
} else {
$this->Flash->error(__('The usuario could not be saved. Please, try again.'));
}
}
$this->set(compact('usuario'));
$this->set('_serialize', ['usuario']);
}
}
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
/**
* Aula Controller
*
* @property \App\Model\Table\AulaTable $Aula
*/
class AulaController extends AppController{
public function index($dataBase = null){
$this->loadModel('Turma');
$turmas = $this->Turma->find()
->where(['Turma.ativo'=>true]);
$dataBase = is_null($dataBase) ? date('Y-m-d') : $dataBase;
$this->set(compact('turmas', 'dataBase'));
}
public function confirmar($horario_id, $dataBase, $faltou = false){
$this->loadModel('Horario');
$this->loadModel('Calendario');
$horario = $this->Horario->get($horario_id, [
'contain'=>['GradeCurricular'=>['Disciplina', 'Turma']]
]);
$calendario = $this->Calendario->find()
->where([
'data'=>$dataBase,
'turma_id'=>$horario->grade_curricular->turma_id
])
->first();
$aula = $this->Aula->find()
->where([
'aula'=>$horario->aula,
'disciplina_id'=>$horario->grade_curricular->disciplina_id,
'calendario_id'=>$calendario->id
])
->first();
if(!$aula){
$aula = $this->Aula->newEntity();
$aula->set([
'status' => $faltou ? "F" : "M",
'aula'=>$horario->aula,
'disciplina_id'=>$horario->grade_curricular->disciplina_id,
'calendario_id'=>$calendario->id
]);
}else{
$aula->status = $faltou ? "F" : "M";
}
if($this->Aula->save($aula)){
$this->Flash->success(__('Aula registrada com sucesso.'));
}else{
$this->Flash->error(__('Aula nao registrada. Please, try again.'));
}
return $this->redirect(['action'=>'index', $dataBase]);
}
public function faltaTurma(){
$turma = $this->Aula->find()
->select(['Turma.id', 'Turma.nome', 'qt'=>'count(*)'])
->group(['Turma.id', 'Turma.nome'])
->contain(['Calendario'=>['Turma']])
->where(['Aula.status'=>'F'])
->autoFields(true);
$this->set(compact('turma'));
}
public function viewFaltas($idTurma){
$this->loadModel('Turma');
$faltas = $this->Aula->find()
->contain(['Disciplina','Calendario'=>['Turma']])
->where(['Aula.status'=>'F', 'Turma.id'=>$idTurma])
->order(['Calendario.data', 'Aula.aula']);
$turma = $this->Turma->get($idTurma);
$this->set(compact(['faltas', 'turma']));
}
public function confirmarReposicao($reposicaoId, $faltou = false){
$this->loadModel('AulaReposicaoAntecipacao');
$aulaReposicao = $this->AulaReposicaoAntecipacao->get($reposicaoId);
$aulaReposicao->status = $faltou==true ? 'F' : 'M';
if($this->AulaReposicaoAntecipacao->save($aulaReposicao)){
$this->Flash->success(__('Aula registrada com sucesso.'));
}else{
$this->Flash->error(__('Aula nao registrada. Please, try again.'));
}
return $this->redirect(['action'=>'index']);
}
}
|
6afff68f870986fac76f6b1eb7b8aec821358441
|
[
"PHP"
] | 78
|
PHP
|
woshington/tcc
|
7037838c6b55d010961c7b92075fdd8525523575
|
a94815572c5f2ddb986a511ae4cab6550ef945cd
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PacientesSys.AcessoDados;
using PacientesSys.AcessoDados.Interface;
namespace PacientesSys.Dominio.Repositorios
{
public class PacienteRepositorio : Contexto, IRepositorio<Paciente>
{
public Paciente BuscarId(int id)
{
throw new NotImplementedException();
}
public string inserir(Paciente entidade)
{
try
{
LimparParametro();
AdicionarParametros("@nome", entidade.Nome);
AdicionarParametros("@CPF", entidade.CPF);
AdicionarParametros("@Datas", entidade.Datas);
AdicionarParametros("@Pescricao", entidade.Pescricao);
string retorno = ExecutarCommando(System.Data.CommandType.StoredProcedure, "uspClienteIn").ToString();
return retorno;
}
catch (Exception ex)
{
return ex.Message;
}
}
private void AdicionarParametros(string v)
{
throw new NotImplementedException();
}
public string Alterar(Paciente entidade)
{
return null;
}
public string Deletar(Paciente entidade)
{
throw new NotImplementedException();
}
public IEnumerable<Paciente> ListarTodos()
{
throw new NotImplementedException();
}
public string Salvar(Paciente entidade)
{
throw new NotImplementedException();
}
string IRepositorio<Paciente>.Salvar(Paciente entidade)
{
throw new NotImplementedException();
}
string IRepositorio<Paciente>.Deletar(Paciente entidade)
{
throw new NotImplementedException();
}
Paciente IRepositorio<Paciente>.BuscarId(int id)
{
throw new NotImplementedException();
}
public IEnumerable<Paciente> ListarDatas(string datas)
{
try
{
LimparParametro();
AdicionarParametros("@Datas", datas);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
IEnumerable<Paciente> IRepositorio<Paciente>.Listardatas(string datas)
{
throw new NotImplementedException();
}
}
}
<file_sep>namespace PacientesSys
{
public class Dominio
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PacientesSys.AcessoDados.Interface
{
public interface IRepositorio<T> where T: class
{
string Salvar(T entidade);
string Deletar(T entidade);
T BuscarId(int id);
IEnumerable<T> Listardatas(string datas);
}
}
<file_sep>create procedure aspPacientes2
@Nome as varchar(100),
@CPF as varchar(11),
@Datas as varchar(8),
@Pescricao as varchar(10)
as
begin
insert into tblPacientes
(Nome, CPF, Datas, Pescricao)
values
(@Nome, @CPF, @Datas, @Pescricao)
select @@IDENTITY as retorno
end
|
61a28e3e184cb62541231945830de2bb87b6044c
|
[
"C#",
"SQL"
] | 4
|
C#
|
maiconflx/Ness
|
5c76e25182e17ac639f4350141b72a39e3e7d306
|
5287eef1acf9563f59976a8ab1b42df9b11faede
|
refs/heads/master
|
<file_sep>#' turnToPost
#'
#' Turn the 88 columns returned by rtweet into a posts dataset
#'
#' @importFrom dplyr select
#' @importFrom dplyr mutate
#' @importFrom lubridate as_datetime
#' @importFrom rlang .data
#' @importFrom stringr str_detect
#' @importFrom bit64 as.integer64
#' @importFrom rtweet users_data
#' @import rex
#' @import tibble
#' @param df The target table
#' @param complete_user Run a query to retrieve missing user data. Default set to FALSE
#' @return A posts dataset
#' @export
turnToPost <- function(
df,
complete_user = FALSE
) {
if (complete_user == TRUE) {
users <- users_data(tweets = df) %>%
turnToAccount()
} else {
users <-
tibble(
user_id = NA,
screen_name = "NaN",
followers_count = NA
)
}
# processing of tweets globally
df2 <-
df %>%
mutate(
user_id = users$user_id,
screen_name = users$screen_name,
followers_count = users$followers_count,
status_id = as.integer64(.data$id_str),
text = .data$full_text,
engagement = as.numeric(.data$retweet_count) + as.numeric(.data$favorite_count),
stamp = as.integer(.data$created_at),
url_post = paste0("https://twitter.com/", .data$screen_name, "/status/", .data$status_id),
characters = nchar(.data$text),
is_retweet = str_detect(.data$full_text, rex(start, "RT", space, "@")),
reply_to_status_id = as.integer64(.data$in_reply_to_status_id_str),
reply_to_user_id = as.integer64(.data$in_reply_to_user_id_str),
reply_to_screen_name = as.integer64(.data$in_reply_to_screen_name),
is_quote = !is.na(.data$quoted_status_id_str),
quoted_status_id = as.integer64(.data$quoted_status_id_str),
hashtags = NA,
quoted_user_id = as.integer64(NA),
quoted_screen_name = NA,
quoted_text = NA,
quoted_created_at = as_datetime(NA),
quoted_favorite_count = NA,
quoted_retweet_count = NA,
quoted_source = NA,
quoted_url = NA,
symbols = NA,
mentions_user_id = NA,
mentions_screen_name = NA,
urls_url = NA,
urls_t.co = NA,
urls_expanded_url = NA,
media_url = NA,
media_t.co = NA,
media_expanded_url = NA,
media_type = NA,
ext_media_url = NA,
ext_media_t.co = NA,
ext_media_expanded_url = NA,
ext_media_type = NA,
retweet_url = NA,
retweet_status_id = as.integer64(NA),
retweet_user_id = as.integer64(NA),
retweet_screen_name = NA,
retweet_created_at = as_datetime(NA),
retweet_favorite_count = NA,
retweet_retweet_count = NA,
retweet_engagement = NA,
retweet_source = NA,
)
# processing tweets one by one
suppressWarnings(for (i in 1:nrow(df2)) {
medias <- df[[7]][[i]][["media"]]
if (is.null(medias) == FALSE) {
if (is.na(medias$media_url[1]) == FALSE) {
df2$media_url[i] <- paste(medias$media_url, collapse = ", ")
df2$media_expanded_url[i] <- paste(medias$expanded_url, collapse = ", ")
df2$media_t.co[i] <- paste(medias$url, collapse = ", ")
df2$media_type[i] <- paste(medias$type, collapse = ", ")
}
}
retweets <- df$retweeted_status[i][[1]]
if (is.data.frame(retweets) == TRUE) {
retweet_status_id <- as.integer64(retweets$id_str)
if (is.na(retweet_status_id) == FALSE) {
df2$retweet_status_id[i] <- retweet_status_id
retweet_user_id <- as.integer64(retweets$user$id_str)
df2$retweet_user_id[i] <- retweet_user_id
retweet_screen_name <- retweets$user$screen_name
df2$retweet_screen_name[i] <- retweet_screen_name
retweet_url <- paste0("https://twitter.com/", retweet_screen_name, "/status/", retweet_status_id)
df2$retweet_url[i] <- retweet_url
retweet_favorite_count <- retweets$favorite_count
df2$retweet_favorite_count[i] <- retweet_favorite_count
retweet_retweet_count <- retweets$retweet_count
df2$retweet_retweet_count[i] <- retweet_retweet_count
retweet_engagement <- retweet_favorite_count + retweet_retweet_count
df2$retweet_engagement[i] <- retweet_engagement
retweet_source <- retweets$source
df2$retweet_source[i] <- retweet_source
retweet_created_at <- convert_date(retweets$created_at)
df2$retweet_created_at[i] <- retweet_created_at
}
}
hashtags <- paste(df[[7]][[i]][["hashtags"]]$text, collapse = ", ")
df2$hashtags[i] <- ifelse(hashtags == "NA", NA, hashtags)
symbols <- paste(df[[7]][[i]][["symbols"]]$text, collapse = ", ")
df2$symbols[i] <- ifelse(symbols == "NA", NA, symbols)
user_mentions <- df[[7]][[i]][["user_mentions"]]
mentions_user_id <- paste(user_mentions$id_str, collapse = ", ")
df2$mentions_user_id[i] <- ifelse(mentions_user_id == "NA", NA, mentions_user_id)
mentions_screen_name <- paste(user_mentions$screen_name, collapse = ", ")
df2$mentions_screen_name[i] <- ifelse(mentions_screen_name == "NA", NA, mentions_screen_name)
urls <- df[[7]][[i]][["urls"]]
urls_t.co <- paste(urls$url, collapse = ", ")
df2$urls_t.co[i] <- ifelse(urls_t.co == "NA", NA, urls_t.co)
urls_expanded_url <- paste(urls$expanded_url, collapse = ", ")
df2$urls_expanded_url[i] <- ifelse(urls_expanded_url == "NA", NA, urls_expanded_url)
quoted <- df[[29]][[i]]
if (is.data.frame(quoted) == TRUE) {
if (is.null(quoted$user$id_str) == FALSE) {
quoted_user_id <- as.integer64(quoted$user$id_str)
df2$quoted_user_id[i] <- quoted_user_id
quoted_screen_name <- quoted$user$screen_name
df2$quoted_screen_name[i] <- quoted_screen_name
quoted_text <- quoted$full_text
df2$quoted_text[i] <- quoted_text
quoted_created_at <- suppressWarnings(convert_date(quoted$created_at))
df2$quoted_created_at[i] <- quoted_created_at
quoted_source <- quoted$source
df2$quoted_source[i] <- quoted_source
quoted_url <- ifelse(
is.na(quoted_screen_name) == TRUE,
NA,
paste0("https://twitter.com/", quoted_screen_name, "/status/", df$quoted_status_id[i])
)
df2$quoted_url[i] <- quoted_url
}
}
rm(
medias,
hashtags,
quoted,
quoted_user_id,
quoted_screen_name,
quoted_text,
quoted_created_at,
quoted_created_at_h,
quoted_created_at_m,
quoted_created_at_j,
quoted_created_at_y,
quoted_source,
quoted_url,
symbols,
user_mentions,
mentions_screen_name,
mentions_user_id,
urls,
urls_expanded_url,
urls_t.co,
retweets,
retweet_created_at,
retweet_engagement,
retweet_favorite_count,
retweet_retweet_count,
retweet_screen_name,
retweet_source,
retweet_status_id,
retweet_url,
retweet_user_id
)
})
rm(i)
# column selection
df2 <-
df2 %>%
select(
.data$user_id,
.data$status_id,
.data$created_at,
.data$screen_name,
.data$followers_count,
.data$text,
.data$favorite_count,
.data$retweet_count,
.data$engagement,
.data$hashtags,
.data$lang,
.data$source,
.data$url_post,
.data$is_retweet,
.data$is_quote,
.data$urls_url,
.data$urls_t.co,
.data$urls_expanded_url,
.data$media_url,
.data$media_t.co,
.data$media_expanded_url,
.data$media_type,
.data$ext_media_url,
.data$ext_media_t.co,
.data$ext_media_expanded_url,
.data$ext_media_type,
.data$retweet_url,
.data$retweet_status_id,
.data$retweet_user_id,
.data$retweet_screen_name,
.data$retweet_created_at,
.data$retweet_favorite_count,
.data$retweet_retweet_count,
.data$retweet_engagement,
.data$retweet_source,
.data$quoted_url,
.data$quoted_status_id,
.data$quoted_user_id,
.data$quoted_screen_name,
.data$quoted_created_at,
.data$quoted_text,
.data$quoted_favorite_count,
.data$quoted_retweet_count,
.data$quoted_source,
.data$reply_to_status_id,
.data$reply_to_user_id,
.data$reply_to_screen_name,
.data$mentions_user_id,
.data$mentions_screen_name,
.data$stamp,
.data$display_text_width,
.data$characters,
.data$symbols
) %>%
suppressMessages(flatlist())
df2
}
<file_sep>#' turnToAccount
#'
#' Turn the columns returned by rtweet into a user account dataset
#'
#' @importFrom dplyr select
#' @importFrom dplyr mutate
#' @importFrom rlang .data
#' @importFrom bit64 as.integer64
#' @importFrom stringr str_detect
#' @importFrom as_datetime
#' @param df The target table
#' @return A user dataset
#' @export
turnToAccount <- function(df) {
df %>%
mutate(
url_account = paste0("https://twitter.com/", .data$screen_name),
user_id = as.integer64(.data$id_str),
account_created_at = .data$created_at,
account_created_at = ifelse(str_detect(account_created_at, "[[:alpha:]]+") == TRUE, convert_date(account_created_at), account_created_at),
account_created_at = as_datetime(account_created_at),
profile_image_url = .data$profile_image_url_https,
profile_url = .data$url,
profile_expanded_url = NA,
account_lang = NA,
profile_background_url = NA,
) %>%
select(
.data$user_id,
.data$screen_name,
.data$followers_count,
.data$friends_count,
.data$listed_count,
.data$statuses_count,
.data$favourites_count,
.data$description,
.data$url,
.data$url_account,
.data$protected,
.data$name,
.data$location,
.data$account_created_at,
.data$verified,
.data$profile_url,
.data$profile_expanded_url,
.data$account_lang,
.data$profile_banner_url,
.data$profile_background_url,
.data$profile_image_url
)
}
<file_sep># Ajouts : flatlist, povertext, convert_date
#' flatlist
#'
#' @importFrom dplyr select
#' @importFrom dplyr mutate
#' @param df Your data frame
#' @return allows you to manage the columns of an array in list format, transforming them into character columns.
flatlist <- function(df) {
i <- as.numeric(length(df))
while (i != 0) {
x <- df %>% select(i)
stock <- names(x)
names(x) <- "temp_name"
classe <- as.character(class(x$temp_name))
if (any(classe == "list")) x <- x %>% mutate(temp_name = as.character(.data$temp_name))
names(x) <- stock
if (exists("newtab") == TRUE) newtab <- cbind(x, newtab)
if (exists("newtab") == FALSE) newtab <- x
i <- i - 1
}
newtab
}
#' povertext
#'
#' Deplete the text value
#' @importFrom stringr str_to_lower
#' @importFrom stringr str_replace_all
#' @param val Your data frame
#' @return Return a text, without any accent or links
povertext <- function(val) {
val <- str_to_lower(val)
val <- str_remove_all(val, "http(?:s)?://[^[:space:]]*") # Links are deleted
val <- str_replace_all(val, "\u00E0", "a")
val <- str_replace_all(val, "\u00E1", "a")
val <- str_replace_all(val, "\u00E2", "a")
val <- str_replace_all(val, "\u00E3", "a")
val <- str_replace_all(val, "\u00E4", "a")
val <- str_replace_all(val, "\u00E5", "a")
val <- str_replace_all(val, "\u00E9", "e")
val <- str_replace_all(val, "\u00E8", "e")
val <- str_replace_all(val, "\u00EA", "e")
val <- str_replace_all(val, "\u00EB", "e")
val <- str_replace_all(val, "\u00EC", "i")
val <- str_replace_all(val, "\u00ED", "i")
val <- str_replace_all(val, "\u00EE", "i")
val <- str_replace_all(val, "\u00EF", "i")
val <- str_replace_all(val, "\u00F2", "o")
val <- str_replace_all(val, "\u00F3", "o")
val <- str_replace_all(val, "\u00F4", "o")
val <- str_replace_all(val, "\u00F5", "o")
val <- str_replace_all(val, "\u00F6", "o")
val <- str_replace_all(val, "\u00F9", "u")
val <- str_replace_all(val, "\u00FA", "u")
val <- str_replace_all(val, "\u00FB", "u")
val <- str_replace_all(val, "\u00FC", "u")
val <- str_replace_all(val, "\u00FF", "y")
val <- str_replace_all(val, "\u00FD", "y")
val <- str_replace_all(val, "\u00E7", "c")
val <- str_replace_all(val, "\u00E6", "ae")
val <- str_replace_all(val, "\u00F1", "n")
val
}
#' convert_date
#'
#' Convert messy dates as they come from the Twitter API in text format
#' @importFrom stringr str_extract
#' @importFrom stringr str_remove_all
#' @importFrom dplyr recode
#' @importFrom lubridate as_datetime
#' @import rex
#' @param created_at the date string to convert
#' @return Return the date in a datetime format
convert_date <-
function(created_at) {
quoted_created_at_h <- str_extract(created_at, rex(numbers, ":", numbers, ":", numbers))
quoted_created_at_y <- str_extract(created_at, rex(number, number, number, number, end))
quoted_created_at_j <- str_extract(created_at, rex(space, numbers, numbers, space))
quoted_created_at_j <- str_remove_all(quoted_created_at_j, rex(spaces))
quoted_created_at_m <- str_extract(created_at, rex(space, letters, space))
quoted_created_at_m <- str_remove_all(quoted_created_at_m, rex(spaces))
quoted_created_at_m <- recode(
quoted_created_at_m,
"Jan" = "01",
"Feb" = "02",
"Mar" = "03",
"Apr" = "04",
"May" = "05",
"Jun" = "06",
"Jul" = "07",
"Aug" = "08",
"Sep" = "09",
"Oct" = "10",
"Nov" = "11",
"Dec" = "12"
)
as_datetime(paste0(quoted_created_at_y, "-", quoted_created_at_m, "-", quoted_created_at_j, " ", quoted_created_at_h))
}
|
d89358d3185c59d8dd5a98470cc0c0c6fc18ef41
|
[
"R"
] | 3
|
R
|
edouardschuppert/rtweetComp
|
6cbb1c5874b9f8131e84d2b0683a277b6566c058
|
c9b8e04a630b6fd8998ff37d66395bc9703ad8f7
|
refs/heads/master
|
<repo_name>Sterlingclark/asgn10-names<file_sep>/functions/utility-functions.php
<?php
// Dump and die function displays the contents of the variable passed
// in an easy-to-read format then exits the program
function dd($value) {
echo "<pre>";
var_dump($value);
echo "</pre>";
exit();
}
?><file_sep>/index.php
<?php
include 'fucntions/utility-functions.php';
$fileName = 'names-short-list.txt';
$lineNumber = 0;
// load up the array
$FH = fopen("$fileName", "r");
$nextName = fgets($FH);
while(!feof($FH)) {
if($lineNumber % 2 == 0) {
$fullName[] = trim(substr($nextName, 0, strpos($nextName, " --")));
}
$lineNumber++;
$nextName = fgets($FH);
}
// get all first names
foreach($fullNames as $fullName) {
$startHere = strpos($fullName, ",") + 1;
$firstNames[] = trim(substr($fullname, $startHere));
}
// get all last names
foreach($fullNames as $fullName) {
$stopHere = strpos($fullName, ",");
$lastNames[] = substr($fullName, 0, $stopHere);
}
// get valid names
for($i = 0; $i < sizeof($fullNames); $i++) {
// jam the first and last name together without a comma, then rest for alpha-only characters
if(ctype_alpha($lastNames[$i].$firstNames[$i])) {
$validFirstNames[$i] = $firstNames[$i];
$validLastNames[$i] = $lastNames[$i];
$validFullNames[$i] = $validLastNames[$i] . "," . $validFirstNames[$i];
}
}
// Display results
echo '<h1>Names - Results</h1>';
echo "<p>There are " . sizeof($fullNames) . " total names</p>";
echo '<ul style="list-style-type:none">';
foreach($fullNames as $fullName) {
echo "<li>$fullName</li>";
}
echo "</ul>";
echo '<h2>All Valid Names</h2>';
echo "<p>There are " . sizeof($validFullNames) . " valid names</p>";
echo '<ul style="list-style-type:none">';
foreach($validFullNames as $validFullname) {
echo "<li>$validFullname</li>";
}
echo "</ul>";
echo '<h2>Unique Names</h2>';
$uniqueValidNames = (array_unique($validFullNames));
echo ("<p>There are " . sizeof($uniqueValidNames) . "Unique names</p>");
echo '<ul style="list-style-type:none">';
foreach($uniqueValidNames as $uniqueValidNames) {
echo "<li>$uniqueValidNames</li>";
}
?>
|
8175459b3c842b8586c84abe13a7f592161a3d90
|
[
"PHP"
] | 2
|
PHP
|
Sterlingclark/asgn10-names
|
0c1a266ffae76e7c7a437db34a9556680c5a07f6
|
0fcc587e4209df7327ba0298fa44c5db6cd3f326
|
refs/heads/master
|
<file_sep>package snu.hcil.gui;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.Timer;
import snu.hcil.tiger.DataManager;
import snu.hcil.tiger.Gene;
import snu.hcil.tiger.MainFrame;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
@SuppressWarnings("serial")
public class RefGenomeGeneNode extends PNode {
// final DataManager dataManager;
static RefGenomeGeneNode curMouseOnNode;
static RefGenomeGeneNode popupCaller;
private static String LINK_UCSC_GENOME_BROWSER = "Link to UCSC Browser";
private static String TO_CHROMOSOME = "See chromosome";
private static String TO_GENOME = "See overview";
private static String TO_GENE = "See gene";
private static final JPopupMenu popupMenu = new JPopupMenu();
private static final JMenuItem showUCSCBrowserMenuItem = new JMenuItem();
private static final JMenuItem seeGeneMenuItem = new JMenuItem();
private static final JMenuItem seeChrMenuItem = new JMenuItem();
private static final JMenuItem seeOverviewMenuItem = new JMenuItem();
final Gene gene;
// final Component popupParent;
public static Component popupParent;
static public void setupPopupMenu() {
showUCSCBrowserMenuItem.setText(LINK_UCSC_GENOME_BROWSER);
seeChrMenuItem.setText(TO_CHROMOSOME);
seeOverviewMenuItem.setText(TO_GENOME);
showUCSCBrowserMenuItem.setActionCommand(LINK_UCSC_GENOME_BROWSER);
seeChrMenuItem.setActionCommand(TO_CHROMOSOME);
seeOverviewMenuItem.setActionCommand(TO_GENOME);
seeGeneMenuItem.setActionCommand(TO_GENE);
showUCSCBrowserMenuItem.addActionListener(actionListener);
seeChrMenuItem.addActionListener(actionListener);
seeOverviewMenuItem.addActionListener(actionListener);
seeGeneMenuItem.addActionListener(actionListener);
popupMenu.add(showUCSCBrowserMenuItem);
popupMenu.addSeparator();
popupMenu.add(seeOverviewMenuItem);
popupMenu.add(seeChrMenuItem);
popupMenu.add(seeGeneMenuItem);
}
private static final ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DataManager dm = DataManager.getInstance();
Gene gene = popupCaller.gene;
double chrLen = dm.getRefGenomeChrLen(gene.getChrName());
String command = e.getActionCommand();
if (LINK_UCSC_GENOME_BROWSER.equals(command)) {
String urlStr = "http://genome.ucsc.edu/cgi-bin/hgTracks?";
String genomeName = dm.getRefGenomeName();
if (genomeName.equals(DataManager.HG18_STR)) {
urlStr = urlStr + "org=Human&db=hg18&position=";
}
urlStr = urlStr + gene.getName() + "&";
urlStr = urlStr + "dense=BasePosition&pack=RefSeq";
try {
URI uri = new URI(urlStr);
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
} else if (TO_CHROMOSOME.equals(command)) {
dm.setCurView(gene.getChrName(), popupCaller);
} else if (TO_GENOME.equals(command)) {
dm.setCurView(null, popupCaller);
} else if (TO_GENE.equals(command)) {
double relStart = gene.getTxStart() / chrLen;
double relEnd = gene.getTxEnd() / chrLen;
dm.setCurView(gene.getChrName(), relStart, relEnd, popupCaller);
}
}
};
private void zoomThisGene() {
DataManager dm = DataManager.getInstance();
int chrLen = dm.getRefGenomeChrLen(gene.getChrName());
String chrName = gene.getChrName();
double start = (double) gene.getTxStart() / (double) chrLen;
double end = (double) gene.getTxEnd() / (double) chrLen;
dm.setCurView(chrName, start, end, this);
}
public RefGenomeGeneNode(Gene gene) {
this.gene = gene;
addInputEventListener(new PBasicInputEventHandler() {
boolean isDblClk = false;
@Override
public void mouseEntered(PInputEvent event) {
curMouseOnNode = RefGenomeGeneNode.this;
Gene gene = RefGenomeGeneNode.this.gene;
MainFrame.getInstance().setCurGene(gene);
}
@Override
public void mouseExited(PInputEvent event) {
curMouseOnNode = null;
MainFrame.getInstance().setCurGene(null);
}
@Override
public void mouseClicked(PInputEvent event) {
event.setHandled(true);
if (event.isLeftMouseButton()) {
if (event.getClickCount() == 2) {
isDblClk = true;
} else if (event.getClickCount() == 1) {
Integer timerinterval = (Integer) Toolkit
.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
Timer timer = new Timer(timerinterval.intValue(),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isDblClk == true) {
// double click
RefGenomeGeneNode.this
.zoomThisGene();
isDblClk = false;
} else {
// single click
}
}
});
timer.setRepeats(false);
timer.start();
}
} else if (event.isRightMouseButton()) {
Point2D p = event.getCanvasPosition();
popupCaller = RefGenomeGeneNode.this;
Gene gene = RefGenomeGeneNode.this.gene;
showUCSCBrowserMenuItem.setText("See " + gene.getName()
+ " in UCSC");
seeChrMenuItem.setText("See " + gene.getChrName());
seeGeneMenuItem.setText("See " + gene.getName());
popupMenu.show(popupParent, (int) p.getX(), (int) p.getY());
}
super.mouseClicked(event);
}
});
}
}
<file_sep>package snu.hcil.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.Timer;
import snu.hcil.tiger.DataManager;
import snu.hcil.tiger.Gene;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PDragSequenceEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.util.PPaintContext;
@SuppressWarnings("serial")
public class RefGenomeChrNode extends PNode {
static boolean isOddNumbered = true;
static Color[] BACKGROUND_COLOR = { new Color(241, 238, 246),
new Color(189, 201, 225) };
static final Color DRAG_COLOR = new Color(239, 138, 98);
static public void resetOddNumbered() {
isOddNumbered = true;
}
private static double GAP_BTW_GENE = 2.0;
private static String LINK_UCSC_GENOME_BROWSER = "Link to UCSC Browser";
private static String TO_CHROMOSOME = "See chromosome";
private static String TO_GENOME = "See overview";
private static String CHR_STR = "chr";
private static final JPopupMenu popupMenu = new JPopupMenu("Chromsome");
private static RefGenomeChrNode popupCaller;
private static final JMenuItem showUCSCBrowserMenuItem = new JMenuItem();
private static final JMenuItem seeChrMenuItem = new JMenuItem();
private static final JMenuItem seeOverviewMenuItem = new JMenuItem();
private static final ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (LINK_UCSC_GENOME_BROWSER.equals(command)) {
DataManager dm = DataManager.getInstance();
String urlStr = "http://genome.ucsc.edu/cgi-bin/hgTracks?";
String genomeName = dm.getRefGenomeName();
if (genomeName.equals(DataManager.HG18_STR)) {
urlStr = urlStr + "org=Human&db=hg18&position=";
}
String curChrName = popupCaller.chrName;
urlStr = urlStr + curChrName + "&";
urlStr = urlStr + "dense=BasePosition&pack=RefSeq";
try {
URI uri = new URI(urlStr);
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
} else if (TO_CHROMOSOME.equals(command)) {
popupCaller.dataManager.setCurView(popupCaller.chrName,
popupCaller);
} else if (TO_GENOME.equals(command)) {
popupCaller.dataManager.setCurView(null, popupCaller);
}
}
};
static public void setupPopupMenu() {
showUCSCBrowserMenuItem.setText(LINK_UCSC_GENOME_BROWSER);
seeChrMenuItem.setText(TO_CHROMOSOME);
seeOverviewMenuItem.setText(TO_GENOME);
showUCSCBrowserMenuItem.setActionCommand(LINK_UCSC_GENOME_BROWSER);
seeChrMenuItem.setActionCommand(TO_CHROMOSOME);
seeOverviewMenuItem.setActionCommand(TO_GENOME);
showUCSCBrowserMenuItem.addActionListener(actionListener);
seeChrMenuItem.addActionListener(actionListener);
seeOverviewMenuItem.addActionListener(actionListener);
popupMenu.add(showUCSCBrowserMenuItem);
popupMenu.addSeparator();
popupMenu.add(seeOverviewMenuItem);
popupMenu.add(seeChrMenuItem);
}
public static Component popupParent;
final DataManager dataManager;
final String chrName;
final String nickName;
final int length;
final Color bgCol;
final PNode dragBox = new PNode();
double dragStartX;
double dragEndX;
final ArrayList<RefGenomeGeneNode> geneNodeList;
public RefGenomeChrNode(DataManager dm, String name, int length) {
dataManager = dm;
this.chrName = name;
nickName = name.substring(3);
this.length = length;
geneNodeList = new ArrayList<RefGenomeGeneNode>();
if (isOddNumbered) {
bgCol = BACKGROUND_COLOR[0];
} else {
bgCol = BACKGROUND_COLOR[1];
}
isOddNumbered = !isOddNumbered;
dragBox.setPaint(DRAG_COLOR);
addChild(dragBox);
addInputEventListener(new PDragSequenceEventHandler() {
boolean isDblClk = false;
@Override
public void mouseClicked(PInputEvent event) {
if (event.isLeftMouseButton()) {
if (event.getClickCount() == 2) {
isDblClk = true;
} else if (event.getClickCount() == 1) {
Integer timerinterval = (Integer) Toolkit
.getDefaultToolkit().getDesktopProperty(
"awt.multiClickInterval");
Timer timer = new Timer(timerinterval.intValue(),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isDblClk == true) {
// double click
dataManager
.setCurView(
RefGenomeChrNode.this.chrName,
RefGenomeChrNode.this);
isDblClk = false;
} else {
// single click
}
}
});
timer.setRepeats(false);
timer.start();
}
} else if (event.isRightMouseButton()) {
Point2D p = event.getCanvasPosition();
popupCaller = RefGenomeChrNode.this;
showUCSCBrowserMenuItem.setText("See " + chrName
+ " in UCSC");
seeChrMenuItem.setText("See " + chrName);
popupMenu.show(popupParent, (int) p.getX(), (int) p.getY());
}
super.mouseClicked(event);
}
@Override
protected void startDrag(PInputEvent event) {
if (event.isLeftMouseButton()) {
Point2D p = event.getPosition();
dragStartX = p.getX();
dragBox.setBounds(p.getX(), getY(), 0.0, getHeight());
super.startDrag(event);
}
}
@Override
protected void drag(PInputEvent event) {
if (event.isLeftMouseButton()) {
Point2D p = event.getPosition();
double curX = p.getX();
if (curX < getX()) {
curX = getX();
}
if (curX > getX() + getWidth()) {
curX = getX() + getWidth();
}
if (curX > dragStartX) {
dragBox.setBounds(dragStartX, getY(),
curX - dragStartX, getHeight());
} else {
dragBox.setBounds(curX, getY(), dragStartX - curX,
getHeight());
}
super.drag(event);
}
}
@Override
protected void endDrag(PInputEvent event) {
if (event.isLeftMouseButton()) {
Point2D p = event.getPosition();
dragEndX = p.getX();
dragBox.setWidth(0.0);
if (dragEndX < getX()) {
dragEndX = getX();
}
if (dragEndX > getX() + getWidth()) {
dragEndX = getX() + getWidth();
}
double relStartX = (dragStartX - getX()) / getWidth();
double relEndX = (dragEndX - getX()) / getWidth();
if (relStartX > relEndX) {
double temp = relEndX;
relEndX = relStartX;
relStartX = temp;
}
if (relEndX > relStartX) {
dataManager.setCurView(RefGenomeChrNode.this.chrName,
relStartX, relEndX, RefGenomeChrNode.this);
}
super.endDrag(event);
}
}
});
}
@Override
protected void layoutChildren() {
double x = getX();
double y = getY();
double w = getWidth();
double h = getHeight();
double chrLen = dataManager.getRefGenomeChrLen(chrName);
double chrGeneOrder = dataManager.getRefGenomeChrGeneOrder(chrName);
// double geneNodeH = h / (chrGeneOrder + 1.0) - GAP_BTW_GENE;
double geneNodeH = (h - chrGeneOrder * GAP_BTW_GENE)
/ (chrGeneOrder + 1.0);
double vGap = GAP_BTW_GENE;
for (Iterator<RefGenomeGeneNode> i = geneNodeList.iterator(); i
.hasNext();) {
RefGenomeGeneNode geneNode = i.next();
Gene gene = geneNode.gene;
double startPos = gene.getTxStart();
double endPos = gene.getTxEnd();
double order = gene.getOrder();
double startX = x + w / chrLen * startPos;
double endX = x + w / chrLen * endPos;
// geneNode.setBounds(startX, y + order * (geneNodeH + vGap), endX
// - startX, geneNodeH);
geneNode.setBounds(startX, y + h - geneNodeH * (order + 1.0) - vGap
* order, endX - startX, geneNodeH);
for (int j = 0; j < gene.getExonCount(); ++j) {
PNode exonNode = geneNode.getChild(j);
double exonLeft = x + w / chrLen * gene.getExonStarts()[j];
double exonRight = x + w / chrLen * gene.getExonEnds()[j];
// exonNode.setBounds(exonLeft, y + order * (geneNodeH + vGap),
// exonRight - exonLeft, geneNodeH);
exonNode.setBounds(exonLeft, y + h - geneNodeH * (order + 1.0)
- vGap * order, exonRight - exonLeft, geneNodeH);
}
}
super.layoutChildren();
}
@Override
protected void paint(PPaintContext paintContext) {
if (dataManager.getCurChrName() == null) {
Graphics2D g = paintContext.getGraphics();
g.setColor(bgCol);
g.fill(getBoundsReference());
double x = getX();
double y = getY();
double w = getWidth();
double h = getHeight();
boolean isDone = false;
int fontSize = 10;
while (!isDone) {
g.setColor(Color.BLACK);
g.setFont(new Font("arial", Font.PLAIN, fontSize));
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int des = fm.getDescent();
int strH = asc + des;
// If you can write the string in a line in this node.
if (fm.stringWidth(chrName) < w) {
int strWidth = fm.stringWidth(chrName);
float strX = (float) (x + (w - strWidth) * 0.5);
float strY = (float) (y + 0.5 * (h + asc - des));
g.drawString(chrName, strX, strY);
isDone = true;
} else if (fm.stringWidth(CHR_STR) < w) {
ArrayList<String> list = new ArrayList<String>();
list.add(CHR_STR);
list.add(nickName);
int lineCnt = list.size();
float startY = (float) (y + 0.5 * (h - lineCnt * strH) + asc);
for (int i = 0; i < list.size(); ++i) {
String str = list.get(i);
int strWidth = fm.stringWidth(str);
float strX = (float) (x + (w - strWidth) * 0.5);
float strY = startY + i * strH;
g.drawString(str, strX, strY);
isDone = true;
}
} else {
fontSize--;
if (fontSize == 0) {
isDone = true;
}
}
}
}
// else if (!dataManager.getCurChrName().equals(chrName)) {
// // don't draw at all
// }
else {
Graphics2D g = paintContext.getGraphics();
g.setColor(Color.WHITE);
g.fill(getBoundsReference());
}
super.paint(paintContext);
}
public int getLength() {
return length;
}
public Object getChrName() {
return chrName;
}
}
<file_sep>package snu.hcil.gui;
import java.awt.Component;
import java.awt.geom.Point2D;
import java.util.Iterator;
import edu.umd.cs.piccolo.event.PDragSequenceEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
@SuppressWarnings("serial")
public class RangeSliderH extends RangeSlider {
public RangeSliderH(Component comp) {
super(comp);
knot.addInputEventListener(new PDragSequenceEventHandler() {
double knotXAtDragStart;
double dragStartX;
boolean isDragging;
boolean isMouseIn;
@Override
protected void startDrag(PInputEvent event) {
Point2D p = event.getPosition();
dragStartX = p.getX();
knotXAtDragStart = knot.getX();
isDragging = true;
knot.setPaint(KNOT_MOVING_COL);
super.startDrag(event);
}
@Override
protected void drag(PInputEvent event) {
Point2D p = event.getPosition();
double delta = p.getX() - dragStartX;
double knotX = knotXAtDragStart + delta;
double knotW = knot.getWidth();
double x = getX();
double w = getWidth();
if (knotX < x) {
knotX = x;
}
double maxKnotX = getX() + w - knotW;
if (knotX > maxKnotX) {
knotX = maxKnotX;
}
knot.setX(knotX);
relStart = (knotX - getX()) / w;
relEnd = (knotX + knotW - getX()) / w;
for (Iterator<RangeSliderEventListener> i = listeners
.iterator(); i.hasNext();) {
RangeSliderEventListener l = i.next();
l.rangeChanging(RangeSliderH.this);
}
super.drag(event);
}
@Override
protected void endDrag(PInputEvent event) {
Point2D p = event.getPosition();
double delta = p.getX() - dragStartX;
double knotX = knotXAtDragStart + delta;
double knotW = knot.getWidth();
double x = getX();
double w = getWidth();
if (knotX < x) {
knotX = x;
}
double maxKnotX = getX() + w - knotW;
if (knotX > maxKnotX) {
knotX = maxKnotX;
}
knot.setX(knotX);
isDragging = false;
if (isMouseIn) {
knot.setPaint(KNOT_MOUSE_COL);
} else {
knot.setPaint(KNOT_COL);
}
relStart = (knotX - x) / w;
relEnd = (knotX + knotW - x) / w;
for (Iterator<RangeSliderEventListener> i = listeners
.iterator(); i.hasNext();) {
RangeSliderEventListener l = i.next();
l.rangeChanged(RangeSliderH.this);
}
super.endDrag(event);
}
@Override
public void mouseEntered(PInputEvent event) {
isMouseIn = true;
if (!isDragging) {
knot.setPaint(KNOT_MOUSE_COL);
component.setCursor(DRAG_CURSOR);
}
super.mouseEntered(event);
}
@Override
public void mouseExited(PInputEvent event) {
isMouseIn = false;
if (!isDragging) {
knot.setPaint(KNOT_COL);
component.setCursor(DEF_CURSOR);
}
super.mouseExited(event);
}
});
}
// @Override
// public void setKnot(double relStart, double relEnd) {
// super.setKnot(relStart, relEnd);
// }
@Override
protected void layoutChildren() {
double x = getX();
double y = getY();
double w = getWidth();
double h = getHeight();
double knotStart = x + w * relStart;
double knotEnd = x + w * relEnd;
knot.setBounds(knotStart, y + h * 0.05, knotEnd - knotStart, h * 0.9);
super.layoutChildren();
}
}
<file_sep>package snu.hcil.tiger;
public class Histogram {
int binCnt;
// final ArrayList<Integer> start = new ArrayList<Integer>();
// final ArrayList<Integer> end = new ArrayList<Integer>();
// final ArrayList<Integer> count = new ArrayList<Integer>();
final int[] starts;
final int[] ends;
final int[] values;
final int start;
final int end;
final int len;
final boolean isDiscreteDouble;
double maxDouble;
/**
* Create a new Histogram instance.
*
* @param start
* start of histogram range.
* @param end
* end of histogram range.
* @param binCount
* count of bins.
*/
public Histogram(int start, int end, int binCount, boolean b) {
this.start = start;
this.end = end;
len = end - start + 1;
this.binCnt = binCount;
this.isDiscreteDouble = b;
starts = new int[binCount];
ends = new int[binCount];
values = new int[binCount];
int len = end - start + 1;
for (int i = 0; i < binCount; ++i) {
starts[i] = start + (int) ((long) i * (long) len / binCount);
ends[i] = start + (int) ((long) (i + 1) * (long) len / binCount);
values[i] = 0;
}
}
/**
* Create new Histogram instance whose length is totalLength.
*
* @param len
* length of histogram.
* @param binCnt
* count of bins.
*/
public Histogram(int len, int binCnt, boolean b) {
start = 1;
end = len;
this.len = len;
this.binCnt = binCnt;
this.isDiscreteDouble = b;
starts = new int[binCnt];
ends = new int[binCnt];
values = new int[binCnt];
for (int i = 0; i < binCnt; ++i) {
starts[i] = (int) ((long) i * (long) len / binCnt) + 1;
ends[i] = (int) ((long) (i + 1) * (long) len / binCnt);
values[i] = 0;
}
}
/**
* Add a value to this histogram.
*
* @param position
* @param value
*/
public void add(int position, int value) {
if (position < start) {
return;
}
if (position > end) {
return;
}
int binIdx = (int) (((long) binCnt * (long) (position - start + 1) - 1) / len);
values[binIdx] += value;
}
/**
* Get the maximum binCount belongs to this histogram.
*
* @return
*/
public int getMaxValue() {
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i < binCnt; ++i) {
if (values[i] > maxValue) {
maxValue = values[i];
}
}
return maxValue;
}
public int getBinCount() {
return binCnt;
}
public double getCount(int i) {
return values[i];
}
}
<file_sep>package snu.hcil.gui;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.Iterator;
import snu.hcil.tiger.DataEventListener;
import snu.hcil.tiger.DataManager;
import edu.umd.cs.piccolo.PCanvas;
@SuppressWarnings("serial")
public class Canvas extends PCanvas implements DataEventListener {
final DataManager dm;
private final CellNameTrack cellNameTrack;
private final CellLineTrack cellLineTrack;
final static double TOP_MARGIN = 10.0;
final static double BOT_MARGIN = 10.0;
final static double LEFT_MARGIN = 10.0;
final static double RIGHT_MARGIN = 10.0;
final static double VERTICAL_GAP = 2.0;
final static double HORIZONTAL_GAP = 0.0;
final static double DEFAULT_NAME_TAG_WIDTH = 100.0;
final static double RULER_WIDTH = 40.0;
final static double MIN_CELL_LINE_TRACK_WIDTH = 600;
final static double MIN_CELL_LINE_TRACK_HEIGHT = 400;
final static double CELL_LINE_HEIGHT = 68.0;
final static double REF_LINE_HEIGHT = 98.0;
final static double VERTICAL_SCROLL_BAR_WIDTH = 20.0;
final static double HORIZONTAL_SCROLL_BAR_HEIGHT = 20.0;
final static double SCR_BAR_BTN_LEN = 20.0;
static final double MIN_KNOT_WIDTH = 5.0;
final static Font FONT = new Font("Lucida console", Font.PLAIN, 10);
public Canvas(final DataManager dm) {
super();
this.dm = dm;
cellNameTrack = new CellNameTrack(dm, this);
cellLineTrack = new CellLineTrack(dm, this);
cellNameTrack.cellLineTrack = cellLineTrack;
getLayer().addChild(cellNameTrack);
getLayer().addChild(cellLineTrack);
setPanEventHandler(null);
setZoomEventHandler(null);
addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent arg0) {
}
@Override
public void componentResized(ComponentEvent e) {
Dimension d = getSize();
didResized(dm, d);
}
@Override
public void componentMoved(ComponentEvent arg0) {
}
@Override
public void componentHidden(ComponentEvent arg0) {
}
});
}
private void didResized(DataManager dataManager, Dimension dimension) {
double width = dimension.getWidth();
double height = dimension.getHeight();
cellNameTrack.setBounds(LEFT_MARGIN, TOP_MARGIN, DEFAULT_NAME_TAG_WIDTH
+ RULER_WIDTH, height - TOP_MARGIN - BOT_MARGIN);
cellLineTrack.setBounds(LEFT_MARGIN + DEFAULT_NAME_TAG_WIDTH
+ RULER_WIDTH + HORIZONTAL_GAP, TOP_MARGIN, width - LEFT_MARGIN
- DEFAULT_NAME_TAG_WIDTH - RULER_WIDTH - HORIZONTAL_GAP
- RIGHT_MARGIN, height - TOP_MARGIN - BOT_MARGIN);
cellLineTrack.layoutChildren();
String chrName = dataManager.getCurChrName();
double relSx = dataManager.getCurRelStartPos();
double relEx = dataManager.getCurRelEndPos();
cellLineTrack.zoom(dataManager, chrName, relSx, relEx, false);
cellLineTrack.hRangeSlider.setKnot(relSx, relEx);
cellLineTrack.resetVRangeSlider();
}
private void link(CellNameTrack nameTrack, CellLineTrack cellTrack) {
for (Iterator<String> i = nameTrack.laneTable.keySet().iterator(); i
.hasNext();) {
String cellLineName = i.next();
CellNameLane nameTag = nameTrack.laneTable.get(cellLineName);
CellLineLane cellLine = cellTrack.laneTable.get(cellLineName);
nameTag.setContent(cellLine);
cellLine.setNameTag(nameTag);
}
}
@Override
public void didAddcellLines(DataManager dataManager, String[] cellLineNames) {
cellNameTrack.addLanes(dataManager, cellLineNames, false);
cellNameTrack.layoutChildren();
cellLineTrack.addLanes(dataManager, cellLineNames);
cellLineTrack.layoutChildren();
cellLineTrack.resetVRangeSlider();
link(cellNameTrack, cellLineTrack);
}
@Override
public void didAddGroup(DataManager dm, String name) {
cellNameTrack.addLane(dm, name, true);
cellNameTrack.setSubNodeBrick(dm, name);
cellNameTrack.layoutChildren();
cellLineTrack.addLane(dm, name);
cellLineTrack.layoutChildren();
cellLineTrack.resetVRangeSlider();
link(cellNameTrack, cellLineTrack);
}
@Override
public void didDeleteLane(DataManager dataManager, String name) {
cellLineTrack.layoutChildren();
cellNameTrack.layoutChildren();
cellLineTrack.resetVRangeSlider();
}
@Override
public void willDeleteLane(DataManager dataManager, String name) {
cellNameTrack.decreaseSubNodeBrick(dataManager, name);
cellLineTrack.removeLane(name);
cellNameTrack.removeLane(name);
cellNameTrack.repaint();
}
@Override
public void willLoadRefGenome(DataManager dataManager) {
cellNameTrack.clear();
cellLineTrack.clear();
}
@Override
public void didLoadRefGenome(DataManager dm) {
cellLineTrack.didLoadRefGenome(dm);
cellNameTrack.didLoadRefGenome(dm);
}
@Override
public void willChangePos(DataManager dm, String chrName,
double relStartPos, double relEndPos, Object invoker) {
if (invoker instanceof RangeSliderH) {
cellLineTrack.zoom(dm, chrName, relStartPos, relEndPos, false);
} else {
double relSx = relStartPos;
double relEx = relEndPos;
cellLineTrack.zoom(dm, chrName, relSx, relEx, true);
cellLineTrack.hRangeSlider.setKnot(relSx, relEx);
}
}
@Override
public void didChangePos(DataManager dataManager) {
Iterator<CellLineLane> i = cellLineTrack.laneTable.values().iterator();
while (i.hasNext()) {
CellLineLane lane = i.next();
lane.repaint();
}
Iterator<CellNameLane> j = cellNameTrack.laneTable.values().iterator();
while (j.hasNext()) {
CellNameLane lane = j.next();
lane.repaint();
}
}
public CellLineTrack getCellLineTrack() {
return cellLineTrack;
}
public CellNameTrack getCellNameTrack() {
return cellNameTrack;
}
@Override
public void didFoldLane(DataManager dataManager, String name, boolean isFold) {
cellNameTrack.changeBrick(dataManager, name, isFold);
cellLineTrack.layoutChildren();
cellNameTrack.layoutChildren();
cellLineTrack.resetVRangeSlider();
}
}
<file_sep>package snu.hcil.gui;
import java.awt.Color;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.Iterator;
import snu.hcil.tiger.DataManager;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.nodes.PPath;
@SuppressWarnings("serial")
public class CellLineLane extends PNode {
public final static Color[] BACKGROUND_COLOR = { new Color(198, 219, 239),
new Color(158, 202, 225) };
private static final Color cutOffLineCol = new Color(222, 45, 38);
private static boolean isOddNumbered = true;
final ArrayList<CellLineNode> nodes = new ArrayList<CellLineNode>();
final PPath cutOffLine = new PPath();
final DataManager dataManager;
final String cellLineName;
CellNameLane nameTag;
final Color backgroundColor;
double relCutOff;
public static void resetOddNumber() {
isOddNumbered = true;
}
public CellLineLane(DataManager dm, String name) {
dataManager = dm;
this.cellLineName = name;
if (isOddNumbered) {
backgroundColor = BACKGROUND_COLOR[0];
} else {
backgroundColor = BACKGROUND_COLOR[1];
}
isOddNumbered = !isOddNumbered;
cutOffLine.setStrokePaint(cutOffLineCol);
cutOffLine.setVisible(true);
// addChild(cutOffLine);
}
public void setNameTag(CellNameLane nameTag) {
this.nameTag = nameTag;
}
public void relCutOffDidChange(CellNameLane cellNameLane) {
setRelCutOff(cellNameLane.relCutOff);
cutOffLine.setY(getY() + getHeight() * relCutOff);
repaint();
}
public void relCutOffDidEnabled(CellNameLane cellNameLane,
boolean isCutoffEnabled) {
cutOffLine.setVisible(isCutoffEnabled);
cutOffLine.setPaintInvalid(true);
double x = getX();
double y = getY();
double w = getWidth();
double h = getHeight();
double lineY = y + h * relCutOff;
double lineLen = 0.0;
if (isCutoffEnabled) {
lineLen = w;
setRelCutOff(cellNameLane.relCutOff);
}
Line2D.Double line = new Line2D.Double(x, lineY, x + lineLen, lineY);
cutOffLine.setPathTo(line);
for (Iterator<CellLineNode> i = nodes.iterator(); i.hasNext();) {
CellLineNode n = i.next();
n.setCutOffEnable(isCutoffEnabled);
}
}
private void setRelCutOff(double d) {
relCutOff = d;
for (Iterator<CellLineNode> i = nodes.iterator(); i.hasNext();) {
CellLineNode n = i.next();
n.setRelCutOff(d);
}
}
}
|
38f7daf458f890da9cd8feb414d361cf1dbe0106
|
[
"Java"
] | 6
|
Java
|
dkjung/Tiger
|
551feb0c6ad6aac00103dcde3220cca92b3a0850
|
88092de2f43c31aab6d19a9e50afdee89623243d
|
refs/heads/main
|
<repo_name>SethBowman/FizzBuzz<file_sep>/Program.cs
using System;
namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type a number.");
FizzBuzz();
}
public static void FizzBuzz()
{
int number = int.Parse(Console.ReadLine());
if (number % 3 == 0 && number % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
if (number % 3 == 0)
{
Console.Write("Buzz");
}
else if (number % 5 == 0)
{
Console.Write("Fizz");
}
else
{
Console.WriteLine("Not divisible by 3 or 5.");
}
}
}
}
|
38b2aae09569a9a9144f060dc3138e034ce47921
|
[
"C#"
] | 1
|
C#
|
SethBowman/FizzBuzz
|
4f5736c2e0dd912282941880999cdb0e81911547
|
cabfcceb0e38c2b33032a835d6b621c32c32d4a2
|
refs/heads/master
|
<file_sep># save-info-into-file-txt.
Using input function we are asking user to enter his name and the name will be save into guests.txt. file by with statement.
<file_sep>prompt = "Enter your name:"
name = input(prompt)
filename = "guest.txt"
with open(filename, 'w') as file_object:
file_object.write(name.title())
|
54285a24ee2ce82082bc6380daae1a7b84e18715
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
lenasokolova/save-info-into-file-txt.
|
bf8e27e103fb55a526b745ad7f4a47adc4fb0fc9
|
9f9baf307da0ab81a442261ddeb024901fcfed59
|
refs/heads/master
|
<file_sep># chatbot
A bot for detecting fraud attempt.
This project was originally created by https://ireoluwaadedugbe.com and modified by https://github.com/Labi-Lawal/.
This version contains the intelligence in the most basic form with a simple Web UI to interact with the bot.
It is built with NodeJS (JavaScript), Html and CSS.
The bot determines if you are a fraudster or not based on the texts you send to it,
an array of words has been saved and would check through the user's text.... if it finds any of the saved words,
it alerts and tags the person as a fraudster.
In the future version, i'm planning to add an additional system to allow people report and submit new words to the database
so the intelligence grows based on the amount of people that use it.
<file_sep>const mongoose = require('mongoose');
mongoose.connect('mongodb://labi:spectacular1@mongodb-5339-0.cloudclusters.net:10017/fraudbot?authSource=admin', {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.once('open', ()=>{
console.log('Connection to database has been made...');
}).on('error', (error)=>{
console.log('Connection error: ', error);
})
module.exports = mongoose;<file_sep>$(document).ready(()=>{
setInterval(fetchMessages, 1000);
function fetchMessages(){
$.ajax({
type: 'GET',
url: '/getmessages',
dataType: 'json',
success: function(data){
$('div.message_box').html('')
var messagesOnScreen = [],
allTexts = data.text;
var userId = data.sessionUser;
var clientId = data.sessionClient;
for(var i = 0; i < allTexts.length; i++){
if(allTexts[i].from == userId.name){
var textsent = '<div class="text_sent">\
<div class="text">' +
allTexts[i].content
+ '</div>\
</div>';
messagesOnScreen.push(textsent);
// $('div.message_box').append(textsent)
}
else{
var textreceived = '<div class="text_received">\
<div class="text">'+
allTexts[i].content
+ '</div>\
</div>';
// $('div.message_box').append(textreceived)
messagesOnScreen.push(textreceived);
}
}
for(var i = 0; i < messagesOnScreen.length; i++){
$('div.message_box').append(messagesOnScreen[i]);
}
if(data.clientFraudLevel == 'innocent'){
} else if(data.clientFraudLevel == 'unsure'){
var unsure = "Hmm... there's something not quite right about this user. ";
$('div.bot_message_text').html(unsure)
} else if(data.clientFraudLevel == 'suspect'){
var suspect = "I'm suspecting this user to be a fraudster.";
$('div.bot_message_text').html(suspect)
} else if(data.clientFraudLevel == 'busted'){
var busted = "This user has been caught trying to scam you. You're advised to block immediately.";
$('div.bot_message_text').html(busted)
} else{
console.log('Couldnt detect level');
}
},
error: function(error){
var errormessage = '<div class="errormsg">There was an error fetching users. Click button below. <br>\
<a href="/"><button>CREATE A NEW CONNECTION</button></a>\
</div>';
$('$div.message_box').html(errormessage)
}
})
}
$('button.sendmessage').click((event)=>{
event.preventDefault();
var text = $('textarea.typing_box');
var message = JSON.stringify({message: text.val()});
if(text.val() != ''){
$('textarea.typing_box').val('')
$.ajax({
type: 'post',
url: '/sendmessage',
contentType: 'application/json',
data: message,
success: function(returnData){
if(returnData.status != ''){
$('div.sendingfail').attr('style', 'display : unset');
}
},
error:function(error){
var errormessage = '<div class="errormsg">There was an error sending message.<br>\
Check your connection <i class="fa fa-wifi"></i>\
</div>';
$('$div.message_box').html(errormessage)
}
})
}
var messageBox = document.querySelector('div.message_box');
messageBox.scrollTo(0, messageBox.scrollHeight)
})
})
<file_sep>const text = require('./text');
const dictionaries = require('./botdictionary');
const users = require('./users');
const session = require('express-session');
module.exports = (app)=>{
app.use(session({
secret: "Keeey",
resave: false,
saveUninitialized: true
}));
//Authentication code, at the end of the process
app.get("/signin", (req, res)=>{
res.render('signin', {
msg: '',
nouser: '',
wrongpassword: '',
signinas: '',
password: '',
});
});
app.post("/signin", (req, res)=>{
users.findOne({name: req.body.signinas.toLowerCase()}, (err, foundUser)=>{
if(err){
res.render('signin', {
msg: 'There was a problem getting your data. Please Try again.',
nouser: '',
wrongpassword: '',
signinas: req.body.signinas,
password: <PASSWORD>
});
} else if(!foundUser){
res.render('signin', {
msg: '',
nouser: 'Account for this user has not been created !',
wrongpassword: '',
signinas: req.body.signinas,
password: <PASSWORD>
})
} else if(foundUser){
if(foundUser.password == <PASSWORD>){
console.log(foundUser.name ,' has successfully logged in.');
req.session.user = foundUser;
res.redirect('/users');
}else {
res.render('signin', {
msg: '',
nouser: '',
wrongpassword: '<PASSWORD>.',
signinas: req.body.signinas,
password: <PASSWORD>
});
}
}
})
});
app.get("/users", (req, res)=>{
if(req.session.user != null) {
users.find({}, (err, foundData)=>{
if(err){
res.render('users', {
msg: 'Couldn\'t fetch users.'
})
}else if(foundData){
res.render('users', {
sessionUser: req.session.user,
sessionClient: req.session.client,
user: foundData,
msg: ''
})
}
})
} else {
res.redirect('/signin')
}
});
app.get("/signup", (req, res)=>{
res.render('signup', {
msg: '',
userexists: '',
username: '',
password: ''
});
});
app.post('/createaccount', (req, res)=>{
var userInputName = req.body.username.trim();
users.findOne({name: userInputName.toLowerCase()}, (err, exist)=>{
if(err){
res.render('signup', {
msg: 'There was a problem saving your data. Please Try again.',
userexists: '',
username: userInputName,
password: <PASSWORD>
});
} else if(exist){
res.render('signup', {
msg: '',
userexists: 'User name has been taken !',
username: userInputName,
password: <PASSWORD>
})
} else {
var newUser = users();
newUser.name = userInputName.toLowerCase()
newUser.password = <PASSWORD>;
newUser.fraudLevel = 'innocent';
newUser.userType = 'user';
newUser.save((err, saved)=>{
if(err){
res.render('signup',{
msg: 'There\'s something wrong with the connection, try again!'
});
}else if(saved){
console.log('New user ' + saved.name ,' has successfully logged in.');
req.session.user = saved;
res.redirect('/users');
}else{
res.render('signup', {
msg: 'There was an error, couldn\'t save your details.. Try again ! ',
userexists: '',
username: userInputName,
password: <PASSWORD>
});
}
})
}
})
})
//Chat Page loads once connection has been established
app.get('/chat/:name', (req, res)=>{
if(req.session.user != null ){
if(req.params.name != null){
var clientName = req.params.name.slice(1, req.params.name.length)
console.log(req.session.user.name + ' is requesting to established a connection with ' + clientName)
users.findOne({name: clientName}, (err, foundClient)=>{
if(err){
res.render('users', {
msg: 'There was an error connecting to ' + clientName,
});
} else if(foundClient){
if(foundClient.name != req.session.user.name){
req.session.client = foundClient;
console.log(req.session.user.name + ' has established a connection with ' + clientName)
res.render('chatroom', {
sessionClient: req.session.client,
sessionUser: req.session.user,
});
} else {
res.redirect('/users')
}
}
})
} else {
res.redirect('/users')
}
} else {
res.redirect('/users')
}
});
var fraud_keywords = [];
dictionaries.find({}, (err, keywords)=>{
if(err){
res.redirect('/disconnect')
} else {
fraud_keywords = keywords;
}
})
var is_fraud_count = 0;
var detected = [];
function fraud_detect(message){
var statement = message.toLowerCase();
for(var i = 0; i < fraud_keywords.length; i++){
if(statement.includes(fraud_keywords[i].content)){
detected.push(fraud_keywords[i].content);
}
}
}
app.get('/getmessages', (req, res)=>{
if(req.session.user != null || req.session.client != null ){
text.find({
$and: [
{$or : [ {from: req.session.user.name}, {from: req.session.client.name} ] },
{$or : [ {to: req.session.user.name}, {to: req.session.client.name} ] }
]
}, (err, foundData)=>{
if(err){
res.send({status: 'Couldn\'t get messages.. '})
}
else if(foundData){
for(var i = 0; i < foundData.length; i++){
if(foundData[i].from == req.session.client.name){
fraud_detect(foundData[i].content);
}
}
var allData, user_status;
is_fraud_count = detected.length;
if(is_fraud_count == 0 || is_fraud_count <= 3){
detected = []
user_status = 'innocent';
}
else if(is_fraud_count >= 4 && is_fraud_count <= 6){
detected = []
user_status = 'unsure';
}
else if(is_fraud_count >= 7 && is_fraud_count <= 9){
detected = []
user_status = 'suspect';
}
else if(is_fraud_count > 9){
detected = []
user_status = 'busted';
}
users.findOne({name: req.session.client.name}, (err, clientData)=>{
if(err){
res.redirect('/disconnect')
}
if(!clientData){
res.redirect('/disconnect')
}
if(clientData){
clientData.fraudLevel = user_status;
clientData.save((err, updated)=>{
if(err){
res.redirect('/disconnect')
} else if(updated){
allData = {
sessionClient: req.session.client,
sessionUser: req.session.user,
text: foundData,
clientFraudLevel: clientData.fraudLevel
}
res.send(allData);
}
})
}
})
}
})
} else {
res.redirect('/users');
}
});
app.post('/sendmessage', (req, res)=>{
const newText = text();
newText.content = req.body.message;
newText.from = req.session.user.name;
newText.to = req.session.client.name;
newText.save((err, saved)=>{
if(err){
res.send({status: 'There\'s was an error sending your text. Check your connection.'})
}
if(saved){
res.send({status: ''})
console.log(req.session.user.name, "has sent a message to", req.session.client.name, '.')
}
})
});
app.get('/refresh', (req, res)=>{
text.remove({
$and: [
{$or : [ {from: req.session.user.name}, {from: req.session.client.name} ] },
{$or : [ {to: req.session.user.name}, {to: req.session.client.name} ] }
]
}, (err)=>{
if(err){
res.render('index', {
msg: 'Unable to refresh chat.'
});
}else{
is_fraud_count = 0;
res.redirect('/');
}
})
})
app.get("/bot", (req, res)=>{
if(req.session.user != null) {
if(req.session.user.userType == 'admin'){
dictionaries.find({}, (err, foundData)=>{
if(err){
res.render('bot', {
msg: 'There was an issue getting the data requested.',
keywords: ''
});
} else {
if(!foundData){
res.render('bot', {
msg: 'There was an issue getting the data requested.',
keywords: ''
});
} else if(foundData){
res.render('bot', {
msg: '',
keywords: foundData,
sessionUser: req.session.user,
sessionClient: req.session.client
});
}
}
})
} else {
res.redirect('/')
}
} else {
res.redirect('/')
}
});
app.post("/removekeyword", (req, res)=>{
dictionaries.deleteOne({content: req.body.a_keyword}, (err)=>{
if(err){
res.render('bot', {
msg: 'There was an issue getting the deleting keyword.',
keywords: ''
});
} else {
res.redirect('/bot');
}
})
});
app.post('/uploaddictionary', (req, res)=>{
if(req.session.user.userType == 'admin'){
dictionaries.findOne({content: req.body.newkeyword.toLowerCase()}, (err, found)=>{
if(err){
res.render('bot', {
msg: 'There was an issue getting the data requested.',
keywords: ''
});
}
if(found){
dictionaries.find({}, (err, foundData)=>{
if(err){
res.render('bot', {
msg: 'There was an issue getting the data requested.',
keywords: ''
});
} else {
if(!foundData){
res.render('bot', {
msg: 'There was an issue getting the data requested.',
keywords: ''
});
} else if(foundData){
res.render('bot', {
msg: ' "' + found.content + '" ' + ' has previously been saved.',
keywords: foundData
});
}
}
});
}
if(!found){
var newToDictionary = dictionaries();
newToDictionary.content = req.body.newkeyword.toLowerCase()
newToDictionary.save((err, saved)=>{
if(err){
console.log(err);
res.render('bot', {
msg: 'There was an error saving new keyword.'
})
}else if(saved){
res.redirect('/bot')
}
});
}
})
} else {
res.redirect('/bot');
}
});
app.get("/resetfraudlevel/:name", (req, res)=>{
var clientName = req.params.name.slice(1, req.params.name.length)
users.findOne({name: clientName}, (err, foundUser)=>{
if(err){
res.render('users', {
msg: 'Couldn\'t fetch users..'
})
}else if(foundUser){
console.log(foundUser)
foundUser.fraudLevel = 'innocent';
foundUser.save((err, saved)=>{
if(err){
res.render('users', {
msg: 'Couldn\'t fetch users..'
})
} else if(saved){
res.redirect('/users')
}
})
}
})
})
app.get('/delete/:name', (req, res)=>{
var clientName = req.params.name.slice(1, req.params.name.length)
users.findOneAndDelete({name: clientName}, (err, deleted)=>{
if(err){
res.redirect('/users');
} else if(deleted){
console.log(req.session.user.name + ' has successfully deleted ' + clientName)
res.redirect('/users');
}
})
})
app.get('/signout', (req, res)=>{
var user = req.session.user.name;
if(req.session.destroy()){
console.log(user + ' has signed off.');
res.redirect('/signin')
}
})
app.get('/*', (req, res)=>{
res.redirect('/users')
})
}
<file_sep>var mongoose = require('./connect');
const botDictionarySchema = mongoose.Schema({
content: String
})
const dictionaries = mongoose.model('dictionaries', botDictionarySchema);
module.exports = dictionaries;
|
35fd2a802256f4a07718028c333b4c78e4028fad
|
[
"Markdown",
"JavaScript"
] | 5
|
Markdown
|
Labi-Lawal/fraudbot
|
3ea933c8d1136d42afd21dc748460edf8dcc7804
|
3110aac22074fed797c2fcc5bd0a526e3c530604
|
refs/heads/master
|
<repo_name>JamesImpression/ACF-Sync-Warning<file_sep>/README.md
# ACF-Sync-Warning
<file_sep>/acf-sync-warning.php
<?php
/*
Plugin Name: ACF Sync Warning
Description: Show a warning in development mode to say acf fields need to be synced
Version: 1.0.0
*/
function acf_sync_warning()
{
if (defined('WP_ENV')) {
if (WP_ENV == 'development') {
// Taken from ACF Pro plugin
$groups = acf_get_field_groups();
// bail early if no field groups
if (empty($groups)) return;
// find JSON field groups which have not yet been imported
foreach ($groups as $group) {
// vars
$sync = array();
$local = acf_maybe_get($group, 'local', false);
$modified = acf_maybe_get($group, 'modified', 0);
$private = acf_maybe_get($group, 'private', false);
// ignore DB / PHP / private field groups
if ($local !== 'json' || $private) {
// do nothing
} elseif (!$group['ID']) {
$sync[$group['key']] = $group;
} elseif ($modified && $modified > get_post_modified_time('U', true, $group['ID'], true)) {
$sync[$group['key']] = $group;
}
}
if(empty($sync)) return;
add_action('admin_notices', function () {
echo '<div class="notice notice-error"><p><strong> *** ACF Needs Syncing! *** </strong> <a href="' . site_url() . '/wp-admin/edit.php?post_type=acf-field-group&post_status=sync">Sync here now</a></p></div>';
});
if (!is_admin() && is_user_logged_in()) {
echo '<div style="position:fixed; bottom:0; left:0; right:0; top:auto; padding:15px; border-top:3px solid red; background-color:white; color:red!important; font-size:24px; text-align:center; margin:0 auto; z-index:9999;"><p style="margin:0;font-size:24px!important; color:red;"><strong>*** ACF Needs Syncing! ***</strong> <a style="text-decoration: underline;" href="' . site_url() . '/wp-admin/edit.php?post_type=acf-field-group&post_status=sync">Sync here now</a></p></div>';
}
}
}
}
add_action('init', 'acf_sync_warning');
?>
|
ebd7e05a58719b246a6e679ae802548135910337
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
JamesImpression/ACF-Sync-Warning
|
7910a16ee16b3d41c47014c37f8d7c97221c0b24
|
645924e73aef056333133959345c53a241fcbc0a
|
refs/heads/main
|
<file_sep>#!/usr/bin/python3
from os import mkdir;
from os.path import exists, join;
import tensorflow as tf;
from models import TextEncoder, VideoGenerator, IntrospectiveDiscriminator;
from dataset.sample_generator import SampleGenerator;
batch_size = 64;
encoder_dim = 16;
def main(filename = None, vocab_size = None, val_interval = 100, ckpt_interval = 10000):
dataset_generator = SampleGenerator(filename);
trainset = dataset_generator.get_trainset().batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE);
testset = dataset_generator.get_testset().batch(1).prefetch(tf.data.experimental.AUTOTUNE);
trainset_iter = iter(trainset);
testset_iter = iter(testset);
e = TextEncoder(vocab_size, encoder_dim);
g = VideoGenerator();
d = IntrospectiveDiscriminator();
true_labels = tf.ones((batch_size,));
false_labels = tf.zeros((batch_size,));
optimizer = tf.keras.optimizers.Adam(tf.keras.optimizers.schedules.ExponentialDecay(1e-4, decay_steps = 20000, decay_rate = 0.97));
if False == exists('checkpoints'): mkdir('checkpoints');
checkpoint = tf.train.Checkpoint(encoder = e, generator = g, discriminator = d, optimizer = optimizer);
checkpoint.restore(tf.train.latest_checkpoint('checkpoints'));
log = tf.summary.create_file_writer('checkpoints');
avg_disc_loss = tf.keras.metrics.Mean(name = 'discriminator loss', dtype = tf.float32);
avg_gen_loss = tf.keras.metrics.Mean(name = 'generator loss', dtype = tf.float32);
while True:
real, caption, matched = next(trainset_iter);
with tf.GradientTape(persistent = True) as tape:
code = e(caption); # code.shape = (batch, 16)
fake = g(code); # fake.shape = (batch, 16, 64, 64, 1)
real_motion_disc, real_frame_disc, real_text_disc, real_recon_latent0, real_recon_latent1 = d([real, code]);
fake_motion_disc, fake_frame_disc, fake_text_disc, fake_recon_latent0, fake_recon_latent1 = d([fake, code]);
# NOTE: D1: text_disc, D2: motion_disc & frame_disc
# NOTE: Q1: real_recon_latent1, Q2: real_recon_latent0
# 1.1) matched discriminator loss
d1_loss = tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, real_text_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, fake_text_disc);
d2_loss = tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, real_motion_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, real_frame_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, fake_motion_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, fake_frame_disc);
q1_loss = tf.keras.losses.MeanSquaredError()(code, real_recon_latent1);
q2_loss = tf.keras.losses.MeanSquaredError()(code, real_recon_latent0);
matched_disc_loss = d1_loss + d2_loss + q1_loss + q2_loss;
# 1.2) unmatched discriminator loss
d1_loss = tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, real_text_disc);
d2_loss = tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, real_motion_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, real_frame_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, fake_motion_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(false_labels, fake_frame_disc);
unmatched_disc_loss = d1_loss + d2_loss;
# 1.3) discriminator loss
disc_loss = tf.where(tf.math.equal(matched,1),matched_disc_loss,unmatched_disc_loss);
# 2) generator loss
g1_loss = tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, fake_text_disc);
g2_loss = tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, fake_motion_disc) \
+ tf.keras.losses.SparseCategoricalCrossentropy()(true_labels, fake_frame_disc);
info_loss = tf.keras.losses.MeanSquaredError()(code, fake_recon_latent1) \
+ tf.keras.losses.MeanSquaredError()(code, fake_recon_latent0);
gen_loss = g1_loss + g2_loss + info_loss;
# 3) encoder loss
enc_loss = disc_loss + gen_loss;
avg_disc_loss.update_state(disc_loss);
avg_gen_loss.update_state(gen_loss);
# 3) gradients
d_grads = tape.gradient(disc_loss, d.trainable_variables);
g_grads = tape.gradient(gen_loss, g.trainable_variables);
e_grads = tape.gradient(enc_loss, e.trainable_variables);
optimizer.apply_gradients(zip(d_grads, d.trainable_variables));
optimizer.apply_gradients(zip(g_grads, g.trainable_variables));
optimizer.apply_gradients(zip(e_grads, e.trainable_variables));
if tf.equal(optimizer.iterations % ckpt_interval, 0):
checkpoint.save(join('checkpoints','ckpt'));
if tf.equal(optimizer.iterations % val_interval, 0):
real, caption, matched = next(testset_iter);
code = e(caption);
fake = g(code); # fake.shape = (1, 16, 64, 64, 1)
fake = tf.transpose(tf.reshape((fake + 1) * 128., (1,4,4,64,64,1)), (0,1,3,2,4,5)); # fake.shape = (1, 4, 64, 4, 64, 1)
fake = tf.tile(tf.reshape(fake, (1, 256, 256, 1)), (1,1,1,3)); # fake.shape = (1, 256, 256, 3)
fake = tf.cast(fake, dtype = tf.uint8);
with log.as_default():
tf.summary.scalar('discriminator loss', avg_disc_loss.result(), step = optimizer.iterations);
tf.summary.scalar('generator loss', avg_gen_loss.result(), step = optimizer.iterations);
tf.summary.image('video', fake, step = optimizer.iterations);
print('#%d disc loss: %f gen loss: %f' % (optimizer.iterations, avg_disc_loss.result(), avg_gen_loss.result()))
avg_disc_loss.reset_states();
avg_gen_loss.reset_states();
if __name__ == "__main__":
from sys import argv;
if len(argv) != 2:
print('Usage: %s (single|double)' % argv[0]);
exit(1);
assert argv[1] in ['single','double'];
if argv[1] == 'single':
from dataset.mnist_caption_single import dictionary;
vocab_size = len(dictionary);
elif argv[1] == 'double':
from dataset.mnist_caption_two_digit import dictionary;
vocab_size = len(dictionary);
main('mnist_single_gif.h5' if argv[1] == 'single' else 'mnist_two_gif.h5', vocab_size);
<file_sep>#!/usr/bin/python3
import tensorflow as tf;
from models import TextEncoder, VideoGenerator, IntrospectiveDiscriminator;
encoder_dim = 16;
def main(vocab_size):
e = TextEncoder(vocab_size, encoder_dim);
g = VideoGenerator();
d = IntrospectiveDiscriminator();
optimizer = tf.keras.optimizers.Adam(tf.keras.optimizers.schedules.ExponentialDecay(1e-3, decay_steps = 60000, decay_rate = 0.5));
checkpoint = tf.train.Checkpoint(encoder = e, generator = g, discriminator = d, optimizer = optimizer);
checkpoint.restore(tf.train.latest_checkpoint('checkpoints'));
e.save('encoder.h5');
g.save_weights('generator_weights.h5');
if __name__ == "__main__":
from sys import argv;
if len(argv) != 2:
print('Usage: %s (single|double)');
exit(1);
assert argv[1] in ['single', 'double'];
if argv[1] == 'single':
from dataset.mnist_caption_single import dictionary;
vocab_size = len(dictionary);
elif argv[1] == 'double':
from dataset.mnist_caption_two_digit import dictionary;
vocab_size = len(dictionary);
main(vocab_size);
<file_sep>#!/usr/bin/python3
import h5py;
import numpy as np;
import tensorflow as tf;
class SampleGenerator(object):
def __init__(self, filename):
f = h5py.File(filename, 'r');
self.data_train = np.array(f['mnist_gif_train']);
self.captions_train = np.array(f['mnist_captions_train']);
self.data_val = np.array(f['mnist_gif_val']);
self.captions_val = np.array(f['mnist_captions_val']);
f.close();
def sample_generator(self, is_trainset = True):
data = self.data_train if is_trainset else self.data_val;
caption = self.captions_train if is_trainset else self.captions_val;
def gen():
for i in range(data.shape[0]):
sample1 = np.transpose(data[i], (0,2,3,1));
caption1 = caption[i];
samples = np.arange(data.shape[0]);
np.delete(samples, i);
samples = np.random.choice(samples, 3, replace=False);
for j in samples:
sample2 = np.transpose(data[j], (0,2,3,1));
caption2 = np.expand_dims(caption[j], axis = -1);
if np.all(caption1 == caption2):
# write a sample with corresponding sample and caption
yield sample1, caption2, 1;
elif np.any(caption1 != caption2):
# write a sample with sample1 and caption2
yield sample1, caption2, 0;
else:
raise Exception('mustn\'t be here');
return gen;
def parse_function(self, sample, caption, label):
sample = sample / 128. - 1; # in range [-1, 1]
return sample, caption, label;
def get_trainset(self,):
return tf.data.Dataset.from_generator(self.sample_generator(True), (tf.float32, tf.int64, tf.int64), (tf.TensorShape([16,64,64,1]), tf.TensorShape([9,1,]), tf.TensorShape([]))).map(self.parse_function).repeat(-1);
def get_testset(self):
return tf.data.Dataset.from_generator(self.sample_generator(False), (tf.float32, tf.int64, tf.int64), (tf.TensorShape([16,64,64,1]), tf.TensorShape([9,1,]), tf.TensorShape([]))).map(self.parse_function).repeat(-1);
if __name__ == "__main__":
import cv2;
generator = SampleGenerator('mnist_single_gif.h5');
trainset = generator.get_trainset();
testset = generator.get_testset();
cv2.namedWindow('sample');
for sample, caption, matched in trainset:
print(caption, matched);
sample = (sample + 1) * 128.;
for image in sample:
cv2.imshow('sample',image.numpy().astype(np.uint8));
cv2.waitKey(50);
generator = SampleGenerator('mnist_two_gif.h5');
trainset = generator.get_trainset();
testset = generator.get_testset();
<file_sep># IRC-GAN
this project implement text2video generative algorithm introduced in paper [IRC-GAN: Introspective Recurrent Convolutional GAN for Text-to-video Generation](https://www.ijcai.org/Proceedings/2019/0307.pdf)
## create dataset
create moving single digit dataset with command
```shell
python3 dataset/mnist_caption_single.py
```
after executing successfully, a file named mnist_single_git.h5 is generated.
create moving double digits dataset with command
```shell
python3 dataset/mnist_caption_two_digit.py
```
after executing successfully, a file named mnist_two_gif.h5 is generated.
the dataset creation code is borrowed from [Sync-Draw](https://github.com/syncdraw/Sync-DRAW/tree/master/dataset) and slightly modified.
## train on moving mnist dataset
train model with command
```shell
python3 train.py (single|double)
```
the parameter is an optional to switch between moving single digit and moving double digits.
## save the latest checkpoint to keras model
save with command
```shell
python3 save_model.py
```
the script save generative model to generator_weights.h5 and save encoder to encoder.h5.
<file_sep>#!/usr/bin/python3
import numpy as np;
import tensorflow as tf;
def TextEncoder(src_vocab_size, input_dims, units = 16):
inputs = tf.keras.Input((None, 1), ragged = True); # inputs.shape = (batch, ragged length, 1)
results = tf.keras.layers.Lambda(lambda x: tf.squeeze(x, axis = -1))(inputs); # results.shape = (batch, ragged length)
results = tf.keras.layers.Embedding(src_vocab_size, input_dims)(results); # results.shape = (batch, ragged length, input_dims)
results = tf.keras.layers.Bidirectional(
layer = tf.keras.layers.LSTM(units // 2),
backward_layer = tf.keras.layers.LSTM(units // 2, go_backwards = True),
merge_mode = 'concat')(results); # results.shape = (batch, units)
return tf.keras.Model(inputs = inputs, outputs = results);
def RecurrentTransconvolutionalGenerator(channels = 16, layers = 5, img_channels = 3):
inputs = tf.keras.Input((channels,)); # inputs.shape = (batch, channels)
hiddens = [tf.keras.Input((2**i * 2**i,)) for i in range(layers)]; # hiddens[i].shape = (batch * channels * 2, 2^i * 2^i)
cells = [tf.keras.Input((2**i * 2**i,)) for i in range(layers)]; # cells[i].shape = (batch * channels * 2, 2^i * 2^i)
results = tf.keras.layers.Reshape((1, 1, channels))(inputs); # results.shape = (batch, 1, 1, channels)
dnorm = tf.keras.layers.Lambda(lambda x: tf.random.normal(shape = tf.shape(x)))(results); # dnorm.shape = (batch, 1, 1, channel)
results = tf.keras.layers.Concatenate(axis = -1)([results, dnorm]); # results.shape = (batch, 1, 1, 2 * channels)
next_hiddens = list();
next_cells = list();
for i in range(layers):
before = results; # before.shape = (batch, 2^i, 2^i, 2 * channels)
results = tf.keras.layers.Lambda(lambda x, l: tf.reshape(tf.transpose(x, (0,3,1,2)), (-1, 2**l * 2**l)), arguments = {'l': i})(results); # results.shape = (batch * 2*channels, 1, 2^i, 2^i)
lstm_inputs = tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis = 1))(results); # lstm.shape = (batch, 1, 2^i * 2^i)
results, hidden, cell = tf.keras.layers.LSTM(units = 2**i * 2**i, return_state = True)(lstm_inputs, initial_state = (hiddens[i], cells[i])); # hidden.shape = (batch * 2 * channels, 2^i * 2^i)
next_hiddens.append(hidden);
next_cells.append(cell);
after = tf.keras.layers.Lambda(lambda x, c, l: tf.transpose(tf.reshape(x, (-1, 2 * c, 2**l, 2**l)), (0, 2, 3, 1)), arguments = {'l': i, 'c': channels})(results); # results.shape = (batch, 2^i, 2^i, 2 * channels)
results = tf.keras.layers.Concatenate(axis = -1)([before, after]); # results.shape = (batch, 2^i, 2^i, 2 * channels)
results = tf.keras.layers.Conv2DTranspose(filters = 2 * channels, kernel_size = (3, 3), strides = (2,2), padding = 'same')(results); # results.shape = (batch, 2^(i+1), 2^(i+1), 2 * channels)
results = tf.keras.layers.BatchNormalization()(results); # results.shape = (batch, 2^(i+1), 2^(i+1), 2 * channels)
results = tf.keras.layers.LeakyReLU()(results); # results.shape = (batch, 2^(i+1), 2^(i+1), 2 * channels)
results = tf.keras.layers.Conv2DTranspose(filters = img_channels, kernel_size = (3, 3), strides = (2,2), padding = 'same')(results); # results.shape = (batch, 64, 64, img_channels)
return tf.keras.Model(inputs = (inputs, *hiddens, *cells), outputs = (results, *next_hiddens, *next_cells));
class VideoGenerator(tf.keras.Model):
def __init__(self, filters = 16, layers = 5, img_channels = 1, length = 16):
super(VideoGenerator, self).__init__();
self.generator = RecurrentTransconvolutionalGenerator(channels = filters, layers = layers, img_channels = img_channels);
self.filters = filters;
self.layer_num = layers;
self.length = length;
def call(self, inputs):
hiddens = [tf.zeros((inputs.shape[0] * 2 * self.filters, 2**i * 2**i)) for i in range(self.layer_num)];
cells = [tf.zeros((inputs.shape[0] * 2 * self.filters, 2**i * 2**i)) for i in range(self.layer_num)];
video = list();
for i in range(self.length):
outputs = self.generator([inputs, *hiddens, *cells]);
frame = outputs[0]; # frame.shape = (batch, height = 64, width = 64, img_channels = 1)
video.append(frame);
hiddens = outputs[1:6];
cells = outputs[6:11];
video = tf.stack(video, axis = 1); # video.shape = (batch, length = 16, height = 64, width = 64, img_channels = 1)
return video;
def IntrospectiveDiscriminator(img_size = 64, img_channels = 1, length = 16, units = 16):
video = tf.keras.Input((length, img_size, img_size, img_channels)); # video.shape = (batch, length = 16, height = 64, width = 64, img_channls = 1)
text = tf.keras.Input((units,)); # text.shape = (batch, units)
# 1) temporal coherence
results = tf.keras.layers.Lambda(lambda x, s, c: tf.reshape(x, (-1, s, s, c)), arguments = {'s': img_size, 'c': img_channels})(video); # results.shape = (batch * length, height, width, img_channels)
results = tf.keras.layers.Conv2D(filters = 64, kernel_size = (3,3), strides = (2,2), padding = 'same')(results); # results.shape = (batch * length, height / 2, width / 2, 64)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv2D(filters = 128, kernel_size = (3,3), strides = (2,2), padding = 'same')(results); # results.shape = (batch * length, height / 4, width / 4, 128)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), strides = (2,2), padding = 'same')(results); # results.shape = (batch * length, height / 8, width / 8, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), strides = (2,2), padding = 'same')(results); # results.shape = (batch * length, height / 16, width / 16, 256)
results = tf.keras.layers.BatchNormalization()(results);
motion_frame_inputs = tf.keras.layers.LeakyReLU()(results);
# 1.1) motion loss
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), padding = 'same')(motion_frame_inputs); # results.shape = (batch * length, height / 16, width / 16, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), padding = 'same')(results); # results.shape = (batch * length, height / 16, width / 16, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Lambda(lambda x, l: tf.reshape(x, (-1, l, x.shape[-3], x.shape[-2], x.shape[-1])), arguments = {'l': length})(results); # results.shape = (batch, length, height / 16, width / 16, 256)
results = tf.keras.layers.Lambda(lambda x: x[:,1:,...] - x[:,:-1,...])(results); # results.shape = (batch, length - 1, height / 16, width / 16, 256)
results = tf.keras.layers.Lambda(lambda x: tf.reshape(x, (-1, x.shape[-3], x.shape[-2], x.shape[-1])))(results); # results.shape = (batch * (length - 1), height / 16, width / 16, 256)
motion_disc = tf.keras.layers.Lambda(lambda x, l: tf.reshape(x, (-1, l-1, x.shape[-3], x.shape[-2], x.shape[-1])), arguments = {'l': length})(results); # motion_disc.shape = (batch, length - 1, height / 16, width / 16, 256)
motion_disc = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(motion_disc); # motion_disc.shape = (batch, 256)
motion_disc = tf.keras.layers.Dense(2, activation = tf.keras.activations.softmax)(motion_disc); # motion_disc.shape = (batch, 2)
recon_latent0_left = tf.keras.layers.Lambda(lambda x, l: tf.reshape(x, (-1, l-1, x.shape[-3], x.shape[-2], x.shape[-1])), arguments = {'l': length})(results); # recon_latent0.shape = (batch, length - 1, height / 16, width / 16, 256)
recon_latent0_left = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(recon_latent0_left); # recon_latent0.shape = (batch, 256)
# 1.2) frame loss
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), padding = 'same')(motion_frame_inputs); # results.shape = (batch * length, height / 16, width / 16, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv2D(filters = 256, kernel_size = (3,3), padding = 'same')(results); # results.shape = (batch * length, height / 16, width / 16, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
frame_disc = tf.keras.layers.Lambda(lambda x, l: tf.reshape(x, (-1, l, x.shape[-3], x.shape[-2], x.shape[-1])), arguments = {'l': length})(results); # frame_disc.shape = (batch, length, height / 16, width / 16, 256)
frame_disc = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(frame_disc); # frame_disc.shape = (batch, 256)
frame_disc = tf.keras.layers.Dense(2, activation = tf.keras.activations.softmax)(frame_disc); # frame_disc.shape = (batch, 2)
recon_latent0_right = tf.keras.layers.Lambda(lambda x, l: tf.reshape(x, (-1, l, x.shape[-3], x.shape[-2], x.shape[-1])), arguments = {'l': length})(results); # recon_latent1.shape = (batch, length, height / 16, width / 16, 256)
recon_latent0_right = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(recon_latent0_right); # recon_latent1.shape = (batch, 256)
recon_latent0 = tf.keras.layers.Concatenate(axis = -1)([recon_latent0_left, recon_latent0_right]); # recon_latent0.shape = (batch, 512)
recon_latent0 = tf.keras.layers.Dense(units, activation = tf.keras.activations.tanh)(recon_latent0); # recon_latent1.shape = (batch, units)
# 2) whole video
results = tf.keras.layers.Conv3D(filters = 64, kernel_size = (3,3,3), strides = (2,2,2), padding = 'same')(video); # results.shape = (batch, length / 2, height / 2, width / 2, 64)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv3D(filters = 128, kernel_size = (3,3,3), strides = (2,2,2), padding = 'same')(results); # results.shape = (batch, length / 4, height / 4, width / 4, 128)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv3D(filters = 256, kernel_size = (3,3,3), strides = (2,2,2), padding = 'same')(results); # results.shape = (batch, length / 8, height / 8, width / 8, 256)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
results = tf.keras.layers.Conv3D(filters = 512, kernel_size = (3,3,3), strides = (2,2,2), padding = 'same')(results); # results.shape = (batch, length / 16, height / 16, width / 16, 512)
results = tf.keras.layers.BatchNormalization()(results);
results = tf.keras.layers.LeakyReLU()(results);
# 2.1) video loss
video_results = tf.keras.layers.Conv3D(filters = 512, kernel_size = (1,3,3), strides = (1,2,2), padding = 'same')(results); # video_results.shape = (batch, length / 16, height / 32, width / 32, 512)
video_results = tf.keras.layers.BatchNormalization()(video_results);
video_results = tf.keras.layers.LeakyReLU()(video_results);
video_results = tf.keras.layers.Conv3D(filters = 512, kernel_size = (1,3,3), strides = (1,2,2), padding = 'same')(video_results); # video_results.shape = (batch, length / 16, height / 64, width / 64, 512)
recon_latent1 = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(video_results); # video_results.shape = (batch, 512)
recon_latent1 = tf.keras.layers.Dense(units, activation = tf.keras.activations.tanh)(recon_latent1); # recon_latent1.shape = (batch, units)
# 2.2) text loss
text_results = tf.keras.layers.Reshape((1, 1, units))(text); # text_results.shape = (batch, 1, 1, units)
text_results = tf.keras.layers.Conv2DTranspose(filters = 256, kernel_size = (3, 3), strides = (2,2), padding = 'same')(text_results); # text_results.shape = (batch, 2, 2, 256)
text_results = tf.keras.layers.BatchNormalization()(text_results);
text_results = tf.keras.layers.LeakyReLU()(text_results);
text_results = tf.keras.layers.Conv2DTranspose(filters = 256, kernel_size = (3, 3), strides = (2,2), padding = 'same')(text_results); # text_results.shape = (batch, 4, 4, 256)
text_results = tf.keras.layers.BatchNormalization()(text_results);
text_results = tf.keras.layers.LeakyReLU()(text_results);
text_results = tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis = 1))(text_results); # text_results.shape = (batch, 1, 4, 4, 256)
text_results = tf.keras.layers.Concatenate(axis = -1)([results, text_results]); # text_results.shape = (batch, 1, 4, 4, 768)
text_results = tf.keras.layers.Conv3D(filters = 512, kernel_size = (1,1,1), strides = (1,1,1), padding = 'same')(text_results); # text_results.shape = (batch, 1, 4, 4, 512)
text_results = tf.keras.layers.BatchNormalization()(text_results);
text_results = tf.keras.layers.LeakyReLU()(text_results);
text_disc = tf.keras.layers.Lambda(lambda x: tf.math.reduce_mean(x, (1,2,3)))(text_results); # text_results.shape = (batch, 512)
text_disc = tf.keras.layers.Dense(2, activation = tf.keras.activations.softmax)(text_disc); # text_disc.shape = (batch, 2)
return tf.keras.Model(inputs = (video, text), outputs = (motion_disc, frame_disc, text_disc, recon_latent0, recon_latent1));
if __name__ == "__main__":
assert tf.executing_eagerly();
encoder = TextEncoder(100,64);
encoder.save('encoder.h5');
tf.keras.utils.plot_model(model = encoder, to_file = 'encoder.png', show_shapes = True, dpi = 64);
inputs = np.random.randint(low = 0, high = 100, size = (50,));
inputs = tf.RaggedTensor.from_row_lengths(inputs, [50,]);
inputs = tf.expand_dims(inputs, axis = -1);
results = encoder(inputs);
print(results.shape);
generator = RecurrentTransconvolutionalGenerator();
generator.save('generator.h5');
tf.keras.utils.plot_model(model = generator, to_file = 'generator.png', show_shapes = True, dpi = 64);
inputs = np.random.normal(size = (8, 16));
hiddens = [np.random.normal(size = (8 * 2 * 16, 2**i * 2**i)) for i in range(5)];
cells = [np.random.normal(size = (8 * 2 * 16, 2**i * 2**i)) for i in range(5)];
results, hidden1, hidden2, hidden3, hidden4, hidden5, cell1, cell2, cell3, cell4, cell5 = generator([inputs, *hiddens, * cells]);
print(results.shape);
print(hidden1.shape);
print(hidden2.shape);
print(hidden3.shape);
print(hidden4.shape);
print(hidden5.shape);
vgen = VideoGenerator();
vgen.save_weights('vgen.h5');
tf.keras.utils.plot_model(model = vgen, to_file = 'vgen.png', show_shapes = True, dpi = 64);
video = vgen(inputs);
print(video.shape);
disc = IntrospectiveDiscriminator();
disc.save('disc.h5');
tf.keras.utils.plot_model(model = disc, to_file = 'disc.png', show_shapes = True, dpi = 64);
motion_disc, frame_disc, text_disc, recon_latent0, recon_latent1 = disc([video, inputs]);
print(motion_disc.shape);
print(frame_disc.shape);
print(text_disc.shape);
print(recon_latent0.shape);
print(recon_latent1.shape);
<file_sep>#!/usr/bin/python3
import numpy as np;
import cv2;
import tensorflow as tf;
import dataset.mnist_caption_single as single;
import dataset.mnist_caption_two_digit as double;
from models import TextEncoder, VideoGenerator, IntrospectiveDiscriminator;
encoder_dim = 16;
def main(digits, movings):
assert len(digits) in [1,2];
assert len(movings) in [1,2];
assert np.all([digit in [0,1,2,3,4,5,6,7,8,9] for digit in digits]);
assert np.all([moving in ['left and right','up and down'] for moving in movings]);
assert len(digits) == len(movings);
if len(digits) == 1:
sentence = 'the digits %d is moving %s .' % (digits[0], movings[0]);
tokens = single.sent2matrix(sentence, single.dictionary);
e = TextEncoder(len(single.dictionary), encoder_dim);
else:
sentence = 'digit %d is %s and digit %d is %s .' % (digits[0], movings[0], digits[1], movings[1]);
tokens = double.sent2matrix(sentence, double.dictionary);
e = TextEncoder(len(double.dictionary), encoder_dim);
print(sentence);
# load weights
g = VideoGenerator();
d = IntrospectiveDiscriminator();
optimizer = tf.keras.optimizers.Adam(tf.keras.optimizers.schedules.ExponentialDecay(1e-3, decay_steps = 60000, decay_rate = 0.5));
checkpoint = tf.train.Checkpoint(encoder = e, generator = g, discriminator = d, optimizer = optimizer);
checkpoint.restore(tf.train.latest_checkpoint('checkpoints'));
# predict
tokens = tf.expand_dims(tokens, axis = -1);
code = e(tokens);
videos = g(code);
video = videos[0].numpy(); # video.shape = (16,64,64,1)
writer = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), 20.0, (64,64), True);
for i,frame in enumerate(video):
frame = frame.astype(np.uint8);
writer.write(frame);
cv2.imwrite('%d.png' % i,frame);
writer.release();
def input_digit(message):
while True:
digit = input(message);
if digit not in [*'0123456789']:
print('wrong digit, enter again');
continue;
break;
return int(digit);
def input_movement(message):
while True:
choice = input('choose a movement from 0: \'left and right\', 1: \'up and down\'');
if choice not in [*'01']:
print('wrong movement choice, enter again');
continue;
break;
return 'left and right' if choice == '0' else 'up and down';
if __name__ == "__main__":
from sys import argv;
if len(argv) != 2:
print('Usage: %s (single|double)' % argv[0]);
exit(1);
if argv[1] == 'single':
digit = input_digit('choose a digit from [0123456789]');
movement = input_movement('choose a movement from 0: \'left and right\', 1: \'up and down\'');
digits = [digit];
movements = [movement];
else:
first_digit = input_digit('choose the first single digit from [0123456789]');
first_movement = input_movement('choose a movement for the first digit from 0: \'left and right\', 1: \'up and down\'');
second_digit = input_digit('choose the second single digit from [0123456789]');
second_movement = input_movement('choose a movement for the second digit from 0: \'left and right\', 1: \'up and down\'');
digits = [first_digit, second_digit];
movements = [first_movement, second_movement];
main(digits, movements);
|
8a55f0dedfd0f52159098622152bb648d9239f01
|
[
"Markdown",
"Python"
] | 6
|
Python
|
SonainJamil/IRCGAN-tf2
|
276fb745393790b555f64c94ca7f69005d3c3082
|
01bd212da571ab26f42c7006ef299b3537e1e2e6
|
refs/heads/master
|
<file_sep># GoogleMapsClusters
Demo de Google Maps con Cluster. Esta es una prueba para verificar que pueda subir los PODS sin ningun problema. Ya que en el pasado habia problemas con los SDK de google
<file_sep>/* Copyright (c) 2016 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.
*/
import GoogleMaps
import UIKit
/// Point of Interest Item which implements the GMUClusterItem protocol.
class POIItem: NSObject, GMUClusterItem
{
var position: CLLocationCoordinate2D
var name: String!
init(position: CLLocationCoordinate2D, name: String)
{
self.position = position
self.name = name
}
}
let kClusterItemCount = 10000
let kCameraLatitude = 36.2077343
let kCameraLongitude = -113.7407914
let kZoom: Float = 4 // min 1 |- - - - - - - -| 10 max
class ClusteringViewController: UIViewController
{
fileprivate var mapView: GMSMapView!
fileprivate var clusterManager: GMUClusterManager!
override func loadView()
{
let camera = GMSCameraPosition.camera(withLatitude: kCameraLatitude, longitude: kCameraLongitude, zoom: kZoom)
self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
//Theme Style
do {
// Set the map style by passing a valid JSON string.
let path = Bundle.main.path(forResource: "map_black_style", ofType: "json")
let url = URL(fileURLWithPath: path!)
self.mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: url)
}
catch
{
print("One or more of the map styles failed to load. \(error)")
}
//Adding to View
self.view = self.mapView
}
override func viewDidLoad()
{
super.viewDidLoad()
//Group buckets : how many levels do you want? (must be increasing order)
let numbers: [NSNumber] = [10, 25, 50, 100, 500, 1000]
let images = [UIImage(named: "cluster_10")!, UIImage(named: "cluster_25")!, UIImage(named: "cluster_50")!, UIImage(named: "cluster_100")!, UIImage(named: "cluster_500")!, UIImage(named: "cluster_1000")!]
// Set up the cluster manager with default icon generator and renderer.
let iconGenerator = GMUDefaultClusterIconGenerator(buckets: numbers, backgroundImages: images)
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)
renderer.delegate = self
// Generate and add random items to the cluster manager.
generateClusterItems()
// Call cluster() after items have been added to perform the clustering and rendering on map.
clusterManager.cluster()
// Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
clusterManager.setDelegate(self, mapDelegate: self)
}
// MARK: - Private
/// Randomly generates cluster items within some extent of the camera and adds them to the
/// cluster manager.
private func generateClusterItems()
{
let extent = 0.2
for index in 1...kClusterItemCount
{
let lat = kCameraLatitude + extent * self.randomScale()
let lng = kCameraLongitude + extent * self.randomScale()
let name = "Item \(index)"
let item = POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name)
self.clusterManager.add(item)
}
}
/// Returns a random value between -1.0 and 1.0.
private func randomScale() -> Double
{
return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0
}
}
// MARK: - GMUClusterManagerDelegate
extension ClusteringViewController: GMUClusterManagerDelegate
{
func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool
{
let newCamera = GMSCameraPosition.camera(withTarget: cluster.position, zoom: mapView.camera.zoom + 1)
let update = GMSCameraUpdate.setCamera(newCamera)
mapView.moveCamera(update)
return false
}
}
// MARK: - GMUMapViewDelegate
extension ClusteringViewController: GMSMapViewDelegate
{
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool
{
if let poiItem = marker.userData as? POIItem {
NSLog("Did tap marker for cluster item \(poiItem.name)")
}
else
{
NSLog("Did tap a normal marker")
}
return false
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D)
{
print("LAT: \(coordinate.latitude) - LONG: \(coordinate.longitude)")
//Get Country and State
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(coordinate) { (GMSReverseGeocodeResponse, error) in
let address = GMSReverseGeocodeResponse?.firstResult()//.results()
print(address?.country ?? "none")
print(address?.administrativeArea ?? "none")
}
}
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView?
{
if let _ = marker.userData as? GMUCluster {
//Cluster
return nil
}
else
{
//Location Point
let view = UIView(frame: CGRect(x: marker.accessibilityActivationPoint.x, y: marker.accessibilityActivationPoint.y, width: 100, height: 100))
return view
}
}
}
//MARK: GMUClusterRendererDelegate
extension ClusteringViewController: GMUClusterRendererDelegate
{
func renderer(_ renderer: GMUClusterRenderer, markerFor object: Any) -> GMSMarker
{
let pin = GMSMarker()
pin.icon = UIImage(named: "pin_location")
return pin
}
func renderer(_ renderer: GMUClusterRenderer, willRenderMarker marker: GMSMarker)
{
print("nada")
}
}
|
74bcb6a1c609b4fe8cf4db92243db56c95c48761
|
[
"Markdown",
"Swift"
] | 2
|
Markdown
|
manuel21/GoogleMapsClusters
|
ca53882036906bf72ec79b93079294565a6d0906
|
79f20cd684412403527100bc7613c8af626b1407
|
refs/heads/master
|
<file_sep>const express = require('express')
const app = express()
const path = require('path')
//app.get('/', (req, res) => res.send('Hello World! Version 1.4'))
app.get('/Sho', (req, res) => res.send('Hello Sho in the World of Node-js and Docker!!!!'))
app.get('/Yod', (req, res) => res.send('Hello Yod!!!!'))
app.get('/Yo', (req, res) => res.send('Hello Yo!!!!'))
app.get('/Sho/1', (req, res) => res.send('Hello Sho Yeahhh!!!!'))
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
app.listen(3310 , () => console.log('Example app listening on port 3310!!'))
/*var express = require("express");
var app = express();
var path = require("path");*/
//app.listen(8080);<file_sep># node-tutorial
Use sample
|
138ef59500010a7e5569a42ec22a4414625685bd
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
Shotawat/node-tutorial
|
52ee76895925638cada66a18450604ec7c59a1ff
|
b7f5b673146a22ee2303e4f0f59e181dc555b87c
|
refs/heads/master
|
<repo_name>zacmon/TelescopingJets<file_sep>/Ana_EventGeneration/NTupler.cc
/*----------------------------------------------------------------------
TITLE : NTupler.cc
DESCRIPTION : Takes input final state particle ntuple from Ana_EventGeneration
and outputs a flat ntuple that contains jet properties created via fastjet
in this code to be used for post-analysis using Ana_MiniNTupleAnalysis. (NOTE!!)
All of the TelescopingJets code from the fastjet contrib should be contained within this code
COMPILE :
$ source compile.sh
RUN :
$ ./NTupler <type> <input> <output>
type : 0 = dijet , 1 = G*->W+W- , 2 = ttbar
input : Input file from Ana_MiniNTupleAnalysis
output : Anything you want - but being logical
//----------------------------------------------------------------------*/
#include "NTuplerTest.h"
int main(int argc, char* argv[]){
//exit if you dont pass a run card
if(argc<4){
cout<<"You need to specify more arguments"<<endl;
cout<<"Arg1 = process type"<<endl;
cout<<"Arg2 = input file path and name"<<endl;
cout<<"Arg3 = output file path and name"<<endl;
cout<<"Arg4 = debug flag (optional)"<<endl;
return 1;
}
//process
string ProcessType = argv[1];
//inputfile
string InputFile = argv[2];
//outputfile
string OutputFile = argv[3];
//debug flag
bool debug=false;
if(argc>=5){
string argdebug = argv[4];
if(argdebug=="debug")
debug=true;
}
//print out the input arguments
cout<<"InputArguments: ProcessType="<<ProcessType<<" InputFile="<<InputFile<<" OutputFile="<<OutputFile<<" Debug="<<debug<<endl;
//dR truth matching
dR_match = 1.0;
//////////////////////////////////////////////
//INPUT
//////////////////////////////////////////////
//get input file and tree
filein = new TFile( InputFile.c_str() );
treein = (TTree*)filein->Get( "tree" );
if(debug) treein->Print();
//set up branch linking to addresses
treein->SetBranchAddress("fspart_id", &fspart_id);
treein->SetBranchAddress("fspart_pt", &fspart_pt);
treein->SetBranchAddress("fspart_eta",&fspart_eta);
treein->SetBranchAddress("fspart_phi",&fspart_phi);
treein->SetBranchAddress("fspart_m", &fspart_m);
treein->SetBranchAddress("truth_q1_pt", &truth_q1_pt);
treein->SetBranchAddress("truth_q1_eta", &truth_q1_eta);
treein->SetBranchAddress("truth_q1_phi", &truth_q1_phi);
treein->SetBranchAddress("truth_q1_m", &truth_q1_m);
treein->SetBranchAddress("truth_q2_pt", &truth_q2_pt);
treein->SetBranchAddress("truth_q2_eta", &truth_q2_eta);
treein->SetBranchAddress("truth_q2_phi", &truth_q2_phi);
treein->SetBranchAddress("truth_q2_m", &truth_q2_m);
treein->SetBranchAddress("truth_t1_pt", &truth_t1_pt);
treein->SetBranchAddress("truth_t1_eta", &truth_t1_eta);
treein->SetBranchAddress("truth_t1_phi", &truth_t1_phi);
treein->SetBranchAddress("truth_t1_m", &truth_t1_m);
treein->SetBranchAddress("truth_t2_pt", &truth_t2_pt);
treein->SetBranchAddress("truth_t2_eta", &truth_t2_eta);
treein->SetBranchAddress("truth_t2_phi", &truth_t2_phi);
treein->SetBranchAddress("truth_t2_m", &truth_t2_m);
treein->SetBranchAddress("truth_W1_pt", &truth_W1_pt);
treein->SetBranchAddress("truth_W1_eta", &truth_W1_eta);
treein->SetBranchAddress("truth_W1_phi", &truth_W1_phi);
treein->SetBranchAddress("truth_W1_m", &truth_W1_m);
treein->SetBranchAddress("truth_W2_pt", &truth_W2_pt);
treein->SetBranchAddress("truth_W2_eta", &truth_W2_eta);
treein->SetBranchAddress("truth_W2_phi", &truth_W2_phi);
treein->SetBranchAddress("truth_W2_m", &truth_W2_m);
treein->SetBranchAddress("truth_H_pt", &truth_H_pt);
treein->SetBranchAddress("truth_H_eta", &truth_H_eta);
treein->SetBranchAddress("truth_H_phi", &truth_H_phi);
treein->SetBranchAddress("truth_H_m", &truth_H_m);
//////////////////////////////////////////////
//OUTPUT
//////////////////////////////////////////////
fileout = new TFile( OutputFile.c_str() ,"RECREATE");
treeout = new TTree("JetTree","JetTree");
treeout->Branch("NumberOfVertices", &NumberOfVertices);
treeout->Branch("TruthRaw_flavor", &TruthRaw_flavor);
treeout->Branch("TruthRaw_pt", &TruthRaw_pt);
treeout->Branch("TruthRaw_eta", &TruthRaw_eta);
treeout->Branch("TruthRaw_phi", &TruthRaw_phi);
treeout->Branch("TruthRaw_m", &TruthRaw_m);
treeout->Branch("TruthRaw_Tau21", &TruthRaw_Tau21);
treeout->Branch("TruthRaw_Tau32", &TruthRaw_Tau32);
treeout->Branch("TruthRaw_D2", &TruthRaw_D2);
treeout->Branch("TruthRaw_T1jet_angle", &TruthRaw_T1jet_angle);
treeout->Branch("TruthRaw_T1jet", &TruthRaw_T1jet);
treeout->Branch("TruthRaw_T2jet_angle", &TruthRaw_T2jet_angle);
treeout->Branch("TruthRaw_T2jet", &TruthRaw_T2jet);
treeout->Branch("TruthRaw_T3jet_angle", &TruthRaw_T3jet_angle);
treeout->Branch("TruthRaw_T3jet_angle1", &TruthRaw_T3jet_angle1);
treeout->Branch("TruthRaw_T3jet_angle2", &TruthRaw_T3jet_angle2);
treeout->Branch("TruthRaw_T3jet", &TruthRaw_T3jet);
treeout->Branch("TruthRaw_T3jet_W", &TruthRaw_T3jet_W);
treeout->Branch("TruthRaw_T3jet_mW", &TruthRaw_T3jet_mW);
treeout->Branch("TruthRaw_T4jet_angle", &TruthRaw_T4jet_angle);
treeout->Branch("TruthRaw_T4jet", &TruthRaw_T4jet);
treeout->Branch("TruthRaw_T5jet_angle", &TruthRaw_T5jet_angle);
treeout->Branch("TruthRaw_T5jet", &TruthRaw_T5jet);
treeout->Branch("TruthRaw_Tpruning", &TruthRaw_Tpruning);
treeout->Branch("TruthRaw_Ttrimming", &TruthRaw_Ttrimming);
treeout->Branch("TruthRaw_Taktreclustering", &TruthRaw_Taktreclustering);
treeout->Branch("TruthRaw_Tktreclustering", &TruthRaw_Tktreclustering);
treeout->Branch("TruthRaw_TJet_m1", &TruthRaw_TJet_m1);
treeout->Branch("TruthRaw_TJet_m2", &TruthRaw_TJet_m2);
treeout->Branch("TruthRawTrim_flavor", &TruthRawTrim_flavor);
treeout->Branch("TruthRawTrim_pt", &TruthRawTrim_pt);
treeout->Branch("TruthRawTrim_eta", &TruthRawTrim_eta);
treeout->Branch("TruthRawTrim_phi", &TruthRawTrim_phi);
treeout->Branch("TruthRawTrim_m", &TruthRawTrim_m);
treeout->Branch("TruthRawTrim_Tau21", &TruthRawTrim_Tau21);
treeout->Branch("TruthRawTrim_Tau32", &TruthRawTrim_Tau32);
treeout->Branch("TruthRawTrim_D2", &TruthRawTrim_D2);
treeout->Branch("TruthRawTrim_T1jet_angle", &TruthRawTrim_T1jet_angle);
treeout->Branch("TruthRawTrim_T1jet", &TruthRawTrim_T1jet);
treeout->Branch("TruthRawTrim_T2jet_angle", &TruthRawTrim_T2jet_angle);
treeout->Branch("TruthRawTrim_T2jet", &TruthRawTrim_T2jet);
treeout->Branch("TruthRawTrim_T3jet_angle", &TruthRawTrim_T3jet_angle);
treeout->Branch("TruthRawTrim_T3jet_angle1", &TruthRawTrim_T3jet_angle1);
treeout->Branch("TruthRawTrim_T3jet_angle2", &TruthRawTrim_T3jet_angle2);
treeout->Branch("TruthRawTrim_T3jet", &TruthRawTrim_T3jet);
treeout->Branch("TruthRawTrim_T3jet_W", &TruthRawTrim_T3jet_W);
treeout->Branch("TruthRawTrim_T3jet_mW", &TruthRawTrim_T3jet_mW);
treeout->Branch("TruthRawTrim_T4jet_angle", &TruthRawTrim_T4jet_angle);
treeout->Branch("TruthRawTrim_T4jet", &TruthRawTrim_T4jet);
treeout->Branch("TruthRawTrim_T5jet_angle", &TruthRawTrim_T5jet_angle);
treeout->Branch("TruthRawTrim_T5jet", &TruthRawTrim_T5jet);
treeout->Branch("TruthRawTrim_Tpruning", &TruthRawTrim_Tpruning);
treeout->Branch("TruthRawTrim_Ttrimming", &TruthRawTrim_Ttrimming);
treeout->Branch("TruthRawTrim_Taktreclustering", &TruthRawTrim_Taktreclustering);
treeout->Branch("TruthRawTrim_Tktreclustering", &TruthRawTrim_Tktreclustering);
treeout->Branch("TruthRawTrim_TJet_m1", &TruthRawTrim_TJet_m1);
treeout->Branch("TruthRawTrim_TJet_m2", &TruthRawTrim_TJet_m2);
<<<<<<< HEAD
treeout->Branch("RecoRaw_flavor", &RecoRaw_flavor);
treeout->Branch("RecoRaw_pt", &RecoRaw_pt);
treeout->Branch("RecoRaw_eta", &RecoRaw_eta);
treeout->Branch("RecoRaw_phi", &RecoRaw_phi);
treeout->Branch("RecoRaw_m", &RecoRaw_m);
treeout->Branch("RecoRaw_Tau21", &RecoRaw_Tau21);
treeout->Branch("RecoRaw_Tau32", &RecoRaw_Tau32);
treeout->Branch("RecoRaw_D2", &RecoRaw_D2);
treeout->Branch("RecoRaw_T2jet_angle", &RecoRaw_T2jet_angle);
treeout->Branch("RecoRaw_T2jet", &RecoRaw_T2jet);
treeout->Branch("RecoRaw_T3jet_angle", &RecoRaw_T3jet_angle);
treeout->Branch("RecoRaw_T3jet", &RecoRaw_T3jet);
treeout->Branch("RecoRaw_Tpruning", &RecoRaw_Tpruning);
treeout->Branch("RecoRaw_Ttrimming", &RecoRaw_Ttrimming);
treeout->Branch("RecoRaw_Taktreclustering", &RecoRaw_Taktreclustering);
treeout->Branch("RecoRaw_Tktreclustering", &RecoRaw_Tktreclustering);
treeout->Branch("RecoRaw_TJet_m1", &RecoRaw_TJet_m1);
treeout->Branch("RecoRaw_TJet_m2", &RecoRaw_TJet_m2);
treeout->Branch("RecoRawTrim_flavor", &RecoRawTrim_flavor);
treeout->Branch("RecoRawTrim_pt", &RecoRawTrim_pt);
treeout->Branch("RecoRawTrim_eta", &RecoRawTrim_eta);
treeout->Branch("RecoRawTrim_phi", &RecoRawTrim_phi);
treeout->Branch("RecoRawTrim_m", &RecoRawTrim_m);
treeout->Branch("RecoRawTrim_Tau21", &RecoRawTrim_Tau21);
treeout->Branch("RecoRawTrim_Tau32", &RecoRawTrim_Tau32);
treeout->Branch("RecoRawTrim_D2", &RecoRawTrim_D2);
treeout->Branch("RecoRawTrim_T2jet_angle", &RecoRawTrim_T2jet_angle);
treeout->Branch("RecoRawTrim_T2jet", &RecoRawTrim_T2jet);
treeout->Branch("RecoRawTrim_T3jet_angle", &RecoRawTrim_T3jet_angle);
treeout->Branch("RecoRawTrim_T3jet", &RecoRawTrim_T3jet);
treeout->Branch("RecoRawTrim_Tpruning", &RecoRawTrim_Tpruning);
treeout->Branch("RecoRawTrim_Ttrimming", &RecoRawTrim_Ttrimming);
treeout->Branch("RecoRawTrim_Taktreclustering", &RecoRawTrim_Taktreclustering);
treeout->Branch("RecoRawTrim_Tktreclustering", &RecoRawTrim_Tktreclustering);
treeout->Branch("RecoRawTrim_TJet_m1", &RecoRawTrim_TJet_m1);
treeout->Branch("RecoRawTrim_TJet_m2", &RecoRawTrim_TJet_m2);
=======
>>>>>>> YTedits
//////////////////////////////////////////////
//random number generator for pileup
//////////////////////////////////////////////
TRandom3 *rand_pileup = new TRandom3();
//////////////////////////////////////////////
//main event loop
//////////////////////////////////////////////
// nEvents = treein->GetEntries();
nEvents = 10000;
cout<<"Number of events: "<<nEvents<<endl;
for (Long64_t jentry=0; jentry<nEvents; jentry++) {
if(jentry%10==0)
cout<<"NTupler: ProcessType="<<ProcessType<<" entry="<<jentry<<endl;
//Get next event from input ntuple
filein->cd();
treein->GetEntry(jentry);
/////////////////////////////
//Reset branches for next event
/////////////////////////////
ResetBranches();
///////////////////////////////////////////////////
//read in all final state particles for jet building from pythia input
///////////////////////////////////////////////////
vector<PseudoJet> input_particles;
input_particles.clear();
int n_fspart = fspart_id->size();
for(int i_fspart=0; i_fspart<n_fspart; i_fspart++){
if(debug){
cout<<fspart_id->at(i_fspart)<<" "
<<fspart_pt->at(i_fspart)<<" "
<<fspart_eta->at(i_fspart)<<" "
<<fspart_phi->at(i_fspart)<<" "
<<fspart_m->at(i_fspart)<<" "<<endl;
}
TLorentzVector temp_p4;
temp_p4.SetPtEtaPhiM(fspart_pt ->at(i_fspart),
fspart_eta->at(i_fspart),
fspart_phi->at(i_fspart),
fspart_m ->at(i_fspart));
input_particles.push_back(PseudoJet(temp_p4.Px(),temp_p4.Py(),temp_p4.Pz(),temp_p4.E()));
}
/*
//////////////////////////////////////////////
//make new input particles collection with pileup
//////////////////////////////////////////////
//this will be using min bias events from simulations
vector<PseudoJet> input_particles_Pileup;
input_particles_Pileup.clear();
for(int ipart=0; ipart<n_fspart; ipart++){
input_particles_Pileup.push_back(input_particles.at(ipart));
}
int n_pileup_vertices = (int)rand_pileup->Poisson(10);
int n_particles_per_vertex = 5;
int n_pileup_particles = n_pileup_vertices*n_particles_per_vertex;
NumberOfVertices = n_pileup_vertices;
if(debug) cout<<"Pileup: "<<NumberOfVertices<<" "<<n_particles_per_vertex<<" "<<n_pileup_particles<<endl;
for(int ipart=0; ipart<n_pileup_particles; ipart++){
double m = 0.0;
double px = rand_pileup->Gaus(0,5.0);
double py = rand_pileup->Gaus(0,5.0);
double pz = rand_pileup->Gaus(0,5.0);
double E = pow( m*m + px*px + py*py + pz*pz , 0.5);
if(debug) cout<<"Pileup: "<<ipart<<" "<<px<<" "<<py<<" "<<pz<<" "<<E<<endl;
input_particles_Pileup.push_back(PseudoJet(px,py,pz,E));
}
*/
//////////////////////////////////////////////
//make pseudocalorimeter cells
//////////////////////////////////////////////
vector<PseudoJet> calo_cells = ToyCalorimeter(input_particles);
//vector<PseudoJet> calo_cells_Pileup = ToyCalorimeter(input_particles_Pileup);
//////////////////////////////////////////////
// get the resulting jets ordered in pt
//////////////////////////////////////////////
fastjet::JetDefinition jet_def(fastjet::antikt_algorithm, 1.0);
fastjet::ClusterSequence clust_seq_TruthRaw(input_particles, jet_def);
vector<fastjet::PseudoJet> inclusive_jets_TruthRaw = sorted_by_pt(clust_seq_TruthRaw.inclusive_jets(5.0));
fastjet::ClusterSequence clust_seq_RecoRaw(calo_cells, jet_def);
vector<fastjet::PseudoJet> inclusive_jets_RecoRaw = sorted_by_pt(clust_seq_RecoRaw.inclusive_jets(5.0));
/*
fastjet::ClusterSequence clust_seq_TruthPileup(input_particles_Pileup, jet_def);
vector<fastjet::PseudoJet> inclusive_jets_TruthPileup = sorted_by_pt(clust_seq_TruthPileup.inclusive_jets(5.0));
fastjet::ClusterSequence clust_seq_RecoPileup(calo_cells_Pileup, jet_def);
vector<fastjet::PseudoJet> inclusive_jets_RecoPileup = sorted_by_pt(clust_seq_RecoPileup.inclusive_jets(5.0));
*/
if(debug){
// label the columns
cout<<"jet# pt eta phi mass"<<endl;
cout<<"Inclusive"<<endl;
// print out the details for each jet
for (unsigned int i = 0; i < inclusive_jets_TruthRaw.size(); i++) {
cout<<i<<" "<<inclusive_jets_TruthRaw[i].pt()
<<" "<<inclusive_jets_TruthRaw[i].eta()
<<" "<<inclusive_jets_TruthRaw[i].phi()
<<" "<<inclusive_jets_TruthRaw[i].m()<<endl;
}
}
//////////////////////////////////////////////
//Setup tools for substructure calculation
//////////////////////////////////////////////
//Telescoping jets (this looks like the Telescoping reclustering)
fastjet::contrib::KT_Axes axes_def;
std::vector<double> r_values;
int N_r = 20;
double r_min = 0.1;
double r_max = 0.6;
for(int i=0; i < N_r; i++){
r_values.push_back( r_min+i*(r_max-r_min)/(N_r-1) );
}
TelescopingJets T_Mass(axes_def,r_values);
//Energy correlation functions
fastjet::contrib::EnergyCorrelatorC2 ecfC2(1.);
fastjet::contrib::EnergyCorrelatorD2 ecfD2(1.);
fastjet::contrib::EnergyCorrelatorDoubleRatio ecfC3(2, 1.);
// Filtering with a pt cut as for trimming (arXiv:0912.1342)
double Rfilt0 = 0.3;
double fcut0 = 0.05;
Transformer *trimmer = new Filter(JetDefinition(kt_algorithm, Rfilt0), SelectorPtFractionMin(fcut0) );
const Transformer &f = *trimmer;
/////////////////////////////////////////////
//Get truth objects for truth matching
/////////////////////////////////////////////
truth_q1.SetPtEtaPhiM(truth_q1_pt,truth_q1_eta,truth_q1_phi,truth_q1_m);
truth_q2.SetPtEtaPhiM(truth_q2_pt,truth_q2_eta,truth_q2_phi,truth_q2_m);
truth_t1.SetPtEtaPhiM(truth_t1_pt,truth_t1_eta,truth_t1_phi,truth_t1_m);
truth_t2.SetPtEtaPhiM(truth_t2_pt,truth_t2_eta,truth_t2_phi,truth_t2_m);
truth_W1.SetPtEtaPhiM(truth_W1_pt,truth_W1_eta,truth_W1_phi,truth_W1_m);
truth_W2.SetPtEtaPhiM(truth_W2_pt,truth_W2_eta,truth_W2_phi,truth_W2_m);
truth_H.SetPtEtaPhiM(truth_H_pt,truth_H_eta,truth_H_phi,truth_H_m);
/*
/////////////////////////////
//TruthRaw
/////////////////////////////
if(debug) cout<<"TruthRaw jet"<<endl;
for(int ijet=0; ijet<inclusive_jets_TruthRaw.size(); ijet++){
TLorentzVector jettemp;
jettemp.SetPtEtaPhiM(inclusive_jets_TruthRaw.at(ijet).pt(),
inclusive_jets_TruthRaw.at(ijet).eta(),
inclusive_jets_TruthRaw.at(ijet).phi(),
inclusive_jets_TruthRaw.at(ijet).m());
/////////////////////////////////
//Getting truth label for filling into ntuple
/////////////////////////////////
jetflavor = GetJetTruthFlavor(jettemp, truth_t1, truth_t2, truth_W1, truth_W2, truth_H, debug);
if(debug) cout<<"FillingJet Raw : flav="<<jetflavor<<" pt="<<jettemp.Pt()<<" m="<<jettemp.M()<<endl;
if(jetflavor==-1)
continue;
/////////////////////////////////
//Fill variables that will go into ntuple
/////////////////////////////////
tempJet_flavor = jetflavor;
tempJet_pt = jettemp.Pt();
tempJet_eta = jettemp.Eta();
tempJet_phi = jettemp.Phi();
tempJet_m = jettemp.M();
tempJet_Tau21 = GetTau21(inclusive_jets_TruthRaw[ijet]);
tempJet_Tau32 = GetTau32(inclusive_jets_TruthRaw[ijet]);
// tempJet_D2 = ecfD2(inclusive_jets_TruthRaw[ijet]);
TSub T2SubOutput = T_2Subjet(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
tempJet_T2jet_angle = T2SubOutput.min_angle;
tempJet_T2jet = T2SubOutput.volatility;
TSub T3SubOutput = T_3Subjet(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
tempJet_T3jet_angle = T3SubOutput.min_angle;
tempJet_T3jet = T3SubOutput.volatility;
// TSub T4SubOutput = T_4Subjet(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
// tempJet_T4jet_angle = T4SubOutput.min_angle;
// tempJet_T4jet = T4SubOutput.volatility;
// TSub T5SubOutput = T_5Subjet(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
// tempJet_T5jet_angle = T5SubOutput.min_angle;
// tempJet_T5jet = T5SubOutput.volatility;
tempJet_Tpruning = T_Pruning (inclusive_jets_TruthRaw[ijet], 0.1, 2.0, 20);
tempJet_Ttrimming = T_Trimming(inclusive_jets_TruthRaw[ijet], 0.0, 0.1, 20);
tempJet_Taktreclustering = T_AkTreclustering(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
<<<<<<< HEAD
tempJet_Tktreclustering = T_kTreclustering(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
tempJet_TJet_m1 = T_Mass(1,inclusive_jets_TruthRaw[ijet]);
tempJet_TJet_m2 = T_Mass(2,inclusive_jets_TruthRaw[ijet]);
=======
// tempJet_Tktreclustering = T_kTreclustering(inclusive_jets_TruthRaw[ijet], 0.05, 0.6, 20);
// tempJet_TJet_m1 = T_Mass(1,inclusive_jets_TruthRaw[ijet]);
// tempJet_TJet_m2 = T_Mass(2,inclusive_jets_TruthRaw[ijet]);
// if(tempJet_flavor==-1)
// continue;
>>>>>>> YTedits
TruthRaw_flavor .push_back(tempJet_flavor);
TruthRaw_pt .push_back(tempJet_pt);
TruthRaw_eta .push_back(tempJet_eta);
TruthRaw_phi .push_back(tempJet_phi);
TruthRaw_m .push_back(tempJet_m);
TruthRaw_Tau21 .push_back(tempJet_Tau21);
TruthRaw_Tau32 .push_back(tempJet_Tau32);
// TruthRaw_D2 .push_back(tempJet_D2);
TruthRaw_T2jet_angle.push_back(tempJet_T2jet_angle);
TruthRaw_T2jet .push_back(tempJet_T2jet);
TruthRaw_T3jet_angle.push_back(tempJet_T3jet_angle);
TruthRaw_T3jet .push_back(tempJet_T3jet);
// TruthRaw_T4jet_angle.push_back(tempJet_T4jet_angle);
// TruthRaw_T4jet .push_back(tempJet_T4jet);
// TruthRaw_T5jet_angle.push_back(tempJet_T5jet_angle);
// TruthRaw_T5jet .push_back(tempJet_T5jet);
TruthRaw_Tpruning .push_back(tempJet_Tpruning);
TruthRaw_Ttrimming .push_back(tempJet_Ttrimming);
TruthRaw_Taktreclustering.push_back(tempJet_Taktreclustering);
// TruthRaw_Tktreclustering.push_back(tempJet_Tktreclustering);
// TruthRaw_TJet_m1 .push_back(tempJet_TJet_m1);
// TruthRaw_TJet_m2 .push_back(tempJet_TJet_m2);
}
*/
/////////////////////////////
//TruthRawTrim
/////////////////////////////
for (unsigned int ijet = 0; ijet < inclusive_jets_TruthRaw.size(); ijet++) {
PseudoJet groomed_jet = f(inclusive_jets_TruthRaw[ijet]);
TLorentzVector jettemp;
jettemp.SetPtEtaPhiM(groomed_jet.pt(),
groomed_jet.eta(),
groomed_jet.phi(),
groomed_jet.m());
/////////////////////////////////
//Getting truth label for filling into ntuple
/////////////////////////////////
jetflavor = GetJetTruthFlavor(jettemp, truth_t1, truth_t2, truth_W1, truth_W2, truth_H, debug);
if(debug) cout<<"FillingJet Trimmed: flav="<<jetflavor<<" pt="<<jettemp.Pt()<<" m="<<jettemp.M()<<endl;
<<<<<<< HEAD
if(jetflavor==-1)
continue;
=======
// if(tempJet_flavor==-1)
// continue;
>>>>>>> YTedits
if(jetflavor==-1)
continue;
/////////////////////////////////
//Fill variables that will go into ntuple
/////////////////////////////////
tempJet_flavor = jetflavor;
tempJet_pt = jettemp.Pt();
tempJet_eta = jettemp.Eta();
tempJet_phi = jettemp.Phi();
tempJet_m = jettemp.M();
tempJet_Tau21 = GetTau21(groomed_jet);
tempJet_Tau32 = GetTau32(groomed_jet);
// tempJet_D2 = ecfD2(groomed_jet);
TSub T1SubOutputTrim = T_1Subjet(groomed_jet, 0.1, 0.6, 20);
tempJet_T1jet_angle = T1SubOutputTrim.min_angle;
tempJet_T1jet = T1SubOutputTrim.volatility;
TSub T2SubOutputTrim = T_2Subjet(groomed_jet, 0.1, 0.6, 20);
tempJet_T2jet_angle = T2SubOutputTrim.min_angle;
tempJet_T2jet = T2SubOutputTrim.volatility;
T3Sub T3SubOutputTrim = T_3Subjet(groomed_jet, 0.1, 0.6, 20);
tempJet_T3jet_angle = T3SubOutputTrim.min_angle;
// tempJet_T3jet_angle1 = T3SubOutputTrim.mid_angle;
// tempJet_T3jet_angle2 = T3SubOutputTrim.max_angle;
tempJet_T3jet = T3SubOutputTrim.volatility;
tempJet_T3jet_W = T3SubOutputTrim.mass_W;
tempJet_T3jet_mW = T3SubOutputTrim.volatility_mass_W;
// TSub T4SubOutputTrim = T_4Subjet(groomed_jet, 0.05, 0.6, 20);
// tempJet_T4jet_angle = T4SubOutputTrim.min_angle;
// tempJet_T4jet = T4SubOutputTrim.volatility;
// TSub T5SubOutputTrim = T_5Subjet(groomed_jet, 0.05, 0.6, 20);
// tempJet_T5jet_angle = T5SubOutputTrim.min_angle;
// tempJet_T5jet = T5SubOutputTrim.volatility;
// tempJet_Tpruning = T_Pruning (groomed_jet, 0.1, 2.0, 20);
// tempJet_Ttrimming = T_Trimming(groomed_jet, 0.0, 0.1, 20);
// tempJet_Taktreclustering = T_AkTreclustering(groomed_jet, 0.05, 0.6, 20);
// tempJet_Tktreclustering = T_kTreclustering(groomed_jet, 0.05, 0.6, 20);
// tempJet_TJet_m1 = T_Mass(1,groomed_jet);
// tempJet_TJet_m2 = T_Mass(2,groomed_jet);
TruthRawTrim_flavor .push_back(tempJet_flavor);
TruthRawTrim_pt .push_back(tempJet_pt);
TruthRawTrim_eta .push_back(tempJet_eta);
TruthRawTrim_phi .push_back(tempJet_phi);
TruthRawTrim_m .push_back(tempJet_m);
TruthRawTrim_Tau21 .push_back(tempJet_Tau21);
TruthRawTrim_Tau32 .push_back(tempJet_Tau32);
// TruthRawTrim_D2 .push_back(tempJet_D2);
TruthRawTrim_T1jet_angle.push_back(tempJet_T1jet_angle);
TruthRawTrim_T1jet .push_back(tempJet_T1jet);
TruthRawTrim_T2jet_angle.push_back(tempJet_T2jet_angle);
TruthRawTrim_T2jet .push_back(tempJet_T2jet);
TruthRawTrim_T3jet_angle.push_back(tempJet_T3jet_angle);
// TruthRawTrim_T3jet_angle1.push_back(tempJet_T3jet_angle1);
// TruthRawTrim_T3jet_angle2.push_back(tempJet_T3jet_angle2);
TruthRawTrim_T3jet .push_back(tempJet_T3jet);
TruthRawTrim_T3jet_W .push_back(tempJet_T3jet_W);
TruthRawTrim_T3jet_mW .push_back(tempJet_T3jet_mW);
// TruthRawTrim_T4jet_angle.push_back(tempJet_T4jet_angle);
// TruthRawTrim_T4jet .push_back(tempJet_T4jet);
// TruthRawTrim_T5jet_angle.push_back(tempJet_T5jet_angle);
// TruthRawTrim_T5jet .push_back(tempJet_T5jet);
// TruthRawTrim_Tpruning .push_back(tempJet_Tpruning);
// TruthRawTrim_Ttrimming .push_back(tempJet_Ttrimming);
// TruthRawTrim_Taktreclustering .push_back(tempJet_Taktreclustering);
// TruthRawTrim_Tktreclustering .push_back(tempJet_Tktreclustering);
// TruthRawTrim_TJet_m1 .push_back(tempJet_TJet_m1);
// TruthRawTrim_TJet_m2 .push_back(tempJet_TJet_m2);
}
/////////////////////////////
//RecoRaw
/////////////////////////////
if(debug) cout<<"RecoRaw jet"<<endl;
for(int ijet=0; ijet<inclusive_jets_RecoRaw.size(); ijet++){
TLorentzVector jettemp;
jettemp.SetPtEtaPhiM(inclusive_jets_RecoRaw.at(ijet).pt(),
inclusive_jets_RecoRaw.at(ijet).eta(),
inclusive_jets_RecoRaw.at(ijet).phi(),
inclusive_jets_RecoRaw.at(ijet).m());
/////////////////////////////////
//Getting truth label for filling into ntuple
/////////////////////////////////
jetflavor = GetJetTruthFlavor(jettemp, truth_t1, truth_t2, truth_W1, truth_W2, truth_H, debug);
if(debug) cout<<"FillingJet Raw : flav="<<jetflavor<<" pt="<<jettemp.Pt()<<" m="<<jettemp.M()<<endl;
if(jetflavor==-1)
continue;
/////////////////////////////////
//Fill variables that will go into ntuple
/////////////////////////////////
tempJet_flavor = jetflavor;
tempJet_pt = jettemp.Pt();
tempJet_eta = jettemp.Eta();
tempJet_phi = jettemp.Phi();
tempJet_m = jettemp.M();
tempJet_Tau21 = GetTau21(inclusive_jets_RecoRaw[ijet]);
tempJet_Tau32 = GetTau32(inclusive_jets_RecoRaw[ijet]);
tempJet_D2 = ecfD2(inclusive_jets_RecoRaw[ijet]);
TSub T2SubOutput = T_2Subjet(inclusive_jets_RecoRaw[ijet], 0.05, 0.6, 20);
tempJet_T2jet_angle = T2SubOutput.min_angle;
tempJet_T2jet = T2SubOutput.volatility;
TSub T3SubOutput = T_3Subjet(inclusive_jets_RecoRaw[ijet], 0.05, 0.6, 20);
tempJet_T3jet_angle = T3SubOutput.min_angle;
tempJet_T3jet = T3SubOutput.volatility;
tempJet_Tpruning = T_Pruning (inclusive_jets_RecoRaw[ijet], 0.1, 2.0, 20);
tempJet_Ttrimming = T_Trimming(inclusive_jets_RecoRaw[ijet], 0.0, 0.1, 20);
tempJet_Taktreclustering = T_AkTreclustering(inclusive_jets_RecoRaw[ijet], 0.05, 0.6, 20);
tempJet_Tktreclustering = T_kTreclustering(inclusive_jets_RecoRaw[ijet], 0.05, 0.6, 20);
tempJet_TJet_m1 = T_Mass(1,inclusive_jets_RecoRaw[ijet]);
tempJet_TJet_m2 = T_Mass(2,inclusive_jets_RecoRaw[ijet]);
RecoRaw_flavor .push_back(tempJet_flavor);
RecoRaw_pt .push_back(tempJet_pt);
RecoRaw_eta .push_back(tempJet_eta);
RecoRaw_phi .push_back(tempJet_phi);
RecoRaw_m .push_back(tempJet_m);
RecoRaw_Tau21 .push_back(tempJet_Tau21);
RecoRaw_Tau32 .push_back(tempJet_Tau32);
RecoRaw_D2 .push_back(tempJet_D2);
RecoRaw_T2jet_angle.push_back(tempJet_T2jet_angle);
RecoRaw_T2jet .push_back(tempJet_T2jet);
RecoRaw_T3jet_angle.push_back(tempJet_T3jet_angle);
RecoRaw_T3jet .push_back(tempJet_T3jet);
RecoRaw_Tpruning .push_back(tempJet_Tpruning);
RecoRaw_Ttrimming .push_back(tempJet_Ttrimming);
RecoRaw_Taktreclustering.push_back(tempJet_Taktreclustering);
RecoRaw_Tktreclustering.push_back(tempJet_Tktreclustering);
RecoRaw_TJet_m1 .push_back(tempJet_TJet_m1);
RecoRaw_TJet_m2 .push_back(tempJet_TJet_m2);
}
/////////////////////////////
//RecoRawTrim
/////////////////////////////
for (unsigned int ijet = 0; ijet < inclusive_jets_RecoRaw.size(); ijet++) {
PseudoJet groomed_jet = f(inclusive_jets_RecoRaw[ijet]);
TLorentzVector jettemp;
jettemp.SetPtEtaPhiM(groomed_jet.pt(),
groomed_jet.eta(),
groomed_jet.phi(),
groomed_jet.m());
/////////////////////////////////
//Getting truth label for filling into ntuple
/////////////////////////////////
jetflavor = GetJetTruthFlavor(jettemp, truth_t1, truth_t2, truth_W1, truth_W2, truth_H, debug);
if(debug) cout<<"FillingJet Trimmed: flav="<<jetflavor<<" pt="<<jettemp.Pt()<<" m="<<jettemp.M()<<endl;
if(jetflavor==-1)
continue;
/////////////////////////////////
//Fill variables that will go into ntuple
/////////////////////////////////
tempJet_flavor = jetflavor;
tempJet_pt = jettemp.Pt();
tempJet_eta = jettemp.Eta();
tempJet_phi = jettemp.Phi();
tempJet_m = jettemp.M();
tempJet_Tau21 = GetTau21(groomed_jet);
tempJet_Tau32 = GetTau32(groomed_jet);
tempJet_D2 = ecfD2(groomed_jet);
TSub T2SubOutputTrim = T_2Subjet(groomed_jet, 0.05, 0.6, 20);
tempJet_T2jet_angle = T2SubOutputTrim.min_angle;
tempJet_T2jet = T2SubOutputTrim.volatility;
TSub T3SubOutputTrim = T_3Subjet(groomed_jet, 0.05, 0.6, 20);
tempJet_T3jet_angle = T3SubOutputTrim.min_angle;
tempJet_T3jet = T3SubOutputTrim.volatility;
tempJet_Tpruning = T_Pruning (groomed_jet, 0.1, 2.0, 20);
tempJet_Ttrimming = T_Trimming(groomed_jet, 0.0, 0.1, 20);
tempJet_Taktreclustering = T_AkTreclustering(groomed_jet, 0.05, 0.6, 20);
tempJet_Tktreclustering = T_kTreclustering(groomed_jet, 0.05, 0.6, 20);
tempJet_TJet_m1 = T_Mass(1,groomed_jet);
tempJet_TJet_m2 = T_Mass(2,groomed_jet);
RecoRawTrim_flavor .push_back(tempJet_flavor);
RecoRawTrim_pt .push_back(tempJet_pt);
RecoRawTrim_eta .push_back(tempJet_eta);
RecoRawTrim_phi .push_back(tempJet_phi);
RecoRawTrim_m .push_back(tempJet_m);
RecoRawTrim_Tau21 .push_back(tempJet_Tau21);
RecoRawTrim_Tau32 .push_back(tempJet_Tau32);
RecoRawTrim_D2 .push_back(tempJet_D2);
RecoRawTrim_T2jet_angle.push_back(tempJet_T2jet_angle);
RecoRawTrim_T2jet .push_back(tempJet_T2jet);
RecoRawTrim_T3jet_angle.push_back(tempJet_T3jet_angle);
RecoRawTrim_T3jet .push_back(tempJet_T3jet);
RecoRawTrim_Tpruning .push_back(tempJet_Tpruning);
RecoRawTrim_Ttrimming .push_back(tempJet_Ttrimming);
RecoRawTrim_Taktreclustering .push_back(tempJet_Taktreclustering);
RecoRawTrim_Tktreclustering .push_back(tempJet_Tktreclustering);
RecoRawTrim_TJet_m1 .push_back(tempJet_TJet_m1);
RecoRawTrim_TJet_m2 .push_back(tempJet_TJet_m2);
}
//////////////////////////////////////
//Fill event into tree
//////////////////////////////////////
if(debug) cout<<"Filling Tree"<<endl;
treeout->Fill();
}
/////////////////////////////////
//Write the output TTree to the OutputFile
/////////////////////////////////
fileout->cd();
treeout->Write();
fileout->Close();
return 0;
}
///=========================================
/// Reset Branches
///=========================================
void ResetBranches(){
NumberOfVertices = 0;
TruthRaw_flavor.clear();
TruthRaw_pt.clear();
TruthRaw_eta.clear();
TruthRaw_phi.clear();
TruthRaw_m.clear();
TruthRaw_Tau21.clear();
TruthRaw_Tau32.clear();
TruthRaw_D2.clear();
TruthRaw_T1jet_angle.clear();
TruthRaw_T1jet.clear();
TruthRaw_T2jet_angle.clear();
TruthRaw_T2jet.clear();
TruthRaw_T3jet_angle.clear();
TruthRaw_T3jet_angle1.clear();
TruthRaw_T3jet_angle2.clear();
TruthRaw_T3jet.clear();
TruthRaw_T3jet_W.clear();
TruthRaw_T3jet_mW.clear();
TruthRaw_T4jet_angle.clear();
TruthRaw_T4jet.clear();
TruthRaw_T5jet_angle.clear();
TruthRaw_T5jet.clear();
TruthRaw_Tpruning.clear();
TruthRaw_Ttrimming.clear();
TruthRaw_Taktreclustering.clear();
TruthRaw_Tktreclustering.clear();
TruthRaw_TJet_m1.clear();
TruthRaw_TJet_m2.clear();
TruthRawTrim_flavor.clear();
TruthRawTrim_pt.clear();
TruthRawTrim_eta.clear();
TruthRawTrim_phi.clear();
TruthRawTrim_m.clear();
TruthRawTrim_Tau21.clear();
TruthRawTrim_Tau32.clear();
TruthRawTrim_D2.clear();
TruthRawTrim_T1jet_angle.clear();
TruthRawTrim_T1jet.clear();
TruthRawTrim_T2jet_angle.clear();
TruthRawTrim_T2jet.clear();
TruthRawTrim_T3jet_angle.clear();
TruthRawTrim_T3jet_angle1.clear();
TruthRawTrim_T3jet_angle2.clear();
TruthRawTrim_T3jet.clear();
TruthRawTrim_T3jet_W.clear();
TruthRawTrim_T3jet_mW.clear();
TruthRawTrim_T4jet_angle.clear();
TruthRawTrim_T4jet.clear();
TruthRawTrim_T5jet_angle.clear();
TruthRawTrim_T5jet.clear();
TruthRawTrim_Tpruning.clear();
TruthRawTrim_Ttrimming.clear();
TruthRawTrim_Taktreclustering.clear();
TruthRawTrim_Tktreclustering.clear();
TruthRawTrim_TJet_m1.clear();
TruthRawTrim_TJet_m2.clear();
RecoRaw_flavor.clear();
RecoRaw_pt.clear();
RecoRaw_eta.clear();
RecoRaw_phi.clear();
RecoRaw_m.clear();
RecoRaw_Tau21.clear();
RecoRaw_Tau32.clear();
RecoRaw_D2.clear();
RecoRaw_T2jet_angle.clear();
RecoRaw_T2jet.clear();
RecoRaw_T3jet_angle.clear();
RecoRaw_T3jet.clear();
RecoRaw_Tpruning.clear();
RecoRaw_Ttrimming.clear();
RecoRaw_Taktreclustering.clear();
RecoRaw_Tktreclustering.clear();
RecoRaw_TJet_m1.clear();
RecoRaw_TJet_m2.clear();
RecoRawTrim_flavor.clear();
RecoRawTrim_pt.clear();
RecoRawTrim_eta.clear();
RecoRawTrim_phi.clear();
RecoRawTrim_m.clear();
RecoRawTrim_Tau21.clear();
RecoRawTrim_Tau32.clear();
RecoRawTrim_D2.clear();
RecoRawTrim_T2jet_angle.clear();
RecoRawTrim_T2jet.clear();
RecoRawTrim_T3jet_angle.clear();
RecoRawTrim_T3jet.clear();
RecoRawTrim_Tpruning.clear();
RecoRawTrim_Ttrimming.clear();
RecoRawTrim_Taktreclustering.clear();
RecoRawTrim_Tktreclustering.clear();
RecoRawTrim_TJet_m1.clear();
RecoRawTrim_TJet_m2.clear();
}
///=========================================
/// Calorimeter Simulation
///=========================================
vector<PseudoJet> ToyCalorimeter(vector<PseudoJet> truth_particles) {
const double pi = 3.14159265359;
const double etaLim = 5.0;
const int nEta = 100;
const int nPhi = 63;
double dEta = 2*etaLim/nEta;
double dPhi = 2*pi/nPhi;
double tower[nEta][nPhi];
for (int i = 0; i < nEta; i++) for (int j = 0; j < nPhi; j++) tower[i][j] = -0.001;
vector<fastjet::PseudoJet> cell_particles;
for (int p = 0; p < (int)truth_particles.size(); p++) {
fastjet::PseudoJet part = truth_particles.at(p);
int etaCell = int((part.eta()+etaLim)/dEta);
int phiCell = int(part.phi()/dPhi);
if (etaCell >= 0 && etaCell < nEta && phiCell >=0 && phiCell < nPhi){
tower[etaCell][phiCell] += part.e();
}
}
for (int i = 0; i < nEta; i++) for (int j = 0; j < nPhi; j++) {
if (tower[i][j] > 0) {
double etaLocal = -etaLim + dEta*(i+0.5);
double phiLocal = dPhi*(j+0.5);
double thetaLocal = 2*atan(exp(-etaLocal));
cell_particles.push_back(fastjet::PseudoJet(sin(thetaLocal)*cos(phiLocal),sin(thetaLocal)*sin(phiLocal),cos(thetaLocal),1)*tower[i][j]);
}
}
return cell_particles;
}
///=========================================
/// Telescoping Pruning
///=========================================
double T_Pruning(PseudoJet& input, double dcut_min, double dcut_max, int N_dcut) {
<<<<<<< HEAD
double zcut = 0.1; // single choice of zcut. can be further telescoped
double Tmass = 0;
vector<double> ms; ms.clear();
for (int i = 0; i < N_dcut; i++){
double dcut = dcut_min + (dcut_max-dcut_min)*i/(N_dcut-1);
fastjet::Pruner pruner(fastjet::cambridge_algorithm, zcut, dcut);
fastjet::PseudoJet pruned_jet = pruner(input);
Tmass = pruned_jet.m();
if(Tmass > M0){ms.push_back(Tmass);}
}
// getVolatility function provided by TelescopingJets
if(ms.size()>0) return getVolatility(ms);
std::cout << "WARNING: zero entries for T_Pruning "<<dcut_min<<" "<<dcut_max<<" "<<N_dcut<<std::endl;
return -1;
=======
double zcut = 0.1; // single choice of zcut. can be further telescoped
double Tmass = 0;
vector<double> ms; ms.clear();
for (int i = 0; i < N_dcut; i++){
double dcut = dcut_min + (dcut_max-dcut_min)*i/(N_dcut-1);
fastjet::Pruner pruner(fastjet::cambridge_algorithm, zcut, dcut);
fastjet::PseudoJet pruned_jet = pruner(input);
Tmass = pruned_jet.m();
if(Tmass > M0){ms.push_back(Tmass);}
}
// getVolatility function provided by TelescopingJets
if(ms.size()>0)
return getVolatility(ms);
std::cout <<"WARNING: zero entries for T_Pruning "<< dcut_min <<" "<< dcut_max <<" "<< N_dcut <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///=========================================
/// Telescoping Trimming
///=========================================
double T_Trimming(PseudoJet& input, double fcut_min, double fcut_max, int N_fcut) {
<<<<<<< HEAD
double Rfilt = 0.1; // single choice of Rfilt. can be further telescoped.
// used Rfilt = 0.1 for higher pT jets and Rfilt = 0.2 for lower pT jets.
double Tmass = 0;
vector<double> ms; ms.clear();
for (int i = 0; i < N_fcut; i++){
double fcut = fcut_min + (fcut_max-fcut_min)*i/(N_fcut-1);
fastjet::Filter trimmer(Rfilt,fastjet::SelectorPtFractionMin(fcut));
fastjet::PseudoJet trimmed_jet = trimmer(input);
Tmass = trimmed_jet.m();
if(Tmass > M0){ms.push_back(Tmass);}
}
// getVolatility function provided by TelescopingJets
if(ms.size()>0) return getVolatility(ms);
std::cout << "WARNING: zero entries for T_Trimming "<<fcut_min<<" "<<fcut_max<<" "<<N_fcut<<std::endl;
return -1;
=======
double Rfilt = 0.1; // single choice of Rfilt. can be further telescoped.
// used Rfilt = 0.1 for higher pT jets and Rfilt = 0.2 for lower pT jets.
double Tmass = 0;
vector<double> ms; ms.clear();
for (int i = 0; i < N_fcut; i++){
double fcut = fcut_min + (fcut_max-fcut_min)*i/(N_fcut-1);
fastjet::Filter trimmer(Rfilt,fastjet::SelectorPtFractionMin(fcut));
fastjet::PseudoJet trimmed_jet = trimmer(input);
Tmass = trimmed_jet.m();
if(Tmass > M0){ms.push_back(Tmass);}
}
// getVolatility function provided by TelescopingJets
if(ms.size()>0)
return getVolatility(ms);
std::cout <<"WARNING: zero entries for T_Trimming "<< fcut_min <<" "<< fcut_max <<" "<< N_fcut <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///=========================================
/// Telescoping Anti-kT reclustering
///=========================================
double T_AkTreclustering(PseudoJet& input, double R_min, double R_max, int N_R) {
vector<double> ms;
double Tmass = 0;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
// used R_min = 0.05 for higher pT jets and R_min = 0.1 for lower pT jets.
for(int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
fastjet::JetDefinition Tjet_def(fastjet::antikt_algorithm, R);
fastjet::ClusterSequence Tcs(input.constituents(), Tjet_def);
vector<fastjet::PseudoJet> recoTjets = sorted_by_pt(Tcs.inclusive_jets());
if(recoTjets.size() < 1) {
std::cout <<"Warning: recluster number of subjet is "<< recoTjets.size() << std::endl;
continue;
}
if(recoTjets.size() == 1){
Tsubjet1.SetPxPyPzE(recoTjets[0].px(),recoTjets[0].py(),recoTjets[0].pz(),recoTjets[0].e());
Tmass = Tsubjet1.M();
if(Tmass > M0){ms.push_back(Tmass);}
}
else if(recoTjets.size() >= 2){
Tsubjet1.SetPxPyPzE(recoTjets[0].px(),recoTjets[0].py(),recoTjets[0].pz(),recoTjets[0].e());
Tsubjet2.SetPxPyPzE(recoTjets[1].px(),recoTjets[1].py(),recoTjets[1].pz(),recoTjets[1].e());
Tmass = (Tsubjet1+Tsubjet2).M();
if(Tmass > M0){ms.push_back(Tmass);}
}
R += deltaR;
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(ms.size()>0) return getVolatility(ms);
std::cout << "WARNING: zero entries for T_AkTreclustering "<<R_min<<" "<<R_max<<" "<<N_R<<std::endl;
return -1;
=======
if(ms.size()>0)
return getVolatility(ms);
std::cout <<"WARNING: zero entries for T_AkTreclustering "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///=========================================
/// Telescoping kT reclustering
///=========================================
double T_kTreclustering(PseudoJet& input, double R_min, double R_max, int N_R) {
vector<double> ms;
double Tmass = 0;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for(int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
fastjet::JetDefinition Tjet_def(fastjet::kt_algorithm, R);
fastjet::ClusterSequence Tcs(input.constituents(), Tjet_def);
vector<fastjet::PseudoJet> recoTjets = sorted_by_pt(Tcs.inclusive_jets());
if(recoTjets.size() < 1) {
std::cout <<"Warning: recluster number of subjet is "<< recoTjets.size() << std::endl;
continue;
}
if(recoTjets.size() == 1){
Tsubjet1.SetPxPyPzE(recoTjets[0].px(),recoTjets[0].py(),recoTjets[0].pz(),recoTjets[0].e());
Tmass = Tsubjet1.M();
if(Tmass > M0){ms.push_back(Tmass);}
}
else if(recoTjets.size() >= 2){
Tsubjet1.SetPxPyPzE(recoTjets[0].px(),recoTjets[0].py(),recoTjets[0].pz(),recoTjets[0].e());
Tsubjet2.SetPxPyPzE(recoTjets[1].px(),recoTjets[1].py(),recoTjets[1].pz(),recoTjets[1].e());
Tmass = (Tsubjet1+Tsubjet2).M();
if(Tmass > M0){ms.push_back(Tmass);}
}
R += deltaR;
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(ms.size()>0) return getVolatility(ms);
std::cout << "WARNING: zero entries for T_kTreclustering "<<R_min<<" "<<R_max<<" "<<N_R<<std::endl;
return -1;
=======
if(ms.size()>0)
return getVolatility(ms);
std::cout <<"WARNING: zero entries for T_kTreclustering "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///=========================================
/// Telescoping Subjet
///=========================================
TSub T_1Subjet(PseudoJet& input, double R_min, double R_max, int N_R){
vector<double> ms;
double beta = 1.0;
double Tmass = 0;
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nSub(1, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
double tau1 = nSub.result(input);
std::vector<fastjet::PseudoJet> tau1axes = nSub.currentAxes();
tau_axis1.SetPxPyPzE(tau1axes[0].px(),tau1axes[0].py(),tau1axes[0].pz(),tau1axes[0].e());
double D_min = tau_axis1.DeltaR(tau_axis1);
double d1;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for (int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
Tsubjet1.SetPxPyPzE(0,0,0,0);
for (unsigned int c = 0; c < input.constituents().size(); c++) {
particle.SetPxPyPzE(input.constituents()[c].px(),input.constituents()[c].py(),input.constituents()[c].pz(),input.constituents()[c].e());
d1 = particle.DeltaR(tau_axis1);
if (d1 <= R){
Tsubjet1 = Tsubjet1 + particle;
}
}
Tmass = Tsubjet1.M();
if(Tmass > M0){ms.push_back(Tmass);}
R += deltaR;
}
TSub result;
result.min_angle = D_min;
if(ms.size()>0) {
result.volatility = getVolatility(ms);
}else{
std::cout <<"WARNING: zero entries for T_1Subjet "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
result.volatility=-1;
}
return result;
}
TSub T_2Subjet(PseudoJet& input, double R_min, double R_max, int N_R){
vector<double> m12s;
double beta = 1.0;
double Tmass = 0;
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nSub(2, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
double tau2 = nSub.result(input);
std::vector<fastjet::PseudoJet> tau2axes = nSub.currentAxes();
tau_axis1.SetPxPyPzE(tau2axes[0].px(),tau2axes[0].py(),tau2axes[0].pz(),tau2axes[0].e());
tau_axis2.SetPxPyPzE(tau2axes[1].px(),tau2axes[1].py(),tau2axes[1].pz(),tau2axes[1].e());
double D_min = tau_axis1.DeltaR(tau_axis2);
double d1,d2;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for (int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
Tsubjet1.SetPxPyPzE(0,0,0,0);
Tsubjet2.SetPxPyPzE(0,0,0,0);
for (unsigned int c = 0; c < input.constituents().size(); c++) {
particle.SetPxPyPzE(input.constituents()[c].px(),input.constituents()[c].py(),input.constituents()[c].pz(),input.constituents()[c].e());
d1 = particle.DeltaR(tau_axis1);
d2 = particle.DeltaR(tau_axis2);
if (d1 <= R && d1 < d2 ){
Tsubjet1 = Tsubjet1 + particle;
}
else if (d2 <= R && d2 < d1 ){
Tsubjet2 = Tsubjet2 + particle;
}
}
Tmass = (Tsubjet1 + Tsubjet2).M();
if(Tmass > M0){m12s.push_back(Tmass);}
R += deltaR;
}
<<<<<<< HEAD
TSub result;
result.min_angle = D_min;
if(m12s.size()>0) result.volatility = getVolatility(m12s);
else {
result.volatility = -1;
std::cout << "WARNING: zero entries for T_2Subjet "<<R_min<<" "<<R_max<<" "<<N_R<<std::endl;
}
return result;
=======
TSub result;
result.min_angle = D_min;
if(m12s.size()>0) {
result.volatility = getVolatility(m12s);
}else{
std::cout <<"WARNING: zero entries for T_2Subjet "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
result.volatility=-1;
}
return result;
>>>>>>> YTedits
}
T3Sub T_3Subjet(PseudoJet& input, double R_min, double R_max, int N_R){
vector<double> m123s; m123s.clear();
vector<double> m12s; m12s.clear();
vector<double> m13s; m13s.clear();
vector<double> m23s; m23s.clear();
// m123 is the invariant mass of the three subjets
double beta = 1.0;
double Tmass = 0;
double Tmass_12 = 0;
double Tmass_13 = 0;
double Tmass_23 = 0;
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nSub(3, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
double tau3 = nSub.result(input);
std::vector<fastjet::PseudoJet> tau3axes = nSub.currentAxes();
tau_axis1.SetPxPyPzE(tau3axes[0].px(),tau3axes[0].py(),tau3axes[0].pz(),tau3axes[0].e());
tau_axis2.SetPxPyPzE(tau3axes[1].px(),tau3axes[1].py(),tau3axes[1].pz(),tau3axes[1].e());
tau_axis3.SetPxPyPzE(tau3axes[2].px(),tau3axes[2].py(),tau3axes[2].pz(),tau3axes[2].e());
double tau3_D12 = tau_axis1.DeltaR(tau_axis2);
double tau3_D13 = tau_axis1.DeltaR(tau_axis3);
double tau3_D23 = tau_axis2.DeltaR(tau_axis3);
double D_min = tau3_D12;
double D_mid = tau3_D13;
double D_max = tau3_D23;
double D_temp;
if(D_mid < D_min ) {D_temp = D_min; D_min = D_mid; D_mid = D_temp;}
if(D_max < D_min ) {D_temp = D_min; D_min = D_max; D_max = D_temp;}
if(D_max < D_mid ) {D_temp = D_mid; D_mid = D_max; D_max = D_temp;}
double d1, d2, d3;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for (int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
Tsubjet1.SetPxPyPzE(0,0,0,0);
Tsubjet2.SetPxPyPzE(0,0,0,0);
Tsubjet3.SetPxPyPzE(0,0,0,0);
for (unsigned int c = 0; c < input.constituents().size(); c++) {
particle.SetPxPyPzE(input.constituents()[c].px(),input.constituents()[c].py(),input.constituents()[c].pz(),input.constituents()[c].e());
d1 = particle.DeltaR(tau_axis1);
d2 = particle.DeltaR(tau_axis2);
d3 = particle.DeltaR(tau_axis3);
if (d1 <= R && d1 < d2 && d1 < d3){
Tsubjet1 = Tsubjet1 + particle;
}
else if (d2 <= R && d2 < d1 && d2 < d3){
Tsubjet2 = Tsubjet2 + particle;
}
else if (d3 <= R && d3 < d1 && d3 < d2){
Tsubjet3 = Tsubjet3 + particle;
}
}
Tmass = (Tsubjet1 + Tsubjet2 + Tsubjet3).M();
Tmass_12 = (Tsubjet1 + Tsubjet2).M();
Tmass_13 = (Tsubjet1 + Tsubjet3).M();
Tmass_23 = (Tsubjet2 + Tsubjet3).M();
if(Tmass > M0){m123s.push_back(Tmass);}
if(Tmass_12 > M0){m12s.push_back(Tmass_12);}
if(Tmass_13 > M0){m13s.push_back(Tmass_13);}
if(Tmass_23 > M0){m23s.push_back(Tmass_23);}
R += deltaR;
}
<<<<<<< HEAD
TSub result;
result.min_angle = D_min;
if(m123s.size()>0) result.volatility = getVolatility(m123s);
else {
result.volatility = -1;
std::cout << "WARNING: zero entries for T_3Subjet "<<R_min<<" "<<R_max<<" "<<N_R<<std::endl;
}
return result;
=======
T3Sub result;
result.min_angle = D_min;
result.mid_angle = D_mid;
result.max_angle = D_max;
if(m123s.size() > 0 && m12s.size() > 0 && m13s.size() > 0 && m23s.size() > 0){
result.volatility = getVolatility(m123s);
if ( abs (Tmass_12 - mW) < abs (Tmass_13 - mW) && abs (Tmass_12 - mW) < abs (Tmass_23 - mW)){
result.mass_W = Tmass_12;
result.volatility_mass_W = getVolatility(m12s);
}
else if ( abs (Tmass_13 - mW) < abs (Tmass_12 - mW) && abs (Tmass_13 - mW) < abs (Tmass_23 - mW)){
result.mass_W = Tmass_13;
result.volatility_mass_W = getVolatility(m13s);
}
else if ( abs (Tmass_23 - mW) < abs (Tmass_12 - mW) && abs (Tmass_23 - mW) < abs (Tmass_13 - mW)){
result.mass_W = Tmass_23;
result.volatility_mass_W = getVolatility(m23s);
}
}else{
std::cout <<"WARNING: zero entries for T_3Subjet "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
result.volatility = -1;
}
return result;
}
TSub T_4Subjet(PseudoJet& input, double R_min, double R_max, int N_R){
vector<double> m1234s; m1234s.clear();
// m1234 is the invariant mass of the four subjets
double beta = 1.0;
double Tmass = 0;
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nSub(4, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
double tau4 = nSub.result(input);
std::vector<fastjet::PseudoJet> tau4axes = nSub.currentAxes();
tau_axis1.SetPxPyPzE(tau4axes[0].px(),tau4axes[0].py(),tau4axes[0].pz(),tau4axes[0].e());
tau_axis2.SetPxPyPzE(tau4axes[1].px(),tau4axes[1].py(),tau4axes[1].pz(),tau4axes[1].e());
tau_axis3.SetPxPyPzE(tau4axes[2].px(),tau4axes[2].py(),tau4axes[2].pz(),tau4axes[2].e());
tau_axis4.SetPxPyPzE(tau4axes[3].px(),tau4axes[3].py(),tau4axes[3].pz(),tau4axes[3].e());
double tau4_D12 = tau_axis1.DeltaR(tau_axis2);
double tau4_D13 = tau_axis1.DeltaR(tau_axis3);
double tau4_D14 = tau_axis1.DeltaR(tau_axis4);
double tau4_D23 = tau_axis2.DeltaR(tau_axis3);
double tau4_D24 = tau_axis2.DeltaR(tau_axis4);
double tau4_D34 = tau_axis3.DeltaR(tau_axis4);
double D_min = tau4_D12;
if(tau4_D13 < D_min ) D_min = tau4_D13;
if(tau4_D14 < D_min ) D_min = tau4_D14;
if(tau4_D23 < D_min ) D_min = tau4_D23;
if(tau4_D24 < D_min ) D_min = tau4_D24;
if(tau4_D34 < D_min ) D_min = tau4_D34;
double d1, d2, d3, d4;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for (int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
Tsubjet1.SetPxPyPzE(0,0,0,0);
Tsubjet2.SetPxPyPzE(0,0,0,0);
Tsubjet3.SetPxPyPzE(0,0,0,0);
Tsubjet4.SetPxPyPzE(0,0,0,0);
for (unsigned int c = 0; c < input.constituents().size(); c++) {
particle.SetPxPyPzE(input.constituents()[c].px(),input.constituents()[c].py(),input.constituents()[c].pz(),input.constituents()[c].e());
d1 = particle.DeltaR(tau_axis1);
d2 = particle.DeltaR(tau_axis2);
d3 = particle.DeltaR(tau_axis3);
d4 = particle.DeltaR(tau_axis4);
if (d1 < R && d1 < d2 && d1 < d3 && d1 < d4){
Tsubjet1 = Tsubjet1 + particle;
}
else if (d2 < R && d2 < d1 && d2 < d3 && d2 < d4){
Tsubjet2 = Tsubjet2 + particle;
}
else if (d3 < R && d3 < d1 && d3 < d2 && d3 < d4){
Tsubjet3 = Tsubjet3 + particle;
}
else if (d4 < R && d4 < d1 && d4 < d2 && d4 < d3){
Tsubjet4 = Tsubjet4 + particle;
}
}
Tmass = (Tsubjet1 + Tsubjet2 + Tsubjet3 + Tsubjet4).M();
if(Tmass > M0){m1234s.push_back(Tmass);}
R += deltaR;
}
TSub result;
result.min_angle = D_min;
if(m1234s.size()>0){
result.volatility = getVolatility(m1234s);
}else{
std::cout <<"WARNING: zero entries for T_4Subjet "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
result.volatility = -1;
}
return result;
}
TSub T_5Subjet(PseudoJet& input, double R_min, double R_max, int N_R){
vector<double> m12345s; m12345s.clear();
// m12345 is the invariant mass of the five subjets
double beta = 1.0;
double Tmass = 0;
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nSub(5, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
double tau5 = nSub.result(input);
std::vector<fastjet::PseudoJet> tau5axes = nSub.currentAxes();
tau_axis1.SetPxPyPzE(tau5axes[0].px(),tau5axes[0].py(),tau5axes[0].pz(),tau5axes[0].e());
tau_axis2.SetPxPyPzE(tau5axes[1].px(),tau5axes[1].py(),tau5axes[1].pz(),tau5axes[1].e());
tau_axis3.SetPxPyPzE(tau5axes[2].px(),tau5axes[2].py(),tau5axes[2].pz(),tau5axes[2].e());
tau_axis4.SetPxPyPzE(tau5axes[3].px(),tau5axes[3].py(),tau5axes[3].pz(),tau5axes[3].e());
tau_axis5.SetPxPyPzE(tau5axes[4].px(),tau5axes[4].py(),tau5axes[4].pz(),tau5axes[4].e());
double tau5_D12 = tau_axis1.DeltaR(tau_axis2);
double tau5_D13 = tau_axis1.DeltaR(tau_axis3);
double tau5_D14 = tau_axis1.DeltaR(tau_axis4);
double tau5_D15 = tau_axis1.DeltaR(tau_axis5);
double tau5_D23 = tau_axis2.DeltaR(tau_axis3);
double tau5_D24 = tau_axis2.DeltaR(tau_axis4);
double tau5_D25 = tau_axis2.DeltaR(tau_axis5);
double tau5_D34 = tau_axis3.DeltaR(tau_axis4);
double tau5_D35 = tau_axis3.DeltaR(tau_axis5);
double tau5_D45 = tau_axis4.DeltaR(tau_axis5);
double D_min = tau5_D12;
if(tau5_D13 < D_min ) D_min = tau5_D13;
if(tau5_D14 < D_min ) D_min = tau5_D14;
if(tau5_D15 < D_min ) D_min = tau5_D15;
if(tau5_D23 < D_min ) D_min = tau5_D23;
if(tau5_D24 < D_min ) D_min = tau5_D24;
if(tau5_D25 < D_min ) D_min = tau5_D25;
if(tau5_D34 < D_min ) D_min = tau5_D34;
if(tau5_D35 < D_min ) D_min = tau5_D35;
if(tau5_D45 < D_min ) D_min = tau5_D45;
double d1, d2, d3, d4, d5;
double deltaR = (R_max - R_min)/(N_R-1);
double R = R_min;
for (int i = 0; i < N_R; i++){
// R = R_min + i*deltaR;
Tsubjet1.SetPxPyPzE(0,0,0,0);
Tsubjet2.SetPxPyPzE(0,0,0,0);
Tsubjet3.SetPxPyPzE(0,0,0,0);
Tsubjet4.SetPxPyPzE(0,0,0,0);
Tsubjet5.SetPxPyPzE(0,0,0,0);
for (unsigned int c = 0; c < input.constituents().size(); c++) {
particle.SetPxPyPzE(input.constituents()[c].px(),input.constituents()[c].py(),input.constituents()[c].pz(),input.constituents()[c].e());
d1 = particle.DeltaR(tau_axis1);
d2 = particle.DeltaR(tau_axis2);
d3 = particle.DeltaR(tau_axis3);
d4 = particle.DeltaR(tau_axis4);
d5 = particle.DeltaR(tau_axis5);
if (d1 < R && d1 < d2 && d1 < d3 && d1 < d4 && d1 < d5){
Tsubjet1 = Tsubjet1 + particle;
}
else if (d2 < R && d2 < d1 && d2 < d3 && d2 < d4 && d2 < d5){
Tsubjet2 = Tsubjet2 + particle;
}
else if (d3 < R && d3 < d1 && d3 < d2 && d3 < d4 && d3 < d5){
Tsubjet3 = Tsubjet3 + particle;
}
else if (d4 < R && d4 < d1 && d4 < d2 && d4 < d3 && d4 < d5){
Tsubjet4 = Tsubjet4 + particle;
}
else if (d5 < R && d5 < d1 && d5 < d2 && d5 < d3 && d5 < d4){
Tsubjet5 = Tsubjet5 + particle;
}
}
Tmass = (Tsubjet1 + Tsubjet2 + Tsubjet3 + Tsubjet4 + Tsubjet5).M();
if(Tmass > M0){m12345s.push_back(Tmass);}
R += deltaR;
}
TSub result;
result.min_angle = D_min;
if(m12345s.size()>0){
result.volatility = getVolatility(m12345s);
}else{
std::cout <<"WARNING: zero entries for T_4Subjet "<< R_min <<" "<< R_max <<" "<< N_R <<" "<< std::endl;
result.volatility = -1;
}
return result;
>>>>>>> YTedits
}
///=========================================
/// Telescoping N-subjettiness
///=========================================
double T_Nsubjettiness(int N, PseudoJet& input, double beta_min, double beta_max, int N_beta) {
vector<double> taus; taus.clear();
for (int i = 0; i < N_beta; i++) {
double beta = beta_min + i*(beta_max - beta_min)/(N_beta-1);
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nsub(N, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
// fastjet::contrib::Nsubjettiness nsub(N, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
taus.push_back(nsub(input));
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(taus.size()>0) return getVolatility(taus);
std::cout << "WARNING: zero entries for T_Nsubjettiness "<<beta_min<<" "<<beta_max<<" "<<N_beta<<std::endl;
return -1;
=======
if(taus.size()>0)
return getVolatility(taus);
std::cout <<"WARNING: zero entries for T_Nsubjettiness "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
double T_NsubjettinessRatio(int N_num, int N_den, PseudoJet& input, double beta_min, double beta_max, int N_beta) {
vector<double> taus; taus.clear();
for (int i = 0; i < N_beta; i++) {
double beta = beta_min + i*(beta_max - beta_min)/(N_beta-1);
fastjet::contrib::UnnormalizedMeasure nsubMeasure(beta);
fastjet::contrib::Nsubjettiness nsub_num(N_num, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
fastjet::contrib::Nsubjettiness nsub_den(N_den, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
double num=nsub_num(input);
double den=nsub_den(input);
if(den!=0)
taus.push_back(num/den);
else
taus.push_back(-1.0);
}
<<<<<<< HEAD
// getVolatility function provided by TelescopingJets
if(taus.size()>0) return getVolatility(taus);
std::cout << "WARNING: zero entries for T_NsubjettinessRatio "<<beta_min<<" "<<beta_max<<" "<<N_beta<<std::endl;
return -1;
=======
if(taus.size()==0){
std::cout <<"WARNING: zero entries for T_NsubjetinessRatio "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
}
// getVolatility function provided by TelescopingJets
if(taus.size()>0)
return getVolatility(taus);
std::cout <<"WARNING: zero entries for T_NsubjettinessRatio "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///=========================================
/// Telescoping Energy Correlators
///=========================================
double T_EnergyCorrelator_C2(PseudoJet& input, double beta_min, double beta_max, int N_beta) {
vector<double> ecfs; ecfs.clear();
for (int i = 0; i < N_beta; i++) {
double beta = beta_min + i*(beta_max - beta_min)/(N_beta-1);
fastjet::contrib::EnergyCorrelatorC2 ecf(beta);
ecfs.push_back(ecf(input));
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(ecfs.size()>0) return getVolatility(ecfs);
std::cout << "WARNING: zero entries for T_EnergyCorrelator_C2 "<<beta_min<<" "<<beta_max<<" "<<N_beta<<std::endl;
return -1;
=======
if(ecfs.size()>0)
return getVolatility(ecfs);
std::cout <<"WARNING: zero entries for T_EnergyCorrelator_C2 "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
double T_EnergyCorrelator_D2(PseudoJet& input, double beta_min, double beta_max, int N_beta) {
vector<double> ecfs; ecfs.clear();
for (int i = 0; i < N_beta; i++) {
double beta = beta_min + i*(beta_max - beta_min)/(N_beta-1);
fastjet::contrib::EnergyCorrelatorD2 ecf(beta);
ecfs.push_back(ecf(input));
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(ecfs.size()>0) return getVolatility(ecfs);
std::cout << "WARNING: zero entries for T_EnergyCorrelator_D2 "<<beta_min<<" "<<beta_max<<" "<<N_beta<<std::endl;
return -1;
=======
if(ecfs.size()>0)
return getVolatility(ecfs);
std::cout <<"WARNING: zero entries for T_EnergyCorrelator_C2 "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
double T_EnergyCorrelator_C3(PseudoJet& input, double beta_min, double beta_max, int N_beta) {
vector<double> ecfs; ecfs.clear();
for (int i = 0; i < N_beta; i++) {
double beta = beta_min + i*(beta_max - beta_min)/(N_beta-1);
fastjet::contrib::EnergyCorrelatorDoubleRatio ecf(3, beta);
ecfs.push_back(ecf(input));
}
// getVolatility function provided by TelescopingJets
<<<<<<< HEAD
if(ecfs.size()>0) return getVolatility(ecfs);
std::cout << "WARNING: zero entries for T_EnergyCorrelator_C3 "<<beta_min<<" "<<beta_max<<" "<<N_beta<<std::endl;
return -1;
=======
if(ecfs.size()>0)
return getVolatility(ecfs);
std::cout <<"WARNING: zero entries for T_EnergyCorrelator_C3 "<< beta_min <<" "<< beta_max <<" "<< N_beta <<" "<< std::endl;
return -1;
>>>>>>> YTedits
}
///========================================
int GetJetTruthFlavor(TLorentzVector jettemp,
TLorentzVector truth_t1,
TLorentzVector truth_t2,
TLorentzVector truth_W1,
TLorentzVector truth_W2,
TLorentzVector truth_H,
int debug){
if(debug){
cout<<"DeltaR: "<<endl
<<"dRMatch: "<<dR_match<<endl
<<"q1: "<<jettemp.DeltaR(truth_q1)<<endl
<<"q2: "<<jettemp.DeltaR(truth_q2)<<endl
<<"W1: "<<jettemp.DeltaR(truth_W1)<<endl
<<"W2: "<<jettemp.DeltaR(truth_W2)<<endl
<<"H: "<<jettemp.DeltaR(truth_H)<<endl
<<"t1: "<<jettemp.DeltaR(truth_t1)<<endl
<<"t2: "<<jettemp.DeltaR(truth_t2)<<endl;
}
int jetflavor = -1;
if (jettemp.DeltaR(truth_q1)<dR_match || jettemp.DeltaR(truth_q2)<dR_match){
jetflavor = 0;
}
else if(jettemp.DeltaR(truth_W1)<dR_match || jettemp.DeltaR(truth_W2)<dR_match){
jetflavor = 1;
}
else if(jettemp.DeltaR(truth_t1)<dR_match || jettemp.DeltaR(truth_t2)<dR_match){
jetflavor = 3;
}
else if(jettemp.DeltaR(truth_H)<dR_match){
jetflavor = 3;
}
else{
jetflavor = -1;
}
if(debug) cout<<"Found jet truth flavor: "<<jetflavor<<endl;
return jetflavor;
}
double GetTau21(PseudoJet& input){
float tau21=-1;
//N-subjettiness
fastjet::contrib::UnnormalizedMeasure nsubMeasure(1.);
fastjet::contrib::Nsubjettiness nsub1(1, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
fastjet::contrib::Nsubjettiness nsub2(2, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
// fastjet::contrib::Nsubjettiness nsub1(1, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
// fastjet::contrib::Nsubjettiness nsub2(2, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
float tau1 = nsub1(input);
float tau2 = nsub2(input);
if(tau1>0)
tau21 = tau2/tau1;
return tau21;
}
double GetTau32(PseudoJet& input){
float tau32=-1;
//N-subjettiness
fastjet::contrib::UnnormalizedMeasure nsubMeasure(1.);
fastjet::contrib::Nsubjettiness nsub2(2, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
fastjet::contrib::Nsubjettiness nsub3(3, fastjet::contrib::OnePass_KT_Axes(), nsubMeasure);
// fastjet::contrib::Nsubjettiness nsub2(2, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
// fastjet::contrib::Nsubjettiness nsub3(3, fastjet::contrib::WTA_KT_Axes(), nsubMeasure);
float tau2 = nsub2(input);
float tau3 = nsub3(input);
if(tau2>0)
tau32 = tau3/tau2;
return tau32;
}
<file_sep>/Ana_EventGeneration/compile_pythia.sh
#! #!/usr/bin/env bash
export PYTHIAPATH=/Users/zacmon/Research/pythia8226
echo
echo "Compiling with : "
echo "$ROOTSYS : "${ROOTSYS}
echo "$PYTHIAPATH : "${PYTHIAPATH}
echo
g++ MakeNTupleFromPythia.cc $PYTHIAPATH/lib/libpythia8.a -o MakeNTupleFromPythia.exe -I$ROOTSYS/include/root -I $PYTHIAPATH/include -rpath $ROOTSYS/lib `$ROOTSYS/bin/root-config --glibs` -std=c++11
|
77b8fa06d94ad57b32b75f5d10d40c6ebb064d02
|
[
"C++",
"Shell"
] | 2
|
C++
|
zacmon/TelescopingJets
|
26231920e0139ed0cb72b7eac269b407b709de43
|
4c06599c2349bf9cbc54c6c5a1cd33054e4e6a49
|
refs/heads/master
|
<file_sep>import io.reactivex.Observable
fun main() {
val source: Observable<String> = Observable.create {
try {
it.onNext("Alpha")
it.onNext("Beta")
it.onNext("Gamma")
it.onNext("Delta")
it.onNext("Epsilon")
it.onComplete()
} catch (e: Throwable) {
it.onError(e)
}
}
source.map {
it.length
}.filter {
it >= 5
}.subscribe {
println("received: $it")
}
}
fun main2() {
val source: Observable<String> = Observable.create {
try {
it.onNext("Alpha")
it.onNext("Beta")
it.onNext("Gamma")
it.onNext("Delta")
it.onNext("Epsilon")
it.onComplete()
} catch (e: Throwable) {
it.onError(e)
}
}
val lengths: Observable<Int> = source.map { it.length }
val filtered: Observable<Int> = lengths.filter { it >= 5 }
filtered.subscribe {
println("filtered: $it, ")
}
source.subscribe {
println("source: $it, ")
}
lengths.subscribe {
println("lenghts: $it")
}
}<file_sep>import io.reactivex.Observable
import io.reactivex.Scheduler
import java.util.concurrent.TimeUnit
fun main() {
val secondIntervals: Observable<Long> = Observable.interval(1, TimeUnit.SECONDS)
secondIntervals.subscribe {
println(it)
}
secondIntervals
.delay(2, TimeUnit.SECONDS)
.subscribe {
println("- $it")
}
sleep(6500)
}
fun sleep(millis: Long) {
try {
Thread.sleep(millis)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}<file_sep>package combining_observables.merging.merge_and_merge_with;
import io.reactivex.Observable;
import java.util.Arrays;
import java.util.List;
public class Launcher3 {
public static void main(String[] args) {
Observable<String> source1 = Observable.just("Alpha", "Beta");
Observable<String> source2 = Observable.just("Gamma", "Delta");
Observable<String> source3 = Observable.just("Epsilon", "Zeta");
Observable<String> source4 = Observable.just("Eta", "Theta");
Observable<String> source5 = Observable.just("Iota", "Kappa");
List<Observable<String>> sources = Arrays.asList(source1, source2, source3, source4, source5);
Observable
.merge(sources)
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}
<file_sep>import io.reactivex.Observable
import java.util.concurrent.TimeUnit
fun main() {
val myStrings: Observable<String> = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
myStrings
.doOnTerminate {
println("do Onterminate")
}
.doOnNext {
println("doOnnext: $it")
}
.doOnComplete {
println("doOncomplet")
}
.map {
it.length
}
.map {
it.plus(it).equals(10)
}
.subscribe {
println(it)
}
}
<file_sep>package Maybe;
import io.reactivex.Maybe;
public class Launcher {
public static void main(String[] args) {
// has emission
Maybe<Integer> presentSource = Maybe.just(100);
presentSource.subscribe(s -> System.out.println("Process 1 received: " + s),
Throwable::printStackTrace,
() -> System.out.println("Process 1 done!"));
//no emission
Maybe<Integer> emptySource = Maybe.empty();
emptySource.subscribe(s -> System.out.println("Process 2 received: " + s),
Throwable::printStackTrace,
() -> System.out.println("Process 2 done!"));
}
}
/**
* A given Maybe<T> will only emit 0 or 1 emissions. It will pass the possible emission to onSuccess(), and in either case, it will call onComplete() when done. Maybe.just() can be used to create a Maybe emitting the single item. Maybe.empty() will create a Maybe that yields no emission:
*
* <NAME>. Learning RxJava: Reactive, Concurrent, and responsive applications . Packt Publishing. Kindle Edition.
*/<file_sep>rootProject.name = 'BasicOperators'
<file_sep>package concurrency_parallelization.new_thread;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
public class Launcher1 {
/**
* This may be helpful in cases where you want to create, use, and then destroy a thread immediately so it does not take up memory. But for complex applications generally, you will want to use Schedulers.io() so there is some attempt to reuse threads if possible. You also have to be careful as Schedulers.newThread() can run amok in complex applications (as can Schedulers.io()) and create a high volume of threads, which could crash your application.
*/
public static void main(String[] args) {
Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.subscribeOn(Schedulers.newThread());
}
}
<file_sep>package concurrency_parallelization.io;
public class Launcher1 {
/**
* IO tasks such as reading and writing databases, web requests, and disk storage are less expensive on the CPU and often have idle time waiting for the data to be sent or come back.
*/
public static void main(String[] args) {
/*Database db = Database.from("conn");
Observable<String> customerNames =
db.select("SELECT NAME FROM CUSTOMER");
db.getAs(String.class);
// .subscribeOn(Schedulers.io());
*/
}
//FAKE DB
private static class Database {
public Database() {
}
static Database from(String conn) {
return new Database();
}
static Database select(String queryFake) {
return new Database();
}
static Database getAs(Class clazz) {
return new Database();
}
}
}
<file_sep># RxJava
RxJave code for exercises inside "Learning RxJava: Reactive, Concurrent, and responsive applications" book by <NAME>
<file_sep>package basic_operators.suppressing_operators.distinct_until_change;
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.just(1, 1, 1, 2, 7, 3, 3, 2, 1, 1)
.distinctUntilChanged()
.subscribe(i -> System.out.println("RECEIVED: " + i));
Observable.just("Alpha", "Beta", "Zeta", "Eta", "Gamma",
"Delta")
.distinctUntilChanged(i -> i.length())
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
}
<file_sep>import io.reactivex.Observable
fun main() {
val source: Observable<String> = Observable.create {
it.onNext("Alpha")
it.onNext("Beta")
it.onNext("Gamma")
it.onNext("Delta")
it.onNext("Epsilon")
it.onComplete()
}
source.subscribe{
println("Received: $it")
}
}<file_sep>package multicasting_replaying_caching.subjects.serialized;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
public class Launcher1 {
public static void main(String[] args) {
Subject<String> subject =
PublishSubject.<String>create().toSerialized();
}
}
|
0fbde026b007fa8f3741d7fda901c86fab7a1f51
|
[
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 12
|
Kotlin
|
jclemus91/RxJava
|
51add768e32eddbd7fdd7acd81c332c337d4773d
|
8695984c6faf2240e35d98c5f860f20406e0f761
|
refs/heads/master
|
<repo_name>GaryLeong/processonline<file_sep>/src/main/resources/static/js/search/searchfun.js
let featurelist = document.getElementById('featurelist');
let listDatas;
/**
* 搜索输入框添加回车enter事件
*/
$('#searchInput').keypress(function (event) {
//回车事件
if (event.which === 13) {
//根据ID获取属性数据
var id = $('#searchInput').val();
getObjectByID(id);
}
});
/**
* 监听输入事件,输入为空时清空输入框
*/
$('#searchInput').on('input propertychange', function () {
//获取input 元素,并实时监听用户输入
if ($('#searchInput').val() == null || $('#searchInput').val() == '') {
let innerHtml = "<button disabled=\"\" class=\"no-results-item\" style=\"display: none;\">" +
"<svg class=\"icon pre-text\">" +
"<use xlink:href=\"#iD-icon-alert\"></use></svg>" +
"<span class=\"entity-name\">" +
"在可见地图区域没有结果\n" +
"</span></button>" +
"<button class=\"geocode-item\" style=\"display: none;\">" +
"<div class=\"label\">" +
"<span class=\"entity-name\">" +
"在全球搜索..." +
"</span></div></button>";
featurelist.innerHTML = innerHtml;
}
});
/**
* 根据id获取对象
* @param id
*/
function getObjectByID(id) {
//ajax发送请求
$.ajax({
//请求方式
type: 'get',
//请求的媒体类型
contentType: 'application/json;charset=UTF-8',
//请求地址
url: 'http://192.168.201.71:8080/geoserver/ows?request=getGeom&service=geominfo&version=1.0.0&ObjectID=' + parseInt(id),
//请求成功
success: function (result) {
drawFeaturelist(result);
},
//请求失败,包含具体的错误信息
error: function (e) {
console.log(e.status);
console.log(e.responseText);
}
}
);
}
/**
* 显示搜索列表
* @param result
*/
function drawFeaturelist(result) {
var obj = JSON.parse(result);
var msg = obj.msg;
if (msg != 'success') {
layuiLayer.open({
title: '提示',
content: '获取图层列表失败'
}
);
return;
}
var datas = obj.data;
var type = '干线道路';
if (datas != null && datas.length > 0) {
listDatas = datas;
}
for (let i = 0, len = listDatas[0].features.length; i < len; i++) {
let objName = listDatas[0].features[i].properties.ObjName;
let OID = listDatas[0].features[i].properties.OID;
let innerHtml = "<button disabled=\"\" class=\"no-results-item\" style=\"display: none;\">" +
"<img src=\"/svg/iD-sprite/icons/icon-alert.svg\" class=\"icon pre-text\">" +
"<span class=\"entity-name\">" +
"在可见地图区域没有结果" +
"</span>" +
"</button>";
innerHtml += "<button class=\"feature-list-item\" style=\"opacity: 1;\" id=\"" + OID + "\" > " +
"<div class=\"label\">" +
"<img src=\"/svg/iD-sprite/icons/icon-line.svg\" class=\"icon pre-text\">" +
"<span class=\"entity-type\">" + type + "</span>" +
"<span class=\"entity-name\">" +
objName +
"</span></div></button>";
innerHtml += "<button class=\"geocode-item\" style=\"display: none;\">" +
"<div class=\"label\">\n" +
"<span class=\"entity-name\">在全球搜索..." +
"</span></div></button>";
featurelist.innerHTML = innerHtml;
}
//添加点击监听事件
$('.feature-list-item').on('click', function () {
featureItemClick($(this)[0].id);
});
}
/**
* 搜索项点击事件-点击定位
* @param element
*/
function featureItemClick(id) {
var itemData = getFeaById(id);
//定位
var coords = itemData.geometry.coordinates[0];
map.getView().setCenter(coords[0]);
}
/**
* 通过id获取feature
* @param id
* @returns {*}
*/
function getFeaById(id) {
for (let i = 0, len = listDatas[0].features.length; i < len; i++) {
if (listDatas[i].features[i].properties.OID == id)
return listDatas[i].features[i];
}
}<file_sep>/src/main/java/com/careland/processonline/service/UserLoginService.java
package com.careland.processonline.service;
import com.careland.processonline.entity.MyUser;
import com.careland.processonline.mapper.MyUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author Administrator
*/
@Service("UserLoginService")
public class UserLoginService {
/**
* 注入dao
*/
@Autowired
private MyUserMapper myUserMapper;
/**
* 用户登录
*
* @param username
* @param password
* @return
*/
public MyUser userLogin(String username, String password) {
MyUser user = myUserMapper.userlogin(username, password);
return user;
}
/**
* 注册新用户
*
* @param username
* @param password
* @param age
* @return
*/
public int adduser(String username, String password, int age) {
return myUserMapper.adduser(username, password, age);
}
/**
* 注册新用户(方式2)
*
* @param username 用户名
* @param password 密码
* @param age 年龄
* @return 注册结果
*/
public int addUser1(String username, String password, int age) {
return myUserMapper.adduser1(username, password, age);
}
}<file_sep>/src/main/java/com/careland/processonline/controller/UserLoginController.java
package com.careland.processonline.controller;
import com.careland.processonline.entity.MyUser;
import com.careland.processonline.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Administrator
*/
@Controller
@RequestMapping(value = {"/user"})
public class UserLoginController {
/**
* 最开始希望用Map的形式接参数,后来不用了,将请求对应的接受方式记录一下
*
* @RequestBody Map<String , Object> map post请求
* @RequestParam Map<String , Object> map get请求
*/
/**
* 注入service
*/
@Autowired
private UserLoginService userLoginService;
/**
* 同时这个时候可以自己了解一下@Controller与@RestController的区别,以及@ResponseBody的用法。
*/
/**
* 跳转到用户登录页面
*
* @return 登录页面
*/
@RequestMapping(value = {"/loginHtml"})
public String loginHtml() {
return "userLogin";
}
/**
* 跳转到用户注册页面
*
* @return 注册页面
*/
@RequestMapping(value = {"/registerpage"})
public String registerpage() {
return "register";
}
/**
* 获取用户名与密码,用户登录
*
* @return 登录成功页面
*/
@ResponseBody
@RequestMapping(value = {"/userLogin"})
public String userLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletRequest request) {
if (StringUtils.isEmpty(username)) {
return "用户名不能为空";
}
if (StringUtils.isEmpty(password)) {
return "密码不能为空";
}
MyUser user = userLoginService.userLogin(username, password);
//登录成功
if (user != null) {
//将用户信息放入session 用于后续的拦截器
request.getSession().setAttribute("session_user", user);
return "登录成功";
}
return "登录失败,用户名或密码错误";
}
/**
* 注册新用户
*
* @return 注册结果
*/
@ResponseBody
@RequestMapping(value = {"/uregister"})
public String addUser(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("password2") String <PASSWORD>,
@RequestParam("age") int age) {
if (StringUtils.isEmpty(username)) {
return "用户名不能为空";
}
if (StringUtils.isEmpty(password)) {
return "密码不能为空";
}
if (StringUtils.isEmpty(password2)) {
return "确认密码不能为空";
}
if (!password.equals(password2)) {
return "两次密码不相同,注册失败!!";
} else {
//int res = userLoginService.adduser(username, password, age);
int res = userLoginService.addUser1(username, password, age);
if (res == 0) {
return "注册失败!";
} else {
return "注册成功!";
}
}
}
}
<file_sep>/src/main/resources/static/js/mouse/mousetip.js
/**
* 放大按钮鼠标移入事件
*/
zoomInBtn.onmouseover = function () {
mouseOverFun(zoomInBtn);
};
/**
* 放大按钮鼠标移开事件
*/
zoomInBtn.onmouseout = function () {
mouseOutFun(zoomInBtn);
};
/**
* 放小按钮鼠标移入事件
*/
zoomOutBtn.onmouseover = function () {
mouseOverFun(zoomOutBtn);
};
/**
* 放小按钮鼠标移开事件
*/
zoomOutBtn.onmouseout = function () {
mouseOutFun(zoomOutBtn);
};
/**
* 位置按钮鼠标移入事件
*/
geolocateBtn.onmouseover = function () {
mouseOverFun(geolocateBtn);
};
/**
* 位置按钮鼠标移开事件
*/
geolocateBtn.onmouseout = function () {
mouseOutFun(geolocateBtn);
};
/**
* 背景按钮鼠标移入事件
*/
setLayersBtn.onmouseover = function () {
mouseOverFun(setLayersBtn);
};
/**
* 背景按钮鼠标移开事件
*/
setLayersBtn.onmouseout = function () {
mouseOutFun(setLayersBtn);
};
/**
* 地图数据按钮鼠标移入事件
*/
setDataBtn.onmouseover = function () {
mouseOverFun(setDataBtn);
};
/**
* 地图数据按钮鼠标移开事件
*/
setDataBtn.onmouseout = function () {
mouseOutFun(setDataBtn);
};
let barBtn = document.getElementById('barBtn');
/**
* 侧边栏按钮鼠标移入事件
*/
barBtn.onmouseover = function () {
mouseOverFun(barBtn);
};
/**
* 侧边栏按钮鼠标移开事件
*/
barBtn.onmouseout = function () {
mouseOutFun(barBtn);
};
/**
* 鼠标移入事件
* @param clickBtn 点击按钮
*/
function mouseOverFun(clickBtn) {
let myDiv = clickBtn.getElementsByTagName('div').item(0);
let className = myDiv.className;
myDiv.className = className + ' in';
}
/**
* 鼠标移出事件
* @param clickBtn 点击按钮
*/
function mouseOutFun(clickBtn) {
let myDiv = clickBtn.getElementsByTagName('div').item(0);
let className = myDiv.className;
//去除class中的in属性
const reg = new RegExp('in');
className = className.replace(reg, '');
className = className.trim();
myDiv.className = className;
}
<file_sep>/src/main/resources/static/libs/ol/layer/GoogleMapLayer.js
goog.provide('ol.layer.GoogleMapLayer');
goog.require('ol.layer.Tile');
goog.require('ol.source.GoogleMapSource');
/**
* @constructor
* @extends {ol.layer.Tile}
* @fires ol.render.Event
* @param opt_options: Layer options.
* @opt_options: extent(图层范围),origin(瓦片原点)默认情况下都不需要赋值,则默认取图层范围的左下角
* @opt_options: layerType(图层类型),默认情况下为"vector"
* @api stable
*/
ol.layer.GoogleMapLayer = function (opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, /** @type {olx.layer.LayerOptions} */(options));
var source = goog.isDef(options.source) ? options.source : null;
if (source == null) {
source = new ol.source.GoogleMapSource(options);
}
this.setSource(source);
};
/**
*
* @param opt_options
* @constructor
*/
ol.layer.GoogleMapLayer = function (opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, /** @type {olx.layer.LayerOptions} */(options));
var source = goog.isDef(options.source) ? options.source : null;
if (source == null) {
source = new ol.source.GoogleMapSource(options);
}
this.setSource(source);
};
goog.inherits(ol.layer.GoogleMapLayer, ol.layer.Tile);<file_sep>/src/main/resources/static/js/locate/locate.js
let coordLocBtn = document.getElementById('coordLocBtn');
coordLocBtn.addEventListener('click', locateByCoord, false);
let closeGeoLocateBtn = document.getElementById('closeGeoLocateBtn');
closeGeoLocateBtn.addEventListener('click', closeGeoLocatePane, false);
/**
* 定位
*/
function locateByCoord() {
let coord = $("#txtCoord").val();
if (coord == "") {
layuiLayer.open({
title: '提示',
content: '请输入坐标'
})
} else {
let myCoord = [parseFloat(coord.split(',')[0]), parseFloat(coord.split(',')[1])];
map.getView().setCenter(myCoord);//设置地图中心点
}
}
/**
* 关闭定位窗口
*/
function closeGeoLocatePane() {
showMapControlClick('geolocatePane', 'geolocateBtn', '');
}<file_sep>/src/main/resources/static/js/mouse/mousekey.js
document.onkeydown = onKeyDown;
/**
* 快捷键事件
*/
function onKeyDown() {
//侧边栏`
if (window.event.keyCode == 192) {
showSidebarClick();
}
//放大键+=
else if (window.event.keyCode == 187) {
zoomIn();
}
//缩小键-_
else if (window.event.keyCode == 189) {
zoomOut();
}
//背景设置B
else if (window.event.keyCode == 66) {
showMapControlClick('backgroundPane', 'setLayersBtn', '');
showMapControlClick('mapDataPane', 'setDataBtn', 'false');
showMapControlClick('geolocatePane', 'geolocateBtn', 'false');
}
//地图数据F
else if (window.event.keyCode == 70) {
showMapControlClick('mapDataPane', 'setDataBtn', '');
showMapControlClick('backgroundPane', 'setLayersBtn', 'false');
showMapControlClick('geolocatePane', 'geolocateBtn', 'false');
}
}
<file_sep>/src/main/resources/static/libs/ol/source/baidumapsource.js
/**
* 加载百度地图
* @returns {ol.layer.Tile}
*/
function loadBaiduMap() {
//数据源信息
var attribution = new ol.control.Attribution({
html: 'Copyright:© 2015 Baidu, i-cubed, GeoEye'
});
//地图范围
var extent = [-20037508.34, -20037508.34, 20037508.34, 20037508.34];
//瓦片大小
var tileSize = 256;
//瓦片参数原点
var origin = [0, 0];
//百度地图在线服务地址
var urlTemplate = "http://online2.map.bdimg.com/tile/?qt=tile&x=" + '{x}' + "&y=" + '{y}' + "&z=" + '{z}' + "&styles=pl&udt=20141219&scaler=1";
//通过范围计算得到地图分辨率数组resolutions
var resolutions = getResolutions(extent, tileSize);
//实例化百度地图数据源
var baiduSource = new ol.source.TileImage({
attributions: [attribution],
tileUrlFunction: function (tileCoord, pixelRatio, projection) {
//判断返回的当前级数的行号和列号是否包含在整个地图范围内
if (this.tileGrid != null) {
var tileRange = this.tileGrid.getTileRangeForExtentAndZ(extent, tileCoord[0], tileRange);
if (!tileRange.contains(tileCoord)) {
return;
}
}
var z = tileCoord[0];
var x = tileCoord[1];
var y = tileCoord[2];
return urlTemplate.replace('{z}', z.toString())
.replace('{y}', y.toString())
.replace('{x}', x.toString());
},
projection: ol.proj.get('EPSG:3857'), //投影坐标系
tileGrid: new ol.tilegrid.TileGrid({
origin: origin, //原点,数组类型,如[0,0],
resolutions: resolutions, //分辨率数组
tileSize: tileSize //瓦片图片大小
})
});
//实例化百度地图瓦片图层
var baiduLayer = new ol.layer.Tile({
source: baiduSource
});
//添加Baidu地图图层
//map.addLayer(baiduLayer);
return baiduLayer;
}
/**
* 加载百度卫星地图
* @returns {ol.layer.Tile}
*/
function loadBaiduMapSate() {
//数据源信息
var attribution = new ol.control.Attribution({
html: 'Copyright:© 2015 Baidu, i-cubed, GeoEye'
});
//地图范围
var extent = [-20037508.34, -20037508.34, 20037508.34, 20037508.34];
//瓦片大小
var tileSize = 256;
//瓦片参数原点
var origin = [0, 0];
//百度地图在线服务地址
var urlTemplate = "https://ss1.bdstatic.com/8bo_dTSlR1gBo1vgoIiO_jowehsv/starpic/?qt=satepc&u=x=" + '{x}' + ";y=" + '{y}' + ";z=" + '{z}' + ";v=009;type=sate&fm=46&app=webearth2&v=009&udt=20190425";
//通过范围计算得到地图分辨率数组resolutions
var resolutions = getResolutions(extent, tileSize);
//实例化百度地图数据源
var baiduSource = new ol.source.TileImage({
attributions: [attribution],
tileUrlFunction: function (tileCoord, pixelRatio, projection) {
//判断返回的当前级数的行号和列号是否包含在整个地图范围内
if (this.tileGrid != null) {
var tileRange = this.tileGrid.getTileRangeForExtentAndZ(extent, tileCoord[0], tileRange);
if (!tileRange.contains(tileCoord)) {
return;
}
}
var z = tileCoord[0];
var x = tileCoord[1];
var y = tileCoord[2];
return urlTemplate.replace('{z}', z.toString())
.replace('{y}', y.toString())
.replace('{x}', x.toString());
},
projection: ol.proj.get('EPSG:3857'), //投影坐标系
tileGrid: new ol.tilegrid.TileGrid({
origin: origin, //原点,数组类型,如[0,0],
resolutions: resolutions, //分辨率数组
tileSize: tileSize //瓦片图片大小
})
});
//实例化百度地图瓦片图层
var baiduLayer = new ol.layer.Tile({
source: baiduSource
});
//map.addLayer(baiduLayer); //添加Baidu地图图层
return baiduLayer;
}
/**
* 通过范围计算得到地图分辨率数组resolutions
* @param extent
* @param tileSize
* @returns {any[]}
*/
function getResolutions(extent, tileSize) {
var width = ol.extent.getWidth(extent);
var height = ol.extent.getHeight(extent);
var maxResolution = (width <= height ? height : width) / (tileSize);//最大分辨率
var resolutions = new Array(16);
var z;
for (var z = 0; z < 16; ++z) {
resolutions[z] = maxResolution / Math.pow(2, z);
}
return resolutions; //返回分辩率数组resolutions
}
/**
* 重新设置地图视图
* @param {ol.Coordinate} center 中心点
* @param {number} zoom 缩放级数
*/
function setMapView(center, zoom) {
var view = map.getView(); //获取地图视图
view.setCenter(center); //平移地图
view.setZoom(zoom); //地图缩放
}
|
0bbafbca20eb59822b0e4a9c918a9b1d89a82c5e
|
[
"JavaScript",
"Java"
] | 8
|
JavaScript
|
GaryLeong/processonline
|
dab5a5d64cb61c14c2e4d77cff36e0da5d57cc7d
|
15721b9644be4a1cf13492f620aa0db7f90c71d4
|
refs/heads/main
|
<repo_name>MasterD98/Boost<file_sep>/Assets/Scenes/Rocket.cs
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Rocket : MonoBehaviour
{
Rigidbody rigidBody;
AudioSource audioSource;
[SerializeField]float rcsThrust =100f;
[SerializeField] float mainThrust = 100f;
[SerializeField] float levelLoadDelay = 2f;
[SerializeField] AudioClip mainEngineAudio;
[SerializeField] AudioClip deathAudio;
[SerializeField] AudioClip successAudio;
[SerializeField] ParticleSystem mainEngineParticles;
[SerializeField] ParticleSystem deathParticles;
[SerializeField] ParticleSystem successParticles;
bool isTransitioning = false;
bool collistionDisable = false;
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
// todo some where stop sound while dead(bug)
if (!isTransitioning) {
ResponseToThrustInput();
ResponseToRotateInput();
}
if (Debug.isDebugBuild) {ResponseToDebugKeys();}
}
private void ResponseToDebugKeys()
{
if (Input.GetKeyDown(KeyCode.C) ) {
collistionDisable = !collistionDisable;
}
if (Input.GetKeyDown(KeyCode.L)) {
LoadNextScene();
}
}
private void OnCollisionEnter(Collision collision)
{
if (isTransitioning || collistionDisable) { return; }
switch (collision.gameObject.tag) {
case "Friendly":
break;
case"Finish":
StartSuccessSequence();
break;
default:
StartDeathSequence();
break;
}
}
private void StartDeathSequence()
{
isTransitioning = true;
if (audioSource.isPlaying) { audioSource.Stop(); }
audioSource.PlayOneShot(deathAudio);
deathParticles.Play();
Invoke("LoadFristLevel", levelLoadDelay);
}
private void StartSuccessSequence()
{
isTransitioning = true;
if (audioSource.isPlaying) { audioSource.Stop(); }
audioSource.PlayOneShot(successAudio);
successParticles.Play();
Invoke("LoadNextScene", levelLoadDelay);
}
private void LoadFristLevel()
{
SceneManager.LoadScene(0);
}
private void LoadNextScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
int nextSceneIndex = currentSceneIndex+ 1;
if (SceneManager.sceneCountInBuildSettings ==nextSceneIndex) { nextSceneIndex = 0; }
SceneManager.LoadScene(nextSceneIndex);
}
private void ResponseToThrustInput()
{
if (Input.GetKey(KeyCode.Space))
{
ApplyThrust();
}
else
{
StopApplyingThrust();
}
}
private void StopApplyingThrust()
{
audioSource.Stop();
mainEngineParticles.Stop();
}
private void ApplyThrust()
{
rigidBody.AddRelativeForce(Vector3.up * mainThrust*Time.deltaTime);
if (!audioSource.isPlaying) { audioSource.PlayOneShot(mainEngineAudio); }
mainEngineParticles.Play();
}
private void ResponseToRotateInput()
{
if (Input.GetKey(KeyCode.A))
{
RotateManually(Time.deltaTime * rcsThrust);
}
else if (Input.GetKey(KeyCode.D)) {
RotateManually(-Time.deltaTime * rcsThrust);
}
}
private void RotateManually(float rotationThisFrame)
{
rigidBody.freezeRotation = true;//take manual control of rotation
transform.Rotate(Vector3.forward * rotationThisFrame);
rigidBody.freezeRotation = false;//resume physics control of rotation
}
}
|
9828c664ea99778761262f3e62d11c479c733cbb
|
[
"C#"
] | 1
|
C#
|
MasterD98/Boost
|
a427d5293ae7e00e2b6503b3d80866fb5b43356d
|
26194d4834d1a875cc4e3c2ad95d4a48a36b6357
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity.Framework;
using System.Data.SqlClient;
namespace Entity
{
public class TaikhoanModel
{
private DuLichVietDbContext db = null;
public TaikhoanModel()
{
db = new DuLichVietDbContext();
}
public bool Login(string username, string password)
{
object[] sqlParamets =
{
new SqlParameter("@Username", username),
new SqlParameter("@Password", password)
};
var res = db.Database.SqlQuery<bool>("Dang_nhap @Username,@Password",sqlParamets).SingleOrDefault();
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity.Framework;
namespace BUS
{
public class Tour_BUS
{
private DuLichVietDbContext db = new DuLichVietDbContext();
public void ThemTour(string matour,string tentour,string dacdiem,int gia,string loaihinh,string thoigian,DateTime ngay,string phuongtien,int tonghanhkhachtour,int dadangky,int trangthai)
{
Tour t = new Tour();
t.Matour = matour;
t.Tentour = tentour;
t.Dacdiem = dacdiem;
t.Giatour = gia;
t.Loaihinh = loaihinh;
t.Thoigian = thoigian;
t.Ngaykhoihanh = ngay;
t.Phuongtien = phuongtien;
t.Tonghanhkhachtour = tonghanhkhachtour;
t.Dadangky = dadangky;
t.Trangthai = trangthai;
db.Tours.Add(t);
db.SaveChanges();
}
public bool KiemMa(string matour)
{
Tour tkm;
tkm = db.Tours.Find(matour);
if(tkm==null)
{
return true;
}
else
{
return false;
}
}
public void SuaTour(string matour, string tentour, string dacdiem, int gia, string loaihinh, string thoigian, DateTime ngay, string phuongtien, int tonghanhkhachtour, int dadangky, int trangthai)
{
Tour ts = db.Tours.Find(matour);
ts.Tentour = tentour;
ts.Dacdiem = dacdiem;
ts.Giatour = gia;
ts.Loaihinh = loaihinh;
ts.Thoigian = thoigian;
ts.Ngaykhoihanh = ngay;
ts.Phuongtien = phuongtien;
ts.Tonghanhkhachtour = tonghanhkhachtour;
ts.Dadangky = dadangky;
ts.Trangthai = trangthai;
db.SaveChanges();
}
public Tour_BUS()
{
}
public List<Tour> get()
{
return db.Tours.ToList();
}
public Tour getById(string id)
{
return db.Tours.Find(id);
}
public void XoaTour(string ID)
{
Tour tx = db.Tours.Find(ID);
db.Tours.Remove(tx);
db.SaveChanges();
}
public bool check_id(string id)
{
var ma = db.Tours.Find(id);
if (ma != null)
{
return true;
}
else
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity.Framework;
namespace BUS
{
public class ThongKe_BUS
{
private DuLichVietDbContext db = new DuLichVietDbContext();
public ThongKe_BUS() { }
public List<Bill> get()
{
return db.Bills.ToList();
}
public List<Tour> gettime(DateTime dt1, DateTime dt2)
{
DateTime start = dt1;
DateTime end = dt2;
return db.Tours.Where(t => t.Ngaykhoihanh >= start && t.Ngaykhoihanh <= end).ToList();
}
public int get_giatour(string Matour)
{
return int.Parse(db.Tours.Where(t => t.Matour.Equals(Matour)).Select(p => p.Giatour).FirstOrDefault().ToString());
}
public int get_tonghanhkhach(string Matour)
{
return int.Parse(db.Tours.Where(t => t.Matour.Equals(Matour)).Select(p => p.Dadangky).FirstOrDefault().ToString());
}
public int get_thanhtien(int gia,int sl)
{
int thanhtien = 0;
thanhtien = gia * sl;
return thanhtien;
}
}
}
<file_sep>namespace Entity.Framework
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Bill")]
public partial class Bill
{
[Key]
public int Mahoadon { get; set; }
public int? Makhachhang { get; set; }
[StringLength(50)]
public string Tenkhachhang { get; set; }
[StringLength(50)]
public string Diachi { get; set; }
[StringLength(50)]
public string Sodienthoai { get; set; }
[StringLength(10)]
public string Madoan { get; set; }
[StringLength(50)]
public string Tendoan { get; set; }
public int? Soluongnguoidangki { get; set; }
[Column(TypeName = "date")]
public DateTime? Ngayxuat { get; set; }
[StringLength(50)]
public string Tinhtrang { get; set; }
public int? Tongtien { get; set; }
public virtual Customer Customer { get; set; }
}
}
<file_sep>namespace Entity.Framework
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Tour")]
public partial class Tour
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Tour()
{
Tourist_Group = new HashSet<Tourist_Group>();
}
[Key]
[StringLength(10)]
public string Matour { get; set; }
[Required]
[StringLength(50)]
public string Tentour { get; set; }
[Required]
[StringLength(4000)]
public string Dacdiem { get; set; }
public int? Giatour { get; set; }
[StringLength(50)]
public string Loaihinh { get; set; }
[StringLength(50)]
public string Thoigian { get; set; }
[Column(TypeName = "date")]
public DateTime? Ngaykhoihanh { get; set; }
[StringLength(50)]
public string Phuongtien { get; set; }
public int? Tonghanhkhachtour { get; set; }
public int? Dadangky { get; set; }
public int? Trangthai { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Tourist_Group> Tourist_Group { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BUS;
namespace FormQuanLiTour
{
public partial class FormQuanLiTour : Form
{
private Tour_BUS tb = new Tour_BUS();
public FormQuanLiTour()
{
InitializeComponent();
}
private void FormQuanLiTour_Load(object sender, EventArgs e)
{
dstour.AutoGenerateColumns = false;
dstour.DataSource = new BindingSource(tb.get(), null);
}
private void btthem_Click(object sender, EventArgs e)
{
Form1 F1 = new Form1();
F1.Show();
}
private void btsua_Click(object sender, EventArgs e)
{
int index = dstour.CurrentRow.Index;
if (index < dstour.RowCount && dstour.Rows[index].Cells[0].Value != null)
{
string matour = dstour.Rows[index].Cells["QLTmatour"].Value.ToString();
string tentour = dstour.Rows[index].Cells["QLTtentour"].Value.ToString();
string dacdiem = dstour.Rows[index].Cells["QLTdacdiem"].Value.ToString();
string thoigian = dstour.Rows[index].Cells["QLTthoigian"].Value.ToString();
string tongsocho = dstour.Rows[index].Cells["QLTtong"].Value.ToString();
string gia = dstour.Rows[index].Cells["QLTgiatour"].Value.ToString();
int tong = Int32.Parse(dstour.Rows[index].Cells["QLTtong"].Value.ToString());
int ddk = Int32.Parse(dstour.Rows[index].Cells["QLTDDK"].Value.ToString());
int con = tong - ddk;
string cons = con.ToString();
string loaihinh = dstour.Rows[index].Cells["QLTloaihinh"].Value.ToString();
string ngaykhoihanh = dstour.Rows[index].Cells["QLTngaykhoihanh"].Value.ToString();
string pt = dstour.Rows[index].Cells["QLTphuongtien"].Value.ToString();
string dd = dstour.Rows[index].Cells["QLTdacdiem"].Value.ToString();
DateTime ngay = Convert.ToDateTime(ngaykhoihanh);
Form1 F1 = new Form1();
F1.getvalue(matour, tentour, gia, tongsocho, cons, loaihinh, thoigian, ngay, pt, dd);
F1.Show();
}
else
{
MessageBox.Show("Xin chọn 1 dòng");
}
}
private void btxoa_Click(object sender, EventArgs e)
{
int index = dstour.CurrentRow.Index;
if (dstour.Rows[index].Cells["QLTmatour"].Value != null)
{
string IDs = dstour.Rows[index].Cells["QLTmatour"].Value.ToString();
tb.XoaTour(IDs);
MessageBox.Show("Đã Xóa Thành Công!!");
}
else
{
MessageBox.Show("Xin chọn 1 dòng");
}
}
private void btchitiet_Click(object sender, EventArgs e)
{
ThemTour TT = new ThemTour();
int index = dstour.CurrentRow.Index;
if (index < dstour.RowCount && dstour.Rows[index].Cells[0].Value != null)
{
string get = dstour.Rows[index].Cells["QLTmatour"].Value.ToString();
DateTime ngay = Convert.ToDateTime(dstour.Rows[index].Cells["QLTngaykhoihanh"].Value);
DateTime cur_date = DateTime.Today;
string get2 = "";
if (DateTime.Compare(ngay, cur_date) < 0)
{
get2 = "1";
}
else
{
get2 = "0";
}
TT.getvalue(get, get2);
TT.Show();
}
else
{
MessageBox.Show("Xin chọn 1 dòng");
}
}
private void btrefresh_Click(object sender, EventArgs e)
{
dstour.DataSource = new BindingSource(tb.get(), null);
}
}
}
<file_sep>using Entity.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entity
{
public class TourModel
{
DuLichVietDbContext db = null;
public TourModel()
{
db = new DuLichVietDbContext();
}
public List<Tour> TourListAll()
{
var list = db.Database.SqlQuery<Tour>("T_ListAll").ToList();
return list;
}
public List<Tour> TourListID(string id)
{
object parameter = new SqlParameter("@Matour", id);
var list = db.Database.SqlQuery<Tour>("T_ListAllID @Matour", parameter).ToList();
return list;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using BUS;
using Entity.Framework;
namespace FormQuanLiTour
{
public partial class Form1 : Form
{
private Entity.Framework.Place dsdd;
private Tour_BUS tb = new Tour_BUS();
private Entity.Framework.Tour nt = new Entity.Framework.Tour();
public Form1()
{
InitializeComponent();
dsdd = new Entity.Framework.Place();
}
private void Form1_Load(object sender, EventArgs e)
{
cbloaihinh.Items.Remove("Du Lịch Khám Phá");
cbloaihinh.Items.Remove("Du Lịch Phượt");
cbloaihinh.Items.Remove("Du Lịch Tham quan");
cbloaihinh.Items.Remove("Du Lịch văn hóa");
cbloaihinh.Items.Add("Du Lịch Khám Phá");
cbloaihinh.Items.Add("Du Lịch Phượt");
cbloaihinh.Items.Add("Du Lịch Tham quan");
cbloaihinh.Items.Add("Du Lịch văn hóa");
cbloaihinh.SelectedIndex = 1;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void click(object sender, EventArgs e)
{
}
private void XoaTour(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
public void getvalue(string ma, string ten,string gia,string tong,string con,string loaihinh,string thoigian,DateTime ngaykhoihanh,string pt,string dd)
{
txtmatour.Text = ma;
btthem.Visible = false;
btsua.Visible = true;
txtmatour.ReadOnly = true;
txttentour.Text = ten;
txtgiatour.Text = gia;
txttongsocho.Text = tong;
txtcon.Text = con;
txtthoigian.Text = thoigian;
dateTimePicker1.Value = ngaykhoihanh;
txtphuongtien.Text = pt;
txtdacdiem.Text = dd;
cbloaihinh.Items.Remove("Du Lịch Khám Phá");
cbloaihinh.Items.Remove("Du Lịch Phượt");
cbloaihinh.Items.Remove("Du Lịch Tham quan");
cbloaihinh.Items.Remove("Du Lịch văn hóa");
cbloaihinh.Items.Add("Du Lịch Khám Phá");
cbloaihinh.Items.Add("Du Lịch Phượt");
cbloaihinh.Items.Add("Du Lịch Tham quan");
cbloaihinh.Items.Add("Du Lịch văn hóa");
cbloaihinh.SelectedIndex = 1;
}
private void themtour(object sender, EventArgs e)
{
btthem.Visible = true;
btsua.Visible = false;
txtmatour.ReadOnly = false;
if (txtmatour.Text == "" || txttentour.Text == "" || txtdacdiem.Text == "" || txtgiatour.Text == "" || txtthoigian.Text == "" || txtphuongtien.Text == "" || txttongsocho.Text == "")
{
MessageBox.Show("Không được bỏ trống !!");
}
else if (kiemtramatour(txtmatour.Text) == true)
{
MessageBox.Show("Mã Tour đã có trong CSDL");
}
else if (KtSo(txtgiatour.Text)!=true|| KtSo(txttongsocho.Text)!=true || KtSo(txtcon.Text) != true)
{
MessageBox.Show("Nhập đúng kiểu dữ liệu");
}
else
{
string mah = txtmatour.Text;
string tenh = txttentour.Text;
string dacdiemh = txtdacdiem.Text;
int giah = Int32.Parse(txtgiatour.Text);
string loaihinhh = cbloaihinh.Text;
string thoigianh = txtthoigian.Text;
DateTime ngayh = dateTimePicker1.Value;
string time = DateTime.Today.ToString();
string pth = txtphuongtien.Text;
int slh = Int32.Parse(txttongsocho.Text);
int ch = Int32.Parse(txtcon.Text);
int ddk = slh - ch;
if (DateTime.Compare(ngayh, DateTime.Parse(time)) < 0)
{
MessageBox.Show("Ngày đã trôi qua !!");
}
else
{
tb.ThemTour(mah, tenh, dacdiemh, giah, loaihinhh, thoigianh, ngayh, pth, slh, ddk, 0);
MessageBox.Show("Đã thêm thành công!!");
}
}
}
private bool kiemtramatour(string vao)
{
string matour = txtmatour.Text;
if (tb.check_id(matour) == true)
return true;
else
return false;
}
private static bool KtSo(string txtvao)
{
if (txtvao != "")
{
return Regex.IsMatch(txtvao, @"^[0-9]\d*\.?[0]*$");
}
else return true;
}
private void capnhattour(object sender, EventArgs e)
{
if (txtmatour.Text == "" || txttentour.Text == "" || txtdacdiem.Text == "" || txtgiatour.Text == "" || txtthoigian.Text == "" || txtphuongtien.Text == "" || txttongsocho.Text == "")
{
MessageBox.Show("Không được bỏ trống !!");
}
else if (KtSo(txtgiatour.Text) != true || KtSo(txttongsocho.Text) != true || KtSo(txtcon.Text) != true)
{
MessageBox.Show("Nhập đúng kiểu dữ liệu");
}
else
{
string mah = txtmatour.Text;
string tenh = txttentour.Text;
string dacdiemh = txtdacdiem.Text;
int giah = Int32.Parse(txtgiatour.Text);
string loaihinhh = cbloaihinh.Text;
string thoigianh = txtthoigian.Text;
DateTime ngayh = dateTimePicker1.Value;
string time = DateTime.Today.ToString();
string pth = txtphuongtien.Text;
int slh = Int32.Parse(txttongsocho.Text);
int ch = Int32.Parse(txtcon.Text);
int ddk = slh - ch;
if (DateTime.Compare(ngayh, DateTime.Parse(time)) < 0)
{
MessageBox.Show("Ngày đã trôi qua !!");
}
else
{
tb.SuaTour(mah, tenh, dacdiemh, giah, loaihinhh, thoigianh, ngayh, pth, slh,ddk,0);
MessageBox.Show("Cập Nhật Thành Công!!");
}
}
}
private void refresh(object sender, MouseEventArgs e)
{
}
private void check(object sender, EventArgs e)
{
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
//txtngaykhoihanh.Text = dateTimePicker1.Value.ToString("MM/dd/yyyy");
}
private void txtdacdiem_TextChanged(object sender, EventArgs e)
{
}
private void btquay_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BUS;
using Entity.Framework;
using System.Text.RegularExpressions;
namespace FormQuanLiTour
{
public partial class ThemTour : Form
{
private Places_BUS pl = new Places_BUS();
private Province_BUS pv = new Province_BUS();
private Tour_BUS tb = new Tour_BUS();
public ThemTour()
{
InitializeComponent();
}
private void Load1(object sender, EventArgs e)
{
CTDTV.AutoGenerateColumns = false;
CTDTV.DataSource = new BindingSource(pl.get(txtmatour.Text),null);
cbten.ValueMember = "Madiadiem";
cbten.DisplayMember = "Tendiadiem";
cbten.DataSource = pl.getall();
}
public void getvalue(string x,string y)
{
txtmatour.Text = x;
if(Int32.Parse(y)==1)
{
lbkhoihanh.Text = "Đã khởi hành";
btthem.Visible = false;
btsua.Visible = false;
btxoa.Visible = false;
btrefresh.Visible = false;
}
else if(Int32.Parse(y) == 0)
{
lbkhoihanh.Text = "Chưa khởi hành";
btthem.Visible = true;
btsua.Visible = true;
btxoa.Visible = true;
btrefresh.Visible = true;
}
}
private void TTDTV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Themtour(object sender, EventArgs e)
{
}
private void TourDTV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void chondong(object sender, DataGridViewCellEventArgs e)
{
/*if (TourDTV.Rows[e.RowIndex].Cells[0].Value != null)
{
Entity.Framework.Tour t = tb.getById(TourDTV.Rows[e.RowIndex].Cells[0].Value.ToString());
txtupdate.Text = TourDTV.Rows[e.RowIndex].Cells[0].Value.ToString();
//TTDTV.DataSource = new BindingSource(t.Places, null);
}*/
}
private void chondongdd(object sender, DataGridViewCellEventArgs e)
{
if (CTDTV.Rows[e.RowIndex].Cells["TTmadiadiem"].Value != null)
{
/*Entity.Framework.Place p = pl.getById(Int32.Parse(CTDTV.Rows[e.RowIndex].Cells["TTmadiadiem"].Value.ToString()));
txtmadiadiem.Text = CTDTV.Rows[e.RowIndex].Cells["TTmadiadiem"].Value.ToString();
txttendiadiem.Text = CTDTV.Rows[e.RowIndex].Cells["TTtendiadiem"].Value.ToString();
txtchitiet.Text = CTDTV.Rows[e.RowIndex].Cells["TTchitiet"].Value.ToString();
txtmatinh.Text = CTDTV.Rows[e.RowIndex].Cells["TTmatinh"].Value.ToString();
txtmatour.Text = CTDTV.Rows[e.RowIndex].Cells["TTmatour"].Value.ToString();*/
}
}
private static bool KtSo(string txtvao)
{
if (txtvao != "")
{
return Regex.IsMatch(txtvao, @"^[0-9]\d*\.?[0]*$");
}
else return true;
}
private int kiemtramadiadiem()
{
int co = 1;
string madiadiem2 = cbten.SelectedValue.ToString();
for (int i = 0; i < CTDTV.RowCount-1; i++)
{
string madiadiem = CTDTV.Rows[i].Cells["TTmadiadiem"].Value.ToString();
if (madiadiem2 == madiadiem)
{
co = 0;
break;
}
}
return co;
}
private void Themdiadiem(object sender, EventArgs e)
{
int co = 0;
if (tbthutu.Text == "")
{
co = 1;
MessageBox.Show("Không được bỏ trống !!");
}
else if (KtSo(tbthutu.Text) != true)
{
co = 2;
MessageBox.Show("Nhập đúng kiểu dữ liệu");
}
else if(kiemtramadiadiem()==0)
{
MessageBox.Show("Địa điểm đã có trong lịch trình");
}
else
{
int thutu = Int32.Parse(tbthutu.Text);
int madd = Int32.Parse(cbten.SelectedValue.ToString());
string matourd = txtmatour.Text;
pl.Themdiadiem(thutu, madd, matourd);
MessageBox.Show("Đã thêm thành công!!");
}
}
private void XoaDiadiem(object sender, EventArgs e)
{
int index = CTDTV.CurrentRow.Index;
if (CTDTV.Rows[index].Cells["TTmadiadiem"].Value != null)
{
int IDs = Int32.Parse(CTDTV.Rows[index].Cells["TTmadiadiem"].Value.ToString());
string matourx = txtmatour.Text;
pl.XoaDiadiem(IDs,matourx);
MessageBox.Show("Đã Xóa Thành Công!!");
}
else
{
MessageBox.Show("Xin chọn 1 dòng");
}
}
private void Capnhatdiadiem(object sender, EventArgs e)
{
int co = 0;
if (tbthutu.Text == "")
{
co = 1;
MessageBox.Show("Không được bỏ trống !!");
}
else if (KtSo(tbthutu.Text) != true)
{
co = 2;
MessageBox.Show("Nhập đúng kiểu dữ liệu");
}
else if (kiemtramadiadiem() == 0)
{
MessageBox.Show("Địa điểm đã có trong lịch trình");
}
else
{
int thutu = Int32.Parse(tbthutu.Text);
int madd = Int32.Parse(cbten.SelectedValue.ToString());
string matourd = txtmatour.Text;
pl.SuaDiadiem(thutu, madd, matourd);
MessageBox.Show("Cập nhật thành công!!");
}
}
private void refresh(object sender, EventArgs e)
{
CTDTV.AutoGenerateColumns = false;
CTDTV.DataSource = new BindingSource(pl.get(txtmatour.Text), null);
cbten.ValueMember = "Madiadiem";
cbten.DisplayMember = "Tendiadiem";
cbten.DataSource = pl.getall();
}
private void cbten_SelectedIndexChanged(object sender, EventArgs e)
{
string madd=cbten.SelectedValue.ToString();
}
}
}
<file_sep>using Entity;
using Entity.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WedDLV.Areas.Admin.Controllers
{
public class TouristController : Controller
{
// GET: Admin/Tourist
public ActionResult Index()
{
return View();
}
[HttpGet]
// GET: Admin/Tourist/Create
public ActionResult Create()
{
return View();
}
[HttpGet]
// GET: Admin/Tourist/Add
public ActionResult Add(string id)
{
ViewBag.Madoan = id;
ViewBag.Customer = new CustomerDAO().CTMListAll();
return View();
}
[HttpGet]
public ActionResult Add1(string Makhachhang,string Madoan)
{
try
{
if (ModelState.IsValid)
{
var model = new CustomerDAO();
int res = model.Add(Int32.Parse(Makhachhang), Madoan);
if (res > 0)
{
ModelState.AddModelError("", "Thêm mới thành công");
return RedirectToAction("Details","Tourist_Group",new { id = Madoan });
}
}
return RedirectToAction("Details", "Tourist_Group", new { id = Madoan });
}
catch
{
return RedirectToAction("Details", "Tourist_Group", new { id = Madoan });
}
}
[HttpGet]
// GET: Admin/Tourist_Group/Delete/5
public ActionResult Delete(string id,string Makhachhang)
{
ViewBag.Madoan = id;
var TG = new CustomerDAO().GetById(Int32.Parse(Makhachhang));
return View(TG);
}
[HttpPost]
public ActionResult Delete(Customer collection,string Madoan)
{
try
{
if (ModelState.IsValid)
{
var model = new CustomerDAO();
int res = model.Delete(collection.Makhachhang,Madoan);
if (res > 0)
{
ModelState.AddModelError("", "Xóa thành công");
return RedirectToAction("Details","Tourist_Group",new {id = Madoan});
}
}
return View(collection);
}
catch
{
return RedirectToAction("Delete", new { id = Madoan, Makhachhang = collection.Makhachhang.ToString() });
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity.Framework;
namespace BUS
{
public class Province_BUS
{
private DuLichVietDbContext db = new DuLichVietDbContext();
public Province_BUS() { }
public List<Province> get()
{
return db.Provinces.ToList();
}
}
}
<file_sep>namespace Entity.Framework
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Tourist_Group
{
[Key]
[StringLength(10)]
public string Madoan { get; set; }
[StringLength(10)]
public string Matour { get; set; }
[StringLength(500)]
public string Tendoan { get; set; }
[StringLength(4000)]
public string Chuongtrinhthamquan { get; set; }
[Column(TypeName = "date")]
public DateTime? Ngaykhoihanh { get; set; }
[Column(TypeName = "date")]
public DateTime? Ngayketthuc { get; set; }
[StringLength(50)]
public string Phuongtien { get; set; }
public int? Tonghanhkhachdoan { get; set; }
public virtual Tour Tour { get; set; }
}
}
<file_sep>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Entity;
namespace WedDLV.Areas.Admin.Controllers
{
public class CustomerController : BaseController
{
// GET: Admin/Customer
public ActionResult Index()
{
var CTM = new CustomerDAO();
var model = CTM.CTMListAll();
return View(model);
}
[HttpGet]
public ActionResult TK(int id, DateTime? Ngaybatdau, DateTime? Ngayketthuc)
{
var CTM = new CustomerDAO().GetById(id);
var CTML = new CustomerDAO();
var model = CTML.TK(id, Ngaybatdau, Ngayketthuc);
ViewBag.RES = model;
return View(model);
}
}
}<file_sep>namespace Entity.Framework
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Place")]
public partial class Place
{
[Key]
public int Madiadiem { get; set; }
public int Matinh { get; set; }
[StringLength(4000)]
public string Tendiadiem { get; set; }
[StringLength(4000)]
public string Chitiet { get; set; }
public virtual Province Province { get; set; }
}
}
<file_sep>using Entity;
using Entity.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Services;
namespace WedDLV.Areas.Admin.Controllers
{
public class Tourist_GroupController : BaseController
{
// GET: Admin/Tourist_Group
public ActionResult Index()
{
var TG = new Tourist_GroupModel();
var model = TG.ListAll();
return View(model);
}
[HttpGet]
// GET: Admin/Tourist_Group/Details/5
public ActionResult Details(string id)
{
var TG = new Tourist_GroupModel().GetById(id);
ViewBag.Customers = new CustomerDAO().ListAll(id);
return View(TG);
}
[HttpGet]
// GET: Admin/Tourist_Group/Create
public ActionResult Create()
{
ViewBag.Tour = new TourModel().TourListAll();
return View();
}
[HttpGet]
// GET: Admin/Tourist_Group/AjaxLoadTourById/5
[WebMethod]
public string AjaxLoadTourById(string id)
{
var jsonSerialiser = new JavaScriptSerializer();
var CT = new TourModel().TourListID(id);
var json = jsonSerialiser.Serialize(CT);
return json;
}
[HttpGet]
public ActionResult Edit(string id)
{
ViewBag.Tour = new TourModel().TourListAll();
var TG = new Tourist_GroupModel().GetById(id);
return View(TG);
}
// POST: Admin/Tourist_Group/Create
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Create(Tourist_Group collection)
{
try
{
if(ModelState.IsValid)
{
var model = new Tourist_GroupModel();
int res = model.Create(collection.Madoan,collection.Matour,collection.Tendoan,collection.Chuongtrinhthamquan,collection.Ngaykhoihanh,collection.Ngayketthuc,collection.Phuongtien);
if(res>0)
{
ModelState.AddModelError("", "Thêm mới thành công");
return RedirectToAction("Index");
}
}
return View(collection);
}
catch
{
return View();
}
}
[HttpPost]
public ActionResult Edit(Tourist_Group collection)
{
try
{
if (ModelState.IsValid)
{
var model = new Tourist_GroupModel();
int res = model.Edit(collection.Madoan,collection.Matour, collection.Tendoan, collection.Chuongtrinhthamquan, collection.Ngaykhoihanh, collection.Ngayketthuc, collection.Phuongtien);
if (res > 0)
{
ModelState.AddModelError("", "Sửa thành công");
return RedirectToAction("Index");
}
}
return View(collection);
}
catch
{
return View();
}
}
[HttpGet]
// GET: Admin/Tourist_Group/Delete/5
public ActionResult Delete(string id)
{
var TG = new Tourist_GroupModel().GetById(id);
return View(TG);
}
// POST: Admin/Tourist_Group/Delete/5
[HttpPost]
public ActionResult Delete(Tourist_Group collection)
{
try
{
if (ModelState.IsValid)
{
var model = new Tourist_GroupModel();
int res = model.Delete(collection.Madoan);
if (res > 0)
{
ModelState.AddModelError("", "Xóa thành công");
return RedirectToAction("Index");
}
}
return View(collection);
}
catch
{
return View();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;
using BUS;
namespace FormQuanLiTour
{
public partial class ThongKe : Form
{
public ThongKe()
{
InitializeComponent();
}
private ThongKe_BUS tkb = new ThongKe_BUS();
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void TKClick(object sender, EventArgs e)
{
try
{
CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");
TKDTV.AutoGenerateColumns = false;
string Matour;
DateTime dt1 = DateTime.Parse(ngaybatdau.Text);
DateTime dt2 = DateTime.Parse(ngayketthuc.Text);
TKDTV.DataSource = new BindingSource(tkb.gettime(dt1, dt2), null);
for(int i=0; i<TKDTV.RowCount; i++)
{
if(TKDTV.Rows[i].Cells[0].Value != null)
{
Matour = TKDTV.Rows[i].Cells[0].Value.ToString();
int gia = tkb.get_giatour(Matour);
int sl = tkb.get_tonghanhkhach(Matour);
TKDTV.Rows[i].Cells["TKgiatour"].Value = tkb.get_giatour(Matour).ToString("#,###",cul.NumberFormat);
TKDTV.Rows[i].Cells["TKtien"].Value = tkb.get_thanhtien(gia,sl).ToString("#,###", cul.NumberFormat);
}
}
tinhtong();
}
catch(Exception)
{
MessageBox.Show("Nhập lại cho đúng !!");
}
}
private void tinhtong()
{
try
{
int tong = TKDTV.Rows.Count;
int thanhtien = 0;
string Matour;
for (int i = 0; i < tong - 1; i++)
{
if (TKDTV.Rows[i].Cells[0].Value != null)
{
Matour = TKDTV.Rows[i].Cells[0].Value.ToString();
int gia = tkb.get_giatour(Matour);
int sl = tkb.get_tonghanhkhach(Matour);
thanhtien = thanhtien + tkb.get_thanhtien(gia,sl);
}
}
String.Format("{0:0,0}", thanhtien);
Tong.Text = String.Format("{0:0,0} VND", thanhtien);
}
catch(Exception)
{
}
}
private void nhapngaybd(object sender, EventArgs e)
{
ngaybatdau.Text = timepicker1.Value.ToString("MM/dd/yyyy");
}
private void nhapngaykt(object sender, EventArgs e)
{
ngayketthuc.Text = timepicker2.Value.ToString("MM/dd/yyyy");
}
}
}
<file_sep>using Entity.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entity
{
public class Tourist_GroupModel
{
private DuLichVietDbContext db = null;
public Tourist_GroupModel()
{
db = new DuLichVietDbContext();
}
public List<Tourist_Group> ListAll()
{
var list = db.Database.SqlQuery<Tourist_Group>("dbo.DLV_TG_ListAll").ToList();
return list;
}
public int Create(string madoan,string matour,string tendoan,string chuongtrinhthamquan,DateTime? ngaykhoihanh,DateTime? ngayketthuc,string phuongtien)
{
object[] parameter =
{
new SqlParameter("@Madoan",madoan),
new SqlParameter("@Matour",matour),
new SqlParameter("@Tendoan",tendoan),
new SqlParameter("@Chuongtrinhthamquan",chuongtrinhthamquan),
new SqlParameter("@Ngaykhoihanh",ngaykhoihanh),
new SqlParameter("@Ngayketthuc",ngayketthuc),
new SqlParameter("@Phuongtien",phuongtien)
};
int res = db.Database.ExecuteSqlCommand("TG_Insert @Madoan,@Matour,@Tendoan,@Chuongtrinhthamquan,@Ngaykhoihanh,@Ngayketthuc,@Phuongtien", parameter);
return res;
}
public int Edit(string madoan,string matour, string tendoan, string chuongtrinhthamquan, DateTime? ngaykhoihanh, DateTime? ngayketthuc, string phuongtien)
{
object[] parameter =
{
new SqlParameter("@Madoan",madoan),
new SqlParameter("@Matour",matour),
new SqlParameter("@Tendoan",tendoan),
new SqlParameter("@Chuongtrinhthamquan",chuongtrinhthamquan),
new SqlParameter("@Ngaykhoihanh",ngaykhoihanh),
new SqlParameter("@Ngayketthuc",ngayketthuc),
new SqlParameter("@Phuongtien",phuongtien)
};
int res = db.Database.ExecuteSqlCommand("DLV_TG_Edit @Madoan,@Matour,@Tendoan,@Chuongtrinhthamquan,@Ngaykhoihanh,@Ngayketthuc,@Phuongtien", parameter);
return res;
}
public Tourist_Group GetById(string madoan)
{
return db.Tourist_Group.Find(madoan);
}
public int Delete(string madoan)
{
object parameter = new SqlParameter("@Madoan", madoan);
int res = db.Database.ExecuteSqlCommand("DLV_TG_Delete @Madoan", parameter);
return res;
}
}
}
<file_sep>using Entity.Framework;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entity
{
public class CustomerDAO
{
DuLichVietDbContext db = null;
public CustomerDAO()
{
db = new DuLichVietDbContext();
}
public List<Customer> ListAll(string Madoan)
{
object parameter = new SqlParameter("@Madoan", Madoan);
var list = db.Database.SqlQuery<Customer>("DLV_CTM_ListAll @Madoan", parameter).ToList();
return list;
}
public List<Customer> CTMListAll()
{
var list = db.Database.SqlQuery<Customer>("CTM_ListAll").ToList();
return list;
}
public List<Tour> TK(int id,DateTime? ngaybatdau,DateTime? ngayketthuc)
{
if (ngaybatdau == null || ngayketthuc == null)
{
object parameter1 = new SqlParameter("@Makhachhang", id);
var res1 = db.Database.SqlQuery<Tour>("CTM_TK_All @Makhachhang", parameter1).ToList();
return res1;
}
else
{
object[] parameter =
{
new SqlParameter("@Makhachhang",id),
new SqlParameter("@Ngaybatdau",ngaybatdau),
new SqlParameter("@Ngayketthuc",ngayketthuc),
};
var res = db.Database.SqlQuery<Tour>("CTM_TK @Makhachhang,@Ngaybatdau,@Ngayketthuc", parameter).ToList();
return res;
}
}
public Customer GetById(int makhachhang)
{
return db.Customers.Find(makhachhang);
}
public int Create(int makhachhang, string tenkhachhang, string cmnd, string diachi, string gioitinh, string sodienthoai)
{
object[] parameter =
{
new SqlParameter("@Makhachhang",makhachhang),
new SqlParameter("@Tenkhachhang",tenkhachhang),
new SqlParameter("@Cmnd",cmnd),
new SqlParameter("@Diachi",diachi),
new SqlParameter("@Gioitinh",gioitinh),
new SqlParameter("@Sodienthoai",sodienthoai)
};
int res = db.Database.ExecuteSqlCommand("CTM_Insert @Makhachhang,@Tenkhachhang,@Cmnd,@Diachi,@Gioitinh,@Sodienthoai", parameter);
return res;
}
public int Add(int makhachhang, string madoan)
{
object[] parameter =
{
new SqlParameter("@Makhachhang",makhachhang),
new SqlParameter("@Madoan",madoan),
};
int res = db.Database.ExecuteSqlCommand("CTM_Insert_CusTour @Makhachhang,@Madoan", parameter);
return res;
}
public int Delete(int makhachhang, string madoan)
{
object[] parameter =
{
new SqlParameter("@Makhachhang",makhachhang),
new SqlParameter("@Madoan",madoan),
};
int res = db.Database.ExecuteSqlCommand("CTM_Delete_CusTour @Makhachhang,@Madoan", parameter);
return res;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormQuanLiTour
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void FormQL(object sender, EventArgs e)
{
FormQuanLiTour Form = new FormQuanLiTour();
Form.Show();
}
private void TK(object sender, EventArgs e)
{
ThongKe tk = new ThongKe();
tk.Show();
}
}
}
<file_sep>namespace Entity.Framework
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class DuLichVietDbContext : DbContext
{
public DuLichVietDbContext()
: base("data source=DESKTOP-MMURNVC\\SQLEXPRESS;initial catalog=DuLichViet;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework")
{
}
public virtual DbSet<Bill> Bills { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Place> Places { get; set; }
public virtual DbSet<Province> Provinces { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public virtual DbSet<Tour> Tours { get; set; }
public virtual DbSet<Tourist_Group> Tourist_Group { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Bill>()
.Property(e => e.Madoan)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Cmnd)
.IsUnicode(false);
modelBuilder.Entity<Province>()
.HasMany(e => e.Places)
.WithRequired(e => e.Province)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Tour>()
.Property(e => e.Matour)
.IsUnicode(false);
modelBuilder.Entity<Tourist_Group>()
.Property(e => e.Madoan)
.IsUnicode(false);
modelBuilder.Entity<Tourist_Group>()
.Property(e => e.Matour)
.IsUnicode(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity;
using Entity.Framework;
using System.Data.SqlClient;
namespace BUS
{
public class Places_BUS
{
private DuLichVietDbContext db = new DuLichVietDbContext();
public Places_BUS()
{
}
public List<Place> get(string matour)
{
object parameter = new SqlParameter("@Matour", matour);
var list = db.Database.SqlQuery<Place>("Place_ListAll @Matour",parameter).ToList();
return list;
}
public List<Place> getall()
{
var list = db.Database.SqlQuery<Place>("Place_ListAllDD").ToList();
return list;
}
public Place getById(int id)
{
return db.Places.Find(id);
}
public int Themdiadiem(int thutu,int madiadiem, string matour)
{
object[] parameter =
{
new SqlParameter("@Stt",thutu),
new SqlParameter("@Madiadiem",madiadiem),
new SqlParameter("@Matour",matour),
};
int res = db.Database.ExecuteSqlCommand("Place_Insert @Stt,@Madiadiem,@Matour", parameter);
return res;
}
public int XoaDiadiem(int ID,string MT)
{
object[] parameter =
{
new SqlParameter("@Madiadiem",ID),
new SqlParameter("@Matour",MT),
};
int res = db.Database.ExecuteSqlCommand("PT_Delete @Madiadiem,@Matour", parameter);
return res;
}
public int SuaDiadiem(int thutu, int madiadiem, string matour)
{
object[] parameter =
{
new SqlParameter("@Stt",thutu),
new SqlParameter("@Madiadiem",madiadiem),
new SqlParameter("@Matour",matour),
};
int res = db.Database.ExecuteSqlCommand("Place_Edit @Stt,@Madiadiem,@Matour", parameter);
return res;
}
public string check_id(int madiadiem,string matour)
{
object[] parameter =
{
new SqlParameter("@Madiadiem",madiadiem),
new SqlParameter("@Matour",matour),
};
var res = db.Database.ExecuteSqlCommand("Check_ID @Madiadiem,@Matour", parameter);
return res.ToString();
/*if ( res != null)
{
return true;
}
else
return false;*/
}
}
}
|
3f83fef0abb4e74c2b74f3e5d07b9375a3ae8fdc
|
[
"C#"
] | 21
|
C#
|
didonguyen/DuLichViet1
|
a60021ec38e050394cf9b9a35a5f088fd53a1545
|
3d5a4da7deb2713f48a3106630aa435e8c462240
|
refs/heads/master
|
<file_sep><?php
$rows = 10;
$cols = 10;
echo '<table border="10">';
for ($tr=1; $tr<=$rows; $tr++){
echo '<tr>';
for ($td=1; $td<=$cols; $td++){
// счётчику $tr.
echo '<td width="30" height="30" bgcolor="#ebebeb">'. $tr*$td .'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
|
dadb2fb0d2f8ff9ba1d6bf8476207b82b33c98ea
|
[
"PHP"
] | 1
|
PHP
|
Azlator/TEST
|
33997c5ac16cabbfc1fa109027ac03e6d48a84cf
|
34e259286530cc83821b2fc6ee9684e30f40a843
|
refs/heads/main
|
<file_sep>{
"name": "frontend",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"dependencies": {
"@nuxtjs/axios": "^5.13.6",
"core-js": "^3.15.1",
"nuxt": "^2.15.7",
"v-tooltip": "^2.1.3",
"vue-2-breadcrumbs": "^0.8.0",
"vue-feather-icons": "^5.1.0",
"vue-js-modal": "^2.0.1"
},
"devDependencies": {
"@nuxtclub/feathericons": "^1.0.0",
"@nuxtjs/color-mode": "^2.1.1",
"@nuxtjs/composition-api": "^0.26.0",
"@nuxtjs/tailwindcss": "^4.2.0",
"fibers": "^5.0.0",
"postcss": "^8.3.5",
"sass": "^1.37.5",
"sass-loader": "10"
}
}
<file_sep># Cloud9 ☁️
Your data, on cloud 9.

## What makes it so special? 🤩
- 📁 **Store your data** ..in one place
- 🔄 **Sync your data** .., appointments and more
- 🔐 **Secure your data** ..without compromise
- 👏 **Share your data** ..with your friends
- 😄 **Enjoy a beautiful handmade user interface**
- 😉 **We do not collect any data from you.**
## Is there a destination?
My goal is to make sure that anyone who wants to set up their own cloud instance doesn't have that path filled with rocks. This project is undoubtedly a mammoth task. However, regular updates are planned for both the user interface, the user experience, and most importantly, security.
## About inspiration, motivation and more
The inspiration, as mentioned above, was drawn mainly from the poor implementations of the alternatives.
The motivation of this project does not come from anywhere. Mainly, from people I like very much. First and foremost, my girlfriend ❤️, who has significantly motivated me to this project.
<file_sep>hello:
@echo "Hello"
build:
docker build -t cloud7:latest .
run:
docker run --name "cloud7" -p 5000:5000 cloud7
dev:
yarn dev<file_sep>import Vue from "vue"
import Breadcrumbs from "vue-2-breadcrumbs"
Vue.use(Breadcrumbs)<file_sep>FROM node:14.17.5-alpine
WORKDIR /app
COPY . .
RUN yarn install
RUN yarn build
LABEL application="cloud7"
LABEL MAINTAINER="<NAME>. <<EMAIL>>"
ENV NUXT_HOST=0.0.0.0
ENV NUXT_PORT=5000
CMD ["yarn", "dev"]
|
739935bbcde11ba7e33c87ff35314738c11218f4
|
[
"JSON",
"Markdown",
"JavaScript",
"Makefile",
"Dockerfile"
] | 5
|
JSON
|
CoasterFreakDE/cloud
|
2b34ff779adb483d53efb5161253881b39e59dc4
|
cd60ac6d799eb6380872b4213e3f591e02f56371
|
refs/heads/master
|
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows;
using OfficeOpenXml;
namespace XlsMerger
{
class Merge: INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
private int percent = 0;
public int Percent
{
get { return percent; }
set
{
percent = value;
NotifyPropertyChange("Percent");
}
}
static bool Check()
{
return true;
}
private bool Check_Filled(ExcelRange block)
{
IEnumerator enumerator = block.GetEnumerator();
while(enumerator.MoveNext())
{
object item = enumerator.Current;
if ((item as ExcelRangeBase).Value != null) return true;
}
return false;
}
private bool Convert(string filePath)
{
GemBox.Spreadsheet.SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
GemBox.Spreadsheet.ExcelFile ef = GemBox.Spreadsheet.ExcelFile.Load(filePath);
ef.Save(filePath + 'x');
return true;
}
public void Merge_xlsx(List<string> inputFiles, string outputPath,string filename, List<int> fixed_rows, List<int> main_rows, int sheet_num = 1, bool ignoreEmpty = true)
{
List<ExcelRange> merge_data = new List<ExcelRange>();
Nullable<int> max_len = null; // indicate the column number
ExcelWorksheet modelsheet = null;
int counter = 0;
foreach (var filePath in inputFiles)
{
++counter;
FileInfo finfo;
// first, convert xls to xlsx if neccessary
if (filePath.EndsWith(".xls"))
{
Convert(filePath);
finfo = new FileInfo(filePath+'x');
}
else finfo = new FileInfo(filePath);
var package = new ExcelPackage(finfo);
ExcelWorksheet worksheet = package.Workbook.Worksheets[sheet_num];
if (modelsheet == null)
modelsheet = package.Workbook.Worksheets[sheet_num];
if (max_len == null)
{
max_len = 0;
// let's determine the max len first
foreach (var row in fixed_rows)
{
for (int i = 1; i <= 100; i++)
{
//var tmp = worksheet.Cells[row, i].Value;
if (worksheet.Cells[row, i].Value != null)
if (max_len != null && max_len < i) max_len = i;
}
}
}
// select the data to be collected
foreach(var mainrow in main_rows)
{
var tmp = worksheet.Cells[mainrow, 1, mainrow, (int)max_len].Value;
if ((!ignoreEmpty) || Check_Filled(worksheet.Cells[mainrow, 1, mainrow, (int)max_len]))
merge_data.Add(worksheet.Cells[mainrow, 1, mainrow, (int)max_len]);
}
Percent = (int)((float)counter / (inputFiles.Count) * 100);
}
// now, create the merged document
var newFile = new FileInfo(outputPath + "\\"+filename);
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo(outputPath + "\\" + filename);
}
using (var package = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(modelsheet.Name, modelsheet);
// add entries from the `main_row`
int curr_row = main_rows.Min();
foreach (var entry in merge_data)
{
worksheet.Cells[curr_row, 1, curr_row, (int)max_len].Value = entry.Value;
curr_row++;
}
package.Save();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace XlsMerger
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Clear_Items(object sender, RoutedEventArgs e)
{
inputfiles.Items.Clear();
}
private void Remove_Items(object sender, RoutedEventArgs e)
{
var selected = inputfiles.SelectedItems;
while(inputfiles.SelectedItems.Count>0)
inputfiles.Items.Remove(inputfiles.SelectedItems[0]);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog fileDialog = new Microsoft.Win32.OpenFileDialog
{
DefaultExt = ".xlsx",
Filter = "电子表格文件|*.xlsx;*.xls",
Multiselect = true
};
Nullable<bool> result = fileDialog.ShowDialog();
if (result == true)
{
// prepare for the same menu
System.Windows.Controls.ContextMenu menu = new System.Windows.Controls.ContextMenu();
System.Windows.Controls.MenuItem clear = new System.Windows.Controls.MenuItem
{
Header = "清空所有项",
IsCheckable = true
};
clear.Click += Clear_Items;
System.Windows.Controls.MenuItem remove = new System.Windows.Controls.MenuItem
{
Header = "移除所选项",
IsCheckable = true
};
remove.Click += Remove_Items;
menu.Items.Add(clear);
menu.Items.Add(remove);
// Open document
string[] filenames = fileDialog.FileNames;
foreach (string filename in filenames)
{
TextBlock item = new TextBlock
{
Text = filename,
ContextMenu = menu
};
inputfiles.Items.Add(item);
}
}
}
private void Output_Button_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
outputpath.Text = dialog.SelectedPath;
}
private readonly string[] commaSeparators = { ",", "," };
private readonly string[] dashSeparators = { "-", "—" };
private void showParseInfo(string messageBoxText= "所填的数据格式不正确。",string caption="嘿!")
{
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Information;
System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);
}
private List<int> parseMultiNumbers(string input)
{
string[] raw_rows = input.Split(commaSeparators, StringSplitOptions.RemoveEmptyEntries);
List<int> rows = new List<int>();
foreach(var group in raw_rows)
{
string[] parsed_rows = group.Split(dashSeparators, StringSplitOptions.RemoveEmptyEntries);
if(parsed_rows.Length>2)
{
showParseInfo();
return null;
}
if (parsed_rows.Length == 1)
{
if (int.TryParse(parsed_rows[0], out int item))
{
if (rows.IndexOf(item) < 0)
rows.Add(item);
}
else
{
showParseInfo(); return null;
}
}
else if (int.TryParse(parsed_rows[0], out int start) &&
int.TryParse(parsed_rows[1], out int end))
{
for (int i = start; i <= end; i++)
if (rows.IndexOf(i) < 0)
rows.Add(i);
}
else
{
showParseInfo();
return null;
}
}
return rows;
}
private bool Check_Value()
{
// first if they are filled with values.
if (publicrow_input.Text.Length == 0 || mergerow_input.Text.Length == 0)
{
showParseInfo("还有空没有填呢。。");
return false;
}
List<int> public_rows = parseMultiNumbers(publicrow_input.Text);
if (public_rows == null)
return false;
List<int> main_rows = parseMultiNumbers(mergerow_input.Text);
if (main_rows == null)
return false;
/*if (int.TryParse(mergerow_input.Text, out int main_row) == false)
{
showParseInfo("合并行数填写格式不正确。");
return false;
}*/
if (int.TryParse(sheetseq.Text, out int sheet_seq) == false)
{
showParseInfo("工作表序号填写不正确。");
return false;
}
List<string> input_files = new List<string>();
foreach (var item in inputfiles.Items)
input_files.Add((item as TextBlock).Text);
Merge mergeobj = new Merge();
mergeobj.Merge_xlsx(input_files, outputpath.Text, filename.Text,public_rows, main_rows, sheet_seq,(bool)ignoreEmptyBox.IsChecked);
return true;
}
private void Merge_Button_Click(object sender, RoutedEventArgs e)
{
if(Check_Value())
showParseInfo("合并成功!");
}
}
}
|
4ea551e3b386663c2aa0bc5a89cafff95ebe8ce7
|
[
"C#"
] | 2
|
C#
|
songchaow/XLSX-Merger
|
d8d4f700407057849a5835dcbbad46410dcdc472
|
cd02f6063df75fb1e351a79cca2d16714d1c3e40
|
refs/heads/master
|
<repo_name>theblum/dwm-status<file_sep>/dwm-status.c
/* ===========================================================================
* File: dwm-status.c
* Date: 18 Feb 2019
* Creator: <NAME> <<EMAIL>>
* Notice: Copyright (c) 2019 <NAME>
* ===========================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <error.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include "options.h"
#include "status.h"
#define TS_ONESEC &(struct timespec){1, 0}
#define PIDFILE "/run/user/1000/dwm-status.pid"
#define LOGFILE "/tmp/dwm-status.log"
#include "status.c"
#include "options.c"
static int running;
static int pidfd;
static struct options opts;
static struct statusitems items[] = {
{ datetime, 0 },
{ 0, 0 },
};
static void
handler(int signum)
{
if(lockf(pidfd, F_ULOCK, 0) < 0)
error(errno, errno, "Unable to unlock %s", opts.pidfile);
close(pidfd);
unlink(opts.pidfile);
running = 0;
}
static void
daemonize(void)
{
pid_t pid = fork();
if(pid < 0) error(errno, errno, "Unable to fork parent");
if(pid > 0) exit(EXIT_SUCCESS);
umask(0);
chdir("/");
int logfd = open(opts.logfile, O_RDWR|O_APPEND|O_CREAT, 0640);
if(logfd < 0) error(errno, errno, "Unable to open %s", opts.logfile);
dup2(logfd, STDIN_FILENO);
dup2(logfd, STDOUT_FILENO);
dup2(logfd, STDERR_FILENO);
close(logfd);
if(setsid() < 0) {
error(errno, errno, "Unable to become session leader");
}
pid = fork();
if(pid < 0) error(errno, errno, "Unable to fork child");
if(pid > 0) exit(EXIT_SUCCESS);
}
static void
killit(void)
{
pidfd = open(opts.pidfile, O_RDONLY);
if(pidfd < 0) error(errno, errno, "Unable to open %s", opts.pidfile);
char pidstr[256];
int nbytes = read(pidfd, pidstr, 255);
if(nbytes < 0)
error(errno, errno, "Unable to read from %s", opts.pidfile);
pidstr[nbytes] = '\0';
int pid = atoi(pidstr);
if(kill(pid, SIGINT) < 0)
error(errno, errno, "Unable to kill %d", pid);
}
int
main(int argc, char **argv)
{
opts.progname = strdup(argv[0]);
opts.logfile = strdup(LOGFILE);
opts.pidfile = strdup(PIDFILE);
optparse(argc, argv, &opts);
if(opts.kill) {
killit();
exit(EXIT_SUCCESS);
}
if(opts.daemon) {
daemonize();
}
pidfd = open(opts.pidfile, O_RDWR|O_CREAT, 0644);
if(pidfd < 0) error(errno, errno, "Unable to open %s", opts.pidfile);
if(lockf(pidfd, F_TLOCK, 0) < 0)
error(errno, errno, "Unable to lock %s", opts.pidfile);
dprintf(pidfd, "%d\n", getpid());
struct sigaction sa = {
.sa_handler = handler,
.sa_flags = 0,
};
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, 0);
sigaction(SIGTERM, &sa, 0);
struct statusbar bar = {0};
bar.handler = handler;
if(!createstatus(&bar)) {
fprintf(stderr, "%s: Unable to create status bar.\n", opts.progname);
exit(EXIT_FAILURE);
}
running = 1;
while(running) {
clearstatus(&bar);
for(struct statusitems *item = items; item->func; ++item)
item->func(&bar, item->data);
updatestatus(&bar);
clock_nanosleep(CLOCK_MONOTONIC, 0, TS_ONESEC, 0);
}
destroystatus(&bar);
free(opts.progname);
free(opts.logfile);
free(opts.pidfile);
exit(EXIT_SUCCESS);
}
<file_sep>/status.h
#if !defined(STATUS_H)
/* ===========================================================================
* File: status.h
* Date: 19 Feb 2019
* Creator: <NAME> <<EMAIL>>
* Notice: Copyright (c) 2019 <NAME>
* ===========================================================================
*/
#include <X11/Xlib.h>
#define MAXSTR 1024
struct statusbar {
Display *dpy;
Window w;
char str[MAXSTR];
size_t len;
void (*handler)(int signum);
};
struct statusitems {
void (*func)(struct statusbar *bar, void *data);
void *data;
};
#define STATUS_H
#endif
<file_sep>/status.c
/* ===========================================================================
* File: status.c
* Date: 19 Feb 2019
* Creator: <NAME> <<EMAIL>>
* Notice: Copyright (c) 2019 <NAME>
* ===========================================================================
*/
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
static void (*barhandler)(int signum);
static int
xioerror(Display *dpy)
{
barhandler(0);
exit(EXIT_SUCCESS);
}
static int
createstatus(struct statusbar *bar) {
bar->dpy = XOpenDisplay(0);
if(!bar->dpy) {
return 0;
}
barhandler = bar->handler;
XSetIOErrorHandler(xioerror);
bar->w = DefaultRootWindow(bar->dpy);
return 1;
}
static void
destroystatus(struct statusbar *bar) {
XCloseDisplay(bar->dpy);
}
static void
clearstatus(struct statusbar *bar)
{
bar->str[0] = '\0';
bar->len = 0;
}
static void
updatestatus(struct statusbar *bar)
{
XTextProperty tp = {
.value = (unsigned char *)bar->str,
.encoding = XA_STRING,
.format = 8,
.nitems = strlen(bar->str),
};
XSetWMName(bar->dpy, bar->w, &tp);
XSync(bar->dpy, False);
}
void
datetime(struct statusbar *bar, void *data)
{
time_t ctim = time(0);
char str[MAXSTR];
strftime(str, MAXSTR, "%a, %b %d %Y :: %I:%M:%S%P", localtime(&ctim));
strncat(bar->str, str, MAXSTR-bar->len-1);
bar->str[MAXSTR-1] = '\0';
bar->len = strlen(bar->str);
}
void
separator(struct statusbar *bar, void *data)
{
char *sep = (char *)data;
strncat(bar->str, sep, MAXSTR-bar->len-1);
bar->str[MAXSTR-1] = '\0';
bar->len = strlen(bar->str);
}
<file_sep>/README.md
# dwm-status
This program simply creates a status bar in dwm and updates it constantly.
It can be run in the foreground or as a daemon.
<file_sep>/run.sh
#!/bin/sh
PROGNAME="dwm-status"
DEBUGEXT="_debug"
if [[ $1 = '-R' ]]; then DEBUGEXT=; shift; fi
PREFIX=
if [[ $1 = '-d' ]]; then PREFIX="lldb --"; shift
elif [[ $1 = '-v' ]]; then PREFIX="valgrind --leak-check=full --"; shift
fi
$PREFIX ./$PROGNAME$DEBUGEXT $@
<file_sep>/build.sh
#!/bin/sh
PROGNAME="dwm-status"
DEBUGFLAGS="-g -O0"
DEBUGEXT="_debug"
if [[ $1 = '-R' ]]; then
DEBUGFLAGS=
DEBUGEXT=
shift
fi
CFLAGS="-std=c11 -pedantic -pipe -D_DEFAULT_SOURCE $(pkg-config --cflags x11)"
WARNINGS="-Wall -Wextra -Wno-unused-variable -Wno-unused-parameter -Wno-unused-function"
LDLIBS="$(pkg-config --libs x11)"
time clang $DEBUGFLAGS $CFLAGS $WARNINGS $@ -o $PROGNAME$DEBUGEXT $PROGNAME.c $LDLIBS
<file_sep>/options.h
#if !defined(OPTIONS_H)
/* ===========================================================================
* File: options.h
* Date: 19 Feb 2019
* Creator: <NAME> <<EMAIL>>
* Notice: Copyright (c) 2019 <NAME>
* ===========================================================================
*/
struct options {
char *progname;
char *logfile;
char *pidfile;
int daemon;
int kill;
};
#define OPTIONS_H
#endif
<file_sep>/options.c
/* ===========================================================================
* File: options.c
* Date: 19 Feb 2019
* Creator: <NAME> <<EMAIL>>
* Notice: Copyright (c) 2019 <NAME>
* ===========================================================================
*/
#include <getopt.h>
static struct option longopts[] = {
{ "daemon", no_argument, 0, 'd' },
{ "kill", no_argument, 0, 'k' },
{ "logfile", required_argument, 0, 'l' },
{ "pidfile", required_argument, 0, 'p' },
{ "help", no_argument, 0, 'h' },
{ 0, 0, 0, 0 },
};
static void
printhelp(char *progname)
{
printf("Usage: %s [OPTION]...\n", progname);
printf("Creates and updates a status bar in dwm.\n\n");
printf(" Options:\n");
printf(" -d, --daemon daemonize this program\n");
printf(" -k, --kill kill running daemon\n");
printf(" -l, --logfile=FILE log file location\n");
printf(" -p, --pidfile=FILE pid file location\n");
printf(" -h, --help print this help\n");
}
static void
optparse(int argc, char **argv, struct options *opts)
{
int val, optindex = 0;
while((val = getopt_long(argc, argv, "dkl:p:h", longopts, &optindex)) != -1) {
switch(val) {
case 'd':
{
opts->daemon = 1;
} break;
case 'k':
{
opts->kill = 1;
} break;
case 'l':
{
free(opts->logfile);
opts->logfile = strdup(optarg);
} break;
case 'p':
{
free(opts->pidfile);
opts->pidfile = strdup(optarg);
} break;
case 'h':
{
printhelp(opts->progname);
exit(EXIT_SUCCESS);
} break;
case '?':
{
printhelp(opts->progname);
exit(EXIT_FAILURE);
}
default: break;
}
}
}
|
d1a7fedae2ecea44cf8e2a3fc0bddcff449193aa
|
[
"Markdown",
"C",
"Shell"
] | 8
|
C
|
theblum/dwm-status
|
e3ec7c4da307829229a5b22aedec85e031b73fea
|
469339623b27a8060e488d6d28944e7d09de43a5
|
refs/heads/main
|
<file_sep>import subprocess
from scipy.io import wavfile
import numpy as np
import re
import math
import os
import argparse
import xml.etree.ElementTree as ET
def getMaxVolume(s):
maxv = float(np.max(s))
minv = float(np.min(s))
return max(maxv,-minv)
def inputToOutputFilename(filename):
dotIndex = filename.rfind(".")
return filename[:dotIndex]+"_ALTERED"+filename[dotIndex:]
parser = argparse.ArgumentParser(description='Cuts out silence from videos.')
parser.add_argument('--input_file', type=str, help='the video file you want modified')
# parser.add_argument('--url', type=str, help='A youtube url to download and process')
parser.add_argument('--output_file', type=str, default="", help="the output file. (optional. if not included, it'll just modify the input file name)")
parser.add_argument('--silent_threshold', type=float, default=0.03, help="the volume amount that frames' audio needs to surpass to be consider \"sounded\". It ranges from 0 (silence) to 1 (max volume)")
parser.add_argument('--sounded_speed', type=float, default=1.00, help="the speed that sounded (spoken) frames should be played at. Typically 1.")
parser.add_argument('--silent_speed', type=float, default=5.00, help="the speed that silent frames should be played at. 999999 for jumpcutting.")
parser.add_argument('--frame_margin', type=float, default=1, help="some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable.")
# parser.add_argument('--sample_rate', type=float, default=44100, help="sample rate of the input and output videos")
parser.add_argument('--frame_rate', type=float, default=30, help="frame rate of the input and output videos.")
# parser.add_argument('--frame_quality', type=int, default=3, help="quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default.")
args = parser.parse_args()
frameRate = args.frame_rate
SILENT_THRESHOLD = args.silent_threshold
INPUT_FILE = args.input_file
FRAME_MARGIN = args.frame_margin
SOUNDED_SPEED = args.sounded_speed
SILENT_SPEED = args.silent_speed
assert INPUT_FILE != None , "I need an input file to process."
if len(args.output_file) >= 1:
OUTPUT_FILE = args.output_file
else:
OUTPUT_FILE = inputToOutputFilename(INPUT_FILE)
command = "ffmpeg -i "+INPUT_FILE+" -ab 160k -ac 2 -ar 44100 -vn ./jumpcutter_audio.wav"
subprocess.call(command, shell=True)
command = "ffmpeg -i "+INPUT_FILE+" 2>&1"
f = open("./jumpcutter_params.txt", "w")
subprocess.call(command, shell=True, stdout=f)
f = open("./jumpcutter_params.txt", 'r+')
pre_params = f.read()
f.close()
params = pre_params.split('\n')
for line in params:
m = re.search('Stream #.*Video.* ([0-9]*) fps',line)
if m is not None:
frameRate = float(m.group(1))
sampleRate, audioData = wavfile.read("./jumpcutter_audio.wav")
audioSampleCount = audioData.shape[0]
maxAudioVolume = getMaxVolume(audioData)
samplesPerFrame = sampleRate/frameRate
audioFrameCount = int(math.ceil(audioSampleCount/samplesPerFrame))
hasLoudAudio = np.zeros((audioFrameCount))
for i in range(audioFrameCount):
start = int(i*samplesPerFrame)
end = min(int((i+1)*samplesPerFrame),audioSampleCount)
audiochunks = audioData[start:end]
maxchunksVolume = float(getMaxVolume(audiochunks))/maxAudioVolume
if maxchunksVolume >= SILENT_THRESHOLD:
hasLoudAudio[i] = 1
chunks = [[0,0,0]]
shouldIncludeFrame = np.zeros((audioFrameCount))
for i in range(audioFrameCount):
start = int(max(0,i-FRAME_MARGIN))
end = int(min(audioFrameCount,i+1+FRAME_MARGIN))
shouldIncludeFrame[i] = np.max(hasLoudAudio[start:end])
if (i >= 1 and shouldIncludeFrame[i] != shouldIncludeFrame[i-1]): # Did we flip?
chunks.append([chunks[-1][1],i,shouldIncludeFrame[i-1]])
chunks.append([chunks[-1][1],audioFrameCount,shouldIncludeFrame[i-1]])
chunks = chunks[1:]
outputAudioData = np.zeros((0,audioData.shape[1]))
outputPointer = 0
etree = ET.Element('mlt')
sprod0 = ET.SubElement(etree, 'producer', attrib={'id': 'producer0','mlt_service': 'timewarp'})
sprod1 = ET.SubElement(etree, 'producer', attrib={'id': 'producer1','mlt_service': 'timewarp'})
sprop0 = ET.SubElement(sprod0, 'property', attrib={'name': 'resource'})
sprop0.text = str(SOUNDED_SPEED)+":"+INPUT_FILE
sprop1 = ET.SubElement(sprod1, 'property', attrib={'name': 'resource'})
sprop1.text = str(SILENT_SPEED)+":"+INPUT_FILE
sprop2 = ET.SubElement(sprod0, 'property', attrib={'name': 'warp_pitch'})
sprop2.text = "1"
sprop3 = ET.SubElement(sprod1, 'property', attrib={'name': 'warp_pitch'})
sprop3.text = "1"
splay = ET.SubElement(etree, 'playlist', attrib={'id': 'playlist0'})
lastExistingFrame = None
for chunk in chunks:
outputPointer = chunk[0]
endPointer = chunk[1]
if (chunk[2]):
if(abs(chunk[0]/SOUNDED_SPEED - chunk[1]/SOUNDED_SPEED) > 1):
ET.SubElement(splay,'entry', attrib={'producer':'producer0', 'in': str(chunk[0]/SOUNDED_SPEED), 'out': str(chunk[1]/SOUNDED_SPEED)})
else:
if(abs(chunk[0]/SILENT_SPEED - chunk[1]/SILENT_SPEED) > 1):
ET.SubElement(splay,'entry', attrib={'producer':'producer1', 'in': str(chunk[0]/SILENT_SPEED), 'out': str(chunk[1]/SILENT_SPEED)})
ET.ElementTree(etree).write('jumpcutter.mlt')
command = ".\melt jumpcutter.mlt -consumer avformat:"+OUTPUT_FILE
subprocess.call(command, shell=True)<file_sep># jumpcutter
More efficient version of carykh's jumpcutter using melt
It assumes melt is in the current directory, and does not require audiotsm or youtube.
|
aa2c6e1793415678dfdb92a638dcabdf5a8d8839
|
[
"Markdown",
"Python"
] | 2
|
Python
|
SED4906/jumpcutter
|
a102a103b48f6b9fe9fca26fb2fd54073d2d924c
|
59108ecacf08b58c96f6a3bebd65ba6bb0dc071d
|
refs/heads/master
|
<repo_name>danmitchell-/questionnaire<file_sep>/app/controllers/forms_controller.rb
class FormsController < ApplicationController
def index
# This is a comment
@name = "Dan"
@location ="Steer"
@now = Time.now
# @message = "Welcome to " + @location + ", " + @name
@message = "Welcome to #{@location}, #{@name}"
# This is an array
@list = ["Rik", "Amelia", "Tim", "Calum"]
@competition_won_by_sev = true
@sev_votes = rand(100)
@mark_votes = rand(100)
if @sev_votes > @mark_votes
@list << "Sev"
elsif @sev_votes == @mark_votes
@list << "Sev"
@list << "Mark"
else
@list << "Mark"
end
@forms = Form.order("rating")
end
def show
@form = Form.find(params[:id])
end
def new
@form = Form.new
end
def create
@form = Form.new(params[:form])
if @form.save
flash[:success] = "You have sucessfully added a reponse!"
redirect_to forms_path
else
render "new"
end
end
def edit
@form = Form.find params[:id]
end
def update
@form = Form.find params[:id]
if @form.update_attributes(params[:form])
flash[:success] = "You have sucessfully edited #{@form.name}!"
redirect_to form_path(@form)
else
render "edit"
end
end
def destroy
@form = Form.find params[:id]
@form.destroy
if @form.destroy
flash[:success] = "You have sucessfully deleted the #{@form.name}!"
end
redirect_to forms_path
end
end
<file_sep>/db/migrate/20130423080502_add_company_fields_to_forms.rb
class AddCompanyFieldsToForms < ActiveRecord::Migration
def change
add_column :forms, :company, :text
add_column :forms, :job_title, :text
end
end
<file_sep>/db/migrate/20130422154021_add_fields_to_forms.rb
class AddFieldsToForms < ActiveRecord::Migration
def change
add_column :forms, :comment, :text
add_column :forms, :rating, :integer
add_column :forms, :would_recommend, :boolean
end
end
<file_sep>/app/models/form.rb
class Form < ActiveRecord::Base
attr_accessible :email, :name, :company, :job_title, :comment, :rating, :would_recommend
validates :name, presence: true, length: { minimum: 2 }
validates :email, presence: true, uniqueness: true
validates :rating, presence: true, numericality: {
greater_than_or_equal_to: 1,
less_than_or_equal_to: 5,
only_interger: true
}
end
|
7cc9ad8be96583c4312e761378aa3c22726fa770
|
[
"Ruby"
] | 4
|
Ruby
|
danmitchell-/questionnaire
|
904e8ac6a63551e37ea0a54951a06ed69e44b6de
|
1d86cc0bf9956fa4e09c8a8d98b802dbc3e79bb7
|
refs/heads/master
|
<file_sep>using System.Collections.Generic;
using IdentityServer4.Models;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(new List<ApiResource>{ new ApiResource("api1", "my api")})
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = "ro.client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "http://localhost";
options.Audience = "api1";
options.RequireHttpsMetadata = false;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseIdentityServer();
app.UseMvc();
}
}
}
<file_sep>using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using WebApp;
using Xunit;
namespace TestServerRepro
{
public class HttpFixture
{
private HttpMessageHandler _messageHandler;
public HttpFixture()
{
var builder = WebHost.CreateDefaultBuilder()
.UseStartup<Startup>()
.ConfigureServices(serviceCollection =>
{
// ensure that HttpClients
// use a message handler for the test server
serviceCollection
.AddHttpClient(Options.DefaultName)
.ConfigurePrimaryHttpMessageHandler(() => _messageHandler);
serviceCollection.PostConfigure<JwtBearerOptions>(
JwtBearerDefaults.AuthenticationScheme,
options => options.BackchannelHttpHandler = _messageHandler);
}); ;
var host = new TestServer(builder);
_messageHandler = host.CreateHandler();
HttpClient = host.CreateClient();
}
public HttpClient HttpClient { get; }
public async Task<string> CreateAsync(string uri, string value)
{
var message = new HttpRequestMessage(HttpMethod.Post, uri);
message.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("text/plain"));
message.Content = new StringContent(value);
HttpResponseMessage response = await HttpClient.SendAsync(message);
Assert.True(response.IsSuccessStatusCode);
return await response.Content.ReadAsStringAsync();
}
public async Task SetupAuth()
{
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("client_id", "ro.client"),
new KeyValuePair<string, string>("client_secret", "secret"),
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("scope", "api1"),
};
var formContent = new FormUrlEncodedContent(values);
HttpResponseMessage tokenResponse = await HttpClient.PostAsync("/connect/token", formContent);
var tokenJson = JObject.Parse(await tokenResponse.Content.ReadAsStringAsync());
var bearerToken = tokenJson["access_token"].Value<string>();
HttpClient.SetBearerToken(bearerToken);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace WebApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
await Task.Delay(4);
return new string[] {
"method",
"test",
};
}
[HttpPost]
public async Task<ActionResult> Post(string content)
{
return Ok("test");
}
}
}
<file_sep>using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace TestServerRepro
{
public class UnitTest: IClassFixture<HttpFixture>
{
private HttpFixture _fixture;
public UnitTest(HttpFixture fixture)
{
_fixture = fixture;
Client = fixture.HttpClient;
}
protected HttpClient Client { get; set; }
[Fact]
public async Task GetTest()
{
await _fixture.SetupAuth();
var response = await Client.GetAsync("/api/values");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task PostTest()
{
await _fixture.SetupAuth();
var response = await _fixture.CreateAsync("/api/values", "test");
Assert.Equal("test", response);
}
}
}
|
44c51d1e51938eeff435f809ce3466695fecaf10
|
[
"C#"
] | 4
|
C#
|
analogrelay/TestServerRepro
|
300d27af04dc9ff60ba22d52f1aaad1a92e9e021
|
0e004088080ddcc60913a6de32dbf8c633ae39d1
|
refs/heads/master
|
<repo_name>chuong2598/myWebSite<file_sep>/src/components/MyNavBar.js
import React, { Component } from 'react';
import { Button, Navbar, Nav } from 'react-bootstrap'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faGithub } from '@fortawesome/free-brands-svg-icons'
class MyNavBar extends Component {
redirectToGithub() {
window.location.href = "https://github.com/chuong2598?tab=repositories"
}
changeNameColor(id) {
var currentColor = document.getElementById(id).style.color
currentColor = currentColor === "white" ? "Coral" : "white"
document.getElementById(id).style.color = currentColor
}
chooseSection(section){
this.props.onSelectSection(section)
}
render() {
return (
<div>
<Navbar bg="dark" variant="dark" fixed="top">
<Navbar.Brand style={{ paddingLeft: "30px" }}>
<Button
id="nav-bar-name"
variant="link"
size="sm"
onClick = {() => this.chooseSection("home")}
onMouseOver={() => this.changeNameColor("nav-bar-name")}
onMouseOut={() => this.changeNameColor("nav-bar-name")}
style={{ fontWeight: 'bold', fontSize: '24px', color: 'White', textDecoration: "none" }} >
<NAME>
</Button>
</Navbar.Brand>
<Nav className="mr-auto">
<Button
onClick={this.redirectToGithub} variant="link" bg="link"
id="nav-bar-github-icon"
onMouseOver={() => this.changeNameColor("nav-bar-github-icon")}
onMouseOut={() => this.changeNameColor("nav-bar-github-icon")}
style={{ color: "white" }} >
<FontAwesomeIcon icon={faGithub} size="2x" />
</Button>
</Nav>
<Nav style={{ paddingRight: "30px" }}>
<Button
bg="link" variant="link"
id="nav-bar-about-me"
onClick = {() => this.chooseSection("about-me")}
onMouseOver={() => this.changeNameColor("nav-bar-about-me")}
onMouseOut={() => this.changeNameColor("nav-bar-about-me")}
style={{ fontWeight: 'bold', fontSize: '18px', color: 'White', textDecoration: "none" }} >
ABOUT ME
</Button>
<Button
bg="link" variant="link"
id="nav-bar-project"
onClick = {() => this.chooseSection("project")}
onMouseOver={() => this.changeNameColor("nav-bar-project")}
onMouseOut={() => this.changeNameColor("nav-bar-project")}
style={{ fontWeight: 'bold', fontSize: '18px', color: 'White', textDecoration: "none" }} >
PROJECTS
</Button>
<Button
bg="link" variant="link"
id="nav-bar-contact"
onClick = {() => this.chooseSection("contact")}
onMouseOver={() => this.changeNameColor("nav-bar-contact")}
onMouseOut={() => this.changeNameColor("nav-bar-contact")}
style={{ fontWeight: 'bold', fontSize: '18px', color: 'White', textDecoration: "none" }} >
CONTACT
</Button>
</Nav>
</Navbar>
</div>
);
}
}
export default MyNavBar;<file_sep>/src/components/AboutMe.js
import React, { Component } from 'react';
import { Container, Card, Row, Col } from 'react-bootstrap'
import '../css/aboutMe.css'
class AboutMe extends Component {
render() {
return (
<div>
<Container className="about-me-container">
<Row className="justify-content-md-center">
<span style={{fontWeight: 'bold', fontSize: '24px', color: 'DarkSlateGray'}}>
About me
</span>
</Row>
<Row className="justify-content-md-center">
<hr style={{width:"15%", color:"white", border: "2px solid DarkSlateGray"}}/>
</Row>
<Row>
<Col>
<Card >
<Card.Body>
<Card.Title >
<Row className="justify-content-md-center">Achievements</Row>
</Card.Title>
<Card.Text>
<ul>
<li>Certificate of Best Performance in 2017 awarded by RMIT Vietnam</li>
<li>RMIT Vietnam 2018 Academic Achievement Scholarship for Current Student</li>
</ul>
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col>
<Card >
<Card.Body>
<Card.Title >
<Row className="justify-content-md-center">Background</Row>
</Card.Title>
<Card.Text>
<ul>
<li>
I have graduated a bachelor of Information Technology at RMIT Vietnam in 2019.
During the period at RMIT Vietnam, I had a special interest in building and deploying a website using React/Redux framwork.
</li>
<li>
I am currently doing a Master of Computing at the ANU univeristy. I just finished my second semester here and I am going to
take part in a research related to Computer Vision in my last year at the ANU.
</li>
</ul>
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col>
<Card >
<Card.Body>
<Card.Title >
<Row className="justify-content-md-center">Interests</Row>
</Card.Title>
<Card.Text>
<ul>
<li>Software/Web Development</li>
<li>Cloud Computing</li>
<li>Machine Learning and Data Analystics</li>
<li>Computer Vision</li>
</ul>
</Card.Text>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
</div>
);
}
}
export default AboutMe;<file_sep>/src/components/projects/TextClassification.js
import React, { Component } from 'react';
import { Col, Container, Row, Form, Button, Spinner } from 'react-bootstrap';
class TextClassification extends Component {
constructor(props){
super(props)
this.state = {sentence: null, prediction: -1, loading_result: false}
this.result = ["negative", "postive"]
}
enterSentence = (e) => {
this.setState({sentence: e.target.value})
}
predict = () => {
if (this.state.sentence === "" || this.state.sentence === null){
alert("Please enter a sentence")
return
}
this.setState({prediction: -1})
this.setState({loading_result: true})
fetch(`http://sentimentclassification-env.eba-ur6pncmi.us-east-1.elasticbeanstalk.com/predict`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body : new URLSearchParams({
'sentence': this.state.sentence
}),
method: "POST",
})
.then(res => res.json())
.then((prediction) => {
this.prediction = prediction
this.setState({prediction: prediction.prediction})
this.setState({loading_result: false})
})
.catch(() => {
this.setState({loading_result: false})
})
}
render() {
return (
<Container style={{ background: "AliceBlue", borderRadius: "20px" }}>
<br />
<Row className="justify-content-md-center">
<span style={{ fontWeight: 'bold', fontSize: '20px', color: 'DarkSlateGray' }}>
Sentiment Classifcaation
</span>
</Row>
<Row>
<Col>
<br />
<Form >
A Machine Learning model that helps to classify whether a sentence is positive or negative sentence.
<br/>
<br/>
Model: BERT
<br/>
API: Python (Flask framwork)
<br/>
<br/>
Enter a sentence to the text box below to classify a sentence.
<br/>
<br/>
<Form.Group controlId="formBasicEmail" >
<Form.Control type="text" placeholder="Enter a sentence" onChange={this.enterSentence}/>
</Form.Group>
{this.state.prediction !== -1
?
<text style={{color:this.state.prediction===1?"green":"red"}}>The sentence is {this.result[this.state.prediction]}
<br/>
</text>
: null
}
</Form>
</Col>
</Row>
<Row style={{alignContent:"center", justifyContent:"center"}}>
<Button disabled={this.state.loading_result} style={{alignContent:"center", justifyContent:"center", width:"50%", display:"flex"}} variant="success" onClick={this.predict}>
{this.state.loading_result ?
<span>
<Spinner size="sm" animation="border" variant="primary" />
Please wait a moment...
</span>
: "Classify"}
</Button>
</Row>
<br />
</Container>
);
}
}
export default TextClassification;<file_sep>/src/App.js
import React, { Component } from 'react';
import './css/custom-navbar.css'
import MyNavBar from './components/MyNavBar'
import Info from './components/Info'
import AboutMe from './components/AboutMe'
import Project from './components/Project'
import { Button } from 'react-bootstrap';
class App extends Component {
constructor(props){
super(props)
this.myRef = React.createRef()
}
navigateSection = (section) => {
section = document.getElementById(section)
console.log(section)
if (section != null){
section.scrollIntoView({behavior: 'smooth'})
}
else {
alert("Have not implemented :)")
}
}
render() {
return (
<div id = "home">
<MyNavBar onSelectSection = {this.navigateSection}/>
<Info/>
<div id = "about-me" ref="">
<AboutMe />
</div>
<div id = "project">
<Project ref={this.myRef} />
</div>
</div>
);
}
}
export default App;<file_sep>/src/components/projects/Elab.js
import React, { Component } from 'react';
import { Col, Container, Row, Image } from 'react-bootstrap';
import elabImg from '../../images/elab.jpg'
class Elab extends Component {
render() {
return (
<Container style={{ background: "AliceBlue", borderRadius: "20px" }}>
<br/>
<Row className="justify-content-md-center">
<span style={{ fontWeight: 'bold', fontSize: '20px', color: 'DarkSlateGray' }}>
Elab
</span>
</Row>
<Row>
<Col>
<br />
<Image height="275px" alt="cam" src={elabImg} />
<br/>
<br/>
</Col>
<Col>
<br />
<br />
Elab a cross-platform system developed for iOS, Android, Web that has four main features: audio call, video call, conferencing, and livestreaming. WebRTC is used as a technology for transfering media data between clients.
<br />
<br />
Frontend: React Native(mobile app version), ReactJs(web version)
<br />
Backend: JavaSrpingMVC
<br/>
Media server: WebRTC + Janus
<br />
<br />
<a href="https://github.com/chuong2598/communicationSystem">Click here to go to Github repo</a>
</Col>
</Row>
</Container>
);
}
}
export default Elab;<file_sep>/src/components/projects/EnglishMater.js
import React, { Component } from 'react';
import { Col, Container, Row, Image } from 'react-bootstrap';
import englishMasterImg from '../../images/englishMaster.png'
class EnglishMater extends Component {
render() {
return (
<Container style={{ background: "AliceBlue", borderRadius: "20px" }}>
<br/>
<Row className="justify-content-md-center">
<span style={{ fontWeight: 'bold', fontSize: '20px', color: 'DarkSlateGray' }}>
English Master
</span>
</Row>
<Row>
<Col>
<br />
<br />
An online learning system that helps Vietnamese students to learn about the meaning, pronuniciation, usage of English words. A web crawling that crawls online articles everyday to collect data such as new word, meaning, example usage, etc.
<br />
<br />
Frontend: ReactJs
<br />
Backend: NodeJs to create Restful API, Dockers
<br />
<br />
A demo of this app can be found <a href="https://englishmaster.s3.amazonaws.com/index.html">in this link</a>
<br />
<a href="https://github.com/chuong2598/englishMaster">Click here to go to Github repo</a>
</Col>
<Col>
<br />
<Image height="300px" alt="cam" src={englishMasterImg} />
</Col>
</Row>
<br/>
</Container>
);
}
}
export default EnglishMater;
|
daae0cd1d978efd08d12b5509cdaeb71c28c4956
|
[
"JavaScript"
] | 6
|
JavaScript
|
chuong2598/myWebSite
|
83f4a39e44938103cc325c3c130bf36ca90080d3
|
823e11134b75602dfeeb9b7423abf431aa4aa9fd
|
refs/heads/master
|
<repo_name>preddy4690/CosmosDbTutorial<file_sep>/README.md
# CosmosDbTutorial
Generic repositories for DocumentDb & MongoDb for Azure CosmosDb
Code for <a href ="https://medium.com/@dmytrozhluktenko/marrying-cosmosdb-and-net-core-7c55c8fca5b3">this</a> medium article.
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">I just published “Marrying CosmosDB and .NET Core” <a href="https://t.co/f2ukL8REpO">https://t.co/f2ukL8REpO</a></p>— <NAME> (@dim0kq) <a href="https://twitter.com/dim0kq/status/892651923207335941">August 2, 2017</a></blockquote>
<file_sep>/CosmosDbTutorial.DataAccess/Repository/IRepository.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CosmosDbTutorial.DataAccess.Repository
{
public interface IRepository : IDisposable
{
Task<bool> AnyAsync<T>(string id) where T : BaseEntity;
Task<T> GetAsync<T>(string id) where T : BaseEntity;
Task<IEnumerable<T>> GetAllAsync<T>() where T : BaseEntity;
Task<IEnumerable<T>> GetAsync<T>(IEnumerable<string> ids) where T : BaseEntity;
Task InsertAsync<T>(T entity) where T : BaseEntity;
Task InsertAsync<T>(IEnumerable<T> entities) where T : BaseEntity;
Task UpsertAsync<T>(T entity) where T : BaseEntity;
Task DeleteAsync<T>(string id) where T : BaseEntity;
}
}<file_sep>/CosmosDbTutorial.DataAccess/Repository/MongoDbRepository.cs
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using System.Threading.Tasks;
using MongoDB.Driver;
using static CosmosDbTutorial.Configuration.Config;
namespace CosmosDbTutorial.DataAccess.Repository
{
public class MongoDbRepository : IRepository
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _db;
public MongoDbRepository()
{
var settings = MongoClientSettings.FromUrl(
new MongoUrl(MongoDbConnectionString)
);
settings.SslSettings =
new SslSettings { EnabledSslProtocols = SslProtocols.Tls12 };
_client = new MongoClient(settings);
_db = _client.GetDatabase(DatabaseName);
}
public async Task<bool> AnyAsync<T>(string id) where T : BaseEntity
{
return await _db.GetCollection<T>(typeof(T).Name).Find(x => x.id == id).AnyAsync();
}
public async Task<T> GetAsync<T>(string id) where T : BaseEntity
{
return await _db.GetCollection<T>(typeof(T).Name).Find(x => x.id == id).FirstAsync();
}
public async Task<IEnumerable<T>> GetAllAsync<T>() where T : BaseEntity
{
return _db.GetCollection<T>(typeof(T).Name).Find(_ => true).ToEnumerable();
}
public async Task<IEnumerable<T>> GetAsync<T>(IEnumerable<string> ids) where T : BaseEntity
{
return _db.GetCollection<T>(typeof(T).Name).Find(x => ids.Contains(x.id)).ToEnumerable();
}
public async Task InsertAsync<T>(T entity) where T : BaseEntity
{
await _db.GetCollection<T>(typeof(T).Name)
.InsertOneAsync(entity, new InsertOneOptions { BypassDocumentValidation = true });
}
public async Task InsertAsync<T>(IEnumerable<T> entities) where T : BaseEntity
{
await _db.GetCollection<T>(typeof(T).Name)
.InsertManyAsync(entities, new InsertManyOptions { BypassDocumentValidation = true, IsOrdered = false });
}
public async Task UpsertAsync<T>(T entity) where T : BaseEntity
{
await _db.GetCollection<T>(typeof(T).Name).UpdateOneAsync(x => x.id == entity.id,
Builders<T>.Update.Set(p => p, entity),
new UpdateOptions { IsUpsert = true });
}
public async Task DeleteAsync<T>(string id) where T : BaseEntity
{
await _db.GetCollection<T>(typeof(T).Name).DeleteOneAsync(x => x.id == id);
}
public void Dispose()
{
throw new System.NotImplementedException();
}
}
}
<file_sep>/CosmosDbTutorial.Entities/Skill.cs
using CosmosDbTutorial.DataAccess;
namespace CosmosDbTutorial.Entities
{
public class Skill : BaseEntity
{
public string Name { get; set; }
}
}<file_sep>/CosmosDbTutorial.Entities/Person.cs
using System.Collections.Generic;
using CosmosDbTutorial.DataAccess;
namespace CosmosDbTutorial.Entities
{
public class Person : BaseEntity
{
public string Name { get; set; }
public List<Skill> Skills { get; set; }
}
}<file_sep>/CosmosDbTutorial.DataAccess/Repository/DocumentDbRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using static CosmosDbTutorial.Configuration.Config;
namespace CosmosDbTutorial.DataAccess.Repository
{
public class DocumentDbRepository : IRepository
{
private readonly DocumentClient _client;
public DocumentDbRepository()
{
_client = new DocumentClient(new Uri(DocumentDbEndpointUrl), DocumentDbPrimaryKey);
_client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseName }).Wait();
}
public void Dispose()
{
_client.Dispose();
}
public async Task<bool> AnyAsync<T>(string id) where T : BaseEntity
{
return _client.CreateDocumentQuery<T>
(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name))
.Any(x => x.id == id);
}
public async Task<T> GetAsync<T>(string id) where T : BaseEntity
{
return _client.CreateDocumentQuery<T>
(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name))
.Where(x => x.id == id).ToList().First();
}
public async Task<IEnumerable<T>> GetAllAsync<T>() where T : BaseEntity
{
return _client.CreateDocumentQuery<T>
(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name));
}
public async Task<IEnumerable<T>> GetAsync<T>(IEnumerable<string> ids) where T : BaseEntity
{
return _client.CreateDocumentQuery<T>
(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name))
.Where(x => ids.Contains(x.id));
}
/// <summary>
/// Insert entity to database even though collection for this entity wasn't created yet.
/// </summary>
/// <typeparam name="T">Type of entity to insert</typeparam>
/// <param name="entity">Entity to insert</param>
public async Task InsertAsync<T>(T entity) where T : BaseEntity
{
await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseName),
new DocumentCollection { Id = typeof(T).Name });
await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name), entity);
}
/// <summary>
/// Insert entities to database even though collection for these entities was not created yet.
/// </summary>
/// <typeparam name="T">Type of entity to insert</typeparam>
/// <param name="entities">Entities to insert</param>
public async Task InsertAsync<T>(IEnumerable<T> entities) where T : BaseEntity
{
await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(DatabaseName),
new DocumentCollection { Id = typeof(T).Name });
foreach (var entity in entities)
await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name), entity);
}
public async Task UpsertAsync<T>(T entity) where T : BaseEntity
{
await _client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, typeof(T).Name), entity);
}
public async Task DeleteAsync<T>(string id) where T : BaseEntity
{
await _client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseName, typeof(T).Name, id));
}
}
}<file_sep>/CosmosDbTutorial.ConsoleApp/Program.cs
using System;
using System.Threading.Tasks;
using CosmosDbTutorial.DataAccess.Repository;
using CosmosDbTutorial.Entities;
namespace CosmosDbTutorial.ConsoleApp
{
public class Program
{
private static async Task Main()
{
var documentDbRepository = new DocumentDbRepository();
var mongoDbRepository = new MongoDbRepository();
await mongoDbRepository.InsertAsync(new Person
{
Name = "Dmytro"
});
await documentDbRepository.InsertAsync(new Person
{
Name = "Dmytro",
});
Console.WriteLine(
(await documentDbRepository.GetAsync<Person>("5980646860ed5943c0f1845b")).Name);
Console.WriteLine(
(await mongoDbRepository.GetAsync<Person>("598064fcc5886c8d0408a07d")).Name);
}
}
}<file_sep>/CosmosDbTutorial.DataAccess/BaseEntity.cs
using System;
using MongoDB.Bson;
namespace CosmosDbTutorial.DataAccess
{
public abstract class BaseEntity
{
// ReSharper disable once InconsistentNaming
public readonly string id = ObjectId.GenerateNewId(DateTime.Now).ToString();
}
}<file_sep>/CosmosDbTutorial.Configuration/Config.cs
using System.IO;
using Microsoft.Extensions.Configuration;
namespace CosmosDbTutorial.Configuration
{
public class Config
{
private static IConfigurationRoot Configuration { get; set; }
public static string DatabaseName => Configuration[nameof(DatabaseName)];
public static string DocumentDbPrimaryKey => Configuration[nameof(DocumentDbPrimaryKey)];
public static string DocumentDbEndpointUrl => Configuration[nameof(DocumentDbEndpointUrl)];
public static string MongoDbConnectionString => Configuration[nameof(MongoDbConnectionString)];
static Config()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
}
}
|
d8bd4c07de1ec31a4fcabd69c87379235edd2927
|
[
"Markdown",
"C#"
] | 9
|
Markdown
|
preddy4690/CosmosDbTutorial
|
b3d1e5ea885dc3f88116a2539bba1c16925e6720
|
04f32757d8dac1e61f5a67402db16af463f0494e
|
refs/heads/master
|
<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 20:24
* @file: BaseField.php
*/
namespace globalindex\phpmvc\form;
use globalindex\phpmvc\Model;
abstract class BaseField
{
public Model $model;
public string $attribute;
/**
* Field constructor.
* @param Model $model
* @param string $attribute
*/
public function __construct(Model $model, string $attribute)
{
$this->model = $model;
$this->attribute = $attribute;
}
abstract public function renderInput(): string;
public function __toString(): string
{
return sprintf('
<div class="mb-3">
<label>%s</label>
%s
<div class="invalid-feedback">%s</div>
</div>
',
$this->model->getLabel($this->attribute),
$this->renderInput(),
$this->model->getFirstError($this->attribute)
);
}
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 20:37
* @file: TextareaField.php
*/
namespace globalindex\phpmvc\form;
class TextareaField extends BaseField
{
public function renderInput(): string
{
return sprintf('<textarea name="%s" class="form-control%s">%s</textarea>',
$this->attribute,
$this->model->hasError($this->attribute) ? " is-invalid" : "",
$this->model->{$this->attribute}
);
}
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 18:48
* @file: ForbiddenException.php
*/
namespace globalindex\phpmvc\exception;
class ForbiddenException extends \Exception
{
protected $message = "You don't have permission to access this page";
protected $code = 403;
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 18:37
* @file: AuthMiddleware.php
*/
namespace globalindex\phpmvc\middlewares;
use globalindex\phpmvc\Application;
use globalindex\phpmvc\exception\ForbiddenException;
class AuthMiddleware extends BaseMiddleware
{
public array $actions = [];
/**
* AuthMiddleware constructor.
* @param array $actions
*/
public function __construct(array $actions = [])
{
$this->actions = $actions;
}
public function execute()
{
if (Application::isGuest()) {
if (empty($this->actions) || in_array(Application::$app->controller->action, $this->actions)) {
throw new ForbiddenException();
}
}
}
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 16:55
* @file: UserModel.php
*/
namespace globalindex\phpmvc;
use globalindex\phpmvc\db\DbModel;
abstract class UserModel extends DbModel
{
abstract public function getDisplayName(): string;
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 18:34
* @file: BaseMiddleware.php
*/
namespace globalindex\phpmvc\middlewares;
abstract class BaseMiddleware
{
abstract public function execute();
}<file_sep><?php
/**
* php-framework
*
* @autor: dimexis aka <NAME>
* @date: 03.04.21
* @time: 19:12
* @file: NotFoundException.php
*/
namespace globalindex\phpmvc\exception;
use Throwable;
class NotFoundException extends \Exception
{
protected $message = "Page not found";
protected $code = 404;
}
|
129a3330e5da94cb27169591a6b4f13b0d0d0e26
|
[
"PHP"
] | 7
|
PHP
|
globalindex/php-framework-core
|
b44a01c3eb48a110d958de0f8be3b0758fafb41e
|
e827d800ad33ad0010e83af75c6869cc15efe311
|
refs/heads/main
|
<file_sep>import './App.css';
import Parser from './Parser';
function App() {
return (
<div className="app">
<Parser />
{/* <Route path={`https://dev.pulsesecure.net/jira/browse/`}><ShowTicket /></Route> */}
</div>
);
}
export default App;
<file_sep>export const htmlContent = `div class="ghx-issues js-issue-list ghx-has-issues" data-skate-ignore="">
<div class="ghx-plan-dropzone"></div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="590020" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Minor"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/minor.svg"
alt="Priority: Minor"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26915"
title="PCS-26915"
class="js-key-link">PCS-26915</a></div>
<div class="ghx-summary"
title="21.x: UI: Criteria details for System Integrity Protection HC rule on mac does not align with 9.x">
<span class="ghx-inner">21.x: UI: Criteria
details for System Integrity Protection
HC rule on mac does not align with
9.x</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=hdarshan&avatarId=15810"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-4"
data-issue-id="590014" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Improvement"><img
alt="Issue Type: Improvement"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10310&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26911"
title="PCS-26911"
class="js-key-link">PCS-26911</a></div>
<div class="ghx-summary"
title="UI: Need option to select all roles in IF-MAP select roles page">
<span class="ghx-inner">UI: Need option to
select all roles in IF-MAP select roles
page</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589962" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26898"
title="PCS-26898"
class="js-key-link">PCS-26898</a></div>
<div class="ghx-summary"
title="Separate Microfrontend for resource profile">
<span class="ghx-inner">Separate
Microfrontend for resource
profile</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589961" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26897"
title="PCS-26897"
class="js-key-link">PCS-26897</a></div>
<div class="ghx-summary"
title="Separate Microfrontend for resource policy">
<span class="ghx-inner">Separate
Microfrontend for resource policy</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589960" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26896"
title="PCS-26896"
class="js-key-link">PCS-26896</a></div>
<div class="ghx-summary"
title="Separate Microfrontend for User role">
<span class="ghx-inner">Separate
Microfrontend for User role</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589929" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26890"
title="PCS-26890"
class="js-key-link">PCS-26890</a></div>
<div class="ghx-summary"
title="End user portal > VDI > Listing and styling for (Citrix and VMWare) ">
<span class="ghx-inner">End user portal >
VDI > Listing and styling for (Citrix
and VMWare) </span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nikunjc&avatarId=16654"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589927" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26888"
title="PCS-26888"
class="js-key-link">PCS-26888</a></div>
<div class="ghx-summary"
title="Host checker and remediate page">
<span class="ghx-inner">Host checker and
remediate page</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589918" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26885"
title="PCS-26885"
class="js-key-link">PCS-26885</a></div>
<div class="ghx-summary"
title="Implement gateway selector in header">
<span class="ghx-inner">Implement gateway
selector in header</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-11"
title="App Switcher and New Menu Navigation"
data-epickey="PCS-25418">App Switcher and
New Menu Navigation</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589815" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26866"
title="PCS-26866"
class="js-key-link">PCS-26866</a></div>
<div class="ghx-summary"
title="Separate Microfrontend for common Functions">
<span class="ghx-inner">Separate
Microfrontend for common
Functions</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-10"
title="Optimization"
data-epickey="PCS-26274">Optimization</span>
<span class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589796" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26859"
title="PCS-26859"
class="js-key-link">PCS-26859</a></div>
<div class="ghx-summary"
title="Separate Microfrontend for common Functions">
<span class="ghx-inner">Separate
Microfrontend for common
Functions</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-10"
title="Optimization"
data-epickey="PCS-26274">Optimization</span>
<span class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="589754" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Minor"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/minor.svg"
alt="Priority: Minor"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26853"
title="PCS-26853"
class="js-key-link"><KEY></a></div>
<div class="ghx-summary"
title="UI: Breadcrumb shows Resource Profiles instead of Resource Policies">
<span class="ghx-inner">UI: Breadcrumb shows
Resource Profiles instead of Resource
Policies</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="589724" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26846"
title="PCS-26846"
class="js-key-link">PCS-26846</a></div>
<div class="ghx-summary"
title="21.x: UI: Newly created Linux rules does not reflect in page, unless page is refreshed">
<span class="ghx-inner">21.x: UI: Newly
created Linux rules does not reflect in
page, unless page is refreshed</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.5">21.5</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=hdarshan&avatarId=15810"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.25</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589719" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26845"
title="PCS-26845"
class="js-key-link">PCS-26845</a></div>
<div class="ghx-summary"
title="Maintenance > import/export > System Configuration">
<span class="ghx-inner">Maintenance >
import/export > System
Configuration</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.6">21.6</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q2 - Maintenance UI"
data-epickey="<KEY>">Q2 - Maintenance
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589718" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26844"
title="PCS-26844"
class="js-key-link">PCS-26844</a></div>
<div class="ghx-summary"
title="Maintenance > Archiving > Local Backups">
<span class="ghx-inner">Maintenance >
Archiving > Local Backups</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.6">21.6</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q2 - Maintenance UI"
data-epickey="PCS-26840">Q2 - Maintenance
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/28fa727bb057a449f321eacac1c2b917?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="589717" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26843"
title="PCS-26843"
class="js-key-link">PCS-26843</a></div>
<div class="ghx-summary"
title="Maintenance > Archiving > Archiving Servers">
<span class="ghx-inner">Maintenance >
Archiving > Archiving Servers</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.6">21.6</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q2 - Maintenance UI"
data-epickey="PCS-26840">Q2 - Maintenance
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/28fa727bb057a449f321eacac1c2b917?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589710" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26841"
title="PCS-26841"
class="js-key-link">PCS-26841</a></div>
<div class="ghx-summary"
title="Revert PCS licensing functionality">
<span class="ghx-inner">Revert PCS licensing
functionality</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.4">21.4</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-4"
data-issue-id="589605" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Improvement"><img
alt="Issue Type: Improvement"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10310&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26823"
title="PCS-26823"
class="js-key-link">PCS-26823</a></div>
<div class="ghx-summary"
title="HC - Remove Solaris and Wince"><span
class="ghx-inner">HC - Remove Solaris
and Wince</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Host Checker UI"
data-epickey="PCS-26207">Q1-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=hdarshan&avatarId=15810"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589374" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26805"
title="PCS-26805"
class="js-key-link">PCS-26805</a></div>
<div class="ghx-summary"
title="Host Checker - mac - Custom - Command rule">
<span class="ghx-inner">Host Checker - mac -
Custom - Command rule</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="<KEY>">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589373" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26804"
title="PCS-26804"
class="js-key-link">PCS-26804</a></div>
<div class="ghx-summary"
title="Host Checker - iOS - Jail Breaking Detection rule">
<span class="ghx-inner">Host Checker - iOS -
Jail Breaking Detection rule</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="PCS-23624">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589372" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26803"
title="PCS-26803"
class="js-key-link">PCS-26803</a></div>
<div class="ghx-summary"
title="Host Checker - Android - Rooting detection rule">
<span class="ghx-inner">Host Checker -
Android - Rooting detection rule</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="<KEY>">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589315" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26777"
title="PCS-26777"
class="js-key-link">PCS-26777</a></div>
<div class="ghx-summary"
title="Enterprise Onboarding > VPN Profiles">
<span class="ghx-inner">Enterprise
Onboarding > VPN Profiles</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.6">21.6</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-14"
title="Q1 - Enterprise Onboarding"
data-epickey="PCS-26739">Q1 - Enterprise
Onboarding</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-4"
data-issue-id="589221" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Improvement"><img
alt="Issue Type: Improvement"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10310&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26758"
title="PCS-26758"
class="js-key-link">PCS-26758</a></div>
<div class="ghx-summary"
title="Grey light when adding server for the first time">
<span class="ghx-inner">Grey light when
adding server for the first time</span>
</div><span
class="aui-label ghx-label ghx-label-single ghx-label-8"
title="Q1-Auth Servers UI"
data-epickey="PCS-24613">Q1-Auth Servers
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589137" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26740"
title="PCS-26740"
class="js-key-link">PCS-26740</a></div>
<div class="ghx-summary"
title="Enterprise Onboarding > CSR Template">
<span class="ghx-inner">Enterprise
Onboarding > CSR Template</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.6">21.6</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-14"
title="Q1 - Enterprise Onboarding"
data-epickey="<KEY>">Q1 - Enterprise
Onboarding</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="589007" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26731"
title="PCS-26731"
class="js-key-link">PCS-26731</a></div>
<div class="ghx-summary"
title="Remove item> LDAP server type> iplanet and Novell eDirectory">
<span class="ghx-inner">Remove item> LDAP
server type> iplanet and Novell
eDirectory</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Auth Servers UI"
data-epickey="PCS-24613">Q1-Auth Servers
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588996" data-issue-key="PCS-26728">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26728"
title="PCS-26728"
class="js-key-link">PCS-26728</a></div>
<div class="ghx-summary"
title="Remove Item > User Roles > HTML 5 Access > Options">
<span class="ghx-inner">Remove Item >
User Roles > HTML 5 Access >
Options</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588995" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26727"
title="PCS-26727"
class="js-key-link">PCS-26727</a></div>
<div class="ghx-summary"
title="Remove Item > Resource Profile > HTML5 Access > add-edit > resource">
<span class="ghx-inner">Remove Item >
Resource Profile > HTML5 Access >
add-edit > resource</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588994" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26726"
title="PCS-26726"
class="js-key-link">PCS-26726</a></div>
<div class="ghx-summary"
title="Remove Item>Terminal Service> Resource Profile Listing">
<span class="ghx-inner">Remove
Item>Terminal Service> Resource
Profile Listing</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588990" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26725"
title="PCS-26725"
class="js-key-link">PCS-26725</a></div>
<div class="ghx-summary"
title="Remove Item>Resource Profiles->Terminal services ">
<span class="ghx-inner">Remove
Item>Resource Profiles->Terminal
services </span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="<KEY>">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588985" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26724"
title="PCS-26724"
class="js-key-link">PCS-26724</a></div>
<div class="ghx-summary"
title="Remove Item > User Roles->Terminal services-> Options > Enable Java for Remote Desktop Launcher ">
<span class="ghx-inner">Remove Item >
User Roles->Terminal services->
Options > Enable Java for Remote
Desktop Launcher </span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588911" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26685"
title="PCS-26685"
class="js-key-link">PCS-26685</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.files.unix-nfs-acls : /users/resource-policies/file-policies/file-nfs-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.files.unix-nfs-acls :
/users/resource-policies/file-policies/file-nfs-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588910" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26684"
title="PCS-26684"
class="js-key-link">PCS-26684</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.files.windows-credentials : /users/resource-policies/file-policies/file-win-sso-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.files.windows-credentials :
/users/resource-policies/file-policies/file-win-sso-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588909" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26683"
title="PCS-26683"
class="js-key-link">PCS-26683</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.files.windows-acls : /users/resource-policies/file-policies/file-win-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.files.windows-acls :
/users/resource-policies/file-policies/file-win-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588908" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26682"
title="PCS-26682"
class="js-key-link">PCS-26682</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.java-code-signing : /users/resource-policies/web-policies/codesigning-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.java-code-signing :
/users/resource-policies/web-policies/codesigning-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588907" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26681"
title="PCS-26681"
class="js-key-link">PCS-26681</a></div>
<div class="ghx-summary"
title="Rework] - API integration rework due to changes in API - Two identifiers - policies.web.java-acls : /users/resource-policies/web-policies/java-acls">
<span class="ghx-inner">Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.java-acls :
/users/resource-policies/web-policies/java-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588906" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26680"
title="PCS-26680"
class="js-key-link">PCS-26680</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.html5.acls : /users/resource-policies/html5-access-policies/html5-access-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers - policies.html5.acls
:
/users/resource-policies/html5-access-policies/html5-access-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588904" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26679"
title="PCS-26679"
class="js-key-link">PCS-26679</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.terminal-services.acls : /users/resource-policies/terminal-services-policies/terminal-services-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.terminal-services.acls :
/users/resource-policies/terminal-services-policies/terminal-services-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588903" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26678"
title="PCS-26678"
class="js-key-link">PCS-26678</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.compression : /users/resource-policies/web-policies/compression-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.compression :
/users/resource-policies/web-policies/compression-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588902" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26677"
title="PCS-26677"
class="js-key-link">PCS-26677</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.sso-basic-ntlm : /users/resource-policies/web-policies/sso-basic-ntlms">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.sso-basic-ntlm :
/users/resource-policies/web-policies/sso-basic-ntlms</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="588901" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26676"
title="PCS-26676"
class="js-key-link">PCS-26676</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.client-auth : /users/resource-policies/web-policies/client-authentications | Blocked on PCS-26385">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.client-auth :
/users/resource-policies/web-policies/client-authentications
| Blocked on PCS-26385</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588900" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26675"
title="PCS-26675"
class="js-key-link">PCS-26675</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.launch-jsam : /users/resource-policies/web-policies/launchjsam-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.launch-jsam :
/users/resource-policies/web-policies/launchjsam-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588899" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26674"
title="PCS-26674"
class="js-key-link">PCS-26674</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.remote-sso-headers : /users/resource-policies/web-policies/sso-headers">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.remote-sso-headers :
/users/resource-policies/web-policies/sso-headers</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588898" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26673"
title="PCS-26673"
class="js-key-link">PCS-26673</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.remote-sso-form-post : /users/resource-policies/web-policies/sso-posts">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.remote-sso-form-post :
/users/resource-policies/web-policies/sso-posts</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588897" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26672"
title="PCS-26672"
class="js-key-link">PCS-26672</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.files.windows-compression : policies.files.unix-compression : /users/resource-policies/file-policies/file-nfs-compression-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.files.windows-compression :
policies.files.unix-compression :
/users/resource-policies/file-policies/file-nfs-compression-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588896" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26671"
title="PCS-26671"
class="js-key-link">PCS-26671</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.files.windows-compression : /users/resource-policies/file-policies/file-win-compression-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.files.windows-compression :
/users/resource-policies/file-policies/file-win-compression-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588895" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26670"
title="PCS-26670"
class="js-key-link">PCS-26670</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.selective-rewriting : /users/resource-policies/web-policies/selective-rewrites">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers -
policies.web.selective-rewriting :
/users/resource-policies/web-policies/selective-rewrites</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588889" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26669"
title="PCS-26669"
class="js-key-link">PCS-26669</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.caching : /users/resource-policies/web-policies/caching/caching-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers - policies.web.caching
:
/users/resource-policies/web-policies/caching/caching-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588888" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26668"
title="PCS-26668"
class="js-key-link">PCS-26668</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.sam.acls : /users/resource-policies/sam-policies/sam-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers - policies.sam.acls :
/users/resource-policies/sam-policies/sam-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588887" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26667"
title="PCS-26667"
class="js-key-link">PCS-26667</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.ptp : /users/resource-policies/web-policies/ptps">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers - policies.web.ptp :
/users/resource-policies/web-policies/ptps</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588886" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26666"
title="PCS-26666"
class="js-key-link">PCS-26666</a></div>
<div class="ghx-summary"
title="[Rework] - API integration rework due to changes in API - Two identifiers - policies.web.acls : /users/resource-policies/web-policies/web-acls">
<span class="ghx-inner">[Rework] - API
integration rework due to changes in API
- Two identifiers - policies.web.acls :
/users/resource-policies/web-policies/web-acls</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588613" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26646"
title="PCS-26646"
class="js-key-link">PCS-26646</a></div>
<div class="ghx-summary"
title="Login-Another session and multi user">
<span class="ghx-inner">Login-Another
session and multi user</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-2"
title="Q1 - Sign In Workflow UI"
data-epickey="PCS-24827">Q1 - Sign In
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588610" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26645"
title="PCS-26645"
class="js-key-link">PCS-26645</a></div>
<div class="ghx-summary"
title="End user portal > Terminal Services > RDP Launch">
<span class="ghx-inner">End user portal >
Terminal Services > RDP Launch</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q1-End User Application UI"
data-epickey="<KEY>">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nikunjc&avatarId=16654"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588584" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26644"
title="PCS-26644"
class="js-key-link">PCS-26644</a></div>
<div class="ghx-summary"
title="End user portal > Terminal Services > Listing">
<span class="ghx-inner">End user portal >
Terminal Services > Listing</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nikunjc&avatarId=16654"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001 ghx-flagged"
data-issue-id="588570" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-flag"><span
class="ghx-iconfont aui-icon aui-icon-small aui-iconfont-flag"
title="Flagged"></span></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26643"
title="PCS-26643"
class="js-key-link">PCS-26643</a></div>
<div class="ghx-summary"
title="Host Checker - Mobile Platforms- Predefined - OS Check rule">
<span class="ghx-inner">Host Checker -
Mobile Platforms- Predefined - OS Check
rule</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="PCS-23624">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588480" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26630"
title="PCS-26630"
class="js-key-link">PCS-26630</a></div>
<div class="ghx-summary"
title="End user portal > Terminal Services > Citrix Launch">
<span class="ghx-inner">End user portal >
Terminal Services > Citrix
Launch</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nikunjc&avatarId=16654"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588479" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26629"
title="PCS-26629"
class="js-key-link">PCS-26629</a></div>
<div class="ghx-summary"
title="End user portal > Terminal Services > Windows Launch">
<span class="ghx-inner">End user portal >
Terminal Services > Windows
Launch</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nikunjc&avatarId=16654"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588168" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26581"
title="PCS-26581"
class="js-key-link">PCS-26581</a></div>
<div class="ghx-summary"
title="HTML for Maintenance XML import/export">
<span class="ghx-inner">HTML for Maintenance
XML import/export</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-3"
title="PCS HTML Tasks for Q1 - 2021"
data-epickey="<KEY>">PCS HTML Tasks for
Q1 - 2021</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ce286debd161ee86c5acd50cece8d541?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588167" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26580"
title="PCS-26580"
class="js-key-link">PCS-26580</a></div>
<div class="ghx-summary"
title="HTML for Archiving servers"><span
class="ghx-inner">HTML for Archiving
servers</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-3"
title="PCS HTML Tasks for Q1 - 2021"
data-epickey="PCS-24452">PCS HTML Tasks for
Q1 - 2021</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ce286debd161ee86c5acd50cece8d541?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="588054" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26570"
title="PCS-26570"
class="js-key-link">PCS-26570</a></div>
<div class="ghx-summary"
title="AD auth and LDAP auth login pages">
<span class="ghx-inner">AD auth and LDAP
auth login pages</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="587840" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26530"
title="PCS-26530"
class="js-key-link">PCS-26530</a></div>
<div class="ghx-summary"
title="config validation implementation with proper error message | Blocked on Config Validation">
<span class="ghx-inner">config validation
implementation with proper error message
| Blocked on Config Validation</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-4"
title="Config Validation for overlay DB"
data-epickey="PCS-26529">Config Validation
for overlay DB</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="587815" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26527"
title="PCS-26527"
class="js-key-link">PCS-26527</a></div>
<div class="ghx-summary"
title="HTML for terminal service sessions and HTML5 access session">
<span class="ghx-inner">HTML for terminal
service sessions and HTML5 access
session</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ce286debd161ee86c5acd50cece8d541?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-1"
data-issue-id="586775" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26338"
title="PCS-26338"
class="js-key-link">PCS-26338</a></div>
<div class="ghx-summary"
title="Issue with Virtual desktop resource profile create">
<span class="ghx-inner">Issue with Virtual
desktop resource profile create</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/28fa727bb057a449f321eacac1c2b917?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-1"
data-issue-id="586660" data-issue-key="PCS-26327">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26327"
title="PCS-26327"
class="js-key-link">PCS-26327</a></div>
<div class="ghx-summary"
title="Certificate Workflow Feedback"><span
class="ghx-inner">Certificate Workflow
Feedback</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q4-Certificate Workflow UI"
data-epickey="<KEY>">Q4-Certificate
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="586383" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26266"
title="PCS-26266"
class="js-key-link">PCS-26266</a></div>
<div class="ghx-summary"
title="HTML for Enterprise On-boarding all the tabs">
<span class="ghx-inner">HTML for Enterprise
On-boarding all the tabs</span></div>
<span
class="aui-label ghx-label ghx-label-single ghx-label-3"
title="PCS HTML Tasks for Q1 - 2021"
data-epickey="PCS-24452">PCS HTML Tasks for
Q1 - 2021</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ce286debd161ee86c5acd50cece8d541?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="586364" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26254"
title="PCS-26254"
class="js-key-link">PCS-26254</a></div>
<div class="ghx-summary"
title="Auth Server > MDM > Mobile Iron > test connection API integration">
<span class="ghx-inner">Auth Server > MDM
> Mobile Iron > test connection
API integration</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Auth Servers UI"
data-epickey="PCS-24613">Q1-Auth Servers
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/28fa727bb057a449f321eacac1c2b917?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: An<NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="586361" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26252"
title="PCS-26252"
class="js-key-link">PCS-26252</a></div>
<div class="ghx-summary"
title="Totp Auth Register and Totp Auth Token Entry and Pre-Post sign in notification">
<span class="ghx-inner">Totp Auth Register
and Totp Auth Token Entry and Pre-Post
sign in notification</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="586359" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26251"
title="PCS-26251"
class="js-key-link">PCS-26251</a></div>
<div class="ghx-summary"
title="ACE server for New pin and Next token">
<span class="ghx-inner">ACE server for New
pin and Next token</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="586287" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26239"
title="PCS-26239"
class="js-key-link">PCS-26239</a></div>
<div class="ghx-summary"
title="All Login pages and Logout page">
<span class="ghx-inner">All Login pages and
Logout page</span></div><span
class="aui-label ghx-label ghx-label-single ghx-label-12"
title="Q1-End User Application UI"
data-epickey="PCS-26061">Q1-End User
Application UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rladumor&avatarId=17201"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="586007" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26172"
title="PCS-26172"
class="js-key-link">PCS-26172</a></div>
<div class="ghx-summary"
title="Code signing certificates"><span
class="ghx-inner">Code signing
certificates</span></div><span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="585594" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26129"
title="PCS-26129"
class="js-key-link">PCS-26129</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Encoding > Detailed Rules > New/Edit rule with Conditions Dictionary ">
<span class="ghx-inner">Resource Policies
> Web > Encoding > Detailed
Rules > New/Edit rule with Conditions
Dictionary </span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="585589" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26124"
title="PCS-26124"
class="js-key-link">PCS-26124</a></div>
<div class="ghx-summary"
title="Resource Policies > Terminal > Access > Detailed Rules > New/Edit rule with Conditions Dictionary ">
<span class="ghx-inner">Resource Policies
> Terminal > Access > Detailed
Rules > New/Edit rule with Conditions
Dictionary </span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q1-Resource Policies-Terminal Service UI"
data-epickey="PCS-26120">Q1-Resource
Policies-Terminal Service UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="584932" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26009"
title="PCS-26009"
class="js-key-link">PCS-26009</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Rewriting > Rewriting Filters > Add/Edit">
<span class="ghx-inner">Resource Policies
> Web > Rewriting > Rewriting
Filters > Add/Edit</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="584930" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-26007"
title="PCS-26007"
class="js-key-link">PCS-26007</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Protocol > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> Web > Protocol > Detailed
Rules > New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: Deep Manek"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="584918" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25996"
title="PCS-25996"
class="js-key-link">PCS-25996</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Web Proxy > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> Web > Web Proxy > Detailed
Rules > New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="584909" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25988"
title="PCS-25988"
class="js-key-link">PCS-25988</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Rewriting > Cross domain access > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> Web > Rewriting > Cross
domain access > Detailed Rules >
New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="584342" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25879"
title="PCS-25879"
class="js-key-link">PCS-25879</a></div>
<div class="ghx-summary"
title="Implement CRL & OCSP APIs"><span
class="ghx-inner">Implement CRL &
OCSP APIs</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.3">21.3</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q4-Certificate Workflow UI"
data-epickey="<KEY>">Q4-Certificate
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">8</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="584258" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25856"
title="PCS-25856"
class="js-key-link">PCS-25856</a></div>
<div class="ghx-summary"
title="Resource Policies > SSH > Access > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> SSH > Access > Detailed Rules
> New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-Resource Policies-SSH UI"
data-epickey="<KEY>">Q1-Resource
Policies-SSH UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="584243" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25845"
title="PCS-25845"
class="js-key-link">PCS-25845</a></div>
<div class="ghx-summary"
title="Resource Policies > Files > SSO > Windows > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> Files > SSO > Windows >
Detailed Rules > New/Edit rule with
Conditions Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-2"
title="Q1-Resource Policies-File UI"
data-epickey="PCS-25826">Q1-Resource
Policies-File UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="569150" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Critical"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/critical.svg"
alt="Priority: Critical"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25833"
title="PCS-25833"
class="js-key-link">PCS-25833</a></div>
<div class="ghx-summary"
title="21.x PCS: Network Routes configuration page wants an API to fetch latest network route status of all the interfaces">
<span class="ghx-inner">21.x PCS: Network
Routes configuration page wants an API
to fetch latest network route status of
all the interfaces</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="REST APIs: Common PCS pages"
data-epickey="PCS-23054">REST APIs: Common
PCS pages</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">6</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583982" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Critical"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/critical.svg"
alt="Priority: Critical"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25784"
title="PCS-25784"
class="js-key-link">PCS-25784</a></div>
<div class="ghx-summary"
title="As an admin, i want an API to configure Telemetry options">
<span class="ghx-inner">As an admin, i want
an API to configure Telemetry
options</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-11"
title="REST APIs for Q1 Deliverables"
data-epickey="PCS-25059">REST APIs for Q1
Deliverables</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="583607" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25723"
title="PCS-25723"
class="js-key-link">PCS-25723</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > SSO > General > Kerberos > Constrained Delegation > Service List">
<span class="ghx-inner">Resource Policies
> Web > SSO > General >
Kerberos > Constrained Delegation
> Service List</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583604" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25722"
title="PCS-25722"
class="js-key-link">PCS-25722</a></div>
<div class="ghx-summary"
title="Resource Policies > web > java > Code-Signing > detailed rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> web > java > Code-Signing
> detailed rules > New/Edit rule
with Conditions Dictionary</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583585" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25709"
title="PCS-25709"
class="js-key-link">PCS-25709</a></div>
<div class="ghx-summary"
title="Resource Policies > web > SSO > Headers/Cookies > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> web > SSO > Headers/Cookies
> Detailed Rules > New/Edit rule
with Conditions Dictionary</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583483" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25674"
title="PCS-25674"
class="js-key-link">PCS-25674</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Rewriting > Selective Rewriting > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> Web > Rewriting > Selective
Rewriting > Detailed Rules >
New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583169" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25636"
title="PCS-25636"
class="js-key-link">PCS-25636</a></div>
<div class="ghx-summary"
title="Resource Policies > web > SSO (Single Sign-on) > Form POST > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> web > SSO (Single Sign-on) >
Form POST > Detailed Rules >
New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583123" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25617"
title="PCS-25617"
class="js-key-link">PCS-25617</a></div>
<div class="ghx-summary"
title="Resource Policies > web > WEB ACL > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> web > WEB ACL > Detailed
Rules > New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="583110" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25611"
title="PCS-25611"
class="js-key-link">PCS-25611</a></div>
<div class="ghx-summary"
title="Resource Policies > Web > Client Authentication > Detailed Rules > New rule with Conditions Dictionary | Blocked on PCS-26385">
<span class="ghx-inner">Resource Policies
> Web > Client Authentication >
Detailed Rules > New rule with
Conditions Dictionary | Blocked on
PCS-26385</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="<KEY>">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583103" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25606"
title="PCS-25606"
class="js-key-link">PCS-25606</a></div>
<div class="ghx-summary"
title="Resource Policies > web > caching > Detailed Rules > New/Edit rule with Conditions Dictionary">
<span class="ghx-inner">Resource Policies
> web > caching > Detailed
Rules > New/Edit rule with Conditions
Dictionary</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="583101" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25604"
title="PCS-25604"
class="js-key-link">PCS-25604</a></div>
<div class="ghx-summary"
title="Resource Policies > web > caching > delete ">
<span class="ghx-inner">Resource Policies
> web > caching > delete
</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-8"
title="Q1-Resource Policies-Web UI"
data-epickey="PCS-25443">Q1-Resource
Policies-Web UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="582594" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25514"
title="PCS-25514"
class="js-key-link">PCS-25514</a></div>
<div class="ghx-summary"
title="Resource Profile > web - Hosted Java applet > resource tab > add/edit ">
<span class="ghx-inner">Resource Profile
> web - Hosted Java applet >
resource tab > add/edit </span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="<KEY>">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="581823" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25348"
title="PCS-25348"
class="js-key-link">PCS-25348</a></div>
<div class="ghx-summary"
title="Roles/permission and licensing check in New Navigation Menu">
<span class="ghx-inner">Roles/permission and
licensing check in New Navigation
Menu</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-11"
title="App Switcher and New Menu Navigation"
data-epickey="<KEY>">App Switcher and
New Menu Navigation</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="581757" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25339"
title="PCS-25339"
class="js-key-link">PCS-25339</a></div>
<div class="ghx-summary"
title="UX-304 HTML for Cloud secure configuration basic ">
<span class="ghx-inner">UX-304 HTML for
Cloud secure configuration basic </span>
</div><span
class="aui-label ghx-label ghx-label-single ghx-label-3"
title="PCS HTML Tasks for Q1 - 2021"
data-epickey="PCS-24452">PCS HTML Tasks for
Q1 - 2021</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ce286debd161ee86c5acd50cece8d541?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="580234" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25127"
title="PCS-25127"
class="js-key-link">PCS-25127</a></div>
<div class="ghx-summary"
title="Resource Profiles > Virtual Desktops > Resource add/edit">
<span class="ghx-inner">Resource Profiles
> Virtual Desktops > Resource
add/edit</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/28fa727bb057a449f321eacac1c2b917?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="579723" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25021"
title="PCS-25021"
class="js-key-link">PCS-25021</a></div>
<div class="ghx-summary"
title="Resource Profile > HTML5 Access > add > bookmark duplicate">
<span class="ghx-inner">Resource Profile
> HTML5 Access > add > bookmark
duplicate</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="579722" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-25020"
title="PCS-25020"
class="js-key-link">PCS-25020</a></div>
<div class="ghx-summary"
title="Resource Profile > HTML5 Access > add > bookmark add/edit | Blocked on PCS-26871, PCS-26872">
<span class="ghx-inner">Resource Profile
> HTML5 Access > add > bookmark
add/edit | Blocked on PCS-26871,
PCS-26872</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-13"
title="Q1-Users Resource Profile UI"
data-epickey="PCS-24642">Q1-Users Resource
Profile UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="579634" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24988"
title="PCS-24988"
class="js-key-link">PCS-24988</a></div>
<div class="ghx-summary"
title="User Role > Terminal Services > Sessions > Add > Resource Profile | Blocked on PCS-24954">
<span class="ghx-inner">User Role >
Terminal Services > Sessions > Add
> Resource Profile | Blocked on
PCS-24954</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="579505" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24975"
title="PCS-24975"
class="js-key-link">PCS-24975</a></div>
<div class="ghx-summary"
title="User Role > File > Windows Bookmarks > Add ( Files Resource Profile )">
<span class="ghx-inner">User Role > File
> Windows Bookmarks > Add ( Files
Resource Profile )</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="579042" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24831"
title="PCS-24831"
class="js-key-link">PCS-24831</a></div>
<div class="ghx-summary"
title="Sign in Pages - Add/Edit - Notifications & Help (Excluding. Meeting type)">
<span class="ghx-inner">Sign in Pages -
Add/Edit - Notifications & Help
(Excluding. Meeting type)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-2"
title="Q1 - Sign In Workflow UI"
data-epickey="<KEY>">Q1 - Sign In
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="579041" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24830"
title="PCS-24830"
class="js-key-link">PCS-24830</a></div>
<div class="ghx-summary"
title="Sign in Pages - Add/Edit - Header & Error Messages Tab (Excluding. Meeting type)">
<span class="ghx-inner">Sign in Pages -
Add/Edit - Header & Error Messages
Tab (Excluding. Meeting type)</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-2"
title="Q1 - Sign In Workflow UI"
data-epickey="<KEY>">Q1 - Sign In
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="579040" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24829"
title="PCS-24829"
class="js-key-link">PCS-24829</a></div>
<div class="ghx-summary"
title="Sign in Pages - Add/Edit - Page Customization Tab (Excluding. Meeting type)">
<span class="ghx-inner">Sign in Pages -
Add/Edit - Page Customization Tab
(Excluding. Meeting type)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-2"
title="Q1 - Sign In Workflow UI"
data-epickey="PCS-24827">Q1 - Sign In
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1.5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="578958" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24808"
title="PCS-24808"
class="js-key-link">PCS-24808</a></div>
<div class="ghx-summary"
title="Shutdown Guest OS and Restart Guest OS commands are not available on 21.2 PCS VM">
<span class="ghx-inner">Shutdown Guest OS
and Restart Guest OS commands are not
available on 21.2 PCS VM</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-single"
title="21.4">21.4</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="578757" data-issue-key="PCS-24734">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24734"
title="PCS-24734"
class="js-key-link">PCS-24734</a></div>
<div class="ghx-summary"
title="User Role > Terminal Services > Option > Edit | Blocked on PCS-26653">
<span class="ghx-inner">User Role >
Terminal Services > Option > Edit
| Blocked on PCS-26653</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="578654" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Blocker"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/blocker.svg"
alt="Priority: Blocker"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24722"
title="PCS-24722"
class="js-key-link">PCS-24722</a></div>
<div class="ghx-summary"
title="User Role > SAM > Application > JSAM > Edit">
<span class="ghx-inner">User Role > SAM
> Application > JSAM >
Edit</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f38d7567af3e8db0cc2dc69edcc14e75?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-3"
data-issue-id="578644" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Task"><img alt="Issue Type: Task"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24718"
title="PCS-24718"
class="js-key-link">PCS-24718</a></div>
<div class="ghx-summary"
title="Get public IP for bng-pcs-gateway from IT">
<span class="ghx-inner">Get public IP for
bng-pcs-gateway from IT</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.1">21.1</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-4"
title="Setup DFS for 21.x PCS Gateway"
data-epickey="PCS-24712">Setup DFS for 21.x
PCS Gateway</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-3"
data-issue-id="578643" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Task"><img alt="Issue Type: Task"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24717"
title="PCS-24717"
class="js-key-link">PCS-24717</a></div>
<div class="ghx-summary"
title="Configure L3 access on 21.x DFS">
<span class="ghx-inner">Configure L3 access
on 21.x DFS</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.1">21.1</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-4"
title="Setup DFS for 21.x PCS Gateway"
data-epickey="PCS-24712">Setup DFS for 21.x
PCS Gateway</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-3"
data-issue-id="578642" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Task"><img alt="Issue Type: Task"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24716"
title="PCS-24716"
class="js-key-link">PCS-24716</a></div>
<div class="ghx-summary"
title="Configure L7 access on 21.x DFS">
<span class="ghx-inner">Configure L7 access
on 21.x DFS</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.1">21.1</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-4"
title="Setup DFS for 21.x PCS Gateway"
data-epickey="<KEY>">Setup DFS for 21.x
PCS Gateway</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="578317" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24662"
title="PCS-24662"
class="js-key-link">PCS-24662</a></div>
<div class="ghx-summary"
title="IF-MAP > This Client > Session-Import Policies > Delete">
<span class="ghx-inner">IF-MAP > This
Client > Session-Import Policies >
Delete</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q1-IF-Map Federation UI"
data-epickey="<KEY>">Q1-IF-Map
Federation UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="578316" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24661"
title="PCS-24661"
class="js-key-link">PCS-24661</a></div>
<div class="ghx-summary"
title="IF-MAP > This Client > Session-Import Policies > Duplicate">
<span class="ghx-inner">IF-MAP > This
Client > Session-Import Policies >
Duplicate</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q1-IF-Map Federation UI"
data-epickey="PCS-24649">Q1-IF-Map
Federation UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="578315" data-issue-key="PCS-24660">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24660"
title="PCS-24660"
class="js-key-link">PCS-24660</a></div>
<div class="ghx-summary"
title="IF-MAP > This Client > Session-Import Policies > Listing & Move up-down">
<span class="ghx-inner">IF-MAP > This
Client > Session-Import Policies >
Listing & Move up-down</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q1-IF-Map Federation UI"
data-epickey="PCS-24649">Q1-IF-Map
Federation UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/bb52d2e8a02a2b2e6509abcfceace16b?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="578140" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24603"
title="PCS-24603"
class="js-key-link">PCS-24603</a></div>
<div class="ghx-summary"
title="User Roles > Web > Bookmark > Add">
<span class="ghx-inner">User Roles > Web
> Bookmark > Add</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q1-User Roles Configuration UI"
data-epickey="PCS-24597">Q1-User Roles
Configuration UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="577106" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Minor"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/minor.svg"
alt="Priority: Minor"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24425"
title="PCS-24425"
class="js-key-link">PCS-24425</a></div>
<div class="ghx-summary"
title="Networking - ARP Cache Dynamic Entries Implementation | Blocked on PCS-23703">
<span class="ghx-inner">Networking - ARP
Cache Dynamic Entries Implementation |
Blocked on PCS-23703</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Networking Workflow UI"
data-epickey="PCS-23305">Q4-Networking
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="575500" data-issue-key="PCS-24217">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24217"
title="PCS-24217"
class="js-key-link">PCS-24217</a></div>
<div class="ghx-summary"
title="Need Api for Pulse Secure MIB file in Log -> SNMP">
<span class="ghx-inner">Need Api for Pulse
Secure MIB file in Log -> SNMP</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="REST APIs: Common PCS pages"
data-epickey="<KEY>">REST APIs: Common
PCS pages</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001 ghx-flagged"
data-issue-id="575267" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-flag"><span
class="ghx-iconfont aui-icon aui-icon-small aui-iconfont-flag"
title="Flagged"></span></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24185"
title="PCS-24185"
class="js-key-link">PCS-24185</a></div>
<div class="ghx-summary"
title="Host Checker - Win- Predefined- CVE check">
<span class="ghx-inner">Host Checker - Win-
Predefined- CVE check</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="PCS-23624">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001 ghx-flagged"
data-issue-id="575254" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-flag"><span
class="ghx-iconfont aui-icon aui-icon-small aui-iconfont-flag"
title="Flagged"></span></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24178"
title="PCS-24178"
class="js-key-link">PCS-24178</a></div>
<div class="ghx-summary"
title="Host Checker - Mac - Predefined-OS Check rule">
<span class="ghx-inner">Host Checker - Mac -
Predefined-OS Check rule</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="<KEY>">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">1</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001 ghx-flagged"
data-issue-id="575253" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-flag"><span
class="ghx-iconfont aui-icon aui-icon-small aui-iconfont-flag"
title="Flagged"></span></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24177"
title="PCS-24177"
class="js-key-link">PCS-24177</a></div>
<div class="ghx-summary"
title="End-point Security Workflow - Host Checker - Win - Predefined-OS Check rule">
<span class="ghx-inner">End-point Security
Workflow - Host Checker - Win -
Predefined-OS Check rule</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-9"
title="Q4-Host Checker UI"
data-epickey="PCS-23624">Q4-Host Checker
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=asifv&avatarId=16640"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574893" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24112"
title="PCS-24112"
class="js-key-link">PCS-24112</a></div>
<div class="ghx-summary"
title="Sign In Workflow - SAML - SP - Edit (manual)">
<span class="ghx-inner">Sign In Workflow -
SAML - SP - Edit (manual)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Sign In Workflow UI"
data-epickey="<KEY>">Q4-Sign In Workflow
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: Deep Manek"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574888" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24110"
title="PCS-24110"
class="js-key-link">PCS-24110</a></div>
<div class="ghx-summary"
title="Sign In Workflow - SAML - SP - Edit (metadata)">
<span class="ghx-inner">Sign In Workflow -
SAML - SP - Edit (metadata)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Sign In Workflow UI"
data-epickey="PCS-23943">Q4-Sign In Workflow
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: Deep Manek"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">3</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574887" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24109"
title="PCS-24109"
class="js-key-link">PCS-24109</a></div>
<div class="ghx-summary"
title="Sign In Workflow - SAML - SP - Add (manual)">
<span class="ghx-inner">Sign In Workflow -
SAML - SP - Add (manual)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Sign In Workflow UI"
data-epickey="PCS-23943">Q4-Sign In Workflow
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: Deep Manek"
data-tooltip="Assignee: Deep Manek">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574886" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24108"
title="PCS-24108"
class="js-key-link">PCS-24108</a></div>
<div class="ghx-summary"
title="Sign In Workflow - SAML - SP - Add (metadata)">
<span class="ghx-inner">Sign In Workflow -
SAML - SP - Add (metadata)</span></div>
<span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Sign In Workflow UI"
data-epickey="PCS-23943">Q4-Sign In Workflow
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f3029ca189d204aa302bfa46cff29819?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574799" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24089"
title="PCS-24089"
class="js-key-link">PCS-24089</a></div>
<div class="ghx-summary"
title="User Role - Listing - ACL Resource Policies: VPN Tunneling">
<span class="ghx-inner">User Role - Listing
- ACL Resource Policies: VPN
Tunneling</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q4-User Role UI"
data-epickey="PCS-23686">Q4-User Role
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574798" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24088"
title="PCS-24088"
class="js-key-link">PCS-24088</a></div>
<div class="ghx-summary"
title="User Role - Listing - Bookmark:All">
<span class="ghx-inner">User Role - Listing
- Bookmark:All</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q4-User Role UI"
data-epickey="<KEY>">Q4-User Role
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="574797" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24087"
title="PCS-24087"
class="js-key-link">PCS-24087</a></div>
<div class="ghx-summary"
title="User Role - Listing - Role mapping rules & realms">
<span class="ghx-inner">User Role - Listing
- Role mapping rules & realms</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q4-User Role UI"
data-epickey="PCS-23686">Q4-User Role
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/f55549d72813e5548cc60ba14f232ae0?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-1"
data-issue-id="574747" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Bug"><img alt="Issue Type: Bug"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10303&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Blocker"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/blocker.svg"
alt="Priority: Blocker"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24084"
title="PCS-24084"
class="js-key-link">PCS-24084</a></div>
<div class="ghx-summary"
title="Unable to create new Pulse client connection set with REST API also need to know to relations/mapping for options table">
<span class="ghx-inner">Unable to create new
Pulse client connection set with REST
API also need to know to
relations/mapping for options
table</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="REST APIs: Common PCS pages"
data-epickey="PCS-23054">REST APIs: Common
PCS pages</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">6</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="574521" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24036"
title="PCS-24036"
class="js-key-link">PCS-24036</a></div>
<div class="ghx-summary"
title="Connection type (L3)"><span
class="ghx-inner">Connection type
(L3)</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q4-Pulse Secure Client Workflow UI"
data-epickey="PCS-24029">Q4-Pulse Secure
Client Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">7</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="574517" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-24034"
title="PCS-24034"
class="js-key-link">PCS-24034</a></div>
<div class="ghx-summary"
title="Add / Edit Connection set"><span
class="ghx-inner">Add / Edit Connection
set</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="Q4-Pulse Secure Client Workflow UI"
data-epickey="PCS-24029">Q4-Pulse Secure
Client Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="573631" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23847"
title="PCS-23847"
class="js-key-link">PCS-23847</a></div>
<div class="ghx-summary"
title="User Role - General - VLAN/Source IP - stand-alone PCS">
<span class="ghx-inner">User Role - General
- VLAN/Source IP - stand-alone
PCS</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-1"
title="Q4-User Role UI"
data-epickey="PCS-23686">Q4-User Role
UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=rjitani&avatarId=16707"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">2</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="572854" data-issue-key="PCS-23714">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Critical"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/critical.svg"
alt="Priority: Critical"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23714"
title="PCS-23714"
class="js-key-link">PCS-23714</a></div>
<div class="ghx-summary"
title="As an admin provide an API to import signed certificate against CSR">
<span class="ghx-inner">As an admin provide
an API to import signed certificate
against CSR</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="REST APIs: Common PCS pages"
data-epickey="PCS-23054">REST APIs: Common
PCS pages</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">20</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001"
data-issue-id="572851" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Critical"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/critical.svg"
alt="Priority: Critical"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23711"
title="PCS-23711"
class="js-key-link">PCS-23711</a></div>
<div class="ghx-summary"
title="API to import "device certificate" and "client auth certificate" with all 2 options">
<span class="ghx-inner">API to import
"device certificate" and "client auth
certificate" with all 2 options</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-12"
title="REST APIs: Common PCS pages"
data-epickey="<KEY>">REST APIs: Common
PCS pages</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">20</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="571098" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23433"
title="PCS-23433"
class="js-key-link">PCS-23433</a></div>
<div class="ghx-summary"
title="Certificate - Client Authentication">
<span class="ghx-inner">Certificate - Client
Authentication</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q4-Certificate Workflow UI"
data-epickey="PCS-23428">Q4-Certificate
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">9</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="571092" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23430"
title="PCS-23430"
class="js-key-link">PCS-23430</a></div>
<div class="ghx-summary"
title="Certificate - CSR"><span
class="ghx-inner">Certificate -
CSR</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q4-Certificate Workflow UI"
data-epickey="<KEY>">Q4-Certificate
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">5</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="571091" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23429"
title="PCS-23429"
class="js-key-link">PCS-23429</a></div>
<div class="ghx-summary"
title="Certificate - List-Import-delete-edit of Device certificates">
<span class="ghx-inner">Certificate -
List-Import-delete-edit of Device
certificates</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Q4-Certificate Workflow UI"
data-epickey="PCS-23428">Q4-Certificate
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=sclark&avatarId=16520"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">6</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="570898" data-issue-key="PCS-23391">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23391"
title="PCS-23391"
class="js-key-link">PCS-23391</a></div>
<div class="ghx-summary"
title="Networking - External Port - ND Cache - List-Delete | Blocked on PCS-24679">
<span class="ghx-inner">Networking -
External Port - ND Cache - List-Delete |
Blocked on PCS-24679</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Networking Workflow UI"
data-epickey="PCS-23305">Q4-Networking
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="570605" data-issue-key="PCS-23351">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23351"
title="PCS-23351"
class="js-key-link">PCS-23351</a></div>
<div class="ghx-summary"
title="Networking - Internal Port - ND Cache - Add-Edit-Delete-List | Blocked on PCS-24679">
<span class="ghx-inner">Networking -
Internal Port - ND Cache -
Add-Edit-Delete-List | Blocked on
PCS-24679</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-3"
title="Q4-Networking Workflow UI"
data-epickey="<KEY>">Q4-Networking
Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=nsaxena&avatarId=16702"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">0</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-type-10001"
data-issue-id="569317" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority" title="Major"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/major.svg"
alt="Priority: Major"></span></div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-23139"
title="PCS-23139"
class="js-key-link">PCS-23139</a></div>
<div class="ghx-summary"
title="Auth Server - Enable Auth Traffic Control in Auth Server Listing Page">
<span class="ghx-inner">Auth Server - Enable
Auth Traffic Control in Auth Server
Listing Page</span></div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.5">21.5</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-4"
title="Q4-Authentication Server Workflow UI"
data-epickey="<KEY>">Q4-Authentication
Server Workflow UI</span> <span
class="ghx-end ghx-estimate"><img
src="https://www.gravatar.com/avatar/ccbcd816f9422be4f8ae04eb58085bd7?d=mm&s=48"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points">4</aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="js-issue js-sortable js-parent-drag ghx-issue-compact ghx-not-rankable ghx-done ghx-type-10001 ghx-selected ghx-selected-primary"
data-issue-id="564312" data-issue-key="<KEY>">
<div class="ghx-issue-content">
<div class="ghx-row"><span class="ghx-type"
title="Story"><img alt="Issue Type: Story"
src="https://dev.pulsesecure.net/jira/secure/viewavatar?size=xsmall&avatarId=10315&avatarType=issuetype"></span>
<div class="ghx-flags"><span
class="ghx-priority"
title="Blocker"><img
src="https://dev.pulsesecure.net/jira/images/icons/priorities/blocker.svg"
alt="Priority: Blocker"></span>
</div>
<div class="ghx-key"><a
href="https://dev.pulsesecure.net/jira/browse/PCS-22481"
title="PCS-22481"
class="js-key-link">PCS-22481</a></div>
<div class="ghx-summary"
title="[ListAPI]Improve config view by responding with annotations of config blocks">
<span class="ghx-inner">[ListAPI]Improve
config view by responding with
annotations of config blocks</span>
</div><span
class="aui-label ghx-label-0 ghx-label ghx-label-double"
title="21.4">21.4</span> <span
class="aui-label ghx-label ghx-label-double ghx-label-6"
title="Headless Gateway Config authoring building blocks Phase2"
data-epickey="PCS-23052">Headless Gateway
Config authoring building blocks
Phase2</span> <span
class="ghx-end ghx-estimate"><img
src="https://dev.pulsesecure.net/jira/secure/useravatar?ownerId=darumuga&avatarId=14906"
class="ghx-avatar-img"
alt="Assignee: <NAME>"
data-tooltip="Assignee: <NAME>">
<aui-badge class=" ghx-statistic-badge"
title="Story Points"> </aui-badge>
</span>
</div>
</div>
<div class="ghx-grabber ghx-grabber-transparent"></div>
<div class="ghx-move-count"><b></b></div>
</div>
<div class="ghx-helper">
<div class="ghx-description">All issues in this sprint
are currently filtered</div>
</div>
</div>`
|
07dfecfc225887eec30768ec9729c3f42c01c983
|
[
"JavaScript"
] | 2
|
JavaScript
|
yash-k-simformsolutions/HTML-Parser
|
066e9209f17ab28ccb20ef74dce007611be709ea
|
cebe378e7c98930504b6b2172dcf258724645096
|
refs/heads/master
|
<repo_name>MusicPlayer-Java/MusicWeb<file_sep>/testjar/src/main/java/SqlHelper.java
import java.sql.*;
import java.util.*;
public class SqlHelper {
public static Connection conn = null;
public static Statement stat = null;
// 连接数据库
public static void getConnection()
{
try
{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:music.db");
stat = conn.createStatement();
stat.executeUpdate( "create table if not exists Sheet(SheetId VARCHAR(50) NOT NULL, Name VARCHAR(30) NOT NULL, Date DATETIME NOT NULL, OwnerId VARCHAR(15) NOT NULL, OwnerName VARCHAR(15) NOT NULL, ImagePath VARCHAR(100) NOT NULL);" );
stat.executeUpdate( "create table if not exists Music(MusicId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name VARCHAR(30) NOT NULL, Singer VARCHAR(30) NOT NULL, SheetId INT NOT NULL, MusicMd5 VARCHAR(40) NOT NULL, MusicPath VARCHAR(100) NOT NULL, Time VARCHAR(10) NOT NULL);" );
}
catch( Exception e )
{
e.printStackTrace ( );
}
}
// 关闭数据库连接
public static void closeConnection()
{
try
{
conn.close();
}
catch( Exception e )
{
e.printStackTrace ( );
}
}
// 更新数据库数据
public static void update(String sql)
{
try
{
getConnection();
stat.executeUpdate(sql);
conn.close();
}
catch( Exception e )
{
e.printStackTrace ( );
}
}
// 查询数据库数据
public static ArrayList select(String sql)
{
try
{
getConnection();
ResultSet rs = stat.executeQuery(sql);
if (rs == null)
return null;
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
ArrayList list = new ArrayList();
Map rowData = new HashMap();
while (rs.next())
{
rowData = new HashMap(columnCount);
for (int i = 1; i <= columnCount; i++)
rowData.put(md.getColumnName(i), rs.getObject(i));
list.add(rowData);
}
conn.close();
return list;
}
catch( Exception e )
{
e.printStackTrace ( );
return null;
}
}
}
<file_sep>/testjar/src/main/java/SheetHelper.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.json.JSONArray;
import org.json.JSONObject;
import ouc.cs.course.java.model.MusicSheet;
import ouc.cs.course.java.musicclient.MusicOperationClient;
import ouc.cs.course.java.httpclient.MusicSheetTaker;
public class SheetHelper {
// 获取全部本地歌单信息
public static ArrayList getAll()
{
SqlHelper.getConnection();
String sql = "select * from Sheet;";
List ls = SqlHelper.select(sql);
SqlHelper.closeConnection();
ArrayList sheets = new ArrayList();
Iterator it = ls.iterator();
while(it.hasNext()) {
Map hm = (Map)it.next();
Sheet mySheet = new Sheet(hm);
sheets.add(mySheet);
}
return sheets;
}
// 根据歌单ID获取歌单信息
public static Sheet getSheet(String id)
{
SqlHelper.getConnection();
String sql = "select * from Sheet where SheetId = '" + id + "';";
List ls = SqlHelper.select(sql);
if(ls.size() != 0) {
SqlHelper.closeConnection();
Map hm = (Map)ls.get(0);
Sheet mySheet = new Sheet(hm);
return mySheet;
}
else
return null;
}
// 根据歌单ID获取歌单中全部歌曲信息
public static ArrayList getAllSongs(String id)
{
SqlHelper.getConnection();
String sql = "select * from Music where SheetId = '" + id + "';";
List ls = SqlHelper.select(sql);
SqlHelper.closeConnection();
ArrayList songs = new ArrayList();
Iterator it = ls.iterator();
while(it.hasNext()) {
Map hm = (Map)it.next();
Music myMusic = new Music(hm);
songs.add(myMusic);
}
return songs;
}
// 获取服务器端所有歌单
public static List getServerSheets() throws HttpException, IOException
{
String url = "http://service.uspacex.com/music.server/queryMusicSheets?type=all";
int port = 80;
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(url, port);
GetMethod method = new GetMethod(url);
client.executeMethod(method);
InputStream bodystreams = method.getResponseBodyAsStream();
JSONObject jsonBody = new JSONObject(MusicSheetTaker.convertStreamToString(bodystreams));
JSONArray jsonMusicSheetList = (JSONArray) jsonBody.get("musicSheetList");
JSONObject jms = null;
List mss = new ArrayList();
MusicSheet ms = null;
for (int i = 0; i < jsonMusicSheetList.length(); i++) {
Map mum = new HashMap();
Object musicSheetObj = jsonMusicSheetList.get(i);
jms = new JSONObject(musicSheetObj.toString());
ms = new MusicSheet();
ms.setUuid((String) jms.get("uuid"));
ms.setName((String) jms.get("name"));
ms.setCreator((String) jms.get("creator"));
if(jms.get("creatorId") == null)
ms.setCreatorId(null);
else
ms.setCreatorId(jms.get("creatorId").toString());
ms.setDateCreated((String) jms.get("dateCreated"));
if(jms.get("picture") == null)
ms.setPicture(null);
else
ms.setPicture(jms.get("picture").toString());
String mi = jms.get("musicItems").toString();
if(mi.length() != 0) {
mi = mi.substring(0, mi.length()-1);
String[] musics = mi.split(",");
for(int j = 0; j < musics.length; j++){
String[] items = musics[j].split(":");
if(items.length > 1) {
int index1 = items[0].indexOf('"');
int index2 = items[0].lastIndexOf('"');
int size = items[1].length();
int index3 = items[1].lastIndexOf('"');
if(items[1].indexOf('.') != -1)
mum.put(items[0].substring(index1 + 1, index2), items[1].substring(1, size-5));
else
mum.put(items[0].substring(index1 + 1, index2), items[1].substring(1));
}
}
ms.setMusicItems(mum);
mss.add(ms);
}
}
method.releaseConnection();
return mss;
}
// 上传歌单
public static void uploadSheet(MusicSheet sheet)
{
MusicOperationClient moc = new MusicOperationClient();
List filePaths = new ArrayList();
SqlHelper.getConnection();
ArrayList musics = SqlHelper.select("select MusicPath from Music where SheetId = '" + sheet.getUuid() + "'");
SqlHelper.closeConnection();
Iterator it = musics.iterator();
while(it.hasNext()) {
Map hm = (Map)it.next();
String path = System.getProperty("user.dir").toString().replace('\\', '/') + hm.get("MusicPath").toString();
System.out.println(path);
filePaths.add(path);
}
MusicSheet ms = new MusicSheet();
ms.setCreatorId(sheet.getCreatorId());
ms.setPicture(sheet.getPicture());
ms.setCreator(sheet.getCreator());
ms.setName(sheet.getName());
moc.createMusicSheetAndUploadFiles(ms, filePaths);
}
// 根据MD5值下载对应的歌单封面图片并返回路径
public static String getPicture(String md5, String pictureName)
{
MusicOperationClient moc = new MusicOperationClient();
moc.downloadMusicSheetPicture(md5, "./images");
String path = System.getProperty("user.dir").toString().replace('\\', '/') + "/images/" + pictureName;
return path;
}
// 创建歌单
public static void createSheet(String name, String imagePath, String creator, String creatorId)
{
Sheet mySheet = new Sheet();
mySheet.setName(name);
File f = new File(imagePath);
String imageName = f.getName();
String newPath = System.getProperty("user.dir").toString().replace('\\', '/') + "/images/" + imageName;
FileHelper.copyFile(imagePath, newPath);
imagePath = "/images/" + imageName;
mySheet.setPicture(imagePath);
SqlHelper.getConnection();
String sql = "insert into Sheet values('" + mySheet.getUuid() + "','" + mySheet.getName() + "','" + mySheet.getDateCreated() + "','" + creatorId + "','" + creator + "','" + mySheet.getPicture() + "')";
SqlHelper.update(sql);
SqlHelper.closeConnection();
}
// 删除歌单
public static void deleteSheet(String uuid)
{
SqlHelper.getConnection();
String sql = "delete from Sheet where SheetId = '" + uuid + "'";
SqlHelper.update(sql);
sql = "delete from Music where SheetId = '" + uuid + "'";
SqlHelper.update(sql);
SqlHelper.closeConnection();
}
}
<file_sep>/testjar/src/main/java/Sheet.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import ouc.cs.course.java.model.MusicSheet;
public class Sheet extends MusicSheet {
private String id;
private String name;
private String date;
private String owner_id;
private String image_path;
private static String root = System.getProperty("user.dir").toString().replace('\\', '/');
public Sheet(Map hm)
{
id = hm.get("SheetId").toString();
name = hm.get("Name").toString();
date = hm.get("Date").toString();
owner_id = hm.get("OwnerId").toString();
image_path = root + hm.get("ImagePath").toString();
}
public Sheet(){
String s1 = "-";
String s2 = "";
id = UUID.randomUUID().toString().replaceAll(s1, s2);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formatter.format(new Date());
}
public String getUuid()
{
return id;
}
public String getName()
{
return name;
}
public String getDateCreated()
{
return date;
}
public String getCreatorId()
{
return owner_id;
}
public String getPicture()
{
return image_path;
}
public void setUuid(String id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public void setDateCreated(String date)
{
this.date = date;
}
public void setCreatorId(String id)
{
this.owner_id = id;
}
public void setPicture(String path)
{
this.image_path = path;
}
}
<file_sep>/MusicWeb/js/Index.js
$(".otherlist-item").each(function () {
$(this).hover(function () {
$(this).children().eq(0).css("display","block");
},function () {
$(this).children().eq(0).css("display","none");
})
});
$(".mylist-other").each(function () {
$(this).hover(function () {
$(this).children().eq(0).css("display","block");
},function () {
$(this).children().eq(0).css("display","none");
})
})
<file_sep>/MusicWeb/js/jQuery.scrollBar.js
/*******
20156-4-27 By jone
********/
(function($){
$.fn.scrollBar = function(options) {
var defaults = {
foregroundColor: '#00adb5',
backgroundColor: '#d5d5d5',
height: 400,
width: 600,
sliderBoxWidth: 10,
sliderBarHeight: 100,
mousewheel: true,
radius: 0,
scrollDirection: "y",
}
var obj = $.extend(defaults, options);
this.each(function(index, el) {
var me = $(this);
var content = me.children().eq(0);
var isMouseDown = false;
var distance = 0;
me.css({
height: obj.height,
position: 'relative',
width: obj.width,
});
content.css("padding", 10)
if (me.outerHeight() < content.outerHeight() || me.outerWidth() < content.outerWidth()) {
var slider = "<div class='slider'><span></span></div>";
me.append(slider);
};
if (slider) {
var sliderBox = me.find(".slider"),
sliderBar = sliderBox.find("span");
// 如果是纵向滚动;
if (obj.scrollDirection.toLowerCase() === "y") {
var BarHeight = me.outerHeight() / content.outerHeight() * obj.sliderBarHeight;
me.css("paddingRight", content.css("paddingLeft"));
sliderBox.css({
position: 'absolute',
top: 2,
right: 2,
width: obj.sliderBoxWidth,
height: obj.height - 4,
background: obj.backgroundColor,
borderRadius: obj.radius,
overflow: 'hidden'
});
sliderBar.css({
position: 'absolute',
top: 0,
right: 0,
width: obj.sliderBoxWidth,
background: obj.foregroundColor,
height: BarHeight,
});
sliderBar.on("mousedown", function(event) {
event.preventDefault();
isMouseDown = true;
});
$(window).on('mousemove', function(event) {
event.preventDefault();
distance = event.pageY - me.offset().top
if (isMouseDown == true) {
scrollY(distance)
}
});
$(window).on('mouseup', function() {
isMouseDown = false;
});
// 鼠标滚轮事件;
if (obj.mousewheel) {
me.bind("mousewheel", function(event, delta) {
distance = sliderBar.offset().top - me.offset().top;
delta > 0 ? distance -= 10 : distance += 10;
scrollY(distance);
})
}
function scrollY(distance) {
if (distance < 0) {
distance = 0
} else if (distance > sliderBox.outerHeight() - sliderBar.outerHeight()) {
distance = sliderBox.outerHeight() - sliderBar.outerHeight();
}
sliderBar.css("top", distance);
var scale = distance / (sliderBox.outerHeight() - sliderBar.outerHeight())
var scrollDistance = parseInt(scale * (content.outerHeight() - me.outerHeight()));
content.css("marginTop", -scrollDistance)
}
}
// 如果是横向滚动;
if (obj.scrollDirection.toLowerCase() === "x") {
content.css("width", content.outerWidth() * 2);
me.css("height", "auto")
var BarWidth = me.outerWidth() / content.outerWidth() * obj.sliderBarHeight;
me.css("paddingBottom", content.css("paddingLeft"));
sliderBox.css({
position: 'absolute',
left: 2,
bottom: 2,
width: obj.width - 4,
height: obj.sliderBoxWidth,
background: obj.backgroundColor,
borderRadius: obj.radius,
overflow: 'hidden'
});
sliderBar.css({
position: 'absolute',
left: 0,
bottom: 0,
width: BarWidth,
background: obj.foregroundColor,
height: obj.sliderBoxWidth,
});
sliderBar.on("mousedown", function(event) {
event.preventDefault();
isMouseDown = true;
});
$(window).on('mousemove', function(event) {
event.preventDefault();
distance = event.pageX - me.offset().left
if (isMouseDown == true) {
scrollX(distance)
}
});
$(window).on('mouseup', function() {
isMouseDown = false;
});
// 鼠标滚轮事件;
if (obj.mousewheel) {
me.bind("mousewheel", function(event, delta) {
distance = sliderBar.offset().left - me.offset().left;
delta > 0 ? distance -= 10 : distance += 10;
scrollX(distance);
})
}
function scrollX(distance) {
if (distance < 0) {
distance = 0
} else if (distance > sliderBox.outerWidth() - sliderBar.outerWidth()) {
distance = sliderBox.outerWidth() - sliderBar.outerWidth();
}
sliderBar.css("left", distance);
var scale = distance / (sliderBox.outerWidth() - sliderBar.outerWidth())
var scrollDistance = parseInt(scale * (content.outerWidth() - me.outerWidth()));
content.css("marginLeft", -scrollDistance)
}
}
}
});
}
})(jQuery);
//sroll($('.box'));<file_sep>/testjar/src/main/java/Music.java
import java.util.Map;
public class Music {
private int id;
private String name;
private String singer;
private String sheet_id;
private String md5;
private String path;
private String time;
private static String root = System.getProperty("user.dir").toString().replace('\\', '/');
public Music(Map hm)
{
id = Integer.parseInt(hm.get("MusicId").toString());
name = hm.get("Name").toString();
singer = hm.get("Singer").toString();
//sheet_id = Integer.parseInt(hm.get("SheetId").toString());
sheet_id =hm.get("SheetId").toString();
md5 = hm.get("MusicMd5").toString();
path = root + hm.get("MusicPath").toString();
time = hm.get("Time").toString();
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public String getSinger()
{
return singer;
}
public String getSheetId()
{
return sheet_id;
}
public String getMd5()
{
return md5;
}
public String getPath()
{
return path;
}
public String getTime()
{
return time;
}
}
<file_sep>/MusicWeb/js/Player.js
var mp3;
var isPlay;
var tSet;
$(document).ready(function () {
mp3 = $(".audio-play")[0];
isPlay = false;
})
$("#stop-begin-button").click(function () {
if(isPlay){
isPlay = false;
$("#stop-begin-button").css("background","url('images/begin.png')");
mp3.pause();
clearInterval(tSet);
}
else {
isPlay = true;
$("#stop-begin-button").css("background","url('images/turn-stop.png')");
mp3.play();
tSet = setInterval(function () {
var width = mp3.currentTime / mp3.duration * 1473;
$(".progress-blue").css({"width":width+"px"});
$(".progress-arc").css("left",(width - 10) + "px");
console.log(width);
},1000);
}
});
|
73aba242e6c8f778acc6930ffff6e34fcd386265
|
[
"JavaScript",
"Java"
] | 7
|
Java
|
MusicPlayer-Java/MusicWeb
|
940ee5017bacec97568191cf1a46dfe22c8c9394
|
7f90d936c90422e28a17c8f81064c17ce58d584c
|
refs/heads/master
|
<repo_name>BishoyBishai/dynamicForm<file_sep>/src/containers/form/reducer.test.ts
import { initialFormState, fromReducers } from "./reducer";
import { getLoadQuestions } from "./api";
import { FORM_TYPE, NewAnswer } from "./types";
import {
LOAD_FORM_QUESTIONS,
ADD_QUESTION_ANSWER,
GO_TO_NEXT_QUESTION,
GO_TO_PERVIOUS_QUESTION,
SUBMIT_FORM,
START_NEW_FORM
} from "./constants";
describe("form reducer", () => {
let initialState;
beforeEach(() => {
initialState = initialFormState;
});
test("should load questions to app store", () => {
const questions = getLoadQuestions();
expect(
fromReducers(initialState, {
type: LOAD_FORM_QUESTIONS,
payload: questions
})
).toMatchObject({ ...initialState, ...questions });
});
test("should change answer of question", () => {
const questions = [
{
id: 2447,
question_type: "TextQuestion",
prompt: "What is your first answer?",
is_required: false,
min_char_length: 15
}
];
const newAnswer: NewAnswer = { id: 2447, answer: "test" };
expect(
fromReducers(
{ ...initialState, questions },
{
type: ADD_QUESTION_ANSWER,
payload: newAnswer
}
).questions[0].answer
).toEqual("test");
});
test("should don't change answer of question if pass wrong id", () => {
const questions = [
{
id: 2447,
question_type: "TextQuestion",
prompt: "What is your first answer?",
is_required: false,
min_char_length: 15
}
];
const newAnswer: NewAnswer = { id: 2448, answer: "test" };
expect(
fromReducers(
{ ...initialState, questions },
{
type: ADD_QUESTION_ANSWER,
payload: newAnswer
}
).questions[0].answer
).toBeUndefined();
});
test("should go to next question", () => {
expect(
fromReducers(initialState, {
type: GO_TO_NEXT_QUESTION
}).activeIndex
).toEqual(1);
});
test("should go to pervious question", () => {
expect(
fromReducers(initialState, {
type: GO_TO_PERVIOUS_QUESTION
}).activeIndex
).toEqual(-1);
});
test("should mark form as submitted form", () => {
expect(
fromReducers(initialState, {
type: SUBMIT_FORM
})
).toMatchObject({
...initialState,
formType: FORM_TYPE.SUBMITTED,
activeIndex: -1
});
});
test("should mark form as editable form", () => {
expect(
fromReducers(initialState, {
type: START_NEW_FORM
})
).toMatchObject({
...initialState,
activeIndex: 0,
formType: FORM_TYPE.EDITABLE
});
});
});
<file_sep>/src/containers/form/constants.ts
export const LOAD_FORM_QUESTIONS = "LOAD_FORM_QUESTIONS";
export const ADD_QUESTION_ANSWER = "ADD_QUESTION_ANSWER";
export const GO_TO_NEXT_QUESTION = "GO_TO_NEXT_QUESTION";
export const GO_TO_PERVIOUS_QUESTION = "GO_TO_PERVIOUS_QUESTION";
export const SUBMIT_FORM = "SUBMIT_FORM";
export const START_NEW_FORM = "START_NEW_FORM";
<file_sep>/src/components/form/header/types.ts
export interface FormHeaderProps {
progressState: number;
title: string;
}
<file_sep>/src/containers/form/helper.ts
import { QUESTION_TYPE } from "./types";
export function isNextEnable(
isRequired: boolean,
questionType: QUESTION_TYPE,
answer,
minCharLength?: number
) {
if (isRequired) {
switch (questionType) {
case QUESTION_TYPE.TextQuestion: {
return answer && (answer as string).trim().length >= minCharLength;
}
}
}
return true;
}
<file_sep>/src/containers/form/api.ts
import { MainForm } from "./types";
export function getLoadQuestions() {
return {
title: "This is a title for the form Header",
questions: [
{
id: 2447,
question_type: "TextQuestion",
prompt: "What is your first answer?",
is_required: false,
min_char_length: 15
},
{
id: 2448,
question_type: "TextQuestion",
prompt: "What is your second answer?",
is_required: true,
min_char_length: 10
},
{
id: 2500,
question_type: "TextQuestion",
prompt: "What is your third answer?",
is_required: true,
min_char_length: 1
}
]
};
}
<file_sep>/src/containers/form/types.ts
export enum QUESTION_TYPE {
TextQuestion = "TextQuestion"
}
export interface Question {
id: number;
question_type: QUESTION_TYPE;
prompt: string;
is_required: boolean;
min_char_length?: number;
answer?: any;
}
export enum FORM_TYPE {
EDITABLE = "EDITABLE",
SUBMITTED = "SUBMITTED"
}
export interface MainForm {
title: string;
questions: Question[];
}
export interface FormState extends MainForm {
activeIndex: number;
formType: FORM_TYPE;
}
export interface NewAnswer {
id: number;
answer;
}
export interface FormComponentProps {
formType: FORM_TYPE;
title: string;
question: Question;
hasNext: boolean;
isNextEnable:boolean;
hasPervious: boolean;
progressState:number;
}
export interface FormComponentActions {
loadQuestionsList: () => void;
addQuestionAnswer: (id: number, answer) => void;
goToNextQuestion(): () => void;
goToPreviousQuestion(): () => void;
submitForm(): () => void;
startNewForm(): () => void;
}
<file_sep>/README.md
# Dynamic Form
[](https://travis-ci.org/BishoyBishai/dynamicForm)
[](https://codeclimate.com/github/BishoyBishai/dynamicForm/maintainability)
## React-Redux [using typescript & Jest ]
- Create a dynamically loading form
### Stack
* React app with babel for transpiration and babel-polyfill for browser support
of latest ECMAScript features
* Redux for state management.
* Typescript for javascript static type
* Jest and Enzyme for testing.
* webpack as the bundler.
### Installation
```javascript
npm install // to install required packages
npm start // to start server on http://127.0.0.1:3000/
```
<file_sep>/src/components/form/footer/types.ts
export interface FormFooterProps {
hasNext: boolean;
hasPrevious: boolean;
isNextEnable:boolean;
goToNextQuestion: () => void;
goToPreviousQuestion: () => void;
submitForm: () => void;
}
<file_sep>/src/containers/form/index.ts
import { connect } from "react-redux";
import AppForm from "../../components/form/index";
import { ReducersProps } from "../../bin/types";
import { FormComponentProps } from "./types";
import { isNextEnable } from "./helper";
import {
loadQuestionsList,
goToNextQuestion,
goToPreviousQuestion,
submitForm,
startNewForm,
addQuestionAnswer
} from "./actions";
const mapStateToProps = (s: ReducersProps): FormComponentProps => {
const { activeIndex, questions, title, formType } = s.fromReducers;
return {
formType,
title,
question: questions[activeIndex],
hasNext: activeIndex < questions.length - 1,
isNextEnable:
questions[activeIndex] &&
isNextEnable(
questions[activeIndex].is_required,
questions[activeIndex].question_type,
questions[activeIndex].answer,
questions[activeIndex].min_char_length
),
hasPervious: activeIndex > 0,
progressState:
(questions.length > 0 && (activeIndex + 1) / questions.length * 100) || 0
};
};
const mapDispatchToProps = dispatch => ({
loadQuestionsList: () => dispatch(loadQuestionsList()),
goToNextQuestion: () => dispatch(goToNextQuestion()),
goToPreviousQuestion: () => dispatch(goToPreviousQuestion()),
submitForm: () => dispatch(submitForm()),
startNewForm: () => dispatch(startNewForm()),
addQuestionAnswer: (id: number, answer) =>
dispatch(addQuestionAnswer(id, answer))
});
export default connect(mapStateToProps, mapDispatchToProps)(AppForm);
<file_sep>/src/containers/form/helper.test.ts
import { isNextEnable } from "./helper";
import { QUESTION_TYPE } from "./types";
describe("isNextEnable function", () => {
test("should function return true when isRequired is false", () => {
expect(isNextEnable(false, QUESTION_TYPE.TextQuestion, "")).toBeTruthy();
});
test("should function return false when isRequired is true and question has no answer", () => {
expect(isNextEnable(true, QUESTION_TYPE.TextQuestion, "")).toBeFalsy();
});
test("should function return false when isRequired is true and question has answer length less than limit", () => {
expect(
isNextEnable(true, QUESTION_TYPE.TextQuestion, "test", 5)
).toBeFalsy();
});
test("should function return true when isRequired is true and question has answer length equal limit", () => {
expect(
isNextEnable(true, QUESTION_TYPE.TextQuestion, "test", 4)
).toBeTruthy();
});
test("should function return true when isRequired is true and question has answer length more than limit", () => {
expect(
isNextEnable(true, QUESTION_TYPE.TextQuestion, "test", 3)
).toBeTruthy();
});
});
<file_sep>/src/containers/form/reducer.ts
import { NewAnswer, FormState, FORM_TYPE, Question, MainForm } from "./types";
import { AnyAction } from "redux";
import {
LOAD_FORM_QUESTIONS,
ADD_QUESTION_ANSWER,
GO_TO_NEXT_QUESTION,
GO_TO_PERVIOUS_QUESTION,
SUBMIT_FORM,
START_NEW_FORM
} from "./constants";
export const initialFormState: FormState = {
title: "",
activeIndex: 0,
formType: FORM_TYPE.EDITABLE,
questions: []
};
export function fromReducers(
state = initialFormState,
action: AnyAction
): FormState {
switch (action.type) {
case LOAD_FORM_QUESTIONS: {
const form: MainForm = action.payload;
return {
...state,
...form
};
}
case ADD_QUESTION_ANSWER: {
const newAnswer: NewAnswer = action.payload;
return {
...state,
questions: state.questions.map(
question =>
question.id === newAnswer.id
? { ...question, answer: newAnswer.answer }
: question
)
};
}
case GO_TO_NEXT_QUESTION:
return {
...state,
activeIndex: state.activeIndex + 1
};
case GO_TO_PERVIOUS_QUESTION:
return {
...state,
activeIndex: state.activeIndex - 1
};
case SUBMIT_FORM:
return {
...state,
formType: FORM_TYPE.SUBMITTED,
activeIndex: -1,
questions: state.questions.map(question => ({
...question,
answer: null
}))
};
case START_NEW_FORM:
return {
...state,
activeIndex: 0,
formType: FORM_TYPE.EDITABLE
};
}
return state;
}
<file_sep>/src/containers/form/actions.ts
import { NewAnswer } from "./types";
import { getLoadQuestions } from "./api";
import {
LOAD_FORM_QUESTIONS,
ADD_QUESTION_ANSWER,
GO_TO_NEXT_QUESTION,
GO_TO_PERVIOUS_QUESTION,
SUBMIT_FORM,
START_NEW_FORM
} from "./constants";
export function loadQuestionsList() {
return function(dispatch) {
dispatch({ type: LOAD_FORM_QUESTIONS, payload: getLoadQuestions() });
};
}
export function addQuestionAnswer(id: number, answer) {
return function(dispatch) {
const newAnswer: NewAnswer = { id, answer };
dispatch({ type: ADD_QUESTION_ANSWER, payload: newAnswer });
};
}
export function goToNextQuestion() {
return function(dispatch) {
dispatch({ type: GO_TO_NEXT_QUESTION });
};
}
export function goToPreviousQuestion() {
return function(dispatch) {
dispatch({ type: GO_TO_PERVIOUS_QUESTION });
};
}
export function submitForm() {
return function(dispatch) {
dispatch({ type: SUBMIT_FORM });
};
}
export function startNewForm() {
return function(dispatch) {
dispatch({ type: START_NEW_FORM });
};
}
<file_sep>/src/bin/types.ts
import { FormState } from '../containers/form/types';
export interface ReducersProps{
fromReducers:FormState
}<file_sep>/src/bin/reducers.ts
import { combineReducers } from "redux";
import { routerReducer as router } from "react-router-redux";
import { AnyAction } from "redux";
import { fromReducers } from "../containers/form/reducer";
export const reducers = combineReducers({
fromReducers
});
<file_sep>/src/bin/store.ts
import thunk from "redux-thunk";
import { createLogger } from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import { routerMiddleware } from "react-router-redux";
import createHistory from "history/createBrowserHistory";
import { reducers } from "./reducers";
import promise from "redux-promise-middleware";
export const localHistory = createHistory();
const middleware = applyMiddleware(
promise(),
thunk,
routerMiddleware(localHistory),
createLogger()
);
export const store = createStore(reducers, middleware);
<file_sep>/src/components/form/question/types.ts
import { Question } from "../../../containers/form/types";
export interface QuestionComponentProps extends Question {
addQuestionAnswer: (id: number, answer) => void;
optional:boolean;
}
|
1497e38edb11d1a7f9266e92a6c97e92431b9d47
|
[
"Markdown",
"TypeScript"
] | 16
|
TypeScript
|
BishoyBishai/dynamicForm
|
3097bb0517d612e0d9a1949b317497f27c8a936c
|
e5db6aa6914b6c9ba517129e4342b86c46b90064
|
refs/heads/master
|
<repo_name>NationNuo/newcs<file_sep>/tcp_echo_cli.c
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#include<signal.h>
#define MAX_CMD_STR 200
#define bprintf(fp,format,...)\
do{\
if (fp==NULL)printf(format,##__VA_ARGS__);\
else{\
printf(format,##__VA_ARGS__);\
fprintf(fp,format,##__VA_ARGS__);\
fflush(fp);\
}\
}while (0);
void
str_cli(int pin, int sockfd,FILE **writefp)
{
char sendline[MAX_CMD_STR+1],recvline[MAX_CMD_STR+1],length[10],totalbuf[MAX_CMD_STR+9]={0};
ssize_t n;
FILE *readfp;
char rfile[10]={0},wfile[20]={0};
int clipintosend=htonl(pin),clipintorecv;
sprintf(rfile,"td%d.txt",pin);
sprintf(wfile,"stu_cli_res_%d.txt",pin);
if((readfp=fopen(rfile,"r"))==NULL){
printf("read file error\n");
}
while (fgets(sendline,MAX_CMD_STR-9,readfp)!=NULL)
{
if(strncmp(sendline,"exit",4)==0)goto echoend;
int len = strnlen(sendline,MAX_CMD_STR);
sendline[len-1]='\0';
*(int*)(&(totalbuf[0]))=clipintosend;
*(int*)(&(totalbuf[4]))=htonl(len);
sprintf(&totalbuf[8],"%s",sendline);
write(sockfd, totalbuf, len+8);
// write(sockfd, &clipintosend,sizeof(clipintosend));
// write(sockfd, &len,sizeof(len));
// write(sockfd, sendline, len);
n = read(sockfd, &clipintorecv, sizeof(clipintorecv));
n = read(sockfd, &len, sizeof(len));
n = read(sockfd, recvline, ntohl(len));
if(clipintosend!=clipintorecv){
printf("pin error %d %d %d %d\n\n",pin,clipintosend,clipintorecv,len);
exit(0);
}
bprintf(*writefp,"[echo_rep](%d) %s\n",(int)getpid(),recvline);
fflush(stdout);
memset(recvline,0,sizeof(recvline));
memset(sendline,0,sizeof(sendline));
memset(totalbuf,0,sizeof(totalbuf));
}
echoend:
close(sockfd);
bprintf(*writefp,"[cli](%d) connfd is closed!\n",(int)getpid());
if(pin==0){//大坑,宏定义不一定代表一行语句
bprintf(*writefp,"[cli](%d) parent process is going to exit!\n",(int)getpid());
}
else{
bprintf(*writefp,"[cli](%d) children process is going to exit!\n",(int)getpid());
}
fclose(readfp);
fclose(*writefp);
printf("[cli](%d) %s is closed!\n",(int)getpid(),wfile);
}
void sig_int(int signo){
printf("[srv] SIGINT is coming!\n");
fflush(stdout);
exit(0);
}
void sig_pip(int signo){
printf("[srv] SIGPIPE is coming!\n");
fflush(stdout);
}
void handler(int signo){
wait(0);
return;
}
int
main(int argc, char **argv)
{
int sockfd,multis,pid;
struct sockaddr_in servaddr;
struct sigaction act1,act2,act3;
if (argc != 4){
printf("usage: tcpcli <IPaddress>");
exit(0);
}
multis=atoi(argv[3]);
sigemptyset(&act1.sa_mask);
act1.sa_handler=sig_pip;
act1.sa_flags=0;
sigaction(SIGPIPE,&act1,NULL);
sigemptyset(&act2.sa_mask);
act2.sa_handler=sig_int;
act2.sa_flags=0;
sigaction(SIGINT,&act2,NULL);
sigemptyset(&act3.sa_mask);
act2.sa_handler=handler;
act2.sa_flags=0;
sigaction(SIGCHLD,&act2,NULL);
for(int pin=multis-1;pin>=0;pin--){//son process start from 1
if(pin==0)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
char fname[20]={0};
FILE* fp;
sprintf(fname,"stu_cli_res_%d.txt",pin);
if((fp=fopen(fname,"wr"))==NULL){
printf("file error");
}
printf("[cli](%d) stu_cli_res_%d.txt is created!\n",(int)getpid(),pin);
bprintf(fp,"[cli](%d) parent process %d is created!\n",(int)getpid(),pin);
fflush(stdout);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2]));//host to network short
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
bprintf(fp,"[cli](%d) server[%s:%d] is connected!\n",(int)getpid(),argv[1],atoi(argv[2]));
fflush(stdout);
str_cli(pin, sockfd,&fp); /* do it all */
//exit(0);
continue;
}else if ((pid = fork())==0)
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
char fname[20]={0};
FILE* fp;
sprintf(fname,"stu_cli_res_%d.txt",pin);
if((fp=fopen(fname,"wr"))==NULL){
printf("file error");
}
printf("[cli](%d) stu_cli_res_%d.txt is created!\n",(int)getpid(),pin);
bprintf(fp,"[cli](%d) child process %d is created!\n",(int)getpid(),pin);
fflush(stdout);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[2]));//host to network short
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
bprintf(fp,"[cli](%d) server[%s:%d] is connected!\n",(int)getpid(),argv[1],atoi(argv[2]));
fflush(stdout);
str_cli(pin, sockfd,&fp); /* do it all */
exit(0);
}
}
}
<file_sep>/testscript
#! /bin/bash
multis=5
rm stu*
rm td*
for i in $(seq 0 $multis)
do
wname="stu_cli_res_${i}.txt"
rname="td${i}.txt"
if [ ! -f $wname ] ;then
touch $wname
echo "hello ${i}" > $wname
date >> $wname
fi
if [ ! -f $rname ] ;then
touch $rname
echo "hello ${i}" > $rname
date >> $rname
fi
done
make
./tcp_echo_srv 127.0.0.1 9877 &
./tcp_echo_cli 127.0.0.1 9877 5<file_sep>/Makefile
CC = gcc
CFLAGS = -c
all:cliandsrv
cliandsrv:tcp_echo_cli.o tcp_echo_srv.o
$(CC) tcp_echo_cli.c -o tcp_echo_cli
$(CC) tcp_echo_srv.o -o tcp_echo_srv
tcp_echo_cli.o: tcp_echo_cli.c
$(CC) $(CFLAGS) $<
tcp_echo_srv.o: tcp_echo_srv.c
$(CC) $(CFLAGS) $<
clean:
rm -rf tcp_echo_cli tcp_echo_srv *.o<file_sep>/tcp_echo_srv.c
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#include<signal.h>
#include<unistd.h>
#define MAX_CMD_STR 200
#define bprintf(fp,format,...)\
do{\
if (fp==NULL)printf(format,##__VA_ARGS__);\
else{\
printf(format,##__VA_ARGS__);\
fprintf(fp,format,##__VA_ARGS__);\
fflush(fp);\
}\
}while (0);
//##__VA_ARGS__ 宏前面加上##的作用在于,当可变参数的个数为0时,这里的##起到把前面多余的","去掉的作用,否则会编译出错
int restart = 0;
FILE* globalfp;
int
str_echo(int sockfd,FILE **writefp)
{
ssize_t n;
char buf[MAX_CMD_STR],length[10],totalbuf[MAX_CMD_STR+9]={0};
int len,pin,recvpin,sendpin;
char wfile[20]={0};
char newname[20]={0};
sprintf(wfile,"stu_srv_res_%d.txt",(int)getpid());
again:
while ( (n = read(sockfd, &pin, sizeof(pin))) > 0){
if(n==0)return -1;
recvpin=ntohl(pin);
sendpin=htonl(recvpin);
//printf("[%d]clipin recv %16x and send %16x\n",sockfd,recvpin,sendpin);
n = read(sockfd, &len, sizeof(len));
n = read(sockfd, buf, ntohl(len));
bprintf(*writefp,"[echo_rqt](%d) %s\n",recvpin,buf);
fflush(stdout);
len = strnlen(buf,MAX_CMD_STR)+1;
buf[len-1]='\0';
*(int*)(&(totalbuf[0]))=sendpin;
*(int*)(&(totalbuf[4]))=htonl(len);
sprintf(&totalbuf[8],"%s",buf);
write(sockfd, totalbuf, len+8);
// write(sockfd, &sendpin, sizeof(sendpin));
// write(sockfd, &len, sizeof(len));
// write(sockfd, buf, len);
// printf("buf %s\n",buf);
memset(buf,0,sizeof(buf));
memset(totalbuf,0,sizeof(totalbuf));
}
if (n < 0 && errno == EINTR)
goto again;
else if (n < 0)
printf("str_echo: read error\n");
bprintf(*writefp,"[srv](%d) res file rename done!\n",(int)getpid());
bprintf(*writefp,"[srv](%d) connfd is closed!\n",(int)getpid());
bprintf(*writefp,"[srv](%d) child process is going to exit!\n",(int)getpid());
printf("[srv](%d) %s is closed!\n",(int)getpid(),wfile);//只打印到stdout
fclose(*writefp);
sprintf(newname,"stu_srv_res_%d.txt",recvpin);
rename(wfile,newname);
return recvpin;
}
void sig_int(int signo){
bprintf(globalfp,"[srv] SIGINT is coming!\n");
fflush(stdout);
}
void sig_pip(int signo){
printf("[srv] SIGPIPE is coming!\n");
fflush(stdout);
}
void sig_chld(int signo){
wait(0);
pid_t pid_chld;
while((pid_chld=waitpid(-1,NULL,WNOHANG)>0));
printf("[srv](%d) server child(%d) terminated.\n",(int)getpid(),pid_chld);
restart=1;
}
int
main(int argc, char **argv)
{
int listenfd, connfd ,childpid;
pid_t childpin;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
sigset_t sigset;
struct sigaction act1,act2,act3;
errno=0;
if (argc != 3){
printf("usage: tcpcli <IPaddress>");
exit(0);
}
char fname[20]={0};
if((globalfp=fopen("stu_srv_res_p.txt","wr"))==NULL){
printf("file error");
}
printf("[srv](%d) stu_srv_res_p.txt is opened!\n",(int)getpid());
// sigemptyset(&act1.sa_mask);
// act1.sa_handler=sig_pip;
// act1.sa_flags=0;
// sigaction(SIGPIPE,&act1,NULL);
sigemptyset(&act2.sa_mask);
act2.sa_handler=sig_int;
act2.sa_flags=0;
sigaction(SIGINT,&act2,NULL);
sigemptyset(&act3.sa_mask);
act2.sa_handler=sig_chld;
act2.sa_flags=SA_RESTART;
sigaction(SIGCHLD,&act2,NULL);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
servaddr.sin_port = htons(atoi(argv[2]));//host to network short
//servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
//servaddr.sin_port = htons(9877);
bprintf(globalfp,"[srv](%d) server[%s:%d] is initializing!\n",(int)getpid(),argv[1],atoi(argv[2]));
fflush(stdout);
bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
listen(listenfd, 1024);
for (int i=1 ;i<100 ;i++ ) {//to protect
char saveipv4[20];
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &clilen);
inet_ntop(AF_INET,(void*)&cliaddr.sin_addr,saveipv4,20);
//printf("%d %d",connfd,errno);
// if(restart==1){
// restart=0;
// continue;
// }
if(connfd==-1&&errno==EINTR){
printf("connfd %d errno %d\n",connfd,errno);
break;
}
bprintf(globalfp,"[srv](%d) client[%s:%d] is accepted!\n",(int)getpid(),saveipv4,ntohs(cliaddr.sin_port));
if ( (childpid = fork()) == 0) { /* child process */
close(listenfd); /* close listening socket */
char fname[20]={0};
FILE* fp;
sprintf(fname,"stu_srv_res_%d.txt",(int)getpid());
if((fp=fopen(fname,"wr"))==NULL){
printf("file error");
}
printf("[srv](%d) stu_srv_res_%d.txt is opened!\n",(int)getpid(),(int)getpid());
bprintf(fp,"[srv](%d) child process is created!\n",(int)getpid());
bprintf(fp,"[srv](%d) listenfd is closed!\n",(int)getpid());
str_echo(connfd,&fp); /* process the request */
close(connfd);
exit(0);
}
close(connfd);/* parent closes connected socket */
}
close(listenfd);
bprintf(globalfp,"[srv] listenfd is closed!\n");
bprintf(globalfp,"[srv](%d) parent process is going to exit!\n",(int)getpid());
fclose(globalfp);
printf("[srv](%d) stu_srv_res_p.txt is closed!\n",(int)getpid());//只打印到stdout
exit(0);
}
|
b9c2593e459189be48b2fe2d41edee46c97a2e2d
|
[
"C",
"Makefile",
"Shell"
] | 4
|
C
|
NationNuo/newcs
|
592e0ce7e129313ffd2cb1fb79c2a99b7a0b08e7
|
d505f8eff7575c9ba3af3eb1b3731c15c57c0ff0
|
refs/heads/main
|
<file_sep>from django.contrib import admin
from django.urls import path, include
from app import views
urlpatterns = [
path('', views.task1, name='task')
]<file_sep>from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View
def task1(self):
a = [2, 4, 3]
b = [5, 6, 4]
result_a = []
result_b = []
for ra in reversed(a):
result_a.append(ra)
[3, 4, 2]
for rb in reversed(b):
result_b.append(rb)
result_a = int("".join(map(str, result_a)))
result_b = int("".join(map(str, result_b)))
result = result_a + result_b
result = str(result)[::-1]
result = list(map(str, result))
print('task 1 : ', result)
task2(self)
return HttpResponse(result)
def task2(self):
new = []
for i in range(1, 100):
i = str(i)
if '0' not in i:
new.append(i)
print('task2 : ', new)
return new
|
71e81301db2221df0bf997f19e99ebd4f8c4b96a
|
[
"Python"
] | 2
|
Python
|
Zarinabonu/task
|
5f82b1a2560ace48ac09427e191568ba3cb9bac7
|
dd5712b53d36b82c41d80f5a3b56983bdc30ead0
|
refs/heads/master
|
<repo_name>KazumaShachou/Game_typeplataform<file_sep>/Assets/Scripts/PlayerJump.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class PlayerJump : MonoBehaviour
{
//Head organiza variáveis
[Header("Components")]
public Rigidbody2D rb;
[Header("Configurations")]
public float JumpForce = 50f;
bool doublejumpAvaliable = true;
[Header("GroundDetectors")]
public float distance = 1;
bool inGround;
public Transform GroundDetector1;
public Transform GroundDetector2;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump") && doublejumpAvaliable)
{
if (!inGround)
{ //if he IS NOT in the ground, he already used the doublejump, so you can't until down
doublejumpAvaliable = false;
}
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.AddForce(Vector2.up * JumpForce);
}
Debug.DrawRay(GroundDetector1.position, Vector2.down * distance, inGround ? Color.blue : Color.red);
Debug.DrawRay(GroundDetector2.position, Vector2.down * distance, inGround ? Color.blue : Color.red);
}
private void FixedUpdate()
{
inGround = Physics2D.Raycast(GroundDetector1.position, Vector2.down, distance, 1 << LayerMask.NameToLayer("Ground"))
|| Physics2D.Raycast(GroundDetector2.position, Vector2.down, distance, 1 << LayerMask.NameToLayer("Ground"));
if (inGround && !doublejumpAvaliable) //Important, need to use this because when you back to ground after double jump, you can use double jump again.
{
doublejumpAvaliable = true;
}
// ? representa se, e o : se não
//transfrm position é a posição do jogador , vetor de posição para baixo vezes a distance, e tambem a layer mask
}
}
<file_sep>/Assets/Scripts/Move.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
public float Velocity = 1f;
public Vector2 direction = Vector2.right;
public bool reversedirection;
public float inverttime = 1f;
int newdirection = 1;
private void Start()
{
if (reversedirection)
{
InvokeRepeating("Reversedirection", inverttime, inverttime);
}
}
void Reversedirection()
{
newdirection *= -1;
}
private void Update()
{
transform.Translate(direction * Velocity * newdirection * Time.deltaTime);
}
}
<file_sep>/README.md
# Plataform Game Demonstration project
Link to play in Web (acc console too ) https://kazumashachou.github.io/Game_typeplataform/Builds/
Enjoy!
<file_sep>/Assets/Scripts/PlayerMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public Rigidbody2D rb;
public Animator anim;
public float velocity = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
var h = Input.GetAxis("Horizontal");
print(h);
/* Seta para direita, o valor do h vai até 1, somando um pouco na horizontal a cada frame
Seta para esquerda, o valor do h vai para -1, dimuindo um pouco a cada frama */
rb.velocity = new Vector2(h * velocity, rb.velocity.y);
//aponta a direção do movimento, personagem vai virar para onde direta ou esquerda
if (h > 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
else if (h < 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
//Animação de movimento
anim.SetBool("Run", Mathf.Abs(rb.velocity.x) > 0);
}
}
<file_sep>/Assets/Scripts/Death.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Death : MonoBehaviour
{
public float ydeath;
private void Update()
{
if (transform.position.y < ydeath)
{
Die();
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Enemy"))
{
Die();
}
}
void Die()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
|
5dbd9f2b3a791503d1d3126ee25e98fb6f988dff
|
[
"Markdown",
"C#"
] | 5
|
C#
|
KazumaShachou/Game_typeplataform
|
af85dd1038a1bc69a796c7a4f9c3223c120f0912
|
c92669e61cc12cccc5f7df260fa636c9c7868e3e
|
refs/heads/master
|
<file_sep># db creation
-- CREATE DATABASE photo_store;
-- SHOW DATABASES;
-- SELECT DATABASE();
-- USE photo_store;
-- SELECT DATABASE();
# table creation ;
# TODO: camera table is done
-- CREATE TABLE cameras(
-- model_name varchar(30),
-- quantity int
-- );
SHOW TABLES;
DESC cameras
<file_sep># mysql
linux path is /opt/lamp/bin/mysql -u root -p
executing from the files
creqate the file with sql note with sql extention (filename.sql) commands
and type the command
### source filepath
<file_sep>SHOW DATABASES;
# db creation
CREATE DATABASE test1;
SHOW DATABASES;
#drop the db
DROP DATABASE test1;
SHOW DATABASES;
|
188947ec6e1b4d81351942d6e9682e75d0af8153
|
[
"Markdown",
"SQL"
] | 3
|
SQL
|
3vilbird/mysql
|
2208fb68475bc0553a0c6a6d712beacdad64b1d8
|
76aecff46bb344d7cc4940d2b49c28865934c95c
|
refs/heads/master
|
<file_sep># Prototypes
Unity projects too small to be separated into their own repos.
<file_sep>using UnityEngine;
using System.Collections;
public class Zombie : MonoBehaviour
{
public int hp = 25, damage = 5;
void Update()
{
}
void OnTriggerEnter(Collider collider)
{
if(collider.tag == "Bullet")
{
hp -= 5;
if (hp <= 0)
Destroy(gameObject);
}
}
}
<file_sep>using UnityEngine;
#if UNITY_ADS
using UnityEngine.Advertisements;
#endif
using System.Collections;
public class GameScript : MonoBehaviour
{
bool adsShown = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
#if UNITY_ADS
if (Advertisement.IsReady() && !adsShown && !Advertisement.isShowing)
{
ShowOptions options = new ShopOptions{resultCallback = toggleAdsShown};
Advertisement.Show(options);
}
#endif
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public float movementSpeed = 1f, rotationSpeed = 1f, bulletSpeed = 1f, barrelFlashDelay = 1f;
public int hp = 100;
public Transform gunBarrelEnd;
public GameObject bulletObject;
public AudioClip gunSound;
public Texture2D deadIcon;
public GUISkin skin;
CharacterController cc;
float barrelFlashTime = 0f, damageTakenTime = 0f;
bool dead = false;
void Start()
{
cc = GetComponent<CharacterController>();
}
void Update()
{
if (!dead)
{
if (gunBarrelEnd.GetComponent<Light>().enabled)
if (Time.time >= barrelFlashTime)
gunBarrelEnd.GetComponent<Light>().enabled = false;
if (Input.GetKeyDown(KeyCode.RightControl) || Input.GetButtonDown("Fire1"))
{
GameObject go = Instantiate(bulletObject, gunBarrelEnd.position, transform.rotation) as GameObject;
go.GetComponent<Rigidbody>().AddForce(transform.forward * bulletSpeed);
gunBarrelEnd.GetComponent<Light>().enabled = true;
barrelFlashTime = Time.time + barrelFlashDelay;
GetComponent<AudioSource>().PlayOneShot(gunSound);
}
}
}
void FixedUpdate()
{
if (!dead)
{
cc.SimpleMove(transform.forward * Input.GetAxis("Vertical") * movementSpeed);
transform.Rotate(Vector3.up * Input.GetAxis("Horizontal") * rotationSpeed);
cc.SimpleMove(transform.right * Input.GetAxis("Strafe") * movementSpeed);
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.transform.tag == "Zombie" && damageTakenTime <= Time.time)
{
hp -= 10;
damageTakenTime = Time.time;
if (hp <= 0)
{
cc.enabled = false;
dead = true;
}
}
}
void OnGUI()
{
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(Screen.width / 1280f, Screen.height / 720f, 1));
GUI.skin = skin;
if (dead)
{
//GUI.Box(new Rect(340, 60, 600, 600), "");
GUI.DrawTexture(new Rect(490, 100, 300, 300), deadIcon);
GUI.Label(new Rect(490, 540, 300, 40), "You died!");
if (GUI.Button(new Rect(490, 600, 300, 40), "Back to main menu"))
Application.LoadLevel(0);
}
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public string[] levels;
public GameObject buttonPrefab;
void Start()
{
if (buttonPrefab != null)
for (int i = 0; i < levels.Length; i++)
{
GameObject button = GameObject.Instantiate(buttonPrefab) as GameObject;
button.GetComponentInChildren<Text>().text = levels[i];
button.transform.SetParent(transform, false);
button.transform.localPosition = Vector3.zero + Vector3.up * (250 - i * 32);
}
else
Debug.LogError("Mainmenu is missing the button prefab");
}
}
|
2565ac9acfcf6d8dc980ac56d027c2bed314b7df
|
[
"Markdown",
"C#"
] | 5
|
Markdown
|
jaakaappi/Prototypes
|
7382ae0edc7875f97696cd1d51cedf395361ba3b
|
c778b838e831cdc9c9d3f173411e1d35d375d1b7
|
refs/heads/main
|
<repo_name>Granvia/TimeTempHumidity<file_sep>/time_temp_humidity_display.ino
//Greetings hackster.io users!
//Date, Time, Temperature and Humidity Display
/////////////////////////For OLED////////////////////////
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// If using software SPI (the default case):
#define OLED_MOSI 9 //MOSI aka SDA
#define OLED_CLK 10 //CLK aka SCL
#define OLED_DC 11
#define OLED_CS 12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
/////////////////////////////////////////////////////////////
////////////////////////////For DHT//////////////////////////
#include<dht.h>
dht DHT;
#define DHT11_PIN 3
int DHTtimer = 0;
/////////////////////////////////////////////////////////////
////////////////////////////For RTC (DS3231)//////////////////////////
//SDA to A4, SCL to A5
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return( (val/16*10) + (val%16) );
}
/////////////////////////////////////////////////////////////
void setup()
{
Wire.begin();
Serial.begin(9600);
//set the initial time here, after setting the time, comment this section
//DS3231 seconds, minutes, hours, day, date, month, year
//setDS3231time(00,24,12,6,3,2,17);
display.begin(SSD1306_SWITCHCAPVCC);
display.clearDisplay();
}
////////////////////////////DS3231 coding//////////////////////////
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)
{
// sets time and date data to DS3231
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set next input to start at the seconds register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
void displayTime()
{
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
// retrieve data from DS3231
readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
&year);
// send it to the serial monitor
Serial.print(hour, DEC);
// convert the byte variable to a decimal number when displayed
Serial.print(":");
if (minute<10)
{
Serial.print("0");
}
Serial.print(minute, DEC);
Serial.print(":");
if (second<10)
{
Serial.print("0");
}
Serial.print(second, DEC);
Serial.print(" ");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
Serial.print(month, DEC);
Serial.print("/");
Serial.print(year, DEC);
Serial.print(" Day of week: ");
//////////////////////////////////////////////////////////////////
display.setCursor(50,0);
display.print(dayOfMonth, DEC);
display.print(",");
display.setCursor(91,0);
display.print("20");
display.print(year, DEC);
if (hour<10)
{
display.setCursor(40,10);
display.print("0");
display.print(hour, DEC);
display.print(":");
}
if (hour>9)
{
display.setCursor(40,10);
display.print(hour, DEC);
display.print(":");
}
if (minute<10)
{
display.setCursor(58,10);
display.print("0");
display.print(minute, DEC);
display.print(":");
}
if (minute>9)
{
display.setCursor(58,10);
display.print(minute, DEC);
display.print(":");
}
if (second<10)
{
display.setCursor(75,10);
display.print("0");
display.print(second, DEC);
}
if (second>9)
{
display.setCursor(75,10);
display.print(second, DEC);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////FOR DAY OF WEEK/////////////////////
switch(dayOfWeek){
case 1:
Serial.println("Sunday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Sun");
break;
case 2:
Serial.println("Monday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Mon");
break;
case 3:
Serial.println("Tuesday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Tue");
break;
case 4:
Serial.println("Wednesday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Wed");
break;
case 5:
Serial.println("Thursday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Thur");
break;
case 6:
Serial.println("Friday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Fri");
break;
case 7:
Serial.println("Saturday");
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(20,0);
display.print("Sat");
break;
}
//////////////////////////////FOR MONTH/////////////////////
switch(month)
{
case 1:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Jan");
break;
case 2:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Feb");
break;
case 3:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Mar");
break;
case 4:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Apr");
break;
case 5:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("May");
break;
case 6:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Jun");
break;
case 7:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Jul");
break;
case 8:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Aug");
break;
case 9:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Sep");
break;
case 10:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Oct");
break;
case 11:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Nov");
break;
case 12:
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,0);
display.print("Dec");
break;
}
/////////////HOUR HAND///////////////
float x1, y1, a, b;
const float pi = 3.14;
a=((hour-15)*30);
b = (a*pi)/180;
x1=40+(9*cos(b));
y1=41+(9*sin(b));
display.drawLine(40,41, x1, y1, WHITE);
/////////////MINUTE HAND///////////////
// float x1, y1, a, b;
// const float pi = 3.14;
a=((minute-15)*6);
b = (a*pi)/180;
x1=40+(17*cos(b));
y1=41+(17*sin(b));
display.drawLine(40,41, x1, y1, WHITE);
/////////////SECOND HAND///////////////
//float x1, y1, a, b;
a=((second-15)*6);
b = (a*pi)/180;
x1=40+(19*cos(b));
y1=41+(19*sin(b));
display.drawLine(40,41, x1, y1, WHITE);
////////////////PARTS OF THE ANALOG CLOCK THAT WILL NOT BE MOVING////////////////
display.drawCircle(40, 41, 22, WHITE);
display.drawCircle(40, 41, 1, WHITE);
display.drawLine(40, 20, 40, 25, WHITE); //12
display.drawLine(40, 63, 40, 58, WHITE); //6
display.drawLine(62, 41, 57, 41, WHITE); //3
display.drawLine(19, 41, 24, 41, WHITE); //9
display.drawLine(50, 24, 47, 28, WHITE); //1
display.drawLine(57, 31, 53, 34, WHITE); //2
display.drawLine(60, 51, 54, 48, WHITE); //4
display.drawLine(51, 58, 48, 54, WHITE); //5
display.drawLine(29, 58, 32, 54, WHITE); //7
display.drawLine(21, 51, 25, 48, WHITE); //8
display.drawLine(22, 31, 27, 33, WHITE); //10
display.drawLine(30, 23, 32, 28, WHITE); //11
}
void ReadTempAndHum ()
{
int chk = DHT.read11(DHT11_PIN);
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(70,45);
display.print("Temp: ");
display.print(DHT.temperature, 0);
display.print("C");
display.setCursor(70,56);
display.print("Hum: ");
display.print(DHT.humidity, 0);
display.print("%");
Serial.print(" Humidity: " );
Serial.print(DHT.humidity, 1);
Serial.print("%");
Serial.print(" | Temperature: ");
Serial.print(DHT.temperature, 1);
Serial.println("C");
}
void loop() {
displayTime(); // display the real-time clock data on the Serial Monitor,
DHTtimer = DHTtimer + 1;
//To ensure that the DHT is read only every 2 seconds, we make a count that goes for 2 seconds
if (DHTtimer > 1)
{
display.fillRect(70, 45, 128, 64, BLACK);
ReadTempAndHum ();
DHTtimer = 0;
}
delay(1000);
display.display();
//The portion of the screen that shows the time and date are cleared
display.fillRect(0, 0, 64, 64, BLACK);
display.fillRect(0, 0, 128, 20, BLACK);
}
|
d10acbcbfa53484274eb50cbf45e143fe4a4ff7d
|
[
"C++"
] | 1
|
C++
|
Granvia/TimeTempHumidity
|
54acc14a006f8a6715ff37d9a54c6597f993a0dc
|
e321fcc50d97a9231558aac19e26142f1ee3e023
|
refs/heads/master
|
<repo_name>joekarasek/kennedy<file_sep>/src/js/scripts.js
(function($, HelloWorldDevsTysonSteele) {
// ======= Fixes =======
HelloWorldDevsTysonSteele.noOrphans('h1,h2,h3,h4,h5,h6,li,p', '.allow-orphan');
HelloWorldDevsTysonSteele.scrollToFix('#primary-menu');
HelloWorldDevsTysonSteele.stopVideoModal('#videoModal', '#video-one');
// ======= Request Appointment Form =======
HelloWorldDevsTysonSteele.requestAppointment('#mail-form', '#success_msg' , '7fb35345-752d-4792-9480-cd3db6674a62');
// ======= Google Maps =======
HelloWorldDevsTysonSteele.googleMap('#google-map5', '45.5769959,-122.7030303', '45.5769959,-122.7030303');
// ======= Carousels =======
HelloWorldDevsTysonSteele.marqueeCarousel({
autoplay: 6000,
effect: 'fade',
speed: 500
});
HelloWorldDevsTysonSteele.pyramidCarousel('.js-team-carousel', {
navText: [
'<img src="assets/arrow_left.png" alt="left navigation arrow">',
'<img src="assets/arrow_right.png" alt="right navigation arrow">'
]
});
HelloWorldDevsTysonSteele.tourCarousel('.js-tour-carousel', {
items: 1,
navText: [
'<i class="icon-chevron-left"></i>',
'<i class="icon-chevron-right"></i>'
]
});
HelloWorldDevsTysonSteele.associationCarousel('.js-associations-carousel', {
nav: false,
autoWidth: false,
slideBy: 1,
});
HelloWorldDevsTysonSteele.tourCarousel('.js-gallery-carousel', {
items: 1,
navText: [
'<i class="icon-chevron-left"></i>',
'<i class="icon-chevron-right"></i>'
]
});
HelloWorldDevsTysonSteele.updateCopyright('.js-copyright-year');
}(jQuery, HelloWorldDevsTysonSteele));
|
141e94e94bf000fd5ce555a0a33254dca0ab3e27
|
[
"JavaScript"
] | 1
|
JavaScript
|
joekarasek/kennedy
|
1f0d92092d577d5b327408a226c1782454ebe0db
|
1dc9f03bf8b62e617d3986ba46e88449b33d5d39
|
refs/heads/master
|
<repo_name>winsonwq/wysihtml5<file_sep>/Gruntfile.js
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
distFileName: '<%= pkg.name %>-<%= pkg.version %>',
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true,
separator: ';'
},
dist: {
src: [
'src/browser.js',
'src/lang/*.js',
'src/dom/*.js',
'src/quirks/*.js',
'src/selection/*.js',
'src/commands.js',
'src/commands/*.js',
'src/undo_manager.js',
'src/views/*.js',
'src/toolbar/*.js',
'src/editor.js'
],
dest: 'dist/<%= distFileName %>.js'
},
},
uglify: {
options: '<%= concat.options %>',
dist: {
src: '<%= concat.dist.src %>',
dest: 'dist/<%= distFileName %>.min.js'
},
},
nodeunit: {
files: ['test/**/*_test.js']
},
watch: {
test: {
files: ['test/*.js', 'test/*/*.js', 'test/*.html'],
tasks: ['qunit']
},
},
qunit: {
options: {
timeout: 10000,
'--cookies-file': 'misc/cookies.txt'
},
all: ['test/*.html']
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.registerTask('build', ['concat', 'uglify']);
};
|
1373fbf27c3d991cb57977495444631ebfaf7047
|
[
"JavaScript"
] | 1
|
JavaScript
|
winsonwq/wysihtml5
|
badd45880267288624329f28cbd744c2b65633c4
|
efa79e106172352412c23d9bc9aa0c0f96f63489
|
refs/heads/master
|
<repo_name>jQwotos/PinAtlas<file_sep>/app/src/main/java/com/pinatlas/pinatlas/viewmodel/DetailsViewModel.kt
package com.pinatlas.pinatlas.viewmodel
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.lifecycle.*
import com.pinatlas.pinatlas.R
import com.pinatlas.pinatlas.model.PlaceDetails
import com.pinatlas.pinatlas.model.Trip
import com.pinatlas.pinatlas.repository.TripsRepository
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.google.firebase.firestore.ListenerRegistration
class DetailsViewModel(tripId: String, placeId: String) : ViewModel() {
private val tripsRepository = TripsRepository()
private val _placeDetails = MutableLiveData(PlaceDetails())
var tripListener: ListenerRegistration
val busyData: LiveData<BarData> = Transformations.map(_placeDetails) {placeDetails: PlaceDetails? ->
var barEntries = placeDetails?.Place?.busyData?.busyTimes?.get(placeDetails.busyDay)?.data?.mapIndexed { index, level ->
BarEntry(index.toFloat(), level.toFloat())
} ?: arrayListOf()
var barDataSet = BarDataSet(barEntries, placeDetails?.busyDay.toString())
barDataSet.color = R.color.quantum_grey
BarData(barDataSet)
}
val place: LiveData<PlaceDetails>
get() = _placeDetails
val rating: LiveData<String> = Transformations.map(_placeDetails) { placeDetails ->
if (placeDetails?.Place?.rating != null) "${placeDetails?.Place?.rating} / 5" else ""
}
val timeSpent: LiveData<String> = Transformations.map(_placeDetails) { placeDetails ->
if (placeDetails.Place?.busyData?.avgSpentTimes != null)
"People spend between ${placeDetails.Place?.busyData!!.avgSpentTimes!![0]} min to ${placeDetails.Place?.busyData!!.avgSpentTimes!![1]} min here."
else ""
}
fun setBusyDay(day: Int) {
_placeDetails.value!!.busyDay = day
_placeDetails.postValue(_placeDetails.value)
}
fun callPlace(view: View) {
var intent = Intent(Intent.ACTION_CALL, Uri.parse("tel: ${place.value!!.Place?.phoneNumber}"))
if (ActivityCompat.checkSelfPermission(view.context, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
view.context.startActivity(intent)
}
}
fun openNavigation(view: View) {
var intent = Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${place.value!!.Place?.address}"))
intent.setPackage("com.google.android.apps.maps");
view.context.startActivity(intent)
}
init {
tripListener = tripsRepository.fetchTrip(tripId).addSnapshotListener { tripSnapshot, _ ->
val trip = Trip.fromFirestore(tripSnapshot!!)
if (trip != null && trip.places.size > 0) {
val place = trip.places.find { p -> p.placeId == placeId }
_placeDetails.value!!.Place = place
_placeDetails.postValue(_placeDetails.value)
}
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/SalesmanGenome.kt
package com.pinatlas.pinatlas.model.matrix
//This code is a modified version of : https://stackabuse.com/traveling-salesman-problem-with-genetic-algorithms-in-java/
import java.util.*
import kotlin.collections.ArrayList
class SalesmanGenome: Comparable<Any> {
var genome: List<Int>
internal set
internal var travelPrices: Array<IntArray>
var startingCity: Int = 0
internal set
internal var numberOfCities: Int = 0
var fitness: Int = 0
//Random genome- Used in initial population
constructor(numberOfCities: Int, travelPrices: Array<IntArray>, startingCity: Int) {
this.travelPrices = travelPrices
this.startingCity = startingCity
this.numberOfCities = numberOfCities
genome = randomSalesman()
fitness = this.calculateFitness()
}
//generates a user defined genome
constructor(
permutationOfCities: List<Int>,
numberOfCities: Int,
travelPrices: Array<IntArray>,
startingCity: Int
) {
genome = permutationOfCities
this.travelPrices = travelPrices
this.startingCity = startingCity
this.numberOfCities = numberOfCities
fitness = this.calculateFitness()
}
fun calculateFitness(): Int {
var fitness = 0
var currentCity = startingCity
for (gene in genome) {
fitness += travelPrices[currentCity][gene]
currentCity = gene
}
fitness += travelPrices[genome[numberOfCities - 2]][startingCity]
return fitness
}
private fun randomSalesman(): List<Int> {
val result = ArrayList<Int>()
for (i in 0 until numberOfCities) {
if (i != startingCity)
result.add(i)
}
Collections.shuffle(result)
return result
}
val optimizedRoute: List<Int>
get() = listOf(listOf(startingCity), genome, listOf(startingCity)).flatten()
override operator fun compareTo(o: Any): Int {
val genome = o as SalesmanGenome
return if (this.fitness > genome.fitness)
1
else if (this.fitness < genome.fitness)
-1
else
0
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/DetailsItemView.kt
package com.pinatlas.pinatlas
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TableRow
import android.widget.TextView
import com.pinatlas.pinatlas.databinding.DetailsItemViewBinding
class DetailsItemView(context: Context, attributeSet: AttributeSet): TableRow(context, attributeSet) {
private var textView: TextView
private var tableRow: TableRow
private var imageView: ImageView
init {
DetailsItemViewBinding.inflate(LayoutInflater.from(context), this, true)
imageView = findViewById(R.id.detailsImage)
textView = findViewById(R.id.detailsTextView)
tableRow = findViewById(R.id.detailsItemView)
val attributes = context.obtainStyledAttributes(attributeSet, R.styleable.DetailsItemView)
val text = attributes.getText(R.styleable.DetailsItemView_text)
imageView.setImageDrawable(attributes.getDrawable(R.styleable.DetailsItemView_imageSrc))
attributes.recycle()
}
/* Data Binding, do not remove */
fun getText() : String {
return textView.text.toString()
}
fun setText(text: String?) {
if (text == "" || text == null) {
tableRow.visibility = View.GONE
} else {
textView.text = text
tableRow.visibility = View.VISIBLE
}
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/constants/TransportationMethods.kt
package com.pinatlas.pinatlas.constants
/*
enum type is a special data type that enables for a variable to be a set of predefined constants; used to check if we dont want to check it's a string
ex/ inside of itinerary mode, we can either hardcode a string. We could do the same w/ the Adapter.
If we have a typo/want to change, then we have to modify the code everywhere.
Instead, we use enum's as a "variables" (don't have to update code if we
*/
/* Owner: MV */
enum class TransportationMethods(val type: String) {
DRIVING("driving"),
WALKING("walking"),
BICYCLING("bicycling"),
TRANSIT("transit")
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/adapter/PlaceListAdapter.kt
package com.pinatlas.pinatlas.adapter
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.pinatlas.pinatlas.DetailsView
import com.pinatlas.pinatlas.ItemMoveCallback
import com.pinatlas.pinatlas.R
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.constants.ViewModes
import com.pinatlas.pinatlas.utils.PlaceThumbnailUtil
import com.pinatlas.pinatlas.viewmodel.CreationViewModel
// Whenever we create an PlaceListAdapter, we specify the mode, the view model, context
/* Owner: AZ */
class PlaceListAdapter (private val viewModel: CreationViewModel, private val mode: ViewModes, private val context: Context
) : RecyclerView.Adapter<PlaceListAdapter.ViewHolder>(), ItemMoveCallback.ItemTouchHelperContract {
private val places = viewModel.tripPlaces
/*
internal Android Logic (Cmd + Click; if asked to override, then it's created by Android)
when Android creates it, it's trying to figure out which layout to use
*/
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(viewGroup.context)
val view = inflater.inflate(R.layout.item_creation_list_tile, viewGroup, false)
return ViewHolder(view)
}
/* internal Android Logic
value: returns actual object stored within LiveData Object
ViewModes: constant (set to ITINERARY MODE)
*/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val place = places.value!![position]
/* in itinerary mode, we hide the delete button in itinerary
*
* We do this to prevent page duplication since the only difference (for now) between itinerary mode and creation mode
* is that itinerary mode does not allow users to delete items (in our system)
* */
PlaceThumbnailUtil.populateImageView(place.placeId, holder.thumbnail, context)
holder.activity.text = place.name
holder.address.text = place.address
if (mode == ViewModes.ITINERARY_MODE) {
holder.deleteButton.visibility = View.GONE
if(!place.canvisit){
holder.address.text = "Unable to visit this place!! Maybe Next time!!"
}else{
holder.address.text = place.starttime.toDate().toString()
}
// this allows us to zoom in to the place when we click on the "card" in itinerary view
holder.itemView.setOnClickListener {
viewModel.latLng.postValue(place.coordinates)
}
}
// updates info in Firebase
holder.deleteButton.setOnClickListener {
viewModel.deletePlace(position)
viewModel.saveTrip()
}
holder.infoButton.setOnClickListener {
val intent = Intent(it.context, DetailsView::class.java)
intent.putExtra(Constants.TRIP_ID.type, viewModel.trip.value!!.tripId)
intent.putExtra(Constants.PLACE_ID.type, place.placeId)
it.context.startActivity(intent)
}
}
// internal Android Logic -- check if list has any items
override fun getItemCount(): Int {
return places.value?.size ?: 0
}
// public -> gets used throughout our code
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(
itemView) {
val activity: TextView = itemView.findViewById(R.id.activityName) as TextView
val address: TextView = itemView.findViewById(R.id.activityAddress) as TextView
val deleteButton: ImageView = itemView.findViewById(R.id.deleteSymbol) as ImageView
val thumbnail: ImageView = itemView.findViewById(R.id.thumbnail) as ImageView
val infoButton: ImageView = itemView.findViewById(R.id.infoSymbol)
val card: CardView = itemView as CardView
}
// when the user clicks on the card, it'll change the background colour to show what the user is selecting
/* Owner: MV */
// todo: change to XML colours (MONICA)
override fun onRowClear(viewHolder: ViewHolder) {
viewHolder.card.setCardBackgroundColor(Color.parseColor("#EA3F60"))
}
// when we move the row, we'll update our Firestore the new priority
override fun onRowMoved(fromPosition: Int, toPosition: Int) {
viewModel.updatePlacePriority(fromPosition, toPosition)
viewModel.saveTrip()
}
// change the background back to the original colour
override fun onRowSelected(viewHolder: ViewHolder) {
viewHolder.card.setCardBackgroundColor(Color.parseColor("#e87289"))
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/TravelDash.kt
package com.pinatlas.pinatlas
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.pinatlas.pinatlas.adapter.TripAdapter
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.model.Trip
import com.pinatlas.pinatlas.viewmodel.TripsViewModel
import com.pinatlas.pinatlas.viewmodel.TripsViewModelFactory
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.mapbox.android.core.permissions.PermissionsListener
import com.mapbox.android.core.permissions.PermissionsManager
import com.mapbox.geojson.Feature
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.Point
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
import com.mapbox.mapboxsdk.location.LocationComponentOptions
import com.mapbox.mapboxsdk.location.modes.CameraMode
import com.mapbox.mapboxsdk.location.modes.RenderMode
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.PropertyFactory
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import com.takusemba.multisnaprecyclerview.MultiSnapRecyclerView
class TravelDash : AppCompatActivity() , OnMapReadyCallback, PermissionsListener, TripAdapter.OnTripSelectedListener {
private val TAG = TravelDash::class.java.simpleName
//Mapbox
private lateinit var mapView : MapView
private lateinit var mapboxMap: MapboxMap
//Items
private lateinit var addTripBtn: Button
// FIREBASE
private val currentUser: FirebaseUser? by lazy { FirebaseAuth.getInstance().currentUser }
private lateinit var viewModel: TripsViewModel
private lateinit var pastTripsAdapter: TripAdapter
private lateinit var upcommingTripsAdapter: TripAdapter
private var permissionsManager: PermissionsManager = PermissionsManager(this)
override fun onTripSelected(trip: Trip) {
val intent = Intent(this, ItineraryView::class.java)
intent.putExtra(Constants.TRIP_ID.type, trip.tripId)
startActivity(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(applicationContext, getString(R.string.mapbox_access_token))
setContentView(R.layout.traveldash)
context = this
//For the Mapbox Implementation
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
addTripBtn = findViewById(R.id.addTripBtn)
//Local the tiles for past/upcoming trips
// Factory Pattern: We can create different ViewModels based on the interface
viewModel = ViewModelProviders.of(
this,
TripsViewModelFactory(userId = this.currentUser!!.uid))
.get(TripsViewModel::class.java)
pastTripsAdapter = TripAdapter(viewModel.previousTrips, context, this)
// Factory Pattern: we modify the ViewModel to do what we need
// Observer Pattern: we watch when the trips change
viewModel.previousTrips.observe(this, Observer { update ->
if (update != null) {
pastTripsAdapter.notifyDataSetChanged()
}
})
// TODO: Change pastTripsQuery to find past trips instead of all trips
val pastRecyclerView = findViewById<MultiSnapRecyclerView>(R.id.PTview)
val pastManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
pastRecyclerView.layoutManager = pastManager
pastRecyclerView.adapter = pastTripsAdapter
// upcoming trips
upcommingTripsAdapter = TripAdapter(viewModel.upcomingTrips, this, this)
viewModel.upcomingTrips.observe(this, Observer { update ->
if (update != null) {
upcommingTripsAdapter.notifyDataSetChanged()
}
})
val upcomingRecyclerView = findViewById<MultiSnapRecyclerView>(R.id.UTView)
val upcomingManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
upcomingRecyclerView.layoutManager = upcomingManager
upcomingRecyclerView.adapter = upcommingTripsAdapter
}
fun updateStyle(style: Style) {
var upcommingTrips = viewModel.upcomingTrips.value
var pastTrips = viewModel.previousTrips.value
if (upcommingTrips != null) {
this.drawPlacesFromTrips(
Constants.UPCOMING_PLACES_LAYER_ID.type,
Constants.UPCOMING_PLACES_ICON_ID.type, style, upcommingTrips
)
}
if (pastTrips != null) {
this.drawPlacesFromTrips(
Constants.PREVIOUS_PLACES_LAYER_ID.type,
Constants.PREVIOUS_PLACES_ICON_ID.type, style, pastTrips
)
}
}
fun setMapStyle(mapboxMap: MapboxMap) {
mapboxMap.setStyle(Style.Builder()
.fromUri("mapbox://styles/davidchopin/cjtz90km70tkk1fo6oxifkd67")) { style ->
style.addImage(
Constants.UPCOMING_PLACES_ICON_ID.type,
BitmapFactory.decodeResource(resources, R.drawable.blue_pin))
style.addImage(
Constants.PREVIOUS_PLACES_ICON_ID.type,
BitmapFactory.decodeResource(resources, R.drawable.pink_pin))
updateStyle(style)
enableLocationComponent(style)
}
}
override fun onMapReady(mapboxMap: MapboxMap) {
this.mapboxMap = mapboxMap
viewModel.previousTrips.observe(this, Observer {
setMapStyle(this.mapboxMap)
})
viewModel.upcomingTrips.observe(this, Observer {
setMapStyle(this.mapboxMap)
})
}
fun drawPlacesFromTrips(layerId: String, iconId: String, style: Style, trips: List<Trip>) {
val sourceId = "${layerId}_SOURCE"
style.removeSource(sourceId)
style.removeLayer(layerId)
val latLngs = arrayListOf<Feature>()
for (trip in trips) {
latLngs.addAll(trip.places.map { place ->
Feature.fromGeometry(Point.fromLngLat(
place.coordinates!!.longitude,
place.coordinates!!.latitude
))
})
}
style.addSource(GeoJsonSource(sourceId, FeatureCollection.fromFeatures(latLngs)))
style.addLayer(
SymbolLayer(layerId, sourceId)
.withProperties(
PropertyFactory.iconImage(iconId),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconSize(0.5f),
PropertyFactory.iconAllowOverlap(true)
)
)
}
@SuppressLint("MissingPermission")
private fun enableLocationComponent(loadedMapStyle: Style) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create and customize the LocationComponent's options
val customLocationComponentOptions = LocationComponentOptions.builder(this)
.trackingGesturesManagement(true)
.accuracyColor(ContextCompat.getColor(this, R.color.mapbox_blue))
.build()
val locationComponentActivationOptions = LocationComponentActivationOptions.builder(this, loadedMapStyle)
.locationComponentOptions(customLocationComponentOptions)
.build()
// Get an instance of the LocationComponent and then adjust its settings
mapboxMap.locationComponent.apply {
// Activate the LocationComponent with options
activateLocationComponent(locationComponentActivationOptions)
// Enable to make the LocationComponent visible
isLocationComponentEnabled = true
// Set the LocationComponent's camera mode
cameraMode = CameraMode.TRACKING
// Set the LocationComponent's render mode
renderMode = RenderMode.COMPASS
}
}
else {
permissionsManager = PermissionsManager(this)
permissionsManager.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show() //Need this is to be removed
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
enableLocationComponent(mapboxMap.style!!)
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show() //Need this is to be removed
finish()
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
fun createNewTrip(view: View) {
val intent = Intent(this, CreationView::class.java)
viewModel.addTrip(Trip(userId = currentUser!!.uid))!!.addOnSuccessListener {
intent.putExtra(Constants.TRIP_ID.type, it.id)
startActivity(intent)
}.addOnFailureListener {
Log.e(TAG, "Failed to create trip with error $it")
Toast.makeText(context, "Failed to make trip", Toast.LENGTH_LONG).show()
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
viewModel.tripsListener.remove()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
fun logout(view: View) {
FirebaseAuth.getInstance().signOut()
intent = Intent(this, GoogleLogin::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
companion object {
lateinit var context: Context
}
}
<file_sep>/settings.gradle
include ':app'
rootProject.name='PinAtlas'
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/utils/MatrixifyUtil.kt
package com.pinatlas.pinatlas.utils
import android.util.Log
import com.pinatlas.pinatlas.model.Place
import com.pinatlas.pinatlas.model.matrix.DistanceMatrixModel
import com.pinatlas.pinatlas.model.matrix.Salesman
import com.pinatlas.pinatlas.model.matrix.SalesmanGenome
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.firebase.Timestamp
import org.jetbrains.anko.doAsync
import java.util.*
import kotlin.collections.ArrayList
/* Owner: SS */
object MatrixifyUtil {
private val TAG = MatrixifyUtil::class.java.simpleName
//Maps the algorithm's index to places
fun repositionPlaces(places: List<Place>, optimizedIndex: List<Int>, distanceMatrixModel: DistanceMatrixModel) : Task<List<Place>> {
return Tasks.forResult(optimizedIndex.map { index -> places.get(index) })
}
fun generateGenome(distanceMatrixModel: DistanceMatrixModel): Task<SalesmanGenome> {
Log.d(TAG, distanceMatrixModel.rows!!.indices.toString())
Log.d(TAG, distanceMatrixModel.status)
val travelDurations = Array(distanceMatrixModel.rows!!.size) { IntArray(distanceMatrixModel.rows!!.size) }
for(n in 0 until (distanceMatrixModel.rows!!.size - 1)) {
for(k in 0 until (distanceMatrixModel.rows!!.size - 1)) {
travelDurations[n][k] = distanceMatrixModel.rows!!.get(n).elements!!.get(k).duration!!.value.toInt()
Log.d(TAG,distanceMatrixModel.rows!!.get(n).elements!!.get(k).duration!!.value.toString())
}
Log.d(TAG,"\n\n")
}
//Optimization is done here
val geneticAlgorithm =
Salesman(distanceMatrixModel.rows!!.size, travelDurations, 0, 0)
return Tasks.forResult(geneticAlgorithm.optimize())
}
fun setPlaceTimes(places : List<Place>, distanceMatrixModel: DistanceMatrixModel, tripstart: Timestamp, tripend: Timestamp): List<Place> {
var placesout : List<Place> = places
var start : Calendar = Calendar.getInstance()
start.setTime(tripstart.toDate())
start.set(Calendar.HOUR_OF_DAY,9)
start.set(Calendar.MINUTE,30)
start.set(Calendar.SECOND,0)
start.set(Calendar.MILLISECOND,0)
Log.e("xox START",start.time.toString())
var endday : Calendar = Calendar.getInstance()
endday.setTime(tripstart.toDate())
endday.set(Calendar.HOUR_OF_DAY,22)
endday.set(Calendar.MINUTE,30)
endday.set(Calendar.SECOND,0)
endday.set(Calendar.MILLISECOND,0)
Log.e("xox END",endday.time.toString())
var end : Calendar = Calendar.getInstance()
end.setTime(tripend.toDate())
end.set(Calendar.HOUR_OF_DAY,10)
end.set(Calendar.MINUTE,30)
end.set(Calendar.SECOND,0)
end.set(Calendar.MILLISECOND,0)
for(place in placesout){
if(placesout.indexOf(place) == placesout.size - 1) {
place.traveltime = 0
}else{
val placeOneIndex : Int? = distanceMatrixModel.origin_addresses?.indexOf(place.address)
val placeTwoIndex : Int? = distanceMatrixModel.destination_addresses?.indexOf(
placesout[placesout.indexOf(place)+1].address)
var duration: Long?
if ((placeOneIndex != null && placeTwoIndex != null && placeOneIndex >= 0 && placeTwoIndex >= 0)) {
duration = distanceMatrixModel.rows?.get(index = placeOneIndex)?.elements?.get(
placeTwoIndex
)?.duration?.value
} else {
duration = 2
}
if (duration != null) {
place.traveltime = duration
}
}
}
for(place in placesout){
//if(start)
if((placesout.indexOf(place) == 0)) {
start.set(Calendar.HOUR_OF_DAY,start.get(Calendar.HOUR_OF_DAY)+2)
place.starttime = Timestamp(start.time)
Log.e(place.name+placesout.indexOf(place).toString()+" xox==O ",place.starttime.toDate().toString())
}
else if(placesout.indexOf(place) != placesout.size-1){
if(start.compareTo(endday) == 1){ // Figure out comparisonL
start.set(Calendar.HOUR_OF_DAY,11)
start.set(Calendar.MINUTE,30)
start.set(Calendar.SECOND,0)
start.set(Calendar.DATE,start.get(Calendar.DATE)+1)
endday.set(Calendar.DATE,endday.get(Calendar.DATE)+1)
place.starttime = Timestamp(start.time)
Log.e(place.name+placesout.indexOf(place).toString()+" xox ooo ",place.starttime.toDate().toString())
place.canvisit = true
}
else if(start.compareTo(end) == 1){
place.canvisit = false
}
else{
place.canvisit = true
start.set(Calendar.SECOND, start.get(Calendar.SECOND) + Integer.parseInt(placesout.get(placesout.indexOf(place) - 1).traveltime.toString())+7200)
place.starttime = Timestamp(start.time)
Log.e(place.name+placesout.indexOf(place).toString()+" xox >>> ",place.starttime.toDate().toString())
}
}
}
return placesout
}
/* Optimize merges DistanceMatrixProvider fetchDistanceMatrix and pipes it into generateGenome */
fun optimizer(places: List<Place>, modes: List<String>, tripstart: Timestamp, tripend: Timestamp, responseHandler: (result: List<Place>?) -> Unit?) {
doAsync {
DistanceMatrixProvider.fetchAllDistanceMatrixes(destinations = places as ArrayList<Place>, modes = modes){ result: DistanceMatrixModel? ->
if (result != null ) {
generateGenome(distanceMatrixModel = result).continueWithTask { genome: Task<SalesmanGenome> ->
repositionPlaces(places, genome.result!!.optimizedRoute, result)
}.addOnSuccessListener { optimizedRoute: List<Place> ->
responseHandler(setPlaceTimes(optimizedRoute,result, tripstart, tripend))
}
} else {
responseHandler(null)
}
}
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/utils/DistanceMatrixProvider.kt
package com.pinatlas.pinatlas.utils
import android.net.Uri
import com.pinatlas.pinatlas.BuildConfig
import com.pinatlas.pinatlas.constants.TransportationMethods
import com.pinatlas.pinatlas.model.Place
import com.pinatlas.pinatlas.model.matrix.DistanceMatrixModel
import com.pinatlas.pinatlas.model.matrix.Element
import com.pinatlas.pinatlas.model.matrix.Row
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.kittinunf.fuel.httpGet
import com.google.gson.Gson
import java.io.Reader
import java.lang.Exception
/* Owner: JL */
object DistanceMatrixProvider {
var TAG = DistanceMatrixProvider::class.java.simpleName
val DISTANCE_MATRIX_BASE_URL: String = "maps.googleapis.com"
fun createDestinationsString(destinations: ArrayList<Place>) : String {
val appendedNames = destinations.map { destination -> "place_id:${destination.placeId}" }
return appendedNames.joinToString (separator = "|")
}
fun buildDistanceMatrixURI(destinations: ArrayList<Place>, mode: String = TransportationMethods.DRIVING.type) : String {
var destinationsString: String = createDestinationsString(destinations)
return Uri.Builder()
.scheme("https")
.authority(DISTANCE_MATRIX_BASE_URL)
.appendPath("maps")
.appendPath("api")
.appendPath("distancematrix")
.appendPath("json")
.appendQueryParameter("units", "metrics")
.appendQueryParameter("mode", mode)
.appendQueryParameter("origins", destinationsString)
.appendQueryParameter("destinations", destinationsString)
.appendQueryParameter("key", BuildConfig.DISTANCE_MATRIX_API_KEY)
.build()
.toString()
}
/**
* Fetches distance matrix from google api
* we use the distance matrix to calculate the time it takes to get
* between each point which will be used
* for calculating the optimal route.
*
* @param destinations List of destinations for the trip
* @param mode mode of transportation
* @param responseHandler procedure that is invoked when query is finished
*/
fun optimizeMatrices(matrixes: List<DistanceMatrixModel>): DistanceMatrixModel? {
return matrixes[0].rows?.foldIndexed(DistanceMatrixModel(
status = matrixes[0].status,
origin_addresses = matrixes[0].origin_addresses,
destination_addresses = matrixes[0].destination_addresses
)) { rowIndex, acc, row ->
acc.rows?.add(Row(
elements = ArrayList(row.elements.mapIndexedNotNull { elemenIndex, _ ->
var allElements = matrixes.mapNotNull {
var element: Element? = it.rows?.get(rowIndex)?.elements?.get(elemenIndex)
if (element?.duration?.value != null) element else null
}
allElements.minBy { it.duration!!.value }
})
))
acc
}
}
fun fetchAllDistanceMatrixes(destinations: ArrayList<Place>, modes: List<String>, responseHandler: (result: DistanceMatrixModel?) -> Any?) {
try {
var results = modes.map {mode ->
buildDistanceMatrixURI(destinations = destinations, mode = mode).httpGet().responseObject(DistanceMatrixDeserializer())
}
var matrices = results.map { result ->
result.third.get()
}
responseHandler(optimizeMatrices(matrices))
} catch(e: Exception) {
responseHandler(null)
}
}
class DistanceMatrixDeserializer: ResponseDeserializable<DistanceMatrixModel> {
override fun deserialize(reader: Reader): DistanceMatrixModel? {
return Gson().fromJson(reader, DistanceMatrixModel::class.java)
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/Distance.kt
package com.pinatlas.pinatlas.model.matrix
class Distance {
var value: Long = 0
var text: String = ""
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/PlaceDetails.kt
package com.pinatlas.pinatlas.model
class PlaceDetails {
var Place: Place? = null
var busyDay: Int = 0
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/Salemesman.kt
package com.pinatlas.pinatlas.model.matrix
//This code is a modified version of : https://stackabuse.com/traveling-salesman-problem-with-genetic-algorithms-in-java/
import java.util.*
class Salesman(
private val numberOfCities: Int,
private val travelPrices: Array<IntArray>,
private val startingCity: Int,
private val targetFitness: Int
) {
private val generationSize: Int
private val genomeSize: Int
private val reproductionSize: Int
private val maxIterations: Int
private val mutationRate: Float
private val tournamentSize: Int
init {
genomeSize = numberOfCities - 1
generationSize = 3000 //Changed from previous 5k making it quicker
reproductionSize = 200
maxIterations = 1000
mutationRate = 0.1f
tournamentSize = 40
}
fun initialPopulation(): List<SalesmanGenome> {
val population = ArrayList<SalesmanGenome>()
for (i in 0 until generationSize) {
population.add(
SalesmanGenome(
numberOfCities,
travelPrices,
startingCity
)
)
}
return population
}
fun selection(population: List<SalesmanGenome>): List<SalesmanGenome> {
val selected = ArrayList<SalesmanGenome>()
for (i in 0 until reproductionSize) {
selected.add(tournamentSelection(population))
}
return selected
}
//called by initial population
fun tournamentSelection(population: List<SalesmanGenome>): SalesmanGenome {
val selected =
pickNRandomElements<SalesmanGenome>(
population,
tournamentSize
)
return Collections.min(selected!!)
}
fun mutate(salesman: SalesmanGenome): SalesmanGenome {
val random = Random()
val mutate = random.nextFloat()
if (mutate < mutationRate) {
val genome = salesman.genome
Collections.swap(genome, random.nextInt(genomeSize), random.nextInt(genomeSize))
return SalesmanGenome(
genome,
numberOfCities,
travelPrices,
startingCity
)
}
return salesman
}
fun createGeneration(population: List<SalesmanGenome>): List<SalesmanGenome> {
val generation = ArrayList<SalesmanGenome>()
var currentGenerationSize = 0
while (currentGenerationSize < generationSize) {
val parents =
pickNRandomElements<SalesmanGenome>(
population,
2
)
val children = crossover(parents!!)
children[0] = mutate(children[0])
children[1] = mutate(children[1])
generation.addAll(children)
currentGenerationSize += 2
}
return generation
}
fun crossover(parents: List<SalesmanGenome>): MutableList<SalesmanGenome> {
val random = Random()
val breakpoint = random.nextInt(genomeSize)
val children = ArrayList<SalesmanGenome>()
var parent1Genome: List<Int> = ArrayList(parents[0].genome)
val parent2Genome = ArrayList(parents[1].genome)
for (i in 0 until breakpoint) {
val newVal: Int
newVal = parent2Genome.get(i)
Collections.swap(parent1Genome, parent1Genome.indexOf(newVal), i)
}
children.add(
SalesmanGenome(
parent1Genome,
numberOfCities,
travelPrices,
startingCity
)
)
parent1Genome = parents[0].genome
for (i in breakpoint until genomeSize) {
val newVal = parent1Genome[i]
Collections.swap(parent2Genome, parent2Genome.indexOf(newVal), i)
}
children.add(
SalesmanGenome(
parent2Genome,
numberOfCities,
travelPrices,
startingCity
)
)
return children
}
fun optimize(): SalesmanGenome {
var population = initialPopulation() // 3000 possible permutations of the matrix
var globalBestGenome = population[0] //Set one first to be the best
for (i in 0 until maxIterations) { //Run a 1000 times
val selected = selection(population) // 200 Instances given suing tournament method
population = createGeneration(selected)
globalBestGenome = Collections.min(population)
if (globalBestGenome.fitness < targetFitness)
break
}
return globalBestGenome
}
companion object {
fun <E> pickNRandomElements(list: List<E>, n: Int): List<E>? {
val r = Random()
val length = list.size
if (length < n) return null
for (i in length - 1 downTo length - n) {
Collections.swap(list, i, r.nextInt(i + 1))
}
return list.subList(length - n, length)
}
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/DetailsView.kt
package com.pinatlas.pinatlas
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.Spinner
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.viewmodel.DetailsViewModel
import com.pinatlas.pinatlas.databinding.DetailsViewBinding
import com.pinatlas.pinatlas.utils.PlaceThumbnailUtil
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.Description
import com.github.mikephil.charting.data.BarData
class DetailsView : AppCompatActivity(), AdapterView.OnItemSelectedListener {
private lateinit var viewModel: DetailsViewModel
private lateinit var imageView: ImageView
private lateinit var busyTimesChart: BarChart
private lateinit var busyTimesSpinner: Spinner
private var daysOfWeek = arrayListOf("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding : DetailsViewBinding = DataBindingUtil.setContentView(this, R.layout.details_view)
var tripId = intent.getStringExtra(Constants.TRIP_ID.type)!!
var placeId = intent.getStringExtra(Constants.PLACE_ID.type)!!
viewModel = DetailsViewModel(tripId, placeId)
binding.viewmodel = viewModel
binding.lifecycleOwner = this
/* Setup image */
imageView = findViewById(R.id.placeImage)
PlaceThumbnailUtil.populateImageView(placeId, imageView, this)
/* Setup Busy Times Spinner */
busyTimesSpinner = findViewById(R.id.busyTimesSelector)
busyTimesSpinner.onItemSelectedListener = this
var busyTimesSpinnerAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, daysOfWeek)
busyTimesSpinner.adapter = busyTimesSpinnerAdapter
/* Setup busy times chart */
busyTimesChart = findViewById(R.id.busyTimesChart)
var description = Description()
description.text = ""
busyTimesChart.description = description
busyTimesChart.axisLeft.setDrawLabels(false)
busyTimesChart.axisRight.setDrawLabels(false)
busyTimesChart.axisLeft.setDrawGridLines(false)
busyTimesChart.axisRight.setDrawGridLines(false)
busyTimesChart.xAxis.setDrawGridLines(false)
busyTimesChart.legend.isEnabled = false
viewModel.busyData.observe(this, Observer { data: BarData ->
if (data.entryCount == 0) {
busyTimesChart.visibility = View.GONE
} else {
busyTimesChart.visibility = View.VISIBLE
}
busyTimesChart.data = data
busyTimesChart.invalidate()
})
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
viewModel.setBusyDay(position)
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/viewmodel/CreationViewModel.kt
package com.pinatlas.pinatlas.viewmodel
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.pinatlas.pinatlas.constants.TransportationMethods
import com.pinatlas.pinatlas.model.BusyData
import com.pinatlas.pinatlas.repository.TripsRepository
import com.pinatlas.pinatlas.model.Place
import com.pinatlas.pinatlas.model.Trip
import com.pinatlas.pinatlas.utils.BusyTimesUtil
import com.pinatlas.pinatlas.utils.DateUtils
import com.google.android.gms.tasks.Task
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.GeoPoint
import com.google.firebase.firestore.ListenerRegistration
/* Owner: AZ */
class CreationViewModel(tripId: String, userId: String) : ViewModel() {
val TAG = CreationViewModel::class.java.simpleName
private val tripsRepository = TripsRepository()
private val _trip = MutableLiveData<Trip>()
private val _places = MutableLiveData<List<Place>>()
private val tripId = tripId
private val userId = userId
lateinit var tripListener: ListenerRegistration
val tripPlaces : LiveData<List<Place>>
get() = _places
val trip: LiveData<Trip>
get() = _trip
val startDateStr: LiveData<String> = Transformations.map(_trip) {trip ->
if (trip != null) DateUtils.formatTimestamp(trip.startDate) else null
}
val endDateStr: LiveData<String> = Transformations.map(_trip) {trip ->
if (trip != null) DateUtils.formatTimestamp(trip.endDate) else null
}
val tripName: LiveData<String> = Transformations.map(_trip) {trip ->
trip?.name
}
val isBiking: LiveData<Boolean> = Transformations.map(_trip) {trip ->
trip?.transportationMethods?.contains(TransportationMethods.BICYCLING.type) ?: false
}
val isDriving: LiveData<Boolean> = Transformations.map(_trip) {trip ->
trip?.transportationMethods?.contains(TransportationMethods.DRIVING.type) ?: false
}
val isWalking: LiveData<Boolean> = Transformations.map(_trip) {trip ->
trip?.transportationMethods?.contains(TransportationMethods.WALKING.type) ?: false
}
val isBussing: LiveData<Boolean> = Transformations.map(_trip) {trip ->
trip?.transportationMethods?.contains(TransportationMethods.TRANSIT.type) ?: false
}
val latLng: MutableLiveData<GeoPoint> = MutableLiveData<GeoPoint>()
init {
registerListener()
}
fun registerListener() {
tripListener = tripsRepository.fetchTrip(tripId).addSnapshotListener { tripSnapshot, _ ->
val trip = Trip.fromFirestore(tripSnapshot!!)
trip?.userId = userId
_trip.postValue(trip)
if (trip != null && trip.places.size > 0) {
var lat = 0.0
var lgt = 0.0
trip.places.forEach { place ->
lat += place.coordinates!!.latitude / trip.places.size
lgt += place.coordinates!!.longitude / trip.places.size
latLng.postValue(GeoPoint(lat, lgt))
}
_places.postValue(trip.places)
} else {
_places.postValue(listOf())
}
}
}
// Posts a task to a main thread to set the given value.
fun updatePlacePriority(fromPos: Int, toPos: Int) {
val arrayOfPlaces = _places.value as ArrayList
arrayOfPlaces.add(toPos, arrayOfPlaces.removeAt(fromPos))
_trip.value!!.places = arrayOfPlaces
_trip.postValue(_trip.value)
_places.postValue(arrayOfPlaces)
}
fun setName(name: String) {
_trip.value?.name = name
_trip.postValue(_trip.value)
}
fun setStartDate(date: Timestamp) {
_trip.value?.startDate = date
_trip.postValue(_trip.value)
}
fun setEndDate(date: Timestamp) {
_trip.value?.endDate = date
_trip.postValue(_trip.value)
}
fun saveTrip(): Task<DocumentReference>? {
return tripsRepository.saveTrip(_trip.value)?.addOnFailureListener {
Log.e(TAG, "Failed to save trip")
}
}
fun deleteTrip(): Task<Void>? {
tripListener.remove()
return tripsRepository.deleteTrip(_trip.value)
}
fun addPlace(place: Place) {
_trip.value?.places?.add(place)
_trip.postValue(_trip.value)
saveTrip()
BusyTimesUtil.fetchBusyTimesData(place.placeId) { result: BusyData? ->
if (result != null) {
place.busyData = result
}
var index = _trip.value?.places?.indexOfLast { it.placeId == place.placeId }
_trip.value?.places?.set(index!!, place)
_trip.postValue(_trip.value)
saveTrip()
}
}
fun setTransportationMethods(methods: List<String>) {
_trip.value?.transportationMethods = methods as ArrayList<String>
_trip.postValue(_trip.value)
}
fun reorderPlaces(places: List<Place>) {
_trip.value?.places?.clear()
_trip.value?.places?.addAll(places)
_trip.postValue(_trip.value)
}
fun deletePlace(i: Int) {
_trip.value?.places?.removeAt(i)
_trip.postValue(_trip.value)
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/ActionItemView.kt
package com.pinatlas.pinatlas
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.pinatlas.pinatlas.databinding.ActionItemViewBinding
class ActionItemView(context: Context, attributeSet: AttributeSet): LinearLayout(context, attributeSet) {
private var textView: TextView
private var imageView: ImageView
init {
ActionItemViewBinding.inflate(LayoutInflater.from(context), this, true)
imageView = findViewById(R.id.actionBtnImage)
textView = findViewById(R.id.actionBtnTxt)
val attributes = context.obtainStyledAttributes(attributeSet, R.styleable.ActionItemView)
imageView.setImageDrawable(attributes.getDrawable(R.styleable.ActionItemView_actionImg))
textView.text = attributes.getText(R.styleable.ActionItemView_actionText)
attributes.recycle()
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/Trip.kt
package com.pinatlas.pinatlas.model
import com.pinatlas.pinatlas.constants.TransportationMethods
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentSnapshot
import java.util.*
import kotlin.collections.ArrayList
class Trip {
var userId: String = ""
var tripId: String? = "" // Auto-generated ID by Firestore
var name: String? = null // Name of the trip
var startDate: Timestamp = Timestamp(Date()) // Start date of the trip
var endDate: Timestamp = Timestamp(Date())
var placeRanking: ArrayList<String> = arrayListOf()
var places: ArrayList<Place> = ArrayList() // Array of places (not sorted in any way)
var transportationMethods: ArrayList<String> = arrayListOf()
override fun toString(): String {
return "User: $userId | Trip: $tripId | Name: $name | start_date: ${startDate.toString()} | end_date: ${endDate.toString()}"
}
constructor()
constructor(
userId: String,
tripId: String? = null,
name: String? = "",
startDate: Timestamp = Timestamp(Date()),
endDate: Timestamp = Timestamp(Date()),
placeRanking: ArrayList<String> = arrayListOf(),
places: ArrayList<Place> = arrayListOf(),
transportationMethods: ArrayList<String> = arrayListOf(TransportationMethods.TRANSIT.type)
) {
this.userId = userId
this.tripId = tripId
this.name = name
this.startDate = startDate
this.endDate = endDate
this.placeRanking = placeRanking
this.places = places //Places ID
this.transportationMethods = transportationMethods
}
// convert a firestore doc into an actual object
companion object {
fun fromFirestore(document: DocumentSnapshot): Trip? {
val trip = document.toObject(Trip::class.java)
trip?.tripId = document.id
return trip
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/Duration.kt
package com.pinatlas.pinatlas.model.matrix
class Duration {
var value: Long = 0
var text: String = ""
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/Row.kt
package com.pinatlas.pinatlas.model.matrix
class Row {
var elements: ArrayList<Element> = ArrayList()
constructor(elements: ArrayList<Element>) {
this.elements = elements
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/Place.kt
package com.pinatlas.pinatlas.model
import android.graphics.Bitmap
import com.google.firebase.Timestamp
import com.google.firebase.firestore.GeoPoint
import com.google.firebase.firestore.IgnoreExtraProperties;
import java.util.*
import kotlin.collections.ArrayList
@IgnoreExtraProperties
class Place {
var placeId: String = "" // Auto populate ID
// Properties of a place for firestore
var name: String? = null // Name of the location
var address: String? = null // Address of location
var phoneNumber: String? = null // Phone number as string
var rating: Double? = null // Google Maps rating
var types: ArrayList<String>? = null // Type (museum, hotel, etc...)
var openingHours: ArrayList<String>? = null // Google Maps array of hours of operation
var permanentlyClosed: Boolean? = null // True if location is permanently closed
var photos: ArrayList<String>? = null // URL of photos from google maps
var coordinates: GeoPoint? = null // Coordinates of location
var busyTimes: ArrayList<Timings>? = null // How busy a place is on a Day of the week
var waitTimes: ArrayList<Timings>? = null // How long are wait times in minutes
var avgSpentTimes: ArrayList<Int>? = null // Range of average time spent in minutes, between [0] to [1] minutes spent
var thumbnail: Bitmap? = null
var starttime: Timestamp = Timestamp(Date())
var traveltime: Long? = null
var busyData: BusyData? = null
var canvisit: Boolean = true
fun openingHoursString() : String {
var combined = ""
openingHours?.forEach { combined += "$it\n" }
return combined
}
// here because it needs to deserialize. If it doesn't find a constructor, it'll break
constructor()
constructor(
placeId: String,
name: String? = null,
address: String? = null,
phoneNumber: String? = null,
rating: Double? = null,
types: ArrayList<String>? = null,
openingHours: ArrayList<String>? = null,
permanentlyClosed: Boolean? = null,
photos: ArrayList<String>? = null,
coordinates: GeoPoint? = null,
busyTimes: ArrayList<Timings>? = null,
waitTimes: ArrayList<Timings>? = null,
avgSpentTimes: ArrayList<Int>? = null,
thumbnail: Bitmap? = null,
starttime: Timestamp = Timestamp(Date()),
traveltime: Long? = null,
busyData: BusyData? = null,
canvisit: Boolean = true
) {
this.placeId = placeId
this.name = name
this.address = address
this.phoneNumber = phoneNumber
this.rating = rating
this.types = types
this.openingHours = openingHours
this.permanentlyClosed = permanentlyClosed
this.photos = photos
this.coordinates = coordinates
this.busyTimes = busyTimes
this.waitTimes = waitTimes
this.avgSpentTimes = avgSpentTimes
this.thumbnail = thumbnail
this.starttime = starttime
this.traveltime = traveltime
this.busyData = busyData
this.canvisit = canvisit
}
class Timings {
var name: String? = null
var data: ArrayList<Int>? = arrayListOf() // an array of the data starting from hour 0 to hour 24
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/utils/PlaceThumbnailUtil.kt
package com.pinatlas.pinatlas.utils
import android.content.Context
import android.widget.ImageView
import com.pinatlas.pinatlas.BuildConfig
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FetchPhotoRequest
import com.google.android.libraries.places.api.net.FetchPlaceRequest
import com.google.android.libraries.places.api.net.PlacesClient
/* Owner: AZ */
object PlaceThumbnailUtil{
private lateinit var placesClient: PlacesClient
fun populateImageView(placeId: String, view: ImageView, context: Context) {
if (!Places.isInitialized()) {
Places.initialize(context, BuildConfig.PLACES_API_KEY)
placesClient = Places.createClient(context)
}
val placeRequest = FetchPlaceRequest.newInstance(placeId, listOf(Place.Field.PHOTO_METADATAS))
placesClient.fetchPlace(placeRequest).addOnSuccessListener {
if (it.place.photoMetadatas != null) {
// TODO: add photoMetadata to Trip.thumbnail to reduce amount of requests
val photoRequest = FetchPhotoRequest.newInstance(it.place.photoMetadatas!![0])
placesClient.fetchPhoto(photoRequest).addOnSuccessListener { photo ->
view.setImageBitmap(photo.bitmap)
}
}
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/ItemMoveCallback.kt
/*
Sources:
https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.Callback
*/
package com.pinatlas.pinatlas
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.pinatlas.pinatlas.adapter.PlaceListAdapter
/*
Allows us to control touch behaviors in the ViewHolder & receive callbacks when user performs these actions
*/
class ItemMoveCallback : ItemTouchHelper.Callback {
private var mAdapter: ItemTouchHelperContract
constructor(adapter: ItemTouchHelperContract) {
mAdapter = adapter
}
// allows long press
override fun isLongPressDragEnabled(): Boolean {
return true
}
// don't allow swipe
override fun isItemViewSwipeEnabled(): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
// we can control which actions user can take on each view by overriding this function
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
return makeMovementFlags(dragFlags, 0)
}
// need to override this method to allow any changes during dragging
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
mAdapter.onRowMoved(viewHolder.adapterPosition, target.adapterPosition)
return true
}
/*
onSelectedChanged gets called when a "row" in ViewHolder is dragged by the ItemTouchHelper is changed.
This calls "onRowSelected" (implemented by the user) & determines what happens after
Source: https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.Callback#onSelectedChanged(android.support.v7.widget.RecyclerView.ViewHolder,%20int)
*/
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder is PlaceListAdapter.ViewHolder) {
var myViewHolder: PlaceListAdapter.ViewHolder = viewHolder
mAdapter.onRowSelected(myViewHolder)
}
}
super.onSelectedChanged(viewHolder, actionState)
}
/*
clearView Called by the ItemTouchHelper when the user interaction with an element is over and it also completed its animation.
This calls "onRowClear" (implemented by the user) & determines what happens when the user completes their action
*/
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
if (viewHolder is PlaceListAdapter.ViewHolder) {
var myViewHolder: PlaceListAdapter.ViewHolder = viewHolder
mAdapter.onRowClear(myViewHolder)
}
}
interface ItemTouchHelperContract {
fun onRowMoved(fromPosition : Int, toPosition : Int)
fun onRowSelected(viewHolder : PlaceListAdapter.ViewHolder)
fun onRowClear(viewHolder : PlaceListAdapter.ViewHolder)
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/Element.kt
package com.pinatlas.pinatlas.model.matrix
class Element {
var status: String = ""
var duration: Duration? = null
var distance: Distance? = null
var priority: Int = 0
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/CreationView.kt
package com.pinatlas.pinatlas
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.icu.util.Calendar
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import android.os.Bundle
import android.view.View
import android.text.Editable
import android.text.TextWatcher
import com.google.android.libraries.places.api.Places as GPlaces
import com.google.android.libraries.places.widget.AutocompleteSupportFragment
import com.google.firebase.Timestamp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener
import android.util.Log
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.pinatlas.pinatlas.adapter.PlaceListAdapter
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.constants.TransportationMethods
import com.pinatlas.pinatlas.constants.ViewModes
import com.pinatlas.pinatlas.databinding.CreationViewBinding
import com.pinatlas.pinatlas.model.Place
import com.pinatlas.pinatlas.utils.DateUtils
import com.pinatlas.pinatlas.utils.MatrixifyUtil
import com.pinatlas.pinatlas.viewmodel.CreationViewModel
import com.pinatlas.pinatlas.viewmodel.CreationViewModelFactory
import com.google.android.gms.common.api.Status
import com.google.firebase.firestore.GeoPoint
import com.google.android.libraries.places.api.model.Place as GPlace
import com.takusemba.multisnaprecyclerview.MultiSnapRecyclerView
import org.jetbrains.anko.doAsync
class CreationView : AppCompatActivity() {
private val TAG = CreationView::class.java.simpleName
private val context: Context = this
private lateinit var viewModel: CreationViewModel
private lateinit var picker: DatePickerDialog
private lateinit var startDateButton : Button
private lateinit var endDateButton : Button
private lateinit var tripNameText: EditText
private lateinit var autocompleteFragment: AutocompleteSupportFragment
private lateinit var deleteButton: Button
private lateinit var loader: ConstraintLayout
private lateinit var tripId: String
private val currentUser: FirebaseUser? by lazy { FirebaseAuth.getInstance().currentUser }
private val PLACE_FIELDS = listOf(
GPlace.Field.ID,
GPlace.Field.NAME,
GPlace.Field.ADDRESS,
GPlace.Field.PHONE_NUMBER,
GPlace.Field.RATING,
GPlace.Field.TYPES,
GPlace.Field.OPENING_HOURS,
GPlace.Field.LAT_LNG,
GPlace.Field.PHOTO_METADATAS
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding : CreationViewBinding = DataBindingUtil.setContentView(this, R.layout.creation_view)
GPlaces.initialize(applicationContext, BuildConfig.PLACES_API_KEY)
tripId = intent.getStringExtra(Constants.TRIP_ID.type)!!
/* Owner: AZ */
val factory = CreationViewModelFactory(tripId, currentUser!!.uid)
viewModel = ViewModelProviders.of(this, factory).get(CreationViewModel::class.java)
// Bind to viewModel
binding.viewmodel = viewModel
binding.lifecycleOwner = this
startDateButton = findViewById(R.id.editStartDate)
endDateButton = findViewById(R.id.endDateButton)
tripNameText = findViewById(R.id.tripName)
tripNameText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(update: Editable?) {
viewModel.setName(update.toString())
viewModel.saveTrip()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
val adapter = PlaceListAdapter(viewModel, ViewModes.EDIT_MODE, this)
val placeList: MultiSnapRecyclerView = findViewById(R.id.placeList)
loader = findViewById(R.id.loader)
val manager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
val touchCallback = ItemMoveCallback(adapter)
val touchHelper = ItemTouchHelper(touchCallback)
touchHelper.attachToRecyclerView(placeList)
placeList.adapter = adapter
placeList.layoutManager = manager
autocompleteFragment = supportFragmentManager.findFragmentById(R.id.searchBar) as AutocompleteSupportFragment
autocompleteFragment.setPlaceFields(PLACE_FIELDS)
autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onError(status: Status) {
if (!status.isCanceled) {
val msg = "An error occurred: $status"
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
Log.e(TAG, msg)
}
}
override fun onPlaceSelected(gPlace: GPlace) {
if (gPlace.id != null) {
val place = Place(
placeId = gPlace.id!!,
openingHours = if (gPlace.openingHours != null)
gPlace.openingHours?.weekdayText as ArrayList<String>
else null,
name = gPlace.name!!,
address = gPlace.address!!,
phoneNumber = gPlace.phoneNumber,
rating = gPlace.rating,
coordinates = GeoPoint(gPlace.latLng!!.latitude,gPlace.latLng!!.longitude)
)
viewModel.addPlace(place)
}
}
})
// update view when tripPlaces changes
viewModel.tripPlaces.observe(this, Observer { update ->
if (update != null) {
adapter.notifyDataSetChanged()
}
})
deleteButton = findViewById(R.id.deleteButton)
deleteButton.setOnClickListener {
viewModel.deleteTrip()
// send to travel dash while clearing activity stack
intent = Intent(this, TravelDash::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(intent)
}
}
/* Owner: MV */
inner class OnCreateDateSetListener (private var datePicker: DatePicker)
: DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: android.widget.DatePicker, year: Int, month: Int, day: Int) {
val calendar = Calendar.getInstance()
calendar.set(year, month, day)
this.datePicker.templateMethod(Timestamp(calendar.time))
}
}
/*
date sets the date to the button connected to the calendar and does the updating in trip (stored in Firebase)
*/
inner class StartDatePicker : DatePicker() {
override var button: Button = startDateButton
override fun setDate(date: Timestamp) {
viewModel.setStartDate(date)
viewModel.saveTrip()
}
}
inner class EndDatePicker : DatePicker() {
override var button: Button = endDateButton
override fun setDate(date: Timestamp) {
viewModel.setEndDate(date)
viewModel.saveTrip()
}
}
abstract class DatePicker {
abstract var button: Button
abstract fun setDate(date: Timestamp)
fun setText(date: Timestamp) {
button.setText(DateUtils.formatTimestamp(date))
}
fun templateMethod(date: Timestamp) {
this.setDate(date)
this.setText(date)
}
}
// Switch createDatePicker to accept a button
private fun createDatePicker(datePickerParam: DatePicker) {
val c = Calendar.getInstance()
picker = DatePickerDialog(context, OnCreateDateSetListener(datePickerParam),
c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH))
picker.show()
}
// Change the components onClick to createStartDatePicker or EndDatePicker
fun createStartDatePicker(view : View) {
createDatePicker(StartDatePicker())
}
fun createEndDatePicker(view : View) {
createDatePicker(EndDatePicker())
}
/* End of Owner: MV */
fun deleteTrip(view: View) {
viewModel.deleteTrip()
finish()
}
fun buildTransportationPicker(view: View) {
val options: Array<String> = TransportationMethods.values().map { it.type }.toTypedArray()
val checked: BooleanArray = options.map { method -> viewModel.trip.value!!.transportationMethods.contains(method) }.toBooleanArray()
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.transpo_picker_msg)
builder.setMultiChoiceItems(options, checked) { _, which, isChecked ->
checked[which] = isChecked
}
builder.setPositiveButton("Submit", null)
builder.setNegativeButton("Cancel", null)
var dialog = builder.create()
dialog.setOnShowListener {
var submitButton: Button = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
submitButton.setOnClickListener { _ ->
if (!checked.contains(true)) {
Toast.makeText(context, "Please select at least one method.", Toast.LENGTH_LONG).show()
} else {
viewModel.setTransportationMethods(
checked.foldIndexed(arrayListOf()) { index: Int, acc: ArrayList<String>, b: Boolean ->
if (b) acc.add(options[index])
acc
})
viewModel.saveTrip()
dialog.dismiss()
} } }
dialog.show()
}
fun changeToItineraryView(view: View? = null) {
val intent = Intent(context, ItineraryView::class.java)
intent.putExtra(Constants.TRIP_ID.type, tripId)
startActivity(intent)
}
fun optimize(view: View) {
if (viewModel.tripPlaces.value!!.size > 2) {
loader.visibility = View.VISIBLE
doAsync {
MatrixifyUtil.optimizer(
viewModel.trip.value!!.places,
viewModel.trip.value!!.transportationMethods,
viewModel.trip.value!!.startDate,
viewModel.trip.value!!.endDate) { newOrderedPlaces: List<Place>? ->
if (newOrderedPlaces != null) {
viewModel.reorderPlaces(newOrderedPlaces)
viewModel.saveTrip()
}
changeToItineraryView()
}
}
} else {
Toast.makeText(context, "You must add more than 2 locations to provide an optimal route", Toast.LENGTH_LONG).show()
}
}
override fun onStop() {
super.onStop()
viewModel.tripListener.remove()
}
override fun onRestart() {
super.onRestart()
viewModel.registerListener()
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/GoogleLogin.kt
package com.pinatlas.pinatlas
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.IdpResponse
import com.google.firebase.auth.FirebaseAuth
class GoogleLogin : AppCompatActivity() {
private lateinit var context: Context
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_login)
if (FirebaseAuth.getInstance().currentUser != null) {
redirectToMainActivity()
}
context = this;
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK) {
val user = FirebaseAuth.getInstance().currentUser
Toast.makeText(context, "Signed in as '" + user!!.email + "'", Toast.LENGTH_LONG).show()
redirectToMainActivity()
} else {
Toast.makeText(context, "Failed to login, please try again.", Toast.LENGTH_LONG).show()
}
}
}
fun redirectToMainActivity() {
val intent = Intent(this, TravelDash::class.java)
startActivity(intent)
}
fun createSignInIntent(view: View) {
// List of authentication providers
val providers = arrayListOf(
AuthUI.IdpConfig.GoogleBuilder().build())
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN)
}
companion object {
private const val RC_SIGN_IN = 123
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/adapter/TripAdapter.kt
package com.pinatlas.pinatlas.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.recyclerview.widget.RecyclerView
import com.pinatlas.pinatlas.R
import com.pinatlas.pinatlas.TravelDash.Companion.context
import com.pinatlas.pinatlas.model.Trip
import com.pinatlas.pinatlas.utils.DateUtils
import com.pinatlas.pinatlas.utils.PlaceThumbnailUtil
/* Owner: AZ */
class TripAdapter (private val pastTrips: LiveData<List<Trip>>, context: Context,
onTripSelectedListener: OnTripSelectedListener): RecyclerView.Adapter<TripAdapter.ViewHolder>() {
// event listener for when a trip gets tapped
private var listener: OnTripSelectedListener = onTripSelectedListener
interface OnTripSelectedListener {
fun onTripSelected(trip: Trip)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(inflater.inflate(R.layout.traveldash_item, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(pastTrips.value!![position], listener)
}
override fun getItemCount(): Int = pastTrips.value?.size ?: 0
// Binds to the RecyclerView and converts the object into something useful
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val title: TextView = itemView.findViewById(R.id.location)
val date: TextView = itemView.findViewById(R.id.dates)
val thumbnail: ImageView = itemView.findViewById(R.id.locationThumbnail)
fun bind(trip: Trip, listener: OnTripSelectedListener) {
title.text = trip.name
date.text = DateUtils.formatTripDate(trip)
if (trip.places.size > 0) {
PlaceThumbnailUtil.populateImageView(trip.places[0]!!.placeId, thumbnail, context)
}
itemView.setOnClickListener(object: View.OnClickListener {
override fun onClick(view: View) {
listener.onTripSelected(trip)
}
})
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/ItineraryView.kt
package com.pinatlas.pinatlas
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.pinatlas.pinatlas.adapter.PlaceListAdapter
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.constants.ViewModes
import com.pinatlas.pinatlas.viewmodel.CreationViewModel
import com.pinatlas.pinatlas.viewmodel.CreationViewModelFactory
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.mapbox.android.core.permissions.PermissionsListener
import com.mapbox.android.core.permissions.PermissionsManager
import com.mapbox.geojson.Feature
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.LineString
import com.mapbox.geojson.Point
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
import com.mapbox.mapboxsdk.location.LocationComponentOptions
import com.mapbox.mapboxsdk.location.modes.CameraMode
import com.mapbox.mapboxsdk.location.modes.RenderMode
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.plugins.annotation.Fill
import com.mapbox.mapboxsdk.style.expressions.Expression.*
import com.mapbox.mapboxsdk.style.layers.LineLayer
import com.mapbox.mapboxsdk.style.layers.Property
import com.mapbox.mapboxsdk.style.layers.PropertyFactory.*
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import com.takusemba.multisnaprecyclerview.MultiSnapRecyclerView
class ItineraryView : AppCompatActivity() , OnMapReadyCallback, PermissionsListener{
private val context: Context = this
private lateinit var mapView : MapView
private lateinit var mapboxMap: MapboxMap
private lateinit var tripName: TextView
private lateinit var viewModel: CreationViewModel
private lateinit var tripId: String
private lateinit var adapter: PlaceListAdapter
private lateinit var fill : Fill
private var permissionsManager: PermissionsManager = PermissionsManager(this)
private val currentUser: FirebaseUser? by lazy { FirebaseAuth.getInstance().currentUser }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(applicationContext, getString(R.string.mapbox_access_token))
setContentView(R.layout.itinerary_view)
//For the Mapbox Implementation
mapView = findViewById(R.id.mapView)
mapView.onCreate(savedInstanceState)
mapView.getMapAsync(this)
tripId = intent.getStringExtra("TRIP_ID")!!
tripName = findViewById(R.id.tripName)
val factory = CreationViewModelFactory(tripId, currentUser!!.uid)
viewModel = ViewModelProviders.of(this, factory).get(CreationViewModel::class.java)
viewModel.tripName.observe(this, Observer {
tripName.text = it
})
//Local the tiles for past/upcoming trips
adapter = PlaceListAdapter(viewModel, ViewModes.ITINERARY_MODE, this)
val submitListView = findViewById<MultiSnapRecyclerView>(R.id.sublist_recycler_view)
val manager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
submitListView.layoutManager = manager
submitListView.adapter = adapter
viewModel.tripPlaces.observe(this, Observer { update ->
if (update != null) {
adapter.notifyDataSetChanged()
}
})
}
override fun onMapReady(mapboxMap: MapboxMap) {
this.mapboxMap = mapboxMap
var isInit = false
viewModel.tripPlaces.observe(this, Observer { placesList ->
if (placesList != null) {
val inLatLngs : ArrayList<Feature> = ArrayList<Feature>()
val markers : MutableList<Point> = ArrayList()
for (n in 0 until placesList.size) {
inLatLngs.add( Feature.fromGeometry(
Point.fromLngLat(placesList[n].coordinates!!.longitude, placesList[n].coordinates!!.latitude))
)
markers.add(Point.fromLngLat(placesList[n].coordinates!!.longitude, placesList[n].coordinates!!.latitude))
}
if (placesList.isNotEmpty()) {
viewModel.latLng.observe(this, Observer { coordinates ->
val lat = coordinates.latitude
val lng = coordinates.longitude
val zoom = when (isInit) {
true -> 20.0
else -> 11.0
}
this.mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(lat, lng), zoom))
isInit = true
})
}
mapboxMap.setStyle(Style.MAPBOX_STREETS){style ->
// Add the SymbolLayer icon im
// age to the map style
style.addImage(ICON_ID, BitmapFactory.decodeResource(
this.getResources(), R.drawable.pink_pin))
// Adding a GeoJson source for the SymbolLayer icons.
style.addSource(
GeoJsonSource(
SOURCE_ID,
FeatureCollection.fromFeatures(inLatLngs)
)
)
style.addLayer(
SymbolLayer(LAYER_ID, SOURCE_ID)
.withProperties(
iconImage(ICON_ID),
iconIgnorePlacement(true),
iconSize(1f),
iconAllowOverlap(true)
)
)
style.addSource(
GeoJsonSource(
"line-source",
FeatureCollection.fromFeatures(
arrayOf(
Feature.fromGeometry(
LineString.fromLngLats(markers!!)
)
)
)
)
)
style.addLayer( LineLayer("linelayer", "line-source").withProperties(
lineCap(Property.LINE_CAP_ROUND),
lineJoin(Property.LINE_JOIN_ROUND),
lineWidth(5f),
lineGradient(interpolate(
linear(), lineProgress(),
stop(0f, rgb(6, 1, 255)), // blue
stop(0.05f, rgb(59, 118, 227)), // royal blue
stop(0.1f, rgb(7, 238, 251)), // cyan
stop(0.25f, rgb(0, 255, 42)), // lime
stop(0.47f, rgb(255, 252, 0)), // yellow
stop(1f, rgb(255, 30, 0)) // red
))))
enableLocationComponent(style)
}
}
})
}
private fun enableLocationComponent(loadedMapStyle: Style) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create and customize the LocationComponent's options
val customLocationComponentOptions = LocationComponentOptions.builder(this)
.trackingGesturesManagement(true)
.accuracyColor(ContextCompat.getColor(this, R.color.mapbox_blue))
.build()
val locationComponentActivationOptions = LocationComponentActivationOptions.builder(this, loadedMapStyle)
.locationComponentOptions(customLocationComponentOptions)
.build()
// Get an instance of the LocationComponent and then adjust its settings
mapboxMap.locationComponent.apply {
// Activate the LocationComponent with options
activateLocationComponent(locationComponentActivationOptions)
// Enable to make the LocationComponent visible
isLocationComponentEnabled = true
// Set the LocationComponent's camera mode
cameraMode = CameraMode.NONE
// Set the LocationComponent's render mode
renderMode = RenderMode.COMPASS
}
} else {
permissionsManager = PermissionsManager(this)
permissionsManager.requestLocationPermissions(this)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
//Need this is to be removed
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show()
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
enableLocationComponent(mapboxMap.style!!)
} else {
//Need this is to be removed
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show()
finish()
}
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
fun onClickEditButton(view: View) {
val intent = Intent(this, CreationView::class.java)
intent.putExtra(Constants.TRIP_ID.type, tripId)
startActivity(intent)
}
companion object {
// Create names for the map's source, icon, and layer IDs.
private val SOURCE_ID = "SOURCE_ID"
private val ICON_ID = "ICON_ID"
private val LAYER_ID = "LAYER_ID"
}
fun changeToTravelBoard(view: View? = null) {
val intent = Intent(context, TravelDash::class.java)
intent.putExtra(Constants.TRIP_ID.type, tripId)
startActivity(intent)
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/matrix/DistanceMatrixModel.kt
package com.pinatlas.pinatlas.model.matrix
class DistanceMatrixModel {
var status: String = ""
// Note: underscore separated to match google
var origin_addresses: ArrayList<String>? = ArrayList()
var destination_addresses: ArrayList<String>? = ArrayList()
var rows: ArrayList<Row>? = ArrayList()
constructor(
status: String,
origin_addresses: ArrayList<String>?,
destination_addresses: ArrayList<String>?
) {
this.status = status
this.origin_addresses = origin_addresses
this.destination_addresses = destination_addresses
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/viewmodel/TripsViewModelFactory.kt
package com.pinatlas.pinatlas.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.IllegalArgumentException
/* Owner: AZ */
class TripsViewModelFactory (private val userId: String) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(TripsViewModel::class.java)) {
return TripsViewModel(userId) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/repository/PlacesRepository.kt
package com.pinatlas.pinatlas.repository
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.model.Place
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.*
/**
* Publish-Subscribe design pattern
* PlacesRepository acts both as a Publisher and Subscriber depending on it's usage
*/
/* Owner: JL */
class PlacesRepository {
// TAG helps us do a log as it typically asks us for the name of the class (to know your log came from)
val TAG = PlacesRepository::class.java.simpleName
var firestoreDB = FirebaseFirestore.getInstance()
/**
* Publish-Subscribe design pattern
* savePlace is a Publish Event
*/
fun savePlace(place: Place): Task<Void> {
return firestoreDB.collection(Constants.PLACES_COLLECTION.type).document(place.placeId).set(place)
}
/**
* Publish-Subscribe design pattern
* @return DocumentReference which a subscriber can be attached using addSnapshotListener
*/
fun fetchPlace(placeId: String): DocumentReference {
return firestoreDB.collection(Constants.PLACES_COLLECTION.type)
.document(placeId)
}
/**
* Warning!! This function does not guarantee the order of the ids
* Publish-Subscribe design pattern
* @return Query which can be subscribed to using addSnapshotListener
*/
fun fetchPlaces(placeIds: ArrayList<String>) : Query {
return firestoreDB.collection(Constants.PLACES_COLLECTION.type)
.whereIn("placeId", placeIds)
}
}<file_sep>/.github/ISSUE_TEMPLATE/issue-template.md
---
name: Issue Template
about: Describe this issue template's purpose here.
title: ''
labels: ''
assignees: ''
---
# Description
A more in depth description.
# Acceptance Criteria
- [ ] Criteria
- [ ] That has to be met
- [ ] Such as Sign in button must exist
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/utils/BusyTimesUtil.kt
package com.pinatlas.pinatlas.utils
import android.net.Uri
import android.util.Log
import com.pinatlas.pinatlas.model.BusyData
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.result.Result
import com.google.gson.Gson
import java.io.Reader
object BusyTimesUtil {
var TAG = BusyTimesUtil::class.java.simpleName
val BT_BASE_URL: String = "us-central1-comp3004-1578511896868.cloudfunctions.net"
fun buildBusyTimesURI(placeId: String): String {
return Uri.Builder()
.scheme("https")
.authority(BT_BASE_URL)
.appendPath("on_place_create")
.appendQueryParameter("placeId", placeId)
.build()
.toString()
}
fun fetchBusyTimesData(placeId: String, responseHandler: (result: BusyData?) -> Any?) {
buildBusyTimesURI(placeId).httpGet().responseObject(BusyTimesDeserializer()) {_, _, result ->
when (result) {
is Result.Failure -> {
Log.w(TAG, "Error when fetching busy times: ${result.getException()}")
responseHandler(null)
}
is Result.Success -> {
val (data, _) = result
responseHandler(data)
}
}
}
}
class BusyTimesDeserializer: ResponseDeserializable<BusyData> {
override fun deserialize(reader: Reader): BusyData? {
return Gson().fromJson(reader, BusyData::class.java)
}
}
}<file_sep>/app/src/main/java/com/pinatlas/pinatlas/repository/TripsRepository.kt
package com.pinatlas.pinatlas.repository
import com.pinatlas.pinatlas.constants.Constants
import com.pinatlas.pinatlas.model.Trip
import com.google.android.gms.tasks.Task
import com.google.firebase.firestore.*
/* Owner: JL */
class TripsRepository {
val TAG = TripsRepository::class.java.simpleName
var tripsCollection = FirebaseFirestore.getInstance().collection(Constants.TRIPS_COLLECTION.type)
fun saveTrip(trip: Trip?): Task<DocumentReference>? {
if (trip != null && trip.tripId == null) {
// create trip
return tripsCollection.add(trip)
} else if (trip != null){
// update trip
val tripDocument = fetchTrip(trip.tripId!!)
tripDocument.set(trip)
}
return null
}
fun deleteTrip(trip: Trip?): Task<Void>? {
return fetchTrip(trip!!.tripId!!).delete()
}
fun fetchTrip(tripId: String): DocumentReference {
return tripsCollection.document(tripId)
}
fun fetchTripsForUser(userId: String): Query {
return tripsCollection.whereEqualTo("userId", userId)
}
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
def apikeyPropertiesFile = rootProject.file("apikey.properties")
def apikeyProperties = new Properties()
apikeyProperties.load(new FileInputStream(apikeyPropertiesFile))
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.pinatlas.pinatlas"
minSdkVersion 26
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
buildConfigField("String", "PLACES_API_KEY", apikeyProperties['PLACES_API_KEY'])
buildConfigField("String", "DISTANCE_MATRIX_API_KEY", apikeyProperties['DISTANCE_MATRIX_API_KEY'])
}
dataBinding {
enabled = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
google()
jcenter()
maven { url 'https://jitpack.io' }
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.google.firebase:firebase-firestore:21.3.1'
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.libraries.places:places:2.1.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:8.6.2'
implementation 'com.android.support:recyclerview-v7:29.0.0'
implementation 'com.android.support:cardview-v7:29.0.0'
implementation 'com.github.takusemba:multisnaprecyclerview:2.0.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
implementation 'com.github.kittinunf.fuel:fuel:2.2.1'
implementation 'com.github.kittinunf.fuel:fuel-gson:2.2.1'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-annotation-v8:0.7.0'
implementation "org.jetbrains.anko:anko:0.10.4"
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
<file_sep>/cloudFunction/requirements.txt
git+https://github.com/m-wrzr/populartimes
google-cloud-firestore==1.6.0<file_sep>/app/src/main/java/com/pinatlas/pinatlas/viewmodel/TripsViewModel.kt
package com.pinatlas.pinatlas.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.pinatlas.pinatlas.model.Trip
import com.pinatlas.pinatlas.repository.TripsRepository
import com.google.android.gms.tasks.Task
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.ListenerRegistration
import java.util.*
/* Owner: AZ */
class TripsViewModel(userId: String) : ViewModel() {
val TAG = TripsViewModel::class.java.simpleName
private val tripsRepository = TripsRepository()
var tripsListener: ListenerRegistration
private val _trips = MutableLiveData<List<Trip>>()
private val _previousTrips = MutableLiveData<List<Trip>>()
private val _upcomingTrips = MutableLiveData<List<Trip>>()
init {
tripsListener = tripsRepository.fetchTripsForUser(userId).addSnapshotListener { value, _ ->
val trips = arrayListOf<Trip>()
val previous = arrayListOf<Trip>()
val upcoming = arrayListOf<Trip>()
for (t in value!!.iterator()) {
val trip = Trip.fromFirestore(t)!!
val now = Timestamp(Date())
trips.add(trip)
if (trip.endDate.seconds < now.seconds) {
previous.add(trip)
} else {
upcoming.add(trip)
}
}
_trips.postValue(trips)
_previousTrips.postValue(previous)
_upcomingTrips.postValue(upcoming)
}
}
fun addTrip(trip: Trip) : Task<DocumentReference>? {
return tripsRepository.saveTrip(trip)
}
val previousTrips : LiveData<List<Trip>>
get() = _previousTrips
val upcomingTrips : LiveData<List<Trip>>
get() = _upcomingTrips
}<file_sep>/cloudFunction/main.py
from google.cloud import firestore
import os
import populartimes
client = firestore.Client()
MAPSKEY = os.environ.get('mapskey', '')
# Inspired by https://cloud.google.com/functions/docs/calling/cloud-firestore#functions_firebase_firestore-python
def on_place_create(data, context):
path_parts = context.resource.split('/documents/')[1].split('/')
collection_path = path_parts[0]
document_path = '/'.join(path_parts[1:])
affected_doc = client.collection(collection_path).document(document_path)
place_id = data["value"]["fields"]["placeId"]["stringValue"]
print(f"Attempting to find popular times for {place_id}")
populartimes_data = populartimes.get_id(MAPSKEY, place_id) or {}
print(f"Received the following data {populartimes_data}")
affected_doc.update({
u'busyTimes': populartimes_data.get("populartimes"),
u'waitTimes': populartimes_data.get("time_wait"),
u'avgSpentTimes': populartimes_data.get("time_spent"),
})
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/utils/DateUtils.kt
package com.pinatlas.pinatlas.utils
import com.pinatlas.pinatlas.model.Place
import com.pinatlas.pinatlas.model.Trip
import com.google.firebase.Timestamp
import java.text.DateFormat
import java.text.SimpleDateFormat
/* Owner: JL */
object DateUtils {
val dateFormat: DateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT)
fun formatTimestamp(timestamp: Timestamp) : String {
return dateFormat.format(timestamp.seconds * 1000)
}
fun formatTripDate(trip: Trip) : String {
val startDate = formatTimestamp(trip.startDate)
val endDate = formatTimestamp(trip.endDate)
return "$startDate - $endDate"
}
fun formatPlaceTime(place: Place) : String {
val sfd = SimpleDateFormat("HH:mm:ss")
val start = sfd.parse(place.starttime.toDate().time.plus(5600).toString())
val end = start.time.plus(3600).toString()
return "${start} - $end"
}
}
<file_sep>/app/src/main/java/com/pinatlas/pinatlas/model/BusyData.kt
package com.pinatlas.pinatlas.model
class BusyData {
var busyTimes: ArrayList<Timings>? = null // How busy a place is on a Day of the week
var waitTimes: ArrayList<Timings>? = null // How long are wait times in minutes
var avgSpentTimes: ArrayList<Int>? = null // Range of average time spent in minutes, between [0] to [1] minutes spent
class Timings {
var name: String? = null
var data: ArrayList<Int>? = arrayListOf() // an array of the data starting from hour 0 to hour 24
}
}
|
fe82ee57ad58e2115aac90b4fa50894ef081f998
|
[
"Markdown",
"Gradle",
"Python",
"Text",
"Kotlin"
] | 38
|
Kotlin
|
jQwotos/PinAtlas
|
37be72afac95332d37449f9209e4514f6933fafa
|
dd120dd22c9c6bacf0d15790bc456493ae190d5d
|
refs/heads/master
|
<file_sep><!--Added newly second time-->
chromeMenu.prototype.createmenu = function() {
var menuDiv =document.createElement("div");
menuDiv.className="menus";
menuDiv.id="menus";
var menuItem=document.createElement("table");
menuItem.id="menuI";
menuItem.className="menuLevel1";
/*var tr1=document.createElement("tr");
tr1.id="menuRow";
var td1=document.createElement("td");
td1.className="menuItems";
tr1.appendChild(td1);
menuItem.appendChild(tr1);*/
menuDiv.appendChild(menuItem);
document.getElementById("menudiv").appendChild(menuDiv);
};
chromeMenu.prototype.addItem = function() {
var id=document.getElementById("menuI");
var tr1=document.createElement("tr");
tr1.id="menurow";
var td1=document.createElement("td");
td1.className="menuItems";
td1.id="menuItems";
var item=document.createTextNode("Item");
td1.appendChild(item);
tr1.appendChild(td1);
id.appendChild(tr1);
};
chromeMenu.prototype.submenu=function()
{
var id=document.getElementById("menurow");
var id2=document.createElement("td");
id2.className="id2";
var id1=document.createElement("table");
id1.className="subtab";
id1.id="subtab";
id2.appendChild(id1);
id.appendChild(id2);
}
chromeMenu.prototype.addSubmenu = function() {
var id1=document.getElementById("subtab");
var tr1=document.createElement("tr");
tr1.id="menurow2";
var td1=document.createElement("td");
td1.className="menuItems";
var item=document.createTextNode("SubItem");
td1.appendChild(item);
tr1.appendChild(td1);
id1.appendChild(tr1);
};
chromeMenu.prototype.deletemenu=function()
{
//var del=document.getElementById("menudiv");
var del1=document.getElementById("menus");
del1.parentNode.removeChild(del1);
};
|
a0177e2f68e770b289dba0f17915cf8898548fc7
|
[
"JavaScript"
] | 1
|
JavaScript
|
Latchumi/myrep
|
0eb945c71cc149471cb2f9bc6bd4ba65d27281fa
|
605998bf9e49599e1c13fb4303b49aa8ac66e4e3
|
refs/heads/master
|
<file_sep>import React from 'react';
import {View, Image, StyleSheet} from 'react-native';
const RoundedIcon = props => (
<View {...props} style={{...styles.main, ...props.mainStyle}}>
<Image
{...props}
source={{uri: props.uri, cache: 'force-cache'}}
style={{...styles.imgView, ...props.mainStyle}}
/>
</View>
);
const styles = StyleSheet.create({
main: {
height: 100,
width: 100,
elevation: 30,
shadowOpacity: 0.5,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 5, width: 0},
borderRadius: 50,
},
imgView: {
height: 98,
width: 98,
borderRadius: 50,
},
});
export default RoundedIcon;
<file_sep>const initState = {
likesMessage: [],
likesCount: [],
};
export const backgroundReducer = (state = initState, action) => {
switch (action.type) {
case 'LIKED':
// console.log('like count', action.payload);
return {
...state,
likesCount: action.payload.res.data.likes_count,
likesMessage: action.payload.message,
};
default:
return state;
}
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Card, Icon, Thumbnail} from 'native-base';
import {
Image,
TouchableHighlight,
TouchableOpacity,
ScrollView,
Text,
} from 'react-native';
import BottomLayout from './BottomLayout';
import LinearGradient from 'react-native-linear-gradient';
import EStyleSheet from 'react-native-extended-stylesheet';
import {AllStyles} from '../AllStyles';
import {useNavigation} from '@react-navigation/native';
const MediaComponent = props => {
var media = [];
props.detail.map(it => {
media.push(
<Card style={styles.cardView}>
<TouchableOpacity
onPress={() =>
props.onPress.navigate('mediaDetail', {
mediadata: it,
title: props.title,
})
}>
<View style={{flexDirection: 'column', padding: 0}}>
<Image
source={{
uri: it.image,
}}
style={{
height: 150,
width: '100%',
borderTopLeftRadius: 5,
borderTopRightRadius: 5,
}}
/>
<LinearGradient
colors={['transparent', '#011844']}
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
height: '100%',
}}
/>
<View
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
padding: 5,
flex: 1,
}}>
<Thumbnail
source={{
uri: it.logo,
}}
style={{
marginHorizontal: 10,
marginVertical: 5,
width: 50,
height: 50,
}}
/>
<Text style={styles.title} numberOfLines={2}>
{it.title}
</Text>
</View>
</View>
</TouchableOpacity>
<BottomLayout
onPress={() =>
props.onPress.navigate('mediaDetail', {
mediadata: it,
title: props.title,
})
}
likes_count={it.likes_count}
comments_count={it.comments_count}
shares_count={it.shares_count}
/>
</Card>,
);
});
return (
<TouchableOpacity>
<View style={{flexDirection: 'column'}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<View
style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
<Image
style={AllStyles.iconsize}
source={require('../../../assets/News/news-lg-yellow.png')}
/>
<Text style={AllStyles.HeaderCardText}>
What is media Saying ?{' '}
</Text>
</View>
<TouchableHighlight
style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}
onPress={props.viewAll}>
<View
style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
<Text
style={{
alignSelf: 'center',
marginHorizontal: 5,
fontSize: 12,
}}>
View All
</Text>
<Icon
style={{colors: 'gray', fontSize: 14, marginHorizontal: 3}}
name="ios-arrow-forward"
type="Ionicons"
/>
</View>
</TouchableHighlight>
</View>
<ScrollView horizontal>{media}</ScrollView>
</View>
</TouchableOpacity>
);
};
export default MediaComponent;
const styles = EStyleSheet.create({
row: {flexDirection: 'row'},
col: {flexDirection: 'column'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
title: {
color: 'white',
flex: 1,
marginTop: '5rem',
fontFamily: 'Lato-bold',
},
cardView: {
width: '300rem',
elevation: 5,
margin: 2,
marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
borderRadius: 5,
},
});
<file_sep>export const firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'naradmuni-df299.firebaseapp.com',
databaseURL: 'https://naradmuni-df299.firebaseio.com',
projectId: 'naradmuni-df299',
storageBucket: 'naradmuni-df299.appspot.com',
messagingSenderId: '576192159637',
appId: '1:576192159637:web:17502d79f6d98ac678609c',
measurementId: 'G-QWKLX096LC',
};
<file_sep>import axios from 'axios';
const baseUrl = 'http://narad.meroshows.com/api/';
<file_sep>/* eslint-disable no-alert */
import axios from 'axios';
const baseUrl = 'http://narad.meroshows.com/api/';
export const postGoogleLogin = (
auth_provider,
profile_id,
full_name,
profile_photo,
email,
) => dispatch => {
console.log('google log:::' + profile_id + ' ' + full_name);
axios
.post(baseUrl + 'auth/google', {
auth_provider: auth_provider,
profile_id: profile_id,
full_name: full_name,
profile_photo: profile_photo,
email: email,
})
.then(res => {
dispatch({
type: 'googleLogin',
payload: res.data,
});
})
.catch(err => alert('Problem ' + err));
};
export const postSignin = (value1, value2) => dispatch => {
dispatch({
type: 'Loading',
});
axios
.post('http://narad.meroshows.com/api/sign-in', {
email: value1,
password: <PASSWORD>,
})
.then(res => {
dispatch({
type: 'SignIn',
payload: res.data,
});
})
.catch(() =>
dispatch({
type: 'SignIn',
payload: [],
}),
);
};
export const postFacebookSignin = value1 => dispatch => {
dispatch({
type: 'Loading',
});
axios
.post('http://narad.meroshows.com/api/auth/facebook', {
access_token: value1,
})
.then(res => {
console.log('fbresponse', res);
dispatch({
type: 'FbLogin',
payload: res.data,
});
})
.catch(() =>
dispatch({
type: 'FbLogin',
payload: false,
}),
);
};
export const postTwitterSignin = (value1, value2) => dispatch => {
dispatch({
type: 'Loading',
});
console.log('twitter outh ' + value1 + ' screat ' + value2);
axios
.post(baseUrl + 'auth/twitter', {
oauth_token: value1,
oauth_token_secret: value2,
})
.then(res => {
console.log('twtterresponse', res);
dispatch({
type: 'FbLogin',
payload: res.data,
});
})
.catch(() =>
dispatch({
type: 'FbLogin',
payload: false,
}),
);
};
export const Logout = () => dispatch => {
dispatch({
type: 'Logout',
});
// axios
// .post(baseUrl + 'auth/twitter', {
// oauth_token: value1,
// oauth_token_secret: value2,
// })
// .then(res => {
// console.log('fbresponse', res);
// dispatch({
// type: 'FbLogin',
// payload: res.data.success,
// });
// })
// .catch(err =>
// dispatch({
// type: 'FbLogin',
// payload: false,
// }),
// );
};
export const clearSignUp = () => dispatch => {
dispatch({
type: 'clearSignup',
});
};
export const loadingClear = () => dispatch => {
dispatch({
type: 'clearLoading',
});
};
export const postSign = (name, email, password) => dispatch => {
dispatch({
type: 'Loading',
});
axios
.post(baseUrl + 'sign-up', {
full_name: name,
email: email,
password: <PASSWORD>,
})
.then(res => {
console.log('signupres', res);
dispatch({
type: 'signUp',
payload: res.data,
});
})
.catch(() =>
dispatch({
type: 'signUp',
payload: [],
}),
);
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, StyleSheet, Text} from 'react-native';
import {AllStyles} from '../AllStyles';
import FollowButtonComponent from './FollowButtonComponent';
import RoundedIcon from '../RoundedIcon';
const FollowViewComponent = props => {
return (
<View>
<View style={styles.fbView}>
<View style={styles.rowFlex}>
<RoundedIcon uri={props.profileImage} mainStyle={styles.iconRound} />
<View style={styles.textFollowView}>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<Text numberOfLines={2} ellipsizeMode="tail" style={{flex: 1}}>
<Text style={styles.boldText}>{props.userName}</Text>
<Text style={styles.normalText}> {props.description}</Text>
</Text>
</View>
<Text style={styles.smallText}>{props.time}</Text>
<View>
<FollowButtonComponent
iconName={props.iconName}
iconType={props.iconType}
buttonTitle={props.buttonTitle}
/>
</View>
</View>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
fbView: {
...AllStyles.activityFBCardView,
justifyContent: 'center',
},
rowFlex: {
flexDirection: 'row',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
},
iconRound: {
...AllStyles.actRoundedImage,
marginRight: 5,
},
textFollowView: {
marginRight: 5,
...AllStyles.textFollowView,
},
boldText: {
...AllStyles.actBoldText,
},
normalText: {
...AllStyles.actNormalText,
},
smallText: {
...AllStyles.actTimeText,
},
circleView: {
...AllStyles.circleView,
alignItems: 'center',
justifyContent: 'center',
},
});
export default FollowViewComponent;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Card, CardItem} from 'native-base';
import {ScrollView, Image, Text} from 'react-native';
import colors from '../../utils/colors';
import BottomLayout from './BottomLayout';
import EStyleSheet from 'react-native-extended-stylesheet';
import {AllStyles} from '../AllStyles';
import {backgroundLikeSend} from '../../actions/BackgroundAPI';
import {connect} from 'react-redux';
class BeforeAndAfterComponent extends React.Component {
constructor(props) {
super(props);
}
sendLike = (token, billId, type, modalId) => {
this.props.backgroundLikeSend(token, billId, type, modalId);
};
render() {
var view = [];
this.props.detail.map(it => {
view.push(
<Card style={styles.cardView}>
<CardItem>
<Text
style={[AllStyles.HeaderCardText, {alignSelf: 'flex-start'}]}
numberOfLines={1}>
Rural Toilet Access
</Text>
</CardItem>
<View
style={{
alignSelf: 'center',
flexDirection: 'column',
marginVertical: 0,
}}>
<View style={{flexDirection: 'row'}}>
<Text style={[styles.textbold]}>{it.stat_number_1}%</Text>
<Text style={styles.textbold}> - </Text>
<Text
style={[
styles.textbold,
{
color: colors.secondaryYellowColor,
},
]}>
{it.stat_number_2}%
</Text>
</View>
</View>
<View style={{alignSelf: 'center'}}>
<View style={{flexDirection: 'row'}}>
<Text style={{fontSize: 13, fontFamily: 'Lato-bold'}}>
{it.stat_text_1}
</Text>
<Text style={{fontSize: 13, fontFamily: 'Lato-bold'}}> & </Text>
<Text
style={{
fontSize: 13,
color: colors.secondaryYellowColor,
}}>
{it.stat_text_2}
</Text>
</View>
</View>
<BottomLayout
// onPress={index =>
// this.sendLike(
// this.props.token && this.props.token,
// this.props.id.bill_detail.bill_id &&
// this.props.id.bill_detail.bill_id,
// 'bill_info_cards',
// it.info_card_id,
// )
// }
onPress={() =>
this.props.onPress.navigate('commentDetailScreen', {
commentdata: it,
title: this.props.title,
icon: this.props.icon,
})
}
likes_count={this.props.like}
comments_count={it.comments_count}
shares_count={it.shares_count}
/>
</Card>,
);
});
return (
<View style={{flexDirection: 'column'}}>
<View style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
<Image
style={[AllStyles.iconrounded]}
source={require('../../../assets/chart/chart-lg-yellow.png')}
/>
<Text style={AllStyles.HeaderCardText}>
Before and After Analysis{' '}
</Text>
</View>
<ScrollView horizontal>{view}</ScrollView>
</View>
);
}
}
const mapStateToProps = state => {
return {
token: state.authReducer.token,
like: state.backgroundReducer.likesCount,
};
};
export default connect(mapStateToProps, {backgroundLikeSend})(
BeforeAndAfterComponent,
);
// export default BeforeAndAfterComponent;
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
cardView: {
width: '300rem',
elevation: 5,
margin: 2,
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
borderRadius: 5,
},
textbold: {fontSize: '40rem', fontFamily: 'Lato-black'},
});
<file_sep>import React from 'react';
import {Text, Icon} from 'native-base';
import {View, StyleSheet} from 'react-native';
import {AllStyles} from '../AllStyles';
import {TouchableHighlight} from 'react-native-gesture-handler';
const FollowButtonComponent = props => {
return (
<View>
<TouchableHighlight activeOpacity={0.8}>
<View style={styles.buttonBold}>
<Icon
name={props.iconName}
type={props.iconType}
style={styles.saveIcon}
/>
<Text style={styles.saveText}>{props.buttonTitle}</Text>
</View>
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
buttonBold: {
marginTop: 5,
...AllStyles.buttonFollowBold,
},
saveIcon: {
...AllStyles.saveIcon,
},
saveText: {
...AllStyles.saveText,
},
});
export default FollowButtonComponent;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Container, Content, Spinner} from 'native-base';
const Loading = () => (
<Container style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Content>
<Spinner />
</Content>
</Container>
);
export default Loading;
<file_sep>import {Dimensions, Platform} from 'react-native';
import colors from '../utils/colors';
import EStyleSheet from 'react-native-extended-stylesheet';
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
export const AllStyles = EStyleSheet.create({
// Activity View >> Follow Component Styles
activityFBCardView: {
backgroundColor: 'white',
height: '100rem',
elevation: 3,
marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
padding: '5rem',
borderRadius: 3,
},
activityNestedView: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
actRoundedImage: {
height: screenWidth * 0.2,
width: screenWidth * 0.2,
borderRadius: (screenWidth * 0.2) / 2,
},
userNameText: {
color: colors.primaryBlueColor,
fontSize: '14rem',
fontFamily: 'Lato-bold',
},
actBoldText: {
color: colors.fontBlueColor,
fontSize: '13rem',
fontFamily: 'Lato-bold',
},
actNormalText: {
color: colors.fontBlueColor,
fontSize: '13rem',
},
textFollowView: {
flex: 1,
},
actTimeText: {
color: 'grey',
fontSize: '11rem',
},
circleView: {
padding: 10,
height: '100%',
aspectRatio: 1,
},
buttonFollowBold: {
flexDirection: 'row',
borderRadius: 5,
backgroundColor: colors.secondaryYellowColor,
justifyContent: 'center',
alignItems: 'center',
height: '30rem',
},
saveIcon: {
fontSize: '15rem',
color: 'white',
},
saveText: {
padding: 5,
fontSize: '15rem',
color: 'white',
fontFamily: 'Lato-bold',
},
questionText: {
padding: 10,
fontSize: '15rem',
color: 'white',
fontFamily: 'Lato-bold',
},
//bill bold text
textbold: {
...Platform.select({
ios: {
fontFamily: 'Lato-bold',
},
android: {
fontFamily: 'Lato-bold',
},
}),
},
HeaderCardText: {
fontFamily: 'Lato-bold',
color: colors.textcolor,
fontSize: '13rem',
},
briefText: {color: '#8F8F8F', fontFamily: 'Lato-medium', fontSize: '11rem'},
iconsize: {width: '25rem', height: '20rem', marginRight: 10},
iconrounded: {width: '25rem', height: '25rem', marginRight: 10},
//Activity Opinion View Component
smallRoundedImage: {
height: screenWidth * 0.15,
width: screenWidth * 0.15,
borderRadius: (screenWidth * 0.15) / 2,
},
activityOpinionCardView: {
backgroundColor: 'white',
// height: "350rem",
marginBottom: '15rem',
elevation: 3,
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
borderRadius: 3,
},
rowDes: {
height: '65rem',
padding: '10rem',
},
headlineImgView: {
height: '180rem',
width: '100%',
borderRadius: 5,
},
title: {
color: 'white',
alignSelf: 'flex-start',
fontSize: '14rem',
fontFamily: 'Lato-bold',
justifyContent: 'center',
},
titleDesc: {
color: 'white',
fontSize: '12rem',
alignSelf: 'flex-start',
justifyContent: 'center',
fontFamily: 'lato-medium',
opacity: 0.8,
},
commentText: {
color: 'grey',
fontSize: '13rem',
fontFamily: 'lato-medium',
},
seeMoreText: {
color: colors.primaryBlueColor,
fontSize: '13rem',
fontFamily: 'lato-medium',
},
fontSmallGray: {
fontSize: '11rem',
color: 'gray',
},
fontMedGray: {
fontSize: '12rem',
color: 'gray',
fontFamily: 'Lato-bold',
},
billTitle: {
color: colors.fontBlueColor,
fontSize: '14rem',
fontFamily: 'Lato-bold',
},
dateText: {
color: 'gray',
fontSize: '13rem',
marginVertical: '5rem',
},
billDescText: {
color: colors.fontBlueColor,
fontSize: '13rem',
},
opiniionTextView: {
backgroundColor: 'white',
elevation: 3,
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
borderRadius: 3,
},
mediumFont: {
fontSize: '12rem',
fontFamily: 'Lato-bold',
color: 'gray',
margin: '5rem',
},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React, {Component} from 'react';
import {View, CardItem} from 'native-base';
import {Dimensions, TouchableOpacity, Image, Text} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
// import {TouchableOpacity} from 'react-native-gesture-handler';
export default class BottomLayout extends Component {
constructor(props) {
super(props);
// this.state = {
// it: this.props.navigation.state.params.it,
// };
}
// componentDidMount() {
// this.getbilllist();
// }
render() {
// console.log('data value', this.props.navigation.state.params.it);
return (
<View>
<CardItem style={[this.props.style, {justifyContent: 'space-between'}]}>
<Text style={styles.smallfont}>
{formatvalue(this.props.likes_count)} Likes
</Text>
<View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<Text style={styles.smallfont}>
{formatvalue(this.props.comments_count)} Comments{' '}
</Text>
<Text style={styles.smallfont}>
{formatvalue(this.props.shares_count)} Shares
</Text>
</View>
</CardItem>
<View
style={{
flex: 1,
flexDirection: 'row',
height: 1,
opacity: 0.4,
backgroundColor: 'lightgray',
marginHorizontal: 10,
}}
/>
<CardItem style={this.props.style}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 0,
flex: 1,
}}>
<TouchableOpacity>
<View style={styles.row}>
<Image
source={require('../../../assets/like.png')}
style={{color: 'lightgray', width: 17, height: 17}}
/>
<Text style={styles.mediumfont}>Like</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={this.props.onPress}
onPressIn={this.props.onPressLong}>
<View style={styles.row}>
<Image
source={require('../../../assets/comment.png')}
style={{color: 'lightgray', width: 17, height: 17}}
/>
<Text style={styles.mediumfont}>Comment</Text>
</View>
</TouchableOpacity>
<TouchableOpacity>
<View style={styles.row}>
<Image
source={require('../../../assets/share.png')}
style={{color: 'lightgray', width: 17, height: 17}}
/>
<Text style={styles.mediumfont}>Share</Text>
</View>
</TouchableOpacity>
</View>
</CardItem>
</View>
);
}
}
const formatvalue = n => {
if (n < 1e3) {
return n;
}
if (n >= 1e3 && n < 1e6) {
return +(n / 1e3).toFixed(1) + 'K';
}
if (n >= 1e6 && n < 1e9) {
return +(n / 1e6).toFixed(1) + 'M';
}
if (n >= 1e9 && n < 1e12) {
return +(n / 1e9).toFixed(1) + 'B';
}
if (n >= 1e12) {
return +(n / 1e12).toFixed(1) + 'T';
}
};
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: '9rem', color: 'gray'},
mediumfont: {
fontSize: '10rem',
fontFamily: 'Lato-bold',
color: 'gray',
margin: '5rem',
},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Text, Icon, Card, Content} from 'native-base';
import {Image, TextInput, Dimensions} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import {getBillCardComment} from '../../actions/BillsApi';
import {connect} from 'react-redux';
import {CommentComponent} from '../../components/MediaDetailComponent';
import {RoundedIcon} from '../../components';
import HeaderComponentwithBack from '../../components/HeaderComponentwithBack';
class MediaDetailView extends React.Component {
constructor(props) {
super(props);
this.state = {
mediadata: this.props.navigation.state.params.mediadata,
};
console.log('hssello data', this.props.navigation.state.params.title);
}
componentDidMount() {
this.getbilllcomment();
}
getbilllcomment() {
// this.props.getBillCardComment(
// this.props.token,
// this.state.id,
// this.state.info_card_id,
// );
}
static navigationOptions = ({navigation}) => {
console.log('hello data12', navigation.state.params.mediadata);
return {
header: (
<HeaderComponentwithBack
moveToNotif={navigation}
title={navigation.state.params.title}
image={navigation.state.params.mediadata.logo}
/>
),
};
};
render() {
return (
<Content>
<View>
<View>
<Image
source={{
uri: this.state.mediadata.image,
}}
style={{height: 200, width: '100%'}}
/>
<View
style={{flexDirection: 'row', alignItems: 'center', padding: 10}}>
<RoundedIcon
//uri={it.logo}
uri={this.state.mediadata.logo}
mainStyle={{width: 50, height: 50}}
/>
<Text style={{marginLeft: 10, flex: 1, fontFamily: 'Lato-bold'}}>
{this.state.mediadata.title}
</Text>
</View>
<View style={{flexDirection: 'column', paddingHorizontal: 10}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Image
source={require('../../../assets/timegray.png')}
style={{width: 15, height: 15}}
/>
<Text
note
style={{
fontSize: 12,
marginLeft: 5,
fontFamily: 'Lato-regular',
}}>
29 oct 2019 08:00 pm
</Text>
</View>
<Text note style={{marginTop: 10, fontFamily: 'Lato-regular'}}>
{this.state.mediadata.description}
</Text>
<View style={{marginVertical: 10}}>
<View
style={{
justifyContent: 'space-between',
flexDirection: 'row',
marginVertical: 10,
}}>
<Text style={styles.smallfont}>
{this.state.mediadata.likes_count} Likes
</Text>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-around',
}}>
<Text style={styles.smallfont}>
{this.state.mediadata.comments_count} Comments{' '}
</Text>
<Text style={styles.smallfont}>
{this.state.mediadata.shares_count} Shares
</Text>
</View>
</View>
<View
style={{
flex: 1,
flexDirection: 'row',
height: 1,
backgroundColor: 'lightgray',
}}
/>
<View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 5,
flex: 1,
}}>
<View style={styles.row}>
<Icon
name="like1"
type="AntDesign"
style={{color: 'lightgray', fontSize: 20}}
/>
<Text style={styles.mediumfont}>Like</Text>
</View>
<View style={styles.row}>
<Icon
name="comment"
type="Foundation"
style={{color: 'lightgray', fontSize: 20}}
/>
<Text style={styles.mediumfont}>Comment</Text>
</View>
<View style={styles.row}>
<Icon
name="share"
type="FontAwesome"
style={{color: 'lightgray', fontSize: 15}}
/>
<Text style={styles.mediumfont}>Share</Text>
</View>
</View>
</View>
</View>
</View>
<View style={{flexDirection: 'row'}}>
<Card style={{flex: 1, height: 40}}>
<TextInput
placeholder="Write your Comment here..."
multiline={true}
style={{
textAlignVertical: 'center',
marginTop: 5,
marginLeft: 5,
flex: 1,
}}
/>
</Card>
<Card style={{width: 80, height: 40}}>
<View
style={{
justifyContent: 'space-around',
flexDirection: 'row',
padding: 10,
}}>
<Image
source={require('../../../assets/done.png')}
style={{width: 10, height: 10, alignSelf: 'center'}}
/>
<Text>Add</Text>
</View>
</Card>
</View>
<CommentComponent
// onPress={() =>
// this.props.navigation.navigate('CommentDetailScreen')
// }
/>
</View>
</View>
</Content>
);
}
}
const mapStateToProps = state =>
console.log('initaial state ::', state) || {
token: state.authReducer.token,
data: state.BIllsReducer.comment,
};
export default connect(
mapStateToProps,
{getBillCardComment},
)(MediaDetailView);
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: '9rem', color: 'gray', fontFamily: 'Lato-regular'},
mediumfont: {
fontSize: '12rem',
fontFamily: 'Lato-regular',
color: 'gray',
margin: '5rem',
},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Icon, CardItem} from 'native-base';
import {StyleSheet, Text} from 'react-native';
import {AllStyles} from '../AllStyles';
import RoundedIcon from '../RoundedIcon';
import colors from '../../utils/colors';
const VoteViewComponent = props => {
return (
<View>
<View style={styles.fbView}>
<View style={styles.rowFlex}>
<RoundedIcon uri={props.profileImage} mainStyle={styles.iconRound} />
<View style={styles.textFollowView}>
<View
style={{flexDirection: 'row', flexWrap: 'wrap', marginBottom: 5}}>
<Text numberOfLines={1} ellipsizeMode="tail" style={{flex: 1}}>
<Text style={styles.normalText}> Your Friend </Text>
<Text style={styles.boldText}>{props.userName}</Text>
<Text style={styles.normalText}> {props.description}</Text>
</Text>
</View>
<Text style={styles.smallText}>{props.time}</Text>
</View>
</View>
<View>
<View
style={{
flexDirection: 'column',
padding: 0,
backgroundColor: colors.primaryBlueColor,
borderRadius: 3,
}}>
<Text style={styles.questionText}>{props.question}</Text>
<View style={styles.buttonBold}>
<Text style={styles.saveText}>{props.option}</Text>
</View>
<View>
<CardItem
style={{
justifyContent: 'space-between',
backgroundColor: 'transparent',
}}>
<Text style={styles.smallfont}>200k Likes</Text>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-around',
}}>
<Text style={styles.smallfont}>2.7k Comments </Text>
<Text style={styles.smallfont}>10 Shares</Text>
</View>
</CardItem>
<View
style={{
flex: 1,
flexDirection: 'row',
height: 1,
backgroundColor: 'lightgray',
marginHorizontal: 10,
}}
/>
<CardItem style={{backgroundColor: 'transparent'}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 5,
flex: 1,
}}>
<View style={styles.row}>
<Icon
name="like1"
type="AntDesign"
style={{color: 'lightgray', fontSize: 20}}
/>
<Text style={styles.mediumfont}>Like</Text>
</View>
<View style={styles.row}>
<Icon
name="comment"
type="Foundation"
style={{color: 'lightgray', fontSize: 20}}
/>
<Text style={styles.mediumfont}>Comment</Text>
</View>
<View style={styles.row}>
<Icon
name="share"
type="FontAwesome"
style={{color: 'lightgray', fontSize: 15}}
/>
<Text style={styles.mediumfont}>Share</Text>
</View>
</View>
</CardItem>
</View>
</View>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
fbView: {
...AllStyles.activityOpinionCardView,
justifyContent: 'center',
},
rowFlex: {
...AllStyles.rowDes,
flexDirection: 'row',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
},
iconRound: {
...AllStyles.smallRoundedImage,
marginRight: 5,
},
textFollowView: {
marginRight: 5,
...AllStyles.textFollowView,
},
boldText: {
...AllStyles.actBoldText,
},
normalText: {
...AllStyles.actNormalText,
},
smallText: {
...AllStyles.actTimeText,
},
circleView: {
...AllStyles.circleView,
alignItems: 'center',
justifyContent: 'center',
},
headlineImgView: {
...AllStyles.headlineImgView,
},
title: {
...AllStyles.title,
marginBottom: 5,
},
titleDesc: {
...AllStyles.titleDesc,
},
commentText: {
...AllStyles.commentText,
},
seeMoreText: {
...AllStyles.seeMoreText,
textDecorationLine: 'underline',
},
buttonBold: {
height: 50,
flexDirection: 'row',
borderRadius: 5,
margin: 10,
backgroundColor: colors.secondaryYellowColor,
justifyContent: 'center',
alignItems: 'center',
},
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {...AllStyles.fontSmallGray},
mediumfont: {...AllStyles.fontMedGray, margin: 5},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
saveText: {
...AllStyles.saveText,
},
questionText: {
...AllStyles.questionText,
},
});
export default VoteViewComponent;
<file_sep>import React from 'react';
import {
View,
FlatList,
List,
RefreshControl,
Alert,
ActivityIndicator,
} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';
import EStyleSheet from 'react-native-extended-stylesheet';
import BillItemCardVIew from '../../components/BillItemCardVIew/BillItemCardVIew';
import {getBillList} from '../../actions/BillsApi';
import {connect} from 'react-redux';
class BillScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
page: 1,
users: [],
isLoading: false,
isRefreshing: false,
id: this.props.navigation.state.params,
};
console.log('billscreeen data', this.props.screenProps.title);
}
componentDidMount() {
this.getlistofdata();
}
getlistofdata = () => {
var billtyple = 0;
switch (this.props.screenProps.title) {
case 'allbills':
billtyple = 1;
break;
case 'cashbill':
billtyple = 2;
break;
case 'opinionbill':
billtyple = 3;
break;
case 'amendment':
billtyple = 4;
break;
}
this.props.getBillList(
this.props.token,
this.state.page + '',
'' + billtyple,
);
};
handleRefresh = () => {
console.log('refresing inside');
this.setState(
{
page: 1,
isRefreshing: true,
},
() => {
this.getlistofdata();
},
);
};
handleLoadMore = () => {
this.setState(
{
page: this.state.page + 1,
},
() => {
this.getlistofdata();
},
);
};
render() {
console.log('bilscreendata', this.props.loading);
var listdata = this.getlistdata();
return (
<View style={layoutStyle.main}>
<FlatList
data={listdata}
renderItem={({item}) => (
<BillItemCardVIew
onPress={() =>
this.props.navigation.navigate('detail', {
billid: item.id,
title: item.title,
icon: item.mp_pic,
})
}
key={item.id}
data={item}
/>
)}
// onEndReached={this.handleLoadMore}
refreshing={this.props.loading}
onRefresh={this.handleRefresh}
keyExtractor={item => item.id}
/>
</View>
);
}
getlistdata = () => {
switch (this.props.screenProps.title) {
case 'allbills':
return this.props.billlist;
case 'cashbill':
return this.props.cashbill;
case 'opinionbill':
return this.props.opinionbill;
case 'amendment':
return this.props.amendment;
}
};
}
const mapStateToProps = state =>
console.log('initaial state ::', state) || {
token: state.authReducer.token,
data: state.BIllsReducer.data,
page: state.BIllsReducer.page,
cashbill: state.BIllsReducer.cashbill,
billlist: state.BIllsReducer.billlist,
amendment: state.BIllsReducer.amendment,
opinionbill: state.BIllsReducer.opinionbill,
loading: state.BIllsReducer.loading,
};
export default connect(
mapStateToProps,
{getBillList},
)(BillScreen);
const layoutStyle = EStyleSheet.create({
main: {
flex: 1,
paddingHorizontal: '5rem',
},
});
<file_sep>import React from 'react';
import {
View,
Image,
TextInput,
Dimensions,
TouchableOpacity,
} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
const PasswordInputText = props => {
return (
<View {...props} style={{...styles.main, ...props.style}}>
<Image
source={props.lpic}
resizeMode="stretch"
style={styles.textLayout}
/>
<TextInput
style={styles.text}
placeholder={props.placeholderText}
onChangeText={props.onChangeText}
secureTextEntry={props.secureTextEntry}
/>
<TouchableOpacity
onPressIn={props.onimgclick}
onPressOut={props.onimgclick}>
<Image
source={props.rpic}
style={styles.textLayout}
resizeMode="stretch"
/>
</TouchableOpacity>
</View>
);
};
const styles = EStyleSheet.create({
main: {
borderColor: 'white',
borderWidth: 1,
flexDirection: 'row',
height: 50,
width: '100%',
borderRadius: 5,
padding: '2rem',
paddingHorizontal: '10rem',
alignItems: 'center',
backgroundColor: 'white',
},
textLayout: {
width: '12rem',
height: '15rem',
},
text: {
width: '80%',
height: '100%',
fontSize: '10rem',
marginHorizontal: '4rem',
fontFamily: 'Lato-medium',
},
});
export default PasswordInputText;
<file_sep>import BottomTabComponent from './BottomTabComponent';
import Loading from './Loading';
import TextInputIcon from './TextInputIcon';
import ButtonIcon from './BottonIcon/ButtonIcon';
import ButtonSocial from './ButtonSocial';
import RoundedIcon from './RoundedIcon';
import TopTabComponent from './TopTabComponent';
import HeaderComponent from './HeaderComponent';
import NotificationComponent from './NotificationComponent';
import FollowerComponent from './FollowerComponent';
import TopTabProfileSettings from './TopTabProfileSettings';
import TitleWithImgComponent from './TitleWithImgComponent';
import ShadowViewComponent from './ShadowViewComponent';
import AllStyles from './AllStyles';
import HeaderWithBackBtn from './HeaderWithBackBtn';
import PasswordInputText from './PasswordInputText';
export {
BottomTabComponent,
Loading,
TextInputIcon,
ButtonIcon,
ButtonSocial,
RoundedIcon,
TopTabComponent,
HeaderComponent,
NotificationComponent,
FollowerComponent,
TopTabProfileSettings,
TitleWithImgComponent,
ShadowViewComponent,
AllStyles,
HeaderWithBackBtn,
PasswordInputText,
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
Header,
Left,
Body,
Right,
Button,
Icon,
Thumbnail,
View,
} from 'native-base';
import {Text} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import colors from '../utils/colors';
const HeaderComponentwithBack = props => (
<Header
style={{backgroundColor: colors.primaryBlueColor, borderBottomWidth: 0}}
androidStatusBarColor="#011844"
iosBarStyle="light-content">
<Left style={{width: 40, flex: 0.1}}>
<Button transparent onPress={() => props.moveToNotif.goBack()}>
<Icon
name="ios-arrow-back"
type="Ionicons"
style={{fontSize: 22, color: 'white'}}
/>
</Button>
</Left>
<Body
style={{flex: 1, justifyContent: 'flex-start', alignItems: 'flex-start'}}>
<View
style={{
flexDirection: 'row',
flex: 1,
marginRight: 5,
alignItems: 'center',
}}>
<Thumbnail
source={{
uri: props.image,
}}
style={styles.headerImgStyle}
/>
<Text
numberOfLines={1}
style={{color: 'white', fontFamily: 'Lato-bold', marginLeft: 5}}>
{props.title}
</Text>
</View>
</Body>
<Right style={{width: 40, flex: 0.2}}>
<Button transparent>
<Icon
name="heart"
type="AntDesign"
style={{fontSize: 22, color: 'white'}}
onPress={() => props.moveToNotif.navigate('NotificationStack')}
/>
</Button>
</Right>
</Header>
);
const styles = EStyleSheet.create({
headerImgStyle: {
width: 30,
height: 30,
borderRadius: 12,
},
});
export default HeaderComponentwithBack;
<file_sep>import BillScreen from "./BIllScreen";
export {BillScreen};<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Button, Text, Icon, View} from 'native-base';
import {Dimensions} from 'react-native';
import colors from '../utils/colors';
var screenWidth = Dimensions.get('window').width;
const TopTabProfileSettings = props => {
return (
<View style={{height: 50}}>
<View style={{flexDirection: 'row'}}>
{props.tabs.map(tab => {
if (props.navigation._childrenNavigation[tab.path].isFocused()) {
return (
<Button
activeOpacity={0.8}
style={{
width: screenWidth / 2,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 0,
backgroundColor: colors.selectedBlue,
}}
key={tab.label}>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<Icon
name={tab.icon}
type={tab.iconType}
style={{
color: colors.secondaryYellowColor,
fontSize: 18,
marginRight: 5,
}}
/>
<Text style={{fontSize: 13, color: '#FFF'}} numberOfLines={1}>
{tab.label}
</Text>
</View>
</Button>
);
} else {
return (
<Button
activeOpacity={0.8}
style={{
width: screenWidth / 2,
shadowRadius: 5,
justifyContent: 'center',
alignItems: 'center',
shadowOffset: {width: 0, height: 1},
shadowColor: '#ccc',
shadowOpacity: 0.6,
borderRadius: 0,
backgroundColor: 'white',
}}
key={tab.label}
active={props.navigation._childrenNavigation[
tab.path
].isFocused()}
onPress={() =>
props.navigation.navigate(tab.path, {itemId: 1})
}>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<Icon
name={tab.icon}
type={tab.iconType}
style={{
color: colors.secondaryYellowColor,
fontSize: 18,
marginRight: 5,
}}
/>
<Text
style={{fontSize: 13, color: colors.selectedBlue}}
numberOfLines={1}>
{tab.label}
</Text>
</View>
</Button>
);
}
})}
</View>
</View>
);
};
export default TopTabProfileSettings;
<file_sep>import BillBreifComponent from './BillBreifComponent';
import BillBreifItemComponent from './BillBreifItemComponent';
import BillTimelineComponent from './BillTimelineComponent';
import KeyStatConponent from './KeyStatComponent';
import OpinionComponent from './OpinionComponent';
import SalientComponent from './SalientComponent';
import BackgroundComponent from './BackgroundComponent';
import BeforeAndAfterComponent from './BeforeAndAfterComponent';
import MediaComponent from './MediaComponent';
import BillOpinion from './BillOpinion';
import VoteNowScreen from './VoteNowScreen';
import CitizenPoll from './CitizenPoll';
import BillCommentScreen from './BillCommentScreen';
export {
BillBreifComponent,
BillBreifItemComponent,
BillTimelineComponent,
KeyStatConponent,
OpinionComponent,
SalientComponent,
BackgroundComponent,
BeforeAndAfterComponent,
MediaComponent,
BillOpinion,
CitizenPoll,
VoteNowScreen,
BillCommentScreen,
};
<file_sep>import axios from 'axios';
// import {getBilldetail} from './BillsApi';
const baseUrl = 'http://narad.meroshows.com/api/';
export const backgroundLikeSend = (
token,
billId,
type,
modalId,
) => async dispatch => {
console.log('modalId', modalId);
await axios
.post(
`${baseUrl}bills/${modalId}/like`,
{
modal_type: type,
bill_id: billId,
},
{
headers: {
Authorization: token,
'Content-Type': 'application/json',
},
},
)
.then(res => {
// const mainData = getState().BIllsReducer.billdetail.data;
console.log('responae', res);
dispatch({
type: 'LIKED',
payload: {
type,
modalId,
res: res.data,
},
});
})
.catch(err => console.log('log' + err));
};
<file_sep>/* eslint-disable no-alert */
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
Container,
Icon,
Text,
View,
Content,
Input,
Textarea,
} from 'native-base';
import ImagePicker from 'react-native-image-picker';
import RoundedIcon from '../../components/RoundedIcon';
import {StyleSheet, TouchableOpacity, Image, Button} from 'react-native';
// import {TouchableOpacity} from 'react-native-gesture-handler';
import {TitleWithImgComponent} from '../../components';
import {ProfileStyles} from './ProfileStyles';
import colors from '../../utils/colors';
class MainInfoScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
filePath: {},
};
}
chooseFile = () => {
var options = {
title: 'Select Image',
customButtons: [
{name: 'customOptionKey', title: 'Choose Photo from Custom Option'},
],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
let source = response;
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
filePath: source,
});
}
});
};
render() {
const {navigation} = this.props;
const uri =
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg';
var imageUrl = JSON.stringify(navigation.getParam('profileImage', uri));
return (
<Container>
<Content>
<View style={{marginHorizontal: 16, marginBottom: 10}}>
<TitleWithImgComponent
source={require('../../../assets/user.png')}
activityName="Full Name"
/>
<View style={styles.shadowView}>
<Input placeholder="<NAME>" />
<Icon name="pencil" type="Octicons" style={styles.activityIcon} />
</View>
<TitleWithImgComponent
source={require('../../../assets/camera.png')}
activityName="Profile Photo"
/>
<View style={styles.shadowViewPhoto}>
<TouchableOpacity onPress={() => this.chooseFile()}>
<RoundedIcon
uri={JSON.parse(imageUrl)}
style={styles.profileRoundIcon}
/>
</TouchableOpacity>
<Text style={styles.activityIcon}>Upload your profile photo</Text>
</View>
<TitleWithImgComponent
source={require('../../../assets/feed.png')}
activityName="Profile Tagline"
/>
<View style={styles.shadowViewTextArea}>
<Textarea
style={styles.styleTextarea}
rowSpan={5}
placeholder="Write you Tagline"
/>
<Icon
name="pencil"
type="Octicons"
style={styles.activityIconTextArea}
/>
</View>
<TouchableOpacity activeOpacity={0.8}>
<View style={styles.buttonBold}>
<Icon name="check" type="FontAwesome" style={styles.saveIcon} />
<Text style={styles.saveText}>Save</Text>
</View>
</TouchableOpacity>
</View>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
titleText: {
...ProfileStyles.boldTitleText,
},
shadowView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
...ProfileStyles.shadowViewAnyHeight,
},
shadowViewPhoto: {
padding: 10,
justifyContent: 'center',
alignItems: 'center',
...ProfileStyles.shadowViewAnyHeight,
},
shadowViewTextArea: {
flexDirection: 'row',
justifyContent: 'space-between',
...ProfileStyles.shadowViewAnyHeight,
},
activityIcon: {
paddingRight: 10,
...ProfileStyles.greySmallIcon,
},
profileRoundIcon: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
...ProfileStyles.followerIcon,
},
activityIconTextArea: {
paddingTop: 5,
paddingRight: 10,
...ProfileStyles.greySmallIcon,
},
saveIcon: {
fontSize: 20,
color: 'white',
},
saveText: {
padding: 5,
fontSize: 20,
color: 'white',
fontWeight: '500',
},
buttonBold: {
height: 50,
flexDirection: 'row',
borderRadius: 5,
marginVertical: 20,
backgroundColor: colors.secondaryYellowColor,
justifyContent: 'center',
alignItems: 'center',
},
styleTextarea: {
width: '95%',
},
});
export default MainInfoScreen;
<file_sep>import React from 'react';
import {Image, View, StyleSheet} from 'react-native';
class SplashScreen extends React.Component {
componentDidMount() {
setTimeout(() => {
this.props.navigation.navigate('SignIn');
}, 2000);
}
render() {
return (
<View style={styles.parent}>
<Image
source={require('../../../assets/mainlogo.png')}
style={styles.imageview}
/>
</View>
);
}
}
const styles = StyleSheet.create({
parent: {
flex: 1,
backgroundColor: '#001142',
justifyContent: 'center',
alignItems: 'center',
},
imageview: {
width: '90%',
height: 80,
marginHorizontal: 10,
paddingHorizontal: 20,
resizeMode: 'center',
alignContent: 'center',
},
});
export default SplashScreen;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Thumbnail, Body, CardItem} from 'native-base';
import {StyleSheet, Image, Text} from 'react-native';
import {AllStyles} from '../AllStyles';
//import { LinearGradient } from 'expo-linear-gradient';
const BillRelatedComponent = props => {
if (props.buttonText === '') {
} else {
}
return (
<View>
<View style={styles.fbView}>
<View>
<View style={{flexDirection: 'column', padding: 0}}>
<Image
source={{
uri:
'https://www.hindustantimes.com/rf/image_size_960x540/HT/p2/2017/03/08/Pictures/sushma-najma-and-brinda-celebrate-bill-passage_9cc65a30-03a8-11e7-87c7-5947ba54d240.jpg',
}}
style={styles.headlineImgView}
/>
<View
colors={['transparent', '#011844']}
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
height: '100%',
}}>
<View
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
}}>
<Thumbnail
style={{margin: 10}}
source={{
uri:
'https://pickaface.net/gallery/avatar/parthisthebest5750125054898.png',
}}
/>
<Body style={{marginVertical: 5}}>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.title}>
J&K Reorganiszation Bill
</Text>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.titleDesc}>
The Bill, which will split J&K into two union
territories.The Bill, which will split J&K into two union
territories.
</Text>
</Body>
</View>
</View>
</View>
<View style={{marginHorizontal: 10}}>
<CardItem>
<View
style={{
justifyContent: 'space-between',
flex: 1,
paddingVertical: 10,
}}>
<Text style={styles.billTitle}>Amendment</Text>
<Text style={styles.dateText}>12 Dec 2019</Text>
<Text style={styles.billDescText}>
The Bill, which will split J&K into two union territories,
wast passed by upper house…
</Text>
</View>
</CardItem>
</View>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
fbView: {
...AllStyles.activityOpinionCardView,
justifyContent: 'center',
},
rowFlex: {
...AllStyles.rowDes,
flexDirection: 'row',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
},
iconRound: {
...AllStyles.smallRoundedImage,
marginRight: 5,
},
textFollowView: {
marginRight: 5,
...AllStyles.textFollowView,
},
headlineImgView: {
...AllStyles.headlineImgView,
},
title: {
...AllStyles.title,
marginBottom: 5,
},
titleDesc: {
...AllStyles.titleDesc,
},
commentText: {
...AllStyles.commentText,
},
seeMoreText: {
...AllStyles.seeMoreText,
textDecorationLine: 'underline',
},
billTitle: {
...AllStyles.billTitle,
},
dateText: {
...AllStyles.dateText,
},
billDescText: {
...AllStyles.billDescText,
},
});
export default BillRelatedComponent;
<file_sep>import Profile from './Profile';
import MainInfoScreen from './MainInfoScreen';
import SecurityInfoScreen from './SecurityInfoScreen';
import stylesA from './ProfileStyles';
import ProfileStyles from './ProfileStyles';
import FollowersList from './FollowersList';
export {
Profile,
MainInfoScreen,
SecurityInfoScreen,
stylesA,
ProfileStyles,
FollowersList,
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Image, TouchableOpacity, StyleSheet} from 'react-native';
import {CardItem, Text} from 'native-base';
import colors from '../../utils/colors';
import CountDowns from '../../utils/CountDowns';
import moment from 'moment';
const BottomVoteNow = props => (
<TouchableOpacity onPress={props.onPress}>
<View
style={{
elevation: 5,
borderTopWidth: 0.5,
shadowColor: 'gray',
borderColor: 'gray',
shadowRadius: 10,
shadowOpacity: 1,
}}>
<CardItem style={(styles.mains, props.style)}>
<View
style={{flexDirection: 'row', flex: 1, justifyContent: 'flex-start'}}>
<CountDowns
until={checkdates(props.detail)}
size={15}
digitStyle={{backgroundColor: colors.primaryBlueColor}}
digitTxtStyle={{color: '#ffffff'}}
/>
</View>
<View
style={{
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
}}>
<TouchableOpacity
style={{
flexDirection: 'row',
flex: 1,
justifyContent: 'center',
}}>
<View
style={{
flexDirection: 'row',
paddingVertical: 10,
paddingHorizontal: 20,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 3,
flexGrow: 1,
backgroundColor: colors.secondaryYellowColor,
}}>
<Image
style={{width: 15, height: 15, marginHorizontal: 5}}
source={require('../../../assets/checkmd.png')}
/>
<Text style={{color: 'white', fontFamily: 'Lato-bold'}}>
Vote Now
</Text>
</View>
</TouchableOpacity>
</View>
</CardItem>
</View>
</TouchableOpacity>
);
function checkdates(finalss) {
var mo = moment(finalss).diff(moment(), 'seconds');
return mo;
}
export default BottomVoteNow;
const styles = StyleSheet.create({
title: {
color: colors.white,
},
textLayout: {
width: 20,
height: 20,
},
mains: {alignItems: 'center', marginTop: 1, marginBottom: 1},
});
<file_sep>import axios from 'axios';
export const opinionSend = (
token,
billId,
opinion,
medaiUrl,
) => async dispatch => {
var formdata = new FormData();
formdata.append('opinion', opinion);
formdata.append('media_url', {
uri: medaiUrl.uri,
name: medaiUrl.fileName,
type: medaiUrl.type,
});
console.log('checking formdata', formdata);
const baseUrl = 'http://narad.meroshows.com/api/';
console.log('mediaurl ', medaiUrl);
await axios
.post(
`${baseUrl}bills/${billId}/opinion`,
formdata,
{
headers: {
Authorization: token,
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
},
)
.then(res => {
console.log('opiniondata', res);
dispatch({
type: 'OPINION',
payload: res.data,
});
})
.catch(err => console.log('log' + err));
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Image, View, StyleSheet, Text} from 'react-native';
import {
TextInputIcon,
ButtonIcon,
// ButtonSocial
} from '../../components';
class ForgotScreen extends React.Component {
render() {
return (
<View style={styles.parent}>
<View>
<Image
source={require('../../../assets/mainlogo.png')}
style={styles.imageview}
/>
</View>
<View style={styles.login}>
<TextInputIcon
style={{marginTop: 20, width: '100%', height: 50}}
placeholderText="Your Email"
lpic={require('../../../assets/email.png')}
rpic={require('../../../assets/editxs.png')}
/>
<ButtonIcon
text="Send Reset Code"
source={require('../../../assets/sendmd.png')}
color="white"
style={{
marginTop: 20,
width: '100%',
height: 50,
backgroundColor: 'orange',
}}
/>
<View style={styles.remmeberlayout}>
<Text
style={{
fontSize: 11,
color: 'gray',
fontFamily: 'Lato-regular',
opacity: 0.7,
}}>
IF YOU REMEMBER YOUR PASSWORD
</Text>
</View>
<ButtonIcon
text="Login"
source={require('../../../assets/loginyellow.png')}
style={{marginTop: 5, width: '100%', height: 50}}
onPress={() => this.props.navigation.navigate('SignIn')}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
parent: {
flex: 1,
backgroundColor: '#001142',
justifyContent: 'center',
alignItems: 'center',
},
login: {
justifyContent: 'center',
},
remmeberlayout: {
flexDirection: 'row',
marginTop: 30,
justifyContent: 'center',
height: 20,
},
});
export default ForgotScreen;
<file_sep>/* eslint-disable react-native/no-inline-styles */
/* eslint-disable no-sparse-arrays */
import React from 'react';
import {View, Card, CardItem, Button, TouchableOpacity} from 'native-base';
import {Image, Text} from 'react-native';
import RadioForm from 'react-native-simple-radio-button';
import colors from '../../utils/colors';
import {ScrollView, TouchableHighlight} from 'react-native-gesture-handler';
import EStyleSheet from 'react-native-extended-stylesheet';
import BottomLayout from './BottomLayout';
import {AllStyles} from '../AllStyles';
class CitizenPoll extends React.Component {
render() {
var radio_props = [
{label: 'For ..%', value: 0},
{label: 'Against--%', value: 1},
,
];
let view = [];
view.push(
<Card style={styles.cardview}>
<CardItem style={{backgroundColor: '#11111100'}}>
<View style={{flexDirection: 'row'}}>
<Text style={{fontSize: 20, fontWeight: 'bold', color: 'white'}}>
Citizen'S polls(5k-10k Voters)
</Text>
</View>
</CardItem>
<CardItem style={{backgroundColor: '#11111100'}}>
<View style={{flexDirection: 'column'}}>
<RadioForm
radio_props={radio_props}
initial={0}
formHorizontal={false}
buttonSize={10}
buttonColor={'#fff'}
selectedButtonColor={'#fff'}
labelColor={'#fff'}
selectedLabelColor={'#fff'}
onPress={() => {}}
/>
</View>
<View style={styles.imageIcon}>
<Image
source={require('../../../assets/lock.png')}
style={styles.iconSTyles}
/>
<View>
<Text style={{fontSize: 15, fontWeight: 'bold', color: 'white'}}>
VOTE TO UNLOCK RESULT
</Text>
</View>
</View>
</CardItem>
<View>
<BottomLayout style={styles.buttomstyling} />
</View>
</Card>,
);
return (
<View style={{flexDirection: 'column'}}>
<ScrollView horizontal>{view}</ScrollView>
</View>
);
}
}
export default CitizenPoll;
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
cardview: {
backgroundColor: colors.primaryBlueColor,
width: 350,
// zIndex: 2,
// height: '100%',
elevation: 5,
margin: 2,
// marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
borderRadius: 5,
},
buttomstyling: {
backgroundColor: colors.primaryBlueColor,
// height: 'auto',
},
imageIcon: {
display: 'flex',
position: 'absolute',
right: '5%',
// display: 'flex',
justifyContent: 'center',
height: '100%',
},
iconSTyles: {
display: 'flex',
alignSelf: 'center',
},
});
<file_sep>// Imports: Dependencies
import {combineReducers} from 'redux';
import authReducer from './authReducer';
import {backgroundReducer} from './backgroundReducer';
import apiReducer from './apiReducer';
import BIllsReducer from './BIllsReducer';
import signUpReducer from './signUpReducer';
// Imports: Reducers
// Redux: Root Reducer
const rootReducer = combineReducers({
authReducer: authReducer,
backgroundReducer,
apiReducer: apiReducer,
BIllsReducer: BIllsReducer,
signUpReducer: signUpReducer,
});
// Exports
export default rootReducer;
<file_sep>import {StyleSheet, Dimensions} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import colors from '../../utils/colors';
var screenHeight = Dimensions.get('window').height;
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
export const ProfileStyles = StyleSheet.create({
shadowView: {
backgroundColor: 'white',
width: '100%',
aspectRatio: 2.5,
elevation: 5,
marginBottom: 5,
borderBottomWidth: 0,
shadowOpacity: 0.5,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
},
column: {
width: screenWidth * 0.4,
justifyContent: 'center',
alignItems: 'center',
},
profileRoundImage: {
height: screenWidth * 0.33,
width: screenWidth * 0.33,
borderRadius: (screenWidth * 0.33) / 2,
},
row: {
height: screenHeight * 0.18,
flexDirection: 'column',
},
rowNested: {
alignItems: 'center',
},
boldTitleText: {
color: colors.fontBlueColor,
fontSize: 18,
fontFamily: 'Lato-bold',
},
boldNameText: {
color: colors.fontBlueColor,
fontSize: 15,
fontFamily: 'Lato-bold',
},
bioInfoText: {
color: 'grey',
fontSize: 13,
},
votesPostsText: {
color: colors.fontBlueColor,
fontSize: 13,
fontFamily: 'lato-medium',
},
profileSmallIcons: {
fontSize: 15,
color: 'orange',
},
rowSettings: {
alignSelf: 'flex-end',
},
profileSettingsView: {
elevation: 2,
marginBottom: -35 / 2,
borderBottomWidth: 0,
shadowOpacity: 0.5,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
height: 35,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: 150,
backgroundColor: 'white',
alignSelf: 'flex-end',
marginRight: 20,
borderRadius: 3,
},
profileSettingsTouchView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
settingsMediumIcon: {
fontSize: 20,
color: 'orange',
},
viewBelowSettingsBtn: {
marginHorizontal: 16,
},
viewFollowersFollowing: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 30,
},
flexRow: {
flexDirection: 'row',
},
greySmallIcon: {
fontSize: 15,
color: '#D3D3D3',
},
followersArrayView: {
flexDirection: 'row',
flex: 1,
marginTop: 10,
justifyContent: 'space-between',
},
singleFollowerView: {
justifyContent: 'center',
alignItems: 'center',
width: screenWidth * 0.2,
},
followerIcon: {
height: screenWidth * 0.2,
width: screenWidth * 0.2,
borderRadius: (screenWidth * 0.2) / 2,
},
followerText: {
marginTop: 5,
fontSize: 13,
fontFamily: 'Lato-bold',
},
actTitleView: {
flexDirection: 'row',
justifyContent: 'flex-start',
marginTop: 20,
marginBottom: 10,
alignItems: 'center',
},
activityCardView: {
backgroundColor: 'white',
height: 60,
elevation: 3,
marginBottom: 15,
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
padding: 10,
borderRadius: 3,
},
activityNestedView: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
actRoundedImage: {
height: screenWidth * 0.15,
width: screenWidth * 0.15,
borderRadius: (screenWidth * 0.15) / 2,
},
shadowViewAnyHeight: {
backgroundColor: 'white',
elevation: 3,
marginBottom: 5,
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
},
});
export const ProfileStyleExt = EStyleSheet.create({
userNameText: {
color: colors.textcolor,
fontSize: '14rem',
fontFamily: 'Lato-bold',
},
notifBoldText: {
color: colors.textcolor,
fontSize: '12rem',
fontFamily: 'Lato-bold',
},
notifDescription: {
color: colors.textcolor,
fontSize: '12rem',
flex: 1,
},
settingsText: {
color: colors.textcolor,
fontSize: '12rem',
fontFamily: 'Lato-bold',
},
bioText: {
color: 'grey',
fontSize: '12rem',
},
voteText: {
color: colors.textcolor,
fontSize: '12rem',
fontFamily: 'lato-medium',
},
rowView: {
height: '90rem',
flexDirection: 'column',
},
profileSettingsView: {
elevation: 2,
marginBottom: -35 / 2,
borderBottomWidth: 0,
shadowOpacity: 0.5,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
height: 35,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: '140rem',
backgroundColor: 'white',
alignSelf: 'flex-end',
marginRight: 20,
borderRadius: 3,
},
profileSmallIcons: {
fontSize: '15rem',
color: 'orange',
},
settingsMediumIcon: {
width: '20rem',
height: '20rem',
color: 'orange',
},
boldTitleText: {
color: colors.fontBlueColor,
fontSize: '15rem',
fontFamily: 'Lato-bold',
},
greySmallIcon: {
fontSize: '13rem',
color: 'grey',
},
followerText: {
flex: 1,
marginTop: 5,
fontSize: '12rem',
fontFamily: 'lato-medium',
alignSelf: 'center',
color: colors.fontBlueColor,
},
// NARADMUNI HEADER STYLE
nmHeaderImage: {
width: '200rem',
height: '30rem',
resizeMode: 'contain',
alignSelf: 'center',
},
notifCardView: {
backgroundColor: 'white',
height: '60rem',
elevation: 3,
marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
padding: '8rem',
borderRadius: 3,
},
actTextCardView: {
flexDirection: 'column',
marginLeft: 5,
flex: 1,
marginVertical: 2,
paddingVertical: '3rem',
},
actTimeText: {
color: 'grey',
fontSize: '11rem',
},
// Notification View Styles
notifTextCardView1: {
flexDirection: 'row',
alignItems: 'flex-start',
flex: 1,
},
followHeartIcon: {
fontSize: '15rem',
color: 'white',
},
followWhiteText: {
padding: 5,
fontSize: '15rem',
color: 'white',
fontFamily: 'Lato-bold',
},
followButtonTouchView: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
followBtnView: {
elevation: 2,
marginBottom: -35 / 2,
borderBottomWidth: 0,
shadowOpacity: 0.5,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
height: 35,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
width: '140rem',
backgroundColor: colors.secondaryYellowColor,
alignSelf: 'flex-end',
marginRight: 20,
borderRadius: 3,
},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Text} from 'native-base';
import {ScrollView} from 'react-native-gesture-handler';
import {TimeCardView} from '../../components/DetailScreenComponent';
import {
BillBreifComponent,
BillTimelineComponent,
OpinionComponent,
KeyStatConponent,
SalientComponent,
BackgroundComponent,
BeforeAndAfterComponent,
MediaComponent,
CitizenPoll,
BillOpinion,
VoteNowScreen,
} from '../../components/BiIlDetailComponent';
import {getBilldetail} from '../../actions/BillsApi';
import {connect} from 'react-redux';
import BottomVoteNow from '../../components/BiIlDetailComponent/BottomVoteNow';
import HeaderComponentwithBack from '../../components/HeaderComponentwithBack';
class DetailBillScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.navigation.state.params.billid,
data: this.props.data,
success: this.props.success,
ordered: [],
title: this.props.navigation.state.params.title,
icon: this.props.navigation.state.params.icon,
};
}
static navigationOptions = ({navigation}) => {
const appToolbarTitle =
navigation.state.params && navigation.state.params.title
? navigation.state.params.title
: '';
const icontitle =
navigation.state.params && navigation.state.params.icon
? navigation.state.params.icon
: '';
console.log('hello data', appToolbarTitle);
return {
header: (
<HeaderComponentwithBack
moveToNotif={navigation}
title={appToolbarTitle}
image={icontitle}
/>
),
};
};
componentDidMount() {
this.getbilllist();
}
getbilllist() {
this.props.getBilldetail(this.props.token, this.state.id);
}
getview(name) {
if (name === 'bill_detail') {
return <BillBreifComponent detail={this.props.data.data.bill_detail} />;
} else if (name === 'bill_opinions') {
return (
<BillOpinion
onPressIn={this.props.navigation}
title={this.state.title}
icon={this.state.icon}
onPress={() => this.props.navigation.navigate('Write')}
detail={this.props.data.data.bill_opinions}
/>
);
} else if (name === 'bill_timelines') {
return (
<BillTimelineComponent
onPress={() =>
this.props.navigation.navigate('timeline', {
timeline: this.props.data.data.bill_timelines,
title: this.state.title,
icon: this.state.icon,
})
}
detail={this.props.data.data.bill_timelines}
data={this.appToolbarTitle}
/>
);
} else if (name === 'bill_info_text_cards') {
return (
<OpinionComponent
onPress={this.props.navigation}
title={this.state.title}
icon={this.state.icon}
detail={this.props.data.data.bill_info_cards.bill_info_text_cards}
id={this.props.data.data}
/>
);
} else if (name === 'bill_info_stat_cards') {
return (
<KeyStatConponent
onPress={this.props.navigation}
title={this.state.title}
icon={this.state.icon}
style={{marginTop: 20}}
detail={this.props.data.data.bill_info_cards.bill_info_stat_cards}
id={this.props.data.data}
/>
);
} else if (name === 'bill_info_salient_cards') {
return (
<SalientComponent
onPress={this.props.navigation}
title={this.state.title}
icon={this.state.icon}
style={{marginTop: 20}}
detail={
this.props.data.data.bill_info_cards.bill_info_salient_points_cards
}
id={this.props.data.data}
/>
);
} else if (name === 'bill_info_background_basics_cards') {
return (
<BackgroundComponent
onPress={this.props.navigation}
title={this.state.title}
icon={this.state.icon}
style={{marginTop: 20}}
detail={
this.props.data.data.bill_info_cards
.bill_info_background_basics_cards
}
id={this.props.data.data}
/>
);
} else if (name === 'bill_info_news_cards') {
return (
<MediaComponent
onPress={this.props.navigation}
icon={this.state.icon}
title={this.state.title}
viewAll={() => this.props.navigation.navigate('ViewAll')}
detail={this.props.data.data.bill_info_cards.bill_info_news_cards}
/>
);
} else if (name === 'bill_info_before_after_analysis_cards') {
return (
<BeforeAndAfterComponent
style={{marginTop: 20}}
onPress={this.props.navigation}
icon={this.state.icon}
title={this.state.title}
detail={
this.props.data.data.bill_info_cards
.bill_info_before_after_analysis_cards
}
id={this.props.data.data}
/>
);
} else if (name === 'bill_citizen_polls') {
return (
<CitizenPoll
onPress={() => this.props.navigation.navigate('Votenow')}
/>
);
}
return <Text>{name}</Text>;
}
render() {
let orderlist = [];
let bottomview = <BottomVoteNow />;
if (this.props.success) {
if (this.props.data != null) {
console.log('data', this.props.data);
this.props.data.data.order.map(or => {
orderlist = [...orderlist, this.getview(or.name)];
});
bottomview = (
<BottomVoteNow detail={this.props.data.data.citizen_poll_deadline} />
);
}
}
return (
<View
style={{
flexDirection: 'column',
justifyContent: 'space-between',
flex: 1,
}}>
<View
style={{
flex: 1,
}}>
<ScrollView>
<View style={{flex: 1}}>
<TimeCardView
data={this.props.data}
onPress={() => this.props.navigation.navigate('Write')}
/>
<View style={{flexDirection: 'column', margin: 10}}>
{orderlist}
<View />
</View>
</View>
</ScrollView>
{bottomview}
</View>
</View>
);
}
}
const mapStateToProps = state =>
console.log('initaial state ::', state) || {
token: state.authReducer.token,
data: state.BIllsReducer.billdetail,
success: state.BIllsReducer.success,
newState: state.BIllsReducer.billdetail,
};
export default connect(mapStateToProps, {getBilldetail})(DetailBillScreen);
<file_sep>/* eslint-disable no-alert */
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {
Image,
View,
StyleSheet,
Text,
KeyboardAvoidingView,
Platform,
} from 'react-native';
import {connect} from 'react-redux';
import {
TextInputIcon,
ButtonIcon,
ButtonSocial,
PasswordInputText,
} from '../../components';
import {postSign, clearSignUp} from '../../actions/LoginScreenApi';
import {NativeModules} from 'react-native';
import {
postFacebookSignin,
postGoogleLogin,
postTwitterSignin,
loadingClear,
} from '../../actions/LoginScreenApi';
import {GoogleSignin, statusCodes} from 'react-native-google-signin';
import {LoginManager, AccessToken} from 'react-native-fbsdk';
import Spinner from 'react-native-loading-spinner-overlay';
import colors from '../../utils/colors';
//const {RNTwitterSignIn} = NativeModules;
const Constants = {
TWITTER_COMSUMER_KEY: '6CD7uIAP8uZC9oaLSEKea2Cdp',
TWITTER_CONSUMER_SECRET: '<KEY>',
};
class SignUpScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
password: '',
repassword: '',
showpassword: true,
reshowpassword: true,
};
}
handleLogout = () => {
console.log('logout');
// RNTwitterSignIn.logOut();
};
_twitterSignIn = () => {
// RNTwitterSignIn.init(
// Constants.TWITTER_COMSUMER_KEY,
// Constants.TWITTER_CONSUMER_SECRET,
// );
// RNTwitterSignIn.logIn()
// .then(loginData => {
// console.log(loginData);
// const {authToken, authTokenSecret} = loginData;
// if (authToken && authTokenSecret) {
// console.log('twitter', authToken);
// console.log('twitter', authTokenSecret);
// this.logintwitter(authToken, authTokenSecret);
// }
// })
// .catch(error => {
// console.log(error);
// });
};
componentDidMount() {
GoogleSignin.configure({
webClientId:
'576192159637-v35ep4jubg9ltib4pp0b7u045hvj52bi.apps.googleusercontent.com',
offlineAccess: true,
forceConsentPrompt: true,
});
this.props.logined && this.props.navigation.navigate('Home');
}
async _signIn() {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
const isSignedIn = await GoogleSignin.getTokens();
console.log('tokens', JSON.stringify(isSignedIn));
this.logingoogle(userInfo);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (f.e. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
}
async signOut() {
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
} catch (error) {
console.error(error);
}
}
handleFacebookLogin() {
LoginManager.logInWithPermissions(['public_profile']).then(result => {
if (result.isCancelled) {
} else {
AccessToken.getCurrentAccessToken().then(data => {
console.log('response :', data);
this.loginfacebook(data.accessToken);
});
}
});
}
loginfacebook = accestoken => {
this.props.postFacebookSignin(accestoken);
};
logintwitter = (accestoken, saccesstoken) => {
this.props.postTwitterSignin(accestoken, saccesstoken);
};
logingoogle = userInfo => {
this.props.postGoogleLogin(
'google',
userInfo.id,
userInfo.user.name,
userInfo.user.photo,
userInfo.user.email,
);
};
login() {
if (this.validate(this.state.email)) {
this.props.postSignin(this.state.email, this.state.password);
}
}
show() {
this.setState({showpassword: !this.state.showpassword});
}
resshow() {
this.setState({reshowpassword: !this.state.reshowpassword});
}
check() {
console.log('check' + this.props.signUp);
this.props.loadingClear();
if (this.props.signUp) {
this.props.clearSignUp();
this.props.navigation.navigate('Home');
} else if (this.props.logined) {
this.props.clearSignUp();
this.props.navigation.navigate('Home');
}
}
render() {
this.check();
return (
<KeyboardAvoidingView
style={{flex: 1}}
behavior={Platform.OS === 'ios' ? 'height' : null}
keyboardVerticalOffset={Platform.OS === 'ios' ? 20 : 0}
enabled>
<View style={styles.parent}>
<Spinner
visible={this.props.loading}
textContent={'Loading...'}
textStyle={{color: '#FFF'}}
/>
<View>
<Image
source={require('../../../assets/mainlogo.png')}
style={styles.imageview}
/>
</View>
<View style={styles.login}>
<TextInputIcon
onChangeText={value => this.setState({name: value.trim()})}
style={{marginTop: 20}}
secureTextEntry={false}
placeholderText="Your <NAME>"
lpic={require('../../../assets/usergray.png')}
rpic={require('../../../assets/editxs.png')}
/>
<TextInputIcon
onChangeText={value => this.setState({email: value.trim()})}
style={{marginTop: 10}}
placeholderText="Your email"
lpic={require('../../../assets/email.png')}
rpic={require('../../../assets/editxs.png')}
/>
<PasswordInputText
onChangeText={value => this.setState({password: value.trim()})}
style={{marginTop: 10}}
secureTextEntry={this.state.showpassword}
placeholderText="Your password"
lpic={require('../../../assets/passwordgray.png')}
rpic={require('../../../assets/eye.png')}
onimgclick={() => this.show()}
/>
<PasswordInputText
onChangeText={value => this.setState({repassword: value.trim()})}
style={{marginTop: 10}}
secureTextEntry={this.state.reshowpassword}
placeholderText="Re-type password"
lpic={require('../../../assets/passwordgray.png')}
rpic={require('../../../assets/eye.png')}
onimgclick={() => this.resshow()}
/>
<ButtonIcon
text="SignUp"
color={'white'}
source={require('../../../assets/loginmd.png')}
style={{
marginTop: 20,
width: '100%',
height: 50,
backgroundColor: 'orange',
}}
onPress={() => this.signUp()}
/>
<Text
style={{
color: 'white',
fontFamily: 'Lato-medium',
alignSelf: 'center',
fontSize: 11,
opacity: 0.5,
marginTop: 30,
marginBottom: 10,
textTransform: 'uppercase',
}}>
DO HAVE AN ACCOUNT?
</Text>
<ButtonIcon
text="Login"
source={require('../../../assets/login.png')}
style={{width: '100%', height: 50}}
onPress={() => this.props.navigation.navigate('SignIn')}
/>
<View style={{alignItems: 'center', marginTop: 20}}>
<Text
style={{
color: 'white',
fontSize: 15,
fontFamily: 'Lato-bold',
}}>
OR LOGIN WITH SOCIAL MEDIA
</Text>
<Text
style={{
color: 'white',
fontSize: 11,
marginBottom: 30,
fontFamily: 'Lato-medium',
opacity: 0.7,
}}>
WE DON'T HAVE ANY ACCESS TO YOUR ACCOUNTS
</Text>
</View>
<View style={styles.sociallayout}>
<ButtonSocial
onPress={() => this.handleFacebookLogin()}
text="Signup"
color={colors.primaryBlueColor}
source={require('../../../assets/fb.png')}
style={{marginHorizontal: 10, height: 40}}
/>
<ButtonSocial
onPress={() => this._twitterSignIn()}
text="Signup"
source={require('../../../assets/twitter.png')}
style={{marginHorizontal: 10, height: 40}}
/>
<ButtonSocial
text="Signup"
onPress={() => this._signIn()}
source={require('../../../assets/google.png')}
style={{marginHorizontal: 10, height: 40}}
/>
</View>
</View>
</View>
</KeyboardAvoidingView>
);
}
validate = text => {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false) {
alert('Email is Not Correct');
this.setState({email: text});
return false;
} else {
return true;
}
};
signUp = () => {
if (this.validate(this.state.email)) {
if (this.state.password === this.state.repassword) {
this.props.postSign(
this.state.name,
this.state.email,
this.state.password,
);
} else {
alert('Password are not same');
}
}
};
}
const styles = StyleSheet.create({
parent: {
flex: 1,
backgroundColor: '#001142',
justifyContent: 'center',
alignItems: 'center',
},
login: {
justifyContent: 'center',
},
remmeberlayout: {
flexDirection: 'row',
justifyContent: 'center',
marginVertical: 20,
height: 20,
},
sociallayout: {
flexDirection: 'row',
justifyContent: 'space-around',
height: 50,
},
});
const mapStateToProps = state =>
console.log('signupLog:::', state) || {
signUp: state.authReducer.signUp,
data: state.authReducer.data,
logined: state.authReducer.loggedIn,
loading: state.authReducer.loading,
};
export default connect(
mapStateToProps,
{
postSign,
postGoogleLogin,
postFacebookSignin,
postTwitterSignin,
clearSignUp,
loadingClear,
},
)(SignUpScreen);
<file_sep>import {Dimensions} from 'react-native';
import colors from '../../utils/colors';
import EStyleSheet from 'react-native-extended-stylesheet';
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
export const ActivityStyles = EStyleSheet.create({
activityFBCardView: {
backgroundColor: 'white',
height: '100rem',
elevation: 3,
marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 3,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 0},
padding: '5rem',
borderRadius: 3,
},
activityNestedView: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
},
actRoundedImage: {
height: screenWidth * 0.2,
width: screenWidth * 0.2,
borderRadius: (screenWidth * 0.2) / 2,
},
userNameText: {
color: colors.primaryBlueColor,
fontSize: '14rem',
fontWeight: '500',
},
actBoldText: {
color: colors.primaryBlueColor,
fontSize: '13rem',
fontWeight: '500',
},
actNormalText: {
color: colors.primaryBlueColor,
fontSize: '13rem',
},
textFollowView: {
flex: 1,
},
actTimeText: {
color: 'grey',
fontSize: '11rem',
},
circleView: {
padding: 10,
height: '100%',
aspectRatio: 1,
},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
/* eslint-disable no-alert */
import React from 'react';
import {Image, View, StyleSheet, Text} from 'react-native';
import {Button} from 'native-base';
import {GoogleSignin, statusCodes} from 'react-native-google-signin';
import {
TextInputIcon,
ButtonIcon,
ButtonSocial,
PasswordInputText,
} from '../../components';
import {LoginManager, AccessToken} from 'react-native-fbsdk';
import {NativeModules} from 'react-native';
import {
postSignin,
postFacebookSignin,
postGoogleLogin,
postTwitterSignin,
loadingClear,
} from '../../actions/LoginScreenApi';
import {connect} from 'react-redux';
import Spinner from 'react-native-loading-spinner-overlay';
import colors from '../../utils/colors';
//const {RNTwitterSignIn} = NativeModules;
//import {firebaseConfig} from '../../config/firebaseConfig';
const Constants = {
TWITTER_COMSUMER_KEY: '<KEY>uZC9oaLSEKea2Cdp',
TWITTER_CONSUMER_SECRET: '<KEY>',
};
//firebase.initializeApp(firebaseConfig);
class LoginScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
showpassword: true,
};
this.props.loadingClear();
}
validate = text => {
let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(text) === false) {
alert('Email is Not Correct');
this.setState({email: text});
return false;
} else {
return true;
}
};
handleLogout = () => {
console.log('logout');
// RNTwitterSignIn.logOut();
};
_twitterSignIn = () => {
// RNTwitterSignIn.init(
// Constants.TWITTER_COMSUMER_KEY,
// Constants.TWITTER_CONSUMER_SECRET,
// );
// RNTwitterSignIn.logIn()
// .then(loginData => {
// console.log(loginData);
// const {authToken, authTokenSecret} = loginData;
// if (authToken && authTokenSecret) {
// console.log('twitter', authToken);
// console.log('twitter', authTokenSecret);
// this.logintwitter(authToken, authTokenSecret);
// }
// })
// .catch(error => {
// console.log(error);
// });
};
componentDidMount() {
GoogleSignin.configure({
webClientId:
'576192159637-v35ep4jubg9ltib4pp0b7u045hvj52bi.apps.googleusercontent.com',
offlineAccess: true,
forceConsentPrompt: true,
});
this.props.logined && this.props.navigation.navigate('Home');
}
async _signIn() {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
const isSignedIn = await GoogleSignin.getTokens();
console.log('tokens', JSON.stringify(isSignedIn));
this.logingoogle(userInfo);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
// user cancelled the login flow
} else if (error.code === statusCodes.IN_PROGRESS) {
// operation (f.e. sign in) is in progress already
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
} else {
// some other error happened
}
}
}
async signOut() {
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
} catch (error) {
console.error(error);
}
}
handleFacebookLogin() {
LoginManager.logInWithPermissions(['public_profile']).then(result => {
if (result.isCancelled) {
alert('cancel');
} else {
AccessToken.getCurrentAccessToken().then(data => {
console.log('response :', data);
this.loginfacebook(data.accessToken);
});
}
});
}
loginfacebook = accestoken => {
this.props.postFacebookSignin(accestoken);
};
logintwitter = (accestoken, saccesstoken) => {
this.props.postTwitterSignin(accestoken, saccesstoken);
};
logingoogle = userInfo => {
console.log('google' + userInfo.user.id);
this.props.postGoogleLogin(
'google',
userInfo.user.id,
userInfo.user.name,
userInfo.user.photo,
userInfo.user.email,
);
};
login() {
this.props.postSignin(this.state.email, this.state.password);
}
show() {
this.setState({showpassword: !this.state.showpassword});
}
render() {
console.log('loading ::', this.props.authLoading);
this.props.logined && this.props.navigation.navigate('Home');
return (
<View style={styles.parent}>
<Spinner
visible={this.props.authLoading}
textContent={'Loading...'}
textStyle={{color: '#FFF'}}
/>
<View>
<Image
source={require('../../../assets/mainlogo.png')}
style={styles.imageview}
/>
</View>
<View style={styles.login}>
<TextInputIcon
style={{marginTop: 20}}
placeholderText="Your email"
secureTextEntry={false}
onChangeText={value => this.setState({email: value.trim()})}
lpic={require('../../../assets/email.png')}
rpic={require('../../../assets/editxs.png')}
/>
<PasswordInputText
onChangeText={value => this.setState({password: value.trim()})}
style={{marginTop: 10, marginBottom: 30}}
placeholderText="Your password"
secureTextEntry={this.state.showpassword}
lpic={require('../../../assets/passwordgray.png')}
rpic={require('../../../assets/eye.png')}
onimgclick={() => this.show()}
/>
<ButtonIcon
text="Login"
color={'#fff'}
source={require('../../../assets/loginmd.png')}
style={{width: '100%', height: 50, backgroundColor: 'orange'}}
onPress={() => this.login()}
// onPress={() => this.props.navigation.navigate('Home')}
/>
<View style={styles.remmeberlayout}>
<Button transparent>
<Image
source={require('../../../assets/uncheck/uncheck.png')}
style={{width: 15, height: 15, marginRight: 10}}
/>
<Text
style={{
color: 'white',
fontSize: 12,
fontFamily: 'Lato-regular',
opacity: 0.8,
}}>
Remember Me
</Text>
</Button>
<Button
transparent
onPress={() => this.props.navigation.navigate('ForgotPassword')}>
<Text
style={{
color: 'white',
fontSize: 12,
fontFamily: 'Lato-regular',
opacity: 0.8,
}}>
Forgot Password?
</Text>
</Button>
{/* <Button onPress={() => this.props.navigation.navigate("ForgotPassword")} color='white' title="Forgot Password?" /> */}
</View>
<Text
style={{
color: 'white',
fontSize: 12,
alignSelf: 'center',
fontFamily: 'Lato-regular',
opacity: 0.5,
textTransform: 'uppercase',
}}>
Don’t have an account?
</Text>
<ButtonIcon
text="Signup"
color={colors.primaryBlueColor}
source={require('../../../assets/login.png')}
style={{width: '100%', height: 50, marginTop: 10}}
onPress={() => this.props.navigation.navigate('CreateAccount')}
/>
<View style={{alignItems: 'center', marginTop: 20}}>
<Text
style={{
color: 'white',
fontSize: 15,
fontFamily: 'Lato-bold',
}}>
OR LOGIN WITH SOCIAL MEDIA
</Text>
<Text
style={{
color: 'white',
fontSize: 11,
marginBottom: 20,
fontFamily: 'Lato-regular',
opacity: 0.5,
}}>
WE DON'T HAVE ANY ACCESS TO YOUR ACCOUNTS
</Text>
</View>
<View style={styles.sociallayout}>
<ButtonSocial
onPress={() => this.handleFacebookLogin()}
text="Signup"
color={colors.primaryBlueColor}
source={require('../../../assets/fb.png')}
style={{marginHorizontal: 10, height: 40}}
/>
<ButtonSocial
onPress={() => this._twitterSignIn()}
text="Signup"
source={require('../../../assets/twitter.png')}
style={{marginHorizontal: 10, height: 40}}
/>
<ButtonSocial
text="Signup"
onPress={() => this._signIn()}
source={require('../../../assets/google.png')}
style={{marginHorizontal: 10, height: 40}}
/>
{/* <LoginButton
publishPermissions={['public_profile email']}
onLoginFinished={(error, result) => {
if (error) {
alert('Login failed with error: ' + error.message);
} else if (result.isCancelled) {
alert('Login was cancelled');
} else {
alert(
'Login was successful with permissions: ' +
result.grantedPermissions,
);
}
}}
onLogoutFinished={() => alert('User logged out')}
/> */}
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
parent: {
flex: 1,
backgroundColor: '#001142',
justifyContent: 'center',
alignItems: 'center',
},
login: {
justifyContent: 'center',
},
remmeberlayout: {
flexDirection: 'row',
justifyContent: 'space-between',
height: 30,
marginBottom: 50,
},
sociallayout: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
const mapStateToProps = state =>
console.log('initaial state ::', state) || {
authLoading: state.authReducer.loading,
logined: state.authReducer.loggedIn,
};
export default connect(
mapStateToProps,
{
postSignin,
postFacebookSignin,
loadingClear,
postTwitterSignin,
postGoogleLogin,
},
)(LoginScreen);
<file_sep>import React from 'react';
import {FontAwesome} from '@expo/vector-icons';
import {createAppContainer, createSwitchNavigator} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import {
createBottomTabNavigator,
createMaterialTopTabNavigator,
} from 'react-navigation-tabs';
import {TestScreen} from '../screens';
import {
BottomTabComponent,
TopTabComponent,
HeaderComponent,
TopTabProfileSettings,
HeaderWithBackBtn,
} from '../components';
import {BillScreen} from '../screens/BIllScreen';
import {
ForgotScreen,
LoginScreen,
ResendPassword,
SignUpScreen,
} from '../screens/AuthScreens';
import {SplashScreen} from '../screens/SplashScreen';
import {
Profile,
MainInfoScreen,
SecurityInfoScreen,
FollowersList,
} from '../screens/ProfileScreens';
import {Activity} from '../screens/ActivityScreens';
import {Notification} from '../screens/NotficationScreens';
import VoteNowScreen from '../components/BiIlDetailComponent/VoteNowScreen';
import BillCommentScreen from '../components/BiIlDetailComponent/BillCommentScreen';
import {CitizenScore} from '../screens/CitizenScore';
import {DetailBillScreen} from '../screens/DetailBillScreen';
import {Toptabs, ProfSettingsTabs} from '../utils/constants';
import {BillTimelineScreen} from '../screens/BillTimelineScreen';
import MediaDetailView from '../screens/MediaDetailView/MediaDetailView';
import HeaderComponentwithBack from '../components/HeaderComponentwithBack';
import ViewAllScreen from '../screens/ViewAllScreen/ViewAllScreen';
import {WriteOpinionScreen} from '../screens/WriteOpinionScreen';
//Landing page when page got start
const splashStack = createStackNavigator({
Landing: {
screen: SplashScreen,
navigationOptions: {
header: null,
},
},
});
//Required screen while authentication with default sighin page
const AuthStack = createSwitchNavigator(
{
SignIn: {
screen: LoginScreen,
navigationOptions: {
header: null,
},
},
CreateAccount: {
screen: SignUpScreen,
navigationOptions: {
header: null,
},
},
ForgotPassword: {
screen: ForgotScreen,
navigationOptions: {
header: null,
},
},
ResetPassword: {
screen: ResendPassword,
navigationOptions: {
header: null,
},
},
},
{
initialRoute: 'SignIn',
},
);
//Required Screeen when user clicked Activity Feed
const ActivityStack = createStackNavigator(
{
ActivityT: {
screen: Activity,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponent moveToNotif={navigation} />};
},
},
},
{
headerMode: 'float',
},
);
//Required Sreen when user clicked Citizen click citizen Score
const CitizenScoreStack = createStackNavigator(
{
CitizenScore: {
screen: CitizenScore,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponent moveToNotif={navigation} />};
},
},
},
{
headerMode: 'float',
},
);
//Sreen stack for notification which is at the top of the topbar notification
const NotificationStack = createStackNavigator(
{
screen: Notification,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponentwithBack moveToNotif={navigation} />};
},
},
{
headerMode: 'float',
},
);
// for Profile Settings Tab
const ProfileSettingTabs = createMaterialTopTabNavigator(
{
main: {
screen: MainInfoScreen,
},
security: {
screen: SecurityInfoScreen,
},
},
{
initialRouteName: 'main',
// eslint-disable-next-line no-undef
transitionConfig: () => fadeout(),
swipeEnabled: false,
tabBarComponent: props => {
return <TopTabProfileSettings {...props} tabs={ProfSettingsTabs} />;
},
},
);
//under implementation
const FollowersActivityStack = createStackNavigator(
{
ProfileScreen: {
screen: Profile,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponent moveToNotif={navigation} />};
},
},
ProfSetting: {
screen: ProfileSettingTabs,
navigationOptions: ({navigation}) => {
return {header: <HeaderWithBackBtn moveToNotif={navigation} />};
},
},
FollowerScreen: {
screen: FollowersList,
navigationOptions: ({navigation}) => {
return {header: <HeaderWithBackBtn moveToNotif={navigation} />};
},
},
},
{
initialRouteName: 'ProfileScreen',
headerMode: 'float',
},
);
//for bill top bar navigation
const TopTabs = createMaterialTopTabNavigator(
{
allbills: {
screen: props => (
<BillScreen {...props} screenProps={{title: 'allbills'}} />
),
},
cashbill: {
screen: props => (
<BillScreen {...props} screenProps={{title: 'cashbill'}} />
),
},
opinionbill: {
screen: props => (
<BillScreen {...props} screenProps={{title: 'opinionbill'}} />
),
},
amendment: {
screen: props => (
<BillScreen {...props} screenProps={{title: 'amendment'}} />
),
},
},
{
initialRouteName: 'allbills',
swipeEnabled: false,
tabBarComponent: props => {
return <TopTabComponent {...props} tabs={Toptabs} />;
},
},
);
//nagivation for bill screen
const BillNavigation = createStackNavigator(
{
topbar: {
screen: TopTabs,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponent moveToNotif={navigation} />};
},
},
detail: {
screen: DetailBillScreen,
},
timeline: {
screen: BillTimelineScreen,
},
commentDetailScreen: {
screen: BillCommentScreen,
},
mediaDetail: {
screen: MediaDetailView,
},
ViewAll: {
screen: ViewAllScreen,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponentwithBack moveToNotif={navigation} />};
},
},
Write: {
screen: WriteOpinionScreen,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponentwithBack moveToNotif={navigation} />};
},
},
Votenow: {
screen: VoteNowScreen,
navigationOptions: ({navigation}) => {
return {header: <HeaderComponentwithBack moveToNotif={navigation} />};
},
},
},
{
initialRouteName: 'topbar',
headerMode: 'screen',
},
);
//for main bottom bar nagivation
const MainTabs = createBottomTabNavigator(
{
BillFeed: {
screen: BillNavigation,
navigationOptions: {
title: 'Bill',
tabBarIcon: () => (
<FontAwesome name="bullhorn" size={22} color="white" />
),
},
},
Activity: {
screen: ActivityStack,
navigationOptions: {
title: 'Activity',
tabBarIcon: () => (
<FontAwesome name="line-chart" size={22} color="white" />
),
},
},
CitizenScore: {
screen: CitizenScoreStack,
navigationOptions: {
title: 'Citizen Score',
tabBarIcon: () => <FontAwesome name="star-o" size={22} color="white" />,
},
},
FollowersActivity: {
screen: FollowersActivityStack,
navigationOptions: {
title: 'Followers',
tabBarIcon: props => {
return <FontAwesome name="users" size={22} color="white" />;
},
},
},
NotificationStack: {
screen: NotificationStack,
},
},
{
navigationOptions: ({navigation}) => {
return {
header: null,
};
},
headerMode: 'screen',
initialRouteName: 'BillFeed',
tabBarOptions: {
activeTintColor: '#e91e63',
inactiveBackgroundColor: 'red',
labelStyle: {
fontSize: 12,
},
style: {
backgroundColor: 'white',
},
},
tabBarComponent: props => {
return <BottomTabComponent {...props} />;
},
},
);
const SettingsStack = createStackNavigator({
SettingsList: {
screen: TestScreen,
navigationOptions: {
headerTitle: 'Settings List',
},
},
Profile: {
screen: TestScreen,
navigationOptions: {
headerTitle: 'Profile',
},
},
});
//Required Sreeen when user clicked post of bill feed
const MainDrawer = createStackNavigator({
MainTabs: MainTabs,
Settings: SettingsStack,
});
//Single stack for maindrawer for switching
const AppModalStack = createStackNavigator(
{
App: MainDrawer,
Promotion1: {
screen: TestScreen,
},
},
{
mode: 'modal',
headerMode: 'none',
},
);
// for start navigation
const AppNavigator = createSwitchNavigator(
{
Home: {
screen: AppModalStack,
},
Auth: {
screen: AuthStack,
},
Landing: {
screen: splashStack,
},
},
{
initialRouteName: 'Landing',
headerMode: 'none',
// headerTitle:"naradmuni"
},
);
export default createAppContainer(AppNavigator);
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import ImagePicker from 'react-native-image-picker';
import {Text, View, Card, Textarea, CardItem} from 'native-base';
import {opinionSend} from '../../actions/OpinionPost';
import {connect} from 'react-redux';
import {
Image,
KeyboardAvoidingView,
Platform,
TouchableOpacity,
} from 'react-native';
import styles from '../../components/BottonIcon/buttonIconStyle';
class WriteOpinionScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
filePath: null,
opinion: '',
mediaUrl: '',
};
}
chooseFile = () => {
var options = {
title: 'Select Image',
customButtons: [
{name: 'customOptionKey', title: 'Choose Photo from Custom Option'},
],
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
alert(response.customButton);
} else {
let source = response;
// const source = {uri: response.uri};
this.setState({
filePath: source,
});
// let source = response;
// You can also display the image using data:
// let source = {uri: 'data:image/jpeg;base64,' + response.data};
// this.setState({
// filePath: source,
// });
}
});
};
onHandelCHange = text => {
this.setState({
opinion: text,
});
};
OnSubmit = () => {
this.props.opinionSend(
this.props.token,
this.props.billId,
this.state.opinion,
this.state.filePath,
);
// alert('hello');
// console.log('data getting', this.state.opinion);
};
render() {
return (
<View style={{flexDirection: 'column', flex: 1}}>
<KeyboardAvoidingView
style={{flex: 1}}
behavior={Platform.OS === 'ios' ? 'height' : null}
keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
enabled>
<View style={{flexDirection: 'column'}}>
<View style={{flexDirection: 'row'}}>
<View
style={{flexDirection: 'row', alignItems: 'center', flex: 1}}>
<Image
source={require('../../../assets/opinionsmd.png')}
style={{width: 25, height: 20, marginHorizontal: 10}}
resizeMode="contain"
/>
<Text>Write your Opinions</Text>
</View>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
flex: 0.7,
marginHorizontal: 10,
}}>
<Card
style={{
flexDirection: 'row',
justifyContent: 'center',
flex: 1,
}}>
<TouchableOpacity onPress={() => this.OnSubmit()}>
<CardItem
style={{flexDirection: 'row', justifyContent: 'center'}}>
<Image
source={require('../../../assets/done.png')}
style={{width: 13, height: 13, marginRight: 7}}
/>
<Text style={{fontSize: 13}}>Add</Text>
</CardItem>
</TouchableOpacity>
</Card>
</View>
</View>
</View>
<View
style={{
flexDirection: 'column',
backgroundColor: 'green',
flex: 4,
}}>
<Textarea
multiline
underlineColorAndroid="transparent"
// value={this.state.opinion}
onChangeText={text => this.onHandelCHange(text)}
// value={value}
id="opinion"
placeholder="What's on Your mind?"
style={{
paddingRight: 10,
backgroundColor: 'white',
flex: 4,
textAlignVertical: 'top',
}}
/>
</View>
<View
style={{
position: 'absolute',
bottom: '15%',
left: '20%',
width: '100%',
flexDirection: 'column',
}}>
<Image
source={this.state.filePath}
style={{width: 200, height: 150, marginRight: 7}}
/>
</View>
<View style={{flexDirection: 'row', width: '100%'}}>
<Card
style={{
position: 'absolute',
bottom: 0,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
}}>
<TouchableOpacity onPress={() => this.chooseFile()}>
<CardItem>
<Image
source={require('../../../assets/camera.png')}
value={this.state.mediaUrl}
style={{width: 15, height: 15, marginHorizontal: 10}}
/>
<Text style={{fontSize: 15, fontFamily: 'Lato-bold'}}>
Upload photo/Video
</Text>
</CardItem>
</TouchableOpacity>
</Card>
</View>
</KeyboardAvoidingView>
</View>
);
}
}
const mapStateToProps = state => {
return {
token: state.authReducer.token,
billId: state.BIllsReducer.billdetail.data.id,
};
};
export default connect(mapStateToProps, {opinionSend})(WriteOpinionScreen);
<file_sep>import React from 'react';
import {View} from 'react-native';
import {
BillRelatedComponent,
FollowViewComponent,
VoteViewComponent,
OpinionViewComponent,
ReplyComponent,
} from '../ActivityComponent';
const ActComponent = props => {
return (
// eslint-disable-next-line react-native/no-inline-styles
<View style={{marginVertical: 10}}>
{props.activity.map(activity => {
let message;
if (activity.headerNo === 1) {
//FOLLOW VIEW with follow action ==== headerNo 1
message = (
<FollowViewComponent
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle={activity.content.action}
/>
);
} else if (activity.headerNo === 2) {
//VOTE VIEW ==== headerNo 2
message = (
<VoteViewComponent
question={activity.content.billDetailVote.question}
option={activity.content.billDetailVote.optionA}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle="Follow"
/>
);
} else if (activity.headerNo === 3) {
//WROTE AN OPINION VIEW === headerNo 3
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<OpinionViewComponent
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 4) {
//Shared/liked this View ==== headerNo 4
message = (
<OpinionViewComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 5) {
//BILL RELATED View ==== headerNo 5
message = (
<BillRelatedComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 6) {
//COMMENTED ON A OPINION View ==== headerNo 6
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<ReplyComponent
opinionComment={activity.content.comment}
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
}
return <View key={activity.id}>{message}</View>;
})}
</View>
);
};
export default ActComponent;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Container, Icon, View, Content} from 'native-base';
import {Col, Row, Grid} from 'react-native-easy-grid';
import {StyleSheet, Text, Alert, TouchableOpacity} from 'react-native';
import {ProfileStyles, ProfileStyleExt} from './ProfileStyles';
import {connect} from 'react-redux';
import {Logout} from '../../actions/LoginScreenApi';
import RoundedIcon from '../../components/RoundedIcon';
import {
followersList,
UserActivities,
followingList,
} from '../../utils/constants';
import {TitleWithImgComponent, FollowerComponent} from '../../components';
import {
OpinionViewComponent,
FollowViewComponent,
VoteViewComponent,
BillRelatedComponent,
ReplyComponent,
} from '../../components/ActivityComponent';
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false, //begin with box closed
};
}
gotologin = () => {
this.props.Logout();
this.props.navigation.navigate('SignIn');
};
signOut = () => {
Alert.alert(
'Logout',
'Are you sure you want to logout?',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'OK', onPress: () => this.gotologin()},
],
{cancelable: false},
);
};
//function that takes in expanded and makes it the opposite of what it currently is
showButton = () => {
this.setState({expanded: !this.state.expanded});
};
render() {
const {navigation} = this.props;
const uri =
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg'; //https://facebook.github.io/react-native/docs/assets/favicon.png";
var nameString = JSON.stringify(navigation.getParam('name', '<NAME>'));
var imageUrl = JSON.stringify(navigation.getParam('profileImage', uri));
var isFollowing = JSON.stringify(
navigation.getParam('following', 'showSettings'),
);
var follow = JSON.parse(isFollowing);
let buttonView;
if (follow === 'showSettings') {
buttonView = (
<View style={styles.settingsBtnView}>
<TouchableOpacity
activeOpacity={0.8}
style={styles.settingTouchView}
onPress={() => this.props.navigation.navigate('ProfSetting')}>
<Icon name="settings" type="Octicons" style={styles.settingsIcon} />
<Text style={styles.profileSettingsText}> Profile Settings </Text>
</TouchableOpacity>
</View>
);
} else if (follow === true) {
buttonView = (
<View style={styles.followBtnView}>
<TouchableOpacity
activeOpacity={0.8}
style={styles.followButtonTouchView}
onPress={() => this.props.navigation.navigate('')}>
<Icon
name="heart"
type="FontAwesome"
style={styles.followHeartIcon}
/>
<Text style={styles.followWhiteText}> Following </Text>
</TouchableOpacity>
</View>
);
} else {
buttonView = (
<View style={styles.followBtnView}>
<TouchableOpacity
activeOpacity={0.8}
style={styles.followButtonTouchView}
onPress={() => this.props.navigation.navigate('')}>
<Icon
name="heart"
type="FontAwesome"
style={styles.followHeartIcon}
/>
<Text style={styles.followWhiteText}> Follow </Text>
</TouchableOpacity>
</View>
);
}
return (
<Container>
<Content>
<View style={styles.profileDetailView}>
<Grid>
<Col style={styles.colView}>
<RoundedIcon
uri={JSON.parse(imageUrl)}
mainStyle={styles.profileRoundIcon}
/>
</Col>
<Col>
<Row />
<Row style={styles.rowViewProfileDetail}>
<Row style={styles.rowUserName}>
<Col>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.usernameBoldText}>
{JSON.parse(nameString)}
</Text>
</Col>
<Col>
<Icon
name="log-out"
type="Feather"
onPress={() => this.signOut()}
style={styles.tinyIcons}
/>
</Col>
</Row>
<Row>
<Text
numberOfLines={2}
ellipsizeMode="tail"
style={styles.userBioInfoText}>
Hi! I'm <NAME>, UX Designer/UI Developer. I like
desiging alot. Check out my latest work.
</Text>
</Row>
<Row style={styles.rowUserName}>
<Icon
name="check-square-o"
type="FontAwesome"
style={styles.tinyIcons}
/>
<Text style={styles.votesText}> 220 Votes </Text>
<Icon
name="comment-processing"
type="MaterialCommunityIcons"
style={styles.tinyIcons}
/>
<Text style={styles.votesText}> 83 Posts</Text>
</Row>
</Row>
<Row style={styles.rowSettingsView}>{buttonView}</Row>
</Col>
</Grid>
</View>
<View style={styles.viewBelow}>
<FollowerComponent
title="Followers"
count="200"
followArray={followersList}
onPressNavigation={this.props.navigation}
/>
<FollowerComponent
title="Following"
count="100"
followArray={followingList}
onPressNavigation={this.props.navigation}
/>
<TitleWithImgComponent
source={require('../../../assets/calendar.png')}
activityName="Remon's Activities"
/>
<View style={{marginVertical: 10}}>
{UserActivities.map(activity => {
let message;
if (activity.headerNo === 1) {
//FOLLOW VIEW with follow action ==== headerNo 1
message = (
<FollowViewComponent
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle={activity.content.action}
/>
);
} else if (activity.headerNo === 2) {
//VOTE VIEW ==== headerNo 2
message = (
<VoteViewComponent
question={activity.content.billDetailVote.question}
option={activity.content.billDetailVote.optionA}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle="Follow"
/>
);
} else if (activity.headerNo === 3) {
//WROTE AN OPINION VIEW === headerNo 3
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<OpinionViewComponent
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 4) {
//Shared/liked this View ==== headerNo 4
message = (
<OpinionViewComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 5) {
//BILL RELATED View ==== headerNo 5
message = (
<BillRelatedComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 6) {
//COMMENTED ON A OPINION View ==== headerNo 6
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<ReplyComponent
opinionComment={activity.content.comment}
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
}
return <View key={activity.id}>{message}</View>;
})}
</View>
</View>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
profileDetailView: {
...ProfileStyles.shadowView,
},
colView: {
...ProfileStyles.column,
},
rowViewProfileDetail: {
// ...ProfileStyles.row
...ProfileStyleExt.rowView,
},
profileRoundIcon: {
...ProfileStyles.profileRoundImage,
},
rowUserName: {
...ProfileStyles.rowNested,
paddingRight: 10,
},
titleText: {
...ProfileStyles.boldTitleText,
},
usernameBoldText: {
// ...ProfileStyles.boldNameText
...ProfileStyleExt.userNameText,
},
profileSettingsText: {
// ...ProfileStyles.boldNameText
...ProfileStyleExt.settingsText,
},
userBioInfoText: {
...ProfileStyleExt.bioText,
paddingRight: 10,
},
tinyIcons: {
// ...ProfileStyles.profileSmallIcons
...ProfileStyleExt.profileSmallIcons,
},
votesText: {
...ProfileStyleExt.voteText,
},
rowSettingsView: {
...ProfileStyles.rowSettings,
},
settingsBtnView: {
// ...ProfileStyles.profileSettingsView
...ProfileStyleExt.profileSettingsView,
},
settingTouchView: {
...ProfileStyles.profileSettingsTouchView,
},
settingsIcon: {
// ...ProfileStyles.settingsMediumIcon
...ProfileStyleExt.profileSmallIcons,
},
viewBelow: {
...ProfileStyles.viewBelowSettingsBtn,
},
followHeartIcon: {
...ProfileStyleExt.followHeartIcon,
},
followWhiteText: {
...ProfileStyleExt.followWhiteText,
},
followButtonTouchView: {
...ProfileStyleExt.followButtonTouchView,
},
followBtnView: {
...ProfileStyleExt.followBtnView,
},
});
export default connect(
null,
{Logout},
)(Profile);
<file_sep>import TimeCardView from './TimeCardView';
export {TimeCardView};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Image} from 'react-native';
import {Card, CardItem, Text} from 'native-base';
import moment from 'moment';
import HeaderComponentwithBack from '../../components/HeaderComponentwithBack';
import {ScrollView} from 'react-native-gesture-handler';
class BillTimelineScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
timeline: this.props.navigation.state.params.timeline,
};
}
static navigationOptions = ({navigation}) => {
const appToolbarTitle =
navigation.state.params && navigation.state.params.title
? navigation.state.params.title
: '';
const icontitle =
navigation.state.params && navigation.state.params.icon
? navigation.state.params.icon
: '';
console.log('sailesh: ', this.state);
return {
header: (
<HeaderComponentwithBack
moveToNotif={navigation}
title={appToolbarTitle.title}
image={icontitle}
/>
),
};
};
render() {
return (
<View style={{padding: 10}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Image
source={require('../../../assets/timeline.png')}
style={{width: 30, height: 30}}
/>
<Text>Bill Timeline </Text>
</View>
<ScrollView>
<View>
{this.state.timeline.map((it, i) => {
var image = '../../../assets/done.png';
if (it.pass_fail === 'pass') {
image = '../../../assets/eye.png';
}
return (
<View style={{marginTop: 10}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<View
style={{
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}>
<View
style={{
width: 0.5,
flexGrow: 1,
backgroundColor: 'black',
}}
/>
<Image source={require('../../../assets/done.png')} />
<View
style={{
width: 0.5,
flexGrow: 1,
backgroundColor: 'black',
}}
/>
</View>
<Card>
<CardItem style={{justifyContent: 'space-between'}}>
<Text>{it.title}</Text>
<Text note>
{moment(it.createdAt).format('DD MMM YYYY')}
</Text>
</CardItem>
<CardItem>
<Text note>{it.summary}</Text>
</CardItem>
</Card>
</View>
</View>
);
})}
</View>
</ScrollView>
</View>
);
}
}
export default BillTimelineScreen;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Container, Content, View} from 'native-base';
import {remonActivites, olderActivites} from '../../utils/constants';
import {NotificationComponent, HeaderComponent} from '../../components';
class Notification extends React.Component {
static navigationOptions = ({navigation}) => {
return {header: <HeaderComponent moveToNotif={navigation} />};
};
render() {
return (
<Container>
<Content>
<View style={{marginHorizontal: 16}}>
<NotificationComponent
activityName="Today's Notifications"
activityArray={remonActivites}
mainIcon="calendar-alt"
mainIconType="FontAwesome5"
/>
<NotificationComponent
activityName="Older Notifications"
activityArray={olderActivites}
mainIcon="calendar-alt"
mainIconType="FontAwesome5"
/>
</View>
</Content>
</Container>
);
}
}
export default Notification;
<file_sep>import SignUpScreen from './SignUpScreen';
import ForgotScreen from './ForgotScreen';
import LoginScreen from './LoginScreen';
import ResendPassword from './ResendPassword';
export {SignUpScreen, ForgotScreen, LoginScreen, ResendPassword};
<file_sep>const initialState = {
billlist: [],
cashbill: [],
opinionbill: [],
amendment: [],
loading: false,
commentdata: [],
billdetail: [],
success: false,
hasMore: true,
};
// Reducers (Modifies The State And Returns A New State)
const BillsReducer = (state = initialState, action) => {
switch (action.type) {
case 'Loading':
return {
...state,
loading: true,
};
case 'BILL_REQUEST':
return {
...state,
loading: true,
hasMore: true,
data: [],
};
case 'billlist': {
switch (action.screen) {
case '1':
var data;
if (action.page === '1') {
data = action.payload;
} else {
data = state.billlist.concat(action.payload);
}
return {
...state,
loading: false,
billlist: data,
};
case '2':
var data;
if (action.page === '1') {
data = action.payload;
} else {
data = state.cashbill.concat(action.payload);
}
return {
...state,
loading: false,
cashbill: data,
};
case '3':
var data;
if (action.page === '1') {
data = action.payload;
} else {
data = state.opinionbill.concat(action.payload);
}
return {
...state,
loading: false,
opinionbill: data,
};
case '4':
var data;
if (action.page === '1') {
data = action.payload;
} else {
data = state.amendment.concat(action.payload);
}
return {
...state,
loading: false,
data: data,
};
default: {
return state;
}
}
}
case 'billdetail': {
return {
...state,
loading: false,
billdetail: action.payload,
success: action.payload.success,
};
}
default: {
return state;
}
}
};
export default BillsReducer;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Card, Text, Thumbnail} from 'native-base';
import {StyleSheet, Image} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import BottomLayout from '../BiIlDetailComponent/BottomLayout';
import LinearGradient from 'react-native-linear-gradient';
const MediaSingleComponent = props => (
<TouchableOpacity onPress={props.onPress}>
<View style={{flexDirection: 'column'}}>
<Card>
<View style={{flexDirection: 'column', padding: 0}}>
<Image
source={{
uri:
'https://www.hindustantimes.com/rf/image_size_960x540/HT/p2/2017/03/08/Pictures/sushma-najma-and-brinda-celebrate-bill-passage_9cc65a30-03a8-11e7-87c7-5947ba54d240.jpg',
}}
style={{height: 200, width: '100%'}}
/>
<LinearGradient
colors={['transparent', '#011844']}
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
height: '100%',
}}
/>
<View
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
}}>
<Thumbnail
source={{
uri:
'https://pickaface.net/gallery/avatar/parthisthebest5750125054898.png',
}}
/>
<View>
<Text style={styles.title}>NativeBase</Text>
<Text style={styles.title} note>
GeekyAnts GeekyAnsss
</Text>
</View>
</View>
</View>
<BottomLayout />
</Card>
</View>
</TouchableOpacity>
);
export default MediaSingleComponent;
const styles = StyleSheet.create({
row: {flexDirection: 'row'},
col: {flexDirection: 'column'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
title: {color: 'white'},
});
<file_sep>import React from 'react';
import {AppNavigator} from './config';
class MainApp extends React.Component {
render() {
return (
// <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<AppNavigator />
// </View>
);
}
}
export default MainApp;
<file_sep>import DetailBillScreen from './DetailBillScreen';
export {DetailBillScreen};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Image, Text, TouchableOpacity} from 'react-native';
import {CardItem, Thumbnail, Left, Body, Right} from 'native-base';
import EStyleSheet from 'react-native-extended-stylesheet';
import LinearGradient from 'react-native-linear-gradient';
import colors from '../../utils/colors';
import moment from 'moment';
import {AllStyles} from '../AllStyles';
import CountDowns from '../../utils/CountDowns';
const BillItemCardVIew = props => (
<TouchableOpacity onPress={props.onPress}>
<View
elevation={5}
style={{
marginBottom: 10,
elevation: 5,
// eslint-disable-next-line no-undef
marginRight: Platform.OS === 'ios' ? 0 : 1,
shadowRadius: 4,
shadowOffset: {width: 0, height: 5},
shadowColor: '#ccc',
shadowOpacity: 0.6,
borderRadius: 4,
}}>
<CardItem
cardBody
bordered
style={{borderTopLeftRadius: 4, borderTopRightRadius: 4}}>
<Image
source={{
uri: props.data.image,
}}
style={[
styles.mainImage,
{borderTopLeftRadius: 4, borderTopRightRadius: 4},
]}
/>
<LinearGradient
colors={['#011f4202', '#011f4290', '#011844']}
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
height: '100%',
}}
/>
<Left
style={{
flexDirection: 'row',
position: 'absolute',
left: 0,
bottom: 0,
width: '100%',
padding: 5,
paddingBottom: 10,
}}>
<Thumbnail
source={{
uri: props.data.mp_pic,
}}
style={{width: 40, height: 45, borderRadius: 40 / 2}}
/>
<Body>
<Text
style={[AllStyles.HeaderCardText, styles.title]}
numberOfLines={1}>
{props.data.title}
</Text>
<Text style={styles.subTitle} numberOfLines={1}>
{props.data.title}
</Text>
</Body>
</Left>
</CardItem>
<CardItem
style={{
marginTop: 1,
marginBottom: 1,
borderBottomLeftRadius: 4,
borderBottomRightRadius: 4,
}}>
<Left style={{flexDirection: 'row', justifyContent: 'flex-start'}}>
<TouchableOpacity style={{marginLeft: 5, marginRight: 5}}>
<Text style={styles.textstyle}>
Votes:{props.data.citizen_poll_count}
</Text>
</TouchableOpacity>
<Text style={styles.textstyle}> | </Text>
<TouchableOpacity style={{marginLeft: 5, marginRight: 5}}>
<Text style={styles.textstyle}>
Opinions:{props.data.opinion_count}
</Text>
</TouchableOpacity>
</Left>
<Right style={{flexDirection: 'row'}}>
<CountDowns
until={checkdates(props.data.citizen_poll_deadline)}
size={15}
digitStyle={{backgroundColor: colors.primaryBlueColor}}
digitTxtStyle={{color: '#ffffff'}}
/>
</Right>
</CardItem>
</View>
</TouchableOpacity>
);
export default BillItemCardVIew;
function checkdates(finalss) {
var mo = moment(finalss).diff(moment(), 'seconds');
return mo;
}
const styles = EStyleSheet.create({
title: {
color: colors.white,
},
textLayout: {
width: '20rem',
height: '20rem',
},
textstyle: {
fontSize: '12rem',
color: colors.textcolor,
fontFamily: 'Lato-bold',
},
subTitle: {
fontSize: '10rem',
color: colors.white,
fontFamily: 'Lato-regular',
},
mainImage: {height: '160rem', width: null, flex: 1},
});
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Container, Content, View} from 'native-base';
import {ActivitiesContent, OlderActivitesContent} from '../../utils/constants';
import {TitleWithImgComponent} from '../../components';
import {
OpinionViewComponent,
FollowViewComponent,
VoteViewComponent,
BillRelatedComponent,
ReplyComponent,
} from '../../components/ActivityComponent';
class Activity extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false, //begin with box closed
};
}
//function that takes in expanded and makes it the opposite of what it currently is
showButton = () => {
this.setState({expanded: !this.state.expanded});
};
render() {
return (
<Container>
<Content>
<View style={{marginHorizontal: 16}}>
<View>
<TitleWithImgComponent
source={require('../../../assets/calendar.png')}
activityName="Today Activities"
/>
<View style={{marginVertical: 10}}>
{ActivitiesContent.map(activity => {
let message;
if (activity.headerNo === 1) {
// FOLLOW VIEW with follow action ==== headerNo 1
message = (
<FollowViewComponent
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle={activity.content.action}
/>
);
} else if (activity.headerNo === 2) {
//VOTE VIEW ==== headerNo 2
message = (
<VoteViewComponent
question={activity.content.billDetailVote.question}
option={activity.content.billDetailVote.optionA}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle="Follow"
/>
);
} else if (activity.headerNo === 3) {
//WROTE AN OPINION VIEW === headerNo 3
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<OpinionViewComponent
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 4) {
//Shared/liked this View ==== headerNo 4
message = (
<OpinionViewComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 5) {
//BILL RELATED View ==== headerNo 5
message = (
<BillRelatedComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 6) {
//COMMENTED ON A OPINION View ==== headerNo 6
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<ReplyComponent
opinionComment={activity.content.comment}
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
}
return <View key={activity.id}>{message}</View>;
})}
</View>
</View>
<View>
<TitleWithImgComponent
source={require('../../../assets/calendar.png')}
activityName="Older Activities"
/>
<View style={{marginVertical: 10}}>
{OlderActivitesContent.map(activity => {
let message;
if (activity.headerNo === 1) {
//FOLLOW VIEW with follow action ==== headerNo 1
message = (
<FollowViewComponent
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle={activity.content.action}
/>
);
} else if (activity.headerNo === 2) {
//VOTE VIEW ==== headerNo 2
message = (
<VoteViewComponent
question={activity.content.billDetailVote.question}
option={activity.content.billDetailVote.optionA}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
iconName="heart"
iconType="FontAwesome"
buttonTitle="Follow"
/>
);
} else if (activity.headerNo === 3) {
//WROTE AN OPINION VIEW === headerNo 3
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<OpinionViewComponent
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 4) {
//Shared/liked this View ==== headerNo 4
message = (
<OpinionViewComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 5) {
//BILL RELATED View ==== headerNo 5
message = (
<BillRelatedComponent
buttonText=""
comment=""
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
} else if (activity.headerNo === 6) {
//COMMENTED ON A OPINION View ==== headerNo 6
const textLong = activity.content.billDetail.opinion;
let textEx = '';
let moreLessText = 'See More';
if (this.state.expanded === true) {
textEx = textLong;
moreLessText = 'See Less';
} else {
textEx =
textLong.length < 70
? `${textLong}`
: `${textLong.substring(0, 70)}... `;
moreLessText = 'See More';
}
message = (
<ReplyComponent
opinionComment={activity.content.comment}
buttonText={moreLessText}
comment={textEx}
state={this.state.expanded}
seeMoreBtn={this.showButton}
userName={activity.content.name}
description={activity.content.act}
name2={activity.content.name2}
time={activity.content.time}
profileImage={activity.content.profileImage}
/>
);
}
return <View key={activity.id}>{message}</View>;
})}
</View>
</View>
</View>
</Content>
</Container>
);
}
}
export default Activity;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React, {useState} from 'react';
import {View, Image, Text} from 'react-native';
import PieChart from 'react-native-pie-chart';
const PieCharts = props => {
const series = [123, 111];
const [iconHeight, setIconHeight] = useState(0);
const [w, swtW] = useState(1);
const find_dimesions = (layout, width) => {
swtW(layout.width / 2 - width / 2);
setIconHeight(layout.height / 2 - width / 2);
};
return (
<View style={{alignItems: 'center'}}>
<View
style={{alignItems: 'center'}}
onLayout={event => {
find_dimesions(event.nativeEvent.layout, props.iconWidth);
}}>
<PieChart
chart_wh={props.style.width}
series={series}
sliceColor={props.sliceColor}
doughnut
coverRadius={0.7}
coverFill="#FFF"
/>
<Image
resizeMode="contain"
source={props.source}
style={{
width: props.iconWidth,
height: props.iconWidth,
position: 'absolute',
left: w,
top: iconHeight,
}}
/>
</View>
<Text style={props.text1Style}>{props.title}</Text>
<Text style={props.text2style}>{props.text2}</Text>
</View>
);
};
export default PieCharts;
<file_sep>import React from 'react';
import {Icon, View} from 'native-base';
import RoundedIcon from './RoundedIcon';
import {StyleSheet, TouchableOpacity, Text} from 'react-native';
import {
ProfileStyles,
ProfileStyleExt,
} from '../screens/ProfileScreens/ProfileStyles';
const FollowerComponent = props => {
return (
<View>
<View style={styles.viewFollow}>
<View style={styles.viewDirectionRow}>
<Text style={styles.titleText}>{props.title}</Text>
<Text style={styles.titleText}>({props.count})</Text>
</View>
<TouchableOpacity
activeOpacity={0.8}
onPress={() =>
props.onPressNavigation.push('FollowerScreen', {
itemId: 1,
otherParam: 'anything you want here',
array: props.followArray,
})
}>
<View style={styles.settingTouchView}>
<Text style={styles.viewAll}>View all</Text>
<Icon name="right" type="AntDesign" style={styles.viewArrow} />
</View>
</TouchableOpacity>
</View>
<View style={styles.followersViewRow}>
{props.followArray.slice(0, 4).map(profile => {
return (
<TouchableOpacity
key={profile.id}
activeOpacity={0.8}
onPress={() =>
props.onPressNavigation.push('ProfileScreen', {
itemId: 1,
otherParam: 'anything you want here',
name: profile.name,
profileImage: profile.profileImage,
following: profile.following,
})
}>
<View style={styles.singleFollower}>
<RoundedIcon
uri={profile.profileImage}
mainStyle={styles.followerRoundIcon}
/>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.followersText}>
{profile.name}
</Text>
</View>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
const styles = StyleSheet.create({
titleText: {
// ...ProfileStyles.boldTitleText
...ProfileStyleExt.boldTitleText,
},
viewFollow: {
...ProfileStyles.viewFollowersFollowing,
},
viewDirectionRow: {
...ProfileStyles.flexRow,
},
viewAll: {
// ...ProfileStyles.bioInfoText
...ProfileStyleExt.bioText,
},
viewArrow: {
// ...ProfileStyles.greySmallIcon
...ProfileStyleExt.greySmallIcon,
},
followersViewRow: {
...ProfileStyles.followersArrayView,
},
singleFollower: {
...ProfileStyles.singleFollowerView,
},
followerRoundIcon: {
...ProfileStyles.followerIcon,
},
followersText: {
// ...ProfileStyles.followerText
...ProfileStyleExt.followerText,
},
settingTouchView: {
...ProfileStyles.profileSettingsTouchView,
},
});
export default FollowerComponent;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Card, CardItem} from 'native-base';
import {Image, Dimensions, Text} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';
import {backgroundLikeSend} from '../../actions/BackgroundAPI';
import {connect} from 'react-redux';
import EStyleSheet from 'react-native-extended-stylesheet';
import colors from '../../utils/colors';
import BottomLayout from './BottomLayout';
import {AllStyles} from '../AllStyles';
import CodePush from 'react-native-code-push';
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
class KeyStatConponent extends React.Component {
sendLike = (token, billId, type, modalId) => {
this.props.backgroundLikeSend(token, billId, type, modalId);
console.log('modelid', this.props.modalId);
};
render() {
var cardpush = [];
this.props.detail.map((it, i) => {
if (i == 0) {
cardpush.push(
<Card style={styles.cardWidth}>
<CardItem>
<Text style={AllStyles.HeaderCardText} numberOfLines={1}>
#{it.title}
</Text>
</CardItem>
<CardItem>
<Text
style={{
fontSize: 40,
color: colors.secondaryYellowColor,
fontFamily: 'Lato-black',
}}>
{formatvalue(it.stat_number_1)}
</Text>
<Text
numberOfLines={1}
style={[
AllStyles.briefText,
{
alignSelf: 'center',
fontFamily: 'Lato-bold',
color: colors.textcolor,
},
]}>
{it.stat_text_1}
</Text>
</CardItem>
<BottomLayout
// onPress={index =>
// this.sendLike(
// this.props.token && this.props.token,
// this.props.id.bill_detail.bill_id &&
// this.props.id.bill_detail.bill_id,
// 'bill_info_cards',
// it.info_card_id,
// )
// }
// onPressLong={this.props.onPress}
onPress={() =>
this.props.onPress.navigate('commentDetailScreen', {
commentdata: it,
title: this.props.title,
icon: this.props.icon,
})
}
likes_count={this.props.like}
comments_count={it.comments_count}
shares_count={it.shares_count}
/>
</Card>,
);
}
return CodePush;
});
return (
<View>
<View style={{flexDirection: 'column'}}>
<View
style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
<Image
style={AllStyles.iconsize}
source={require('../../../assets/statistics/statistics.png')}
/>
<Text style={AllStyles.HeaderCardText}>Key Stats </Text>
</View>
<ScrollView horizontal>{cardpush}</ScrollView>
</View>
</View>
);
}
}
const formatvalue = n => {
if (n < 1e3) {
return n;
}
if (n >= 1e3 && n < 1e6) {
return +(n / 1e3).toFixed(0) + 'K';
}
if (n >= 1e6 && n < 1e9) {
return +(n / 1e6).toFixed(0) + 'M';
}
if (n >= 1e9 && n < 1e12) {
return +(n / 1e9).toFixed(0) + 'B';
}
if (n >= 1e12) {
return +(n / 1e12).toFixed(0) + 'T';
}
};
const mapStateToProps = state => {
return {
token: state.authReducer.token,
like: state.backgroundReducer.likesCount,
};
};
export default connect(mapStateToProps, {backgroundLikeSend})(KeyStatConponent);
// export default KeyStatConponent;
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
cardWidth: {
width: '300rem',
justifyContent: 'space-between',
backgroundColor: 'white',
elevation: 5,
marginBottom: '15rem',
borderBottomWidth: 0,
shadowOpacity: 0.3,
shadowRadius: 5,
shadowColor: 'gray',
shadowOffset: {height: 0, width: 1},
padding: '5rem',
borderRadius: 5,
},
description: {flexGrow: 1, justifyContent: 'flex-start'},
});
<file_sep>/* eslint-disable no-alert */
export const increment = () => dispatch => {
alert('testing');
dispatch({
type: 'increase',
payload: 23,
});
};
<file_sep>/* eslint-disable no-alert */
/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Header, Left, Body, Right, Button, Icon, Thumbnail} from 'native-base';
import {Image} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import colors from '../utils/colors';
const HeaderWithBackBtn = props => (
<Header
style={{backgroundColor: colors.primaryBlueColor, borderBottomWidth: 0}}
androidStatusBarColor="#011844"
iosBarStyle="light-content">
<Left style={{width: 40}}>
<Button
transparent
onPress={() => {
alert('call');
props.moveToNotif.goBack();
}}>
<Image
source={require('../../assets/backBtn/back-bar-white.png')}
style={styles.backIconStyle}
/>
</Button>
</Left>
<Body style={{flex: 1}}>
<Thumbnail
square
source={require('../../assets/mainlogo.png')}
style={styles.headerImgStyle}
/>
</Body>
<Right>
<Button transparent>
<Icon
name="bell"
type="MaterialCommunityIcons"
style={{fontSize: 22, color: 'white'}}
onPress={() => props.moveToNotif.navigate('NotificationStack')}
/>
</Button>
</Right>
</Header>
);
const styles = EStyleSheet.create({
headerImgStyle: {
width: '200rem',
height: '30rem',
resizeMode: 'contain',
alignSelf: 'center',
},
backIconStyle: {
width: 20,
height: 20,
resizeMode: 'contain',
alignSelf: 'center',
},
});
export default HeaderWithBackBtn;
<file_sep>import React from 'react';
// eslint-disable-next-line no-unused-vars
import {Icon} from 'native-base';
import {View, StyleSheet, TouchableOpacity, Text} from 'react-native';
import RoundedIcon from './RoundedIcon';
import {
ProfileStyles,
ProfileStyleExt,
} from '../screens/ProfileScreens/ProfileStyles';
import TitleWithImgComponent from './TitleWithImgComponent';
const NotificationComponent = props => {
return (
<View>
<TitleWithImgComponent
source={require('../../assets/calendar.png')}
activityName={props.activityName}
styleView={props.styleView}
/>
<View>
{props.activityArray.map(activity => {
return (
<TouchableOpacity
activeOpacity={0.8}
key={activity.id}
onPress={() => console.log('hey activity clicked')}>
<View style={styles.actView}>
<View style={styles.actNested}>
<RoundedIcon
uri={activity.profileImage}
mainStyle={styles.actRoundedIcon}
/>
<View style={styles.actTextCardView}>
<View style={styles.activityCardView1}>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.actUserName}>
{activity.name}
</Text>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.actDesc}>
{' '}
{activity.act}{' '}
</Text>
</View>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.actTime}>
{activity.time}
</Text>
</View>
</View>
</View>
</TouchableOpacity>
);
})}
</View>
</View>
);
};
const styles = StyleSheet.create({
actView: {
...ProfileStyleExt.notifCardView,
},
actNested: {
...ProfileStyles.activityNestedView,
},
actRoundedIcon: {
...ProfileStyles.actRoundedImage,
},
actTextCardView: {
...ProfileStyleExt.actTextCardView,
},
activityCardView1: {
...ProfileStyleExt.notifTextCardView1,
},
actUserName: {
...ProfileStyleExt.notifBoldText,
},
actDesc: {
...ProfileStyleExt.notifDescription,
},
actTime: {
...ProfileStyleExt.actTimeText,
},
iconSize: {
...ProfileStyleExt.iconSize,
},
});
export default NotificationComponent;
<file_sep>export const mainTabs = [
{
label: 'Bill Feed',
path: 'BillFeed',
active: require('./../../assets/BillTabsActive/bills-tab-active.png'),
inactive: require('./../../assets/BillTabs/bills-tab.png'),
},
{
label: 'Activity Feed',
path: 'Activity',
active: require('./../../assets/ActivityTabActive/activity-tab-active.png'),
inactive: require('./../../assets/ActivityTabInactive/activity-tab.png'),
},
{
label: 'Citizen Score',
path: 'CitizenScore',
active: require('./../../assets/ScoreTabActive/score-tab-active.png'),
inactive: require('./../../assets/ScoreTabInactive/score-tab.png'),
},
{
label: 'My Profile',
path: 'FollowersActivity',
active: require('./../../assets/ProfileTabActive/profile-tab-active.png'),
inactive: require('./../../assets/ProfileTabInactive/profile-tab.png'),
},
];
export const followersList = [
{
id: 1,
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
following: true,
},
{
id: 2,
bg: 'red',
name: '<NAME>',
profileImage:
'https://imgix.bustle.com/uploads/image/2018/5/9/fa2d3d8d-9b6c-4df4-af95-f4fa760e3c5c-2t4a9501.JPG?w=970&h=546&fit=crop&crop=faces&auto=format&q=70',
following: true,
},
{
id: 3,
bg: 'blue',
name: '<NAME>',
profileImage:
'https://i.pinimg.com/originals/a6/0d/68/a60d685194a7fd984d08a595a0a99ae7.jpg',
following: false,
},
{
id: 4,
bg: 'green',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
following: true,
},
{
id: 5,
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
following: true,
},
{
id: 6,
bg: 'red',
name: '<NAME>',
profileImage:
'https://imgix.bustle.com/uploads/image/2018/5/9/fa2d3d8d-9b6c-4df4-af95-f4fa760e3c5c-2t4a9501.JPG?w=970&h=546&fit=crop&crop=faces&auto=format&q=70',
following: true,
},
{
id: 7,
bg: 'blue',
name: '<NAME>',
profileImage:
'https://i.pinimg.com/originals/a6/0d/68/a60d685194a7fd984d08a595a0a99ae7.jpg',
following: false,
},
{
id: 8,
bg: 'green',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
following: true,
},
];
export const followingList = [
{
id: 1,
bg: 'green',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
following: true,
},
{
id: 2,
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
following: true,
},
{
id: 3,
bg: 'blue',
name: '<NAME>',
profileImage:
'https://i.pinimg.com/originals/a6/0d/68/a60d685194a7fd984d08a595a0a99ae7.jpg',
following: true,
},
{
id: 4,
bg: 'red',
name: '<NAME>',
profileImage:
'https://imgix.bustle.com/uploads/image/2018/5/9/fa2d3d8d-9b6c-4df4-af95-f4fa760e3c5c-2t4a9501.JPG?w=970&h=546&fit=crop&crop=faces&auto=format&q=70',
following: true,
},
];
export const remonActivites = [
{
id: 1,
bg: 'green',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'voted in J&K Reorganisation Bill.',
time: '3 seconds ago',
},
{
id: 2,
bg: 'pink',
name: '<NAME>',
profileImage:
'https://legaltechnology-compass.com/wp-content/uploads/2018/04/shutterstock_1_web.jpg',
act: 'wrote an opinion on J&K Reorganisation Bill.',
time: '1 minute ago',
},
{
id: 3,
bg: 'blue',
name: 'Rupert',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'commented on Karthiks opinion about the J&K Bill',
time: '3 minutes ago',
},
{
id: 4,
bg: 'red',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'voted in Dam Safety Bill.',
time: '5 minutes ago',
},
{
id: 5,
bg: 'blue',
name: 'Lyanna',
profileImage:
'https://legaltechnology-compass.com/wp-content/uploads/2018/04/shutterstock_1_web.jpg',
act: 'commented on Karthiks opinion about the J&K Bill',
time: '45 minutes ago',
},
{
id: 6,
bg: 'red',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'voted in Dam Safety Bill.',
time: '1 hour ago',
},
];
export const olderActivites = [
{
id: 1,
bg: 'green',
name: '<NAME>',
profileImage:
'https://legaltechnology-compass.com/wp-content/uploads/2018/04/shutterstock_1_web.jpg',
act: 'voted in J&K Reorganisation Bill.',
time: '3 days ago',
},
{
id: 2,
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'wrote an opinion on J&K Reorganisation Bill.',
time: '5 days ago',
},
{
id: 3,
bg: 'blue',
name: '<NAME>',
profileImage:
'https://i.pinimg.com/originals/a6/0d/68/a60d685194a7fd984d08a595a0a99ae7.jpg',
act: 'commented on Karthiks opinion about the J&K Bill',
time: '1 month ago',
},
{
id: 4,
bg: 'red',
name: 'AJ',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'voted in Dam Safety Bill.',
time: '6th June, 2019',
},
];
export const Toptabs = [
{label: 'All Bills', path: 'allbills', tabIcon: 'home', id: 0},
{label: 'Opinions Polls', path: 'opinionbill', tabIcon: 'home', id: 1},
{label: 'Cash Bills', path: 'cashbill', tabIcon: 'beer', id: 2},
{label: 'Amendement Bills', path: 'amendment', tabIcon: 'beer', id: 3},
];
export const ProfSettingsTabs = [
{
label: 'Main Information',
path: 'main',
tabIcon: 'home',
icon: 'info-with-circle',
iconType: 'Entypo',
},
{
label: 'Security Information',
path: 'security',
tabIcon: 'home',
icon: 'ios-lock',
iconType: 'Ionicons',
},
];
export const ActivitiesContent = [
{
id: 1,
headerNo: 1,
content: {
bg: 'green',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'Facebook friend just joined!',
time: 'From 3 mins ago',
action: 'Follow',
},
},
{
id: 2,
headerNo: 2,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'voted in favor of the bill.',
billDetailVote: {
question: 'Do you think this bill will boost economic status of J&K?',
optionA: "It won't have any effect.",
},
time: 'From 10 mins ago',
},
},
{
id: 3,
headerNo: 3,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'wrote an opinion.',
billDetail: {
opinion:
'The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. ',
},
time: 'From 23 mins ago',
},
},
{
id: 4,
headerNo: 4,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'shared this.',
time: 'From 30 mins ago',
},
},
];
export const OlderActivitesContent = [
{
id: 1,
headerNo: 6,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'replied to',
name2: "Remon's",
billDetail: {
opinion:
'The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. The Jammu and Kashmir Reorganisation Act, 2019 is an act of the Parliament of India. ',
},
comment:
"This works fine... I get your point, but the thing is I was't talking about the act itself. ",
time: 'From 6 days ago',
},
},
{
id: 2,
headerNo: 4,
content: {
bg: 'red',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'liked this.',
time: 'From 7 days ago',
},
},
{
id: 3,
headerNo: 1,
content: {
bg: 'blue',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'followed you!',
time: 'From 12 November 2019',
action: 'Follow Back',
},
},
{
id: 4,
headerNo: 5,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'shared this.',
time: 'From 24 June 2019',
},
},
{
id: 5,
headerNo: 2,
content: {
bg: 'pink',
name: '<NAME>',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'voted opposing the bill.',
billDetailVote: {
question: 'Do you think this bill will boost economic status of J&K?',
optionA: 'Nope.',
},
time: 'From 20 June 2019',
},
},
{
id: 6,
headerNo: 1,
content: {
bg: 'blue',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'followed you!',
time: 'From 12 February 2019',
action: 'Follow Back',
},
},
{
id: 7,
headerNo: 1,
content: {
bg: 'blue',
name: '<NAME>',
profileImage:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
act: 'followed you!',
time: 'From 12 January 2019',
action: 'Follow Back',
},
},
];
export const UserActivities = [
{
id: 1,
headerNo: 4,
content: {
bg: 'pink',
name: 'Remon',
profileImage:
'https://images.askmen.com/1080x540/2016/01/25-021526-facebook_profile_picture_affects_chances_of_getting_hired.jpg',
act: 'shared this.',
time: 'From 30 mins ago',
},
},
];
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Card, CardItem} from 'native-base';
import {Text, TouchableOpacity, View} from 'react-native';
import {backgroundLikeSend} from '../../actions/BackgroundAPI';
import {connect} from 'react-redux';
import BottomLayout from './BottomLayout';
import {AllStyles} from '../AllStyles';
class OpinionComponent extends React.Component {
constructor(props) {
super(props);
}
sendLike = (token, billId, type, modalId) => {
this.props.backgroundLikeSend(token, billId, type, modalId);
console.log('modelid', this.props.modalId);
};
render() {
let view = [];
this.props.detail.map(it => {
view.push(
<Card
style={[
this.props.style,
{
elevation: 7,
shadowOffset: {width: 0, height: 5},
borderRadius: 5,
},
]}>
<CardItem
style={{
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'flex-start',
borderTopLeftRadius: 5,
borderTopRightRadius: 5,
}}>
<Text style={[AllStyles.HeaderCardText, {marginBottom: 10}]}>
{it.title}:
</Text>
<Text style={AllStyles.briefText} numberOfLines={3}>
{it.description}
</Text>
</CardItem>
<BottomLayout
// onPress={index =>
// this.sendLike(
// this.props.token && this.props.token,
// this.props.id.bill_detail.bill_id &&
// this.props.id.bill_detail.bill_id,
// 'bill_info_cards',
// it.info_card_id,
// )
// }
onPress={() =>
this.props.onPress.navigate('commentDetailScreen', {
commentdata: it,
title: this.props.title,
icon: this.props.icon,
})
}
likes_count={it.likes_count}
// onPressLong={this.props.onPress}
comments_count={it.comments_count}
shares_count={it.shares_count}
style={{
borderBottomLeftRadius: 5,
borderBottomRightRadius: 5,
}}
/>
</Card>,
);
});
return <View>{view}</View>;
}
}
const mapStateToProps = state => {
return {
token: state.authReducer.token,
};
};
export default connect(mapStateToProps, {backgroundLikeSend})(OpinionComponent);
// export default OpinionComponent;
<file_sep>import React from 'react';
import {Container, Icon, View, Content, Input} from 'native-base';
import {Dimensions} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import colors from '../../utils/colors';
import {FollowersAllComponent} from '../../components/FollowerViewAllComponent';
class FollowersList extends React.Component {
render() {
const {navigation} = this.props;
var arrayList = navigation.getParam('array', []);
return (
<Container>
<Content>
<View style={styles.searchView}>
<Icon
name="magnifying-glass"
type="Entypo"
style={styles.searchIcon}
/>
<Input style={styles.inputTextField} placeholder="Search" />
</View>
<View style={styles.viewBelow}>
<FollowersAllComponent usersArray={arrayList} />
</View>
</Content>
</Container>
);
}
}
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
export const styles = EStyleSheet.create({
searchView: {
flexDirection: 'row',
alignItems: 'center',
height: '40rem',
padding: '5rem',
backgroundColor: colors.lightGreySearch,
margin: '10rem',
borderRadius: 5,
},
searchIcon: {
fontSize: '20rem',
color: colors.primaryBlueColor,
},
inputTextField: {
height: '40rem',
},
viewBelow: {
marginBottom: '10rem',
flex: 1,
},
});
export default FollowersList;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Button, View, Text, Image} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {connect} from 'react-redux';
import {increment} from '../../actions/couterAction';
import {getPosts} from '../../actions/fakeApiCall';
import {Logout} from '../../actions/LoginScreenApi';
class HomeScreen extends React.Component {
gotologin = () => {
this.props.Logout();
this.props.navigation.navigate('SignIn');
};
render() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<TouchableOpacity
onPress={() => {
this.gotologin();
}}>
<Text>increase</Text>
</TouchableOpacity>
<Text>
{' '}
counter:
{this.props.counter}
</Text>
<TouchableOpacity onPress={() => this.props.decreaseCounter()}>
<Text>Decrease</Text>
</TouchableOpacity>
<Button
title="Go to Sign In"
onPress={() => this.props.navigation.navigate('SignIn')}
/>
<Button
title="Call API from AXIOS"
onPress={() => this.props.getPosts()}
/>
{this.props.data.map(val => (
<View key={val.id}>
<Text>{val.email}</Text>
</View>
))}
<Image
style={{width: 100, height: 100}}
source={{
uri: 'https://facebook.github.io/react/logo-og.png',
cache: 'force-cache',
}}
/>
</View>
);
}
}
function mapStateToProps(state) {
return {
counter: state.authReducer.counter,
data: state.apiReducer.data,
logined: state.authReducer.loggedIn,
};
}
// function mapDispatchToprops(dispatch)
// {
// return{
// increaseCounter:()=>dispatch({type:"increase"}),
// decreaseCounter:()=>dispatch({type:"decrease"}),
// };
// }
export default connect(
mapStateToProps,
{increment, getPosts, Logout},
)(HomeScreen);
<file_sep>export const allBills = [
{
id: 1,
title: 'J&K ReOraganisation Bill',
profileImage:
'https://legaltechnology-compass.com/wp-content/uploads/2018/04/shutterstock_1_web.jpg',
images:
'https://dynaimage.cdn.cnn.com/cnn/q_auto,w_900,c_fill,g_auto,h_506,ar_16:9/http%3A%2F%2Fcdn.cnn.com%2Fcnnnext%2Fdam%2Fassets%2F170117152835-beautiful-india-hawa-mahal-jaipur-132721224.jpg',
},
{
id: 3,
title: 'Delhi Road Bill',
profileImage:
'https://legaltechnology-compass.com/wp-content/uploads/2018/04/shutterstock_1_web.jpg',
images:
'http://cdn.walkthroughindia.com/wp-content/uploads/2013/05/Brackish-Lagoons-Alleppey-600x400.jpg',
},
];
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Header, Left, Body, Right, Button, Icon, Thumbnail} from 'native-base';
import {StyleSheet, Image} from 'react-native';
import {ProfileStyleExt} from '../screens/ProfileScreens/ProfileStyles';
const HeaderComponent = props => (
<Header
style={{backgroundColor: '#011844', borderBottomWidth: 0}}
androidStatusBarColor="#011844"
iosBarStyle="light-content">
{console.log('header::::', props)}
<Left style={{flex: 1}}>
<Button transparent>
<Image
source={require('../../assets/cogbar.png')}
style={{width: 20, height: 20}}
onPress={() => props.moveToNotif.navigate('NotificationStack')}
/>
</Button>
</Left>
<Body style={{flex: 1}}>
<Thumbnail
square
source={require('../../assets/mainlogo.png')}
style={styles.headerImgStyle}
/>
</Body>
<Right style={{flex: 1}}>
<Button transparent>
<Icon
name="bell"
type="MaterialCommunityIcons"
style={{fontSize: 22, color: 'white'}}
onPress={() => props.moveToNotif.navigate('NotificationStack')}
/>
</Button>
</Right>
</Header>
);
const styles = StyleSheet.create({
headerImgStyle: {
...ProfileStyleExt.nmHeaderImage,
},
});
export default HeaderComponent;
<file_sep>import React from 'react';
import {View, StyleSheet} from 'react-native';
import {ProfileStyles} from '../screens/ProfileScreens/ProfileStyles';
const ShadowViewComponent = props => {
return <View style={{...styles.actView, ...props.styleView}} />;
};
const styles = StyleSheet.create({
titleText: {
...ProfileStyles.boldTitleText,
},
actView: {
...ProfileStyles.activityCardView,
},
activityIcon: {
...ProfileStyles.settingsMediumIcon,
},
});
export default ShadowViewComponent;
<file_sep>import CitizenScore from "./CitizenScore";
export {CitizenScore};<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {Container, Icon, Text, View} from 'native-base';
import MediaSingleComponent from '../../components/VIewAllComponet/MediaSingleComponent';
import colors from '../../utils/colors';
class ViewAllScreen extends React.Component {
render() {
return (
<Container>
<View style={{flexDirection: 'row', margin: 10, alignItems: 'center'}}>
<Icon
name="bar-graph"
type="Entypo"
style={{color: colors.secondaryYellowColor}}
/>
<Text style={{fontWeight: 'bold'}}> Bills News </Text>
</View>
<MediaSingleComponent
onPress={() => this.props.navigation.navigate('mediaDetail')}
/>
</Container>
);
}
}
export default ViewAllScreen;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Thumbnail, Body} from 'native-base';
import {StyleSheet, Image, Text} from 'react-native';
import {AllStyles} from '../AllStyles';
import RoundedIcon from '../RoundedIcon';
import BottomLayout from '../BiIlDetailComponent/BottomLayout';
const OpinionViewComponent = props => {
let commentView;
if (props.buttonText === '') {
commentView = null;
} else {
commentView = (
<Text style={{margin: 10, flex: 1}}>
<Text style={styles.commentText}>{props.comment}</Text>
<Text onPress={props.seeMoreBtn} style={styles.seeMoreText}>
{props.buttonText}
</Text>
</Text>
);
}
return (
<View>
<View style={styles.fbView}>
<View style={styles.rowFlex}>
<RoundedIcon uri={props.profileImage} mainStyle={styles.iconRound} />
<View style={styles.textFollowView}>
<View
style={{flexDirection: 'row', flexWrap: 'wrap', marginBottom: 5}}>
<Text numberOfLines={2} ellipsizeMode="tail" style={{flex: 1}}>
<Text style={styles.boldText}>{props.userName}</Text>
<Text style={styles.normalText}> {props.description}</Text>
</Text>
</View>
<Text style={styles.smallText}>{props.time}</Text>
</View>
</View>
<View>
<View style={{flexDirection: 'column', padding: 0}}>
<Image
source={{
uri:
'https://www.hindustantimes.com/rf/image_size_960x540/HT/p2/2017/03/08/Pictures/sushma-najma-and-brinda-celebrate-bill-passage_9cc65a30-03a8-11e7-87c7-5947ba54d240.jpg',
}}
style={styles.headlineImgView}
/>
<View
colors={['transparent', '#011844']}
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
height: '100%',
}}>
<View
style={{
flexDirection: 'row',
position: 'absolute',
bottom: 0,
width: '100%',
}}>
<Thumbnail
style={{margin: 10}}
source={{
uri:
'https://pickaface.net/gallery/avatar/parthisthebest5750125054898.png',
}}
/>
<Body style={{marginVertical: 5}}>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.title}>
J&K Reorganiszation Bill
</Text>
<Text
numberOfLines={1}
ellipsizeMode="tail"
style={styles.titleDesc}>
The Bill, which will split J&K into two union
territories.The Bill, which will split J&K into two union
territories.
</Text>
</Body>
</View>
</View>
</View>
<View style={{flexDirection: 'row', marginHorizontal: 10}}>
{commentView}
</View>
<BottomLayout />
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
fbView: {
...AllStyles.activityOpinionCardView,
justifyContent: 'center',
},
rowFlex: {
...AllStyles.rowDes,
flexDirection: 'row',
justifyContent: 'center',
alignContent: 'center',
alignItems: 'center',
},
iconRound: {
...AllStyles.smallRoundedImage,
marginRight: 5,
},
textFollowView: {
marginRight: 5,
...AllStyles.textFollowView,
},
boldText: {
...AllStyles.actBoldText,
},
normalText: {
...AllStyles.actNormalText,
},
smallText: {
...AllStyles.actTimeText,
},
circleView: {
...AllStyles.circleView,
alignItems: 'center',
justifyContent: 'center',
},
headlineImgView: {
...AllStyles.headlineImgView,
},
title: {
...AllStyles.title,
marginBottom: 5,
},
titleDesc: {
...AllStyles.titleDesc,
},
commentText: {
...AllStyles.commentText,
},
seeMoreText: {
...AllStyles.seeMoreText,
textDecorationLine: 'underline',
},
});
export default OpinionViewComponent;
<file_sep>import BillTimelineScreen from './BillTimelineScreen';
export {BillTimelineScreen};
<file_sep>//USERS
export const GET_USERS = 'GET_USERS';
export const GET_USERS_BY_ID = 'GET_USER_BY_ID';
export const FOllOW_USER_BY_ID = 'FOLLOW_USER_BY_ID';
//BILLS
export const GET_BILLS = 'GET_BILLS';
export const GET_BILLSDETAIL_BY_ID = 'GET_BILLSDETAIL_BY_ID';
export const POST_OPINION = 'POST_OPINION';
export const POST_LIKE = 'POST_LIKE';
export const POST_SHARE = 'POST_SHARE';
export const POST_COMMENT = 'POST_COMMENT';
export const POST_VOTE = 'POST_VOTE';
export const POST_REPLY = 'POST_REPLY';
export const GET_REPLIES_BY_COMMENTID = 'GET_REPLIES_BY_COMMENTID';
export const GET_TIMELINES = 'GET_TIMELINES';
export const GET_TIMELINES_BY_ID = 'GET_TIMELINES_BY_ID';
export const GET_CARD_BY_ID = 'GET_CARD_BY_ID';
export const GET_OPINION_BY_ID = 'GET_OPINION_BY_ID';
export const GET_NEWSCARDS = 'GET_NEWSCARDS';
//Activities
export const GET_ACTIVITIES = 'GET_ACTIVITIES';
//Notification
export const GET_NOTIFICATIONS = 'GET_NOTIFICATIONS';
//PROFILE SETTINGS
export const UPDATE_MAIN_INFO = 'UPDATE_MAIN_INFO';
export const UPDATE_SECURITY_INFO = 'UPDATE_SECURITY_INFO';
<file_sep>import WriteOpinionScreen from './WriteOpinionScreen';
export {WriteOpinionScreen};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View} from 'native-base';
import {StyleSheet, Text} from 'react-native';
import colors from '../../utils/colors';
import {AllStyles} from '../AllStyles';
class BillBreifItemComponent extends React.Component {
constructor(props) {
super(props);
console.log('bill inside', props);
}
render() {
return (
<View style={{flexDirection: 'column', margin: 10}}>
<View style={styles.breif}>
<Text
style={{
fontSize: 15,
fontFamily: 'Lato-bold',
color: colors.textcolor,
}}>
{this.props.title}
</Text>
<Text style={AllStyles.briefText}>{this.props.description}</Text>
</View>
</View>
);
}
}
export default BillBreifItemComponent;
const styles = StyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
smallfont: {fontSize: 10},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {flexDirection: 'row', justifyContent: 'space-between'},
});
<file_sep>//import { LOGIN } from "../config/store";
// Initial State
const initialState = {
SignUp: false,
data: [],
loadings: false,
};
// Reducers (Modifies The State And Returns A New State)
const signUpReducer = (state = initialState, action) => {
switch (action.type) {
case 'RLoading':
return {
...state,
loadings: true,
};
default: {
return state;
}
}
};
export default signUpReducer;
<file_sep>import {AsyncStorage} from 'react-native';
import {createStore, applyMiddleware} from 'redux';
import {createLogger} from 'redux-logger';
import thunk from 'redux-thunk';
import {persistStore, persistReducer} from 'redux-persist';
import rootReducer from '../reducers';
// Imports: Redux
// Middleware: Redux Persist Config
const persistConfig = {
// Root
key: 'root',
// Storage Method (React Native)
storage: AsyncStorage,
// storage,
// Whitelist (Save Specific Reducers)
whitelist: ['apiReducer', 'authReducer'],
// Blacklist (Don't Save Specific Reducers)
blacklist: ['counterReducer'],
};
// Middleware: Redux Persist Persisted Reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);
const allMiddlewares = [thunk, createLogger()];
// Redux: Store
const store = createStore(persistedReducer, applyMiddleware(...allMiddlewares));
// Middleware: Redux Persist Persister
const persistor = persistStore(store);
// Exports
export {store, persistor};
<file_sep>import Activity from './Activity';
export {Activity};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Image, TouchableHighlight} from 'react-native';
import {Text} from 'native-base';
import styles from './buttonIconStyle';
const ButtonIcon = props => (
<TouchableHighlight onPress={props.onPress}>
<View style={{...styles.buttonLayout, ...props.style}}>
<Image
source={props.source}
style={{
width: 20,
height: 20,
marginHorizontal: 5,
resizeMode: 'cover',
}}
/>
<Text style={{fontFamily: 'Lato-bold', fontSize: 15, color: props.color}}>
{props.text}
</Text>
</View>
</TouchableHighlight>
);
export default ButtonIcon;
<file_sep>import {
SignUpScreen,
ForgotScreen,
LoginScreen,
ResendPassword,
} from './AuthScreens';
import {HomeScreen} from './HomeScreen';
import {TestScreen} from './TestScreen';
export {
SignUpScreen,
ForgotScreen,
LoginScreen,
ResendPassword,
HomeScreen,
TestScreen,
};
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Image, StyleSheet, TouchableOpacity} from 'react-native';
const ButtonSocial = props => (
<TouchableOpacity
style={{...styles.buttonLayout, ...props.style}}
onPress={props.onPress}>
<View>
<Image
source={props.source}
style={{width: 20, height: 20, resizeMode: 'contain'}}
/>
</View>
</TouchableOpacity>
);
const styles = StyleSheet.create({
buttonLayout: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
// padding: 20,
backgroundColor: 'white',
borderRadius: 5,
},
textLayout: {
width: 20,
height: 20,
},
});
export default ButtonSocial;
<file_sep>/* eslint-disable react-native/no-inline-styles */
import React from 'react';
import {View, Card, CardItem, Icon, Thumbnail} from 'native-base';
import {Dimensions, Image, Text, TextInput} from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import CommentComponent from '../../components/MediaDetailComponent/CommentComponent';
class CommentDetailScreen extends React.Component {
render() {
return (
<View>
<CommentComponent />
<View style={{flexDirection: 'row'}}>
<Card style={{flexGrow: 1}}>
<CardItem>
<TextInput placeholder="Write your Comment here..." />
</CardItem>
</Card>
<Card style={{width: 100}}>
<CardItem style={{justifyContent: 'space-around'}}>
<Image
source={require('../../../assets/done.png')}
style={{width: 10, height: 10}}
/>
<Text>Add</Text>
</CardItem>
</Card>
</View>
<Card>
<CardItem style={{justifyContent: 'space-between'}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Thumbnail
source={{
uri:
'https://makehimyours.com.au/wp-content/uploads/2016/11/Depositphotos_9830876_l-2015Optimised.jpg',
}}
style={{width: 40, height: 40, borderRadius: 20}}
/>
<Text style={{fontSize: 10}}> <NAME></Text>
</View>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Image
source={require('../../../assets/timesm.png')}
style={{width: 15, height: 15, marginHorizontal: 5}}
/>
<Text style={{fontSize: 10}}>20 min ago</Text>
</View>
</CardItem>
<CardItem>
<Text style={styles.smallfont}>
Special Status will be Withdrawn.JK will have its Own legislature
</Text>
</CardItem>
style=
{{
flex: 1,
flexDirection: 'row',
height: 1,
backgroundColor: 'gray',
marginHorizontal: 10,
}}
/>
<CardItem>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 5,
flex: 1,
}}>
<View
style={{flexDirection: 'row', justifyContent: 'space-around'}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
flex: 1,
}}>
<Icon
name="like1"
type="AntDesign"
style={{color: 'lightgray', fontSize: 20}}
/>
<Text style={styles.mediumfont}>like</Text>
</View>
</View>
</View>
</CardItem>
</Card>
</View>
);
}
}
export default CommentDetailScreen;
var screenWidth = Dimensions.get('window').width;
EStyleSheet.build({$rem: screenWidth / 350});
const styles = EStyleSheet.create({
row: {flexDirection: 'row', alignItems: 'center'},
col: {flexDirection: 'column', alignItems: 'center'},
detailtop: {flexDirection: 'row', flexGrow: 1, justifyContent: 'flex-start'},
breif: {
flexDirection: 'column',
alignItems: 'flex-start',
},
timeline: {
flexDirection: 'column',
},
timelinetop: {
flexDirection: 'row',
justifyContent: 'space-between',
margin: 10,
},
rowspace: {
flexDirection: 'row',
justifyContent: 'space-between',
},
smallfont: {fontSize: '9rem', color: 'gray'},
mediumfont: {
fontSize: '12rem',
fontFamily: 'Lato-bold',
color: 'gray',
margin: '5rem',
},
});
<file_sep>import React from 'react';
import {PersistGate} from 'redux-persist/integration/react';
import {Provider} from 'react-redux';
import axios from 'axios';
//import * as Font from 'expo-font';
import AppNavigator from './app/config/AppNavigator';
import {store, persistor} from './app/config/store';
import {Loading} from './app/components';
import codePush from 'react-native-code-push';
let codePushOptions = {checkFrequency: codePush.CheckFrequency.ON_APP_RESUME};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
};
}
// async componentWillMount() {
// await Font.loadAsync({
// Roboto: require("native-base/Fonts/Roboto.ttf"),
// Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
// });
// }
async componentDidMount() {
// Add a request interceptor
axios.interceptors.request.use(
function(config) {
// Do something before request is sent
console.log('This is request', config);
return config;
},
function(error) {
// Do something with request error
console.log('This is request error', error);
return Promise.reject(error);
},
);
// Add a response interceptor
axios.interceptors.response.use(
function(response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log('This is response', response);
return response;
},
function(error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
console.log('This is response error', error);
return Promise.reject(error);
},
);
// await Font.loadAsync({
// Roboto: require('native-base/Fonts/Roboto.ttf'),
// Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
// Begok: require('./assets/fonts/Begok.ttf'),
// Lato: require('./assets/fonts/Lato-Regular.ttf'),
// LatoMedium: require('./assets/fonts/lato.medium.ttf'),
// LatoBold: require('./assets/fonts/lato.bold.ttf'),
// });
// setCustomText({
// style: {
// fontFamily: 'Lato',
// },
// });
}
render() {
const {loading} = this.state;
return loading ? (
<Loading />
) : (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<AppNavigator />
</PersistGate>
</Provider>
);
}
}
App = codePush(codePushOptions)(App);
export default App;
<file_sep>import axios from 'axios';
const baseUrl = 'http://narad.meroshows.com/api/';
export const getBillList = (token, page, bill_type_flag) => dispatch => {
console.log('getbilllist', page + bill_type_flag);
axios
.get(`${baseUrl}bills?page=${page}&bill_type_flag=${bill_type_flag}`, {
headers: {Authorization: token},
page: page,
})
.then(res => {
dispatch({
type: 'billlist',
payload: res.data.data,
screen: bill_type_flag,
page: page,
});
})
.catch(err => console.log('log' + err));
};
export const getBillCardComment = (
token,
billId,
type,
modalId,
) => dispatch => {
console.log('bill id ', billId);
console.log('type ', type);
console.log('infocard', modalId);
axios
.get(`${baseUrl}bill/${billId}/card/${modalId}`, {
headers: {Authorization: token},
})
.then(res => {
console.log('comment', res.data);
dispatch({
type: 'Billlist_Comment',
payload: {
data: res.data,
billId,
type,
modalId,
},
});
})
.catch(err => console.log('comment' + err));
};
export const getBilldetail = (token, id) => dispatch => {
axios
.get(`${baseUrl}bills/${id}/details`, {
headers: {Authorization: token},
})
.then(res => {
dispatch({
type: 'billdetail',
payload: res.data,
});
})
.catch(err => console.log(err));
};
|
9544b98cc81f6223215a3dcce3a8b50c9b92aa7d
|
[
"JavaScript"
] | 79
|
JavaScript
|
Ritzrawal/nardmob
|
54162137d81c8d5903fed8022b679db1e91de2bc
|
8b79a9f513c90f53fcadf11997a61806b33e1b4d
|
refs/heads/master
|
<file_sep>var Board = {
selector: "#selector",
initialize: function(selector) {
this.selector = selector;
this.handlePostIts();
},
handlePostIts: function() {
var self = this;
$(this.selector).on('click', function(event){
console.log("board clicked");
var x = event.offsetX;
var y = event.offsetY;
self.renderPostIt(x, y);
});
},
renderPostIt: function(x, y) {
post = new PostIt(this.selector, x, y);
post.render();
}
};
function PostIt(selector, x, y) {
this.html = $('<div class="post-it"><div class="header"><a class="delete">X</a></div><p contenteditable="true" class="content">aersgoij</p></div>');
this.pos_x;
this.pos_y;
this.container;
var self = this;
function initialize(selector, x, y) {
self.pos_x = x;
self.pos_y = y;
self.container = selector;
self.makeCustomizable();
}
this.makeCustomizable = function() {
$(self.html).draggable({handle: ".header"});
self.html.click(function(event) {
event.stopPropagation();
$target = $(event.target);
if ($target.is(".delete")) {
$(this).remove();
}
});
}
this.render = function() {
self.html.css("top", self.pos_y).css("left", self.pos_x);
self.html.appendTo(self.container);
}
initialize(selector, x, y);
};
$(document).ready(function() {
Board.initialize('#board');
});
<file_sep>var Board = {
initialize: function(selector) {
$(selector).on('click', function(event){
var x = event.offsetX;
var y = event.offsetY;
post = new PostIt(x, y);
post.initialize(selector);
$(this).append(post.html(x, y));
});
}
};
function PostIt() {
this.html = function(x, y){
return '<div class="post-it" style="left:'+x+';top:'+y+'"><div class="header"><a class="delete">X</a></div><p contenteditable="true" class="content">aersgoij</p></div>'
}
this.initialize = function(board){
$(board).on('click', '.post-it', function(event){
event.stopPropagation();
$target = $(event.target);
if ($target.is(".header")) {
$(this).draggable();
} else if ($target.is(".delete")) {
$(this).remove();
}
});
}
};
$(document).ready(function() {
Board.initialize('#board');
});
|
b6699ad99c5d819ece5ee11824d301f89998944f
|
[
"JavaScript"
] | 2
|
JavaScript
|
waysidekoi/Post-it-OOJS
|
3df6de26ce22412971e8ff7c337c9b3b7e7e2006
|
147a95e783e479d6e051cb264fe3db35fdbd07b3
|
refs/heads/master
|
<file_sep>#!bin/bash
set -xe
if [ $# -lt 1 ]; then
echo "Usage: "
echo "CUDA_VISIBLE_DEVICES=0 bash run.sh train /ssd3/benchmark_results/cwh/logs"
exit
fi
task="$1"
run_log_path=${2:-$(pwd)}
device=${CUDA_VISIBLE_DEVICES//,/ }
arr=($device)
num_gpu_devices=${#arr[*]}
batch_size=1
log_file=${run_log_path}/Pytorch_Pix2Pix_GPU_cards_${num_gpu_devices}
log_parse_file=${log_file}
train(){
echo "Train on ${num_gpu_devices} GPUs"
echo "current CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES, gpus=$num_gpu_devices"
env no_proxy=localhost python3.5 train.py \
--dataroot ./datasets/cityscapes \
--name cityscapes_pix2pix \
--model pix2pix \
--netG unet_256 \
--direction BtoA \
--lambda_L1 100 \
--dataset_mode aligned \
--norm batch \
--pool_size 0 > ${log_file} 2>&1 &
train_pid=$!
sleep 200
kill -9 $train_pid
}
analysis_times(){
skip_step=$1
awk 'BEGIN{count=0}/time:/{
count_fields=6;
step_times[count]=$count_fields;
count+=1;
}END{
print "\n================ Benchmark Result ================"
print "total_step:", count
print "batch_size:", "'${batch_size}'"
if(count>1){
step_latency=0
step_latency_without_step0_avg=0
step_latency_without_step0_min=step_times['${skip_step}']
step_latency_without_step0_max=step_times['${skip_step}']
for(i=0;i<count;++i){
printf("%.5f", step_times[i])
step_latency+=step_times[i];
if(i>='${skip_step}'){
step_latency_without_step0_avg+=step_times[i];
if(step_times[i]<step_latency_without_step0_min){
step_latency_without_step0_min=step_times[i];
}
if(step_times[i]>step_latency_without_step0_max){
step_latency_without_step0_max=step_times[i];
}
}
}
step_latency/=count;
step_latency_without_step0_avg/=(count-'${skip_step}')
printf("average latency (origin result):\n")
printf("\tAvg: %.3f s/step\n", step_latency)
printf("\tFPS: %.3f images/s\n", "'${batch_size}'"/step_latency)
printf("average latency (skip '${skip_step}' steps):\n")
printf("\tAvg: %.3f s/step\n", step_latency_without_step0_avg)
printf("\tMin: %.3f s/step\n", step_latency_without_step0_min)
printf("\tMax: %.3f s/step\n", step_latency_without_step0_max)
printf("\tFPS: %.3f images/s\n", '${batch_size}'/step_latency_without_step0_avg)
printf("\n")
}
}' ${log_parse_file}
}
echo "Benchmark for $task"
echo "test speed"
job_bt=`date '+%Y%m%d%H%M%S'`
$task
job_et=`date '+%Y%m%d%H%M%S'`
hostname=`echo $(hostname)|awk -F '.baidu.com' '{print $1}'`
# monquery -n $hostname -i GPU_AVERAGE_UTILIZATION -s $job_bt -e $job_et -d 60 > gpu_avg_utilization
# monquery -n $hostname -i CPU_USER -s $job_bt -e $job_et -d 60 > cpu_use
cpu_num=$(cat /proc/cpuinfo | grep processor | wc -l)
gpu_num=$(nvidia-smi -L|wc -l)
# awk '{if(NR>1 && $3 >0){time+=$3;count+=1}} END{if(count>0) avg=time/count; else avg=0; printf("avg_gpu_use=%.2f\n" ,avg*'${gpu_num}')}' gpu_avg_utilization
# awk '{if(NR>1 && $3 >0){time+=$3;count+=1}} END{if(count>0) avg=time/count; else avg=0; printf("avg_cpu_use=%.2f\n" ,avg*'${cpu_num}')}' cpu_use
analysis_times 5
|
5537c4e00577f6ec5b0ab29553919ca08afdee80
|
[
"Shell"
] | 1
|
Shell
|
GPC-debug/benchmark
|
9a86b3155f20caf4cf83396472eb8a08c9287c1c
|
9a63376a04b035add9f19e8cc99b0385ed8485aa
|
refs/heads/master
|
<file_sep>var Cahier = {
actualBookings: [],
finishedBookings:[],
bookings: [{
owner: {id:0,name:"<NAME>",sex:"male"},
bookables: [],
participantCount: 1,
destination: "Non défini",
startComment: ""
}],
personalBookable: {
id: 0,
code: "Perso",
name:"Matériel personnel"
},
ProgressBarTexts: ["Nom", "Informations", "Embarcations", "Confirmation"],
getImageUrl: function (_bookable, size = 220) {
if (_bookable == Cahier.personalBookable) {
return 'url(img/icons/own-sail.png)';
}
else if (_bookable.image != null) {
return 'url(https://ichtus.club/image/' + _bookable.image.id + '/' + size + ')';
}
else {
return 'url(img/icons/no-picture.png)';
}
},
getFullName: function (booking = Cahier.bookings[0]) {
if (booking.guest) { return booking.guestName; } else { return booking.owner.name; }
},
getSingularOrPlural: function (nbr = Cahier.nbrParticipants, txt = " Participant") {
if (nbr == 0) {
return "Aucun";
}
else if (nbr == 1) {
return "1" + txt;
}
else {
return nbr + txt + "s";
}
},
getBookableName: function (booking) {
if (booking.bookables.length == 0) {
return "??";
}
else {
return booking.bookables[0].name;
}
},
getBookableCode: function (booking) {
if (booking.bookables.length == 0) {
return "";
}
else {
return booking.bookables[0].code;
}
},
// get Owner
getOwner: function (booking, wantImg = false, shortenOptions = { length: 10000, fontSize: 20 }) {
if (wantImg) {
var img = "img/icons/man.png";
if (booking.owner.sex == "female") { img = "img/icons/woman.png"; }
return "<div id='" + booking.owner.name + "' class='TableEntriesImg' style='background-image:url(" + img + "); display: inline-block;vertical-align: middle;'>" + "</div>" + "<div style=' display: inline-block;vertical-align: middle;'>" + booking.owner.name.shorten(shortenOptions.length - 40, shortenOptions.fontSize) + "</div>";
}
else {
return booking.owner.name;
}
},
//new Booking
newUserBooking: function () {
popUser(Cahier.bookings.length);
},
//new Booking
newGuestBooking: function () {
popGuest(Cahier.bookings.length);
},
// cancel - clearData
cancel: function () {
// #divCahierInfos
var allTabCahierFields = document.getElementsByClassName("TabCahierFields");
for (var i = 0; i < allTabCahierFields.length - 1; i++) { // -1 POUR EVITER LA TEXTAREA
allTabCahierFields[i].getElementsByTagName("input")[0].value = "";
allTabCahierFields[i].getElementsByTagName("input")[0].style.backgroundImage = "none";
allTabCahierFields[i].getElementsByTagName("input")[0].style.borderColor = "black";
allTabCahierFields[i].getElementsByTagName("div")[0].style.backgroundColor = "black";
}
document.getElementsByClassName("divTabCahierInfosStartComment")[0].getElementsByTagName("textarea")[0].value = "";
document.getElementsByClassName("divTabCahierInfosNbrInvites")[0].getElementsByTagName("input")[0].value = "1";
document.getElementsByClassName("divTabCahierInfosDestination")[0].getElementsByTagName("input")[0].value = "Baie";
$('inputTabCahierEquipmentElementsInputSearch').value = "";
$('divTabCahierEquipmentElementsSelectSort').getElementsByTagName("select")[0].getElementsByTagName("option")[0].selected = "selected";
$('divTabCahierEquipmentElementsSelectSort').getElementsByTagName("div")[0].style.backgroundImage = 'url("img/icons/sort-asc.png")';
document.getElementsByClassName('divTabCahierEquipmentChoiceInputCodeContainer')[0].getElementsByTagName('input')[0].value = "";
$('divTabCahierMember').getElementsByTagName("input")[0].value = "";
$("divTabCahierSearchResult").innerHTML = "";
changeProgress(1);
document.getElementsByClassName("divTabCahierEquipmentChoiceContainer")[0].children[3].children[0].classList.remove("buttonNonActive");
Requests.getActualBookingList();
Cahier.bookings = [{
owner: {},
bookables: [],
participantCount: 1,
destination: "Non défini",
startComment: ""
}];
//console.log("--> Cahier.cancel()");
},
deleteBooking: function (nbr) {
Cahier.bookings.splice(nbr, 1);
Cahier.actualizeConfirmation();
},
confirm: function () {
// if more bookables than participants
if (Cahier.bookings[0].participantCount < Cahier.bookings[0].bookables.length) {
popAlertMoreBookablesThanParticipants(Cahier.bookings[0].bookables.length, Cahier.bookings[0].participantCount);
}
else {
// if bookables already used
for (var i = 0; i < Cahier.bookings[0].bookables.length; i++) {
if (Cahier.bookings[0].bookables[i].available === false) {
break;
}
}
if (Cahier.bookings[0].bookables.length != i) {
popAlertBookablesNotAvailable();
}
else {
Requests.createBooking();
animate();
}
//console.log("--> Cahier.confirm()");
}
},
actualizeProgressBar: function () {
var allDivTabCahierProgressTexts = document.getElementsByClassName("divTabCahierProgressText");
for (var i = 0; i < allDivTabCahierProgressTexts.length; i++) {
if (i < currentProgress-1) {
switch (i) {
case 0:
allDivTabCahierProgressTexts[i].innerHTML = Cahier.bookings[0].owner.name;
break;
case 1:
allDivTabCahierProgressTexts[i].innerHTML = Cahier.bookings[0].destination + " & " + Cahier.bookings[0].participantCount + " P.";
break;
case 2:
var txt = "";
for (let k = 0; k < Cahier.bookings[0].bookables.length; k++) {
if (Cahier.bookings[0].bookables[k].code != null) {
txt += Cahier.bookings[0].bookables[k].code + ", ";
}
else {
txt += Cahier.bookings[0].bookables[k].name + ", ";
}
}
txt = txt.substring(0,txt.length - 2);
allDivTabCahierProgressTexts[i].innerHTML = txt;
break;
default:
break;
}
}
else {
allDivTabCahierProgressTexts[i].innerHTML = Cahier.ProgressBarTexts[i];
}
}
if (currentProgress == 1) {
$('divTabCahierProgressReturn').style.visibility = "hidden";
}
else {
$('divTabCahierProgressReturn').style.visibility = "visible";
$('divTabCahierProgressReturn').onclick = function () {
newTab(progessionTabNames[currentProgress - 1]);
};
}
},
actualizeConfirmation: function () {
if (currentTabElement.id == "divTabCahierConfirmation") {
loadConfirmation();
}
},
setOwner: function (nbr = 0, _owner = { id: "", name: "", sex: "female" }, force = false) {
var t = true;
if (!force) {
for (var i = 0; i < Cahier.actualBookings.length; i++) {
if (Cahier.actualBookings[i].owner.id == _owner.id) {
t = false;
break;
}
}
}
if (_owner.id == "2085") {
//alert("<NAME>");
}
if (t) {
Cahier.bookings[nbr].owner.id = _owner.id;
Cahier.bookings[nbr].owner.name = _owner.name;
// Cahier.bookings[nbr].owner.name = _owner.surName + " " + _owner.firstName;
Cahier.bookings[nbr].owner.sex = _owner.sex;
Cahier.actualizeConfirmation();
newTab("divTabCahierInfos");
}
else {
popAlertAlreadyHavingABooking(_owner);
}
},
addBookable: function (nbr = 0, _bookable = Cahier.personalBookable, _lastBooking) {
Cahier.bookings[nbr].bookables.push(_bookable);
if (_bookable == Cahier.personalBookable) {
document.getElementsByClassName("divTabCahierEquipmentChoiceContainer")[0].children[3].children[0].classList.add("buttonNonActive");
}
else if (_lastBooking != undefined) {
Cahier.bookings[nbr].bookables[Cahier.bookings[nbr].bookables.length - 1].available = _lastBooking.endDate == null ? false : true;
Cahier.bookings[nbr].bookables[Cahier.bookings[nbr].bookables.length - 1].lastBooking = _lastBooking;
//console.log("automatic", Cahier.bookings[nbr].bookables[Cahier.bookings[nbr].bookables.length - 1].available);
}
else {
Requests.getBookableLastBooking(_bookable.id);
//console.log("need request");
}
//console.log("setBookable(): ", nbr, Cahier.bookings[nbr].bookables);
actualizeBookableList();
Cahier.actualizeConfirmation();
},
actualizeAvailability: function (bookableId, bookings) {
for (var i = 0; i < Cahier.bookings[0].bookables.length; i++) {
if (Cahier.bookings[0].bookables[i].id === bookableId.toString()) {
break;
}
}
if (bookings.length !== 0) {
Cahier.bookings[0].bookables[i].available = bookings[0].endDate == null ? false : true;
Cahier.bookings[0].bookables[i].lastBooking = bookings[0];
}
else {
Cahier.bookings[0].bookables[i].available = true;
}
actualizeBookableList();
},
removeBookable: function (nbr = 0, _bookable = 0) {
for (var i = 0; i < Cahier.bookings[nbr].bookables.length; i++) {
if (Cahier.bookings[nbr].bookables[i].id == _bookable.id) {
break;
}
}
if (_bookable == Cahier.personalBookable) {
document.getElementsByClassName("divTabCahierEquipmentChoiceContainer")[0].children[3].children[0].classList.remove("buttonNonActive");
}
Cahier.bookings[nbr].bookables.splice(i, 1);
//console.log("removeBookable(): ", nbr, Cahier.bookings[nbr].bookables);
Cahier.actualizeConfirmation();
actualizeBookableList();
if (currentTabElement.id == "divTabCahierEquipmentElements") {
actualizeElements();
}
},
setInfos: function (nbr = 0, _participantCount = 1, _destination = "Non choisi", _startComment = "mmh.") {
Cahier.bookings[nbr].participantCount = _participantCount;
Cahier.bookings[nbr].destination = _destination;
Cahier.bookings[nbr].startComment = _startComment;
//console.log("setInfos(): ", nbr, Cahier.bookings[nbr].participantCount, Cahier.bookings[nbr].destination, Cahier.bookings[nbr].startComment);
Cahier.actualizeConfirmation();
}
};
function transformComment(txt, fill) {
txt = txt.replaceTxtByTxt("nft", " <img style='display:inline-block; vertical-align:middle;' src='img/comments/nft.png'/> ");
txt = txt.replaceTxtByTxt("joran", " joran<img style='display:inline-block; vertical-align:middle;' src='img/comments/joran.png'/> ", true);
txt = txt.replaceTxtByTxt("Joran", " Joran<img style='display:inline-block; vertical-align:middle;' src='img/comments/joran.png'/> ", true);
txt = txt.replaceTxtByTxt("soleil", "soleil<img style='display:inline-block; vertical-align:middle;' src='img/comments/soleil.png'/> ", true);
txt = txt.replaceTxtByTxt("Soleil", "Soleil<img style='display:inline-block; vertical-align:middle;' src='img/comments/soleil.png'/> ", true);
txt = txt.replaceTxtByTxt("Corto", "<img style='display:inline-block; vertical-align:middle;' src='img/comments/corto.png'/> ", true);
txt = txt.replaceTxtByTxt("Dimitri", "<img style='display:inline-block; vertical-align:middle;' src='img/comments/dimitri.png'/> ", true);
if (txt.length == 0 && fill) {
txt = "Pas de commentaire";
}
return txt;
}
function getStartCommentFromBooking(booking, fill = false) {
var txt = booking.startComment;
return transformComment(txt, fill);
}
function getEndCommentFromBooking(booking, fill = false) {
var txt = booking.endComment;
return transformComment(txt, fill);
}
<file_sep>var categories = ["Canoë & Kayak","SUP","Rame", "Planche à voile", "Voile"];
var categoriesValues = ["Canoe_Kayak", "SUP", "Aviron", "Planche", "Voile"];
function loadMateriel(container = $("divTabCahierEquipmentCategoriesContainer")) {
for (var i = 0; i < categories.length; i++) {
var d = document.createElement("div");
d.id = categories[i];
d.classList.add("BoxesContainer");
container.appendChild(d);
var d1 = div(d);
d1.id = i;
d1.classList.add("Boxes");
var dTop = div(d1);
dTop.classList.add("BoxesTop");
dTop.style.backgroundImage = "url(img/icons/chose.png)," + "url(img/categorie/" + categoriesValues[i] + ".png)";
var dBottom = document.createElement("div");
dBottom.classList.add("BoxesBottom");
d1.appendChild(dBottom);
var dBottomText1 = document.createElement("div");
dBottomText1.classList.add("BoxesBottomText1");
dBottom.appendChild(dBottomText1);
dBottomText1.innerHTML = categories[i];
var dBottomText2 = document.createElement("div");
dBottomText2.classList.add("BoxesBottomText2");
dBottom.appendChild(dBottomText2);
Requests.getBookableNbrForBookableTag(categoriesValues[i], dBottomText2, "", " " + categories[i] + "s");
if (categoriesValues[i] == "MP") { // useless
d.addEventListener("click", function () {
Cahier.bookableId = "";
Cahier.bookableName = "<NAME>";
newTab("divTabCahierInfos");
});
}
else {
d.addEventListener("click", function () {
newTab("divTabCahierEquipmentElements");
$('divTabCahierEquipmentElementsSelectCategorie').getElementsByTagName("select")[0].getElementsByTagName("option")[parseInt(this.getElementsByTagName("div")[0].id) + 0].selected = "selected";
changeSelectCategorie($('divTabCahierEquipmentElementsSelectCategorie').getElementsByTagName("select")[0]);
});
}
var opt = document.createElement("option");
opt.innerHTML = categories[i];
opt.value = categoriesValues[i];
$('divTabCahierEquipmentElementsSelectCategorie').getElementsByTagName("select")[0].appendChild(opt);
}
var opt = document.createElement("option");
opt.innerHTML = "Toutes les catégories";
opt.value = "all";
$('divTabCahierEquipmentElementsSelectCategorie').getElementsByTagName("select")[0].appendChild(opt);
}
<file_sep># Ichtus Reservations
Carnet de sortie
# Première installation sur un poste
NodeJs 8 est nécessaire, il ne faut l'installation qu'une seule fois sur un poste.
```
https://nodejs.org/en/download/
```
Installer github desktop
```
https://desktop.github.com/
```
# Installation du projet
Ajouter le repository dans github desktop n'importe où sur le disque (même une clé usb)
```
https://github.com/sambaptista/ichtus-reservations
```
Ouvrir l'invite de commande windows
```
Ouvrir le menu démarrer (win+r) et chercher invite de commande
```
Aller dans le répertoire du projet, p.ex :
```
c:\Users\???\sites\ichtus-reservations
```
Installer les dépendances :
```
npm install
```
# Travailler
Lancer le serveur, la page index.html s'ouvrira :
```
npm dev
```
<file_sep>var textToolTipGuest = "Un non-membre doit toujours être accompagné par un membre d'Ichtus. <br/> Il n'a donc pas le droit d'aller seul.";
var textToolTipUser = "Sortie pour les membres d'Ichtus<br/><br/>";
function loadActualBookings(_actualBookings) {
Cahier.actualBookings = _actualBookings;
$('divTabCahierTableActualBookings').previousElementSibling.innerHTML = "Sorties en cours (" + _actualBookings.length + ")";
var bookableNbr = 0;
var participantNbr = 0;
for (var i = 0; i < _actualBookings.length; i++) {
participantNbr += _actualBookings[i].participantCount;
bookableNbr += _actualBookings[i].bookables.length;
}
$('divTabCahierTableActualBookings').previousElementSibling.title = "bookableNbr" + bookableNbr + "participantNbr" + participantNbr;
var children = $('divTabCahierTables').children;
for (var i = 0; i < children.length; i++) {
if (children[i].id != "divTabCahierTableActualBookings" && children[i].id != "inputTabCahierActualBookingsSearch" && children[i].id != "divTabCahierActualBookingsSearchTitle" && children[i].id != "divTabCahierAlertButtonsLegend") {
$('divTabCahierTables').removeChild(children[i]);
i--;
}
}
Cahier.finishedBookings = [];
newBookingTable(new Date(), "Sorties terminées"); // tables sorties finies
$('inputTabCahierActualBookingsSearch').value = "";
actualizeActualBookings(Cahier.actualBookings);
}
function actualizeActualBookings(_actualBookings) {
var all = $('divTabCahierTableActualBookings').getElementsByClassName("TableEntries");
for (var i = 0; i < all.length; i++) {
if (all[i].id != "divTabCahierTableActualBookingsTopBar") {
all[i].parentNode.removeChild(all[i]);
i--;
}
}
if (_actualBookings.length == 0) {
var entry = div($('divTabCahierTableActualBookings'));
entry.classList.add("TableEntries");
entry.classList.add("TableEntriesHover");
div(entry);
}
for (var i = 0; i < _actualBookings.length; i++) {
var container = div($('divTabCahierTableActualBookings'));
container.id = i;
container.classList.add("TableEntries");
container.classList.add("TableEntriesHover");
if (options.seeWhichApplication) {
if (_actualBookings[i].creator.name.toLowerCase() === "booking only" || _actualBookings[i].creator.name.toLowerCase() === "<NAME>") { // parce que Fred s'est connecté sur ichtus.club grrr...
container.style.backgroundColor = "green";
}
else {
container.style.backgroundColor = "orange";
}
}
container.addEventListener("click", function (event) {
if (event.target.classList.contains("Buttons")) {
popBookingFinish(_actualBookings[this.id]);
}
else if (event.target.parentElement.classList.contains("TableEntriesBookableBox") || event.target.parentElement.parentElement.classList.contains("TableEntriesBookableBox")) {
// do nothing
}
else if (typeof event.target.getElementsByTagName("div")[0] != "undefined") {
if (event.target.getElementsByTagName("div")[0].classList.contains("Buttons")) {
popBookingFinish(_actualBookings[this.id]);
}
else {
popBookingInfos(_actualBookings[this.id]);
}
}
else {
popBookingInfos(_actualBookings[this.id]);
}
});
var divDate = div(container);
var maxHours = 24;
if (Date.now() - (new Date(_actualBookings[i].startDate)).getTime() > maxHours/6 * 60 * 60 * 1000) {
var d = div(divDate);
d.classList.add('TableEntriesAlert');
d.style.filter = "grayscale(1) invert(1)";
d.title = "+ de 4 heures";
divDate.title = "+ de 4 heures";
if (Date.now() - (new Date(_actualBookings[i].startDate)).getTime() > maxHours/2 * 60 * 60 * 1000) {
d.style.filter = "none";
d.style.filter = "grayscale(1)";
d.title = "+ de 12 heures";
divDate.title = "+ de 12 heures";
}
if (Date.now() - (new Date(_actualBookings[i].startDate)).getTime() > maxHours * 60 * 60 * 1000) {
d.style.filter = "none";
d.title = "+ de 24 heures";
divDate.title = "+ de 24 heures";
}
}
divDate.id = "SORTING" + (new Date(_actualBookings[i].startDate)).toISOString(); // for the sorting
divDate.innerHTML += (new Date(_actualBookings[i].startDate)).getNiceTime(":", true);
var participantCount = div(container);
participantCount.innerHTML = _actualBookings[i].participantCount;
participantCount.title = Cahier.getSingularOrPlural(_actualBookings[i].participantCount);
div(container).innerHTML = Cahier.getOwner(_actualBookings[i],true);
if (_actualBookings[i].bookables.length == 0) {
createBookingBookableBox(div(container));
}
else {
var c = div(container);
for (let k = 0; k < _actualBookings[i].bookables.length; k++) {
createBookingBookableBox(c, _actualBookings[i].bookables[k]);
}
}
div(container).innerHTML = _actualBookings[i].destination.shorten(150,16);
div(container).innerHTML = getStartCommentFromBooking(_actualBookings[i]).shorten(200, 16);
var c = div(container);
c.title = "Terminer cette sortie";
var btn = div(c);
btn.classList.add("Buttons");
}
sortTable($('divTabCahierTableActualBookings'));
}
// new search system
function bookingTableSearch(_table) {
var bookings;
txts = _table.previousElementSibling.previousElementSibling.value.split(" ");
// means finishedBookings
if (_table != $('divTabCahierTableActualBookings')) {
var all = document.getElementsByClassName("BookingsTable");
for (var i = 1; i < all.length; i++) {
if (all[i] == _table) {
break;
}
}
bookings = Cahier.finishedBookings[i - 1];
}
else { // means actualBookings
bookings = Cahier.actualBookings;
}
var result = [];
for (let t = 0; t < txts.length; t++) {
result[t] = [];
for (let b = 0; b < bookings.length; b++) {
var add = false;
// fields taken into account in the search
if (bookings[b].owner.name.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
}
else if ((new Date(bookings[b].startDate)).getNiceTime(":", true).includes(txts[t].toUpperCase())) {
add = true;
}
else if ((new Date(bookings[b].endDate)).getNiceTime(":", true).includes(txts[t].toUpperCase())) {
add = true;
}
else if (bookings[b].destination.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
}
else if (bookings[b].startComment.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
}
else if (bookings[b].endComment.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
}
else if (bookings[b].participantCount.toString().includes(txts[t])) {
add = true;
}
else {
for (let e = 0; e < bookings[b].bookables.length; e++) {
if (bookings[b].bookables[e].name.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
break;
}
else if (bookings[b].bookables[e].code.toUpperCase().includes(txts[t].toUpperCase())) {
add = true;
break;
}
}
}
if (add) {
result[t].push(bookings[b]);
}
}
}
// merge but only take the bookings which are in every search result !
var send = result.mergeAND();
if (_table == $('divTabCahierTableActualBookings')) {
actualizeActualBookings(send);
}
else {
actualizeFinishedBookingListForDay(send, _table);
}
}
function createBookingBookableBox(elem, bookable = {code:"ZZZ"}) {
var d = div(elem);
if (bookable.code != null) {
d.id = bookable.code;
}
else {
d.id = "999";
}
var img = div(d);
var code = div(d);
if (bookable == Cahier.personalBookable) {
img.style.backgroundImage = "url(img/icons/own-sail.png)";
code.style.backgroundImage = "none";
code.innerHTML = Cahier.personalBookable.name;
code.style.margin = "0px";
code.style.fontSize = "16px";
code.style.lineHeight = "35px";
d.style.cursor = "unset";
d.id = "ZZZZ"; // // to be at the bottom of the list
d.style.backgroundColor = "transparent";
}
else {
d.onclick = function () {
popBookable(bookable.id);
};
img.style.backgroundImage = Cahier.getImageUrl(bookable, 35);
if (bookable.code != null) {
code.innerHTML = bookable.code;
var codeLength = bookable.code.pixelLength(20);
div(d).innerHTML = bookable.name.shorten(170 - codeLength, 18);
}
else {
code.innerHTML = "";
div(d).innerHTML = bookable.name.shorten(170 - 0, 18);
}
}
elem.classList.add("TableEntriesBookableBox");
}
function loadTableTopBars(allTables = document.getElementsByClassName("BookingsTable")) {
for (var u = 0; u < allTables.length; u++) {
var table = allTables[u];
var top = table.getElementsByClassName("TableTopBar")[0];
var all = top.getElementsByTagName("div");
for (var i = 0; i < all.length; i = i + 2) {
all[i].getElementsByTagName("div")[0].style.backgroundImage = "url(img/icons/sort-asc.png)";
if (!(all[i].parentElement.id == 'divTabCahierTableActualBookingsTopBar' && all[i].id == '6')) { // not sort finish buttons
all[i].addEventListener("click", function () {
if (this.getElementsByTagName("div")[0].style.backgroundImage == 'url("img/icons/sort-desc.png")' || !(this.classList.contains("BookingsTopBarSorted"))) {
this.getElementsByTagName("div")[0].style.backgroundImage = "url(img/icons/sort-asc.png)";
order = 1;
}
else {
this.getElementsByTagName("div")[0].style.backgroundImage = "url(img/icons/sort-desc.png)";
order = -1;
}
var allButtons = this.parentElement.getElementsByTagName("div");
for (var k = 0; k < all.length; k = k + 2) {
if (allButtons[k] != this) {
allButtons[k].classList.remove("BookingsTopBarSorted");
allButtons[k].getElementsByTagName("div")[0].style.backgroundImage = "url(img/icons/sort-asc.png)";
}
}
this.classList.add("BookingsTopBarSorted");
sortTable(this.parentElement.parentElement);
});
}
}
}
}
function sortTable(table) {
var field = parseInt(table.getElementsByClassName("BookingsTopBarSorted")[0].id);
var order = function () {
if (table.getElementsByClassName("BookingsTopBarSorted")[0].getElementsByTagName("div")[0].style.backgroundImage == 'url("img/icons/sort-desc.png")') {
return -1;
}
else {
return 1;
}
};
var all = table.getElementsByClassName("TableEntries");
var switching = true;
while (switching) {
switching = false;
for (var i = 1; i < all.length - 1; i++) {
if (getSortingText(all[i].children[field]) > getSortingText(all[i + 1].children[field]) && order() == 1 || getSortingText(all[i].children[field]) < getSortingText(all[i + 1].children[field]) && order() == -1) {
all[i].parentElement.insertBefore(all[i + 1], all[i]);
switching = true;
}
}
}
}
function getSortingText(elem) {
if (elem.id.indexOf("SORTING") == 0) {
return elem.id;
}
else {
return elem.innerHTML.toUpperCase();
}
}
function newBookingTable(date,title = "?") {
if (title == "?"){title = date.getNiceDate();}
Requests.getFinishedBookingListForDay(date, undefined,title);
$('divTabCahierButtonMoreBookingsContainer').getElementsByTagName("div")[0].id = date.getPreviousDate();
$('divTabCahierButtonMoreBookingsContainer').getElementsByTagName("div")[0].innerHTML = "Charger les sorties du " + date.getPreviousDate().getNiceDate(true);
}
function createBookingsTable(date,title) {
var input = document.createElement("input");
input.type = "text";
input.value = "";
input.spellcheck = false;
input.placeholder = "Rechercher";
input.onkeyup = function () {
bookingTableSearch(table);
};
$('divTabCahierTables').appendChild(input);
var t = div($('divTabCahierTables'));
t.classList.add("BookingsTableText");
if (title == "?") {
title = date.getNiceDate();
}
t.innerHTML = title;
var table = div($('divTabCahierTables'));
table.id = date.toISOString();
table.classList.add("BookingsTable");
var topBar = div(table);
topBar.classList.add("TableEntries");
topBar.classList.add("TableTopBar");
var fields = ["", "", "", "Responsable", "Embarcations", "Destination", "Commentaire de départ", "Commentaire d'arrivée"];
var images = ["icons/start", "icons/end","icons/participant-count","icons/responsible","icons/sail", "icons/destination", "icons/start-comment", "icons/end-comment"];
for (var i = 0; i < fields.length; i++) {
var d = div(topBar);
d.id = i;
div(d);
var img = document.createElement("img");
img.src = "img/" + images[i] + ".png";
img.alt = "?";
d.appendChild(img);
d.innerHTML += fields[i];
}
topBar.getElementsByTagName("div")[0].classList.add("BookingsTopBarSorted");
var b = div(table);
b.style.position = "absolute";
b.style.width = "100%";
b.style.height = "2px";
b.style.backgroundColor = "gray";
b.style.zIndex = "2";
loadTableTopBars([table]);
return table;
}
function createNoBookingMessage(date) {
var t = div($('divTabCahierTables'));
t.classList.add("BookingsTableTextNoBooking");
t.innerHTML = "Aucune sortie le "+ date.getNiceDate();
}
function actualizeFinishedBookingListForDay(bookings,table) {
var all = table.getElementsByClassName("TableEntries");
for (var i = 0; i < all.length; i++) {
if (all[i].classList.contains("TableTopBar") === false) {
all[i].parentNode.removeChild(all[i]);
i--;
}
}
if (bookings.length === 0) {
var ent = div(table);
ent.classList.add("TableEntries");
ent.classList.add("TableEntriesHover");
div(ent);
}
else {
for (let i = 0; i < bookings.length; i++) {
var entry = div(table);
entry.id = i;
entry.classList.add("TableEntries");
entry.classList.add("TableEntriesHover");
entry.addEventListener("click", function (event) {
if (!(event.target.parentElement.classList.contains("TableEntriesBookableBox") || event.target.parentElement.parentElement.classList.contains("TableEntriesBookableBox"))) {
popBookingInfos(bookings[this.id]);
}
});
if (options.seeWhichApplication) {
if (bookings[i].creator.name.toLowerCase() === "booking only" || bookings[i].creator.name.toLowerCase() === "<NAME>") { // parce que Fred s'est connecté sur ichtus.club grrr...
entry.style.backgroundColor = "green";
}
else {
entry.style.backgroundColor = "orange";
}
}
div(entry).innerHTML = (new Date(bookings[i].startDate)).getNiceTime(":", true);
div(entry).innerHTML = (new Date(bookings[i].endDate)).getNiceTime(":", true);
div(entry).innerHTML = bookings[i].participantCount;
div(entry).innerHTML = Cahier.getOwner(bookings[i],true);
if (bookings[i].bookables.length === 0) {
createBookingBookableBox(div(entry));
}
else {
var c = div(entry);
for (let k = 0; k < bookings[i].bookables.length; k++) {
createBookingBookableBox(c, bookings[i].bookables[k]);
}
}
div(entry).innerHTML = bookings[i].destination.shorten(150, 16);
div(entry).innerHTML = getStartCommentFromBooking(bookings[i]).shorten(200, 16); // "".shorten(200, 200);//getStartCommentFromBooking(bookings[i]);//.startComment.shorten(200, 20); // BIZARRRRERELRKJASéDL KFJASéDLF JKAéSLDKFJ
div(entry).innerHTML = getEndCommentFromBooking(bookings[i]).shorten(200,16);//.endComment.shorten(200, 20);
}
sortTable(table);
}
}
<file_sep>function popBookable(bookableId, justPreview = true, nbr = 0, modal = openPopUp()) {
Requests.getBookableInfos(nbr, bookableId, modal);
if (modal == $('divTabCahierEquipmentBookableContainer')) {
modal.innerHTML = "";
}
var pop = div(modal);
pop.classList.add("Boxes");
pop.classList.add("divTabCahierEquipmentElementsPopUp");
if (modal != $('divTabCahierEquipmentBookableContainer')) {
var close = div(pop);
close.className = "divPopUpClose";
close.onclick = function () {
closePopUp({ target: modal }, modal);
};
}
else {
div(pop);
newTab('divTabCahierEquipmentBookable');
}
var imgContainer = div(pop);
var descriptionTitle = div(pop);
descriptionTitle.innerHTML = "Description";
var description = div(pop); // description box
var btn2 = div(pop);
btn2.classList.add("Buttons"); btn2.classList.add("ReturnButtons");
btn2.style.visibility = "hidden";
btn2.innerHTML = "Historique";
if (!justPreview) {
var btn = div(pop);
btn.classList.add("Buttons"); btn.classList.add("ValidateButtons");
btn.innerHTML = "Choisir";
btn.setAttribute('tabindex', '0');
btn.focus();
}
else {
// description.style.width = "660px";
}
var textsContainer = div(pop);
textsContainer.className = "divTabCahierEquipmentElementsContainerTextsContainer";
div(textsContainer);
div(textsContainer);
div(textsContainer);
div(textsContainer);
}
var eventListenerFunction;
function actualizePopBookable(nbr, bookable,bookings, elem) {
elem.getElementsByTagName("div")[2].style.backgroundImage = Cahier.getImageUrl(bookable);
elem.getElementsByClassName('divTabCahierEquipmentElementsPopUp')[0].getElementsByTagName("div")[3].innerHTML = bookable.description;
var textsContainer = elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0];
if (bookable.code != null) {
textsContainer.getElementsByTagName("div")[0].innerHTML = bookable.code;
}
else {
textsContainer.getElementsByTagName("div")[0].innerHTML = "";
}
textsContainer.getElementsByTagName("div")[1].innerHTML = bookable.name.shorten(420, 20);
if (options.showRemarks) {
div(textsContainer).innerHTML = bookable.remarks;
}
else {
div(textsContainer);
}
for (var i = 0; i < bookable.licenses.length; i++) {
var lic = div(textsContainer);
lic.innerHTML = "<asdf style='font-weight:bold'>License requise: </asdf >" + bookable.licenses[i].name ;
}
if (bookings.length != 0) {
if (currentTabElement.id != "divTabCahier" && bookings.items[0].endDate == null) {
//console.log("embarcation déjà utilisée");
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].innerHTML = "Cette embarcation semble déjà être utlisée par " + Cahier.getOwner(bookings.items[0], false);
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].style.color = "red";
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].style.backgroundImage = "url(img/icons/alert.png)";
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].style.paddingLeft = "40px";
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].style.backgroundSize = "25px";
}
else {
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[2].innerHTML = "Dernière utilisation le " + (new Date(bookings.items[0].startDate)).getNiceDate() + "<br/> Par " + Cahier.getOwner(bookings.items[0], false);
}
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[3].innerHTML = Cahier.getSingularOrPlural(bookings.length, " sortie");
elem.getElementsByClassName('Buttons')[0].style.visibility = "visible";
elem.getElementsByClassName('Buttons')[0].addEventListener("click", function () {
popBookableHistory(this.parentElement.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[1].id);
});
}
else {
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[3].innerHTML = "Encore aucune sortie enregistrée";
elem.getElementsByClassName('Buttons')[0].style.visibility = "hidden";
}
if (elem.getElementsByClassName("ValidateButtons").length == 1) { // if !justPreview
var choseFunction = function () {
Cahier.addBookable(nbr, bookable, bookings.items[0]);
newTab('divTabCahierEquipmentChoice');
$('divTabCahierEquipmentChoice').getElementsByClassName('divTabCahierEquipmentChoiceInputCodeContainer')[0].getElementsByTagName("input")[0].value = "";
$('divTabCahierEquipmentChoice').getElementsByClassName('divTabCahierEquipmentChoiceInputCodeContainer')[0].getElementsByTagName("input")[0].nextElementSibling.nextElementSibling.children[0].classList.remove("activated");
};
elem.getElementsByClassName("ValidateButtons")[0].addEventListener("click", choseFunction);
eventListenerFunction = function (event) {
if (event.keyCode == 13 && elem.id == "divModal" + lastModals) { // so the highest modal open
// choseFunction();
}
};
// setTimeout(function () { document.body.addEventListener("keyup", eventListenerFunction); //console.log("added event listener"); },4000);
// ("keyup", eventListenerFunction);
}
//if (bookable.remarks != "" && options.showRemarks) {
// var bar = grayBar(elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0]);
// bar.style.position = "absolute";
// bar.style.bottom = "-13px";
// bar.style.width = "100%";
//}
elem.getElementsByClassName('divTabCahierEquipmentElementsContainerTextsContainer')[0].getElementsByTagName("div")[1].id = bookable.id;
}
<file_sep>var currentBookables;
function loadElements(bookables ,nbr = 0) {
currentBookables = bookables;
document.getElementsByClassName("divTabCahierEquipmentElementsContainer")[0].innerHTML = "";
var codes = [];
for (var i = 0; i < Cahier.bookings[nbr].bookables.length; i++) {
codes.push(Cahier.bookings[nbr].bookables[i].id);
}
for (var i = 0; i < bookables.length; i++) {
container = document.createElement("div");
container.id = i;
if (bookables[i].used === true) {
container.classList.add("used");
container.title = "Cette embarcation est déjà utilisée";
}
var x = codes.findIndex(bookables[i].id);
if (x !== -1) {
container.classList.add("selected");
container.onclick = function (event) {
if (!(event.target.classList.contains("infoJS"))) {
Cahier.removeBookable(nbr, bookables[this.id]);
actualizeElements();
}
};
}
else {
container.onclick = function (event) {
if (!(event.target.classList.contains("infoJS"))) {
Cahier.addBookable(nbr, bookables[this.id]);
actualizeElements();
}
};
}
document.getElementsByClassName("divTabCahierEquipmentElementsContainer")[0].appendChild(container);
var secondContainer = document.createElement("div");
container.appendChild(secondContainer);
var size = document.createElement("div");
if (bookables[i].code != null) {
size.innerHTML = bookables[i].code;
if (bookables[i].code.length > 4) {
size.style.fontSize = "17px";
}
}
else {
size.innerHTML = "";
}
secondContainer.appendChild(size);
var bottom = document.createElement("div");
secondContainer.appendChild(bottom);
var brand = div(bottom);
brand.innerHTML = bookables[i].name.shorten(160*2,20);
// model = div(bottom);
// model.innerHTML = bookables[i].id;
var background = div(secondContainer);
background.style.backgroundImage = Cahier.getImageUrl(bookables[i]);
var selection = div(secondContainer);
var info = div(secondContainer);
info.id = bookables[i].id;
info.classList.add("infoJS");
info.onclick = function () {
popBookable(this.id);
};
if (bookables[i].licenses.length > 0) {
var license = div(secondContainer);
license.title = bookables[i].licenses[0].name;
}
if (bookables[i].used) {
var used = div(container);
used.innerHTML = "Déjà utilisé";
}
}
if (bookables.length == 0) {
var d = div(document.getElementsByClassName("divTabCahierEquipmentElementsContainer")[0]);
d.innerHTML = "Aucun résultat";
//console.log('Aucun résultat');
}
}
function actualizeElements() {
var bookables = currentBookables;
var codes = [];
for (var i = 0; i < Cahier.bookings[0].bookables.length; i++) {
codes.push(Cahier.bookings[0].bookables[i].id);
}
var containers = document.getElementsByClassName("divTabCahierEquipmentElementsContainer")[0].children;
for (var i = 0; i < containers.length; i++) {
var container = containers[i];
if (codes.findIndex(bookables[i].id) != -1) {
container.classList.add("selected");
container.onclick = function (event) {
if (!(event.target.classList.contains("infoJS"))) {
Cahier.removeBookable(0, bookables[this.id]);
actualizeElements();
}
};
}
else {
container.classList.remove("selected");
container.onclick = function (event) {
if (!(event.target.classList.contains("infoJS"))) {
Cahier.addBookable(0, bookables[this.id]);
actualizeElements();
}
};
}
}
}
function clickSortIcon(elem) {
if (elem.style.backgroundImage == 'url("img/icons/sort-desc.png")') {
elem.style.backgroundImage = 'url("img/icons/sort-asc.png")';
}
else {
elem.style.backgroundImage = 'url("img/icons/sort-desc.png")';
}
}
function changeSelectCategorie(elem) {
$('divTabCahierEquipmentElementsSelectCategorie').getElementsByTagName("div")[0].style.backgroundImage = "url(img/categorie/" + elem.value + ".png)";
}
<file_sep>function loadJs(filePath, cb) {
// Create a script tag, set its source
var scriptTag = document.createElement("script");
// And listen to it
if (cb) {
scriptTag.onload = cb();
}
// Make sure this file actually loads instead of a cached version
var cacheBuster = "?time=" + new Date().getTime();
// Set the type of file and where it can be found
scriptTag.type = "text/javascript";
scriptTag.src = filePath + cacheBuster;
// Finally add it to the <head>
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
<file_sep>function popBookableHistory(bookableId) {
currentYear = -1;
currentMonth = -1;
currentDay = -1;
var modal = openPopUp();
Requests.getBookableHistory(bookableId, modal, new Date());
var container;
container = div(modal);
container.classList.add("Boxes");
container.style.position = "absolute";
container.style.width = "700px";
container.style.top = "50%";
container.style.marginLeft = "0px";
container.style.left = "50%";
container.style.transform = "translate(-50%,-50%)";
container.style.padding = "10px";
container.classList.add("PopUpBookableHistoryContainer");
container.innerHTML += '<div style=" font-size:25px; text-align:center; color:black;">Historique</div>';
grayBar(container, 5);
var close = div(container);
close.className = "divPopUpClose";
close.onclick = function () {
closePopUp({ target: modal }, modal);
};
var scroll = div(container);
scroll.className = "PopUpBookableHistoryContainerScroll";
}
var currentYear = -1;
var currentMonth = -1;
var currentDay = -1;
function actualizePopBookableHistory(bookings, elem) {
var lastDate = new Date(bookings[bookings.length - 1].startDate); // avant changeDaySorting !
bookings = changeDaySorting(bookings);
var bookableId = bookings[0].bookable.id;
var container = elem.getElementsByTagName("div")[0];
container.getElementsByTagName("div")[0].innerHTML = ("Historique de " + bookings[0].bookable.name).shorten(600,25);
var scroll = container.getElementsByClassName("PopUpBookableHistoryContainerScroll")[0];
if (scroll.getElementsByClassName("Buttons").length ==1 ) {
scroll.removeChild(scroll.getElementsByClassName("Buttons")[0]);
scroll.removeChild(scroll.getElementsByTagName("br")[0]);
}
for (var i = 0; i < bookings.length; i++) {
var d = new Date(bookings[i].startDate);
var newYear = d.getFullYear();
if (newYear != currentYear) {
var year = popUpYear(scroll, newYear);
var start = new Date(d.getFullYear(), 0, 1, 0, 0, 1);
var end = new Date(d.getFullYear() + 1, 0, 1, 0, 0, 0, 1);
Requests.getBookingsNbrBetween(start.toISOString(), end.toISOString(), bookableId, year);
}
var newMonth = d.getMonth();
if (newMonth != currentMonth || newYear != currentYear) {
var month = popUpMonth(scroll, Mois[newMonth]);
var start = new Date(d.getFullYear(), newMonth, 1, 0, 0, 0, 1);
var end = new Date(d.getFullYear(), newMonth + 1, 1, 0, 0, 0, 1);
Requests.getBookingsNbrBetween(start.toISOString(), end.toISOString(), bookableId, month);
}
var newDay = d.getDate();
if (newDay != currentDay || newMonth != currentMonth || newYear != currentYear) {
var all = scroll.getElementsByClassName("PopUpMonth");
var day = popUpDay(all[all.length-1], d.getNiceDate(true));
var start = new Date(d.getFullYear(), newMonth, newDay, 0, 0, 0, 1);
var end = new Date(d.getFullYear(), newMonth , newDay+1, 0, 0, 0, 1);
Requests.getBookingsNbrBetween(start.toISOString(), end.toISOString(), bookableId, day,false);
}
currentYear = newYear;
currentMonth = newMonth;
currentDay = newDay;
var all = scroll.getElementsByClassName("PopUpDay");
var sortie = div(all[all.length-1]);
sortie.id = i;
sortie.classList.add("PopUpSortie");
sortie.onclick = function () {
popBooking(bookings[this.id]);
};
div(sortie).innerHTML = d.getNiceTime();
var c = div(sortie);
div(c).innerHTML = Cahier.getOwner(bookings[i], true, { length: 240, fontSize: 20 },true);
div(c).innerHTML = bookings[i].destination.shorten(150, 20);
div(c).innerHTML = getStartCommentFromBooking(bookings[i]).shorten(150, 15);
}
var space = document.createElement("br");
scroll.appendChild(space);
var plus = div(scroll);
plus.classList.add("Buttons");
plus.classList.add("NormalButtons");
plus.innerHTML = "Afficher plus";
plus.onclick = function () {
Requests.getBookableHistory(bookableId, elem, lastDate);
};
if (currentMonth != -1) {
// scroll.scrollTo(0, scroll.scrollHeight);
}
}
function changeDaySorting(bookings) {
var oldDate = (new Date(bookings[0].startDate)).getDate();
var oldMonth = (new Date(bookings[0].startDate)).getMonth();
var result = bookings;
var c = 0;
for (var i = 1; i < result.length; i++) {
var newDate = (new Date(result[i].startDate)).getDate();
var newMonth = (new Date(result[i].startDate)).getMonth();
if (oldDate == newDate && oldMonth == newMonth) {
c++;
//console.log("i:" + i, "c++");
}
else if (c!= 0) { //c!=0
var i1 = i - 1 - c;
var i2 = i - 1;
c = 0;
//console.log("i:" + i,"switch - " + i1 + "to" + i2);
result.inverse(i1, i2);
}
//console.log("i:" + i, "old:" + oldDate + "/" + oldMonth + "<br/>" + "new:" + newDate + "/" + newMonth + "<br/> c:" + c);
oldDate = newDate;
oldMonth = newMonth;
}
if (c != 0) {
var i1 = i - 1 - c;
var i2 = i - 1;
result.inverse(i1, i2);
//console.log("switch",i1, i2);
}
return result;
}
function popUpYear (container,txt) {
var c = div(container);
c.className = "PopUpYear";
div(c);
var inner = div(c);
inner.innerHTML = txt;
var nbr = div(div(c));
return nbr;
}
function popUpMonth(container, txt) {
var c = div(container);
c.className = "PopUpMonth";
div(c);
var inner = div(c);
inner.innerHTML = txt;
var nbr = div(div(c));
return nbr;
}
function popUpDay(container, txt) {
var c = div(container);
c.className = "PopUpDay";
var infos = div(c);
div(infos);
var inner = div(infos);
inner.innerHTML = txt;
var nbr = div(div(infos));
return nbr;
}<file_sep>function loadCahierEquipmentChoice(loc = $('divTabCahierEquipmentChoice').getElementsByClassName("MaterielChoiceContainer")[0],nbr = 0) {
var isTab = true;
if (loc != $('divTabCahierEquipmentChoice').getElementsByClassName("MaterielChoiceContainer")[0]) {
isTab = false;
}
var container = div(loc);
container.classList.add("divTabCahierEquipmentChoiceContainer");
var c = div(container);
c.classList.add("divTabCahierEquipmentChoiceInputCodeContainer");
var i = input(c, "Taper un code...");
i.onkeyup = function (event) {
if (event.keyCode == 13) {
Requests.getBookableByCode(this,nbr);
}
if (this.value != '') {
this.nextElementSibling.nextElementSibling.children[0].classList.add("activated");
}
else { this.nextElementSibling.nextElementSibling.children[0].classList.remove("activated"); }
};
if (!isTab) {
i.focus();
}
div(c);
var btn = div(div(c));
btn.classList.add("ValidateButtons", "Buttons");
btn.title = "Choisir cette embarcation";
btn.onclick = function () { Requests.getBookableByCode(this.parentElement.previousElementSibling.previousElementSibling,nbr); };
div(container).innerHTML = "Par exemple: C401";
div(container).innerHTML = "Ou";
var btnContainer = div(container);
var btn1 = div(btnContainer);
btn1.innerHTML = "Prendre du matériel personnel";
btn1.title = "Prendre du matériel personnel";
btn1.style.fontSize = "19px";
if (isTab) {
btn1.onclick = function () {
var t = true;
for (let k = 0; k < Cahier.bookings[0].bookables.length; k++) {
if (Cahier.bookings[0].bookables[k] == Cahier.personalBookable) {
t = false;
break;
}
}
if (t) {
Cahier.addBookable(nbr);
}
};
}
else {
btn1.onclick = function () {
Cahier.addBookable(nbr);
closePopUp("last");
};
}
btn1.classList.add("NormalButtons", "Buttons");
var btn2 = div(btnContainer);
btn2.innerHTML = "Voir la liste du matériel";
if (isTab) {
btn2.onclick = function () { newTab('divTabCahierEquipmentCategories'); };
}
else {
// btn2.onclick = function () { alert('a'); };
btn2.style.backgroundColor = "lightgray";
btn2.style.opacity = 0.5;
btn2.style.cursor = "no-drop";
}
btn2.classList.add("NormalButtons", "Buttons");
btn2.title = "Voir la liste du matériel";
}<file_sep>function popStats() {
var elem = openPopUp();
var container;
container = div(elem);
container.classList.add("PopUpStatsContainer");
container.classList.add("Boxes");
var close = div(container);
close.className = "divPopUpClose";
close.onclick = function () {
closePopUp({ target: elem }, elem);
};
var d = div(container);
d.style.textAlign = "center";
d.style.fontSize = "25px";
d.innerHTML = "Statistiques";
grayBar(container, 5);
div(container).innerHTML = "Sorties";
div(container).innerHTML = "Jour";
var t = div(container);
t.classList.add("PopUpStatsContainerTitle");
div(t);
var c = div(container);
c.classList.add("divStatsContainer");
loadStats();
}
function loadStats(end = new Date()) {
var start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0, 1);
var t = document.getElementsByClassName("PopUpStatsContainerTitle")[0];
t.innerHTML = "";
var btn = div(t);
btn.onclick = function () {
loadStats(new Date(start.getFullYear(), start.getMonth(), 0, 23, 59, 59, 99)); // day 0
};
var btn2 = div(t);
if (new Date(end.getFullYear(), end.getMonth()+1, 0, 0, 0, 0, 1) > new Date()) {
btn2.style.visibility = "hidden";
}
else {
btn2.onclick = function () {
loadStats(new Date(start.getFullYear(), start.getMonth() + 2, 0, 23, 59, 59, 99)); // day 0
};
}
div(t).innerHTML = Mois[start.getMonth()];
var c = document.getElementsByClassName("divStatsContainer")[0];
c.innerHTML = "";
var scale = div(c);
var center = div(c);
var legend = div(c);
div(scale);
div(scale);
div(scale).innerHTML = 0;
div(legend);
div(legend);
Requests.getStats(start, end, c);
}
function actualizeStats(start, end, elem, bookings) {
var stats = [];
var elapsedTime = Math.abs(end.getTime() - start.getTime());
var daysNbr = parseInt(elapsedTime / (1000 * 3600 * 24));
for (var i = 0; i < daysNbr+1; i++) {
stats.push(0);
}
for (var i = 0; i < bookings.length; i++) {
var date = new Date(bookings[i].startDate);
var elapsedTime = Math.abs(date.getTime() - start.getTime());
var daysNbr = parseInt(elapsedTime / (1000 * 3600 * 24));
stats[daysNbr]++;
}
div(elem.parentElement.getElementsByClassName("PopUpStatsContainerTitle")[0]).innerHTML = Cahier.getSingularOrPlural(bookings.length, " sortie");
var scale = elem.children[0];
var center = elem.children[1];
var legend = elem.children[2];
var legends = Jours.concat(Jours).concat(Jours);
var max = stats.max();
for (var i = 0; i < stats.length; i++) {
var d = div(center);
d.style.width = 100 / stats.length + "%";
var bar = div(d);
bar.style.height = stats[i] / max * 90 + "%";
var nbr = div(d);
nbr.innerHTML = stats[i];
var l = div(legend);
l.style.width = 100 / stats.length + "%";
if (i % parseInt(stats.length / 10) == 0 || stats.length / 10 < 1) {
var date = new Date(start);
date.setDate(start.getDate() + i);
div(l).innerHTML = date.getDate();
}
}
var step = 1;
var count = (max - max % step) / step;
while (count > 8) {
if (step.toString().indexOf("1") != -1) {
step = step * 2.5;
}
else if (step.toString().indexOf("2") != -1) {
step = step * 2;
}
else if (step.toString().indexOf("5") != -1) {
step = step * 2;
}
count = (max - max % step) / step;
}
for (var i = 1; i < count + 1; i++) {
var s = div(scale);
s.style.top = 100 - i * step / max * 90 + "%";
s.innerHTML = i * step;
div(s);
div(s);
}
}
Array.prototype.max = function () {
var m = this[0];
for (var i = 1; i < this.length; i++) {
if (this[i] > m) {
m = this[i];
}
}
return m;
};<file_sep>//var uri;
//uri = 'http://localhost/IchtusWebApi/api/ConsoleValue/2015/06/14';
//uri = 'api/ActualValue';
//uri = 'api/ConsoleValue';
//uri = 'api/GarminValue';
//uri = 'http://fsmarin.mooo.com/IchtusWebApi/api/GarminValue';
////uri = 'api/ConsoleValue';
//$(document).ready(function () {
// console.log("ok");
// // Send an AJAX request
// $.getJSON(uri)
// .done(function (data) {
// console.log(data);
// console.log(data.windDirectionDegrees);
// // On success, 'data' contains a list of products.
// $.each(data, function (key, item) {
// // Add a list item for the product.
// $('<li>', { text: formatItem(item) }).appendTo($('#products'));
// });
// });
//});<file_sep>function popLogin() {
var elem = openPopUp();
var container;
container = div(elem);
container.classList.add("PopUpLoginContainer");
container.classList.add("Boxes");
var close = div(container);
close.className = "divPopUpClose";
close.onclick = function () {
closePopUp({ target: elem }, elem);
};
var d = div(container);
d.style.textAlign = "center";
d.style.fontSize = "25px";
d.innerHTML = "Connexion";
grayBar(container, 5);
div(container);
var i = input(container);
i.type = "password";
i.placeholder = "<PASSWORD>";
i.addEventListener("keyup", function (event) {if (event.keyCode == 13) { Requests.login(this.value); } });
var b = div(container);
b.classList.add("Buttons");
b.classList.add("ValidateButtons");
b.innerHTML = "Connexion";
b.addEventListener("click", function () { Requests.login(this.parentElement.getElementsByTagName("input")[0].value); });
setTimeout(function () {
i.focus();
setTimeout(function () {
if (i.value != "" && options.automaticConnexion) {
console.warn("Connexion automatique");
Requests.login(i.value);
}
else {
console.warn("Pas de connexion automatique");
}
}, 50);
}, 800);
}<file_sep>//ProgressBar
var progessionTabNames = ["divTabCahier","divTabCahierMember", "divTabCahierInfos", "divTabCahierEquipmentChoice", "divTabCahierConfirmation"];
function createProgressBar() {
for (var i = 0; i < 4; i++) {
var divStep = document.createElement("div");
divStep.classList.add("divTabCahierProgressStep");
divStep.style.left = (6 + 26 * i) + "%";
divStep.addEventListener("click", function () {
var c = (parseInt(this.style.left) - 6) / 26 +1;
if (c <= currentProgress) {
newTab(progessionTabNames[c]);
}
});
$("divTabCahierProgress").appendChild(divStep);
divStep.classList.add("divTabCahierProgressStepCompleted");
var divNumber = document.createElement("div");
divNumber.classList.add("divTabCahierProgressNumber");
divNumber.innerHTML = (i + 1);
divStep.appendChild(divNumber);
var divCircle = document.createElement("div");
divCircle.classList.add("divTabCahierProgressCircle");
divStep.appendChild(divCircle);
var divText = document.createElement("div");
divText.classList.add("divTabCahierProgressText");
divText.innerHTML = Cahier.ProgressBarTexts[i];
divStep.appendChild(divText);
}
var divBar = document.createElement("div");
divBar.id = "divTabCahierProgressBar";
divBar.style.left = (11 + 26 * 0) + "%";
$("divTabCahierProgress").appendChild(divBar);
var divBarBlue = document.createElement("div");
divBarBlue.id = "divTabCahierProgressBarBlue";
divBarBlue.style.left = (11 + 26 * 0) + "%";
$("divTabCahierProgress").appendChild(divBarBlue);
}
var currentProgress = 0;
function changeProgress(c) {
//var sign;
//if (c != currentProgress) {
// sign = Math.abs(c - currentProgress) / (c - currentProgress);
//}
currentProgress = c;
for (var i = 1; i < 5; i++) {
document.getElementsByClassName("divTabCahierProgressStep")[i-1].className = "divTabCahierProgressStep";
if (i < c) {
document.getElementsByClassName("divTabCahierProgressStep")[i-1].classList.add("divTabCahierProgressStepCompleted");
}
else if (i == c) {
document.getElementsByClassName("divTabCahierProgressStep")[i-1].classList.add("divTabCahierProgressStepCurrent");
}
else {
document.getElementsByClassName("divTabCahierProgressStep")[i-1].classList.add("divTabCahierProgressStepIncompleted");
}
}
$("divTabCahierProgressBarBlue").style.width = (c-1) * 26 + "%";
}<file_sep>function popUser(nbr = 0, elem = openPopUp()) {
var container;
container = div(elem);
container.id = nbr;
container.classList.add("PopUpUserContainer");
if (elem != $("divTabCahierMemberContainer")) {
container.classList.add("Boxes");
var close = div(container);
close.className = "divPopUpClose";
close.onclick = function () {
closePopUp({ target: elem }, elem);
};
var d = div(container);
d.style.textAlign = "center";
d.style.fontSize = "25px";
d.innerHTML = "Nom et prénom du membre";
grayBar(container, 5);
}
var i1 = document.createElement("input");
i1.autocomplete = "off";
i1.id = "inputTabCahierSearch";
i1.title = "Veuillez écrire votre nom et prénom";
i1.spellcheck = false;
i1.type = "text";
i1.placeholder = "Entrez votre nom, prénom...";
i1.onkeyup = function (event) {
if (this.value.length > 2) {
Search(event);
}
else {
$("divTabCahierSearchResult").innerHTML = "<div style='margin-top:10px; color:var(--fontBlack);'>Veuillez taper au moins trois caractères</div>";
}
};
i1.oninput = function (event) {
if (this.value.length > 2) {
Search(event);
}
else {
$("divTabCahierSearchResult").innerHTML = "<div style='margin-top:10px; color:var(--fontBlack);'>Veuillez taper au moins trois caractères</div>";
}
};
i1.onkeydown = function (event) {SearchDown(event);};
container.appendChild(i1);
if (elem != $("divTabCahierMemberContainer")) {
i1.focus();
}
var d = div(container);
d.id = "divTabCahierSearchResult";
}
var enterSearchPosition = 0;
function Search(e) {
var text = $("inputTabCahierSearch").value.toUpperCase();
if (e.keyCode == 13) {
var all = document.getElementsByClassName("divTabCahierResultEntry");
for (var i = 0; i < all.length; i++) {
if (typeof all[i].getElementsByTagName("img")[0] != "undefined") {
// var _firstName = all[i].getElementsByClassName("spanTabCahierFirstName")[0].innerHTML;
// var _surName = all[i].getElementsByClassName("spanTabCahierSurName")[0].innerHTML;
var _name = all[i].getElementsByClassName("spanTabCahierSurName")[0].innerHTML;
var _id = lastPeople[all[i].id].id;
var _sex = lastPeople[all[i].id].sex; // modifier
var nbr = parseInt(document.getElementsByClassName('PopUpUserContainer')[0].id); // modifier problem si plusieurs popUp ouverts...
var owner = { id: _id, name: _name, sex: _sex };
Cahier.setOwner(nbr, owner);
}
}
}
else if (e.keyCode == 40 || e.keyCode == 38) {
//do nothing
}
else { //text != ""
Requests.getUsersList(text, 5);
enterSearchPosition = 0;
}
}
function SearchDown(e) {
if (e.keyCode == 40 || e.keyCode == 38) {
if (e.keyCode == 40) {
enterSearchPosition++;
}
else {
enterSearchPosition--;
}
if (lastPeople.length != 0) {
for (var i = 0; i < lastPeople.length; i++) {
var elem = document.getElementsByClassName("divTabCahierResultEntry")[i];
elem.style.backgroundColor = "";
if (typeof elem.getElementsByTagName("img")[0] != "undefined") {
elem.removeChild(elem.getElementsByTagName("img")[0]);
}
if (i == (enterSearchPosition % lastPeople.length + lastPeople.length) % lastPeople.length) {
var img = document.createElement("img");
img.id = "imgTabCahierSearchEnter";
img.src = "img/icons/enter.png";
elem.appendChild(img);
elem.style.backgroundColor = "darkgray";
}
}
}
e.preventDefault();
}
}
var lastPeople = [];
function createSearchEntries(PeopleCorresponding) {
lastPeople = PeopleCorresponding;
$("divTabCahierSearchResult").innerHTML = "";
if (PeopleCorresponding.length == 0) {
var divResult = document.createElement("div");
divResult.classList.add("divTabCahierResultEntry");
$("divTabCahierSearchResult").appendChild(divResult);
var span1 = document.createElement("span");
span1.classList.add("spanTabCahierSurName");
span1.innerHTML = "Aucun résultat"; //. Cliquez pour vous rendre sur <c style='color:blue; text-decoration:underline;'> ichtus.ch </c>";
//span1.onclick = function () {
// var win = window.open("https://ichtus.ch", '_blank');
// win.focus();
//};
divResult.appendChild(span1);
divResult.style.backgroundImage = "url(img/icons/no-result.png)";
lastPeople = [];
}
else {
for (var i = 0; i < PeopleCorresponding.length; i++) {
var divResult = document.createElement("div");
// divResult.id = PeopleCorresponding[i].id;
divResult.classList.add("divTabCahierResultEntry");
$("divTabCahierSearchResult").appendChild(divResult);
var nbr = parseInt(document.getElementsByClassName('PopUpUserContainer')[0].id); // modifier problem si plusieurs popUp ouverts...
divResult.id = i;
divResult.addEventListener("mousedown", function () { Cahier.setOwner(nbr, { id: PeopleCorresponding[this.id].id, name: PeopleCorresponding[this.id].name, sex: PeopleCorresponding[this.id].sex }); });
var span1 = document.createElement("span");
span1.classList.add("spanTabCahierSurName");
span1.innerHTML = PeopleCorresponding[i].name; //.split(" ")[0]; //changed ! --> div names are false $$
divResult.appendChild(span1);
//var span2 = document.createElement("span");
//span2.classList.add("spanTabCahierFirstName");
//span2.innerHTML = PeopleCorresponding[i].name.split(" ")[1];
//divResult.appendChild(span2);
if (i == 0) {
var img = document.createElement("img");
img.id = "imgTabCahierSearchEnter";
img.src = "img/icons/enter.png";
divResult.appendChild(img);
divResult.style.backgroundColor = "darkgray";
}
if (PeopleCorresponding[i].sex == "male") {
divResult.style.backgroundImage = "url(img/icons/man.png)";
}
else {
divResult.style.backgroundImage = "url(img/icons/woman.png)";
}
}
}
}
<file_sep>var stillMoving = false;
var currentTabElement; //see load for the first element = divtabcahier
var changeTime = 0.3;
// changeTab
function changeTab(newElement, sign) {
stillMoving = true;
document.documentElement.scrollTop = 0;
currentTabElement.style.zIndex = "10";
currentTabElement.style.transition = "transform " + changeTime + "s linear 0s,padding-right 0.3s linear 0s";
newElement.style.zIndex = "5";
currentTabElement.style.transform = "translate(" + (-sign) + "00%)"; //element.style.transform = "translate(" + (-sign * widthToDisplay) + "px)"; //meme chose
newElement.style.top = "0px";
setTimeout(function () {
currentTabElement.style.zIndex = "2";
currentTabElement.style.transition = "none";
currentTabElement.style.transform = "translate(0px)";
setTimeout(function () { currentTabElement.style.transition = "transform " + changeTime + "s linear 0s, padding-right 0.3s linear 0s"; }, 30);
setTimeout(function () {
stillMoving = false;
currentTabElement.style.top = "-30000px";
currentTabElement = newElement;
}, 50);
}, changeTime * 1000);
}
// newTab
function newTab(id) {
if (stillMoving == false) {
window.location = "#" + id;
}
}
// historyBackTab
function historyBackTab(elem) {
window.history.back();
}
// tabs
var tabs = [];
tabs.push({ id: "divTabCahier", order: 0, progress: 0, position: 0, TopBar: false, ListBar: false, title: "Cahier de sortie", Enter: function () { Cahier.cancel(); }, Remove: function () { } });
tabs.push({
id: "divTabCahierMember", order: 6, progress: 1, position: 0, TopBar: true, ListBar: false, title: "Veuillez écrire votre nom et prénom", Enter: function () {
$('divTabCahierMember').getElementsByTagName("input")[0].focus();
}, Remove: function () { }
});
tabs.push({
id: "divTabCahierInfos", order: 7, progress: 2, position: 0, TopBar: true, ListBar: false, title: "Complétez les champs", Enter: function () {
if (currentTabElement.id == "divTabCahierMember") {
document.getElementsByClassName("divTabCahierInfosNbrInvites")[0].getElementsByTagName("input")[0].focus();
writeNbrInvites(document.getElementsByClassName("divTabCahierInfosNbrInvites")[0].getElementsByTagName("input")[0]);
writeDestination(document.getElementsByClassName("divTabCahierInfosDestination")[0].getElementsByTagName("input")[0]);
}
}, Remove: function () { }
});
tabs.push({
id: "divTabCahierEquipmentChoice", order: 9, progress: 3, position: 0, TopBar: true, ListBar: true, title: "Tapez les codes de vos embarcations",
Enter: function () {
document.getElementsByClassName('divTabCahierEquipmentChoiceInputCodeContainer')[0].getElementsByTagName("input")[0].focus();
document.getElementsByClassName('divTabCahierEquipmentChoiceInputCodeContainer')[0].getElementsByTagName("input")[0].value = "";
}, Remove: function () {}});
tabs.push({ id: "divTabCahierEquipmentBookable", order: 10, progress: 3, position: 0, TopBar: true, ListBar: true, title: "Validez cette embarcation", Enter: function () {}, Remove: function () { } });
tabs.push({ id: "divTabCahierEquipmentCategories", order: 12, progress: 3, position: 0, TopBar: true, ListBar: true,title: "Veuillez choisir votre type d'activité", Enter: function () { }, Remove: function () { } });
tabs.push({
id: "divTabCahierEquipmentElements", order: 13, progress: 3, position: 0, TopBar: true, ListBar: true, title: "Sélectionnez vos embarcations",
Enter: function () {
MaterielElementsFirstLoad = true; Requests.getBookablesList(); $('inputTabCahierEquipmentElementsInputSearch').focus();
$('divTabCahierTopList').children[1].style.opacity = 1;
},
Remove: function () {
$('divTabCahierTopList').children[1].style.opacity = 0;
}
});
tabs.push({ id: "divTabCahierConfirmation", order: 15, progress: 4, position: 0, TopBar: true, ListBar: false, title: "Confirmez et créez votre sortie", Enter: function () { loadConfirmation();}, Remove: function () { } });
//WINDOW LOCATION CHANGE
var OldElement = tabs[0];
var NewElement = tabs[0];
window.onhashchange = function () {
var newLocation = window.location.toString();
var res = newLocation.substr(newLocation.indexOf("#") + 1);
if (res != currentTabElement.id) { //onload refresh
var i0;
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].id == res) {
i0 = i;
NewElement = tabs[i];
break;
}
}
var sign = 1;
if (NewElement.progress == 0 && OldElement.progress != 0 && NewElement.id != "divTabCahier") {
sign = NewElement.order;
}
else if (NewElement.order < OldElement.order) {
sign = -1;
}
changeTab($(NewElement.id), sign);
// TopBar Enter/Remove
if (NewElement.TopBar == true && OldElement.TopBar == false) {
enterProgressBar(sign);
}
else if (NewElement.TopBar == false && OldElement.TopBar == true) {
removeProgressBar(sign);
}
// ListBar Enter/Remove
if (NewElement.ListBar == true && OldElement.ListBar == false) {
enterListBar(sign);
actualizeBookableList();
}
else if (NewElement.ListBar == false && OldElement.ListBar == true) {
removeListBar(sign);
}
// Enter & Remove Functions
NewElement.Enter();
OldElement.Remove();
// Change Title
if (NewElement.title != undefined) {
$('divTopBarText').innerHTML = NewElement.title;
}
else {
$('divTopBarText').innerHTML = "?";
}
// change ProgressBar
changeProgress(NewElement.progress);
// actualize Progress Bar // AFTER CHANGING PROGRESS
Cahier.actualizeProgressBar();
// save OldElement
OldElement = NewElement;
}
};
//ENTER PROGRESS BAR
function enterProgressBar() {
$("divTabCahierTop").style.zIndex = 6;
setTimeout(function () { $("divTabCahierTop").style.zIndex = 11; }, changeTime * 1000);
}
//REMOVE PROGRESS BAR
function removeProgressBar(sign) {
$("divTabCahierTop").style.zIndex = "11"; //11
$("divTabCahierTop").style.transition = "transform " + changeTime + "s linear 0s";
$("divTabCahierTop").style.transform = "translate(" + (-sign) + "00%)";
setTimeout(function () {
$("divTabCahierTop").style.zIndex = "2";
$("divTabCahierTop").style.transition = "none";
$("divTabCahierTop").style.transform = "translate(0px)";
setTimeout(function () { $("divTabCahierTop").style.transition = "transform " + changeTime + "s linear 0s"; }, 20);
}, changeTime * 1000);
}
//ENTER LIST BAR
function enterListBar() {
$("divTabCahierTopList").style.zIndex = 6;
setTimeout(function () { $("divTabCahierTopList").style.zIndex = 10; }, changeTime * 1000);
}
//REMOVE LIST BAR
function removeListBar(sign) {
$("divTabCahierTopList").style.zIndex = "10"; //10
$("divTabCahierTopList").style.transition = "transform " + changeTime + "s linear 0s";
$("divTabCahierTopList").style.transform = "translate(" + (-sign) + "00%)";
setTimeout(function () {
$("divTabCahierTopList").style.zIndex = "2";
$("divTabCahierTopList").style.transition = "none";
$("divTabCahierTopList").style.transform = "translate(0px)";
setTimeout(function () { $("divTabCahierTopList").style.transition = "transform " + changeTime + "s linear 0s"; }, 20);
}, changeTime * 1000);
}<file_sep>//options
var options = { bookablesComment: false, statsButtonTextActive: false, showRemarks: true, automaticConnexion: true, seeWhichApplication:false }; //showMetadatas: false,
// shortcut
function $(id) {
return document.getElementById(id);
}
// createElements
function div(loc) {
var x = document.createElement("div");
loc.appendChild(x);
return x;
}
function input(loc,_placeholder = "") {
var x = document.createElement("input");
x.autocomplete = "off";
x.type = "text";
x.spellcheck = false;
x.placeholder = _placeholder;
loc.appendChild(x);
return x;
}
function br(loc) {
var x = document.createElement("br");
loc.appendChild(x);
}
//Load
function load() {
currentTabElement = $("divTabCahier");
actualizeTime();
setInterval(actualizeTime, 5000); //5 secondes
createProgressBar();
createAllPropositions();
window.location = "#" + "divTabCahier";
loadReturnButtons();
popUser(0, $("divTabCahierMemberContainer"));
loadTableTopBars();
loadCahierEquipmentChoice();
loadEscListener();
if (window.location.hostname === 'navigations.ichtus.club') {
console.warn("Version de production");
$('divTopBarText').innerHTML = tabs[0].title;
}
else {
console.warn("Version de démo");
tabs[0].title = "Cahier de sortie (démo)";
$('divTopBarText').innerHTML = tabs[0].title;
}
//SERVER
ServerInitialize();
Requests.checkLogin();
loadBottoms();
loadMateriel();
}
// auto actualize if mouse doesn't move
var timeout;
function setTimeoutMove() {
//console.log("start timeout");
clearTimeout(timeout);
timeout = setTimeout(function () {
if (currentTabElement.id === "divTabCahier") {
location.reload();
}
else {
Requests.getActualBookingList();
}
}, 1 * 60 * 1000);
}
setTimeoutMove();
document.onmousemove = function () {
setTimeoutMove();
};
// too complicated now...
//function loadButtonFocus() {
// var btn = document.getElementsByClassName('ValidateButtons');
// for (var i = 0, len = btn.length; i < len; i++) {
// btn[i].setAttribute('tabindex', '0');
// }
//}
// could be improved...
var Time = {
getActualMinutes: function (m = date.getMinutes()) {
if (m < 10) {
x = "0" + m;
}
else {
x = m.toString();
}
return x;
}
};
Date.prototype.getNiceTime = function (separator = ":", addZero = false) {
if (addZero == true && this.getHours() < 10) {
return Time.getActualMinutes(this.getHours()) + separator + Time.getActualMinutes(this.getMinutes());
}
else {
return this.getHours() + separator + Time.getActualMinutes(this.getMinutes());
}
};
Date.prototype.getNiceDate = function (substr = false, year = false) {
var r = "";
if (substr) {
r = Jours[this.getDay()] + " " + this.getDate() + " " + Mois[this.getMonth()].substring(0,3);
}
else {
r = Jours[this.getDay()] + " " + this.getDate() + " " + Mois[this.getMonth()];
}
if (year) {
r += " " + this.getFullYear();
}
return r;
};
Date.prototype.getPreviousDate = function () {
var yesterday = new Date(this);
yesterday.setDate(this.getDate() - 1);
return yesterday;
};
function DeleteObjects() {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] != "undefined" && typeof arguments[i].parentElement != "undefined" && arguments[i].parentElement != null) {
arguments[i].parentElement.removeChild(arguments[i]);
}
else {
//console.log("tried to delete a non-existent object");
}
}
}
//Time
var date;
var Jours = ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"];
var Mois = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
function actualizeTime() {
date = new Date();
$("divTopBarTime").innerHTML = date.getNiceTime() + "<br/>" + date.getNiceDate(true); //.substring(0, 3)
}
// NOt USED ANYMORE
// 1 -> checked // 0 --> not
//function check(checkParent) {
// if (checkParent.getElementsByClassName('checkBox')[0].id == undefined || checkParent.getElementsByClassName('checkBox')[0].id == 1) {
// checkParent.getElementsByClassName('checkBox')[0].id = 0;
// checkParent.getElementsByClassName('checkBox')[0].style.backgroundImage = 'none';
// }
// else {
// checkParent.getElementsByClassName('checkBox')[0].id = 1;
// checkParent.getElementsByClassName('checkBox')[0].style.backgroundImage = 'url(img/icons/check-black.png)';
// }
//}
function loadReturnButtons() {
var allReturnButtons = document.getElementsByClassName("ReturnButtons");
for (var i = 0; i < allReturnButtons.length; i++) {
allReturnButtons[i].title = "Retour";
}
}
// Modals
var lastModals = 0;
function openPopUp() {
var modal = div(document.body);
modal.onclick = function (event) {
closePopUp(event);
};
lastModals++;
modal.id = "divModal" + lastModals;
modal.classList.add("Modals");
modal.style.display = "block";
setTimeout(function () { modal.style.opacity = 1; }, 10);
$('divScreen').classList.add("Blur");
$('divTopBar').classList.add("Blur");
return modal;
}
function closePopUp(e) {
var t = false;
if (e == "last") {
if (lastModals != 0) {
t = true;
}
}
else if (e.target.id.indexOf("divModal") != -1) {
t = true;
}
if (t) {
var modal = $('divModal' + lastModals);
modal.style.opacity = 0;
setTimeout(function () { modal.style.display = 'none'; modal.innerHTML = ""; modal.parentNode.removeChild(modal); }, 100);
lastModals--;
if (lastModals == 0) {
$('divScreen').classList.remove("Blur");
$('divTopBar').classList.remove("Blur");
//special
//document.body.removeEventListener("keyup", eventListenerFunction);
}
}
}
function loadEscListener() {
document.body.addEventListener("keydown", function (event) {
if (event.keyCode == 27) {
//console.log("ESC");
closePopUp("last");
}
});
}
String.prototype.pixelLength = function (_fontSize = 20) {
var c = document.createElement("span");
document.body.appendChild(c);
c.innerHTML = this;
c.style.fontSize = _fontSize + "px";
var length = c.offsetWidth;
document.body.removeChild(c);
return length;
};
String.prototype.shorten = function (maxLength, _fontSize = 20) {
var txt = this;
if (this == "" || (txt).pixelLength(_fontSize) <= maxLength) {
return this;
}
while ((txt + "...").pixelLength(_fontSize) > maxLength - "...".pixelLength(_fontSize) && txt.length > 0) {
txt = txt.substr(0, txt.length - 1);
}
return txt + "...";
};
function grayBar(elem, marginTop = 10, marginBottom = 15) {
var d = div(elem);
d.style.backgroundColor = "lightgray";
d.style.height = "2px";
d.style.marginBottom = marginBottom + "px";
d.style.marginTop = marginTop + "px";
d.borderRadius = "2px";
return d;
}
String.prototype.replaceTxtByTxt = function (replace = "", by = "", caseSensitive = false) {
var i = 0;
var where = [];
var txt = caseSensitive ? this : this.toUpperCase();
var replaceTxt = caseSensitive ? replace : replace.toUpperCase();
while (txt.indexOf(replaceTxt, i) !== -1) {
where.push(txt.indexOf(replaceTxt, i));
i = where[where.length - 1]+1;
}
var r = "";
for (let k = 0; k <= where.length; k++) {
let start = k === 0 ? 0 : where[k - 1];
let end = k === where.length ? this.length : where[k];
let s = this.slice(start, end);
let sTxt = caseSensitive ? s : s.toUpperCase();
let x = sTxt.indexOf(replaceTxt);
let t = x !== -1 ? s.slice(0, x) + by + s.slice(x + replace.length) : s;
r += t;
}
return r;
};
// ARRAY PROTOTYPES
Array.prototype.switch = function (i1, i2) {
var content_i1 = this[i1];
this.splice(i1, 1, this[i2]);
this.splice(i2, 1, content_i1);
return this;
};
Array.prototype.inverse = function (i1, i2) {
for (var i = i1; i < parseInt((i1 + i2) / 2 + 0.5); i++) {
this.switch(i, i1 + i2 - i);
}
return this;
};
Array.prototype.findIndex = function (x) {
var index = -1;
for (var i = 0; i < this.length; i++) {
if (this[i] == x) {
index = i;
break;
}
}
return index;
};
Array.prototype.deleteMultiples = function () {
var r = [];
for (var i = 0; i < this.length; i++) {
if (r.findIndex(this[i]) === -1) {
r.push(this[i]);
}
}
return r;
}
// sortBy
Array.prototype.sortBy = function (sortFields, order = 1) {
if (order == "ASC") {
order = -1;
}
else if (order == "DESC") {
order = 1;
}
var switching = true;
while (switching) {
switching = false;
for (var i = 0; i < this.length - 1; i++) {
if (sortFields[i] > sortFields[i + 1] && order == 1 || sortFields[i] < sortFields[i + 1] && order == -1) { //
this.switch(i, i + 1);
sortFields.switch(i, i + 1);
switching = true;
}
}
}
};
// fillArray
Array.prototype.fillArray = function (length, what = 0) {
for (var i = 0; i < length; i++) {
this[i] = what;
}
};
// merge and only takes the elements which are in every array
Array.prototype.mergeAND = function () {
var send = [];
for (let b = 0; b < this[0].length; b++) {
var item = this[0][b];
var c = 0;
for (let r2 = 1; r2 < this.length; r2++) {
if (this[r2].findIndex(item) != -1) {
c++;
}
}
if (c == this.length - 1) {
send.push(item);
}
}
return send;
};
// clone
Object.prototype.clone = function () {
return JSON.parse(JSON.stringify(this));
};
// transformBookings
function transformBookings(_bookings) {
if (_bookings.length > 0) {
var final = [];
final.push(_bookings[0].clone());
final[0].ids = [_bookings[0].id];
if (_bookings[0].bookable == null) {
final[0].bookables = [Cahier.personalBookable];
}
else {
final[0].bookables = [_bookings[0].bookable];
}
for (var i = 1; i < _bookings.length; i++) {
// add bookable
if (_bookings[i].startDate == _bookings[i - 1].startDate && _bookings[i].owner.id == _bookings[i - 1].owner.id) {
if (_bookings[i].bookable == null) {
final[final.length - 1].bookables.push(Cahier.personalBookable);
}
else {
final[final.length - 1].bookables.push(_bookings[i].bookable);
}
final[final.length - 1].ids.push(_bookings[i].id);
final[final.length - 1].participantCount += _bookings[i].participantCount;
}
// new booking
else {
final.push(_bookings[i].clone());
final[final.length - 1].ids = [_bookings[i].id];
if (_bookings[i].bookable == null) {
final[final.length - 1].bookables = [Cahier.personalBookable];
}
else {
final[final.length - 1].bookables = [_bookings[i].bookable];
}
}
}
return final;
}
else {
return [];
}
}
<file_sep>function loadBottoms() {
var allDivTabs = document.getElementsByClassName("divTab");
for (var i = 0; i < allDivTabs.length; i++) {
var s = div(allDivTabs[i]);
s.className = "divSpacers";
var b = div(allDivTabs[i]);
b.className = "divBottoms";
var divMonth = div(b);
divMonth.onclick = function () { popStats(); };
}
if (options.statsButtonTextActive) {
var end = new Date(Date.now());
var start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0, 1);
Requests.getMonthlyBookingsNbr(start, end);
}
else {
var all = document.getElementsByClassName("divBottoms");
for (var i = 0; i < all.length; i++) {
all[i].children[0].innerHTML = "Voir les statistiques du mois";
}
}
}
|
3abe1cbc4f8b75e2dc93ab4b728894ac0e0f1072
|
[
"JavaScript",
"Markdown"
] | 17
|
JavaScript
|
AlainSchoebi/ichtus-reservations
|
e9b5295a95632e5a5b42f0be0c416273977ab257
|
9f2b36ac6b472bc039bf3770eadaf9747ef6b941
|
refs/heads/master
|
<repo_name>LuisNegrao/Warehouse<file_sep>/src/main/java/database/DataSource.java
package database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DataSource {
private static final String DB_USERNAME = "user";
private static final String DB_PASSWORD = "<PASSWORD>";
private static final String DB_URL = "jdbcUrl";
private static final String DB_CLASS_NAME = "className";
private static HikariConfig config = new HikariConfig();
private static HikariDataSource dataSource;
private static Properties properties = null;
static {
try {
properties = new Properties();
properties.load(new FileInputStream("src/main/java/database/database.properties"));
config.setJdbcUrl(properties.getProperty(DB_URL));
config.setDataSourceClassName(properties.getProperty(DB_CLASS_NAME));
config.setUsername(properties.getProperty(DB_USERNAME));
config.setPassword(properties.getProperty(DB_PASSWORD));
dataSource = new HikariDataSource(config);
} catch (IOException e) {
e.printStackTrace();
}
}
public DataSource() {
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/*public ResultSet connect(String query){
String SQL_QUERY = query;
String SQL = "use warehouse";
try (Connection con = dataSource.getConnection();) {
PreparedStatement pst = con.prepareStatement(SQL);
pst.executeQuery();
pst = con.prepareStatement(SQL_QUERY);
ResultSet rs = pst.executeQuery();
return rs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}*/
}
<file_sep>/src/main/java/enteties/Warehouse.java
package enteties;
import database.Database;
import database.SQLDatabase;
import utils.Auxiliar;
import java.util.*;
public class Warehouse {
private Auxiliar auxiliar = new Auxiliar();
private Database database = new SQLDatabase();
String warehouseID;
User onlineUser;
private final int MAX_STORAGE = 25000;
public Warehouse(User user) {
this.onlineUser = user;
System.out.println(user.getUserId());
this.warehouseID = user.getWarehouseID();
warehouseMenu();
}
public void warehouseMenu() {
System.out.println("1- See Available Stock");
System.out.println("2- Ship Sock");
System.out.println("3- Add Stock");
System.out.println("4- Logout");
if (onlineUser.getSecurityLevel() != SecurityLevel.Employee) {
System.out.println("5- Manager Options");
}
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
switch (choice) {
case 1:
seeAvailableStockMenu(input);
break;
case 2:
shipStockMenu(input);
warehouseMenu();
break;
case 3:
addStockMenu(input);
break;
case 4:
break;
case 5:
if (onlineUser.getSecurityLevel() == SecurityLevel.Employee) {
auxiliar.sendErrMsg(choice + " is not a valid choice.");
warehouseMenu();
break;
} else {
managerMenu();
warehouseMenu();
}
break;
default:
auxiliar.sendErrMsg(choice + " is not a valid choice.");
warehouseMenu();
break;
}
}
private void managerMenu() {
System.out.println("1- See delivery list");
System.out.println("2- See logIn log");
System.out.println("3- Back");
}
private void addStockMenu(Scanner input) {
System.out.println("1- Add items");
System.out.println("2- Back");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("How many items of the same type do you wish to add?");
int amount = input.nextInt();
System.out.println("Please introduce the itemType.");
input.nextLine();
String itemType = input.nextLine();
System.out.println("Please introduce the value of the item");
int value = input.nextInt();
Item item = new Item(itemType, value, amount);
int storage = database.getWarehouseStorage(this);
if (storage + amount < MAX_STORAGE) {
System.out.println("HERE");
if (database.getItemByItemType(itemType) != null) {
System.out.println("HERE");
database.updateItemAmount(item, "UP");
database.updateWarehouseStorage(this, amount + item.getAmount());
} else {
database.sendItemToDb(item);
}
}
break;
case 2:
warehouseMenu();
break;
default:
auxiliar.sendErrMsg(choice + " is not a valid choice.");
addStockMenu(input);
break;
}
}
private void shipStockMenu(Scanner input) {
System.out.println("1- Ship stock");
System.out.println("2- Confirm delivery");
System.out.println("3- Back");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("How many different items do you wish to ship");
int numDifItems = input.nextInt();
String stockList = "";
HashMap<String, Integer> items = new HashMap<>();
input.nextLine();
for (int i = 0; i < numDifItems; i++) {
System.out.println("Introduce Item to ship");
String item = input.nextLine();
System.out.println("How many do ypu wish to ship");
int amount = input.nextInt();
items.put(item, amount);
stockList += "[" + item + "," + amount + "] ";
input.nextLine();
}
Iterator it = items.entrySet().iterator();
int value = 0;
boolean flag = true;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Item item = database.getItemByItemType(pair.getKey().toString());
if (item == null) {
flag = false;
auxiliar.sendErrMsg("The warehouse does not have the item you want to ship: " + pair.getKey().toString());
break;
} else {
value = item.getItemValue() * items.get(item.getItemType());
}
}
if (flag) {
System.out.println("Where do you want to ship?");
String location = input.nextLine();
ShippedStock stock = new ShippedStock(location, onlineUser.getUserId(), stockList);
stock.setValue(value);
database.addShipStockToDb(stock);
}
break;
case 2:
System.out.println("Please insert the ID of the delivery that you want to mark as delivered");
input.nextLine();
String id = input.nextLine();
database.updateDeliveryStatus(id);
break;
case 3:
warehouseMenu();
break;
default:
auxiliar.sendErrMsg(choice + " is not a valid choice.");
shipStockMenu(input);
break;
}
}
public void seeAvailableStockMenu(Scanner input) {
System.out.println("1- See all stock");
System.out.println("2- See stock from a certain itemType");
System.out.println("3- Back");
int choice = input.nextInt();
switch (choice) {
case 1:
LinkedList<Item> items = database.getItems();
if (items == null)
break;
for (Item item : items) {
item.print();
}
break;
case 2:
input.nextLine();
System.out.println("What item are you looking for?");
String itemType = input.nextLine();
Item item = database.getItemByItemType(itemType);
if (item == null) {
auxiliar.sendErrMsg(itemType + " is not a valid itemType.");
break;
}
item.print();
break;
case 3:
warehouseMenu();
break;
default:
auxiliar.sendErrMsg(choice + " is not a valid choice.");
seeAvailableStockMenu(input);
break;
}
}
public String getWarehouseID() {
return warehouseID;
}
public void setWarehouseID(String warehouseID) {
this.warehouseID = warehouseID;
}
public int getMAX_STORAGE() {
return MAX_STORAGE;
}
}
<file_sep>/src/main/java/enteties/SecurityLevel.java
package enteties;
public enum SecurityLevel {
Employee, Manager,Owner
}
|
f5a82ae0365bf84d1f896406bd6b6eab91a1bcfd
|
[
"Java"
] | 3
|
Java
|
LuisNegrao/Warehouse
|
990c2f678becd6d3bad8c28d86317caa27f3ecd7
|
9b4e683a98f5a43f148df9493fcb84a40c9120ef
|
refs/heads/master
|
<file_sep>__author__ = '<NAME>'
class memoria_estatica:
__autos = ['Audi', 'Ferrari', 'Ford']
def getAutos(self):
return self.__autos
def recorrerArreglo(self):
for x in self.getAutos():
print (self.getAutos().index(x)+1, x)
def agregarelementoarray(self, elemento):
self.__autos.append(elemento)
<file_sep>__author__ = '<NAME>'
from esfera import *
from memoria_estatica import *
Esferita = Esfera(56)
"""
print "El radio es:" , Esferita.getRadio()
print "El diametro es:" , Esferita.getDiametro()
print "La circunferencia es: ", Esferita.getCircunferencia()
print "El area es: ", Esferita.getArea()
print "El volumen es: ", Esferita.getVolumen()
arreglo = memoria_estatica()
arreglo.recorrerArreglo()
print 'Agregar elemento'
elemento = raw_input()
arreglo.agregarelementoarray(elemento)
arreglo.recorrerArreglo()
"""
promedio = 9.67
otralista = []
supermercado = ['fruta','agua', 'refresco', 'pan', 'pastel']
estructuradedatos = ['<NAME>', '<NAME>', '<NAME>']
precios = [12, 34, 45, 47]
porcentajes = [.34, .56, .12, 1.2]
print ('Primera lista')
print (supermercado)
supermercado.append('jamon')
print ('Uso de append')
print (supermercado)
print ('Uso de copy')
otralista = supermercado.copy()
print (otralista)
otralista.clear()
otralista.append('pera')
otralista.append('manzana')
print (otralista)
supermercado.extend(otralista)
print (supermercado)
supermercado.append('agua')
print (supermercado)
print ('la lista supermercado tiene ', supermercado.count('agua'))
supermercado.insert(0, 'galletas')
print (supermercado)
supermercado.pop(2)
print (supermercado)
supermercado.remove('pera')
print (supermercado)
supermercado.sort()
print(supermercado)
supermercado.reverse()
print(supermercado)
|
28d7e422fcae0fe7902110769fc64adc89c88bf2
|
[
"Python"
] | 2
|
Python
|
urimessi/ProyectosEstructurasDatos
|
0e60676b8073673fd18bde6f87b7a6d80fd4e98d
|
7c2e3f5161cd89a4baeb2a2a186f03fb4cb97017
|
refs/heads/master
|
<file_sep>package com.callfire.api.client.api.callstexts;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ClientUtils.buildQueryParams;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.callstexts.model.Call;
import com.callfire.api.client.api.callstexts.model.CallRecipient;
import com.callfire.api.client.api.callstexts.model.request.FindCallsRequest;
import com.callfire.api.client.api.callstexts.model.request.SendCallsRequest;
import com.callfire.api.client.api.campaigns.model.CallRecording;
import com.callfire.api.client.api.common.model.Page;
/**
* Represents rest endpoint /calls
* Use the /calls API to quickly send individual calls, get results.
* A verified Caller ID and sufficient credits are required to make a call.
* <br>
*
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
* @since 1.0
*/
public class CallsApi {
private static final String CALLS_PATH = "/calls";
private static final String CALLS_ITEM_PATH = "/calls/{}";
private static final String CALLS_ITEM_RECORDINGS_PATH = "/calls/{}/recordings";
private static final String CALLS_ITEM_RECORDING_BY_NAME_PATH = "/calls/{}/recordings/{}";
private static final String CALLS_ITEM_MP3_RECORDING_BY_NAME_PATH = "/calls/{}/recordings/{}.mp3";
private static final String CALLS_ITEM_RECORDING_BY_ID_PATH = "/calls/recordings/{}";
private static final String CALLS_ITEM_MP3_RECORDING_BY_ID_PATH = "/calls/recordings/{}.mp3";
private RestApiClient client;
public CallsApi(RestApiClient client) {
this.client = client;
}
/**
* Finds all calls sent or received by the user, filtered by different properties, broadcast id,
* toNumber, fromNumber, label, state, etc. Use "campaignId=0" parameter to query
* for all calls sent through the POST /calls API {@link CallsApi#send(List)}.
*
* @param request request object with different fields to filter
* @return Page with @{Call} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
public Page<Call> find(FindCallsRequest request) {
return client.get(CALLS_PATH, pageOf(Call.class), request);
}
/**
* Get call by id
*
* @param id id of call
* @return Call object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Call get(Long id) {
return get(id, null);
}
/**
* Get call by id
*
* @param id id of call
* @param fields limit fields returned. Example fields=id,name
* @return Call object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Call get(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = CALLS_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(Call.class), queryParams);
}
/**
* Send calls to recipients through default campaign.
* Use the API to quickly send individual calls.
* A verified Caller ID and sufficient credits are required to make a call.
*
* @param recipients call recipients
* @return list of {@link Call}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Call> send(List<CallRecipient> recipients) {
return send(recipients, null, null);
}
/**
* Send call to recipients through existing campaign, if null default campaign will be used
* Use the API to quickly send individual calls.
* A verified Caller ID and sufficient credits are required to make a call.
*
* @param recipients call recipients
* @param campaignId specify a campaignId to send calls quickly on a previously created campaign
* @param fields fields returned. E.g. fields=id,name or fields=items(id,name)
* @return list of {@link Call}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Call> send(List<CallRecipient> recipients, Long campaignId, String fields) {
List<NameValuePair> queryParams = new ArrayList<>(2);
addQueryParamIfSet("campaignId", campaignId, queryParams);
addQueryParamIfSet("fields", fields, queryParams);
return client.post(CALLS_PATH, listHolderOf(Call.class), recipients, queryParams).getItems();
}
/**
* Send call to recipients through existing campaign, if null default campaign will be used
* Use the API to quickly send individual calls.
* A verified Caller ID and sufficient credits are required to make a call.
*
* @param request {@link SendCallsRequest} request with parameters (campaignId, defaultLiveMessage, defaultMachineMessage etc)
* @return list of {@link Call}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Call> send(SendCallsRequest request) {
List<NameValuePair> queryParams = buildQueryParams(request);
return client.post(CALLS_PATH, listHolderOf(Call.class), request.getRecipients(), queryParams).getItems();
}
/**
* Returns call recordings for a call
*
* @param id id of call
* @return list of {@link CallRecording}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<CallRecording> getCallRecordings(Long id) {
return getCallRecordings(id, null);
}
/**
* Returns call recordings for a call
*
* @param id id of call
* @param fields Limit text fields returned. Example fields=limit,offset,items(id,message)
* @return list of {@link CallRecording}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<CallRecording> getCallRecordings(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = CALLS_ITEM_RECORDINGS_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, listHolderOf(CallRecording.class), queryParams).getItems();
}
/**
* Returns call recording by name
*
* @param callId id of call
* @param recordingName name of call recording
* @return CallRecording meta object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CallRecording getCallRecordingByName(Long callId, String recordingName) {
return getCallRecordingByName(callId, recordingName, null);
}
/**
* Returns call recording by name
*
* @param callId id of call
* @param recordingName name of call recording
* @param fields Limit text fields returned. Example fields=limit,offset,items(id,message)
* @return CallRecording meta object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CallRecording getCallRecordingByName(Long callId, String recordingName, String fields) {
Validate.notNull(callId, "id cannot be null");
Validate.notNull(recordingName, "recordingName cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = CALLS_ITEM_RECORDING_BY_NAME_PATH.replaceFirst(PLACEHOLDER, callId.toString()).replaceFirst(PLACEHOLDER, recordingName);
return client.get(path, of(CallRecording.class), queryParams);
}
/**
* Download call mp3 recording by name
*
* @param callId id of call
* @param recordingName name of call recording
* @return mp3 file as input stream
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public InputStream getCallRecordingMp3ByName(Long callId, String recordingName) {
Validate.notNull(callId, "id cannot be null");
Validate.notNull(recordingName, "recordingName cannot be null");
String path = CALLS_ITEM_MP3_RECORDING_BY_NAME_PATH.replaceFirst(PLACEHOLDER, callId.toString()).replaceFirst(PLACEHOLDER, recordingName);
return client.get(path, of(InputStream.class));
}
/**
* Returns call recording by id
*
* @param id id of call recording
* @return CallRecording meta object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CallRecording getCallRecording(Long id) {
return getCallRecording(id, null);
}
/**
* Returns call recording by id
*
* @param id id of call recording
* @param fields Limit text fields returned. Example fields=limit,offset,items(id,message)
* @return CallRecording meta object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CallRecording getCallRecording(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = CALLS_ITEM_RECORDING_BY_ID_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(CallRecording.class), queryParams);
}
/**
* Download call mp3 recording by id
*
* @param id id of call recording
* @return mp3 file as input stream
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public InputStream getCallRecordingMp3(Long id) {
Validate.notNull(id, "id cannot be null");
String path = CALLS_ITEM_MP3_RECORDING_BY_ID_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(InputStream.class));
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* CallBroadcast that represents an IVR or Voice broadcast. If 'dialplanXml' field
* is set then broadcast is IVR, otherwise Voice.
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CallBroadcast extends RetriableBroadcast {
private List<Recipient> recipients;
/**
* IVR xml document describing dialplan. If dialplanXml != null then this is IVR broadcast
*/
private String dialplanXml;
/**
* Voice broadcast sounds
*/
private CallBroadcastSounds sounds;
private AnsweringMachineConfig answeringMachineConfig;
private Integer maxActiveTransfers;
}
<file_sep>package com.callfire.api.client.api.numbers.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class NumberConfig extends CallfireModel {
private String number;
private ConfigType configType;
private CallTrackingConfig callTrackingConfig;
private IvrInboundConfig ivrInboundConfig;
public enum ConfigType {
IVR,
TRACKING;
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
/**
* Media for MMS message
*/
@Getter
public class Media extends CallfireModel {
private Long id;
private Long accountId;
private String name;
private Long created;
private Long lengthInBytes;
private MediaType mediaType;
private String publicUrl;
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.callstexts.model.Call;
import com.callfire.api.client.api.common.model.request.ConvertToString;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* <p>
* Request object used to find all calls sent or received by the user.
* Use "campaignId=0" parameter to query for all calls sent through the POST /calls API.
* </p>
*
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindCallsRequest extends FindCallsTextsRequest {
/**
* Call statuses
*
* @return call statuses
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
@ConvertToString private List<Call.State> states = new ArrayList<>();
/**
* Get call results.
*
* @return list of call results
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
@ConvertToString private List<Call.CallResult> results = new ArrayList<>();
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class
*/
public static class Builder extends CallsTextsBuilder<Builder, FindCallsRequest> {
private Builder() {
super(new FindCallsRequest());
}
/**
* Set call statuses to filter
*
* @param states list of states to filter
* @return builder self reference
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
public Builder states(List<Call.State> states) {
request.states = states;
return this;
}
/**
* Set call results
*
* @param results call results to set
* @return builder self reference
* @see <a href="https://developers.callfire.com/results-responses-errors.html">call states and results</a>
*/
public Builder results(List<Call.CallResult> results) {
request.results = results;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.contacts;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockitoAnnotations;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.common.model.ListHolder;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.common.model.request.GetByIdRequest;
import com.callfire.api.client.api.contacts.model.Contact;
import com.callfire.api.client.api.contacts.model.ContactHistory;
import com.callfire.api.client.api.contacts.model.request.FindContactsRequest;
public class ContactsApiTest extends AbstractApiTest {
protected static final String RESPONSES_PATH = "/contacts/contactsApi/response/";
protected static final String EMPTY_CONTACT_ID_MSG = "contact.id cannot be null";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
client.getRestApiClient().setHttpClient(mockHttpClient);
}
@Test
public void testFind() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "findContacts.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindContactsRequest request = FindContactsRequest.create()
.limit(1L)
.offset(5L)
.build();
Page<Contact> contacts = client.contactsApi().find(request);
assertThat(jsonConverter.serialize(contacts), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("limit=1"));
assertThat(arg.getURI().toString(), containsString("offset=5"));
}
@Test
public void testCreate() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "createContact.json");
mockHttpResponse(expectedJson);
Contact contact = new Contact();
contact.setHomePhone("231554254");
List<Contact> inputContacts = Arrays.asList(contact);
List<ResourceId> resultResourceIds = client.contactsApi().create(inputContacts);
assertThat(jsonConverter.serialize(new ListHolder<>(resultResourceIds)),
equalToIgnoringWhiteSpace(expectedJson));
}
@Test
public void testGetByNullId() throws Exception {
ex.expectMessage(EMPTY_ID_MSG);
ex.expect(NullPointerException.class);
client.contactsApi().get(null);
}
@Test
public void testGetById() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "getContactById.json");
mockHttpResponse(expectedJson);
Contact contact = client.contactsApi().get(TEST_ID);
assertThat(jsonConverter.serialize(contact), equalToIgnoringWhiteSpace(expectedJson));
}
@Test
public void testGetByIdAndFields() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "getContactById.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
Contact contact = client.contactsApi().get(TEST_ID, FIELDS);
assertThat(jsonConverter.serialize(contact), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
@Test
public void testUpdateByNullId() {
ex.expectMessage(EMPTY_CONTACT_ID_MSG);
ex.expect(NullPointerException.class);
client.contactsApi().update(new Contact());
}
@Test
public void testUpdate() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
Contact contact = new Contact();
contact.setId(TEST_ID);
client.contactsApi().update(contact);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
}
@Test
public void testDeleteByNullId() throws Exception {
ex.expectMessage(EMPTY_ID_MSG);
ex.expect(NullPointerException.class);
client.contactsApi().delete(null);
}
@Test
public void testDelete() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.contactsApi().delete(TEST_ID);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/" + TEST_ID));
}
@Test
public void testGetContactHistoryByNullId() throws Exception {
ex.expectMessage(EMPTY_REQUEST_ID_MSG);
ex.expect(NullPointerException.class);
client.contactsApi().getHistory(GetByIdRequest.create().build());
}
@Test
public void testGetContactHistory() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "getContactHistory.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
GetByIdRequest request = GetByIdRequest.create()
.id(TEST_ID)
.limit(1L)
.offset(5L)
.build();
ContactHistory contactHistory = client.contactsApi().getHistory(request);
assertThat(jsonConverter.serialize(contactHistory), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("limit=1"));
assertThat(arg.getURI().toString(), containsString("offset=5"));
}
}
<file_sep>package com.callfire.api.client.integration.webhooks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.webhooks.WebhooksApi;
import com.callfire.api.client.api.webhooks.model.ResourceType;
import com.callfire.api.client.api.webhooks.model.Webhook;
import com.callfire.api.client.api.webhooks.model.WebhookResource;
import com.callfire.api.client.api.webhooks.model.request.FindWebhooksRequest;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /webhooks api endpoint
*/
public class WebhooksApiTest extends AbstractIntegrationTest {
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void testCrudOperations() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
WebhooksApi api = callfireClient.webhooksApi();
Webhook webhook = new Webhook();
webhook.setCallback("https://test_callback");
webhook.setResource(ResourceType.TEXT_BROADCAST);
ResourceType.ResourceEvent[] ev = {ResourceType.ResourceEvent.STARTED};
webhook.setEvents(new TreeSet<>(Arrays.asList(ev)));
webhook.setName("test_name1");
webhook.setSingleUse(true);
ResourceId resourceId1 = api.create(webhook);
assertNotNull(resourceId1.getId());
webhook.setName("test_name2");
ResourceId resourceId2 = api.create(webhook);
webhook.setResource(ResourceType.CONTACT_LIST);
ResourceType.ResourceEvent[] ev2 = {ResourceType.ResourceEvent.VALIDATION_FINISHED};
webhook.setEvents(new TreeSet<>(Arrays.asList(ev2)));
ResourceId resourceId3 = api.create(webhook);
assertNotNull(resourceId3.getId());
FindWebhooksRequest findRequest = FindWebhooksRequest.create()
.limit(30L)
.name("test_name1")
.fields("items(id,callback,name,resource,events,singleUse)")
.build();
Page<Webhook> page = api.find(findRequest);
Webhook found = page.getItems().get(0);
assertTrue(page.getItems().size() > 0);
assertEquals("https://test_callback", found.getCallback());
assertEquals("test_name1", found.getName());
assertNotNull(found.getId());
assertEquals(ResourceType.TEXT_BROADCAST, found.getResource());
assertEquals(1, found.getEvents().size());
assertTrue(found.getSingleUse());
findRequest = FindWebhooksRequest.create()
.limit(30L)
.name("test_name1")
.build();
page = api.find(findRequest);
webhook = page.getItems().get(0);
webhook.setName("test_name2");
webhook.setSingleUse(false);
api.update(webhook);
Webhook updated = api.get(webhook.getId());
assertEquals(webhook.getResource(), updated.getResource());
assertFalse(page.getItems().get(0).getSingleUse());
api.delete(resourceId1.getId());
api.delete(resourceId2.getId());
api.delete(resourceId3.getId());
expect404NotFoundCallfireApiException(ex);
api.get(resourceId1.getId());
expect404NotFoundCallfireApiException(ex);
api.get(resourceId2.getId());
}
@Test
public void testResourceTypeOperations() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
WebhooksApi api = callfireClient.webhooksApi();
List<WebhookResource> resources = api.findWebhookResources();
assertNotNull(resources);
assertEquals(resources.size(), 11);
resources = api.findWebhookResources("items(resource)");
assertNotNull(resources.get(0).getResource());
assertEquals(resources.get(0).getSupportedEvents().size(), 0);
WebhookResource resource = api.findWebhookResource(ResourceType.CALL_BROADCAST);
assertNotNull(resource);
assertNotNull(resource.getSupportedEvents());
assertEquals(resource.getResource(), ResourceType.CALL_BROADCAST.toString());
resource = api.findWebhookResource(ResourceType.CALL_BROADCAST, "resource");
assertNotNull(resource.getResource());
assertEquals(resource.getSupportedEvents().size(), 0);
}
}
<file_sep>package com.callfire.api.client.api.numbers;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.numbers.model.NumberConfig;
import com.callfire.api.client.api.numbers.model.NumberLease;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeaseConfigsRequest;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeasesRequest;
/**
* Represents rest endpoint /numbers/leases
*
* @since 1.0
*/
public class NumberLeasesApi {
private static final String NUMBER_LEASES_PATH = "/numbers/leases";
private static final String NUMBER_LEASES_ITEM_PATH = "/numbers/leases/{}";
private static final String NUMBER_CONFIGS_PATH = "/numbers/leases/configs";
private static final String NUMBER_CONFIGS_ITEM_PATH = "/numbers/leases/configs/{}";
private RestApiClient client;
public NumberLeasesApi(RestApiClient client) {
this.client = client;
}
/**
* Find number leases by prefix, zipcode, etc...
* This API is useful for finding all numbers currently owned by an account.
*
* @param request request payload
* @return page of number leases
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<NumberLease> find(FindNumberLeasesRequest request) {
return client.get(NUMBER_LEASES_PATH, pageOf(NumberLease.class), request);
}
/**
* Get number lease by number
*
* @param number leased phone number
* @return object which represents number lease
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public NumberLease get(String number) {
return get(number, null);
}
/**
* Get number lease by number
*
* @param number leased phone number
* @param fields Limit fields returned. Example fields=id,name
* @return object which represents number lease
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public NumberLease get(String number, String fields) {
Validate.notBlank(number, "number cannot be blank");
List<NameValuePair> queryParams = new ArrayList<>();
addQueryParamIfSet("fields", fields, queryParams);
String path = NUMBER_LEASES_ITEM_PATH.replaceFirst(PLACEHOLDER, number);
return client.get(path, of(NumberLease.class), queryParams);
}
/**
* Update number lease
*
* @param lease update payload
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void update(NumberLease lease) {
Validate.notBlank(lease.getNumber(), "lease.number cannot be blank");
client.put(NUMBER_LEASES_ITEM_PATH.replaceFirst(PLACEHOLDER, lease.getNumber()), null, lease);
}
/**
* Find all number lease configs for the user.
*
* @param request request payload
* @return page of number leases configs
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<NumberConfig> findConfigs(FindNumberLeaseConfigsRequest request) {
return client.get(NUMBER_CONFIGS_PATH, pageOf(NumberConfig.class), request);
}
/**
* Get number lease config
*
* @param number leased phone number
* @return object which represents number lease config
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public NumberConfig getConfig(String number) {
return getConfig(number, null);
}
/**
* Get number lease config
*
* @param number leased phone number
* @param fields Limit fields returned. Example fields=id,name
* @return object which represents number lease config
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public NumberConfig getConfig(String number, String fields) {
Validate.notBlank(number, "number cannot be blank");
List<NameValuePair> queryParams = new ArrayList<>();
addQueryParamIfSet("fields", fields, queryParams);
String path = NUMBER_CONFIGS_ITEM_PATH.replaceFirst(PLACEHOLDER, number);
return client.get(path, of(NumberConfig.class), queryParams);
}
/**
* Update number lease config
*
* @param config update payload
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void updateConfig(NumberConfig config) {
Validate.notBlank(config.getNumber(), "config.number cannot be blank");
client.put(NUMBER_CONFIGS_ITEM_PATH.replaceFirst(PLACEHOLDER, config.getNumber()), null, config);
}
}
<file_sep>package com.callfire.api.client.integration.numbers;
import static com.callfire.api.client.api.numbers.model.NumberConfig.ConfigType.TRACKING;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.HashSet;
import org.junit.Test;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.common.model.DayOfWeek;
import com.callfire.api.client.api.common.model.LocalTime;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.WeeklySchedule;
import com.callfire.api.client.api.numbers.NumberLeasesApi;
import com.callfire.api.client.api.numbers.model.CallTrackingConfig;
import com.callfire.api.client.api.numbers.model.GoogleAnalytics;
import com.callfire.api.client.api.numbers.model.NumberConfig;
import com.callfire.api.client.api.numbers.model.NumberLease;
import com.callfire.api.client.api.numbers.model.NumberLease.FeatureStatus;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeaseConfigsRequest;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeasesRequest;
import com.callfire.api.client.integration.AbstractIntegrationTest;
import lombok.extern.slf4j.Slf4j;
/**
* integration tests for /numbers/leases api endpoint
*/
@Slf4j
public class NumberLeasesApiTest extends AbstractIntegrationTest {
@Test
public void testFindNumberLeases() {
CallfireClient callfireClient = getCallfireClient();
FindNumberLeasesRequest request = FindNumberLeasesRequest.create()
.limit(2L)
.build();
Page<NumberLease> leases = callfireClient.numberLeasesApi().find(request);
assertEquals(2, leases.getItems().size());
assertFalse(leases.getItems().get(0).getLabels().isEmpty());
log.info("{}", leases);
}
@Test
public void testGetNumberLease() {
CallfireClient callfireClient = getCallfireClient();
String number = getDid3();
NumberLease lease = callfireClient.numberLeasesApi().get(number);
assertNotNull(lease.getRegion());
assertEquals(number, lease.getNumber());
assertFalse(lease.getLabels().isEmpty());
assertThat(lease.getRegion().getCity(), containsString("LOS ANGELES"));
log.info("{}", lease);
}
@Test
public void testUpdateNumberLease() {
CallfireClient callfireClient = getCallfireClient();
String number = getDid3();
NumberLeasesApi api = callfireClient.numberLeasesApi();
NumberLease lease = api.get(number);
assertNotNull(lease.getRegion());
lease.setNumber(number);
lease.setTextFeatureStatus(FeatureStatus.DISABLED);
lease.setCallFeatureStatus(FeatureStatus.DISABLED);
api.update(lease);
lease = api.get(number, "number,callFeatureStatus,textFeatureStatus");
assertNotNull(lease.getNumber());
assertEquals(FeatureStatus.DISABLED, lease.getCallFeatureStatus());
assertEquals(FeatureStatus.DISABLED, lease.getTextFeatureStatus());
lease.setTextFeatureStatus(FeatureStatus.ENABLED);
lease.setCallFeatureStatus(FeatureStatus.ENABLED);
api.update(lease);
log.info("{}", lease);
}
@Test
public void testFindNumberLeaseConfigs() {
CallfireClient callfireClient = getCallfireClient();
FindNumberLeaseConfigsRequest request = FindNumberLeaseConfigsRequest.create()
.limit(2L)
.build();
Page<NumberConfig> configs = callfireClient.numberLeasesApi().findConfigs(request);
assertEquals(2, configs.getItems().size());
log.info("{}", configs);
}
@Test
public void testGetNumberLeaseConfig() {
CallfireClient callfireClient = getCallfireClient();
NumberConfig config = callfireClient.numberLeasesApi().getConfig(getDid3());
assertEquals(TRACKING, config.getConfigType());
assertNotNull(config.getCallTrackingConfig());
log.info("{}", config);
}
@Test
public void testUpdateNumberLeaseConfig() {
CallfireClient callfireClient = getCallfireClient();
String number = getDid3();
NumberLeasesApi api = callfireClient.numberLeasesApi();
NumberConfig config = api.getConfig(number, "number,configType,callTrackingConfig");
assertNull(config.getIvrInboundConfig());
assertEquals(TRACKING, config.getConfigType());
config.setConfigType(NumberConfig.ConfigType.TRACKING);
CallTrackingConfig callTrackingConfig = new CallTrackingConfig();
callTrackingConfig.setScreen(true);
callTrackingConfig.setRecorded(true);
callTrackingConfig.setTransferNumbers(asList("12132212384"));
callTrackingConfig.setVoicemail(true);
callTrackingConfig.setIntroSoundId(9643523003L);
callTrackingConfig.setVoicemailSoundId(9643523003L);
callTrackingConfig.setFailedTransferSoundId(9643523003L);
callTrackingConfig.setWhisperSoundId(9643523003L);
WeeklySchedule weeklySchedule = new WeeklySchedule();
weeklySchedule.setStartTimeOfDay(new LocalTime(1, 1, 1));
weeklySchedule.setStopTimeOfDay(new LocalTime(2, 2, 2));
weeklySchedule.setDaysOfWeek(new HashSet<>(Arrays.asList(DayOfWeek.MONDAY, DayOfWeek.FRIDAY)));
weeklySchedule.setTimeZone("America/New_York");
callTrackingConfig.setWeeklySchedule(weeklySchedule);
GoogleAnalytics googleAnalytics = new GoogleAnalytics();
googleAnalytics.setCategory("Sales");
googleAnalytics.setGoogleAccountId("UA-12345-26");
googleAnalytics.setDomain("testDomain");
callTrackingConfig.setGoogleAnalytics(googleAnalytics);
config.setCallTrackingConfig(callTrackingConfig);
api.updateConfig(config);
config = api.getConfig(number, "callTrackingConfig,configType");
assertNotNull(config.getCallTrackingConfig());
assertNull(config.getNumber());
assertEquals(TRACKING, config.getConfigType());
log.info("{}", config);
}
}
<file_sep>package com.callfire.api.client.integration.callstexts;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Date;
import org.junit.Test;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.callstexts.model.Media;
import com.callfire.api.client.api.callstexts.model.MediaType;
import com.callfire.api.client.api.callstexts.model.request.FindMediaRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /media api endpoint
*/
public class MediaApiTest extends AbstractIntegrationTest {
public static final String TRAIN_MP3 = "file-examples/train1.mp3";
public static final String TRAIN_WAV = "file-examples/train1.wav";
@Test
public void testFind() throws Exception {
CallfireClient callfireClient = getCallfireClient();
File cfLogoFile = new File(getClass().getClassLoader().getResource("file-examples/cf.png").toURI());
File ezLogoFile = new File(getClass().getClassLoader().getResource("file-examples/ez.png").toURI());
ResourceId cfResourceId = callfireClient.mediaApi().upload(ezLogoFile);
ResourceId ezResourceId = callfireClient.mediaApi().upload(cfLogoFile);
assertNotNull(cfResourceId.getId());
assertNotNull(ezResourceId.getId());
Page<Media> mediaPage = callfireClient.mediaApi().find(FindMediaRequest.create().filter("cf.png").build());
assertEquals(1, mediaPage.getItems().size());
}
@Test
public void testUpload() throws Exception {
CallfireClient callfireClient = getCallfireClient();
File mp3File = new File(getClass().getClassLoader().getResource(TRAIN_MP3).toURI());
File wavFile = new File(getClass().getClassLoader().getResource(TRAIN_WAV).toURI());
ResourceId wavResourceId = callfireClient.mediaApi().upload(wavFile);
ResourceId mp3ResourceId = callfireClient.mediaApi().upload(mp3File, createMp3FileName());
assertNotNull(wavResourceId.getId());
assertNotNull(mp3ResourceId.getId());
}
@Test
public void testGet() throws Exception {
CallfireClient callfireClient = getCallfireClient();
File mp3File = new File(getClass().getClassLoader().getResource(TRAIN_MP3).toURI());
ResourceId mp3ResourceId;
try
{
mp3ResourceId = callfireClient.mediaApi().upload(mp3File, createMp3FileName());
}
catch (BadRequestException e)
{
mp3ResourceId = new ResourceId();
mp3ResourceId.setId(selectIdFromBadRequestErrorString(e.getApiErrorMessage().getMessage()));
}
Media media = callfireClient.mediaApi().get(mp3ResourceId.getId());
assertNotNull(media);
assertTrue(media.getName().contains("mp3_test_"));
assertEquals(media.getId(), mp3ResourceId.getId());
assertEquals(media.getMediaType(), MediaType.MP3);
assertNotNull(media.getLengthInBytes());
assertNotNull(media.getCreated());
assertNotNull(media.getPublicUrl());
media = callfireClient.mediaApi().get(mp3ResourceId.getId(), "id,created");
assertNull(media.getName());
assertNull(media.getLengthInBytes());
assertNull(media.getPublicUrl());
assertNull(media.getMediaType());
}
@Test
public void testGetDataById() throws Exception {
CallfireClient callfireClient = getCallfireClient();
File mp3File = new File(getClass().getClassLoader().getResource(TRAIN_MP3).toURI());
ResourceId mp3ResourceId;
try
{
mp3ResourceId = callfireClient.mediaApi().upload(mp3File, createMp3FileName());
}
catch (BadRequestException e)
{
mp3ResourceId = new ResourceId();
mp3ResourceId.setId(selectIdFromBadRequestErrorString(e.getApiErrorMessage().getMessage()));
}
try
{
InputStream is = callfireClient.mediaApi().getData(mp3ResourceId.getId(), MediaType.MP3);
File tempFile = File.createTempFile("mp3_sound", "mp3");
Files.copy(is, tempFile.toPath(), REPLACE_EXISTING);
}
catch (CallfireApiException e)
{
assertTrue(e.getApiErrorMessage().getMessage().contains("file currently unavailable for mediaId:"));
}
}
@Test
public void testGetDataByKey() throws Exception {
CallfireClient callfireClient = getCallfireClient();
File mp3File = new File(getClass().getClassLoader().getResource(TRAIN_MP3).toURI());
ResourceId mp3ResourceId;
try
{
mp3ResourceId = callfireClient.mediaApi().upload(mp3File, createMp3FileName());
}
catch (BadRequestException e)
{
mp3ResourceId = new ResourceId();
mp3ResourceId.setId(selectIdFromBadRequestErrorString(e.getApiErrorMessage().getMessage()));
}
Media media = callfireClient.mediaApi().get(mp3ResourceId.getId());
try
{
InputStream is = callfireClient.mediaApi().getData(selectHashPartFromUrlString(media.getPublicUrl()), MediaType.MP3);
File tempFile = File.createTempFile("mp3_sound", "mp3");
Files.copy(is, tempFile.toPath(), REPLACE_EXISTING);
}
catch (CallfireApiException e)
{
assertTrue(e.getApiErrorMessage().getMessage().contains("file currently unavailable for mediaId:"));
}
}
private static String createMp3FileName() {
long timestamp = new Date().getTime();
return"mp3_test_" + timestamp;
}
private static long selectIdFromBadRequestErrorString(String message){
return Long.parseLong(message.substring(message.indexOf("mediaId:") + 9));
}
private static String selectHashPartFromUrlString(String message){
int hashStartedAt = message.indexOf("public/") + 7;
int hashFinishedAt = message.lastIndexOf('.');
return message.substring(hashStartedAt, hashFinishedAt);
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.AbstractBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = PRIVATE)
public class AgentInviteRequest extends CallfireModel {
private List<Long> agentsIds;
private List<String> agentEmails;
private Boolean sendEmail;
@JsonIgnore private Long campaignId;
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
public static class Builder extends AbstractBuilder<AgentInviteRequest> {
private Builder() {
super(new AgentInviteRequest());
}
public Builder sendEmail(Boolean sendEmail) {
request.sendEmail = sendEmail;
return this;
}
public Builder agentEmails(List<String> agentEmails) {
request.agentEmails = agentEmails;
return this;
}
public Builder agentsIds(List<Long> agentsIds) {
request.agentsIds = agentsIds;
return this;
}
public Builder campaignId(Long campaignId) {
request.campaignId = campaignId;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.numbers;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.HashSet;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.common.model.DayOfWeek;
import com.callfire.api.client.api.common.model.LocalTime;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.WeeklySchedule;
import com.callfire.api.client.api.numbers.model.CallTrackingConfig;
import com.callfire.api.client.api.numbers.model.GoogleAnalytics;
import com.callfire.api.client.api.numbers.model.NumberConfig;
import com.callfire.api.client.api.numbers.model.NumberConfig.ConfigType;
import com.callfire.api.client.api.numbers.model.NumberLease;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeaseConfigsRequest;
import com.callfire.api.client.api.numbers.model.request.FindNumberLeasesRequest;
public class NumberLeasesApiTest extends AbstractApiTest {
private static final String JSON_PATH = BASE_PATH + "/numbers/numberLeasesApi";
@Test
public void testFind() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/response/findNumberLeases.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindNumberLeasesRequest request = FindNumberLeasesRequest.create()
.limit(5L)
.offset(0L)
.state("LA")
.labelName("label")
.build();
Page<NumberLease> leases = client.numberLeasesApi().find(request);
assertThat(jsonConverter.serialize(leases), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertUriContainsQueryParams(arg.getURI(), "limit=5", "offset=0", "state=LA", "labelName=label");
}
@Test
public void testGet() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/response/getNumberLease.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
NumberLease lease = client.numberLeasesApi().get("12345678901", FIELDS);
assertThat(jsonConverter.serialize(lease), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
client.numberLeasesApi().get("12345678901");
assertEquals(2, captor.getAllValues().size());
assertThat(captor.getAllValues().get(1).getURI().toString(), not(containsString("fields")));
}
@Test
public void testGetNullNumber() {
ex.expectMessage("number cannot be blank");
ex.expect(NullPointerException.class);
client.numberLeasesApi().get(null);
}
@Test
public void testUpdate() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/request/updateNumberLease.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
NumberLease lease = new NumberLease();
lease.setNumber("12345678901");
lease.setAutoRenew(false);
client.numberLeasesApi().update(lease);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(expectedJson));
assertThat(arg.getURI().toString(), containsString("/numbers/leases/12345678901"));
}
@Test
public void testUpdateNullNumber() {
ex.expectMessage("number cannot be blank");
ex.expect(NullPointerException.class);
client.numberLeasesApi().update(new NumberLease());
}
@Test
public void testFindConfigs() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/response/findNumberLeaseConfigs.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindNumberLeaseConfigsRequest request = FindNumberLeaseConfigsRequest.create()
.limit(5L)
.offset(0L)
.state("LA")
.labelName("label")
.build();
Page<NumberConfig> configs = client.numberLeasesApi().findConfigs(request);
assertThat(jsonConverter.serialize(configs), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertUriContainsQueryParams(arg.getURI(), "limit=5", "offset=0", "state=LA", "labelName=label");
}
@Test
public void testGetConfig() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/response/getNumberLeaseConfig.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
NumberConfig config = client.numberLeasesApi().getConfig("12345678901", FIELDS);
assertThat(jsonConverter.serialize(config), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
client.numberLeasesApi().getConfig("12345678901");
assertEquals(2, captor.getAllValues().size());
assertThat(captor.getAllValues().get(1).getURI().toString(), not(containsString("fields")));
}
@Test
public void testGetConfigNullNumber() {
ex.expectMessage("number cannot be blank");
ex.expect(NullPointerException.class);
client.numberLeasesApi().getConfig(null);
ex.expectMessage("number cannot be blank");
ex.expect(NullPointerException.class);
client.numberLeasesApi().getConfig(null, FIELDS);
}
@Test
public void testUpdateConfig() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/request/updateNumberLeaseConfig.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
NumberConfig config = new NumberConfig();
config.setNumber("12345678901");
config.setConfigType(ConfigType.TRACKING);
CallTrackingConfig callTrackingConfig = new CallTrackingConfig();
callTrackingConfig.setScreen(false);
callTrackingConfig.setRecorded(true);
callTrackingConfig.setTransferNumbers(asList("12135551122", "12135551189"));
callTrackingConfig.setVoicemail(true);
callTrackingConfig.setIntroSoundId(1234L);
callTrackingConfig.setVoicemailSoundId(1234L);
callTrackingConfig.setFailedTransferSoundId(1234L);
callTrackingConfig.setWhisperSoundId(1234L);
callTrackingConfig.setWeeklySchedule(new WeeklySchedule(
new LocalTime(1, 1, 1),
new LocalTime(2, 2, 2),
new HashSet<>(singletonList(DayOfWeek.FRIDAY)),
"America/Los_Angeles"
));
GoogleAnalytics googleAnalytics = new GoogleAnalytics();
googleAnalytics.setCategory("Sales");
googleAnalytics.setGoogleAccountId("UA-12345-26");
googleAnalytics.setDomain("testDomain");
callTrackingConfig.setGoogleAnalytics(googleAnalytics);
config.setCallTrackingConfig(callTrackingConfig);
client.numberLeasesApi().updateConfig(config);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(expectedJson));
assertThat(arg.getURI().toString(), containsString("/numbers/leases/configs/12345678901"));
}
@Test
public void testUpdateConfigNullNumber() {
ex.expectMessage("number cannot be blank");
ex.expect(NullPointerException.class);
client.numberLeasesApi().updateConfig(new NumberConfig());
}
}
<file_sep>package com.callfire.api.client.integration.account;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.account.model.NumberOrder;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.keywords.model.request.KeywordPurchaseRequest;
import com.callfire.api.client.api.numbers.model.request.NumberPurchaseRequest;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /orders api endpoint
*/
public class OrdersApiTest extends AbstractIntegrationTest {
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void testOrderKeywords() throws Exception {
CallfireClient callfireClient = getCallfireClient();
KeywordPurchaseRequest request = KeywordPurchaseRequest.create()
.keywords(asList("TEST1", "TEST2"))
.build();
ex.expect(CallfireApiException.class);
ex.expect(hasProperty("apiErrorMessage", hasProperty("httpStatusCode", is(400))));
ex.expect(hasProperty("apiErrorMessage", hasProperty("message", equalTo("no valid credit card on file"))));
ResourceId resourceId = callfireClient.ordersApi().orderKeywords(request);
assertNotNull(resourceId.getId());
NumberOrder order = callfireClient.ordersApi().getOrder(resourceId.getId());
System.out.println(order);
expect404NotFoundCallfireApiException(ex);
callfireClient.ordersApi().getOrder(1L);
}
@Test
public void testOrderNumbers() throws Exception {
CallfireClient callfireClient = getCallfireClient();
NumberPurchaseRequest request = NumberPurchaseRequest.create()
.numbers(asList(getDid1()))
.build();
ex.expect(CallfireApiException.class);
ex.expect(hasProperty("apiErrorMessage", hasProperty("httpStatusCode", is(400))));
ex.expect(hasProperty("apiErrorMessage", hasProperty("message", equalTo("unavailable numbers: 12132212289"))));
ResourceId resourceId = callfireClient.ordersApi().orderNumbers(request);
assertNotNull(resourceId.getId());
NumberOrder order = callfireClient.ordersApi().getOrder(resourceId.getId());
System.out.println(order);
expect404NotFoundCallfireApiException(ex);
callfireClient.ordersApi().getOrder(1L);
}
}
<file_sep>package com.callfire.api.client.api.numbers.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
@Getter
public class Region extends CallfireModel {
private String prefix;
private String city;
private String state;
private String zipcode;
private String country;
private String lata;
private String rateCenter;
private Double latitude;
private Double longitude;
private String timeZone;
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Deprecated
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CccCampaign extends Broadcast {
private Script script;
private String smartDropSoundText;
private Voice smartDropSoundTextVoice;
private Long smartDropSoundId;
private Boolean recorded;
private Boolean allowAnyTransfer;
private Integer multilineDialingRatio;
private Boolean multilineDialingEnabled;
private Integer scrubLevel;
@Builder.Default private List<Agent> agents = new ArrayList<>();
@Builder.Default private List<AgentGroup> agentGroups = new ArrayList<>();
@Builder.Default private List<TransferNumber> transferNumbers = new ArrayList<>();
}
<file_sep>package com.callfire.api.client.api.account.model.request;
import java.util.Date;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.AbstractBuilder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Contains intervalBegin and intervalEnd fields for date range filtering
*/
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class DateIntervalRequest extends CallfireModel {
/**
* Gets beginning of filtering period
*
* @return beginning of filtering period
*/
private Date intervalBegin;
/**
* Gets end of filtering period
*
* @return end of filtering period
*/
private Date intervalEnd;
@Deprecated
public static Builder create() {
return new Builder();
}
@Deprecated
public static class Builder extends AbstractBuilder<DateIntervalRequest> {
private Builder() {
super(new DateIntervalRequest());
}
public Builder intervalBegin(Date intervalBegin) {
request.intervalBegin = intervalBegin;
return this;
}
public Builder intervalEnd(Date intervalEnd) {
request.intervalEnd = intervalEnd;
return this;
}
}
}
<file_sep>package com.callfire.api.client.integration.keywords;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.keywords.model.Keyword;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /keywords api endpoint
*/
public class KeywordsApiTest extends AbstractIntegrationTest {
@Test
public void testGetKeywordsInCatalog() throws Exception {
CallfireClient client = getCallfireClient();
String KW1 = "TESTAVAILABLE";
List<Keyword> keywords = client.keywordsApi().find(asList(KW1));
assertEquals(1, keywords.size());
assertThat(keywords, hasItem(Matchers.<Keyword>hasProperty("keyword", is(KW1))));
}
@Test
public void testIsKeywordAvailable() throws Exception {
CallfireClient client = getCallfireClient();
assertTrue(client.keywordsApi().isAvailable("TEST"));
}
}
<file_sep>package com.callfire.api.client.api.common.model;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ListHolder<T> extends CallfireModel {
protected List<T> items = new ArrayList<>();
}
<file_sep>package com.callfire.api.client.api.common.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Dto to represent date and time (year, month, day, hour, minute, second).
* 1 based date, 0 based time
* example (1964, 12, 25, 23, 0, 59)
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class LocalDateTime extends LocalDate {
private Integer hour;
private Integer minute;
private Integer second;
}
<file_sep>package com.callfire.api.client.integration.campaigns;
import static org.junit.Assert.assertNotEquals;
import org.junit.Test;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.campaigns.BatchesApi;
import com.callfire.api.client.api.campaigns.model.Batch;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /campaigns/batches api endpoint
*/
public class BatchesApiTest extends AbstractIntegrationTest {
@Test
public void testCrudOperations() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
BatchesApi api = callfireClient.batchesApi();
Batch batch = api.get(5283098003L);
System.out.println(batch);
Boolean enabled = batch.getEnabled();
batch.setEnabled(!enabled);
api.update(batch);
Batch updatedBatch = api.get(5283098003L);
assertNotEquals(updatedBatch.getEnabled(), enabled);
}
}
<file_sep>package com.callfire.api.client.api.campaigns;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.callstexts.model.Call;
import com.callfire.api.client.api.callstexts.model.Text;
import com.callfire.api.client.api.campaigns.model.Batch;
import com.callfire.api.client.api.campaigns.model.Recipient;
import com.callfire.api.client.api.campaigns.model.TextBroadcast;
import com.callfire.api.client.api.campaigns.model.TextBroadcastStats;
import com.callfire.api.client.api.campaigns.model.TextRecipient;
import com.callfire.api.client.api.campaigns.model.request.AddBatchRequest;
import com.callfire.api.client.api.campaigns.model.request.AddRecipientsRequest;
import com.callfire.api.client.api.campaigns.model.request.CreateBroadcastRequest;
import com.callfire.api.client.api.campaigns.model.request.FindBroadcastTextsRequest;
import com.callfire.api.client.api.campaigns.model.request.FindTextBroadcastsRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.common.model.request.GetByIdRequest;
/**
* Represents rest endpoint /texts/broadcasts
*
* @since 1.0
*/
public class TextBroadcastsApi {
private static final String TB_PATH = "/texts/broadcasts";
private static final String TB_ITEM_PATH = "/texts/broadcasts/{}";
private static final String TB_ITEM_BATCHES_PATH = "/texts/broadcasts/{}/batches";
private static final String TB_ITEM_TEXTS_PATH = "/texts/broadcasts/{}/texts";
private static final String TB_ITEM_START_PATH = "/texts/broadcasts/{}/start";
private static final String TB_ITEM_STOP_PATH = "/texts/broadcasts/{}/stop";
private static final String TB_ITEM_ARCHIVE_PATH = "/texts/broadcasts/{}/archive";
private static final String TB_ITEM_STATS_PATH = "/texts/broadcasts/{}/stats";
private static final String TB_ITEM_RECIPIENTS_PATH = "/texts/broadcasts/{}/recipients";
private static final String TB_ITEM_TOGGLE_RECIPIENTS_STATUS_PATH = "/texts/broadcasts/{}/toggleRecipientsStatus";
private RestApiClient client;
public TextBroadcastsApi(RestApiClient client) {
this.client = client;
}
/**
* Find all text broadcasts created by the user. Can query on label, name, and the current
* running status of the campaign.
*
* @param request finder request with properties to search by
* @return {@link Page} with {@link TextBroadcast} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<TextBroadcast> find(FindTextBroadcastsRequest request) {
return client.get(TB_PATH, pageOf(TextBroadcast.class), request);
}
/**
* Create a text broadcast campaign using the Text Broadcast API. A campaign can be created with
* no contacts and bare minimum configuration, but contacts will have to be added further on to use the campaign.
*
* @param broadcast text broadcast to create
* @return {@link ResourceId} object with id of created broadcast
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ResourceId create(TextBroadcast broadcast) {
return create(broadcast, null);
}
/**
* Create a text broadcast campaign using the Text Broadcast API. A campaign can be created with
* no contacts and bare minimum configuration, but contacts will have to be added further on to use the campaign.
* If start set to true campaign starts immediately
*
* @param broadcast text broadcast to create
* @param start if set to true broadcast will starts immediately
* @return {@link ResourceId} object with id of created broadcast
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ResourceId create(TextBroadcast broadcast, Boolean start) {
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("start", start, queryParams);
return client.post(TB_PATH, of(ResourceId.class), broadcast, queryParams);
}
/**
* Create a text broadcast campaign using the Text Broadcast API. A campaign can be created with
* no contacts and bare minimum configuration, but contacts will have to be added further on to use the campaign.
* If start set to true campaign starts immediately
*
* @param request request to create text broadcast
* @return {@link ResourceId} object with id of created broadcast
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ResourceId create(CreateBroadcastRequest<TextBroadcast> request) {
return client.post(TB_PATH, of(ResourceId.class), request.getBroadcast(), request);
}
/**
* Get text broadcast by id
*
* @param id id of broadcast
* @return {@link TextBroadcast} object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextBroadcast get(Long id) {
return get(id, null);
}
/**
* Get text broadcast by id
*
* @param id id of broadcast
* @param fields limit fields returned. Example fields=id,message
* @return {@link TextBroadcast} object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextBroadcast get(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
return client.get(TB_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString()), of(TextBroadcast.class), queryParams);
}
/**
* Update text broadcast
*
* @param broadcast broadcast to update
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void update(TextBroadcast broadcast) {
update(broadcast, null);
}
/**
* Update text broadcast
*
* @param broadcast broadcast to update
* @param strictValidation strict validation flag for broadcast
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void update(TextBroadcast broadcast, Boolean strictValidation) {
Validate.notNull(broadcast.getId(), "broadcast.id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("strictValidation", strictValidation, queryParams);
client.put(TB_ITEM_PATH.replaceFirst(PLACEHOLDER, broadcast.getId().toString()), null, broadcast, queryParams);
}
/**
* Starts text campaign
*
* @param id id of campaign
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void start(Long id) {
Validate.notNull(id, "id cannot be null");
client.post(TB_ITEM_START_PATH.replaceFirst(PLACEHOLDER, id.toString()), null, null);
}
/**
* Stops text campaign
*
* @param id id of campaign
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void stop(Long id) {
Validate.notNull(id, "id cannot be null");
client.post(TB_ITEM_STOP_PATH.replaceFirst(PLACEHOLDER, id.toString()), null, null);
}
/**
* Archives text campaign
*
* @param id id of campaign
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void archive(Long id) {
Validate.notNull(id, "id cannot be null");
client.post(TB_ITEM_ARCHIVE_PATH.replaceFirst(PLACEHOLDER, id.toString()), null, null);
}
/**
* Get text broadcast batches. Retrieve batches associated with text campaign
*
* @param request get request
* @return {@link Page} with {@link Batch} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<Batch> getBatches(GetByIdRequest request) {
String path = TB_ITEM_BATCHES_PATH.replaceFirst(PLACEHOLDER, request.getId().toString());
return client.get(path, pageOf(Batch.class), request);
}
/**
* Add batch to text broadcast.
* The add batch API allows the user to add additional batches to an already created text broadcast
* campaign. The added batch will go through the CallFire validation process, unlike in the
* recipients version of this API. Because of this, use the scrubDuplicates flag to remove duplicates
* from your batch. Batches may be added as a contact list id, a list of contact ids, or a list of numbers.
*
* @param request request with contacts
* @return {@link ResourceId} with id of created {@link Batch}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ResourceId addBatch(AddBatchRequest request) {
String path = TB_ITEM_BATCHES_PATH.replaceFirst(PLACEHOLDER, request.getCampaignId().toString());
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("strictValidation", request.getStrictValidation(), queryParams);
return client.post(path, of(ResourceId.class), request, queryParams);
}
/**
* @deprecated this method will be removed soon, please use findTexts() instead
*
* Get texts associated with text broadcast ordered by date
*
* @param request request with properties to filter
* @return {@link Page} with {@link Call} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
@Deprecated
public Page<Text> getTexts(GetByIdRequest request) {
String path = TB_ITEM_TEXTS_PATH.replaceFirst(PLACEHOLDER, request.getId().toString());
return client.get(path, pageOf(Text.class), request);
}
/**
* Get texts associated with text broadcast ordered by date
*
* @param request request with properties to filter
* @return {@link Page} with {@link Call} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<Text> findTexts(FindBroadcastTextsRequest request) {
String path = TB_ITEM_TEXTS_PATH.replaceFirst(PLACEHOLDER, request.getId().toString());
return client.get(path, pageOf(Text.class), request);
}
/**
* Get statistics on text broadcast
*
* @param id text broadcast id
* @return broadcast stats object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextBroadcastStats getStats(Long id) {
return getStats(id, null, null, null);
}
/**
* Get statistics on text broadcast
*
* @param id text broadcast id
* @param fields limit fields returned. Example fields=id,message
* @param begin begin date to filter
* @param end end date to filter
* @return broadcast stats object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextBroadcastStats getStats(Long id, String fields, Date begin, Date end) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(3);
addQueryParamIfSet("fields", fields, queryParams);
addQueryParamIfSet("begin", begin, queryParams);
addQueryParamIfSet("end", end, queryParams);
String path = TB_ITEM_STATS_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(TextBroadcastStats.class), queryParams);
}
/**
* Use this API to add recipients to an already created text broadcast. Post a list of Recipient
* objects for them to be immediately added to the text broadcast campaign. These contacts do not
* go through validation process, and will be acted upon as they are added. Recipients may be added
* as a list of contact ids, or list of numbers.
*
* @param id id of text broadcast
* @param recipients recipients to add
* @return list of {@link ResourceId} with recipient ids
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Text> addRecipients(Long id, List<TextRecipient> recipients) {
return addRecipients(id, recipients, null);
}
/**
* Use this API to add recipients to an already created text broadcast. Post a list of Recipient
* objects for them to be immediately added to the text broadcast campaign. These contacts do not
* go through validation process, and will be acted upon as they are added. Recipients may be added
* as a list of contact ids, or list of numbers.
*
* @param id id of text broadcast
* @param recipients recipients to add
* @param fields limit fields returned. E.g. fields=id,name or fields=items(id,name)
* @return Text objects which were sent to recipients
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Text> addRecipients(Long id, List<TextRecipient> recipients, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = TB_ITEM_RECIPIENTS_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.post(path, listHolderOf(Text.class), recipients, queryParams).getItems();
}
/**
* Use this API to add recipients to an already created text broadcast. Post a list of Recipient
* objects for them to be immediately added to the text broadcast campaign. These contacts do not
* go through validation process, and will be acted upon as they are added. Recipients may be added
* as a list of contact ids, or list of numbers.
*
* @param request request with properties for adding recipients
* @return Text objects which were sent to recipients
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Text> addRecipients(AddRecipientsRequest request) {
String path = TB_ITEM_RECIPIENTS_PATH.replaceFirst(PLACEHOLDER, request.getCampaignId().toString());
return client.post(path, listHolderOf(Text.class), request.getRecipients(), request).getItems();
}
/**
* Use this API to toggle not dialed recipients in created text broadcast. Post a list of Recipient
* objects which will be immediately disabled/enabled if still not sent. Recipients may be added
* as a list of contact ids, or list of numbers. If recipients array contains already dialed contact - it would be ignored.
*
* @param id id of call broadcast
* @param recipients recipients to add
* @param enable flag to indicate action (true is enabling and vice versa)
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void toggleRecipientsStatus(Long id, List<Recipient> recipients, Boolean enable) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("enable", enable, queryParams);
String path = TB_ITEM_TOGGLE_RECIPIENTS_STATUS_PATH.replaceFirst(PLACEHOLDER, id.toString());
client.post(path, null, recipients, queryParams);
}
}
<file_sep>plugins {
id 'com.jfrog.bintray' version '1.8.4'
id 'co.riiid.gradle' version '0.4.2'
id 'io.freefair.lombok' version '4.1.5'
id 'idea'
id 'java'
id 'maven'
}
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
ext {
versions = [:]
versions.jackson = '2.10.0'
versions.httpclient = '4.5.10'
versions.commonsLang = '3.9'
versions.junit = '4.12'
versions.hamcrest = '1.3'
versions.mockito = '3.1.0'
versions.jsonassert = '1.5.0'
versions.slf4j = '1.7.29'
}
repositories {
jcenter()
mavenCentral()
}
sourceSets {
itest {
compileClasspath += main.output
runtimeClasspath += main.output
java.srcDir file('src/itest/java')
}
}
generateLombokConfig.enabled = false
configurations {
itestCompileOnly.extendsFrom compileOnly
itestAnnotationProcessor.extendsFrom annotationProcessor
itestImplementation.extendsFrom implementation
itestImplementation.extendsFrom testImplementation
}
idea {
module {
downloadSources = true
downloadJavadoc = true
testSourceDirs = testSourceDirs + sourceSets.itest.allJava.srcDirs
testResourceDirs = testResourceDirs + sourceSets.itest.resources.srcDirs
}
}
build {
dependsOn javadoc
}
processResources {
expand(project.properties)
}
dependencies {
implementation "com.fasterxml.jackson.core:jackson-core:${versions.jackson}"
implementation "com.fasterxml.jackson.core:jackson-annotations:${versions.jackson}"
implementation "com.fasterxml.jackson.core:jackson-databind:${versions.jackson}"
implementation "org.apache.httpcomponents:httpclient:${versions.httpclient}"
implementation "org.apache.httpcomponents:httpmime:${versions.httpclient}"
implementation "org.apache.commons:commons-lang3:${versions.commonsLang}"
testImplementation("junit:junit:${versions.junit}") {
exclude module: 'hamcrest'
exclude module: 'hamcrest-core'
}
testImplementation "org.hamcrest:hamcrest-all:${versions.hamcrest}"
testImplementation "org.mockito:mockito-core:${versions.mockito}"
testImplementation "org.skyscreamer:jsonassert:${versions.jsonassert}"
testImplementation "org.slf4j:slf4j-api:${versions.slf4j}"
testImplementation "org.slf4j:slf4j-simple:${versions.slf4j}"
}
task itest(type: Test) {
testClassesDirs = sourceSets.itest.output.classesDirs
classpath = sourceSets.itest.runtimeClasspath + sourceSets.test.runtimeClasspath
systemProperty "testApiUsername", sysProp("testApiUsername")
systemProperty "testApiPassword", sysProp("<PASSWORD>")
systemProperty "testAccountName", sysProp("testAccountName")
systemProperty "testAccountPassword", sysProp("<PASSWORD>")
systemProperty "testCallerId", sysProp("testCallerId")
}
task sourcesJar(type: Jar, dependsOn: classes) {
archiveClassifier.set('sources')
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
archiveClassifier.set('javadoc')
from javadoc.destinationDir
}
task clientFatJar(type: Jar, dependsOn: jar) {
archiveClassifier.set('all')
from {
[
sourceSets.main.output,
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
]
}
}
tasks.withType(Jar) {
manifest.attributes(
'Manifest-Version': '1.0',
'Implementation-Title': archiveBaseName,
'Implementation-Version': archiveVersion,
'Implementation-Build-Number': sysProp('BUILD_NUMBER'),
'Implementation-Vendor': project.orgName,
'Implementation-Build-Date': new Date().format('yyyy-MM-dd'),
'Implementation-Build-JDK': sysProp('java.version'),
'Implementation-Build-Gradle': gradle.gradleVersion,
'Implementation-Target-JDK': project.targetCompatibility,
'Description': project.description,
'Documentation': project.docsUrl,
'Repository': project.vcsUrl)
into('META-INF') { from 'LICENSE.txt' }
}
javadoc {
failOnError = false
source = delombok
}
task generatePom {
doLast {
pom {
project {
inceptionYear '2015'
licenses {
license {
name "The MIT License (MIT)"
url "https://opensource.org/licenses/MIT"
distribution "repo"
}
}
developers {
developer {
id "vladimir-mhl"
name "<NAME>"
email "<EMAIL>"
}
}
}
}
.withXml {
asNode().dependencies.'*'
.findAll { it.scope.text() == 'test' }
.each { it.parent().remove(it) }
}
.writeTo("build/META-INF/maven/${project.group}/${project.name}/pom.xml")
}
}
jar {
into('META-INF') {
from 'build/META-INF'
}
dependsOn generatePom
}
artifacts {
archives sourcesJar
archives javadocJar
}
github {
def assetPath = "build/libs/${project.name}-${project.version}"
repo = project.repoName
owner = sysProp('gitHubOwner')
token = sysProp('gitHubToken')
tagName = project.version
targetCommitish = 'master'
name = project.version
body = releaseNotes()
assets = [
"${assetPath}-all.jar",
"${assetPath}-javadoc.jar",
"${assetPath}-sources.jar",
"${assetPath}.jar"
]
}
bintray {
user = sysProp('BINTRAY_USER')
key = sysProp('BINTRAY_KEY')
configurations = ['archives']
publish = true
pkg {
repo = 'maven'
name = project.repoName
desc = project.description
websiteUrl = project.orgUrl
issueTrackerUrl = project.issueTrackerUrl
vcsUrl = project.vcsUrl
licenses = ['MIT']
labels = ['callfire', 'api', 'client']
publicDownloadNumbers = true
}
}
def releaseNotes() {
def matches = file('Changelog.txt').text =~ /(?s)Version .+?\n(.+?)(?=Version)/
matches.count > 0 ? matches[0][1] : 'N/A'
}
static def sysProp(String name) {
"${System.properties[name] ?: 'not set'}"
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Agent extends CallfireModel {
private Long id;
private Boolean enabled;
private String name;
private String email;
private Date lastLogin;
private Long activeSessionId;
@Builder.Default private List<Long> campaignIds = new ArrayList<>();
@Builder.Default private List<Long> groupIds = new ArrayList<>();
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Sounds for a CallBroadcast.
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CallBroadcastSounds {
private String liveSoundText;
private Voice liveSoundTextVoice;
private Long liveSoundId;
private String machineSoundText;
private Voice machineSoundTextVoice;
private Long machineSoundId;
private String transferSoundText;
private Voice transferSoundTextVoice;
private Long transferSoundId;
private String transferDigit;
private String transferNumber;
private String dncSoundText;
private Voice dncSoundTextVoice;
private Long dncSoundId;
private String dncDigit;
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.Date;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
@Getter
public class CampaignSound extends CallfireModel {
private Long id;
private String name;
private Date created;
private Integer lengthInSeconds;
private Status status;
private Boolean duplicate;
public enum Status {
UPLOAD,
RECORDING,
ACTIVE,
FAILED,
ARCHIVED
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum MediaType {
JPEG("jpeg", "image/jpeg"),
PNG("png", "image/png"),
BMP("bmp", "image/bmp"),
GIF("gif", "image/gif"),
MP4("mp4", "video/mp4"),
M4A("m4a", "audio/m4a"),
MP3("mp3", "audio/mp3"),
WAV("wav", "audio/x-wav"),
UNKNOWN("unknown", "application/octet-stream");
private String type;
private String mimeType;
MediaType(String type, String mimeType) {
this.type = type;
this.mimeType = mimeType;
}
@JsonCreator
public static MediaType fromMime(String mimeType) {
for (MediaType t : values()) {
if (Objects.equals(String.valueOf(t.mimeType), mimeType)) {
return t;
}
}
throw new IllegalArgumentException("there is no type for MediaType: " + mimeType);
}
public String getType() {
return type;
}
@JsonValue
public String getMimeType() {
return mimeType;
}
@Override
public String toString() {
return mimeType;
}
}
<file_sep>package com.callfire.api.client.api.numbers.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.AbstractBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = PRIVATE)
public class NumberPurchaseRequest extends CallfireModel {
private Integer tollFreeCount;
private Integer localCount;
private String prefix;
private String city;
private String state;
private String zipcode;
private String lata;
private String rateCenter;
private List<String> numbers = new ArrayList<>();
public static Builder create() {
return new Builder();
}
public static class Builder extends AbstractBuilder<NumberPurchaseRequest> {
private Builder() {
super(new NumberPurchaseRequest());
}
public Builder tollFreeCount(Integer tollFreeCount) {
request.tollFreeCount = tollFreeCount;
return this;
}
public Builder numbers(List<String> numbers) {
request.numbers = numbers;
return this;
}
public Builder rateCenter(String rateCenter) {
request.rateCenter = rateCenter;
return this;
}
public Builder localCount(Integer localCount) {
request.localCount = localCount;
return this;
}
public Builder prefix(String prefix) {
request.prefix = prefix;
return this;
}
public Builder city(String city) {
request.city = city;
return this;
}
public Builder lata(String lata) {
request.lata = lata;
return this;
}
public Builder zipcode(String zipcode) {
request.zipcode = zipcode;
return this;
}
public Builder state(String state) {
request.state = state;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.campaigns.model.Batch;
public class BatchesApiTest extends AbstractApiTest {
private static final String JSON_PATH = BASE_PATH + "/campaigns/batchesApi";
@Test
public void testGetNullId() {
ex.expectMessage("id cannot be null");
ex.expect(NullPointerException.class);
client.batchesApi().get(null);
}
@Test
public void testUpdate() throws Exception {
String expectedJson = getJsonPayload(JSON_PATH + "/request/updateBatch.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
Batch batch = new Batch();
batch.setId(11L);
batch.setEnabled(false);
client.batchesApi().update(batch);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(expectedJson));
assertThat(arg.getURI().toString(), containsString("/11"));
}
@Test
public void testUpdateNullId() {
ex.expectMessage("id cannot be null");
ex.expect(NullPointerException.class);
Batch batch = new Batch();
client.batchesApi().update(batch);
}
}
<file_sep>package com.callfire.api.client.api.contacts;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.api.common.model.request.GetByIdRequest;
import com.callfire.api.client.api.contacts.model.Contact;
import com.callfire.api.client.api.contacts.model.ContactHistory;
import com.callfire.api.client.api.contacts.model.request.FindContactsRequest;
/**
* Represents rest endpoint /contacts
*
* @since 1.0
*/
public class ContactsApi {
private static final String CONTACTS_PATH = "/contacts";
private static final String CONTACTS_ITEM_PATH = "/contacts/{}";
private static final String CONTACTS_ITEM_HISTORY_PATH = "/contacts/{}/history";
private RestApiClient client;
public ContactsApi(RestApiClient client) {
this.client = client;
}
/**
* Find contacts by id, contact list, or on any property name. Returns a paged list of contacts.
*
* @param request request object with different fields to filter
* @return {@link Page} with {@link Contact} objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<Contact> find(FindContactsRequest request) {
return client.get(CONTACTS_PATH, pageOf(Contact.class), request);
}
/**
* Create contacts in the CallFire system. These contacts are not validated on creation.
* They will be validated upon being added to a campaign.
*
* @param contacts contacts to create
* @return list of ids newly created contacts
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<ResourceId> create(List<Contact> contacts) {
return client.post(CONTACTS_PATH, listHolderOf(ResourceId.class), contacts).getItems();
}
/**
* Get contact by id. Deleted contacts can still be retrieved but will be marked deleted
* and will not show up when quering contacts.
*
* @param id id of contact
* @return requested contact
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Contact get(Long id) {
return get(id, null);
}
/**
* Get contact by id. Deleted contacts can still be retrieved but will be marked deleted
* and will not show up when quering contacts.
*
* @param id id of contact
* @param fields limit fields returned. Example fields=id,name
* @return requested contact
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Contact get(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
return client.get(CONTACTS_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString()), of(Contact.class), queryParams);
}
/**
* Update contact
*
* @param contact contact to update
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void update(Contact contact) {
Validate.notNull(contact.getId(), "contact.id cannot be null");
client.put(CONTACTS_ITEM_PATH.replaceFirst(PLACEHOLDER, contact.getId().toString()), null, contact);
}
/**
* Delete contact by id. This does not actually delete the contact, it just removes the contact from
* any contact lists and marks the contact as deleted so won't show up in queries anymore.
*
* @param id id of contact
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void delete(Long id) {
Validate.notNull(id, "id cannot be null");
client.delete(CONTACTS_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString()));
}
/**
* Find all texts and calls attributed to a contact.
*
* @param request request to get particular contact's history
* @return returns a list of calls and texts a contact has been involved with.
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ContactHistory getHistory(GetByIdRequest request) {
Validate.notNull(request.getId(), "request.id cannot be null");
String path = CONTACTS_ITEM_HISTORY_PATH.replaceFirst(PLACEHOLDER, request.getId().toString());
return client.get(path, of(ContactHistory.class), request);
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Represents text auto-reply object
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class TextAutoReply extends CallfireModel {
/**
* Unique ID of text auto reply
*
* @param id unique ID of text auto reply
* @return unique ID of text auto reply
*/
private Long id;
/**
* Phone number to configure an auto reply message
*
* @param number phone number to configure an auto reply message
* @return phone number to configure an auto reply message
*/
private String number;
/**
* Keyword associated with account
*
* @param keyword keyword associated with account
* @return keyword associated with account
*/
private String keyword;
/**
* Matching text is either null or empty which represents all matches.
* All other text, for example 'rocks', will be matched as case insensitive whole words.
*
* @param match text to match
* @return matching text is either null or empty which represents all matches.
*/
private String match;
/**
* Templated message to return as auto reply (ex: 'Here is an echo - ${text.message}')
*
* @param message templated message to set
* @return templated message
*/
private String message;
}
<file_sep>package com.callfire.api.client.api.common.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Dto to represent time (hour, minute, second)
* 0 based time, example (23, 0, 59)
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class LocalTime extends CallfireModel {
private Integer hour;
private Integer minute;
private Integer second;
}
<file_sep>package com.callfire.api.client.api.campaigns;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.campaigns.model.TextAutoReply;
import com.callfire.api.client.api.campaigns.model.request.FindTextAutoRepliesRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
/**
* Represents rest endpoint /texts/auto-replys
*
* @since 1.0
*/
public class TextAutoRepliesApi {
private static final String TEXT_AUTO_REPLIES_PATH = "/texts/auto-replys";
private static final String TEXT_AUTO_REPLIES_ITEM_PATH = "/texts/auto-replys/{}";
private RestApiClient client;
public TextAutoRepliesApi(RestApiClient client) {
this.client = client;
}
/**
* Query for text auto replies using optional number
*
* @param request request object with filtering options
* @return page with TextAutoReply objects
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<TextAutoReply> find(FindTextAutoRepliesRequest request) {
return client.get(TEXT_AUTO_REPLIES_PATH, pageOf(TextAutoReply.class), request);
}
/**
* Create and configure new text auto reply message for existing number.
* Auto-replies are text message replies sent to a customer when a customer replies to
* a text message from a campaign. A keyword will need to have been purchased before an Auto-Reply can be created.
*
* @param textAutoReply auto-reply object to create
* @return ResourceId object with id of created auto-reply
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ResourceId create(TextAutoReply textAutoReply) {
return client.post(TEXT_AUTO_REPLIES_PATH, of(ResourceId.class), textAutoReply);
}
/**
* Get text auto reply
*
* @param id id of text auto reply object
* @return text auto reply object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextAutoReply get(Long id) {
return get(id, null);
}
/**
* Get text auto reply
*
* @param id id of text auto reply object
* @param fields limit fields returned. Example fields=id,message
* @return text auto reply object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public TextAutoReply get(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = TEXT_AUTO_REPLIES_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(TextAutoReply.class), queryParams);
}
/**
* Delete text auto reply message attached to number.
* Can not delete a TextAutoReply currently active on a campaign.
*
* @param id id of text auto reply
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void delete(Long id) {
Validate.notNull(id, "id cannot be null");
client.delete(TEXT_AUTO_REPLIES_ITEM_PATH.replaceFirst(PLACEHOLDER, Objects.toString(id)));
}
}
<file_sep>package com.callfire.api.client.api.common.model.request;
import static lombok.AccessLevel.PRIVATE;
import org.apache.commons.lang3.Validate;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Common get request with id
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class GetByIdRequest extends FindRequest {
@QueryParamIgnore private Long id;
public static Builder create() {
return new Builder();
}
/**
* Request builder
*/
public static class Builder extends FindRequestBuilder<Builder, GetByIdRequest> {
private Builder() {
super(new GetByIdRequest());
}
public Builder id(Long id) {
request.id = id;
return this;
}
@Override
public GetByIdRequest build() {
Validate.notNull(request.id, "request.id cannot be null");
return super.build();
}
}
}
<file_sep>package com.callfire.api.client.api.contacts.model.request;
import static lombok.AccessLevel.PRIVATE;
import org.apache.commons.lang3.Validate;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for
* <p>
* PUT /contacts/dncs/{number}
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class UpdateDncRequest extends CallsTextsRequest {
/**
* Number of Dnc
*
* @return Number of Dnc
*/
@JsonIgnore private String number;
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends CallsTextsBuilder<Builder, UpdateDncRequest> {
/**
* Set Dnc number
*
* @param number dnc number to update
* @return builder self-reference
*/
public Builder number(String number) {
request.number = number;
return this;
}
private Builder() {
super(new UpdateDncRequest());
}
@Override
public UpdateDncRequest build() {
Validate.notNull(request.number, "number cannot be null");
return super.build();
}
}
}
<file_sep>package com.callfire.api.client.api.callstexts;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.callstexts.model.Action.State;
import com.callfire.api.client.api.callstexts.model.Text;
import com.callfire.api.client.api.callstexts.model.request.FindTextsRequest;
import com.callfire.api.client.api.callstexts.model.request.SendTextsRequest;
import com.callfire.api.client.api.campaigns.model.TextRecipient;
import com.callfire.api.client.api.common.model.ListHolder;
import com.callfire.api.client.api.common.model.Page;
public class TextsApiTest extends AbstractApiTest {
@Test
public void testSendTexts() throws Exception {
String requestJson = getJsonPayload("/callstexts/textsApi/request/sendTexts.json");
String responseJson = getJsonPayload("/callstexts/textsApi/response/sendTexts.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(responseJson);
TextRecipient r1 = new TextRecipient();
r1.setPhoneNumber("12135551100");
r1.setMessage("Hello World!");
TextRecipient r2 = new TextRecipient();
r2.setPhoneNumber("12135551101");
r2.setMessage("Testing 1 2 3");
r2.setFromNumber("12135551102");
List<Text> texts = client.textsApi().send(asList(r1, r2), 100L, FIELDS);
assertThat(jsonConverter.serialize(new ListHolder<>(texts)), equalToIgnoringWhiteSpace(responseJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPost.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
assertThat(arg.getURI().toString(), containsString("campaignId=100"));
}
@Test
public void testSendTextsUsingRequest() throws Exception {
String requestJson = getJsonPayload("/callstexts/textsApi/request/sendTexts.json");
String responseJson = getJsonPayload("/callstexts/textsApi/response/sendTexts.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(responseJson);
TextRecipient r1 = new TextRecipient();
r1.setPhoneNumber("12135551100");
r1.setMessage("Hello World!");
TextRecipient r2 = new TextRecipient();
r2.setPhoneNumber("12135551101");
r2.setMessage("Testing 1 2 3");
r2.setFromNumber("12135551102");
SendTextsRequest request = SendTextsRequest.create()
.recipients(asList(r1, r2))
.campaignId(100L)
.defaultMessage("testMessage")
.fields(FIELDS)
.strictValidation(true)
.build();
List<Text> texts = client.textsApi().send(request);
assertThat(jsonConverter.serialize(new ListHolder<>(texts)), equalToIgnoringWhiteSpace(responseJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPost.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
assertThat(arg.getURI().toString(), containsString("campaignId=100"));
assertThat(arg.getURI().toString(), containsString("defaultMessage=testMessage"));
assertThat(arg.getURI().toString(), containsString("strictValidation=true"));
}
@Test
public void testFindTexts() throws Exception {
String expectedJson = getJsonPayload("/callstexts/textsApi/response/findTexts.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindTextsRequest request = FindTextsRequest.create()
.limit(5L)
.offset(0L)
.states(asList(State.CALLBACK, State.DISABLED))
.id(asList(1L, 2L, 3L))
.batchId(100L)
.build();
Page<Text> texts = client.textsApi().find(request);
assertThat(jsonConverter.serialize(texts), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("limit=5"));
assertThat(arg.getURI().toString(), containsString("limit=5"));
assertThat(arg.getURI().toString(), containsString("offset=0"));
assertThat(arg.getURI().toString(), containsString("states=" + encode("CALLBACK,DISABLED")));
assertThat(arg.getURI().toString(), containsString("id=1"));
assertThat(arg.getURI().toString(), containsString("id=2"));
assertThat(arg.getURI().toString(), containsString("id=3"));
assertThat(arg.getURI().toString(), containsString("batchId=100"));
}
@Test
public void getText() throws Exception {
String expectedJson = getJsonPayload("/callstexts/textsApi/response/getText.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
Text text = client.textsApi().get(1L);
HttpUriRequest arg = captor.getValue();
assertThat(arg.getURI().toString(), not(containsString("fields")));
text = client.textsApi().get(1L, FIELDS);
assertThat(jsonConverter.serialize(text), equalToIgnoringWhiteSpace(expectedJson));
arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
@Test
public void testGetTextNullId() throws Exception {
ex.expectMessage("id cannot be null");
ex.expect(NullPointerException.class);
client.textsApi().get(null);
}
}
<file_sep>package com.callfire.api.client.api.contacts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.List;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /contacts which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindContactsRequest extends FindRequest {
/**
* Particular contact list id to search by
*
* @return particular contact list id to search by
*/
private Long contactListId;
/**
* Name of contact property to search by
*
* @return name of contact property to search by
*/
private String propertyName;
/**
* Value of contact property to search by
*
* @return value of contact property to search by
*/
private String propertyValue;
/**
* Multiple contact numbers can be specified. If the number parameter is included,
* the other query parameters are ignored.
*
* @return contact numbers
*/
private List<String> number;
/**
* Multiple contact ids can be specified. If the id parameter is included,
* the other query parameters are ignored.
*
* @return contact ids
*/
private List<Long> id;
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for find method
*/
public static class Builder extends FindRequestBuilder<Builder, FindContactsRequest> {
private Builder() {
super(new FindContactsRequest());
}
/**
* A particular contact list to search by
*
* @param contactListId particular contact list to search by
* @return builder self reference
*/
public Builder contactListId(Long contactListId) {
request.contactListId = contactListId;
return this;
}
/**
* Set name of contact property to search by
*
* @param propertyName name of contact property to search by
* @return builder self reference
*/
public Builder propertyName(String propertyName) {
request.propertyName = propertyName;
return this;
}
/**
* Set value of contact property to search by
*
* @param propertyValue value of contact property to search by
* @return builder self reference
*/
public Builder propertyValue(String propertyValue) {
request.propertyValue = propertyValue;
return this;
}
/**
* Multiple contact numbers can be specified. If the number parameter is included,
* the other query parameters are ignored.
*
* @param number list of numbers to query
* @return builder self reference
*/
public Builder number(List<String> number) {
request.number = number;
return this;
}
/**
* Multiple contact ids can be specified. If the id parameter is included,
* the other query parameters are ignored.
*
* @param id contact ids to search by
* @return builder self reference
*/
public Builder id(List<Long> id) {
request.id = id;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import com.callfire.api.client.api.campaigns.model.Recipient;
import com.callfire.api.client.api.campaigns.model.Voice;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CallRecipient extends Recipient {
/** If dialplanXml != null then IVR Broadcast. */
private String dialplanXml;
private String liveMessage;
private Long liveMessageSoundId;
private String machineMessage;
private Long machineMessageSoundId;
private String transferMessage;
private Long transferMessageSoundId;
private String transferDigit;
private String transferNumber;
private Voice voice;
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PROTECTED;
import com.callfire.api.client.api.common.model.request.FindByIdRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Common request object for GET /calls/broadcasts/{id}/calls or /texts/broadcasts/{id}/texts
*/
@Getter
@NoArgsConstructor(access = PROTECTED)
public abstract class FindBroadcastCallsTextsRequest extends FindByIdRequest {
/**
* Filter by batchId
*
* @return batchId
*/
protected Long batchId;
@SuppressWarnings("unchecked")
public static abstract class FindBroadcastCallsTextsBuilder
<B extends FindBroadcastCallsTextsBuilder, R extends FindBroadcastCallsTextsRequest> extends FindByIdBuilder<B, R> {
public FindBroadcastCallsTextsBuilder(R request) {
super(request);
}
/**
* Filter by batchId
*
* @param batchId id of contact batch uploaded to broadcast
* @return builder self reference
*/
public B batchId(Long batchId) {
request.batchId = batchId;
return (B) this;
}
}
}
<file_sep>package com.callfire.api.client.api.common.model.request;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excludes selected field from http query param
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface QueryParamIgnore {
/**
* Set annotation enabled. Enabled by default
*
* @return true if annotation enabled
*/
boolean enabled() default true;
}
<file_sep>package com.callfire.api.client.api.common.model.request;
import static lombok.AccessLevel.PROTECTED;
import org.apache.commons.lang3.Validate;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Abstract find request with id
*/
@Getter
@NoArgsConstructor(access = PROTECTED)
public abstract class FindByIdRequest extends FindRequest {
@QueryParamIgnore protected Long id;
/**
* Request builder
*/
@SuppressWarnings("unchecked")
public static class FindByIdBuilder<B extends FindByIdBuilder, R extends FindByIdRequest> extends FindRequestBuilder<B, R> {
protected FindByIdBuilder(R request) {
super(request);
}
public B id(Long id) {
request.id = id;
return (B) this;
}
@Override
public R build() {
Validate.notNull(request.id, "request.id cannot be null");
return super.build();
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
@Getter
public class TextBroadcastStats extends BroadcastStats {
private Integer sentCount;
private Integer unsentCount;
// property with typo
@JsonProperty("recievedCount") private Integer receivedCount;
private Integer doNotTextCount;
private Integer tooBigCount;
private Integer errorCount;
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
@Getter
public class ActionRecord extends CallfireModel {
private Long id;
private Double billedAmount;
private Date finishTime;
private String toNumber;
private String callerName;
private String switchId;
private Set<String> labels = new HashSet<>();
}
<file_sep>package com.callfire.api.client.api.contacts.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
@Getter
public class UniversalDnc extends CallfireModel {
/**
* Required number for DNC
*
* @return toNumber
*/
private String toNumber;
/**
* Optional destination/source number for DNC
*
* @return source number
*/
private String fromNumber;
/**
* @return true if toNumber can receive calls or If toNumber can call fromNumber
*/
private Boolean inboundCall;
/**
* @return true if toNumber can receive texts or if toNumber can text fromNumber
*/
private Boolean inboundText;
/**
* @return true if toNumber can send call or If fromNumber can call toNumber
*/
private Boolean outboundCall;
/**
* @return true if toNumber can send texts or If fromNumber can text toNumber
*/
private Boolean outboundText;
public Boolean isInboundCall() {
return inboundCall;
}
public Boolean isInboundText() {
return inboundText;
}
public Boolean isOutboundCall() {
return outboundCall;
}
public Boolean isOutboundText() {
return outboundText;
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.callstexts.model.Text;
import com.callfire.api.client.api.callstexts.model.TextRecord;
import com.callfire.api.client.api.common.model.request.ConvertToString;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /texts which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindTextsRequest extends FindCallsTextsRequest {
/**
* Filter text statuses
*
* @return text statuses
*/
@ConvertToString private List<Text.State> states = new ArrayList<>();
/**
* Filter text results
*
* @return list of text results
*/
@ConvertToString private List<TextRecord.TextResult> results = new ArrayList<>();
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class
*/
public static class Builder extends CallsTextsBuilder<Builder, FindTextsRequest> {
private Builder() {
super(new FindTextsRequest());
}
/**
* Set text statuses to filter
*
* @param states list of states to filter
* @return builder self reference
*/
public Builder states(List<Text.State> states) {
request.states = states;
return this;
}
/**
* Set text results
*
* @param results text results to set
* @return builder self reference
*/
public Builder results(List<TextRecord.TextResult> results) {
request.results = results;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Inbound/Outbound Text Action
*/
@Getter
@NoArgsConstructor
public class Text extends Action<TextRecord> {
private String message;
private TextResult finalTextResult;
private List<Media> media = new ArrayList<>();
public enum TextResult {
SENT,
RECEIVED,
DNT,
TOO_BIG,
INTERNAL_ERROR,
CARRIER_ERROR,
CARRIER_TEMP_ERROR,
UNDIALED,
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import lombok.NoArgsConstructor;
/**
* Request object for searching voice broadcasts
*
* @deprecated use com.callfire.api.client.api.campaigns.model.request.FindCallBroadcastsRequest
*/
@Deprecated
@NoArgsConstructor(access = PRIVATE)
public class FindVoiceBroadcastsRequest extends FindBroadcastsRequest {
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends FindBroadcastsBuilder<Builder, FindVoiceBroadcastsRequest> {
protected Builder() {
super(new FindVoiceBroadcastsRequest());
}
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.campaigns.model.CallRecording;
import lombok.Getter;
@Getter
public class CallRecord extends ActionRecord {
private CallResult result;
private Long originateTime;
private Long answerTime;
private Long duration;
private List<Note> notes = new ArrayList<>();
private List<CallRecording> recordings = new ArrayList<>();
private List<QuestionResponse> questionResponses = new ArrayList<>();
public enum CallResult {
LA,
AM,
BUSY,
DNC,
XFER,
NO_ANS,
XFER_LEG,
INTERNAL_ERROR,
CARRIER_ERROR,
CARRIER_TEMP_ERROR,
UNDIALED,
SD,
POSTPONED,
ABANDONED,
SKIPPED
}
}
<file_sep>package com.callfire.api.client.api.contacts;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.List;
import org.apache.commons.lang3.Validate;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.contacts.model.DoNotContact;
import com.callfire.api.client.api.contacts.model.UniversalDnc;
import com.callfire.api.client.api.contacts.model.request.CreateDncsRequest;
import com.callfire.api.client.api.contacts.model.request.FindDncNumbersRequest;
import com.callfire.api.client.api.contacts.model.request.FindUniversalDncsRequest;
import com.callfire.api.client.api.contacts.model.request.UpdateDncRequest;
/**
* Represents /contacts/dncs endpoint
*
* @since 1.0
*/
public class DncApi {
private static final String DNC_PATH = "/contacts/dncs";
private static final String DNC_SOURCES_PATH = "/contacts/dncs/sources/{}";
private static final String UNIVERSAL_DNC_PATH = "/contacts/dncs/universals/{}";
private static final String DNC_NUMBER_PATH = "/contacts/dncs/{}";
private RestApiClient client;
public DncApi(RestApiClient client) {
this.client = client;
}
/**
* Find all Do Not Contact (DNC) objects created by the user.
* These DoNotContact entries only affect calls/texts/campaigns on this account.
*
* @param request find request with different properties to filter
* @return Page with numbers which must not be contacted
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<DoNotContact> find(FindDncNumbersRequest request) {
return client.get(DNC_PATH, pageOf(DoNotContact.class), request);
}
/**
* Get do not contact (dnc).
*
* @param number DNC number to get dnc for
* @return DoNotContact object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public DoNotContact get(String number) {
return client.get(DNC_NUMBER_PATH.replaceFirst(PLACEHOLDER, number), of(DoNotContact.class));
}
/**
* Add Do Not Contact (DNC) entries.
*
* @param request DNC items to create
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void create(CreateDncsRequest request) {
client.post(DNC_PATH, null, request);
}
/**
* Update a Do Not Contact (DNC) value. Can toggle whether the DNC is enabled for calls/texts.
*
* @param request DNC update request
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void update(UpdateDncRequest request) {
client.put(DNC_NUMBER_PATH.replaceFirst(PLACEHOLDER, request.getNumber()), null, request);
}
/**
* Delete a Do Not Contact (DNC) value.
*
* @param number DNC number to remove dnc for
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void delete(String number) {
Validate.notNull(number, "number cannot be null");
client.delete(DNC_NUMBER_PATH.replaceFirst(PLACEHOLDER, number));
}
/**
* Find universal do not contacts (udnc) associated with toNumber
*
* @param request find request with different properties to filter
* @return List with universal dncs
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<UniversalDnc> findUniversalDncs(FindUniversalDncsRequest request) {
return client.get(UNIVERSAL_DNC_PATH.replaceFirst(PLACEHOLDER, request.getToNumber()), listHolderOf(UniversalDnc.class), request).getItems();
}
/**
* Delete do not contact (dnc) numbers contained in source.
*
* @param source Source associated with Do Not Contact (DNC) entry.
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void deleteDncsFromSource(String source) {
Validate.notNull(source, "number cannot be null");
client.delete(DNC_SOURCES_PATH.replaceFirst(PLACEHOLDER, source));
}
}
<file_sep>group=com.callfire
baseName=callfire-api-client
version=1.8.0
description=Callfire API Java Client
orgName=CallFire Inc.
orgUrl=https://www.callfire.com
devEmail=<EMAIL>
docsUrl=https://developers.callfire.com
repoName=callfire-api-client-java
vcsUrl=https://github.com/CallFire/callfire-api-client-java.git
issueTrackerUrl=https://github.com/CallFire/callfire-api-client-java/issues
<file_sep>package com.callfire.api.client.api.account.model.request;
import static lombok.AccessLevel.PRIVATE;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.AbstractBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for
* POST /admin/callerids/{callerid}/verification-code
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class CallerIdVerificationRequest extends CallfireModel {
private String verificationCode;
@JsonIgnore
private String callerId;
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends AbstractBuilder<CallerIdVerificationRequest> {
public Builder verificationCode(String verificationCode) {
request.verificationCode = verificationCode;
return this;
}
public Builder callerId(String callerId) {
request.callerId = callerId;
return this;
}
private Builder() {
super(new CallerIdVerificationRequest());
}
}
}
<file_sep>package com.callfire.api.client.api.contacts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.List;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /contacts/dncs which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindDncNumbersRequest extends FindRequest {
/**
* Prefix (1-10 digits) of numbers
*
* @return prefix (1-10 digits) of numbers
*/
private String prefix;
/**
* Filter by campaignId property
*
* @return Campaign Id filter
*/
private Long campaignId;
/**
* Filter by source property
*
* @return Source filter
*/
private String source;
/**
* Filter by call property
*
* @return true if filter by call set
*/
private Boolean call;
/**
* Filter by text property
*
* @return true if filter by text set
*/
private Boolean text;
/**
* Filter by numbers list property
*
* @return Numbers filter
*/
private List<String> numbers;
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for find method
*/
public static class Builder extends FindRequestBuilder<Builder, FindDncNumbersRequest> {
private Builder() {
super(new FindDncNumbersRequest());
}
/**
* Set prefix (1-10 digits) of numbers
*
* @param prefix prefix (1-10 digits) of numbers
* @return builder self-reference
*/
public Builder prefix(String prefix) {
request.prefix = prefix;
return this;
}
/**
* Set Campaign Id to filter lists
*
* @param campaignId Campaign Id to filter lists
* @return builder self-reference
*/
public Builder campaignId(Long campaignId) {
request.campaignId = campaignId;
return this;
}
/**
* Set Source to filter lists
*
* @param source Source to filter lists
* @return builder self-reference
*/
public Builder source(String source) {
request.source = source;
return this;
}
/**
* Set filter by call
*
* @param call filter by call
* @return builder self-reference
*/
public Builder call(Boolean call) {
request.call = call;
return this;
}
/**
* Set filter by text
*
* @param text filter by text
* @return builder self-reference
*/
public Builder text(Boolean text) {
request.text = text;
return this;
}
/**
* Set Numbers to filter lists
*
* @param numbers Numbers filter
* @return builder self-reference
*/
public Builder numbers(List<String> numbers) {
request.numbers = numbers;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.account;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ClientUtils.addQueryParamIfSet;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import static com.callfire.api.client.ModelType.pageOf;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.account.model.Account;
import com.callfire.api.client.api.account.model.ApiCredentials;
import com.callfire.api.client.api.account.model.BillingPlanUsage;
import com.callfire.api.client.api.account.model.CallerId;
import com.callfire.api.client.api.account.model.CreditsUsage;
import com.callfire.api.client.api.account.model.request.CallerIdVerificationRequest;
import com.callfire.api.client.api.account.model.request.DateIntervalRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.request.CommonFindRequest;
/**
* Represents rest endpoint /me
*
* @since 1.0
*/
public class MeApi {
private static final String ME_ACCOUNT_PATH = "/me/account";
private static final String ME_BILLING_PATH = "/me/billing/plan-usage";
private static final String ME_BILLING_CREDIT_PATH = "/me/billing/credit-usage";
private static final String ME_API_CREDS_PATH = "/me/api/credentials";
private static final String ME_API_CREDS_ITEM_PATH = "/me/api/credentials/{}";
private static final String ME_CALLERIDS_PATH = "/me/callerids";
private static final String ME_CALLERIDS_CODE_PATH = "/me/callerids/{}";
private static final String ME_CALLERIDS_VERIFY_PATH = "/me/callerids/{}/verification-code";
private RestApiClient client;
public MeApi(RestApiClient client) {
this.client = client;
}
/**
* Find account details for the user. Details include name, email, and basic account permissions.
* GET /me/account
*
* @return user's account
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Account getAccount() {
return client.get(ME_ACCOUNT_PATH, of(Account.class));
}
/**
* Get Plan usage statistics
* GET /me/billing/plan-usage
*
* @return BillingPlanUsage object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public BillingPlanUsage getBillingPlanUsage() {
return client.get(ME_BILLING_PATH, of(BillingPlanUsage.class));
}
/**
* Find credit usage for the user. Returns credits usage for time period specified or if unspecified then total for all time.
* GET /me/billing/credit-usage
*
* @return CreditsUsage object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CreditsUsage getCreditUsage() {
return client.get(ME_BILLING_CREDIT_PATH, of(CreditsUsage.class));
}
/**
* Find credit usage for the user. Returns credits usage for time period specified or if unspecified then total for all time.
* GET /me/billing/credit-usage
*
* @param request request for date range filtering
* @return CreditsUsage object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public CreditsUsage getCreditUsage(DateIntervalRequest request) {
return client.get(ME_BILLING_CREDIT_PATH, of(CreditsUsage.class), request);
}
/**
* Returns a list of verified caller ids. If the number is not shown in the list,
* then it is not verified, and will have to send for a verification code.
* GET /me/callerids
*
* @return list of callerId numbers
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<CallerId> getCallerIds() {
return client.get(ME_CALLERIDS_PATH, listHolderOf(CallerId.class)).getItems();
}
/**
* Send generated verification code to callerid number.
* The verification code is delivered via a phone call.
* After receiving verification code on phone call POST /callerids/{callerid}/verification-code to verify number.
* POST /me/callerids/{callerid}
*
* @param callerid callerid number
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void sendVerificationCode(String callerid) {
Validate.notBlank(callerid, "callerid cannot be blank");
client.post(ME_CALLERIDS_CODE_PATH.replaceFirst(PLACEHOLDER, callerid), null);
}
/**
* Verify callerId by providing calling number and verificationCode received on phone.
* POST /me/callerids/{callerid}/verification-code
*
* @param request request object
* @return true or false depending on whether verification was successful or not.
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Boolean verifyCallerId(CallerIdVerificationRequest request) {
Validate.notBlank(request.getCallerId(), "callerid cannot be blank");
String path = ME_CALLERIDS_VERIFY_PATH.replaceFirst(PLACEHOLDER, request.getCallerId());
return client.post(path, of(Boolean.class), request);
}
/**
* Create API credentials for the CallFire API. This endpoint requires full CallFire account
* credentials to be used, authenticated using Basic Authentication. At this time, the user
* can only supply the name for the credentials. The generated credentials can be used to
* access any endpoint on the CallFire API. ApiCredentials.name property required
*
* @param credentials API credentials to create
* @return {@link ApiCredentials} object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ApiCredentials createApiCredentials(ApiCredentials credentials) {
return client.post(ME_API_CREDS_PATH, of(ApiCredentials.class), credentials);
}
/**
* Find API credentials associated with current account
* Performs GET /me/api/credentials request
*
* @param request request with properties to filter
* @return {@link ApiCredentials} object
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Page<ApiCredentials> findApiCredentials(CommonFindRequest request) {
return client.get(ME_API_CREDS_PATH, pageOf(ApiCredentials.class), request);
}
/**
* Get API credentials by id
* GET /me/api/credentials/{id}
*
* @param id id of credentials
* @return {@link ApiCredentials}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ApiCredentials getApiCredentials(Long id) {
return getApiCredentials(id, null);
}
/**
* Get API credentials by id
* GET /me/api/credentials/{id}
*
* @param id id of credentials
* @param fields limit fields returned. Example fields=id,name
* @return {@link ApiCredentials}
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public ApiCredentials getApiCredentials(Long id, String fields) {
Validate.notNull(id, "id cannot be null");
List<NameValuePair> queryParams = new ArrayList<>(1);
addQueryParamIfSet("fields", fields, queryParams);
String path = ME_API_CREDS_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString());
return client.get(path, of(ApiCredentials.class), queryParams);
}
/**
* Delete API credentials by id
* DELETE /me/api/credentials/{id}
*
* @param id id of credentials
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public void deleteApiCredentials(Long id) {
Validate.notNull(id, "id cannot be null");
client.delete(ME_API_CREDS_ITEM_PATH.replaceFirst(PLACEHOLDER, id.toString()));
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PROTECTED;
import java.util.Date;
import java.util.List;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /calls or /texts
*/
@Getter
@NoArgsConstructor(access = PROTECTED)
public abstract class FindCallsTextsRequest extends FindRequest {
/**
* Filter id of broadcast
*
* @return id of broadcast
*/
protected Long campaignId;
/**
* Filter id of contact batch
*
* @return id of contact batch
*/
protected Long batchId;
/**
* Filter phone number call/text was sent to
*
* @return phone number call/text was sent to
*/
protected String fromNumber;
/**
* Filter phone number call/text was sent from
*
* @return phone number call/text was sent from
*/
protected String toNumber;
/**
* Filter label assigned with call/text
*
* @return label assigned with call/text
*/
protected String label;
/**
* Filter inbound call/text
*
* @return true if call/text inbound, otherwise false
*/
protected Boolean inbound;
/**
* Filter beginning of time interval
*
* @return beginning of time interval
*/
protected Date intervalBegin;
/**
* Filter end of time interval
*
* @return end of time interval
*/
protected Date intervalEnd;
/**
* Filter particular text ids
*
* @return list of text ids
*/
protected List<Long> id;
/**
* Builder class
*/
@SuppressWarnings("unchecked")
public static abstract class CallsTextsBuilder<B extends CallsTextsBuilder, R extends FindCallsTextsRequest>
extends FindRequestBuilder<B, R> {
public CallsTextsBuilder(R request) {
super(request);
}
/**
* Set E.164 number that calls/texts are from
*
* @param fromNumber phone number text was sent from
* @return builder self reference
*/
public B fromNumber(String fromNumber) {
request.fromNumber = fromNumber;
return (B) this;
}
/**
* Set label assigned with call/text
*
* @param label label assigned with call/text
* @return builder self reference
*/
public B label(String label) {
request.label = label;
return (B) this;
}
/**
* Query for calls/texts inside of a particular campaign.
*
* @param campaignId id of campaign
* @return builder self reference
*/
public B campaignId(Long campaignId) {
request.campaignId = campaignId;
return (B) this;
}
/**
* Query for calls/texts which were created with particular contact batch.
*
* @param batchId id of contact batch
* @return builder self reference
*/
public B batchId(Long batchId) {
request.batchId = batchId;
return (B) this;
}
/**
* Set E.164 number that calls/texts are to
*
* @param toNumber phone number text was sent to
* @return builder self reference
*/
public B toNumber(String toNumber) {
request.toNumber = toNumber;
return (B) this;
}
/**
* Set inbound call/text
*
* @param inbound true if call/text inbound
* @return builder self reference
*/
public B inbound(Boolean inbound) {
request.inbound = inbound;
return (B) this;
}
/**
* Set beginning of time interval
*
* @param intervalBegin beginning of time interval
* @return builder self reference
*/
public B intervalBegin(Date intervalBegin) {
request.intervalBegin = intervalBegin;
return (B) this;
}
/**
* Set end of time interval
*
* @param intervalEnd end of time interval
* @return builder self reference
*/
public B intervalEnd(Date intervalEnd) {
request.intervalEnd = intervalEnd;
return (B) this;
}
/**
* Set particular call/text ids to filter
*
* @param id text ids to filter
* @return builder self reference
*/
public B id(List<Long> id) {
request.id = id;
return (B) this;
}
}
}
<file_sep>package com.callfire.api.client.api.keywords;
import static com.callfire.api.client.ClientConstants.PLACEHOLDER;
import static com.callfire.api.client.ModelType.listHolderOf;
import static com.callfire.api.client.ModelType.of;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.callfire.api.client.AccessForbiddenException;
import com.callfire.api.client.BadRequestException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClientException;
import com.callfire.api.client.InternalServerErrorException;
import com.callfire.api.client.ResourceNotFoundException;
import com.callfire.api.client.RestApiClient;
import com.callfire.api.client.UnauthorizedException;
import com.callfire.api.client.api.keywords.model.Keyword;
/**
* Represents rest endpoint /keywords
*
* @since 1.0
*/
public class KeywordsApi {
private static final String KEYWORDS_PATH = "/keywords";
private static final String KEYWORD_AVAILABLE_PATH = "/keywords/{}/available";
private RestApiClient client;
public KeywordsApi(RestApiClient client) {
this.client = client;
}
/**
* Find keywords for purchase on the CallFire platform. If a keyword appears in the response,
* it is available for purchase.
*
* @param keywords keywords to find
* @return available keywords
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public List<Keyword> find(List<String> keywords) {
List<NameValuePair> queryParams = new ArrayList<>(keywords.size());
for (String keyword : keywords) {
queryParams.add(new BasicNameValuePair("keywords", keyword));
}
return client.get(KEYWORDS_PATH, listHolderOf(Keyword.class), queryParams).getItems();
}
/**
* Find an individual keyword for purchase on the CallFire platform.
*
* @param keyword keyword to check status of
* @return true if keyword is available, otherwise false
* @throws BadRequestException in case HTTP response code is 400 - Bad request, the request was formatted improperly.
* @throws UnauthorizedException in case HTTP response code is 401 - Unauthorized, API Key missing or invalid.
* @throws AccessForbiddenException in case HTTP response code is 403 - Forbidden, insufficient permissions.
* @throws ResourceNotFoundException in case HTTP response code is 404 - NOT FOUND, the resource requested does not exist.
* @throws InternalServerErrorException in case HTTP response code is 500 - Internal Server Error.
* @throws CallfireApiException in case HTTP response code is something different from codes listed above.
* @throws CallfireClientException in case error has occurred in client.
*/
public Boolean isAvailable(String keyword) {
Validate.notBlank(keyword, "keyword cannot be blank");
return client.get(KEYWORD_AVAILABLE_PATH.replaceFirst(PLACEHOLDER, keyword), of(Boolean.class));
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.math.BigDecimal;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
/**
* Statistics for a Broadcast (Call or Text).
*/
@Getter
public abstract class BroadcastStats extends CallfireModel {
private Integer totalOutboundCount;
private Integer remainingOutboundCount;
private BigDecimal billedAmount;
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PROTECTED;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.AbstractBuilder;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for POST /calls or /texts
*/
@Getter
@NoArgsConstructor(access = PROTECTED)
public abstract class SendCallsTextsRequest extends CallfireModel {
/**
* Id of broadcast
*
* @return id of broadcast
*/
protected Long campaignId;
/**
* Strict validation flag
*
* @return strict validation turned on Boolean
*/
protected String fields;
/**
* Get limit fields returned. Example fields=id,items(name,agents(id))
*
* @return field to return
*/
protected Boolean strictValidation;
/**
* Builder class
*/
@SuppressWarnings("unchecked")
public static abstract class SendCallsTextsBuilder<B extends SendCallsTextsBuilder, R extends SendCallsTextsRequest>
extends AbstractBuilder<R> {
public SendCallsTextsBuilder(R request) {
super(request);
}
/**
* Sending calls/texts inside of a particular campaign.
*
* @param campaignId id of campaign
* @return builder self reference
*/
public B campaignId(Long campaignId) {
request.campaignId = campaignId;
return (B) this;
}
/**
* Setting strict validation flag for sending calls/texts
*
* @param strictValidation strict validation flag
* @return builder self reference
*/
public B strictValidation(Boolean strictValidation) {
request.strictValidation = strictValidation;
return (B) this;
}
/**
* Set limit fields returned. Example fields=id,items(name,agents(id))
*
* @param fields fields to return
* @return builder object
*/
public B fields(String fields) {
request.fields = fields;
return (B) this;
}
}
}
<file_sep>= Callfire API v2 REST client
Java client for Callfire platform API version 2. See link:https://developers.callfire.com/callfire-api-client-java.html[Getting Started]
page for setup instructions.
.*Requirements:*
* Java 8+
.*Dependencies:*
* Fasterxml Jackson 2.6.1
* Apache HttpClient 4.5
* Apache commons-lang3 3.4
.*Table of contents*
* link:https://developers.callfire.com/callfire-api-client-java.html[Getting Started]
* link:https://developers.callfire.com/docs.html[REST endpoints documentation and api code samples]
* Have a question ?
** link:https://developers.callfire.com/chat.html[Public chat room]
** link:http://stackoverflow.com/questions/tagged/callfire[Ask on stackoverflow]
** link:https://answers.callfire.com/hc/en-us[Call Us]
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /campaigns/sounds which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindSoundsRequest extends FindRequest {
/**
* Search field for fileName/name
*
* @return search field for fileName/name
*/
private String filter;
/**
* Include archived sounds filter
*
* @return include archived sounds filter
*/
private Boolean includeArchived;
/**
* Include archived sounds filter
*
* @return include pending sounds filter
*/
private Boolean includePending;
/**
* Include scrubbed sounds filter
*
* @return include scrubbed sounds filter
*/
private Boolean includeScrubbed;
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends FindRequestBuilder<Builder, FindSoundsRequest> {
private Builder() {
super(new FindSoundsRequest());
}
public Builder filter(String filter) {
request.filter = filter;
return this;
}
public Builder includeScrubbed(Boolean includeScrubbed) {
request.includeScrubbed = includeScrubbed;
return this;
}
public Builder includePending(Boolean includePending) {
request.includePending = includePending;
return this;
}
public Builder includeArchived(Boolean includeArchived) {
request.includeArchived = includeArchived;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.callstexts.model.Media;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TextRecipient extends Recipient {
private String message;
private List<Media> media = new ArrayList<>();
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for GET /agent-groups which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PRIVATE)
public class FindAgentGroupsRequest extends FindRequest {
/**
* ID of campaign
*
* @return Id of campaign
*/
private Long campaignId;
/**
* Agent group name
*
* @return group name
*/
private String name;
/**
* Agent id
* <p>
* Id of agent (agentId and agentEmail are mutually exclusive, please only provide one)
*
* @return id
*/
private Long agentId;
/**
* Email of agent (agentId and agentEmail are mutually exclusive, please only provide one)
*
* @return email
*/
private String agentEmail;
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for find method
*/
public static class Builder extends FindRequestBuilder<Builder, FindAgentGroupsRequest> {
private Builder() {
super(new FindAgentGroupsRequest());
}
public Builder campaignId(Long campaignId) {
request.campaignId = campaignId;
return this;
}
public Builder name(String name) {
request.name = name;
return this;
}
public Builder agentId(Long agentId) {
request.agentId = agentId;
return this;
}
public Builder agentEmail(String agentEmail) {
request.agentEmail = agentEmail;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import lombok.NoArgsConstructor;
/**
* Request object for searching call broadcasts
*/
@NoArgsConstructor(access = PRIVATE)
public class FindCallBroadcastsRequest extends FindBroadcastsRequest {
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends FindBroadcastsBuilder<Builder, FindCallBroadcastsRequest> {
protected Builder() {
super(new FindCallBroadcastsRequest());
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import lombok.NoArgsConstructor;
/**
* Request object for searching ccc broadcasts
*/
@Deprecated
@NoArgsConstructor(access = PRIVATE)
public class FindCccBroadcastsRequest extends FindBroadcastsRequest {
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends FindBroadcastsBuilder<Builder, FindCccBroadcastsRequest> {
protected Builder() {
super(new FindCccBroadcastsRequest());
}
}
}
<file_sep>package com.callfire.api.client.api.common.model;
import lombok.Getter;
@Getter
public class Page<T> extends ListHolder<T> {
private Long limit;
private Long offset;
private Long totalCount;
}
<file_sep>com.callfire.api.client.path = https://api.callfire.com/v2
com.callfire.api.client.version = ${project.baseName}-java-${project.version}<file_sep>package com.callfire.api.client.api.account.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* CallerId
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CallerId extends CallfireModel {
private String phoneNumber;
}
<file_sep>package com.callfire.api.client;
import static com.callfire.api.client.ClientConstants.CLIENT_CONFIG_FILE;
import java.io.IOException;
import java.util.Properties;
import com.callfire.api.client.api.account.MeApi;
import com.callfire.api.client.api.account.OrdersApi;
import com.callfire.api.client.api.callstexts.CallsApi;
import com.callfire.api.client.api.callstexts.MediaApi;
import com.callfire.api.client.api.callstexts.TextsApi;
import com.callfire.api.client.api.campaigns.BatchesApi;
import com.callfire.api.client.api.campaigns.CallBroadcastsApi;
import com.callfire.api.client.api.campaigns.CampaignSoundsApi;
import com.callfire.api.client.api.campaigns.TextAutoRepliesApi;
import com.callfire.api.client.api.campaigns.TextBroadcastsApi;
import com.callfire.api.client.api.contacts.ContactListsApi;
import com.callfire.api.client.api.contacts.ContactsApi;
import com.callfire.api.client.api.contacts.DncApi;
import com.callfire.api.client.api.keywords.KeywordLeasesApi;
import com.callfire.api.client.api.keywords.KeywordsApi;
import com.callfire.api.client.api.numbers.NumberLeasesApi;
import com.callfire.api.client.api.numbers.NumbersApi;
import com.callfire.api.client.api.webhooks.WebhooksApi;
import com.callfire.api.client.auth.BasicAuth;
/**
* Callfire API v2 client
* <p>
* <b>Authentication:</b> the CallFire API V2 uses HTTP Basic Authentication to verify
* the user of an endpoint. A generated username/password API credential from your
* account settings is required.
* </p>
* <b>Errors:</b> codes in the 400s range detail all of the errors a CallFire Developer could
* encounter while using the API. Bad Request, Rate Limit Reached, and Unauthorized
* are some of the sorts of responses in the 400s block. Codes in the 500s range are
* error responses from the CallFire system. If an error has occurred anywhere in
* the execution of a resource that was not due to user input, a 500 response
* will be returned with a corresponding JSON error body. In that body will contain a message
* detailing what went wrong.
* API client methods throw 2 types of exceptions: API and client itself. API exceptions are mapped to
* HTTP response codes:
* <ul>
* <li>{@link BadRequestException} - 400 - Bad request, the request was formatted improperly.</li>
* <li>{@link UnauthorizedException} - 401 - Unauthorized, API Key missing or invalid.</li>
* <li>{@link AccessForbiddenException} - 403 - Forbidden, insufficient permissions.</li>
* <li>{@link ResourceNotFoundException} - 404 - NOT FOUND, the resource requested does not exist.</li>
* <li>{@link InternalServerErrorException} - 500 - Internal Server Error.</li>
* <li>{@link CallfireApiException} - other error codes mapped to base exception.</li>
* </ul>
* Client exceptions:
* <ul>
* <li>{@link CallfireClientException} - if error occurred inside client</li>
* </ul>
*
* @author <NAME> (email: <EMAIL>)
* @see <a href="https://developers.callfire.com/docs.html">Callfire API documentation</a>
* @see <a href="https://developers.callfire.com/learn.html">HowTos and examples</a>
* @see <a href="http://stackoverflow.com/questions/tagged/callfire">Stackoverflow community questions</a>
* @since 1.0
*/
public class CallfireClient {
private static Properties clientConfig = new Properties();
static {
loadConfig();
}
private RestApiClient restApiClient;
// campaigns
private BatchesApi batchesApi;
private CampaignSoundsApi campaignSoundsApi;
private CallBroadcastsApi callBroadcastsApi;
private TextBroadcastsApi textBroadcastsApi;
private TextAutoRepliesApi textAutoRepliesApi;
// keywords
private KeywordsApi keywordsApi;
private KeywordLeasesApi keywordLeasesApi;
// numbers
private NumbersApi numbersApi;
private NumberLeasesApi numberLeasesApi;
// calls & texts
private CallsApi callsApi;
private TextsApi textsApi;
private MediaApi mediaApi;
// account
private MeApi meApi;
private OrdersApi ordersApi;
// contacts
private ContactsApi contactsApi;
private ContactListsApi contactListsApi;
private DncApi dncApi;
// webhooks
private WebhooksApi webhooksApi;
/**
* Constructs callfire client
*
* @param username api login
* @param password api password
*/
public CallfireClient(String username, String password) {
restApiClient = new RestApiClient(new BasicAuth(username, password));
}
/**
* Get REST api client which uses Apache httpclient inside
*
* @return rest client
*/
public RestApiClient getRestApiClient() {
return restApiClient;
}
/**
* Get client configuration
*
* @return configuration properties
*/
public static Properties getClientConfig() {
return clientConfig;
}
/**
* Get /texts/text-broadcasts api endpoint
*
* @return endpoint object
*/
public TextBroadcastsApi textBroadcastsApi() {
if (textBroadcastsApi == null) {
textBroadcastsApi = new TextBroadcastsApi(restApiClient);
}
return textBroadcastsApi;
}
/**
* Get /calls/broadcasts api endpoint
*
* @return endpoint object
*/
public CallBroadcastsApi callBroadcastsApi() {
if (callBroadcastsApi == null) {
callBroadcastsApi = new CallBroadcastsApi(restApiClient);
}
return callBroadcastsApi;
}
/**
* Get /me api endpoint
*
* @return endpoint object
*/
public MeApi meApi() {
if (meApi == null) {
meApi = new MeApi(restApiClient);
}
return meApi;
}
/**
* Get /contacts api endpoint
*
* @return endpoint object
*/
public ContactsApi contactsApi() {
if (contactsApi == null) {
contactsApi = new ContactsApi(restApiClient);
}
return contactsApi;
}
/**
* Get /texts endpoint
*
* @return endpoint object
* @see TextsApi
*/
public TextsApi textsApi() {
if (textsApi == null) {
textsApi = new TextsApi(restApiClient);
}
return textsApi;
}
/**
* Get /media endpoint
*
* @return endpoint object
* @see MediaApi
*/
public MediaApi mediaApi() {
if (mediaApi == null) {
mediaApi = new MediaApi(restApiClient);
}
return mediaApi;
}
/**
* Get /keywords endpoint
*
* @return endpoint object
*/
public KeywordsApi keywordsApi() {
if (keywordsApi == null) {
keywordsApi = new KeywordsApi(restApiClient);
}
return keywordsApi;
}
/**
* Get /keywords/leases endpoint
*
* @return endpoint object
*/
public KeywordLeasesApi keywordLeasesApi() {
if (keywordLeasesApi == null) {
keywordLeasesApi = new KeywordLeasesApi(restApiClient);
}
return keywordLeasesApi;
}
/**
* Get /numbers endpoint
*
* @return endpoint object
*/
public NumbersApi numbersApi() {
if (numbersApi == null) {
numbersApi = new NumbersApi(restApiClient);
}
return numbersApi;
}
/**
* Get /numbers/leases endpoint
*
* @return endpoint object
*/
public NumberLeasesApi numberLeasesApi() {
if (numberLeasesApi == null) {
numberLeasesApi = new NumberLeasesApi(restApiClient);
}
return numberLeasesApi;
}
/**
* Get /calls endpoint
*
* @return endpoint object
*/
public CallsApi callsApi() {
if (callsApi == null) {
callsApi = new CallsApi(restApiClient);
}
return callsApi;
}
/**
* Get /orders endpoint
*
* @return endpoint object
*/
public OrdersApi ordersApi() {
if (ordersApi == null) {
ordersApi = new OrdersApi(restApiClient);
}
return ordersApi;
}
/**
* Get /webhooks endpoint
*
* @return endpoint object
*/
public WebhooksApi webhooksApi() {
if (webhooksApi == null) {
webhooksApi = new WebhooksApi(restApiClient);
}
return webhooksApi;
}
/**
* Get /campaigns/sounds endpoint
*
* @return endpoint object
*/
public CampaignSoundsApi campaignSoundsApi() {
if (campaignSoundsApi == null) {
campaignSoundsApi = new CampaignSoundsApi(restApiClient);
}
return campaignSoundsApi;
}
/**
* Get /campaigns/text-auto-replys endpoint
*
* @return endpoint object
*/
public TextAutoRepliesApi textAutoRepliesApi() {
if (textAutoRepliesApi == null) {
textAutoRepliesApi = new TextAutoRepliesApi(restApiClient);
}
return textAutoRepliesApi;
}
/**
* Get /campaigns/batches endpoint
*
* @return endpoint object
*/
public BatchesApi batchesApi() {
if (batchesApi == null) {
batchesApi = new BatchesApi(restApiClient);
}
return batchesApi;
}
/**
* Get /contacts/do-not-calls api endpoint
*
* @return endpoint object
*/
public DncApi dncApi() {
if (dncApi == null) {
dncApi = new DncApi(restApiClient);
}
return dncApi;
}
/**
* Get /contacts/lists api endpoint
*
* @return endpoint object
*/
public ContactListsApi contactListsApi() {
if (contactListsApi == null) {
contactListsApi = new ContactListsApi(restApiClient);
}
return contactListsApi;
}
private static void loadConfig() {
try {
clientConfig.load(CallfireClient.class.getResourceAsStream(CLIENT_CONFIG_FILE));
} catch (IOException e) {
throw new CallfireClientException("Cannot instantiate Callfire Client.", e);
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import com.callfire.api.client.api.common.model.LocalDate;
import com.callfire.api.client.api.common.model.WeeklySchedule;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Campaign Schedule
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Schedule extends WeeklySchedule {
private Long id;
private Long campaignId;
private LocalDate startDate;
private LocalDate stopDate;
}
<file_sep>package com.callfire.api.client;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.ErrorMessage;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* Callfire API exception is thrown by client in case of 4xx or 5xx HTTP code
* response
*
* @since 1.0
*/
@Getter
@Setter
@AllArgsConstructor
public class CallfireApiException extends RuntimeException {
/**
* Detailed error message with HTTP code, help link, etc.
*
* @param apiErrorMessage detailed message
* @return detailed message
*/
protected ErrorMessage apiErrorMessage;
@Override
public String toString() {
return CallfireModel.toString(this);
}
}
<file_sep>package com.callfire.api.client.api.contacts.model;
import java.util.HashMap;
import java.util.Map;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Represents contact information in Callfire system
*/
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Contact extends CallfireModel {
private Long id;
private String firstName;
private String lastName;
private String zipcode;
private String homePhone;
private String workPhone;
private String mobilePhone;
private String externalId;
private String externalSystem;
private Boolean deleted;
@Builder.Default private Map<String, String> properties = new HashMap<>();
}
<file_sep>package com.callfire.api.client.api.common.model.request;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
/**
* Contains common fields for finder endpoints
*/
@Getter
public abstract class FindRequest extends CallfireModel {
/**
* Max number of records per page to return. If items.size() less than limit assume no more items.
* If value not set, default is 100
*
* @return limit number
*/
protected Long limit;
/**
* Offset to start of page, if value not set, default is 0
*
* @return offset
*/
protected Long offset;
/**
* Limit fields returned. Example fields=id,items(name,agents(id))
*
* @return field to return
*/
protected String fields;
/**
* Abstract builder for find requests
*
* @param <B> type of builder
*/
@SuppressWarnings("unchecked")
public static abstract class FindRequestBuilder<B extends FindRequestBuilder, R extends FindRequest> extends AbstractBuilder<R> {
protected FindRequestBuilder(R request) {
super(request);
}
/**
* Set max number of items returned.
*
* @param limit max number of items
* @return builder object
*/
public B limit(Long limit) {
request.limit = limit;
return (B) this;
}
/**
* Offset from start of paging source
*
* @param offset offset value
* @return builder object
*/
public B offset(Long offset) {
request.offset = offset;
return (B) this;
}
/**
* Set limit fields returned. Example fields=id,items(name,agents(id))
*
* @param fields fields to return
* @return builder object
*/
public B fields(String fields) {
request.fields = fields;
return (B) this;
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.ArrayList;
import java.util.List;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Deprecated
public class Script extends CallfireModel {
private String content;
private List<Question> questions = new ArrayList<>();
}
<file_sep>package com.callfire.api.client.api.numbers.model.request;
import static lombok.AccessLevel.PROTECTED;
import com.callfire.api.client.api.common.model.request.FindRequest;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Request object for searching numbers, region data, etc. which incapsulates
* different query pairs
*/
@Getter
@NoArgsConstructor(access = PROTECTED)
public abstract class FindByRegionDataRequest extends FindRequest {
/**
* 4-7 digit prefix
*
* @return 4-7 digit prefix
*/
protected String prefix;
/**
* City name
*
* @return city name
*/
protected String city;
/**
* 2 letter state code
*
* @return 2 letter state code
*/
protected String state;
/**
* 5 digit zipcode
*
* @return 5 digit zipcode
*/
protected String zipcode;
/**
* Local access and transport area (LATA) code
*
* @return LATA code
*/
protected String lata;
/**
* rate center code
*
* @return rate center code
*/
protected String rateCenter;
/**
* Builder class
*/
@SuppressWarnings("unchecked")
public static abstract class RegionDataBuilder<B extends RegionDataBuilder, R extends FindByRegionDataRequest>
extends FindRequestBuilder<B, R> {
protected RegionDataBuilder(R request) {
super(request);
}
/**
* Set prefix
*
* @param prefix 4-7 digit prefix
* @return builder self reference
*/
public B prefix(String prefix) {
request.prefix = prefix;
return (B) this;
}
public B city(String city) {
request.city = city;
return (B) this;
}
/**
* Set state
*
* @param state 2 letter state code
* @return builder self reference
*/
public B state(String state) {
request.state = state;
return (B) this;
}
/**
* Set zipcode
*
* @param zipcode 5 digit zipcode
* @return builder self reference
*/
public B zipcode(String zipcode) {
request.zipcode = zipcode;
return (B) this;
}
/**
* Set Local access and transport area (LATA) code
*
* @param lata LATA code
* @return builder self reference
*/
@Deprecated
public B lata(String lata) {
request.lata = lata;
return (B) this;
}
/**
* Set RateCenter code
*
* @param rateCenter RateCenter code
* @return builder self reference
*/
@Deprecated
public B rateCenter(String rateCenter) {
request.rateCenter = rateCenter;
return (B) this;
}
}
}
<file_sep>package com.callfire.api.client;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.callfire.api.client.api.common.model.CallfireModel;
import com.callfire.api.client.api.common.model.request.ConvertToString;
import com.callfire.api.client.api.common.model.request.QueryParamIgnore;
import lombok.experimental.UtilityClass;
/**
* Utility class
*
* @since 1.0
*/
@UtilityClass
public class ClientUtils {
/**
* Add query param to name-value query list if it's value not null
*
* @param name parameter name
* @param value parameter value
* @param queryParams parameters list
*/
public static void addQueryParamIfSet(String name, Object value, List<NameValuePair> queryParams) {
if (name != null && value != null && queryParams != null) {
if (value instanceof Date) {
Date date = (Date) value;
queryParams.add(new BasicNameValuePair(name, String.valueOf(date.getTime())));
}
else {
queryParams.add(new BasicNameValuePair(name, Objects.toString(value)));
}
}
}
/**
* Add {@link Iterable} value as query param to name-value query list
*
* @param name parameter name
* @param value collection with values
* @param queryParams parameters list
*/
public static void addQueryParamIfSet(String name, Iterable value, List<NameValuePair> queryParams) {
if (name != null && value != null && queryParams != null) {
for (Object o : value) {
queryParams.add(new BasicNameValuePair(name, o.toString()));
}
}
}
/**
* Method traverses request object using reflection and build {@link List} of {@link NameValuePair} from it
*
* @param request request
* @param <T> type of request
* @return list contains query parameters
* @throws CallfireClientException in case IllegalAccessException occurred
*/
public static <T extends CallfireModel> List<NameValuePair> buildQueryParams(T request)
throws CallfireClientException {
List<NameValuePair> params = new ArrayList<>();
Class<?> superclass = request.getClass().getSuperclass();
while (superclass != null) {
readFields(request, params, superclass);
superclass = superclass.getSuperclass();
}
readFields(request, params, request.getClass());
return params;
}
private static void readFields(Object request, List<NameValuePair> params, Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
try {
readField(request, params, field);
}
catch (IllegalAccessException e) {
throw new CallfireClientException(e);
}
}
}
private static void readField(Object request, List<NameValuePair> params, Field field)
throws IllegalAccessException {
field.setAccessible(true);
if (field.isAnnotationPresent(QueryParamIgnore.class) &&
field.getAnnotation(QueryParamIgnore.class).enabled()) {
return;
}
Object value = field.get(request);
if (value != null) {
if (field.isAnnotationPresent(ConvertToString.class) && value instanceof Iterable) {
value = StringUtils.join((Iterable) value, field.getAnnotation(ConvertToString.class).separator());
if (StringUtils.isEmpty((String) value)) {
return;
}
}
if (value instanceof Iterable) {
for (Object o : (Iterable) value) {
params.add(new BasicNameValuePair(field.getName(), o.toString()));
}
return;
}
if (value instanceof Date) {
value = ((Date) value).getTime();
}
params.add(new BasicNameValuePair(field.getName(), value.toString()));
}
}
}
<file_sep>package com.callfire.api.client.api.contacts;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockitoAnnotations;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.common.model.ListHolder;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.contacts.model.DoNotContact;
import com.callfire.api.client.api.contacts.model.UniversalDnc;
import com.callfire.api.client.api.contacts.model.request.CreateDncsRequest;
import com.callfire.api.client.api.contacts.model.request.FindDncNumbersRequest;
import com.callfire.api.client.api.contacts.model.request.FindUniversalDncsRequest;
import com.callfire.api.client.api.contacts.model.request.UpdateDncRequest;
public class DncApiTest extends AbstractApiTest {
protected static final String RESPONSES_PATH = "/contacts/dncApi/response/";
protected static final String REQUESTS_PATH = "/contacts/dncApi/request/";
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
client.getRestApiClient().setHttpClient(mockHttpClient);
}
@Test
public void testFind() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "findDncs.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindDncNumbersRequest request = FindDncNumbersRequest.create()
.limit(1L)
.offset(5L)
.fields(FIELDS)
.prefix("1")
.call(true)
.text(true)
.numbers((Arrays.asList("12135551189")))
.build();
Page<DoNotContact> doNotContactList = client.dncApi().find(request);
assertThat(jsonConverter.serialize(doNotContactList), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("prefix=1"));
assertThat(arg.getURI().toString(), containsString("limit=1"));
assertThat(arg.getURI().toString(), containsString("offset=5"));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
assertThat(arg.getURI().toString(), containsString("call=true"));
assertThat(arg.getURI().toString(), containsString("text=true"));
assertThat(arg.getURI().toString(), containsString("numbers=12135551189"));
}
@Test
public void getDnc() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "getDnc.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
DoNotContact doNotContact = client.dncApi().get("12135551188");
assertThat(jsonConverter.serialize(doNotContact), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/12135551188"));
}
@Test
public void testUpdate() throws Exception {
String requestJson = getJsonPayload(BASE_PATH + REQUESTS_PATH + "updateDnc.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
UpdateDncRequest request = UpdateDncRequest.create().call(true).text(true).number("100500").build();
client.dncApi().update(request);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPut.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
}
@Test
public void testCreate() throws Exception {
String requestJson = getJsonPayload(BASE_PATH + REQUESTS_PATH + "addDnc.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
CreateDncsRequest request = CreateDncsRequest.create()
.call(true)
.text(true)
.numbers(Arrays.asList("12135551188"))
.source("testSource")
.build();
client.dncApi().create(request);
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPost.METHOD_NAME, arg.getMethod());
assertThat(extractHttpEntity(arg), equalToIgnoringWhiteSpace(requestJson));
}
@Test
public void testDeleteByNullId() throws Exception {
ex.expectMessage(EMPTY_REQUEST_NUMBER_MSG);
ex.expect(NullPointerException.class);
client.dncApi().delete(null);
}
@Test
public void testDelete() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.dncApi().delete("12135551188");
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/12135551188"));
}
@Test
public void testDeleteDncsFromSourceByNullId() throws Exception {
ex.expectMessage(EMPTY_REQUEST_NUMBER_MSG);
ex.expect(NullPointerException.class);
client.dncApi().deleteDncsFromSource(null);
}
@Test
public void testDeleteDncsFromSource() throws Exception {
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse();
client.dncApi().delete("testSource");
HttpUriRequest arg = captor.getValue();
assertEquals(HttpDelete.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("/testSource"));
}
@Test
public void testFindUniversalDncs() throws Exception {
String expectedJson = getJsonPayload(BASE_PATH + RESPONSES_PATH + "findUniversalDncs.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
FindUniversalDncsRequest request = FindUniversalDncsRequest.create()
.toNumber("12135551188")
.fromNumber("18442800143")
.fields(FIELDS)
.build();
List<UniversalDnc> udncsList = client.dncApi().findUniversalDncs(request);
assertThat(jsonConverter.serialize(new ListHolder<>(udncsList)), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString("toNumber=12135551188"));
assertThat(arg.getURI().toString(), containsString("fromNumber=18442800143"));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
}
}
<file_sep>package com.callfire.api.client.integration.callstexts;
import static com.callfire.api.client.api.callstexts.model.Text.State;
import static com.callfire.api.client.api.callstexts.model.TextRecord.TextResult;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.callstexts.model.Text;
import com.callfire.api.client.api.callstexts.model.request.FindTextsRequest;
import com.callfire.api.client.api.callstexts.model.request.SendTextsRequest;
import com.callfire.api.client.api.campaigns.model.TextRecipient;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /texts api endpoint
*/
public class TextsApiTest extends AbstractIntegrationTest {
@Test
public void testFindAndGetParticularTexts() throws Exception {
CallfireClient client = getCallfireClient();
FindTextsRequest request = FindTextsRequest.create()
.states(asList(State.FINISHED, State.READY))
.results(asList(TextResult.SENT, TextResult.RECEIVED))
.limit(2L)
.build();
Page<Text> page = client.textsApi().find(request);
assertFalse(page.getItems().isEmpty());
System.out.println(page);
Text text = client.textsApi().get(page.getItems().get(0).getId(), "id,fromNumber,state");
assertNotNull(text.getId());
assertNotNull(text.getFromNumber());
assertNotNull(text.getState());
assertNull(text.getToNumber());
}
@Test
public void testSendText() throws Exception {
CallfireClient client = getCallfireClient();
TextRecipient recipient1 = new TextRecipient();
recipient1.setMessage("msg");
recipient1.setPhoneNumber(getCallerId());
TextRecipient recipient2 = new TextRecipient();
recipient2.setPhoneNumber(getCallerId());
recipient2.setFromNumber(getCallerId());
List<Text> texts = client.textsApi()
.send(asList(recipient1, recipient2), 7415135003L, "items(id,fromNumber,state)");
System.out.println(texts);
assertEquals(2, texts.size());
assertNotNull(texts.get(0).getId());
assertNull(texts.get(0).getCampaignId());
assertTrue(State.READY.equals(texts.get(0).getState()) || State.FINISHED.equals(texts.get(0).getState()));
recipient1.setMessage(null);
SendTextsRequest request = SendTextsRequest.create()
.recipients(asList(recipient1, recipient2))
.campaignId(7415135003L)
.fields("items(id,fromNumber,state)")
.defaultMessage("defaultMessage")
.strictValidation(true)
.build();
texts = client.textsApi().send(request);
Text text = client.textsApi().get(texts.get(1).getId());
assertEquals("defaultMessage", text.getMessage());
}
}
<file_sep>package com.callfire.api.client.integration.campaigns;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.campaigns.TextAutoRepliesApi;
import com.callfire.api.client.api.campaigns.model.TextAutoReply;
import com.callfire.api.client.api.campaigns.model.request.FindTextAutoRepliesRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.ResourceId;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /campaings/text-auto-replys api endpoint
*/
public class TextAutoRepliesApiTest extends AbstractIntegrationTest {
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void testCrudOperations() {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
TextAutoRepliesApi api = callfireClient.textAutoRepliesApi();
TextAutoReply textAutoReply = new TextAutoReply();
textAutoReply.setNumber(getDid3());
textAutoReply.setMessage("test message");
textAutoReply.setMatch("test match");
ResourceId resourceId = api.create(textAutoReply);
assertNotNull(resourceId.getId());
FindTextAutoRepliesRequest request = FindTextAutoRepliesRequest.create()
.number(getDid3())
.build();
Page<TextAutoReply> textAutoReplies = api.find(request);
System.out.println(textAutoReplies);
assertTrue(textAutoReplies.getTotalCount() > 0);
assertTrue(textAutoReplies.getItems().size() > 0);
TextAutoReply savedTextAutoReply = api.get(resourceId.getId(), "number,message");
System.out.println(savedTextAutoReply);
assertNull(savedTextAutoReply.getId());
assertNull(savedTextAutoReply.getKeyword());
assertEquals(textAutoReply.getNumber(), savedTextAutoReply.getNumber());
assertEquals(textAutoReply.getMessage(), savedTextAutoReply.getMessage());
api.delete(resourceId.getId());
expect404NotFoundCallfireApiException(ex);
api.get(resourceId.getId());
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.List;
import com.callfire.api.client.api.callstexts.model.CallRecipient;
import com.callfire.api.client.api.campaigns.model.Voice;
import com.callfire.api.client.api.common.model.request.QueryParamIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = PRIVATE)
public class SendCallsRequest extends SendCallsTextsRequest {
@QueryParamIgnore protected List<CallRecipient> recipients;
protected String defaultLiveMessage;
protected String defaultMachineMessage;
protected Long defaultLiveMessageSoundId;
protected Long defaultMachineMessageSoundId;
protected Voice defaultVoice;
public static Builder create() {
return new Builder();
}
public static class Builder extends SendCallsTextsBuilder<Builder, SendCallsRequest> {
private Builder() {
super(new SendCallsRequest());
}
public Builder recipients(List<CallRecipient> recipients) {
request.recipients = recipients;
return this;
}
public Builder defaultLiveMessage(String defaultLiveMessage) {
request.defaultLiveMessage = defaultLiveMessage;
return this;
}
public Builder defaultMachineMessage(String defaultMachineMessage) {
request.defaultMachineMessage = defaultMachineMessage;
return this;
}
public Builder defaultLiveMessageSoundId(Long defaultLiveMessageSoundId) {
request.defaultLiveMessageSoundId = defaultLiveMessageSoundId;
return this;
}
public Builder defaultMachineMessageSoundId(Long defaultMachineMessageSoundId) {
request.defaultMachineMessageSoundId = defaultMachineMessageSoundId;
return this;
}
public Builder defaultVoice(Voice defaultVoice) {
request.defaultVoice = defaultVoice;
return this;
}
}
}
<file_sep>package com.callfire.api.client.integration;
import static com.callfire.api.client.ClientConstants.BASE_PATH_PROPERTY;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.hasProperty;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.hamcrest.Matchers;
import org.junit.rules.ExpectedException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.campaigns.model.Recipient;
import com.callfire.api.client.api.campaigns.model.TextRecipient;
/**
* Base class for all integration tests
*/
public class AbstractIntegrationTest {
private static String BASE_PATH = "https://api.callfire.com/v2";
private String apiUserName;
private String apiUserPassword;
private String accountName;
private String accountPassword;
private String callerId;
private String did1;
private String did2;
private String did3;
public AbstractIntegrationTest() {
System.out.println(BASE_PATH);
apiUserName = System.getProperty("testApiUsername");
apiUserPassword = System.getProperty("testApiPassword");
accountName = System.getProperty("testAccountName");
accountPassword = System.getProperty("testAccountPassword");
callerId = System.getProperty("testCallerId");
Validate.notEmpty(apiUserName, "Username cannot be empty, set it with -DtestApiUsername option");
Validate.notEmpty(apiUserPassword, "Password cannot be empty, set it with -DtestApiPassword option");
Validate.notEmpty(callerId, "CallerID is not set, set it with -DtestCallerId option");
this.did1 = "12132212289";
this.did2 = "14246525473";
this.did3 = "12132041238";
CallfireClient.getClientConfig().put(BASE_PATH_PROPERTY, BASE_PATH);
}
public CallfireClient getCallfireClient() {
return new CallfireClient(getApiUserName(), getApiUserPassword());
}
public String getApiUserName() {
return apiUserName;
}
public String getApiUserPassword() {
return apiUserPassword;
}
public String getAccountName() {
return accountName;
}
public String getAccountPassword() {
return accountPassword;
}
public String getCallerId() {
return callerId;
}
public String getDid1() {
return did1;
}
public String getDid2() {
return did2;
}
public String getDid3() {
return did3;
}
protected void expect404NotFoundCallfireApiException(ExpectedException ex) {
ex.expect(CallfireApiException.class);
ex.expect(hasProperty("apiErrorMessage", hasProperty("httpStatusCode", Matchers.is(404))));
}
protected List<Recipient> makeRecipients() {
Recipient recipient1 = new Recipient();
recipient1.setPhoneNumber(did2);
Recipient recipient2 = new Recipient();
recipient2.setPhoneNumber(did3);
return asList(recipient1, recipient2);
}
protected List<TextRecipient> makeTextRecipients() {
TextRecipient recipient1 = new TextRecipient();
recipient1.setPhoneNumber(did2);
recipient1.setMessage("msg1");
TextRecipient recipient2 = new TextRecipient();
recipient2.setPhoneNumber(did3);
recipient2.setMessage("msg1");
return asList(recipient1, recipient2);
}
protected String getSoundText() {
return "live sound text test";
}
}
<file_sep>package com.callfire.api.client.api.account.model;
import java.math.BigDecimal;
import java.util.Date;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
/**
* Object represents Plan usage statistics
*/
@Getter
public class BillingPlanUsage extends CallfireModel {
/**
* Gets start of usage period
*
* @return start of usage period
*/
private Date intervalStart;
/**
* Gets end of usage period
*
* @return end of usage period
*/
private Date intervalEnd;
/**
* Gets remaining plan credits rounded to nearest whole value.
*
* @return remaining plan credits rounded to nearest whole value.
*/
private BigDecimal remainingPlanCredits;
/**
* Gets remaining pay as you go credits rounded to nearest whole value.
*
* @return remaining pay as you go credits rounded to nearest whole value.
*/
private BigDecimal remainingPayAsYouGoCredits;
/**
* Gets total remaining credits (remainingPlanCredits + remainingPayAsYouGoCredits)
*
* @return total remaining credits (remainingPlanCredits + remainingPayAsYouGoCredits)
*/
private BigDecimal totalRemainingCredits;
}
<file_sep>package com.callfire.api.client.integration.account;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.callfire.api.client.CallfireApiException;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.account.model.Account;
import com.callfire.api.client.api.account.model.Account.UserPermission;
import com.callfire.api.client.api.account.model.ApiCredentials;
import com.callfire.api.client.api.account.model.BillingPlanUsage;
import com.callfire.api.client.api.account.model.CallerId;
import com.callfire.api.client.api.account.model.CreditsUsage;
import com.callfire.api.client.api.account.model.request.CallerIdVerificationRequest;
import com.callfire.api.client.api.account.model.request.DateIntervalRequest;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.api.common.model.request.CommonFindRequest;
import com.callfire.api.client.integration.AbstractIntegrationTest;
/**
* integration tests for /me api endpoint
*/
public class MeApiTest extends AbstractIntegrationTest {
@Rule
public ExpectedException ex = ExpectedException.none();
@Test
public void testGetAccount() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
Account account = callfireClient.meApi().getAccount();
assertNotNull(account.getId());
assertThat(account.getEmail(), stringContainsInOrder(Arrays.asList("@", ".")));
assertTrue(StringUtils.isNoneBlank(account.getName()));
assertTrue(StringUtils.isNoneBlank(account.getFirstName()));
assertTrue(StringUtils.isNoneBlank(account.getLastName()));
assertTrue(account.getPermissions().contains(UserPermission.ACCOUNT_HOLDER));
}
@Test
public void testGetBillingPlanUsage() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
BillingPlanUsage billingPlanUsage = callfireClient.meApi().getBillingPlanUsage();
assertNotNull(billingPlanUsage.getIntervalStart());
assertNotNull(billingPlanUsage.getIntervalEnd());
assertNotNull(billingPlanUsage.getRemainingPayAsYouGoCredits());
assertNotNull(billingPlanUsage.getRemainingPlanCredits());
assertNotNull(billingPlanUsage.getTotalRemainingCredits());
}
@Test
public void testGetCreditsUsage() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
DateIntervalRequest request = DateIntervalRequest.create()
.intervalBegin(DateUtils.addMonths(new Date(), -2))
.intervalEnd(new Date())
.build();
CreditsUsage creditUsage = callfireClient.meApi().getCreditUsage(request);
assertNotNull(creditUsage.getIntervalBegin());
assertNotNull(creditUsage.getIntervalEnd());
assertNotNull(creditUsage.getTextsSent());
assertNotNull(creditUsage.getCreditsUsed());
assertNotNull(creditUsage.getCallsDurationMinutes());
creditUsage = callfireClient.meApi().getCreditUsage();
assertNotNull(creditUsage.getIntervalBegin());
assertNotNull(creditUsage.getIntervalEnd());
assertNotNull(creditUsage.getTextsSent());
assertNotNull(creditUsage.getCreditsUsed());
assertNotNull(creditUsage.getCallsDurationMinutes());
request = DateIntervalRequest.create()
.intervalEnd(DateUtils.addMonths(new Date(), -2))
.build();
creditUsage = callfireClient.meApi().getCreditUsage(request);
assertNotNull(creditUsage.getIntervalBegin());
assertNotNull(creditUsage.getIntervalEnd());
assertNotNull(creditUsage.getTextsSent());
assertNotNull(creditUsage.getCreditsUsed());
assertNotNull(creditUsage.getCallsDurationMinutes());
}
@Test
public void testGetCallerIds() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
List<CallerId> callerIds = callfireClient.meApi().getCallerIds();
System.out.println(callerIds);
assertThat(callerIds, hasItem(Matchers.<CallerId>hasProperty("phoneNumber", equalTo("12132212384"))));
}
@Test
@Ignore("requires environment setup")
public void testSendVerificationCode() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
callfireClient.meApi().sendVerificationCode(getDid1());
ex.expect(CallfireApiException.class);
ex.expect(hasProperty("apiErrorMessage", hasProperty("httpStatusCode", is(400))));
ex.expect(hasProperty("apiErrorMessage", hasProperty("message", containsString("that is already verified"))));
callfireClient.meApi().sendVerificationCode(getCallerId());
}
@Test
public void testVerifyCallerId() throws Exception {
CallfireClient callfireClient = new CallfireClient(getApiUserName(), getApiUserPassword());
CallerIdVerificationRequest request = CallerIdVerificationRequest.create()
.callerId(getCallerId())
.verificationCode("1234")
.build();
Boolean verified = callfireClient.meApi().verifyCallerId(request);
assertTrue(verified);
request = CallerIdVerificationRequest.create()
.callerId(getCallerId().replace("84", "85"))
.verificationCode("1234")
.build();
verified = callfireClient.meApi().verifyCallerId(request);
assertTrue(verified);
}
@Test
public void testCreateGetDeleteApiCredentials() throws Exception {
CallfireClient callfireClient = new CallfireClient(getAccountName(), getAccountPassword());
ApiCredentials credentials = new ApiCredentials();
credentials.setName("test1");
ApiCredentials created = callfireClient.meApi().createApiCredentials(credentials);
System.out.println(created);
assertEquals(credentials.getName(), created.getName());
assertTrue(created.getEnabled());
assertNotNull(created.getId());
created = callfireClient.meApi().getApiCredentials(created.getId(), "id,name,enabled");
assertEquals(credentials.getName(), created.getName());
assertTrue(created.getEnabled());
assertNotNull(created.getId());
assertNull(created.getPassword());
callfireClient.meApi().deleteApiCredentials(created.getId());
expect404NotFoundCallfireApiException(ex);
callfireClient.meApi().getApiCredentials(created.getId(), "name,enabled");
}
@Test
public void testFindApiCredentials() throws Exception {
CallfireClient callfireClient = new CallfireClient(getAccountName(), getAccountPassword());
CommonFindRequest request = CommonFindRequest.create()
.limit(2L)
.build();
Page<ApiCredentials> credentials = callfireClient.meApi().findApiCredentials(request);
System.out.println(credentials);
assertEquals(2, credentials.getItems().size());
assertNotNull(credentials.getItems().get(0).getId());
assertNotNull(credentials.getItems().get(0).getEnabled());
}
}
<file_sep>rootProject.name = 'callfire-api-client'
<file_sep>package com.callfire.api.client.api.campaigns.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LocalTimeRestriction extends CallfireModel {
private Boolean enabled;
private Integer beginHour;
private Integer beginMinute;
private Integer endHour;
private Integer endMinute;
}
<file_sep>package com.callfire.api.client.api.campaigns.model.request;
import static lombok.AccessLevel.PRIVATE;
import lombok.NoArgsConstructor;
/**
* Request object for searching text broadcasts
*/
@NoArgsConstructor(access = PRIVATE)
public class FindTextBroadcastsRequest extends FindBroadcastsRequest {
/**
* Create request builder
*
* @return request build
*/
public static Builder create() {
return new Builder();
}
/**
* Builder class for request
*/
public static class Builder extends FindBroadcastsBuilder<Builder, FindTextBroadcastsRequest> {
protected Builder() {
super(new FindTextBroadcastsRequest());
}
}
}
<file_sep>package com.callfire.api.client.integration.callstexts;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.time.DateUtils;
import org.junit.Test;
import com.callfire.api.client.CallfireClient;
import com.callfire.api.client.api.callstexts.CallsApi;
import com.callfire.api.client.api.callstexts.model.Action.State;
import com.callfire.api.client.api.callstexts.model.Call;
import com.callfire.api.client.api.callstexts.model.CallRecipient;
import com.callfire.api.client.api.callstexts.model.request.FindCallsRequest;
import com.callfire.api.client.api.callstexts.model.request.SendCallsRequest;
import com.callfire.api.client.api.campaigns.model.CallRecording;
import com.callfire.api.client.api.campaigns.model.Voice;
import com.callfire.api.client.api.common.model.Page;
import com.callfire.api.client.integration.AbstractIntegrationTest;
import lombok.extern.slf4j.Slf4j;
/**
* integration tests for /calls api endpoint
*/
@Slf4j
public class CallsApiTest extends AbstractIntegrationTest {
@Test
public void testGetCall() {
CallfireClient callfireClient = getCallfireClient();
Call call = callfireClient.callsApi().get(1930885149003L, "id,toNumber,state");
assertEquals(Long.valueOf(1930885149003L), call.getId());
assertEquals("12132212384", call.getToNumber());
assertEquals(State.FINISHED, call.getState());
log.info("Call response: {}", call);
}
@Test
public void testFindCalls() {
CallfireClient callfireClient = getCallfireClient();
FindCallsRequest request = FindCallsRequest.create()
.intervalBegin(DateUtils.addMonths(new Date(), -10))
.intervalEnd(new Date())
.limit(1L)
.build();
Page<Call> calls = callfireClient.callsApi().find(request);
log.info("Calls response: {}", calls);
assertEquals(1, calls.getItems().size());
}
@Test
public void testSendCall() {
CallfireClient client = getCallfireClient();
CallRecipient recipient1 = new CallRecipient();
recipient1.setLiveMessage("test");
recipient1.setPhoneNumber(getCallerId());
recipient1.setTransferMessage("transferTestMessage");
recipient1.setTransferNumber("14246525473");
recipient1.setTransferDigit("1");
CallRecipient recipient2 = new CallRecipient();
recipient2.setLiveMessage("test");
recipient2.setPhoneNumber(getCallerId());
recipient2.setTransferMessage("transferTestMessage");
recipient2.setTransferDigit("2");
recipient2.setFromNumber(getCallerId());
List<Call> calls = client.callsApi()
.send(asList(recipient1, recipient2), 7373471003L, "items(id,fromNumber,state)");
log.info("Calls response: {}", calls);
assertEquals(2, calls.size());
assertNotNull(calls.get(0).getId());
assertNull(calls.get(0).getCampaignId());
assertEquals(State.READY, calls.get(0).getState());
SendCallsRequest request = SendCallsRequest.create()
.recipients(asList(recipient1, recipient2))
.defaultLiveMessage("defaultLive")
.defaultMachineMessage("defaultMachine")
.defaultVoice(Voice.FRENCHCANADIAN1)
.strictValidation(true)
.build();
calls = client.callsApi().send(request);
assertEquals(2, calls.size());
request = SendCallsRequest.create()
.recipients(asList(recipient1, recipient2))
.defaultLiveMessage("test")
.defaultMachineMessage("test")
.defaultVoice(Voice.FRENCHCANADIAN1)
.build();
calls = client.callsApi().send(request);
assertEquals(2, calls.size());
}
@Test
public void testGetCallRecording() {
CallsApi api = getCallfireClient().callsApi();
CallRecording rec = api.getCallRecording(18666772003L);
log.info("Recording response: {}", rec);
assertNotNull(rec);
assertNotNull(rec.getId());
assertNotNull(rec.getMp3Url());
rec = api.getCallRecording(18666772003L, "campaignId");
assertNull(rec.getId());
}
@Test
public void getCallRecordingInMp3Format() throws Exception {
CallsApi api = getCallfireClient().callsApi();
InputStream is = api.getCallRecordingMp3(18666772003L);
Files.copy(is, File.createTempFile("test_call_recording", "mp3").toPath(), REPLACE_EXISTING);
}
@Test
public void testGetCallRecordings() {
CallsApi api = getCallfireClient().callsApi();
CallRecording rec = api.getCallRecording(18666772003L);
List<CallRecording> recs = api.getCallRecordings(rec.getCallId());
assertNotNull(recs);
assertEquals(rec.getCallId(), recs.get(0).getCallId());
recs = api.getCallRecordings(rec.getCallId(), "items(callId)");
assertNull(recs.get(0).getId());
assertNotNull(recs.get(0).getCallId());
}
@Test
public void testGetCallRecordingByName() {
CallsApi api = getCallfireClient().callsApi();
CallRecording rec = api.getCallRecording(18666772003L);
CallRecording recording = api.getCallRecordingByName(rec.getCallId(), rec.getName());
assertNotNull(rec);
assertEquals(recording.getCallId(), rec.getCallId());
assertEquals(recording.getId(), rec.getId());
assertEquals(recording.getName(), rec.getName());
assertEquals(recording.getMp3Url(), rec.getMp3Url());
recording = api.getCallRecordingByName(rec.getCallId(), rec.getName(), "callId");
assertNull(recording.getId());
assertNotNull(recording.getCallId());
}
@Test
public void getCallRecordingMp3ByName() throws Exception {
CallsApi api = getCallfireClient().callsApi();
CallRecording rec = api.getCallRecording(18666772003L);
InputStream is = api.getCallRecordingMp3ByName(rec.getCallId(), rec.getName());
Files.copy(is, File.createTempFile("test_call_recording", "mp3").toPath(), REPLACE_EXISTING);
}
}
<file_sep>package com.callfire.api.client.api.common.model.request;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Converts iterable field to string representation using provided separator char
* [A, B, C] to "A,B,C"
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ConvertToString {
/**
* Separator between joined strings. Comma by default.
*
* @return values separator
*/
String separator() default ",";
}
<file_sep>package com.callfire.api.client;
/**
* Client constants
*
* @since 1.0
*/
public interface ClientConstants {
String BASE_PATH_PROPERTY = "com.callfire.api.client.path";
String USER_AGENT_PROPERTY = "com.callfire.api.client.version";
String PROXY_ADDRESS_PROPERTY = "com.callfire.api.client.proxy.address";
String PROXY_CREDENTIALS_PROPERTY = "com.callfire.api.client.proxy.credentials";
int DEFAULT_PROXY_PORT = 8080;
String CLIENT_CONFIG_FILE = "/com/callfire/api/client/callfire.properties";
String PLACEHOLDER = "\\{\\}";
// Use ISO 8601 format for date and datetime.
// See https://en.wikipedia.org/wiki/ISO_8601
String DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
String GENERIC_HELP_LINK = "https://answers.callfire.com/hc/en-us";
}
<file_sep>package com.callfire.api.client;
import com.callfire.api.client.api.common.model.ErrorMessage;
/**
* Exception thrown in case if platform returns HTTP code 403 - Forbidden, insufficient permissions
*
* @since 1.5
*/
public class AccessForbiddenException extends CallfireApiException {
public AccessForbiddenException(ErrorMessage errorMessage) {
super(errorMessage);
}
}
<file_sep>package com.callfire.api.client.auth;
import org.apache.http.client.methods.HttpUriRequest;
import com.callfire.api.client.CallfireClientException;
/**
* Provides authentication interface to client for different auth types
*/
public interface Authentication {
/**
* Apply authentication to http request
*
* @param request HTTP request
* @return updated http request
* @throws CallfireClientException in case error has occurred in client
*/
HttpUriRequest apply(HttpUriRequest request);
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import java.util.Date;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.Getter;
/**
* CallRecording
*/
@Getter
public class CallRecording extends CallfireModel {
private Long id;
private Long callId;
private Long campaignId;
private String name;
private Date created;
private Long lengthInBytes;
private Integer lengthInSeconds;
private String hash;
private String mp3Url;
private CallRecordingState state;
public enum CallRecordingState {
RECORDING,
READY,
ERROR
}
}
<file_sep>package com.callfire.api.client.api.callstexts;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.io.File;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.callfire.api.client.api.AbstractApiTest;
import com.callfire.api.client.api.callstexts.model.Media;
import com.callfire.api.client.api.common.model.ResourceId;
public class MediaApiTest extends AbstractApiTest {
@Test
public void upload() throws Exception {
String responseJson = getJsonPayload("/callstexts/mediaApi/response/upload.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(responseJson);
File file = new File(getClass().getClassLoader().getResource("file-examples/train.mp3").toURI());
ResourceId id = client.mediaApi().upload(file, "fname");
assertThat(jsonConverter.serialize(id), equalToIgnoringWhiteSpace(responseJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpPost.METHOD_NAME, arg.getMethod());
}
@Test
public void get() throws Exception {
String expectedJson = getJsonPayload("/callstexts/mediaApi/response/get.json");
ArgumentCaptor<HttpUriRequest> captor = mockHttpResponse(expectedJson);
Media media = client.mediaApi().get(11L, FIELDS);
assertThat(jsonConverter.serialize(media), equalToIgnoringWhiteSpace(expectedJson));
HttpUriRequest arg = captor.getValue();
assertEquals(HttpGet.METHOD_NAME, arg.getMethod());
assertNull(extractHttpEntity(arg));
assertThat(arg.getURI().toString(), containsString(ENCODED_FIELDS));
client.mediaApi().get(11L);
assertEquals(2, captor.getAllValues().size());
assertThat(captor.getAllValues().get(1).getURI().toString(), not(containsString("fields")));
}
@Test
public void getNullId() throws Exception {
ex.expectMessage("id cannot be null");
ex.expect(NullPointerException.class);
client.mediaApi().get(null);
}
@Test
public void getDataNullId() throws Exception {
ex.expectMessage("id cannot be null");
ex.expect(NullPointerException.class);
client.mediaApi().getData((Long) null, null);
ex.expectMessage("type cannot be null");
ex.expect(NullPointerException.class);
client.mediaApi().getData(1L, null);
}
@Test
public void getDataEmptyKey() throws Exception {
ex.expectMessage("key cannot be blank");
ex.expect(IllegalArgumentException.class);
client.mediaApi().getData(" ", null);
ex.expectMessage("type cannot be null");
ex.expect(NullPointerException.class);
client.mediaApi().getData("key", null);
}
}
<file_sep>package com.callfire.api.client.api.callstexts.model.request;
import static lombok.AccessLevel.PRIVATE;
import java.util.List;
import com.callfire.api.client.api.campaigns.model.TextRecipient;
import com.callfire.api.client.api.common.model.request.QueryParamIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = PRIVATE)
public class SendTextsRequest extends SendCallsTextsRequest {
@QueryParamIgnore protected List<TextRecipient> recipients;
protected String defaultMessage;
public static Builder create() {
return new Builder();
}
public static class Builder extends SendCallsTextsBuilder<Builder, SendTextsRequest> {
private Builder() {
super(new SendTextsRequest());
}
public Builder recipients(List<TextRecipient> recipients) {
request.recipients = recipients;
return this;
}
public Builder defaultMessage(String defaultMessage) {
request.defaultMessage = defaultMessage;
return this;
}
}
}
<file_sep>package com.callfire.api.client.api.campaigns.model;
import com.callfire.api.client.api.common.model.CallfireModel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TransferNumber extends CallfireModel {
private String name;
private Boolean allowAssistedTransfer;
private String phoneNumber;
}
|
13b18fe81c119c992d287a3548e782d510aa458a
|
[
"Java",
"AsciiDoc",
"INI",
"Gradle"
] | 92
|
Java
|
CallFire/callfire-api-client-java
|
6d79cb88a466de714a29da78e28eaf333a479254
|
73cd541704a476dc4bbeb64b7632260b728e9aa8
|
refs/heads/master
|
<repo_name>Fenix4088/PortfolioApp<file_sep>/src/Components/Footer/Footer.jsx
import React from "react";
import "./Footer.scss"
export const Footer = () => {
return(
<footer className="footer">
<div className="container">
<div className="footer__devName">© 2020 - <NAME></div>
<p>Web developer from Zaporozhzhye, creating websites - my passion.</p>
</div>
</footer>
)
}<file_sep>/src/Components/ProjectInfo/AboutProject/SubNavigation.jsx
import React, { useContext } from "react";
import { ProjectsDataContext } from "../../../index";
import { NavLink } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faArrowAltCircleLeft,
faArrowAltCircleRight,
} from "@fortawesome/free-regular-svg-icons";
export const SubNavigation = (props) => {
const projectsData = useContext(ProjectsDataContext);
// const allPagesIds = Object.keys(projectsData).reverse();
const getPagesDirection = (currentPage, allProjects) => {
return allProjects.reduce(
(acc, currentElem, i, arr) => {
if (currentElem.id === currentPage) {
if (arr[i + 1]) {
acc.nextPage = arr[i + 1].id;
} else {
acc.nextPage = arr[0].id;
}
if (arr[i - 1]) {
acc.prevPage = arr[i - 1].id;
} else {
acc.prevPage = arr[arr.length - 1].id;
}
}
return acc;
},
{ prevPage: "", nextPage: "" }
);
};
const { prevPage, nextPage } = getPagesDirection(
props.currentPage,
projectsData
);
return (
<div className="about-project__buttons">
<NavLink
to={`/projectPage/${prevPage}`}
className="about-project__button-previous"
>
<FontAwesomeIcon icon={faArrowAltCircleLeft} size={"3x"} />
</NavLink>
<NavLink
to={`/projectPage/${nextPage}`}
className="about-project__button-next"
>
<FontAwesomeIcon icon={faArrowAltCircleRight} size={"3x"} />
</NavLink>
</div>
);
};<file_sep>/src/Components/Navigation/Navigation.jsx
import React, { useEffect} from "react";
import "./Navigation.scss";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import useResizeObserver from "use-resize-observer";
import useScrollBlock from "../../utils/blockScroll";
import {
faFacebookF,
faGithub,
faLinkedinIn,
} from "@fortawesome/free-brands-svg-icons";
import {Intouch} from "../CommonComponents/IntouchBlock/Intouch";
import {NavLink} from "react-router-dom";
import {HashLink} from "react-router-hash-link";
export const Navigation = ({menuStatus, setMenuStatus}) => {
const [blockScroll, allowScroll] = useScrollBlock();
const { ref, width = 1} = useResizeObserver();
const toggleMenu = () => setMenuStatus(!menuStatus);
const navigationBlockStyle = {
right: `${menuStatus || width > 991 ? "0px" : "-400px"}`,
};
useEffect(() => {
if (menuStatus) {
blockScroll();
} else {
allowScroll();
}
const body = document.querySelector("body");
const handler = (e) => {
if (e.path && !e.path.some((el) => el.dataset?.elem === "navigation")) {
setMenuStatus(false);
}
};
if (menuStatus) {
body && body.addEventListener("click", handler);
}
return () => {
body && body.removeEventListener("click", handler);
};
}, [menuStatus, blockScroll, allowScroll, setMenuStatus]);
return (
<div className="fixed-wrapper nav-fixed" ref={ref}>
<nav className="header__navigation">
<div className="header__navigation-logo">
<span className="title-line">
<NavLink to="/">YP</NavLink>
</span>
</div>
<div
data-elem="navigation"
className="header__navigation-block"
style={navigationBlockStyle}
>
<ul className="header__navigation-list">
<li className="header__navigation-list-item">
<NavLink to="/" className="active-page">
Main
</NavLink>
</li>
<li className="header__navigation-list-item">
<HashLink to="#projects">Projects</HashLink>
</li>
<li className="header__navigation-list-item">
<HashLink to="#contacts">Contacts</HashLink>
</li>
</ul>
<div className="header__navigation--intouch">
<Intouch size={"2x"}/>
</div>
<div className="header__naviation-email mobile-email">
<a href="mailto:<EMAIL>"><EMAIL></a>
</div>
</div>
<div className="header__navigation-icons">
<div className="header__navigation-icon linkedin-icon">
<a
href="https://www.linkedin.com/in/yehor-pliasov-5776981a2/"
target="_blank"
rel="noreferrer"
>
<FontAwesomeIcon
icon={faLinkedinIn}
size={"2x"}
className={"fa-linkedin-in"}
/>
</a>
</div>
<div className="header__navigation-icon git-icon">
<a
href="https://github.com/Fenix4088?tab=repositories"
target="_blank"
rel="noreferrer"
>
<FontAwesomeIcon
icon={faGithub}
size={"2x"}
className={"fa-linkedin-in"}
/>
</a>
</div>
<div className="header__navigation-icon facebook-icon">
<a
href="https://www.facebook.com/profile.php?id=100013553615468&ref=bookmarks"
target="_blank"
rel="noreferrer"
>
<FontAwesomeIcon
icon={faFacebookF}
size={"2x"}
className={"fa-facebook-f"}
/>
</a>
</div>
</div>
<BurgerMenu menuStatus={menuStatus} toggleMenu={toggleMenu} />
</nav>
</div>
);
};
export const BurgerMenu = (props) => {
const burgerMenuFinalStyle =
(props.menuStatus ? "burgerMenuOpen" : "burgerMenuClose") +
" " +
"burgerMenuCommon";
const toggleMenuCallback = () => props.toggleMenu(!props.menuStatus);
return (
<div className="header__burger-wrap" onClick={toggleMenuCallback}>
<span className={burgerMenuFinalStyle}> </span>
</div>
);
};
<file_sep>/src/Components/Header/HeaderContent.jsx
import React from "react";
import "./Header.scss";
import avatar from "../../assets/img/header/avatar.jpg";
import { PortfolioBTN } from "../CommonComponents/PortfolioBTN/PortfolioBTN";
export const HeaderContent = (props) => {
return (
<div className={"container"}>
<div className="header__content-wrapper">
<div className="header__content-description">
<h1 className="header__title">
<span className="title-line-big">Yehor</span>
<br />
<span className="title-line-big"> Pliasov</span>
</h1>
<p>
Front-end developer.
<br />
Quality, efficiency, compliance with deadlines and technical tasks.
</p>
<div className="header__btn-container">
<PortfolioBTN
path={"#aboutMe"}
linkType={"hash"}
theme={"color"}
title={"About me"}
additionalClass={"header__btn"}
/>
<PortfolioBTN
path={"#contacts"}
linkType={"hash"}
theme={"colorless"}
title={"Contacts"}
additionalClass={"header__btn"}
/>
</div>
</div>
<div className="header__content-photo">
<img src={avatar} alt="<NAME>" />
</div>
<div className="header__content-photo-back"></div>
</div>
</div>
);
};
<file_sep>/src/Components/CommonComponents/Notification/Notification.jsx
import React from "react";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
export const Notification = () => {
return (
<div>
<ToastContainer />
</div>
);
};<file_sep>/src/App.js
import React, { useEffect, useState } from "react";
import "./App.css";
import { Navigation } from "./Components/Navigation/Navigation";
import { Home } from "./Components/Home/Home";
import { Switch, Route } from "react-router-dom";
import { ProjectInfoContainer } from "./Components/ProjectInfo/ProjectInfo";
import useResizeObserver from "use-resize-observer";
import {Footer} from "./Components/Footer/Footer";
function App() {
const [menuStatus, setMenuStatus] = useState(false);
const { ref, width = 1 } = useResizeObserver();
useEffect(() => {
if (width >= 991) setMenuStatus(false);
}, [width]);
return (
<div ref={ref}>
<Overlay menuStatus={menuStatus} />
<Navigation menuStatus={menuStatus} setMenuStatus={setMenuStatus} />
<Switch>
<Route exact path="/" render={() => <Home />} />
<Route
exact
path="/projectPage/:projectName"
render={() => <ProjectInfoContainer />}
/>
</Switch>
<Footer/>
</div>
);
}
export const Overlay = ({ menuStatus }) => {
return <div className={`${menuStatus ? "overlay" : ""}`}> </div>;
};
export default App;
<file_sep>/src/Components/Timeline/TimelineStage.jsx
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
export const TimelineStage = React.memo((props) => {
const { title, desc, dates, icon } = props.data;
return (
<div className="how-it-works__timeline-stage">
<div className="timeline-stage-wrapper ">
<div className="how-it-works__timeline-title">
<span className="title-line">{title}</span>
</div>
<div className="how-it-works__timeline-description">{desc}</div>
<div className="how-it-works__timeline-timing">{dates}</div>
</div>
<div className="how-it-works__timeline-img">
{icon.icon && (
<FontAwesomeIcon
icon={icon.icon}
size={"3x"}
className={icon.class}
/>
)}
</div>
</div>
);
});<file_sep>/README.md
# Portfolio-project
This is my portfolio project, all my Web projects presented here.
### Technologies:
* HTML
* CSS(SCSS)
* JavaScript, React.js
[View demo](https://fenix4088.github.io/PortfolioApp/);
<file_sep>/src/Components/Timeline/Timeline.jsx
import React from "react";
import "./Timeline.scss";
import { timelineData } from "../../assets/data/timelineData";
import { TimelineStage } from "./TimelineStage";
import bgImage from "../../assets/img/backgrounds/how-it-works-lines-bg.jpg"
export const Timeline = React.memo(() => {
return (
<section className="how-it-works" id="how-it-work" style={{backgroundImage: `url(${bgImage})`}}>
<div className="container">
<div className="sub-container">
<h2 className="how-it-works__title">
<span className="title-line-middle">Education</span>
</h2>
<div className="how-it-works__timeline">
{timelineData.map((timelineStage, i) => {
return <TimelineStage key={i} data={timelineStage} />;
})}
</div>
</div>
</div>
</section>
);
});
<file_sep>/src/assets/data/timelineData.js
import {faJsSquare, faReact,} from "@fortawesome/free-brands-svg-icons";
import {faCode, faUniversity} from "@fortawesome/free-solid-svg-icons";
export const timelineData = [
{
title: "Zaporizhzhia Technical University",
desc:
"Bachelor's Degree in in welding technologies and equipment\n" +
"Engineering and Technology Faculty\n",
dates: "2009 - March 2013",
icon: {
icon: faUniversity,
class: "fa-university",
},
},
{
title: "Zaporizhzhia Technical University",
desc: "Specialist in welding technologies and equipment\n" +
"Engineering and Technology Faculty\n",
dates: "2013 - March 2014",
icon: {
icon: faUniversity,
class: "fa-university--specialist",
},
},
{
title: "Online course on HTML / CSS coding",
desc: "HTML, CSS coding, responsive web design, PixelPerfect, Bootsrtap, basics of JS, jQuery",
dates: "2013 - March 2014",
icon: {
icon: faCode,
class: "fa-code",
},
},
{
title: "JavaScript course",
desc: "JavaScript (OOP), working with DOM, creating SPA applications, working with Webpack",
dates: "April 2020 – July 2020",
icon: {
icon: faJsSquare,
class: "fab fa-js-square",
},
},
{
title: "JavaScript course (advanced level)",
desc: "JavaScript (OOP), working with DOM, creating SPA applications, UI for programmers",
dates: "August 2020 – November 2020",
icon: {
icon: faJsSquare,
class: "fab fa-js-square",
},
},
{
title: "React/Redux course",
desc: "React, Redux(react-redux, redux-thunk), TypeScript, JavaScript, MaterialUI, Unit-test",
dates: "December 2020",
icon: {
icon: faReact,
class: "fab fa-react",
},
},
];
<file_sep>/src/Components/Project/Project.jsx
import React from "react";
import "./Project.scss";
import { NavLink } from "react-router-dom";
export const Project = (props) => {
const { linkTitle, images, title, type, id, } = props.data;
return (
<div className={`portfolio__card ${props.animation}`}>
<div className="portfolio__project-img">
<img src={images.small} alt={title} />
<NavLink to={`/projectPage/${id}`} className="portfolio__project-btn">
View
</NavLink>
</div>
<div className="portfolio__project-desk">
<div className="portfolio__project-title-wrapper">
<NavLink
to={`/projectPage/${id}`}
className="portfolio__project-title portfolio__project-title--small"
>
{linkTitle}
</NavLink>
<div className="portfolio__project-description portfolio__project-description--small">
{type}
</div>
</div>
</div>
</div>
);
};<file_sep>/src/Components/ProjectInfo/ProjectHeader/ProjectHeader.jsx
import React from "react";
import "./ProjectHeader.scss"
export const ProjectHeader = (props) => {
const { title, mainTech } = props;
return (
<div className="project-info">
<div className="container">
<h2 className="project-info__title">
<span className="title-line-middle">{title}</span>
</h2>
<div className="project-info__technology">
{mainTech.map((t, i) => {
return (
<div
key={i}
className={`project-info__technology-item project-info__technology-item--${t}`}
>
{t}
</div>
);
})}
</div>
</div>
</div>
);
};<file_sep>/src/Components/ProjectInfo/AboutProject/AboutProject.jsx
import React from "react";
import "./AboutProject.scss";
import { SubNavigation } from "./SubNavigation";
import { ProjectDescription } from "./ProjectDescription";
import { ProjectDetails } from "./ProjectDetails";
export const AboutProject = (props) => {
const { links, desc, project, allTech, features, images } = props.data;
const currentPageId = props.data.id;
return (
<section className="about-project">
<div className="container" style={{ position: "relative" }}>
<div className="project-wrapper">
<div className="about-project__info">
<div className="about-project__links-wrap">
<div className="about-project__wrapper--mobile">
<ProjectDescription links={links} desc={desc} />
<ProjectDetails
project={project}
links={links}
allTech={allTech}
features={features}
/>
</div>
</div>
</div>
<div className="about-project__img">
<img src={images.big} alt="budget-calculator" />
</div>
</div>
<SubNavigation currentPage={currentPageId} />
</div>
</section>
);
};
<file_sep>/src/Components/MySkills/MySkills.jsx
import React from "react"
import "./MySkills.scss"
import cv from "../../assets/docs/Pliasov_Yehor_ReactDev_CV.pdf"
import {Intouch} from "../CommonComponents/IntouchBlock/Intouch";
import {PortfolioBTN} from "../CommonComponents/PortfolioBTN/PortfolioBTN";
export const MySkills = () => {
return (
<div>
<div className="container">
<section className="header__my-skils-wrapper" id="aboutMe" >
<div className="header__my-skils">
<h3 className="header__my-skils-title">My skills:</h3>
<ul className="header__my-skils-lists">
<li className="header__my-skils-list">
React.js + Redux
</li>
<li className="header__my-skils-list">
JavaScript, TypeScript
</li>
<li className="header__my-skils-list">
redux-thunk/saga, redux-toolkit
</li>
<li className="header__my-skils-list">
HTML, CSS(SCSS/LESS), RWD, AWD
</li>
<li className="header__my-skils-list">
Axios, REST API
</li>
<li className="header__my-skils-list">
Photoshop, Figma, Avocode
</li>
<li className="header__my-skils-list">
GIT
</li>
<li className="header__my-skils-list">
UNIT-test(JEST), Storybook, TDD
</li>
<li className="header__my-skils-list">
Material-UI, Ant Design, styled-components, module-css,
</li>
</ul>
<PortfolioBTN
path={cv}
linkType={"download"}
theme={"color"}
title={"Download CV"}
additionalClass={"header__my-skils-btn"}
/>
</div>
<Intouch size={"3x"} showTitle={true} showEmail={true}/>
</section>
</div>
</div>
);
}<file_sep>/src/Components/CommonComponents/PortfolioBTN/PortfolioBTN.jsx
import { HashLink } from "react-router-hash-link";
import { NavLink } from "react-router-dom";
import React from "react";
import "./PortfolioBTN.scss"
import {faFileDownload} from "@fortawesome/free-solid-svg-icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
export const PortfolioBTN = (props) => {
const { theme, linkType, title, path, additionalClass } = props;
const linkStyle = theme === "color" ? "color" : "colorless";
return (
<>
{linkType === "hash" ? (
<HashLink to={path} className={`${linkStyle}-btn ${additionalClass}`}>
{title}
</HashLink>
) :
linkType === "nav" ? (
<NavLink to={path} className={`${linkStyle}-btn ${additionalClass}`}>
{title}
</NavLink>
) :
<a href={path} className={`${linkStyle}-btn ${additionalClass}`} target="_blank" rel="noreferrer" download>
<div style={{display: "flex", justifyContent: "center", alignItems: "center"}}>
<FontAwesomeIcon icon={faFileDownload} style={{marginRight: "10px"}}/>
{title}
</div>
</a>
}
</>
);
};<file_sep>/src/Components/CommonComponents/ContactUs/ContactUs.jsx
import React, { useState } from "react";
import emailjs from "emailjs-com";
import { Preloader } from "../Preloader/Preloader";
import { Notification } from "../Notification/Notification";
import { toast } from "react-toastify";
export function ContactUs() {
const [isSending, setIsSending] = useState(false);
const [nameInpVal, setNameInputValue] = useState("");
const [emailInpVal, setEmailInpVal] = useState("");
const [messageInpVal, setMessageInpVal] = useState("");
const nameInpChange = (curVal) => setNameInputValue(curVal);
const emailInpChange = (curVal) => setEmailInpVal(curVal);
const messageInpChange = (curVal) => setMessageInpVal(curVal);
const messageSendCallback = (messageText, status) => {
const toastPosition = {
position: toast.POSITION.BOTTOM_CENTER
}
if(status) {
toast.success(messageText, toastPosition);
} else {
toast.error(messageText, toastPosition);
}
}
function sendEmail(e) {
e.preventDefault();
setIsSending(true);
emailjs
.sendForm(
"service_2wk4yc9",
"template_59m3bfi",
e.target,
"user_LF091J7HzI7ijp7ACG5T1"
)
.then(
() => {
messageSendCallback("Message sent!", true);
setIsSending(false);
nameInpChange("");
emailInpChange("");
messageInpChange("");
},
() => {
messageSendCallback("This message wasn't send!", false);
setIsSending(false);
}
);
}
const formInputData = [
{
inputType: "input",
name: "user_name",
placeholder: "Name",
value: nameInpVal,
onInputChange: nameInpChange,
},
{
inputType: "input",
name: "user_email",
placeholder: "Your email",
value: emailInpVal,
onInputChange: emailInpChange,
},
{
inputType: "textarea",
name: "message",
placeholder: "Message",
value: messageInpVal,
onInputChange: messageInpChange,
},
];
return (
<form className="contacts__form" onSubmit={sendEmail}>
<Notification />
{isSending && <Preloader />}
{isSending && <div className={"form-overlay"}></div>}
<input type="hidden" name="contact_number" />
<div className="contacts__form-inputs-wrapper">
{formInputData.map((item, i) => (
<FormInput
key={i}
value={item.value}
onInputChange={item.onInputChange}
name={item.name}
inputType={item.inputType}
disabled={isSending}
placeholder={item.placeholder}
/>
))}
</div>
<button
disabled={isSending}
type="submit"
className="contacts__form-btn"
value="Send"
>
Send
</button>
</form>
);
}
export const FormInput = ({
inputType,
disabled,
placeholder,
name,
value,
onInputChange,
}) => {
const [isActive, setIsActive] = useState(false);
const activePlaceholderStyles = {
fontSize: "16px",
color: "rgb(237, 150, 38)",
top: "-20px",
};
const onFocusHandler = (e) => {
setIsActive(true);
};
const onBlurHandler = (e) => {
const { value } = e.currentTarget;
if (value.trim()) {
setIsActive(true);
} else {
setIsActive(false);
}
};
const onChangeHandler = (e) => onInputChange(e.currentTarget.value);
return (
<div className="contacts__form-item">
{inputType === "input" ? (
<input
onFocus={onFocusHandler}
onBlur={onBlurHandler}
onChange={onChangeHandler}
disabled={disabled}
value={value}
type="text"
name={name}
className="contacts__form-input"
required
/>
) : (
<textarea
onFocus={onFocusHandler}
onBlur={onBlurHandler}
onChange={onChangeHandler}
value={value}
disabled={disabled}
className="contacts__form-input contacts__form-input--textarea"
name={name}
/>
)}
<span
className="contacts__form-placeholder"
style={isActive ? activePlaceholderStyles : {}}
>
{placeholder}
</span>
</div>
);
};
<file_sep>/src/Components/Portfolio/Portfolio.jsx
import React, { useContext, useState } from "react";
import "./Portfolio.scss";
import { Project } from "../Project/Project";
import { ProjectsDataContext } from "../../index";
import { v1 } from "uuid";
const menuItemList = [
{ title: "All projects", mark: "all" },
{ title: "Native JS", mark: "js" },
{ title: "React.js", mark: "react" },
{ title: "HTML/CSS", mark: "markup" },
];
export const Portfolio = () => {
const projectsData = useContext(ProjectsDataContext);
const [currentProjects, setCurrentProjects] = useState(projectsData);
const [isActive, setIsActive] = useState(0);
const [isAnimate, setIsAnimate] = useState(false);
const onProjectMenuClick = (e, index) => {
setIsAnimate(true);
setTimeout(() => {
setIsAnimate(false);
}, 1000);
setIsActive(index);
let filteredProjectData = [...projectsData];
const { project } = e.currentTarget.dataset;
if (project !== "all") {
filteredProjectData = filteredProjectData.filter(
(p) => p.label === project
);
setCurrentProjects(filteredProjectData);
} else {
setCurrentProjects(filteredProjectData);
}
};
return (
<section className="portfolio" id="projects">
<div className="container">
<h2 className="portfolio__title">
<span className="title-line-middle">Portfolio</span>
</h2>
<div className="portfolio__toggles">
{menuItemList.map((item, i) => {
return (
<MenuItem
key={v1()}
mark={item.mark}
title={item.title}
index={i}
onProjectMenuClick={onProjectMenuClick}
isActive={isActive}
/>
);
})}
</div>
<div
className="portfolio__projects-wrapper"
id="portfolio-project-filter"
>
{currentProjects.map((p, i) => (
<Project
key={p.id}
data={p}
animation={isAnimate ? "portfolio__card--animation" : ""}
/>
))}
</div>
</div>
</section>
);
};
export const MenuItem = (props) => {
return (
<div
data-project={props.mark}
className={`portfolio__toggle ${
props.isActive === props.index ? "portfolio__toggle--active" : ""
}`}
onClick={(e) => props.onProjectMenuClick(e, props.index)}
>
{props.title}
</div>
);
};
|
8842b643b043f8d3d5f950e8780ab104ad237809
|
[
"JavaScript",
"Markdown"
] | 17
|
JavaScript
|
Fenix4088/PortfolioApp
|
18e20b1a6ccef9c6c05530feaa1e9147fd273ecb
|
3ec5f4790344104ea3a7083d6f81418a589f13ae
|
refs/heads/master
|
<file_sep>//
// AlertLearnViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/30.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class AlertLearnViewController: UIViewController {
var controller:UIAlertController?
override func viewDidLoad() {
super.viewDidLoad()
// controller = UIAlertController(title: "Title",
// message: "Message",
// preferredStyle: .Alert)
// let action = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default,
// handler: {
// (paramAction:UIAlertAction!) in
// print("The Done button was tapped")
// })
// controller!.addAction(action)
controller = UIAlertController(
title: "Choose how you would like to share this photo",
message: "You cannot bring back a deleted photo",
preferredStyle: .ActionSheet)
let actionEmail = UIAlertAction(title: "Via email", style: UIAlertActionStyle.Default,
handler: {(paramAction:UIAlertAction!) in
/* Send the photo via email */
})
let actionImessage = UIAlertAction(title: "Via iMessage", style: UIAlertActionStyle.Default,
handler: {(paramAction:UIAlertAction!) in
/* Send the photo via iMessage */
})
let actionDelete = UIAlertAction(title: "Delete photo", style: UIAlertActionStyle.Destructive,
handler: {(paramAction:UIAlertAction!) in
/* Delete the photo here */
})
controller!.addAction(actionEmail)
controller!.addAction(actionImessage)
controller!.addAction(actionDelete)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.presentViewController(controller!, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showAlert(sender: AnyObject) {
// let buttonTitle = "sender.titleLabel?.text" // 1
// var message = ""
// if buttonTitle == country!.correctAnswer { // 2
// message = "You answered correctly!"
// } else {
// message = "That answer is incorrect, please try again."
// }
//
// let alert = UIAlertController(title:nil, message:message, preferredStyle:UIAlertControllerStyle.ActionSheet) // 3
//
// alert.addAction(UIAlertAction(title: "OK",style: UIAlertActionStyle.Default,
// handler: {
// (alert :UIAlertAction) in
// print("You tapped OK")
// })) // 4
//
// alert.popoverPresentationController?.sourceView = view
// alert.popoverPresentationController?.sourceRect = sender.frame
//
// self.presentViewController(alert, animated: true, completion: nil) // 5
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// BubbleViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/6.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class BubbleViewController: UIViewController {
@IBOutlet weak var dismissBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// dismissBtn.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
dismissBtn.layer.cornerRadius = CGRectGetHeight(self.dismissBtn.frame) / 2
dismissBtn.layer.shadowColor = UIColor.blackColor().CGColor
dismissBtn.layer.shadowOpacity = 0.75
dismissBtn.layer.shadowRadius = 5.0
dismissBtn.layer.shadowOffset = CGSize(width: 0, height: 1.5)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dismissView(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep># swiftLearn
learn iOS
更多MK:https://github.com/nghialv/MaterialKit
<file_sep>//
// CircleAnimationViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/5.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class CircleAnimationViewController: UIViewController {
var starView:StarView = StarView(frame: CGRectMake(0, 0, 100, 100))
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
starView.center = CGPointMake(self.view.center.x, self.view.center.y-200)
self.view.addSubview(starView)
let number = randomInRange(1...100)
starView.startLoadNumber(number)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func animation(sender: UIButton) {
let number = randomInRange(1...100)
starView.startLoadNumber(number)
}
func initProcess(){
}
func randomInRange(range: Range<Int>) -> Int {
let count = UInt32(range.endIndex - range.startIndex)
return Int(arc4random_uniform(count)) + range.startIndex
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
class StarView: UIView {
var progressLayer: CAShapeLayer = CAShapeLayer()
var passesLabel:UILabel = UILabel(frame: CGRectMake(15, 64, 60, 20))
var tensSliderContainer:SliderLabelContainer = SliderLabelContainer(frame: CGRectMake(27, 13, 20, 45), type: SliderLabelContainerType.TensDigitType)
var singleSliderContainer:SliderLabelContainer = SliderLabelContainer(frame: CGRectMake(50, 13, 20, 45), type: SliderLabelContainerType.SingleDigitType)
override init(frame: CGRect) {
super.init(frame: frame)
progressLayer.lineWidth = 2
progressLayer.fillColor = UIColor.clearColor().CGColor
progressLayer.strokeColor = UIColor.whiteColor().CGColor
progressLayer.path = UIBezierPath(ovalInRect: self.bounds).CGPath
self.layer.addSublayer(progressLayer)
passesLabel.backgroundColor = UIColor.blueColor()
passesLabel.font = UIFont.systemFontOfSize(15)
passesLabel.text = "PASSES"
passesLabel.textColor = UIColor.whiteColor()
passesLabel.center = CGPointMake(CGRectGetWidth(self.bounds)/2.0, CGRectGetHeight(self.bounds)/2+20.0)
passesLabel.textAlignment = NSTextAlignment.Center
self.addSubview(passesLabel)
self.addSubview(singleSliderContainer)
self.addSubview(tensSliderContainer)
}
func startLoadNumber(num:Int){
let tensDigit:Int = num/10
let singleDigit:Int = num%10
print(tensDigit)
print(singleDigit)
tensSliderContainer.scrollToNum(tensDigit)
singleSliderContainer.scrollToNum(singleDigit)
startDrawCircleAnimation()
}
override func layoutSubviews() {
let radius:CGFloat = CGRectGetWidth(self.bounds)/2.0
let center = CGPointMake(radius, radius)
let startAngle = -M_PI_2
let endAngle = M_PI_2*3.0
let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true)
progressLayer.path = circlePath.CGPath
}
func startDrawCircleAnimation(){
let pathAnimation:CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.fromValue = 0
pathAnimation.toValue = 1
pathAnimation.duration = 0.5
progressLayer.addAnimation(pathAnimation, forKey: "pathAnimation")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
enum SliderLabelContainerType{
case SingleDigitType
case TensDigitType
}
class SliderLabelContainer: UIView {
var singleDigitsScroll:UIScrollView!
private var scrollType:SliderLabelContainerType = SliderLabelContainerType.SingleDigitType
init(frame: CGRect, type:SliderLabelContainerType) {
super.init(frame: frame)
scrollType = type
singleDigitsScroll = UIScrollView(frame: self.bounds)
singleDigitsScroll.contentSize = CGSizeMake(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)*10)
for i in 0...10{
let label:UILabel = UILabel(frame: CGRectMake(0, CGRectGetHeight(self.bounds) * CGFloat(i), CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)))
label.text = "\(i)"
label.textAlignment = NSTextAlignment.Center
label.font = UIFont.boldSystemFontOfSize(30)
label.textColor = UIColor.whiteColor()
singleDigitsScroll.addSubview(label)
}
self.addSubview(singleDigitsScroll)
}
func scrollToNum(num:Int){
if scrollType == .SingleDigitType{
UIView.animateWithDuration(0.85, animations: { () -> Void in
self.singleDigitsScroll.contentOffset = CGPointMake(0, CGRectGetHeight(self.bounds) * CGFloat(num))
})
}else {
UIView.animateWithDuration(1, animations: { () -> Void in
self.singleDigitsScroll.contentOffset = CGPointMake(0, CGRectGetHeight(self.bounds) * CGFloat(num))
})
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
<file_sep>//
// PlistPersistenceViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/7.
// Copyright © 2015年 D_ttang. All rights reserved.
//
//只有如下集中OC类才能够用writeToFile(<path: String>, atomically: <Bool>)方法将它们存储到属性列表中
//NSArray
//NSMutableArray
//NSDictionary
//NSMutableDictionary
//NSData
//NSMutableData
//NSString
//NSMutableString
//NSNumber
//NSDate
import UIKit
class PlistPersistenceViewController: UIViewController {
@IBOutlet weak var textFiled: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let filename:NSString = self.filePath("properties.plist")
if NSFileManager.defaultManager().fileExistsAtPath(filename as String) {
// let data:NSArray = NSArray(contentsOfFile: filename as String)!
if let fileData = NSMutableDictionary(contentsOfFile: filename as String) {
let data: NSMutableDictionary = fileData
print(data)
}
// textFiled.text = data.objectAtIndex(0) as? String
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPush(sender: AnyObject) {
print("click")
let filename:NSString = self.filePath("properties.plist")
print(filename)
let data:NSMutableDictionary = NSMutableDictionary()
data.setObject(["name": "black", "color": "color"], forKey: "color")
data.writeToFile(filename as String, atomically: true)
}
//这个函数首先是获取Documents目录,每个程序都有自己的Documents文件夹,并且它们仅仅只能读写自己的Documents文件夹中的内容,这也是我们数据存储的地方。那么如何检索Documents目录的完整路径呢?这里我们使用C函数NSSearchPathForDirectoriesInDomain()来查找各种目录。
//这个函数中的常量NSSearchPathDirectory.DocumentDirectort表明我们正在查找Documents目录的路径(NSSearchPathDirectory中还有其他的目录路径,感兴趣的读者可以前去看一看);第二个常量NSSearchPathDomainMask.UserDomainMask表明我们希望将搜索限制在应用程序的沙盒内。
//虽然这个函数返回了一个匹配路径的数组,但是我们知道数组中位于索引0处的一定是Documents目录,因为每个应用程序仅有一个Documents目录,因此只有一个目录符合指定的检索条件。
//之后,我们在刚刚检索到的路径尾巴后面附上另外一个字符串来创建文件名,这就要使用stringByAppendingPathComponent方法.
//完成此调用之后,filePath()这个函数就是返回应用程序的Documents目录中的filename文件的完整路径了,这个时候我们就可以来创建、读取文件了
func filePath(filename: NSString) -> NSString {
let mypaths:NSArray = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let mydocpath:NSString = mypaths.objectAtIndex(0) as! NSString
let filepath = mydocpath.stringByAppendingPathComponent(filename as String)
return filepath
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// SocketViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/4.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class StreamSocketViewController: UIViewController {
var inputStream : NSInputStream?
var outputStream : NSOutputStream?
var receivedData: NSMutableData!
let host = "localhost"
let port = 30000
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.connect()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func send(sender: UIButton) {
// print("sending...")
sendData()
}
func connect() {
var readStream : Unmanaged<CFReadStream>?
var writeStream : Unmanaged<CFWriteStream>?
let host : CFString = NSString(string: self.host)
let port : UInt32 = UInt32(self.port)
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream)
inputStream = readStream!.takeUnretainedValue()
outputStream = writeStream!.takeUnretainedValue()
// inputStream!.delegate = self
// outputStream!.delegate = self
inputStream?.setProperty(kCFBooleanTrue, forKey: kCFStreamPropertyShouldCloseNativeSocket as String)
outputStream?.setProperty(kCFBooleanTrue, forKey: kCFStreamPropertyShouldCloseNativeSocket as String)
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
// CFReadStreamScheduleWithRunLoop(readStream, NSRunLoop().getCFRunLoop(), NSDefaultRunLoopMode)
// CFWriteStreamScheduleWithRunLoop(writeStream, NSRunLoop().getCFRunLoop(), NSDefaultRunLoopMode)
inputStream!.open()
outputStream!.open()
}
func sendData(){
let data: NSData = "hello world".dataUsingEncoding(NSUTF8StringEncoding)!
print("\(outputStream?.streamStatus.rawValue)")
outputStream?.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
}
func reciveServer(message mes: String){
print("message has been recived :\(mes)")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension StreamSocketViewController: NSStreamDelegate {
func stream(theStream: NSStream, handleEvent eventCode: NSStreamEvent) {
print("stream event \(eventCode)")
switch eventCode {
case NSStreamEvent.OpenCompleted:
print("OpenCompleted")
case NSStreamEvent.HasBytesAvailable:
print("has bytes")
if theStream == inputStream{
var buffer: UInt8 = 0
var len: Int!
while (inputStream?.hasBytesAvailable != nil){
len = inputStream?.read(&buffer, maxLength: 1024)
if len > 0{
let output = NSString(bytes: &buffer, length: len, encoding:NSUTF8StringEncoding)
if nil != output{
self.reciveServer(message: output as! String)
}
}
}
}else {
print("some other")
}
case NSStreamEvent.ErrorOccurred:
print("Can not connect to the host!")
case NSStreamEvent.EndEncountered:
print("EndEncountered")
outputStream!.close()
outputStream!.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream = nil
default:
print("Unknown event")
}
// if theStream == inputStream {
// print("inputStream status : \(theStream.streamStatus.rawValue)")
// }
// if theStream == outputStream {
// print("outputStream status : \(theStream.streamStatus.rawValue)")
// }
}
}<file_sep>//
// CustomImageView.swift
// swiftLearn
//
// Created by D_ttang on 15/7/8.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class CustomImageView: UIImageView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let ctx:CGContextRef = UIGraphicsGetCurrentContext()
CGContextBeginPath(ctx)
CGContextMoveToPoint (ctx, CGRectGetMinX(rect), CGRectGetMidY(rect)); // top left
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect)); // mid right
CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)); // bottom left
CGContextClosePath(ctx);
CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
CGContextFillPath(ctx);
}
*/
func customShape(){
let mask: CAShapeLayer = CAShapeLayer()
// mask.path = [[self polygonPathWithRect:self.imageView.bounds lineWidth:0.0 sides:6] CGPath];
mask.path = self.polygonPathWithRect(self.bounds, lineWidth: 0.0 ,sides: 6).CGPath
mask.strokeColor = UIColor.redColor().CGColor
mask.fillColor = UIColor.whiteColor().CGColor
self.layer.mask = mask
}
/** Create UIBezierPath for regular polygon inside a CGRect
*
* @param square The CGRect of the square in which the path should be created.
* @param lineWidth The width of the stroke around the polygon. The polygon will be inset such that the stroke stays within the above square.
* @param sides How many sides to the polygon (e.g. 6=hexagon; 8=octagon, etc.).
*
* @return UIBezierPath of the resulting polygon path.
*/
func polygonPathWithRect(square: CGRect, lineWidth: CGFloat, sides:Int) -> UIBezierPath {
let path = UIBezierPath()
let a: CGFloat = 2.0
let b: CGFloat = CGFloat(M_PI / Double(sides))
let theta = a * b
let c: CGFloat = CGFloat(cosf(Float(theta) / 2.0))
let d: CGFloat = CGFloat(tanf(Float(theta) / 2.0))
let squareWidth = min(square.size.width, square.size.height)
var length = squareWidth - lineWidth
if sides % 4 != 0 {
length = length * c
}
let sideLength = length * d
var point = CGPoint(x: squareWidth / 2.0 + sideLength / 2.0, y: squareWidth - (squareWidth - length) / 2.0)
var angle = CGFloat(M_PI)
path.moveToPoint(point)
for (var side = 0; side < sides; side++) {
let x: CGFloat = point.x + sideLength * CGFloat(cosf(Float(angle)))
let y: CGFloat = point.y + sideLength * CGFloat(sinf(Float(angle)))
point = CGPointMake(x, y)
path.addLineToPoint(point)
angle += theta
}
path.closePath()
return path
}
// - (UIBezierPath *)polygonPathWithRect:(CGRect)square
// lineWidth:(CGFloat)lineWidth
// sides:(NSInteger)sides
// {
// UIBezierPath *path = [UIBezierPath bezierPath];
//
// CGFloat theta = 2.0 * M_PI / sides; // how much to turn at every corner
// CGFloat squareWidth = MIN(square.size.width, square.size.height); // width of the square
//
// // calculate the length of the sides of the polygon
//
// CGFloat length = squareWidth - lineWidth;
// if (sides % 4 != 0) { // if not dealing with polygon which will be square with all sides ...
// length = length * cosf(theta / 2.0); // ... offset it inside a circle inside the square
// }
// CGFloat sideLength = length * tanf(theta / 2.0);
//
// // start drawing at `point` in lower right corner
//
// CGPoint point = CGPointMake(squareWidth / 2.0 + sideLength / 2.0, squareWidth - (squareWidth - length) / 2.0);
// CGFloat angle = M_PI;
// [path moveToPoint:point];
//
// // draw the sides and rounded corners of the polygon
//
// for (NSInteger side = 0; side < sides; side++) {
// point = CGPointMake(point.x + sideLength * cosf(angle), point.y + sideLength * sinf(angle));
// [path addLineToPoint:point];
// angle += theta;
// }
//
// [path closePath];
//
// return path;
// }
}
<file_sep>//
// ExtendTransition.swift
// swiftLearn
//
// Created by D_ttang on 15/7/1.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import Foundation
import UIKit
class ExtendTransition: NSObject, UIViewControllerAnimatedTransitioning {
var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()
self.transitionContext = transitionContext
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! FirstViewController
let fromView = fromViewController.view //from view
let toController: UIViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
var toView = toController.view
// toView.clipsToBounds = true
//
// let scaleTransform = CGAffineTransformMakeScale(1, 0.3)
//
// toView.transform = scaleTransform
//
containerView!.addSubview(fromView)
containerView!.addSubview(toView)
containerView!.bringSubviewToFront(toView)
//
// UIView.animateWithDuration(1, animations: {
// toView.transform = CGAffineTransformIdentity
// }, completion: {
// _ in
// transitionContext.completeTransition(true)
// })
let buttonFrame = fromViewController.btn.frame
let buttonFrameCenter = fromViewController.btn.center
print("\(buttonFrameCenter)")
let endFrame = CGRectMake( buttonFrameCenter.x - CGRectGetHeight(toView.frame) , buttonFrameCenter.y-CGRectGetHeight(fromView.frame), CGRectGetHeight(toView.frame)*2, CGRectGetHeight(toView.frame)*2)
// containerView!.addSubview(fromViewController.view)
// containerView!.addSubview(destinationView)
let maskPath = UIBezierPath(ovalInRect: buttonFrame)
let maskLayer = CAShapeLayer()
maskLayer.frame = toView.frame
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.redColor().CGColor
toView.layer.mask = maskLayer
let bigCirclePath = UIBezierPath(ovalInRect: endFrame)
let pathAnimation = CABasicAnimation(keyPath: "path")
pathAnimation.delegate = self
pathAnimation.fromValue = maskPath.CGPath
pathAnimation.toValue = bigCirclePath
pathAnimation.duration = 0.3
// pathAnimation.duration = transitionDuration(transitionContext)
// maskLayer.fillColor = UIColor.redColor().CGColor
maskLayer.path = bigCirclePath.CGPath
maskLayer.addAnimation(pathAnimation, forKey: "pathAnimation")
// fromView.backgroundColor = UIColor.redColor()
toView.backgroundColor = UIColor.whiteColor()
// toView.backgroundColor = UIColor.redColor()
// UIView.animateWithDuration(0.23, animations: {
// // toView.transform = CGAffineTransformIdentity
////
// }, completion: {
// _ in
//
// transitionContext.completeTransition(true)
// })
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let transitionContext = self.transitionContext {
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
}
}
}<file_sep>//
// AddViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/6.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class AddViewController: UIViewController {
@IBOutlet weak var addBtn: UIButton!
let transition = BubbleTransition()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addBtn.layer.cornerRadius = CGRectGetHeight(self.addBtn.frame) / 2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController
controller.transitioningDelegate = self
controller.modalPresentationStyle = .Custom
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension AddViewController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Present
// transition.transitionMode = .Pop
transition.startingPoint = addBtn.center
transition.bubbleColor = addBtn.backgroundColor!
return transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Dismiss
transition.startingPoint = addBtn.center
transition.bubbleColor = addBtn.backgroundColor!
return transition
}
}
<file_sep>//
// CustomView.swift
// swiftLearn
//
// Created by D_ttang on 15/7/8.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class CustomView: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
override func drawRect(rect: CGRect) {
// Drawing code
let ctx:CGContextRef = UIGraphicsGetCurrentContext()
CGContextBeginPath(ctx)
CGContextMoveToPoint (ctx, CGRectGetMinX(rect), CGRectGetMidY(rect)); // top left
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect)); // mid right
CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)); // bottom left
CGContextClosePath(ctx);
CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
CGContextFillPath(ctx);
}
}
//let ctx:CGContextRef = UIGraphicsGetCurrentContext()
//
//CGContextBeginPath(ctx)
//
//CGContextMoveToPoint (ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)); // top left
//CGContextAddLineToPoint(ctx, CGRectGetMidX(rect), CGRectGetMinY(rect)); // mid right
//CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMaxY(rect)); // bottom left
//
//CGContextClosePath(ctx);
//
//CGContextSetRGBFillColor(ctx, 241/255.0, 241/255.0, 241/255.0, 1);
//CGContextFillPath(ctx);
<file_sep>//
// TimerViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/6/28.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class TimerViewController: UIViewController {
@IBOutlet weak var showLabel: UILabel!
@IBOutlet weak var startBtn: UIButton!
@IBOutlet weak var stopBtn: UIButton!
@IBOutlet weak var backZeroBtn: UIButton!
var timer = NSTimer()
var timeCount = 0
var timerRuning = false
func Counting(){
timeCount += 1
showLabel.text = "\(timeCount)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
showLabel.text = "0"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func startAction(sender: UIButton) {
if !timerRuning {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("Counting"), userInfo: nil, repeats: true)
timerRuning = true
}
}
@IBAction func stopAction(sender: UIButton) {
if timerRuning {
timer.invalidate()
timerRuning = false
}
}
@IBAction func backZeroAction(sender: AnyObject) {
timeCount = 0
showLabel.text = "0"
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// ViewController.swift
// subPhoto
//
// Created by D_ttang on 15/6/28.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var subImageView: UIImageView!
@IBOutlet weak var imageView: UIImageView!
var subRect: CGRect!
var scaleSize: CGSize!
var useSubRect: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let sizeWidth = view.frame.width
var sizeHeight = view.frame.height
subRect = CGRectMake(view.center.x - 50, view.center.y - 50, 300, 300)
// subImageView.layer.cornerRadius = CGRectGetWidth(subImageView.frame) / 2
// subImageView.layer.masksToBounds = true
var imageViewImage = imageView.image
let imageViewImageSize = imageViewImage?.size
let imageViewImageSizeWidth = imageViewImageSize?.width
let imageViewImageSizeHeight = imageViewImageSize?.height
print("\(imageViewImageSizeWidth)...\(imageViewImageSizeHeight)")
if let imageWidth = imageViewImageSizeWidth, imageHeight = imageViewImageSizeHeight {
sizeHeight = sizeWidth / imageWidth * imageHeight
}
// let imageViewFrame = self.imageView.center
// print("\(imageViewFrame)")
// print("\(self.view.frame)")
// scaleSize = CGSize(width: sizeWidth, height: sizeHeight)
// subRect = CGRectMake(0, self.view.center.y - self.imageView.bounds.height / 2, sizeWidth, sizeWidth)
useSubRect = CGRectMake(0, 50, sizeWidth, sizeWidth)
let subLayer = CALayer()
subLayer.frame = useSubRect
subLayer.borderColor = UIColor.blueColor().CGColor
subLayer.borderWidth = 3.0
subLayer.cornerRadius = 15.0
imageView.layer.addSublayer(subLayer)
guard let image = imageViewImage else {
print("imageViewImage is nil")
return
}
imageViewImage = image.scaleToSize(sizeWidth)
imageView.image = imageViewImage
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func selectFromLib(sender: UITapGestureRecognizer) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true , completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// let scaleImage = scaleFromImage(selectImage, scaleToSize: CGSize(width: self.view.frame.width , height: self.view.frame.height))
imageView.image = selectImage.scaleToSize(view.frame.width)
dismissViewControllerAnimated(true , completion: nil)
}
@IBAction func subImageAction(sender: UIButton) {
let imageViewImage = imageView.image
guard let image = imageViewImage else {
print("imageView image is nil")
return
}
let subImage = image.getSubImage(useSubRect)
subImageView.image = subImage
}
func scaleFromImage(image: UIImage, scaleToSize: CGSize) -> UIImage{
UIGraphicsBeginImageContext(scaleToSize)
image.drawInRect(CGRectMake(0, 0, scaleToSize.width, scaleToSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
extension UIImage{
func getSubImage(rect: CGRect) -> UIImage{
let subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect)
let smallBounds:CGRect = CGRectMake(CGFloat(0.0), CGFloat(0.0), CGFloat(CGImageGetWidth(subImageRef)), CGFloat(CGImageGetHeight(subImageRef)))
UIGraphicsBeginImageContext(smallBounds.size)
let context: CGContextRef = UIGraphicsGetCurrentContext()
CGContextDrawImage(context, smallBounds, subImageRef)
let smallImage:UIImage = UIImage(CGImage: subImageRef!)
UIGraphicsEndImageContext()
return smallImage
}
func scaleToSize(viewWidth: CGFloat) -> UIImage{
let sizeWidth = viewWidth
let sizeHeight = viewWidth / self.size.width * self.size.height
let size = CGSize(width: sizeWidth, height: sizeHeight)
print("size: \(size)")
UIGraphicsBeginImageContext(size)
self.drawInRect(CGRectMake(0, 0, size.width, size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
<file_sep>//
// KeyChainPersistentceViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/7.
// Copyright © 2015年 D_ttang. All rights reserved.
//
//简单来讲,一共就是四个函数
//
//SecItemCopyMatching - 查询和获取
//SecItemUpdate - 更新
//SecItemAdd - 添加
//SecItemDelete - 删除
import UIKit
class KeyChainPersistentceViewController: UIViewController {
@IBOutlet weak var usernameTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
usernameTextfield.delegate = self
passwordTextfield.delegate = self
}
@IBAction func add(sender: AnyObject) {
print("add")
let keyChainItem = self.createDefaultKeyChainItemDic()
if SecItemCopyMatching(keyChainItem,nil) == noErr{
self.alertWithMessage("User name already exits")
}else{
keyChainItem.setObject(self.passwordTextfield.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)!, forKey: kSecValueData as String)
let status = SecItemAdd(keyChainItem, nil)
self.alertWithStatus(status)
}
}
@IBAction func update(sender: AnyObject) {
print("update")
let keyChainItem = self.createDefaultKeyChainItemDic()
if SecItemCopyMatching(keyChainItem,nil) == noErr{
let updateDictionary = NSMutableDictionary()
updateDictionary.setObject(self.passwordTextfield.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)!, forKey:kSecValueData as String)
let status = SecItemUpdate(keyChainItem,updateDictionary)
self.alertWithStatus(status)
}else{
self.alertWithMessage("The keychain doesnot exist")
}
}
@IBAction func deleteKeyChain(sender: AnyObject) {
print("delete")
let keyChainItem = self.createDefaultKeyChainItemDic()
if SecItemCopyMatching(keyChainItem,nil) == noErr{
let status = SecItemDelete(keyChainItem)
self.alertWithStatus(status)
}else{
self.alertWithMessage("The keychain doesnot exist")
}
}
@IBAction func getKeyChain(sender: AnyObject) {
print("get")
let keyChainItem = self.createDefaultKeyChainItemDic()
keyChainItem.setObject(kCFBooleanTrue, forKey: kSecReturnData as String)
keyChainItem.setObject(kCFBooleanTrue, forKey: kSecReturnAttributes as String)
var queryResult: Unmanaged<AnyObject>?
_ = SecItemCopyMatching(keyChainItem,&queryResult)
let opaque = queryResult?.toOpaque()
// var contentsOfKeychain: NSString?
if let op = opaque {
let retrievedData = Unmanaged<NSDictionary>.fromOpaque(op).takeUnretainedValue()
let passwordData = retrievedData.objectForKey(kSecValueData) as! NSData
let passwordString = NSString(data: passwordData, encoding: NSUTF8StringEncoding)!
self.alertWithMessage("Password: \(password<PASSWORD>)")
}else{
self.alertWithMessage("The keychain doesnot exist")
}
}
//创建默认的描述字典
func createDefaultKeyChainItemDic()->NSMutableDictionary{
let keyChainItem = NSMutableDictionary()
keyChainItem.setObject(kSecClassInternetPassword as NSString, forKey: kSecClass as NSString)
keyChainItem.setObject("blog.csdn.net/hello_hwc", forKey: kSecAttrServer as NSString)
keyChainItem.setObject(self.usernameTextfield.text! as String, forKey: kSecAttrAccount as NSString)
return keyChainItem
}
//用UIAlertController提示信息
func alertWithMessage(message:String){
let alertController = UIAlertController(title:"Info", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title:"OK", style: UIAlertActionStyle.Cancel, handler:nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
func alertWithStatus(status:OSStatus){
if(status == 0){
self.alertWithMessage("Success")
}else{
self.alertWithMessage("Fail ErrorCode is\(status)")
}
}
}
extension KeyChainPersistentceViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
<file_sep>//
// ScaleTransition.swift
// swiftLearn
//
// Created by D_ttang on 15/7/1.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import Foundation
import UIKit
class ScaleTransition: NSObject, UIViewControllerAnimatedTransitioning {
var transitionContext: UIViewControllerContextTransitioning?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 1
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
}
}
<file_sep>//: Playground - noun: a place where people can play
import UIKit
import CoreFoundation
var str = "Hello, playground"
//
//func printFrom1To1000() {
// for counter in 0...1000 {
// var a = counter
// }
//}
//
//var timer = NSTimer.scheduledTimerWithTimeInterval(0,
// target: self,
// selector: Selector("printFrom1To1000"),
// userInfo: nil,
// repeats: false
//)
//timer.fire()
class myClass: NSTimer{
func printFrom1To1000() {
for counter in 0...1000 {
var b = counter
}
}
}
let myClassInstance = myClass()
var timer = NSTimer.scheduledTimerWithTimeInterval(10,
target: myClassInstance,
selector: Selector("printFrom1To1000"),
userInfo: nil,
repeats: false
)
timer.fire()
CFAbsoluteTimeGetCurrent()
CFTimeInterval()
var a: CGFloat = 2.0
var b: CGFloat = 3.2
a * b
<file_sep>//
// TranstionDelegate.swift
// swiftLearn
//
// Created by D_ttang on 15/7/1.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import Foundation
import UIKit
class TransitionDelegate: NSObject, UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return ExtendTransition()
}
// func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
// return ScaleTransition()
// return ExtendTransition()
// }
}<file_sep>//
// CFSocketViewController.swift
// swiftLearn
//
// Created by D_ttang on 15/7/4.
// Copyright © 2015年 D_ttang. All rights reserved.
//
import UIKit
import CoreFoundation
//import <CoreFoundation/CoreFoundation.h>
//include <sys/socket.h>
//include <netinet/in.h>
class CFSocketViewController: UIViewController {
var socket: CFSocketRef!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//
// var context: CFSocketContext = CFSocketContext()
// CFDataRef address = CFDataCreate(
// kCFAllocatorDefault,
// (UInt8*)&addr,
// sizeof(addr));
// socket = CFSocketCreate(kCFAllocatorDefault,
// PF_INET, SOCK_STREAM, IPPROTO_TCP, CFOptionFlags(CFSocketCallBackType.ReadCallBack), { (socket, CFSocketCallBackType(rawValue: <#T##CFOptionFlags#>), <#CFData!#>, <#UnsafePointer<Void>#>, <#UnsafeMutablePointer<Void>#>) -> Void in
// <#code#>
// }, context: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
84bfa25d616100f1262f3f888183c0e142b3fc80
|
[
"Swift",
"Markdown"
] | 17
|
Swift
|
Tonyce/swiftLearn
|
d1247227edf6651c4aaffb4263b897689d57ea7b
|
b5ef824a4eb29ad1c12ff542de122a2eb38e53c7
|
refs/heads/master
|
<file_sep>// app/controllers/application.js
import Ember from 'ember';
import {MAP_TYPES} from 'google-map/components/google-map';
var lat = 40.75047;
var lng = -73.98061;
export default Ember.Controller.extend({
lat: lat,
lng: lng,
zoom: 15,
type: 'road',
mapTypes: MAP_TYPES,
markers: [
{title: 'liftforward', lat: lat, lng: lng, description: 'New office'},
{title: 'tallan', lat: 40.74646, lng: -73.98427, description: 'Old office'},
],
});
|
32851b55b2b68bcdb9bce1989c698daa176822ab
|
[
"JavaScript"
] | 1
|
JavaScript
|
kriskhaira/maps-demo
|
291ba73811d692ad4038accff99cb946b046f7ad
|
8fbcc291a117e8a768256f4b1039646a0e93f8ab
|
refs/heads/master
|
<repo_name>kanthall/Arkamonsters<file_sep>/Assets/Scripts/Score.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
int startingScore = 0;
[SerializeField] int score;
[SerializeField] Text scoreField;
void Start()
{
score = 0;
UpdateScore();
}
public void AddToScore(int points)
{
score += points;
UpdateScore();
}
public void ReloadScore()
{
scoreField.text = startingScore.ToString();
}
void UpdateScore()
{
scoreField.text = "" + score;
}
}
<file_sep>/Assets/Scripts/SceneLoader.cs
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class SceneLoader : MonoBehaviour
{
LevelManager level;
int monsters;
Score score;
Ball ball;
NextLevelCanvas levelCanvas;
private void Start()
{
score = FindObjectOfType<Score>();
//coroutine = WaitBeforeGameOver(2);
ball = FindObjectOfType<Ball>();
levelCanvas = FindObjectOfType<NextLevelCanvas>();
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.G))
{
GameOver();
}
if (Input.GetKeyDown(KeyCode.N))
{
NextLevel();
}
if (monsters < 0)
{
NextLevel();
}
if(Input.GetKeyDown(KeyCode.R))
{
int currentScene = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentScene);
score.ReloadScore();
ball.ResetBallPosition();
}
}
public void NextLevel()
{
levelCanvas.ShowWarning();
StartCoroutine("WaitBeforeNextLevel");
ball.ResetBallPosition();
}
public void Credits()
{
SceneManager.LoadScene("5Scene_Credits");
}
public void QuitGame()
{
Application.Quit();
}
public void MainMenu()
{
SceneManager.LoadScene("1Scene_Menu");
}
public void GameOver()
{
score.ReloadScore();
StartCoroutine("WaitBeforeGameOver");
}
public void LoadFirstLevel()
{
SceneManager.LoadScene("2Scene_level0");
}
IEnumerator WaitBeforeGameOver()
{
yield return new WaitForSeconds(5);
Debug.Log("Loading next scene");
SceneManager.LoadScene("4Scene_GameOver");
}
IEnumerator WaitBeforeNextLevel()
{
yield return new WaitForSeconds(1);
Debug.Log("Loading next level");
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
<file_sep>/Assets/Scripts/MonsterSpawn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterSpawn : MonoBehaviour
{
[SerializeField] List<GameObject> monsters = new List<GameObject>();
void Start()
{
Spawn();
}
public void Spawn()
{
GameObject monster = monsters[Random.Range(0, monsters.Count)];
var newObject = Instantiate(monster, transform.position, Quaternion.identity);
newObject.transform.parent = gameObject.transform;
}
}
<file_sep>/Assets/Scripts/Texture.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Texture : MonoBehaviour
{
[SerializeField] List<Sprite> textures = new List<Sprite>();
SpriteRenderer spriteR;
void Start()
{
spriteR = GetComponent<SpriteRenderer>();
spriteR.sprite = GetRandomSprite();
//Debug.Log("Texture name " + spriteR.sprite.name);
}
Sprite GetRandomSprite()
{
int randomNum = Random.Range(0, textures.Count);
return textures[randomNum];
}
}
<file_sep>/Assets/Scripts/PlayerHealth.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
[SerializeField] List<GameObject> hearts = new List<GameObject>();
[SerializeField] int health;
[SerializeField] int maxHealth;
SceneLoader scene;
CameraShake camera;
Chromatic chromatic;
Vector2 temp;
int actualSize = 0;
[Header("Sound")]
[SerializeField] AudioClip playerHit;
[SerializeField] [Range(0, 1)] float playerHitVolume;
AudioSource audioSource;
[Header("Flash Square")]
[SerializeField] float flashTime;
[SerializeField] GameObject flashSquare;
private void Awake()
{
int paddle = FindObjectsOfType<PlayerHealth>().Length;
if (paddle > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
camera = FindObjectOfType<CameraShake>();
chromatic = FindObjectOfType<Chromatic>();
health = hearts.Count;
maxHealth = health;
scene = FindObjectOfType<SceneLoader>();
audioSource = GetComponent<AudioSource>();
}
public void DealDamage()
{
health -= 1;
camera.Shake();
chromatic.UseChromaticAbberation();
StartCoroutine(YellowFlash());
audioSource.PlayOneShot(playerHit, playerHitVolume);
if (hearts.Count > 0)
{
Destroy(hearts[0].gameObject);
hearts.RemoveAt(0);
}
if (health == 0)
{
Debug.Log("Game over");
scene.GameOver();
}
}
public void AddHealth()
{
if (health < maxHealth)
{
Debug.Log("I can add health");
}
else
{
Debug.Log("Health max");
}
}
public void SizeUp()
{
if (actualSize < 2)
{
temp = transform.localScale;
temp.x += 0.25f;
transform.localScale = temp;
actualSize++;
Debug.Log("SizeUP " + actualSize);
}
else
{
Debug.Log("Resize prevent");
return;
}
}
public void SizeDown()
{
if (actualSize > -1)
{
temp = transform.localScale;
temp.x -= 0.25f;
transform.localScale = temp;
actualSize--;
Debug.Log("SizeDOWN " + actualSize);
}
else
{
Debug.Log("Resize prevent");
return;
}
}
public void ResetPaddleSize()
{
actualSize = 0;
Debug.Log("Paddle Reset");
}
IEnumerator YellowFlash()
{
flashSquare.GetComponent<SpriteRenderer>().enabled = true;
yield return new WaitForSeconds(flashTime);
flashSquare.GetComponent<SpriteRenderer>().enabled = false;
}
}
<file_sep>/Assets/Scriptables/Levels/LevelDisplay.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelDisplay : MonoBehaviour
{
public Level level;
public Text levelNameField;
void Start()
{
levelNameField.text = level.levelName;
}
}
<file_sep>/Assets/PowerUps/PowerUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour
{
Rigidbody2D powerUpRigidbody2D;
[SerializeField] GameObject powerUpParticle;
[Header("Movement Params")]
[SerializeField] float yMin;
[SerializeField] float yMax;
[Space(10)]
[SerializeField] float speed = 1f;
protected void MoveDown()
{
powerUpRigidbody2D = GetComponent<Rigidbody2D>();
powerUpRigidbody2D.velocity = new Vector2(0f, Random.Range(yMin, yMax) * speed * Time.deltaTime);
}
public void DestroyPowerUp()
{
Destroy(gameObject, 30.0f);
}
public void CreateAndDestroyParticle()
{
GameObject particle = Instantiate(powerUpParticle, transform.position, Quaternion.identity);
Destroy(particle, 0.5f);
}
}<file_sep>/Assets/Scriptables/Values/Probability.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Values", menuName = "Scriptables/Values")]
public class Probability : ScriptableObject
{
public int minValue;
public int maxValue;
public GameObject objectToSpawn;
}
<file_sep>/Assets/Scripts/LoseCollider.cs
using UnityEngine.SceneManagement;
using UnityEngine;
public class LoseCollider : MonoBehaviour
{
PlayerHealth health;
SceneLoader scene;
Paddle paddle;
Ball ball;
private void Start()
{
health = FindObjectOfType<PlayerHealth>();
scene = FindObjectOfType<SceneLoader>();
paddle = FindObjectOfType<Paddle>();
ball = FindObjectOfType<Ball>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag.Equals("Ball"))
{
//health.DealDamage();
paddle.ResetPaddlePosition();
//health.ResetPaddleSize();
ball.ResetBallPosition();
}
}
}
<file_sep>/Assets/Scripts/Chromatic.cs
using System.Collections;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine;
public class Chromatic : MonoBehaviour
{
ChromaticAberration chromaticAberration = null;
[SerializeField] PostProcessVolume volume;
private void Awake()
{
int ball = FindObjectsOfType<Chromatic>().Length;
if (ball > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
volume.profile.TryGetSettings(out chromaticAberration);
if (chromaticAberration != null)
{
chromaticAberration.enabled.value = true;
}
}
public void UseChromaticAbberation()
{
StartCoroutine("ChromaticSplitSecond");
}
IEnumerator ChromaticSplitSecond()
{
chromaticAberration.intensity.value = 0.350f;
Time.timeScale = 0.5f;
yield return new WaitForSeconds(0.3f);
chromaticAberration.intensity.value = 0;
Time.timeScale = 1.0f;
}
}
<file_sep>/Assets/Scripts/Ball.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
[Header("Movement")]
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 15f;
[SerializeField] float randomFactor = 1f;
[SerializeField] float thrust = 10f;
[Space(10)]
[Header("Sound")]
[SerializeField] AudioClip ballHitSound;
[SerializeField] [Range(0, 1)] float ballHitSoundVolume;
[Space(10)]
[SerializeField] Paddle paddle;
[SerializeField] GameObject placeToShowParticle;
[Space(10)]
[SerializeField] GameObject paddleHitParticle;
Vector2 paddleToBallVector;
bool gameStarted = false;
Rigidbody2D ballRigidBody2D;
AudioSource audio;
CameraShake shake;
/*private void Awake()
{
transform.position = new Vector2(0f, 1.28f);
}*/
private void Awake()
{
int ball = FindObjectsOfType<Ball>().Length;
if (ball > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}
void Start()
{
ballRigidBody2D = GetComponent<Rigidbody2D>();
audio = GetComponent<AudioSource>();
paddleToBallVector = transform.position - paddle.transform.position;
shake = FindObjectOfType<CameraShake>();
}
void Update()
{
if (!gameStarted)
{
LaunchBall();
LockBallTopaddle();
}
}
void LaunchBall()
{
if (Input.GetMouseButtonDown(0))
{
gameStarted = true;
ballRigidBody2D.velocity = new Vector2(xPush, yPush);
}
}
void LockBallTopaddle()
{
Vector2 paddlePosition = new Vector2(paddle.transform.position.x, paddle.transform.position.y);
transform.position = paddlePosition + paddleToBallVector;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag.Equals("Projectile"))
{
Debug.Log("Projectile Hit");
}
else
{
if (collision.collider.tag.Equals("Monster"))
shake.Shake();
Vector2 velocityTweak = new Vector2(Random.Range(0.1f, randomFactor), Random.Range(0.1f, randomFactor));
if (gameStarted)
{
audio.PlayOneShot(ballHitSound, ballHitSoundVolume);
ballRigidBody2D.velocity += velocityTweak;
}
}
if (collision.collider.tag.Equals("Paddle"))
{
ballRigidBody2D.AddForce(transform.up * thrust);
//Debug.Log("Force Added");
var particle = Instantiate(paddleHitParticle, placeToShowParticle.transform.position, Quaternion.identity);
Destroy(particle, 0.5f);
}
}
public void ResetBallPosition()
{
Vector2 paddlePosition = new Vector2(paddle.transform.position.x, paddle.transform.position.y);
transform.position = paddlePosition + paddleToBallVector;
gameStarted = false;
}
}
<file_sep>/Assets/Scripts/EnemyHealth.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
[Header("Values")]
[SerializeField] int health;
[SerializeField] int scoreValue;
[SerializeField] bool killLock;
[SerializeField] int timesHit;
[Header("Objects")]
[SerializeField] GameObject deathParticle;
[SerializeField] GameObject hitParticle;
[SerializeField] Sprite[] hitSprites;
ProjectileSpawner spawner;
LevelManager level;
Score score;
Collider2D enemyCollider;
SpriteRenderer sprite;
[Header("Probability")]
[SerializeField] Probability probability;
void Start()
{
level = FindObjectOfType<LevelManager>();
spawner = GetComponent<ProjectileSpawner>();
sprite = GetComponent<SpriteRenderer>();
if (tag == "Monster")
{
level.MonstersCount();
}
score = FindObjectOfType<Score>();
enemyCollider = GetComponent<Collider2D>();
}
void DealDamage()
{
health = health - 1;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag.Equals("Ball"))
{
DealDamage();
if (health > 0)
{
GameObject hit = Instantiate(hitParticle, transform.position, Quaternion.identity);
Destroy(hit, 0.3f);
}
timesHit++;
int maxHits = hitSprites.Length + 1;
StartCoroutine("ChangeColor");
if (health <= 0)
{
spawner.SpawnOnDeath();
DestroyMonster();
SpawnPowerUp();
}
else
{
ShowNextHitSprite();
Debug.Log("Loading next sprite");
}
}
}
IEnumerator ChangeColor()
{
sprite.color = Color.red;
yield return new WaitForSeconds(0.3f);
sprite.color = Color.white;
}
private void ShowNextHitSprite()
{
int spriteIndex = timesHit - 1;
if (hitSprites[spriteIndex] != null)
{
GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
}
else
{
Debug.LogError("Block sprite is missing from array" + gameObject.name);
}
}
private void DestroyMonster()
{
GameObject particle = Instantiate(deathParticle, transform.position, Quaternion.identity);
Destroy(particle, 1f);
if (killLock == false)
{
enemyCollider.enabled = false;
killLock = true;
score.AddToScore(scoreValue);
Destroy(gameObject, 0.2f);
level.MonsterKilled();
}
}
private void SpawnPowerUp()
{
int chanceValue;
chanceValue = (UnityEngine.Random.Range(probability.minValue, probability.maxValue));
//Debug.Log(chanceValue);
if (chanceValue > 70)
{
Instantiate(probability.objectToSpawn, transform.position, Quaternion.identity);
}
}
}
<file_sep>/Assets/Scripts/ProjectileSpawner.cs
using UnityEngine;
public class ProjectileSpawner : MonoBehaviour
{
[SerializeField] Transform spawnerPosition;
[SerializeField] GameObject projectile;
[SerializeField] int spawnCount = 0;
[SerializeField] int spawn = 0;
public void SpawnOnDeath()
{
for (int i = 0; i < spawnCount; i++)
{
if (spawn <= spawnCount)
{
Instantiate(projectile, transform.position, Quaternion.identity);
spawn++;
}
}
}
}
<file_sep>/Assets/Scripts/Heart.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Heart : MonoBehaviour
{
LevelManager level;
void Start()
{
level = FindObjectOfType<LevelManager>();
if (tag == "Heart")
{
level.PlayerHealthCount();
}
}
}
<file_sep>/Assets/Scriptables/Levels/Level.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Level", menuName = "Scriptables/Level")]
public class Level : ScriptableObject
{
public string levelName;
}
<file_sep>/Assets/PowerUps/SizeUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SizeUp : PowerUp
{
PlayerHealth player;
private void Start()
{
player = FindObjectOfType<PlayerHealth>();
DestroyPowerUp();
MoveDown();
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag.Equals("Paddle"))
{
Destroy(gameObject);
player.SizeUp();
CreateAndDestroyParticle();
}
}
}
<file_sep>/Assets/Scripts/NextLevelCanvas.cs
using System.Collections;
using UnityEngine;
public class NextLevelCanvas : MonoBehaviour
{
[SerializeField] Canvas levelCanvas;
/*
private void Awake()
{
int ball = FindObjectsOfType<NextLevelCanvas>().Length;
if (ball > 1)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(gameObject);
}
}*/
private void Start()
{
levelCanvas.enabled = false;
}
public void ShowWarning()
{
StartCoroutine(WaveCanvasEnable());
}
private IEnumerator WaveCanvasEnable()
{
levelCanvas.enabled = true;
yield return new WaitForSeconds(1);
levelCanvas.enabled = false;
}
}<file_sep>/Assets/Scripts/EnemyProjectile.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyProjectile : MonoBehaviour
{
Rigidbody2D projectileRigidbody2D;
[SerializeField] GameObject playerHitParticle;
PlayerHealth player;
[Header("Movement Params")]
[SerializeField] float xMin;
[SerializeField] float xMax;
[Space(10)]
[SerializeField] float yMin;
[SerializeField] float yMax;
[Space(10)]
[SerializeField] float speed = 1f;
[SerializeField] float rotation;
void Start()
{
player = FindObjectOfType<PlayerHealth>();
projectileRigidbody2D = GetComponent<Rigidbody2D>();
projectileRigidbody2D.velocity = new Vector2(Random.Range(xMin, xMax), Random.Range(yMin, yMax) * speed * Time.deltaTime);
projectileRigidbody2D.rotation = 45f;
Destroy(gameObject, 15.0f);
}
private void FixedUpdate()
{
projectileRigidbody2D.rotation += rotation;
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag.Equals("Paddle"))
{
player.DealDamage();
CreateAndDestroyParticle();
}
}
void CreateAndDestroyParticle()
{
GameObject particle = Instantiate(playerHitParticle, transform.position, Quaternion.identity);
Destroy(particle, 0.5f);
Destroy(gameObject);
}
}
<file_sep>/Assets/Scripts/LevelManager.cs
using UnityEngine.SceneManagement;
using UnityEngine;
public class LevelManager : MonoBehaviour
{
[SerializeField] public int monsters;
int hearts;
SceneLoader scene;
Ball ball;
private void Start()
{
scene = FindObjectOfType<SceneLoader>();
ball = FindObjectOfType<Ball>();
}
public void MonstersCount()
{
monsters++;
}
public void MonsterKilled()
{
monsters--;
if (monsters <= 0)
{
scene.NextLevel();
ball.ResetBallPosition();
}
}
public void PlayerHealthCount()
{
hearts++;
}
public void LifeLost()
{
hearts--;
if (hearts <= 0)
{
scene.GameOver();
}
}
}
|
130e6513ab646eeb3368869522b444103e73dc42
|
[
"C#"
] | 19
|
C#
|
kanthall/Arkamonsters
|
276e2b8eee664d772ec249fc9c6ab6e330a5fc75
|
d1b5240ace4aeeed958399bc2103baa7c8a7b99b
|
refs/heads/master
|
<repo_name>jdiaspinheiro/ChatDSI<file_sep>/README.md
# ChatDSI
Webchat via sockets com backend em Java
Run Server.java
Access Webchat on port 8081
<file_sep>/Servidor.java
import java.net.*;
import java.io.*;
public class Servidor {
static int DEFAULT_PORT=8081;
public static void main(String[] args) {
int port=DEFAULT_PORT;
Presencas presences = new Presencas();
ServerSocket servidor = null;
try {
servidor = new ServerSocket(port);
} catch (Exception e) {
System.err.println("Erro ao criar o socket do servidor...");
e.printStackTrace();
System.exit(-1);
}
System.out.println("Servidor a espera de ligacoes na porta " + port);
while(true) {
try {
Socket ligacao = servidor.accept();
ServidorHandler server = new ServidorHandler(ligacao, presences);
server.start();
} catch (IOException e) {
System.out.println("Erro na execucao do servidor: "+e);
System.exit(1);
}
}
}
}
|
029ef3bc595ea0cdfadab2653477ef70c6652c05
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
jdiaspinheiro/ChatDSI
|
c4a7c528142e6c78baa6af3f445ec1bfe084498d
|
24a39d23f57f064ddb6c5dc73cf4defdfbca3730
|
refs/heads/master
|
<file_sep>package com.clinics.patient.exception;
import java.util.UUID;
public class VisitNotFoundException extends RuntimeException{
public VisitNotFoundException(UUID uuid) {
super(String.format("Visit with uuid '%s' not found", uuid));
}
}
<file_sep>import {Typography} from "@material-ui/core";
import {withStyles} from "@material-ui/styles";
export const StylesTabTypography = withStyles({
button: {
color: "white",
fontSize: "1.05rem",
height: "26px"
},
caption: {
color: "#e6e6e6",
fontSize: "0.7rem"
}
})(Typography)
export const StylesButtonTypography = withStyles({
button: {
color: "white",
fontSize: "0.9rem",
height: "26px"
},
caption: {
color: "#e6e6e6",
fontSize: "0.6rem"
}
})(Typography)
export const StylesTextFieldLabelTypography = withStyles({
h4: {
fontSize: "1rem"
},
h2: {
fontSize: "0.8rem"
}
})(Typography)<file_sep>import { createMuiTheme } from '@material-ui/core/styles';
const AppTheme = createMuiTheme({
palette: {
primary: {
main: '#4d1919'
}
},
status: {
danger: "red",
},
});
export default AppTheme<file_sep>package com.clinics.patient.service;
import com.clinics.common.DTO.request.outer.EditPatientDTO;
import com.clinics.common.DTO.request.outer.RegisterPatientDTO;
import com.clinics.common.DTO.response.outer.DoctorResponseDTO;
import com.clinics.common.DTO.response.outer.PatientRegisterResponseDTO;
import com.clinics.patient.client.PatientClient;
import com.clinics.patient.entity.Patient;
import com.clinics.patient.entity.Visit;
import com.clinics.patient.exception.PatientNotFoundException;
import com.clinics.patient.repository.PatientRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.*;
@Service
@Transactional
public class PatientServiceImpl implements PatientService{
final private PatientRepository patientRepository;
final private ModelMapper modelMapper;
final private RestTemplate restTemplate;
final private PatientClient patientClient;
@Autowired
public PatientServiceImpl(PatientRepository patientRepository, ModelMapper modelMapper, RestTemplate restTemplate, PatientClient patientClient) {
this.patientRepository = patientRepository;
this.modelMapper = modelMapper;
this.restTemplate = restTemplate;
this.patientClient = patientClient;
}
@Override
public PatientRegisterResponseDTO addPatient(RegisterPatientDTO registerPatientDTO, HttpServletRequest request) {
try{
patientClient.activatePatientInAuth(registerPatientDTO, request);
} catch (Exception e) {
throw new NoSuchElementException("There is no such user in AUTH or something else went wrong");
}
var patient = modelMapper.map(registerPatientDTO, Patient.class);
patientRepository.save(patient);
return modelMapper.map(patient, PatientRegisterResponseDTO.class);
}
@Override
public List<Patient> findAll() {
return patientRepository.findAll();
}
@Override
public Patient findByUuid(UUID patientUUID) {
Optional<Patient> patient = patientRepository.findByPatientUUID(patientUUID);
if(patient.isPresent()){
return patient.get();
}else{
throw new PatientNotFoundException(patientUUID);
}
}
@Override
public Optional<Patient> findById(Long ID) {
return patientRepository.findById(ID);
}
@Override
public void deleteByUuid(UUID patientUUID) {
//TODO catch exception
String uri = String.format("http://auth/auth/users/%s", patientUUID);
restTemplate.delete(uri);
patientRepository.deleteByPatientUUID(patientUUID);
}
@Override
public void editPatient(UUID patientUUID, EditPatientDTO editPatientDTO) {
Optional<Patient> existingPatient = patientRepository.findByPatientUUID(patientUUID);
existingPatient.ifPresentOrElse(
patient -> {
modelMapper.map(editPatientDTO, patient);
patientRepository.save(patient);
},
() -> {
throw new PatientNotFoundException(patientUUID);
}
);
}
@Override
public List<Visit> findAllVisits(UUID patientUUID) {
Optional<Patient> patient = patientRepository.findByPatientUUID(patientUUID);
if(patient.isPresent()) {
return patient.get().getVisits();
}else{
throw new PatientNotFoundException(patientUUID);
}
}
}
<file_sep>package com.clinics.common.exception.validators;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = RoleValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RoleConstraint {
String message() default "invalid role, allowed patient, doctor, assistant";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
<file_sep>package com.clinics.doctors.ui.service;
import com.clinics.common.DTO.response.outer.MedicalUnitResponseDTO;
import java.util.List;
import java.util.UUID;
public interface DoctorMedicalUnitClient {
List<MedicalUnitResponseDTO> getAll(UUID doctorUUID);
MedicalUnitResponseDTO get(UUID doctorUUID, UUID medicalUnitUUID);
MedicalUnitResponseDTO save(UUID medicalUnitUUID, UUID doctorUUID);
void delete(UUID doctorUUID, UUID medicalUnitUUID);
}
<file_sep>package com.clinics.patient.controller;
import com.clinics.common.DTO.request.outer.DiseaseDTO;
import com.clinics.patient.entity.Disease;
import com.clinics.patient.service.DiseaseService;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
@RestController
@JsonDeserialize(using = LocalDateDeserializer.class)
@RequestMapping(value = "patients/{patientUUID}/visits/{visitUUID}/disease")
public class DiseaseController {
final private DiseaseService diseaseService;
public DiseaseController(DiseaseService diseaseService) {
this.diseaseService = diseaseService;
}
@PostMapping
public ResponseEntity<Disease> addDisease(@PathVariable UUID visitUUID, HttpServletRequest request, @RequestBody DiseaseDTO diseaseDTO){
return ResponseEntity.status(HttpStatus.CREATED).body(diseaseService.addDisease(visitUUID, diseaseDTO));
}
@DeleteMapping(value = "/{diseaseUUID}")
public void removeDisease(@PathVariable UUID visitUUID, @PathVariable UUID diseaseUUID, HttpServletRequest request){
diseaseService.removeDisease(diseaseUUID);
}
}
<file_sep>import React from "react";
export const VisitRegistration = () => {
/*TODO: Pobieranie wszystkich doktorów i wybranie jednego z nich:
1. Stworzenie żądania do pobierania wszystkich doktorów
2. Utworzyć status dla wszystkich doktorów | (tutaj mamy już wszystkich doktorów i ich informacje)
3. Stworzenie wywołania żadania po pierwszym wywołaniu komponentu i zapisania wyniku w statusie
4. Stworzyć listę wszystkich doktorów do wyboru | (czyli select dla wielu) | {Imię + Nazwisko}
!!!SPRAWDZAMY KAŻDY KROK!!!
*/
return (<p>hello</p>)
};
export default VisitRegistration<file_sep>import {ContainerForUserInformation} from "../../../AdditionalComponents/ContainerForUserInformation/ContainerForUserInformation";
import React from "react";
export const PatientInfoComponent = (props) => {
return(
<ContainerForUserInformation
{...props}
userInformation={props.patientInformation}
primaryTitleRole={"Pacjent"}
secondaryTitleRole={"Patient"}
firstName={true}
lastName={true}
pesel={true}
/>
)
};
export default PatientInfoComponent<file_sep>import React from "react";
import Typography from "@material-ui/core/Typography";
import {Card, CardContent} from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
export const AppointmentCard = ({appointments}) => {
return (
<>
{appointments ? (appointments.map((appointment) =>
<Grid item xs={3} key={appointment.appointmentUUID}>
<Card>
<CardContent>
<Typography color="textSecondary" gutterBottom>
UUID: {appointment.appointmentUUID}
</Typography>
<Typography variant="h5" component="h2">
Patient First Name: {appointment.patientFirstName}
</Typography>
<Typography color="textSecondary">
Time:
</Typography>
<Typography variant="body2" component="p">
Info
</Typography>
</CardContent>
</Card>
</Grid>)) : <></>}
</>)
};
export default AppointmentCard<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class UserResponseDTO {
private String token; //todo token in body is less secure than in header ? maybe we should hide this field ?
private UUID userUUID;
private String email;
private String role;
}
<file_sep>package com.clinics.common.bean;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.Contact;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class BeanFactory implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
// public static <T> T getBean(Class<T> beanClass) {
// return context.getBean(beanClass);
// }
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public ObjectMapper getObjectMapper(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper
.enable(JsonParser.Feature.ALLOW_COMMENTS)
.setDateFormat(dateFormat)
.registerModules(
new ParameterNamesModule(),
new Jdk8Module(),
new JavaTimeModule());
return objectMapper;
}
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(){
return new Jackson2ObjectMapperBuilder() {
@Override
public void configure(ObjectMapper objectMapper) {
super.configure(objectMapper);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
objectMapper.setDateFormat(dateFormat);
}
};
}
@Bean
public ModelMapper getModelMapper(){
var modelMapper = new ModelMapper();
modelMapper
.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT)
.setFieldMatchingEnabled(true)
.setSkipNullEnabled(true);
// .setFieldMatchingEnabled(true)
// .setCollectionsMergeEnabled(true)
// .setDeepCopyEnabled(false);
return modelMapper;
}
@Bean
public ApiInfoBuilder apiInfoBuilder(){
return new ApiInfoBuilder()
.title("E-Clinics REST API")
.contact(new Contact("Clinic team", "www.janusze.microserices", "<EMAIL>"))
.license("Free")
.licenseUrl("free.com");
}
//todo
// @Bean
// @LoadBalanced
// public RestTemplate getRestTemplate(){
// return new RestTemplate(getClientHttpRequestFactory());
// }
//
// private HttpComponentsClientHttpRequestFactory getClientHttpRequestFactory(){
// HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
// = new HttpComponentsClientHttpRequestFactory();
// httpComponentsClientHttpRequestFactory.setConnectTimeout(2000);
// httpComponentsClientHttpRequestFactory.setReadTimeout(2000);
// return httpComponentsClientHttpRequestFactory;
// }
}
<file_sep>import {useHistory} from "react-router";
import {useEffect, useReducer} from "react";
import {URLs} from "../../../URLs";
import {logOut} from "../../../redux/actions";
export const ContainerPatientPage = ({userDetails, userInformation, setStoreUserInformation, children}) => {
//History
const history = useHistory();
//Reducer
const setPatientPageState = (state, action) => {
switch (action.type) {
case "SETTING_INFORMATION_SUCCESS":
return {
...state,
patientInformation: action.patientInformation
};
case "SETTING_INFORMATION_FAILED":
return state;
case "DELETE_ACCOUNT_SUCCESS":
return state;
case "DELETE_ACCOUNT_FAILED":
return state;
case "CHANGE_COMPONENT":
return {
...state,
componentToShow: action.componentToShow
};
case "USER_INFORMATION_HAS_BEEN_EDIT_SUCCESS":
return {
...state,
userInformationHasBeenEdit: !state.userInformationHasBeenEdit
};
case "USER_INFORMATION_HAS_BEEN_EDIT_FAILED":
return state;
default:
return state;
}
};
const init = (initialState) => initialState;
const initialState = {
patientInformation: {
patientUUID: null,
pesel: null,
firstName: null,
lastName: null,
photoUrl: null,
visits: []
},
appointments: [],
userInformationHasBeenEdit: false,
componentToShow: 0,
};
const[patientPageState, dispatchPatientPageState] = useReducer(setPatientPageState, initialState, init);
//Fetch
const fetchForDeleteAccount = async () => {
try{
const init = {
method: 'DELETE',
body: null,
headers: {
'Authorization': localStorage.token,
'Content-Type': 'application/json',
}
};
await fetch(URLs.DELETE_PATIENT(userDetails.uuid), init)
.catch(() => dispatchPatientPageState({type: "DELETE_ACCOUNT_FAILED"}));
dispatchPatientPageState({type: "DELETE_ACCOUNT_SUCCESS"});
logOut(history);
} catch (e) {
dispatchPatientPageState({type: "DELETE_ACCOUNT_FAILED"})
}
};
const fetchForChangeUserInformation = async (newUserInformation) => {
try{
const body = JSON.stringify({
"firstName" :newUserInformation.firstName,
"lastName" :newUserInformation.lastName,
"pesel" :newUserInformation.pesel,
"photoUrl" :newUserInformation.photoUrl
});
const init = {
method: 'PATCH',
body: body,
headers: {
'Authorization': localStorage.token,
'Content-Type': 'application/json',
}
};
await fetch(URLs.CHANGE_PATIENT_INFORMATION(userDetails.uuid), init)
.catch(() => dispatchPatientPageState({type: "USER_INFORMATION_HAS_BEEN_EDIT_FAILED"}));
dispatchPatientPageState({type: "USER_INFORMATION_HAS_BEEN_EDIT_SUCCESS"})
} catch (e) {
dispatchPatientPageState({type: "USER_INFORMATION_HAS_BEEN_EDIT_FAILED"})
}
};
const onClickChangeTabPanel = (event, newValue) => {
dispatchPatientPageState({type: "CHANGE_COMPONENT", componentToShow: newValue})
};
useEffect(() => {
const fetchForPatientInformation = async () => {
try {
const init = {
method: 'GET',
body: null,
headers: {'Authorization': localStorage.token}
};
const response = await fetch(URLs.GET_PATIENT_INFORMATION(userDetails.uuid), init);
const result = await response.json();
setStoreUserInformation(result);
dispatchPatientPageState({type: "SETTING_INFORMATION_SUCCESS", patientInformation:result})
}catch (e) {
dispatchPatientPageState({type: "SETTING_INFORMATION_FAILED"})
}
};
fetchForPatientInformation();
}, [patientPageState.userInformationHasBeenEdit, setStoreUserInformation, userDetails.uuid]);
return(children({
patientPageState,
userInformation,
onClickChangeTabPanel,
fetchForChangeUserInformation,
fetchForDeleteAccount,
}))
};<file_sep>package com.clinics.patient;
import com.clinics.patient.client.PatientClient;
import com.clinics.patient.entity.Visit;
import com.clinics.patient.exception.VisitNotFoundException;
import com.clinics.patient.repository.PatientRepository;
import com.clinics.patient.repository.VisitRepository;
import com.clinics.patient.service.VisitServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class VisitServiceTest {
@Mock private PatientRepository patientRepository;
@Mock private ModelMapper modelMapper;
@Mock private PatientClient patientClient;
@Mock private Visit visit;
@Mock private VisitRepository visitRepository;
private UUID visitUUID = UUID.randomUUID();
@InjectMocks VisitServiceImpl subject;
@Test
void shouldReturnVisitFindByUUID () {
when(visitRepository.findByVisitUUID(visitUUID)).thenReturn(Optional.of(visit));
Visit result = subject.findByUuid(visitUUID);
verify(visitRepository, times(1)).findByVisitUUID(visitUUID);
Assertions.assertEquals(visit, result);
}
@Test
void findByUuidShouldThrowVisitNotFoundException () {
Assertions.assertThrows(VisitNotFoundException.class, () -> {
subject.findByUuid(visitUUID);
});
}
}
<file_sep>
export const URLs = {
REGISTER_USER: "http://localhost:8762/auth/users/",
REGISTER_PATIENT: "http://localhost:8762/patient-mssc/patients",
REGISTER_DOCTOR: "http://localhost:8762/doctor-mssc/doctors/",
GET_ALL_DOCTORS: "http://localhost:8762/doctor-mssc/doctors",
GET_DETAILS_BY_TOKEN: "http://localhost:8762/auth/users/uuidAndRole/",
LOGIN_USER: "http://localhost:8762/auth/login",
CHANGE_PATIENT_INFORMATION: (patientUUID) => (`http://localhost:8762/patient-mssc/patients/${patientUUID}`),
DELETE_PATIENT: (patientUUID) => (`http://localhost:8762/patient-mssc/patients/${patientUUID}`),
GET_PATIENT_INFORMATION: (patientUUID) => (`http://localhost:8762/patient-mssc/patients/${patientUUID}`) ,
CHANGE_DOCTOR_INFORMATION: (doctorUUID) => (`http://localhost:8762/doctor-mssc/doctors/${doctorUUID}`) ,
DELETE_DOCTOR: (doctorUUID) => (`http://localhost:8762/doctor-mssc/doctors/${doctorUUID}`),
GET_DOCTOR_INFORMATION: (doctorUUID) => (`http://localhost:8762/doctor-mssc/doctors/${doctorUUID}`),
GET_ALL_DOCTOR_CALENDARS: (doctorUUID) => (`http://localhost:8762/doctor-mssc/doctors/${doctorUUID}/calendars`),
GET_ALL_APPOINTMENTS_IN_GIVEN_CALENDAR : (doctorUUID, calendarUUID) => (`http://localhost:8762/doctor-mssc/doctors/${doctorUUID}/calendars/${calendarUUID}/appointments`),
GET_ALL_PATIENT_APPOINTMENTS: (patientUUID) => (`http://localhost:8762/patient-mssc/patients/${patientUUID}/visits`),
};<file_sep>import React, {useEffect, useState} from "react";
import {
sendFetchRequestForGetAllAppointmentsForGivenCalendar,
sendFetchRequestForGetAllCalendars
} from "./ContainersForDoctorPageComponents/ContainerForVisitComponent";
import {Card, CardContent, Grid} from "@material-ui/core";
import Typography from "@material-ui/core/Typography";
import AppointmentCard from "./AppointmentCardForVisitsComponent";
export const VisitsComponent = (props) => {
return(
<div>
<p>Hello</p>
</div>
)
};
export default VisitsComponent<file_sep>package com.clinics.patient.configuration;
import com.clinics.common.bean.BeanFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Configuration
@Service
public class PatientConfig extends BeanFactory implements ApplicationContextAware {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate(getClientHttpRequestFactory());
}
private HttpComponentsClientHttpRequestFactory getClientHttpRequestFactory(){
HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
httpComponentsClientHttpRequestFactory.setConnectTimeout(2000);
httpComponentsClientHttpRequestFactory.setReadTimeout(2000);
return httpComponentsClientHttpRequestFactory;
}
//This to serialize LocalDateTime to format like 2019-02-08T13:30:00
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
<file_sep>import React from "react";
import {MenuItem} from "@material-ui/core";
import StylesTextField from "../CustomTextField/StylesTextField";
import TextFieldCustomTypography from "../CustomTypography/TypesOfCustomTypography/TextFieldLabelCustomTypography";
export const RoleForm = (props) => {
const {handleChange, role} = props;
return (
<StylesTextField
fullWidth
variant="outlined"
label={
<TextFieldCustomTypography
primaryLabel={"<NAME>"}
secondaryLabel={"Register As"}
/>
}
select
value={role}
onChange={(event) => {
handleChange(event.target.value)
}}
>
<MenuItem value="doctor">
<TextFieldCustomTypography
primaryLabel={"Doktor"}
secondaryLabel={"Doctor"}
/>
</MenuItem>
<MenuItem value="patient">
<TextFieldCustomTypography
primaryLabel={"Pacjent"}
secondaryLabel={"Patient"}
/>
</MenuItem>
<MenuItem value="assistant">
<TextFieldCustomTypography
primaryLabel={"Asystentka"}
secondaryLabel={"Assistant"}
/>
</MenuItem>
</StylesTextField>
)
};<file_sep>package com.clinics.doctors.ui.service;
import com.clinics.common.DTO.request.outer.doctor.SpecializationDTO;
import com.clinics.common.DTO.response.outer.SpecializationResponseDTO;
import java.util.List;
import java.util.UUID;
public interface SpecializationService {
List<SpecializationResponseDTO> getAllSpecializations();
List<SpecializationResponseDTO> getDoctorSpecializations(UUID doctorUUID);
SpecializationResponseDTO getDoctorSpecialization(UUID doctorUUID, UUID specializationUUID);
SpecializationResponseDTO getSpecializationByUUID(UUID specializationUUID);
SpecializationResponseDTO saveSpecialization(SpecializationDTO specializationDTO);
SpecializationResponseDTO saveSpecializationIntoDoctor(UUID doctorUUID, SpecializationDTO specializationDTO);
SpecializationResponseDTO saveExistingSpecializationIntoDoctor(UUID doctorUUID, UUID specializationUUID);
void editSpecialization(SpecializationDTO specializationDTO, UUID specializationUUID);
void removeSpecializationFromDoctor(UUID doctorUUID, UUID specializationUUID);
void deleteSpecialization(UUID specializationUUID);
}
<file_sep>package com.clinics.common.DTO.request.outer;
import com.clinics.common.patient.VisitStatus;
import lombok.Data;
import lombok.ToString;
import javax.validation.constraints.Size;
@Data
@ToString
public class EditVisitDTO {
@Size(max = 1000, message = "Description length out of range")
private String description;
private VisitStatus status;
}
<file_sep>package com.clinics.doctors.data.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Collection;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder
@ToString
@DynamicInsert
@DynamicUpdate
@Entity
public class Specialization {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(
updatable = false,
nullable = false,
unique = true)
private UUID specializationUUID;
@Column(unique = true)
@NotBlank(message = "name is mandatory")
@Size(min = 2, max = 100, message = "name length out of range")
private String name;
@JsonBackReference
@ManyToMany(targetEntity = Doctor.class)
@JoinTable(
name = "doctor_specialization",
joinColumns = {@JoinColumn(name = "spacialization_id")},
inverseJoinColumns = {@JoinColumn(name = "doctor_id")})
Collection<Doctor> doctors;
//todo move creation doctors into method
}
<file_sep>import {connect} from "react-redux";
import {setStoreDoctorInformation, setStoreError} from "../../../redux/actions";
import ContainerDoctorPage from "./ContainerDoctorPage";
const getUserDetails = state => ( state.info.userDetails );
const getUserInformation = state => ( state.info.userInformation );
const getError = state => ( state.error );
const mapStateToProps = state => ({
error: getError(state),
userDetails: getUserDetails(state),
userInformation: getUserInformation(state)
});
const mapDispatchToProps = dispatch => ({
setStoreUserInformation: (userInformation) => {dispatch(setStoreDoctorInformation(userInformation))},
setStoreError: (error) => {dispatch(setStoreError(error))}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(ContainerDoctorPage)<file_sep>import {connect} from "react-redux";
import {setStoreError, setStorePatientInformation} from "../../../redux/actions";
import {ContainerPatientPage} from "./ContainerPatientPage";
const getUserDetails = state => ( state.info.userDetails );
const getUserInformation = state => ( state.info.userInformation );
const getError = state => ( state.error );
const mapStateToProps = state => ({
error: getError(state),
userDetails: getUserDetails(state),
userInformation: getUserInformation(state)
});
const mapDispatchToProps = dispatch => ({
setStoreUserInformation: (userInformation) => {dispatch(setStorePatientInformation(userInformation))},
setStoreError: (error) => {dispatch(setStoreError(error))}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(ContainerPatientPage)
<file_sep>package com.clinics.zuul;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
//https://dzone.com/articles/quick-guide-to-microservices-with-spring-boot-20-e
//@EnableSwagger2 //todo <--- show all endpoints
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
<file_sep>package com.clinics.patient;
import com.clinics.common.DTO.request.outer.DiseaseDTO;
import com.clinics.patient.entity.Disease;
import com.clinics.patient.entity.Visit;
import com.clinics.patient.exception.DiseaseNotFoundException;
import com.clinics.patient.exception.VisitNotFoundException;
import com.clinics.patient.repository.DiseaseRepository;
import com.clinics.patient.repository.VisitRepository;
import com.clinics.patient.service.DiseaseServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class DiseaseServiceTest {
@Mock private ModelMapper modelMapper;
@Mock private Disease disease;
@Mock private DiseaseDTO diseaseDTO;
@Mock private Visit visit;
@Mock private VisitRepository visitRepository;
@Mock private DiseaseRepository diseaseRepository;
private UUID visitUUID = UUID.randomUUID();
private UUID diseaseUUID = UUID.randomUUID();
@InjectMocks DiseaseServiceImpl subject;
@Test
void shouldReturnVisit(){
when(visitRepository.findByVisitUUID(visitUUID)).thenReturn(Optional.of(visit));
when(modelMapper.map(diseaseDTO, Disease.class)).thenReturn(disease);
subject.addDisease(visitUUID, diseaseDTO);
verify(diseaseRepository, times(1)).save(disease);
}
@Test
void shouldThrowVisitNotFoundException(){
Assertions.assertThrows(VisitNotFoundException.class, () -> {
subject.addDisease(visitUUID, diseaseDTO);
});
}
@Test
void shouldRemoveDisease(){
when(diseaseRepository.findByDiseaseUUID(diseaseUUID)).thenReturn(Optional.of(disease));
subject.removeDisease(diseaseUUID);
verify(diseaseRepository, times(1)).deleteDiseaseByDiseaseUUID(diseaseUUID);
}
@Test
void shouldThrowDiseaseNotFoundExceptionRemoveDisease(){
Assertions.assertThrows(DiseaseNotFoundException.class, () -> {
subject.removeDisease(diseaseUUID);
});
}
}
<file_sep>package com.clinics.doctors.data.repositorie;
import com.clinics.doctors.data.model.Calendar;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface CalendarRepository extends JpaRepository<Calendar, Long> {
// List<Calendar> getAllByDoctor_Doctoruuid(UUID uuid);
// Optional<Calendar> getCalendarByCalendaruuid(UUID uuid);
// void deleteByCalendaruuid(UUID uuid);
List<Calendar> getCalendarsByDoctor_DoctorUUID(UUID doctorUUID);
Optional<Calendar> getCalendarByCalendarUUID(UUID calendarUUID);
void deleteByCalendarUUID(UUID uuid);
}
<file_sep>import React from "react";
import {Button} from "@material-ui/core";
import {EmailForm} from "./ElementsForFormForInputUserInformation/EmailForm";
import {PasswordForm} from "./ElementsForFormForInputUserInformation/PasswordForm";
import {FirstNameForm} from "./ElementsForFormForInputUserInformation/FirstNameForm";
import {LastNameForm} from "./ElementsForFormForInputUserInformation/LastNameForm";
import {LicenceForm} from "./ElementsForFormForInputUserInformation/LicenceForm";
import {PhotoURLForm} from "./ElementsForFormForInputUserInformation/PhotoURLForm";
import {Form} from "react-bootstrap";
import {PeselForm} from "./ElementsForFormForInputUserInformation/PeselForm";
import ButtonCustomTypography from "../CustomTypography/TypesOfCustomTypography/ButtonCustomTypography";
export const FormForInputUserInformation = (props) => {
const {
onSubmit,
showEmailForm,
showPasswordForm,
showFirstNameForm,
showLastNameForm,
showLicenceForm,
showPhotoURLForm,
showPeselForm,
submitButtonAvailable,
validation,
handleChange,
setIsCorrectInputInForms,
userInformation,
primaryLabel,
secondaryLabel
} = props;
return (
<Form
onSubmit={e => onSubmit(e)}
>
<Form.Row>
{showEmailForm ? ( <EmailForm handleChange={handleChange} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
{showPasswordForm ? ( <PasswordForm handleChange={handleChange} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
</Form.Row>
<Form.Row>
{showFirstNameForm ? ( <FirstNameForm handleChange={handleChange} userInformation={userInformation} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
{showLastNameForm ? ( <LastNameForm handleChange={handleChange} userInformation={userInformation} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
</Form.Row>
<Form.Row>
{showLicenceForm ? ( <LicenceForm handleChange={handleChange} userInformation={userInformation} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
{showPhotoURLForm ? ( <PhotoURLForm handleChange={handleChange} userInformation={userInformation} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
</Form.Row>
<Form.Row>
{showPeselForm ? ( <PeselForm handleChange={handleChange} userInformation={userInformation} validation={validation} setIsCorrectInputInForms={setIsCorrectInputInForms}/> ) : null}
</Form.Row>
<Button
variant="contained"
color="primary"
type="submit"
disabled={!submitButtonAvailable && validation}
disableElevation
>
<ButtonCustomTypography
primaryLabel={primaryLabel}
secondaryLabel={secondaryLabel}
/>
</Button>
</Form>
);
};<file_sep>package com.clinics.patient.exception;
import java.util.UUID;
public class PatientNotFoundException extends RuntimeException{
public PatientNotFoundException(UUID uuid) {
super(String.format("Patient with uuid '%s' not found", uuid));
}
}
<file_sep>package com.clinics.auth.data.model;
import com.clinics.common.security.Role;
import com.fasterxml.jackson.annotation.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@ToString
@Builder(toBuilder = true)
@DynamicInsert
@DynamicUpdate
@EqualsAndHashCode
@Entity(name = "auth_user")
public class User implements Role, Serializable, UserDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@Column(updatable = false, nullable = false)
private UUID userUUID;
@Column(unique = true)
@NotBlank(message = "email is mandatory")
@Size(min = 3, max = 200, message = "email length out of range")
@Email(message = "email invalid")
private String email;
@NotBlank(message = "password is mandatory")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Size(min = 8, max = 100, message = "password length out of range")
private String password;
@Column(nullable = false)
private String role;
@Column(name = "created", updatable = false, nullable = false)
@CreationTimestamp
private LocalDateTime creationDateStamp;
@Column(name = "updated", nullable = false)
@UpdateTimestamp
private LocalDateTime updateDateStamp;
@Builder.Default
private boolean isEnabled = false;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + this.role);
authorities.add(authority);
return authorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return this.isEnabled;
}
}
<file_sep># Microservices-Clinic
Implementation of medical unit administration system based on Spring Framework. The system is set up as distributed microservices architecture with use of Spring Boot tools. Main functionality of that system is registration of users(patients, doctors), managing doctors calendars and registering patients for visits.
## Table of contents
* [Architecture ](#architecture)
* [Tech_Stack](#tech_stack)
* [Screenshots](#screenshots)
* [TODO](#TODO)
* [Contact](#contact)
# Architecture

### Eureka Registry
This is typical implementation of Netflix Eureka registry. In simple words, in my opinion, this is a simple version of DNS for a microservice :)
### Zuul
Service gateway is responsible for authorization. This service has 2 majors tasks, first if JWT doesn't exist and a request is directed to auth for new JWT or registration then pass this request further. Second
if JWT exists, unpack and check if it is correct and decide if the request is allowed to reach a specific endpoint.
### Authentication
Service responsible for authentication.
This service has two tasks. One is to register new users and keep then in DB. The second is to check if the user exists if the password is correct and return JWT.
### Patient Doctor Clinic
These three services are the core of the whole system. Our main goal is to be able to record the patient's visit to the doctor and a whole bunch of features related to doing this right.
### Rabbit MQ, Search, Config, Statistic
These four services aren't implemented yet. Right now we have to decide how to make communication between services less pained.
* Rabbit MQ we have tested in other projects but ... we're wondering if Kaffka in this project not will be a better choice?
* Search after we decide Rabbit or Kaffka then we will be able to learn ElasticSearch and then implement into our system if it's will be fitted.
* Config will be a simple typical config service, with the possibility to change the config on the fly.
* Statistic we would like to make in .NET core MVC and check how these main two different technology play together.
All that is right now stopped by tests. We have to do some unit and integrated tests.
### Security

### Example communication between mssc

# Tech_Stack
* Java 13
* Spring Boot 2
* Netflix Eureka
* DB Postgres
* JPA / Hibernate
* Swagger 2
* ReactJS
# Screenshots







## TODO in progress
#### Back-End:
* doctor's unitests tests and integration tests <--- move here tests from postman
* search (kafka || rabit && elasticSearch)
* statistic mssc in .NET MVC
* config mssc
* rewrite to use faign, hateos
#### Front-End:
* create documentation about each component and container
* add new animations when logging in or registration
* add unit and integration tests
Project is in progress.
## Contact
Created by:
* [<NAME>](mailto:<EMAIL>) - feel free to contact me!
* [<NAME>](mailto:<EMAIL>) our frontend master
* <NAME>
<file_sep>import {DelAccountBtn} from "../../../AdditionalComponents/DelAccountBtn/DelAccountBtn";
import React from "react";
export const DeleteAccountComponent = (props) => {
return(
<DelAccountBtn
{...props}
/>
)
};
export default DeleteAccountComponent<file_sep>spring.application.name=patient-mssc
server.port=8082
eureka.client.service-url.default-zone=http://localhost:8761/eureka/
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/clinics_patient
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.serialization.write-dates-as-timestamps=false<file_sep>package com.clinics.doctors.ui.controller;
import com.clinics.common.DTO.request.outer.doctor.SpecializationDTO;
import com.clinics.common.DTO.response.outer.SpecializationResponseDTO;
import com.clinics.doctors.ui.service.JPAimpl.SpecializationServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping(value = "/specializations")
public class SpecializationController {
final private SpecializationServiceImpl specializationServiceImpl;
public SpecializationController(SpecializationServiceImpl specializationServiceImpl) {
this.specializationServiceImpl = specializationServiceImpl;
}
@GetMapping
public ResponseEntity<List<SpecializationResponseDTO>> getAll(){
return ResponseEntity.ok().body(specializationServiceImpl.getAllSpecializations());
}
@GetMapping(value = "/{specializationUUID}")
public ResponseEntity<SpecializationResponseDTO> getByUUID(
@PathVariable UUID specializationUUID){
return ResponseEntity.ok().body(specializationServiceImpl.getSpecializationByUUID(specializationUUID));
}
@PostMapping
public ResponseEntity<SpecializationResponseDTO> add (
@Valid @RequestBody SpecializationDTO specializationDTO){
return ResponseEntity.status(HttpStatus.CREATED).body(specializationServiceImpl.saveSpecialization(specializationDTO));
}
@PatchMapping(value = "/{specializationUUID}")
public ResponseEntity<Void> edit(
@Valid @RequestBody SpecializationDTO specializationDTO,
@PathVariable UUID specializationUUID) {
specializationServiceImpl.editSpecialization(specializationDTO, specializationUUID);
return ResponseEntity.ok().build();
}
@DeleteMapping(value = "/{specializationUUID}")
public ResponseEntity<Void> del(
@PathVariable UUID specializationUUID) {
specializationServiceImpl.deleteSpecialization(specializationUUID);
return ResponseEntity.ok().build();
}
}
<file_sep>package com.clinics.auth.data.bootstrap;
import com.clinics.auth.data.model.User;
import com.clinics.auth.data.repository.UserRepository;
import com.clinics.common.security.Role;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Component
public class BootStrapUser implements CommandLineRunner, Role {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public BootStrapUser(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String... args) throws Exception {
init();
}
public void init(){
User userPatient1 = User
.builder()
.userUUID(UUID.randomUUID())
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.PATIENT)
.build();
User userPatient2 = User
.builder()
.userUUID(UUID.randomUUID())
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.PATIENT)
.build();
User userPatient3 = User
.builder()
.userUUID(UUID.fromString("11f0f891-b243-4547-803b-605f72b11b11"))
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.PATIENT)
.isEnabled(true)
.build();
User userDoctor1 = User
.builder()
.userUUID(UUID.fromString("03f0f891-b243-4547-803b-605f72b11be9"))
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.DOCTOR)
.isEnabled(true)
.build();
User userDoctor2 = User
.builder()
.userUUID(UUID.fromString("fbb44683-a210-4a93-8a17-c84f16954d8d"))
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.DOCTOR)
.isEnabled(true)
.build();
User userAssistant1 = User
.builder()
.userUUID(UUID.randomUUID())
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.ASSISTANT)
.build();
User userAssistant2 = User
.builder()
.userUUID(UUID.randomUUID())
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.ASSISTANT)
.build();
User creepy = User
.builder()
.userUUID(UUID.randomUUID())
.email("<EMAIL>")
.password(passwordEncoder.encode("<PASSWORD>"))
.role(Role.SYSTEM_ADMIN)
.isEnabled(true)
.build();
List<User> userList = Arrays.asList(
userPatient1,
userPatient2,
userPatient3,
userDoctor1,
userDoctor2,
userAssistant1,
userAssistant2,
creepy);
userRepository.saveAll(userList);
}
}
<file_sep>package com.clinics.common.patient;
public enum VisitStatus {
NEW, FINISHED
}
<file_sep>package com.clinics.doctors.ui.service.JPAimpl;
import com.clinics.common.DTO.request.outer.doctor.AppointmentDTO;
import com.clinics.common.DTO.response.outer.AppointmentResponseDTO;
import com.clinics.common.exception.validators.AppointmentAlreadyBookedException;
import com.clinics.doctors.data.model.Appointment;
import com.clinics.doctors.data.repositorie.RepositoryAppointment;
import com.clinics.doctors.ui.service.AppointmentService;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.stream.Collectors;
@Transactional
@Service
public class AppointmentServiceImpl implements AppointmentService {
final private RepositoryAppointment appointmentRepository;
final private CalendarServiceImpl calendarServiceImpl;
final private ModelMapper modelMapper;
public AppointmentServiceImpl(
RepositoryAppointment appointmentRepository,
CalendarServiceImpl calendarServiceImpl,
ModelMapper modelMapper) {
this.appointmentRepository = appointmentRepository;
this.calendarServiceImpl = calendarServiceImpl;
this.modelMapper = modelMapper;
}
public List<AppointmentResponseDTO> getAllDoctorAppointments(UUID doctorUUID, UUID calendarUUID) {
var calendar = calendarServiceImpl.getDoctorCalendar(doctorUUID, calendarUUID);
return calendar
.getAppointments()
.stream()
.map(appointment -> modelMapper.map(appointment, AppointmentResponseDTO.class))
.collect(Collectors.toList());
}
public AppointmentResponseDTO getDoctorAppointment(UUID doctorUUID, UUID calendarUUID, UUID appointmentUUID) {
var optionalAppointmentResponseDTO = getAllDoctorAppointments(doctorUUID, calendarUUID)
.stream()
.filter(appointmentResponseDTO -> appointmentResponseDTO.getAppointmentUUID().equals(appointmentUUID))
.findFirst();
if (optionalAppointmentResponseDTO.isEmpty()) {
throw new NoSuchElementException(String.format("Calendar doesn't have such appointment %s", appointmentUUID ));
}
return optionalAppointmentResponseDTO.get();
}
public AppointmentResponseDTO saveAppointment(UUID doctorUUID, UUID calendarUUID, AppointmentDTO appointmentDTO) {
var calendar = calendarServiceImpl.getDoctorCalendar(doctorUUID, calendarUUID);
//todo some meat left
if (calendar
.getAppointments()
.stream()
.anyMatch(appointment -> appointment.getLocalDateTime()
.equals(appointmentDTO.getLocalDateTime()))) {
throw new NoSuchElementException("Calendar already have appointment on this time");
}
var appointment = modelMapper.map(appointmentDTO, Appointment.class);
appointment.setAppointmentUUID(UUID.randomUUID());
appointment.setCalendar(calendar);
appointment = appointmentRepository.save(appointment);
return modelMapper.map(appointment, AppointmentResponseDTO.class);
}
public List<AppointmentResponseDTO> saveAppointments(UUID doctorUUID, UUID calendarUUID, List<AppointmentDTO> listDddEditAppointmentDTO) {
return listDddEditAppointmentDTO
.stream()
.map(appointmentDTO -> saveAppointment(doctorUUID, calendarUUID, appointmentDTO))
.collect(Collectors.toList());
}
public void editAppointment(UUID doctorUUID, UUID calendarUUID, UUID appointmentUUID, AppointmentDTO appointmentDTO) {
var calendar = calendarServiceImpl.getDoctorCalendar(doctorUUID, calendarUUID);
var optionalAppointment = calendar.getAppointments().stream().filter(a -> a.getAppointmentUUID().equals(appointmentUUID)).findFirst();
if (optionalAppointment.isEmpty()) {
throw new NoSuchElementException("Calendar doesn't have such appointment");
}
var appointment = optionalAppointment.get();
if(appointment.getPatientUUID()!=null){
throw new AppointmentAlreadyBookedException(appointmentUUID);
}
modelMapper.map(appointmentDTO, appointment);
appointmentRepository.save(appointment);
}
public void deleteAppointment(UUID doctorUUID, UUID calendarUUID, UUID appointmentUUID) {
var calendar = calendarServiceImpl.getDoctorCalendar(doctorUUID, calendarUUID);
var appointment = calendar.getAppointments().stream().filter(a -> a.getAppointmentUUID().equals(appointmentUUID)).findFirst();
if (appointment.isEmpty()) {
throw new NoSuchElementException("Calendar doesn't have such appointment");
}
appointmentRepository.delete(appointment.get());
}
}
<file_sep>package com.clinics.medicalunits.ui.service;
import com.clinics.common.DTO.request.outer.medicalUnit.RegisterMedicalUnitDTO;
import com.clinics.common.DTO.response.outer.MedicalUnitResponseDTO;
import com.clinics.medicalunits.data.model.MedicalUnit;
import com.clinics.medicalunits.data.repositorie.MedicalUnitRepository;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.transaction.Transactional;
import java.util.*;
@Transactional
@Slf4j
@Service
public class MedicalUnitService {
final private MedicalUnitRepository medicalUnitRepository;
final private ModelMapper modelMapper;
final private RestTemplate restTemplate;
final private Environment environment;
public MedicalUnitService(
MedicalUnitRepository medicalUnitRepository,
ModelMapper modelMapper,
RestTemplate restTemplate,
Environment environment) {
this.medicalUnitRepository = medicalUnitRepository;
this.restTemplate = restTemplate;
this.environment = environment;
this.modelMapper = modelMapper;
}
public List<MedicalUnitResponseDTO> getAll() {
List<MedicalUnitResponseDTO> medicalUnitResponseDTOList = new LinkedList<>();
for (var one :medicalUnitRepository.findAll()) {
medicalUnitResponseDTOList.add(modelMapper.map(one, MedicalUnitResponseDTO.class));
}
return medicalUnitResponseDTOList;
}
public MedicalUnitResponseDTO save(RegisterMedicalUnitDTO registerMedicalUnitDTO) {
var medicalUnit = modelMapper.map(registerMedicalUnitDTO, MedicalUnit.class);
medicalUnit.setMedicalUnitUUID(UUID.randomUUID());
return modelMapper.map(medicalUnitRepository.save(medicalUnit), MedicalUnitResponseDTO.class);
}
public MedicalUnitResponseDTO getByUUID(UUID medicalUnitUUID) {
var medicalUnit = medicalUnitRepository.findByMedicalUnitUUID(medicalUnitUUID);
if (medicalUnit.isEmpty()) {
throw new NoSuchElementException("No such medial unit in system");
}
return modelMapper.map(medicalUnit.get(), MedicalUnitResponseDTO.class);
}
}
<file_sep>package com.clinics.doctors.ui.client;
import com.clinics.common.DTO.response.outer.MedicalUnitResponseDTO;
import com.clinics.doctors.ui.service.JPAimpl.DoctorMedicalUnitClientImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping(value = "/doctors/{doctorUUID}/medical-units")
public class DoctorMedicalUnitController {
final private DoctorMedicalUnitClientImpl doctorMedicalUnitClientImpl;
public DoctorMedicalUnitController(
DoctorMedicalUnitClientImpl doctorMedicalUnitClientImpl) {
this.doctorMedicalUnitClientImpl = doctorMedicalUnitClientImpl;
}
@GetMapping
public ResponseEntity<List<MedicalUnitResponseDTO>> getAllDoctorMedicalUnites(@PathVariable UUID doctorUUID){
return ResponseEntity.ok().body(doctorMedicalUnitClientImpl.getAll(doctorUUID));
}
@GetMapping(value = "/{medicalUnitUUID}")
public ResponseEntity<MedicalUnitResponseDTO> getDoctorsMedicalUnit(
@PathVariable UUID doctorUUID,
@PathVariable UUID medicalUnitUUID
){
return ResponseEntity.ok().body(doctorMedicalUnitClientImpl.get(doctorUUID, medicalUnitUUID));
}
@PostMapping(value = "/{medicalUnitUUID}")
public ResponseEntity<MedicalUnitResponseDTO> addMedicalUniteIntoDoctor(
@PathVariable UUID medicalUnitUUID,
@PathVariable UUID doctorUUID) {
return ResponseEntity.status(HttpStatus.CREATED).body(doctorMedicalUnitClientImpl.save(medicalUnitUUID, doctorUUID));
}
@DeleteMapping(value = "/{medicalUnitUUID}")
public ResponseEntity<Void> removeMedicalUniteFromDoctor(
@PathVariable UUID medicalUnitUUID,
@PathVariable UUID doctorUUID) {
doctorMedicalUnitClientImpl.delete(doctorUUID, medicalUnitUUID);
return ResponseEntity.ok().build();
}
}
<file_sep>package com.clinics.patient.service;
import com.clinics.common.DTO.request.outer.EditPatientDTO;
import com.clinics.common.DTO.request.outer.RegisterPatientDTO;
import com.clinics.common.DTO.response.outer.PatientRegisterResponseDTO;
import com.clinics.patient.entity.Patient;
import com.clinics.patient.entity.Visit;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface PatientService {
PatientRegisterResponseDTO addPatient(RegisterPatientDTO registerPatientDTO, HttpServletRequest request);
List<Patient> findAll();
Patient findByUuid(UUID patientUUID);
Optional<Patient> findById(Long ID);
void deleteByUuid(UUID patientUUID);
void editPatient(UUID patientUUID, EditPatientDTO patient);
List<Visit> findAllVisits(UUID patientUUID);
}<file_sep>import {setStoreError, setStoreUserDetails} from "../../../redux/actions";
import {connect} from "react-redux";
import ContainerLoginPage from "./ContainerLoginPage";
const mapStateToProps = state => ({
error: state.error
});
const mapDispatchToProps = dispatch => ({
setStoreUserDetails: (userDetails) => {dispatch(setStoreUserDetails(userDetails))},
setStoreError: (error) => {dispatch(setStoreError(error))}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(ContainerLoginPage)<file_sep>import {useEffect, useReducer} from "react";
import {URLs} from "../../../URLs";
import {logOut} from "../../../redux/actions";
import {useHistory} from "react-router";
export const ContainerDoctorPage = ({userInformation, children, userDetails, setStoreUserInformation}) => {
//History
const history = useHistory();
//Reducer
const setDoctorPageState = (state, action) => {
switch (action.type) {
case "SETTING_INFORMATION_SUCCESS":
return {
...state,
doctorInformation: action.doctorInformation
};
case "SETTING_INFORMATION_FAILED":
return state;
case "SETTING_ALL_CALENDARS_INFORMATION_SUCCESS":
return {
...state,
calendars: action.calendars
};
case "SETTING_ALL_CALENDARS_INFORMATION_FAILED":
return state;
case "SETTING_ALL_CALENDAR_APPOINTMENTS_INFORMATION_SUCCESS":
return {
...state,
appointments: [...state.appointments, action.appointments]
};
case "SETTING_ALL_CALENDAR_APPOINTMENTS_INFORMATION_FAILED":
return state;
case "DELETE_ACCOUNT_SUCCESS":
return state;
case "DELETE_ACCOUNT_FAILED":
return state;
case "USER_INFORMATION_HAS_BEEN_EDIT_SUCCESS":
return {
...state,
userInformationHasBeenEdit: !state.userInformationHasBeenEdit
};
case "USER_INFORMATION_HAS_BEEN_EDIT_FAILED":
return state;
case "SETTING_APPOINTMENTS_TO_CALENDARS_SUCCESS":
const setAppointments = (calendar) => {
for (let i = 0; i < state.appointments.length; i++){
if (calendar.calendarUUID === state.appointments[i].calendarUUID){
calendar.appointments = state.appointments[i].appointments;
}
}
};
state.calendars.map((calendar) =>
setAppointments(calendar)
);
return {...state};
case "SETTING_APPOINTMENT_TO_CALENDARS_FAILED":
return state;
case "CHANGE_COMPONENT":
return {
...state,
componentToShow: action.componentToShow
};
default:
return state;
}
};
const init = (initialState) => initialState;
const initialState = {
doctorInformation: {
doctorUUID: null,
firstName: null,
lastName: null,
photoUrl: null,
licence: null,
calendarsUUID: null,
specializations: null,
patientsUUIDs: null,
medicalUnitsUUID: null
},
calendars: [],
appointments: [],
userInformationHasBeenEdit: false,
componentToShow: 0
};
const [doctorPageState, dispatchDoctorPageState] = useReducer(setDoctorPageState, initialState, init);
useEffect(() => {
const fetchForDoctorInformation = async () => {
try {
const init = {
method: 'GET',
body: null,
headers: {'Authorization': localStorage.token}
};
const response = await fetch(URLs.GET_DOCTOR_INFORMATION(userDetails.uuid), init);
const result = await response.json();
setStoreUserInformation(result);
dispatchDoctorPageState({type: "SETTING_INFORMATION_SUCCESS", doctorInformation: result})
} catch (e) {
dispatchDoctorPageState({type: "SETTING_INFORMATION_FAILED"})
}
};
const fetchForSetAllCalendarsInformation = async () => {
try {
const initCalendars = {
method: 'GET',
body: null,
headers: {'Authorization': localStorage.token}
};
const responseCalendars = await fetch(URLs.GET_ALL_DOCTOR_CALENDARS(userDetails.uuid), initCalendars)
const resultCalendars = await responseCalendars.json();
if (responseCalendars.ok) {
dispatchDoctorPageState({type: "SETTING_ALL_CALENDARS_INFORMATION_SUCCESS", calendars: resultCalendars})
} else {
dispatchDoctorPageState({type: "SETTING_ALL_CALENDARS_INFORMATION_FAILED"})
}
} catch (e) {
dispatchDoctorPageState({type: "SETTING_ALL_CALENDARS_INFORMATION_FAILED"})
}
};
fetchForDoctorInformation();
fetchForSetAllCalendarsInformation();
}, [doctorPageState.userInformationHasBeenEdit, setStoreUserInformation, userDetails.uuid]);
useEffect(() => {
const fetchForSetAppointmentsInCalendar = async (calendar) => {
try {
const initAppointments = {
method: 'GET',
body: null,
headers: {'Authorization':localStorage.token}
};
const response = await fetch(URLs.GET_ALL_APPOINTMENTS_IN_GIVEN_CALENDAR(userDetails.uuid, calendar.calendarUUID), initAppointments);
const result = await response.json();
const appointments = {
appointments: result,
calendarUUID: calendar.calendarUUID
};
dispatchDoctorPageState({type: "SETTING_ALL_CALENDAR_APPOINTMENTS_INFORMATION_SUCCESS", appointments: appointments})
} catch (e) {
dispatchDoctorPageState({type: "SETTING_ALL_CALENDAR_APPOINTMENTS_INFORMATION_FAILED"})
}
};
try {
doctorPageState.calendars.map((calendar) =>
fetchForSetAppointmentsInCalendar(calendar)
);
} catch{
dispatchDoctorPageState({type: "SETTING_ALL_CALENDAR_APPOINTMENTS_INFORMATION_FAILED"})
}
}, [doctorPageState.calendars, userDetails.uuid]);
useEffect(() => {
if (!(doctorPageState.calendars === [] || doctorPageState.appointments === [])){
try {
dispatchDoctorPageState({type: "SETTING_APPOINTMENTS_TO_CALENDARS_SUCCESS"})
} catch {
dispatchDoctorPageState({type: "SETTING_APPOINTMENTS_TO_CALENDARS_FAILED"})
}
}
}, [doctorPageState.calendars, doctorPageState.appointments]);
//Fetch
const fetchForDeleteAccount = async () => {
try {
const init = {
method: 'DELETE',
body: null,
headers: {
'Authorization': localStorage.token,
'Content-Type': 'application/json',
}
};
await fetch(URLs.DELETE_DOCTOR(userDetails.uuid), init)
.catch(() => dispatchDoctorPageState({type: "DELETE_ACCOUNT_FAILED"}));
dispatchDoctorPageState({type: "DELETE_ACCOUNT_SUCCESS"});
logOut(history);
} catch (e) {
dispatchDoctorPageState({type: "DELETE_ACCOUNT_FAILED"})
}
};
const fetchForChangeUserInformation = async (newUserInformation) => {
console.log("CLICK!");
console.log(newUserInformation);
try {
const body = JSON.stringify({
"email": newUserInformation.email,
"password": <PASSWORD>,
"firstName": newUserInformation.firstName,
"lastName": newUserInformation.lastName,
"photoUrl": newUserInformation.photoUrl,
"licence": newUserInformation.licence,
});
const init = {
method: 'PATCH',
body: body,
headers: {
'Authorization': localStorage.token,
'Content-Type': 'application/json',
}
};
await fetch(URLs.CHANGE_DOCTOR_INFORMATION(userDetails.uuid), init);
dispatchDoctorPageState({type: "USER_INFORMATION_HAS_BEEN_EDIT_SUCCESS"});
console.log("SUCCESS!");
} catch (e) {
dispatchDoctorPageState({type: "USER_INFORMATION_HAS_BEEN_EDIT_FAILED"})
console.log("FAILED!");
}
};
const onClickChangeTabPanel = (event, newValue) => {
dispatchDoctorPageState({type: "CHANGE_COMPONENT", componentToShow: newValue});
};
return(children({
doctorPageState,
fetchForDeleteAccount,
fetchForChangeUserInformation,
onClickChangeTabPanel,
userDetails,
userInformation,
}))
};
export default ContainerDoctorPage<file_sep>import {Col, Form} from "react-bootstrap";
import React, {useState} from "react";
import StylesTextField from "../../CustomTextField/StylesTextField";
import TextFieldCustomTypography from "../../CustomTypography/TypesOfCustomTypography/TextFieldLabelCustomTypography";
export const PasswordForm = (props) => {
const { handleChange, validation, setIsCorrectInputInForms } = props;
const [isCorrectInput, setIsCorrectInput] = useState(true);
const [messageForIncorrectInput, setMessageForIncorrectInput] = useState(null);
const setGoodInputInAllStates = () => {
setIsCorrectInput(true);
setIsCorrectInputInForms({passwordForm: true});
};
const setWrongInputInAllStates = () => {
setIsCorrectInput(false);
setIsCorrectInputInForms({passwordForm: false});
};
//Validation for input data
const checkInputCorrect = (e) => {
if (e.target.value.length < 9 || e.target.value.length > 16){
setWrongInputInAllStates();
setMessageForIncorrectInput("Must contain between 8 and 16 characters")
} else {
setGoodInputInAllStates();
setMessageForIncorrectInput(null);
}
};
return (
<Form.Group as={Col} controlId="formGridPassword">
<StylesTextField
onChange={(e) => {
handleChange({password : e.target.value});
if (validation){checkInputCorrect(e)}
}}
name="password"
type="password"
label={
<TextFieldCustomTypography
primaryLabel={"Hasło"}
secondaryLabel={"Password"}
/>
}
variant="outlined"
error={!isCorrectInput}
helperText={messageForIncorrectInput}
fullWidth
/>
</Form.Group>)
};<file_sep>package com.clinics.doctors.bean;
import com.clinics.common.bean.BeanFactory;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class DoctorBeanFactory extends BeanFactory implements ApplicationContextAware {
}
<file_sep>import React, {useEffect, useState} from "react";
import Typography from "@material-ui/core/Typography";
import {Card, CardContent} from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
export const AppointmentCard = (props) => {
const {
sendFetchRequestForGetAllAppointmentsForGivenCalendar,
doctorUUID,
calendarUUID
} = props;
const [allAppointmentsInCalendar, setAllAppointmentsInCalendar] = useState(null);
const [key, setKey] = useState(0);
useEffect(() => {
sendFetchRequestForGetAllAppointmentsForGivenCalendar(doctorUUID ,calendarUUID, setAllAppointmentsInCalendar);
}, []);
return allAppointmentsInCalendar ?
allAppointmentsInCalendar.map((appointment, index) =>
<Grid item xs={3} key={index}>
<Card>
<CardContent>
<Typography color="textSecondary" gutterBottom>
UUID:
</Typography>
<Typography variant="h5" component="h2">
{appointment.appointmentUUID}
</Typography>
<Typography color="textSecondary">
Time:
</Typography>
<Typography variant="body2" component="p">
Info
</Typography>
</CardContent>
</Card>
</Grid>
) : null
};
export default AppointmentCard<file_sep>package com.clinics.zuul.security;
import com.clinics.common.security.JwtProperties;
import com.clinics.common.security.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Slf4j
@Component
public class UserUUIDChecker implements JwtProperties {
public boolean checkUserUUID(Authentication authentication, String uuid) {
if(
authentication == null ||
authentication.getCredentials() == null ||
authentication.getCredentials().toString().length() == 0)
return false;
if (authentication
.getAuthorities()
.stream()
.anyMatch(a -> a.getAuthority().replace("ROLE_", "").equals(Role.SYSTEM_ADMIN))) {
return true;
}
HashMap<String, Object> credentials = (HashMap<String, Object>)authentication.getCredentials();
return uuid.equals(credentials.get("UUID"));
}
}
<file_sep>package com.clinics.common.exception.validators;
import com.clinics.common.security.Role;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class RoleValidator implements ConstraintValidator<RoleConstraint, String>, Role {
@Override
public void initialize(RoleConstraint constraintAnnotation) {
}
@Override
public boolean isValid(String role, ConstraintValidatorContext constraintValidatorContext) {
return getAllRoles().stream()
.filter(r -> r.equals(role)
&& !r.equals(Role.SYSTEM_ADMIN))
.count() == 1;
}
}
<file_sep>package com.clinics.common.DTO.request.outer;
import lombok.Data;
import lombok.ToString;
import org.hibernate.validator.constraints.pl.PESEL;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.UUID;
@Data
@ToString
public class RegisterPatientDTO {
@NotNull(message = "uuid cannot be null")
private UUID patientUUID;
@NotBlank(message = "fistName is mandatory")
@Size(min = 2, max = 100, message = "firstName length out of range")
private String firstName;
@NotBlank(message = "lastName is mandatory")
@Size(min = 3, max = 100, message = "lastName length out of range")
private String lastName;
@PESEL
@NotBlank(message = "pesel is mandatory")
private String pesel;
@Size(max = 500, message = "photoUrl length out of range ")
private String photoUrl;
}
<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.Collection;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class DoctorResponseDTO {
private UUID doctorUUID;
private String firstName;
private String lastName;
private String photoUrl;
private String licence;
private Collection<UUID> calendarsUUID;
private Collection<SpecializationResponseDTO> specializations;
private Collection<UUID> patientsUUIDs; //todo get ALL cannot show patients ? however there will be only uuid so ... ?
private Collection<UUID> medicalUnitsUUID;
}
<file_sep>package com.clinics.patient.service;
import com.clinics.common.DTO.request.outer.DiseaseDTO;
import com.clinics.patient.entity.Disease;
import java.util.UUID;
public interface DiseaseService {
Disease addDisease(UUID visitUUID, DiseaseDTO diseaseDTO);
void removeDisease(UUID diseaseUUID);
}<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.Collection;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class PatientRegisterResponseDTO {
private UUID patientUUID;
private String firstName;
private String lastName;
private String photoUrl;
private String pesel;
private Collection<Object> visits;
}
<file_sep>package com.clinics.doctors.data.model;
import com.fasterxml.jackson.annotation.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Collection;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
@DynamicInsert
@DynamicUpdate
@ToString
@Entity
public class Calendar {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@Column(updatable = false,
nullable = false,
unique = true)
private UUID calendarUUID;
@Column(unique = true)
@NotBlank(message = "name is mandatory")
@Size(min = 2, max = 100, message = "name length out of range")
private String name;
private UUID medicalUnitUUID;
@JsonIgnore
@ManyToOne(
targetEntity=Doctor.class,
fetch = FetchType.LAZY)
@JoinColumn(name="doctor_id")
private Doctor doctor;
@OneToMany(
targetEntity=Appointment.class,
mappedBy="calendar",
cascade={CascadeType.REMOVE},
fetch = FetchType.LAZY,
orphanRemoval=true)
private Collection<Appointment> appointments;
}
<file_sep>import {Grid, Typography} from "@material-ui/core";
import {FormForInputUserInformation} from "../../../AdditionalComponents/FormForInputUserInfo/FormForInputUserInformation";
import React from "react";
import ContainerForFormForInputUserInformation
from "../../../AdditionalComponents/FormForInputUserInfo/ContainerForFormForInputUserInformation";
export const EditDataFormComponent = (props) => {
const {
userInformation,
fetchRequest
} = props;
return(
<Grid item>
<Typography
align="center"
variant="h6"
>
Proszę uzupełnić lub zmienić tylko te elementy które chcesz zmienić
</Typography>
<Typography
align="center"
variant="subtitle1"
>
Fill or change only variables which you want to change
</Typography>
<br/>
<ContainerForFormForInputUserInformation
userInformation ={userInformation}
fetchRequest ={fetchRequest}
primaryLabel ="Edytuj"
secondaryLabel ="Edit"
showEmailForm ={true}
showPasswordForm ={true}
showRoleForm ={false}
showFirstNameForm ={true}
showLastNameForm ={true}
showLicenceForm ={true}
showPhotoURLForm ={true}
>
{({
onSubmit,
showEmailForm,
showPasswordForm,
showFirstNameForm,
showLastNameForm,
showLicenceForm,
showPhotoURLForm,
primaryLabel,
secondaryLabel,
submitButtonAvailable,
validation,
handleChange,
setIsCorrectInputInForms,
userInformation
}) => (
<FormForInputUserInformation
onSubmit={onSubmit}
primaryLabel={primaryLabel}
secondaryLabel={secondaryLabel}
showEmailForm={showEmailForm}
showPasswordForm={showPasswordForm}
showFirstNameForm={showFirstNameForm}
showLastNameForm={showLastNameForm}
showLicenceForm={showLicenceForm}
showPhotoURLForm={showPhotoURLForm}
submitButtonAvailable={submitButtonAvailable}
validation={validation}
handleChange={handleChange}
setIsCorrectInputInForms={setIsCorrectInputInForms}
userInformation={userInformation}
/>
)}
</ContainerForFormForInputUserInformation>
</Grid>
)
};
export default EditDataFormComponent<file_sep>package com.clinics.patient;
import com.clinics.common.DTO.request.outer.RegisterPatientDTO;
import com.clinics.common.DTO.response.outer.PatientRegisterResponseDTO;
import com.clinics.patient.client.PatientClient;
import com.clinics.patient.entity.Patient;
import com.clinics.patient.entity.Visit;
import com.clinics.patient.exception.PatientNotFoundException;
import com.clinics.patient.repository.PatientRepository;
import com.clinics.patient.service.PatientServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.modelmapper.ModelMapper;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class PatientServiceTest {
@Mock
private PatientRepository patientRepository;
@Mock
private ModelMapper modelMapper;
@Mock
private PatientClient patientClient;
@Mock
private Patient patient;
private UUID patientUUID = UUID.randomUUID();
@InjectMocks PatientServiceImpl subject;
@Test
void findByUuidShouldReturnPatient () {
when(patientRepository.findByPatientUUID(patientUUID)).thenReturn(Optional.of(patient));
Patient result = subject.findByUuid(patientUUID);
verify(patientRepository, times(1)).findByPatientUUID(patientUUID);
Assertions.assertEquals(patient, result);
}
@Test
void findByUuidShouldThrowWhenNoPatient () {
Assertions.assertThrows(PatientNotFoundException.class, () -> {
subject.findByUuid(patientUUID);
});
}
@Test
void shouldFindAllPatientsVisits(){
Visit visit = mock(Visit.class);
when(patientRepository.findByPatientUUID(patientUUID)).thenReturn(Optional.of(patient));
when(patient.getVisits()).thenReturn(List.of(visit));
List<Visit> result = subject.findAllVisits(patientUUID);
Assertions.assertTrue(result.contains(visit));
}
@Test
void shouldThrowPatientNotFoundException(){
Assertions.assertThrows(PatientNotFoundException.class, () -> {
subject.findAllVisits(patientUUID);
});
}
@Test
void shouldActivatePatientInAuth(){
RegisterPatientDTO registerPatientDTO = mock(RegisterPatientDTO.class);
HttpServletRequest request = mock(HttpServletRequest.class);
subject.addPatient(registerPatientDTO, request);
verify(patientClient, times(1)).activatePatientInAuth(registerPatientDTO, request);
}
@Test
void shouldSavePatient() {
RegisterPatientDTO registerPatientDTO = mock(RegisterPatientDTO.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(modelMapper.map(registerPatientDTO, Patient.class)).thenReturn(patient);
subject.addPatient(registerPatientDTO, request);
verify(patientRepository, times(1)).save(patient);
}
@Test
void shouldReturnPatientRegisterResponseDTO(){
RegisterPatientDTO registerPatientDTO = mock(RegisterPatientDTO.class);
PatientRegisterResponseDTO patientRegisterResponseDTO = mock(PatientRegisterResponseDTO.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(modelMapper.map(registerPatientDTO, Patient.class)).thenReturn(patient);
when(modelMapper.map(patient, PatientRegisterResponseDTO.class)).thenReturn(patientRegisterResponseDTO);
PatientRegisterResponseDTO result = subject.addPatient(registerPatientDTO, request);
Assertions.assertEquals(patientRegisterResponseDTO, result);
}
@Test
void shouldThrowNoSuchElementException(){
RegisterPatientDTO registerPatientDTO = mock(RegisterPatientDTO.class);
HttpServletRequest request = mock(HttpServletRequest.class);
doThrow(NoSuchElementException.class).when(patientClient).activatePatientInAuth(registerPatientDTO, request);
Assertions.assertThrows(NoSuchElementException.class, () -> {
subject.addPatient(registerPatientDTO, request);
});
}
}
<file_sep>package com.clinics.medicalunits.data.model;
import com.fasterxml.jackson.annotation.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.*;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
@ToString
@DynamicInsert
@DynamicUpdate
@Entity(name = "medical_unit")
public class MedicalUnit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@Column(updatable = false,
nullable = false,
unique = true)
private UUID medicalUnitUUID;
@Column(unique = true)
@NotBlank(message = "name is mandatory")
@Size(min = 2, max = 100, message = "name length out of range")
private String name;
@NotBlank(message = "adress is mandatory")
@Size(min = 3, max = 100, message = "address length out of range")
private String address; //todo <--- this we need to do properly
@JsonIgnore
@ElementCollection
private Collection<UUID> patientsUUID;
@ElementCollection
private Collection<UUID> doctorsUUID;
}
<file_sep>package com.clinics.common.DTO.request.outer.doctor;
import lombok.*;
import org.hibernate.validator.constraints.time.DurationMax;
import org.hibernate.validator.constraints.time.DurationMin;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.UUID;
@Data
@ToString
public class AppointmentDTO {
private LocalDateTime localDateTime;
@DurationMax(minutes = 60)
@DurationMin(minutes = 10)
private Duration duration;
private UUID patientUUID;
private String patientFirstName;
private String patientSecondName;
}
<file_sep>import AppBar from "@material-ui/core/AppBar";
import React, {useState} from "react";
import {Container} from "@material-ui/core";
import TabPanel from "../../AdditionalComponents/TabPanel/TabPanel";
import LoginPage from "../LoginPage/LoginPage";
import ContainerLoginPage from "../LoginPage/ReduxContainerLoginPage";
import ContainerRegisterPage from "../RegisterPage/ContainerRegisterPage";
import RegisterPage from "../RegisterPage/RegisterPage";
import {StylesTab, StylesTabs} from "../../AdditionalComponents/CustomTab/StylesTab";
import TabCustomTypography from "../../AdditionalComponents/CustomTypography/TypesOfCustomTypography/TabCustomTypography";
//CSS Stylesheet
const styleForMainContainer = {
marginTop: "50px"
};
const styleForTabPanel = {
backgroundColor: "white",
};
export const MainPage = () => {
const [whichPage, setPage] = useState(0);
const handleChange = (event, newValue) => {
setPage(newValue);
};
return (
<Container maxWidth="sm" style={styleForMainContainer}>
<AppBar position="static">
<StylesTabs
value={whichPage}
onChange={handleChange}
variant="fullWidth"
>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Logowanie"}
secondaryLabel={"Log In"}
/>
}
/>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Rejestracja"}
secondaryLabel={"Register"}
/>
}
/>
</StylesTabs>
</AppBar>
<TabPanel
value={whichPage}
index={0}
classes={styleForTabPanel}
>
<ContainerLoginPage>
{({userDetails, dispatchUserState, sendFetchForLoginUser}) => (
<LoginPage
userDetails={userDetails}
dispatchUserState={dispatchUserState}
sendFetchForLoginUser={sendFetchForLoginUser}
/>
)}
</ContainerLoginPage>
</TabPanel>
<TabPanel
value={whichPage}
index={1}
classes={styleForTabPanel}
>
<ContainerRegisterPage>
{({fetchRegisterNewUser, registerStatus, dispatchRegisterStatus, handleChangeRole}) => (
<RegisterPage
fetchRegisterNewUser={fetchRegisterNewUser}
registerStatus={registerStatus}
dispatchRegisterStatus={dispatchRegisterStatus}
handleChangeRole={handleChangeRole}
/>
)}
</ContainerRegisterPage>
</TabPanel>
</Container>
);
};
export default MainPage;<file_sep>package com.clinics.medicalunits.ui.controller;
import com.clinics.common.DTO.request.outer.medicalUnit.RegisterMedicalUnitDTO;
import com.clinics.common.DTO.response.outer.MedicalUnitResponseDTO;
import com.clinics.medicalunits.ui.service.MedicalUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.validation.Valid;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping(value = "/medical-units")
public class MedicalUnitController {
final MedicalUnitService medicalUnitService;
final RestTemplate restTemplate;
@Autowired
public MedicalUnitController(MedicalUnitService medicalUnitService, RestTemplate restTemplate) {
this.medicalUnitService = medicalUnitService;
this.restTemplate = restTemplate;
}
@GetMapping
public ResponseEntity<List<MedicalUnitResponseDTO>> getAllMedicalUnits(){
return ResponseEntity.ok().body(medicalUnitService.getAll());
}
@GetMapping(path = "/{medicalUnitUUID}")
public ResponseEntity<MedicalUnitResponseDTO> getMedicalUnitByUUID(@PathVariable UUID medicalUnitUUID){
return ResponseEntity.ok().body(medicalUnitService.getByUUID(medicalUnitUUID));
}
@PostMapping
public ResponseEntity<MedicalUnitResponseDTO> add(@Valid @RequestBody RegisterMedicalUnitDTO registerMedicalUnitDTO) {
return ResponseEntity.status(HttpStatus.CREATED).body(medicalUnitService.save(registerMedicalUnitDTO));
}
@GetMapping(path = "/test")
public ResponseEntity<String> getDefault(){
return ResponseEntity.ok().body("{\"message\":\"Hello world from medical unit\"}");
}
@GetMapping(path = "/test/{text}")
public ResponseEntity<String> getTestFromAuth(@PathVariable String text){
return ResponseEntity.ok().body(restTemplate.getForObject("http://auth/auth/test/" + text, String.class));
}
}
<file_sep>import {Col, Form} from "react-bootstrap";
import React, {useState} from "react";
import StylesTextField from "../../CustomTextField/StylesTextField";
import TextFieldCustomTypography from "../../CustomTypography/TypesOfCustomTypography/TextFieldLabelCustomTypography";
export const
EmailForm = (props) => {
const { handleChange, validation, setIsCorrectInputInForms } = props;
const [isCorrectInput, setIsCorrectInput] = useState(true);
const [messageForIncorrectInput, setMessageForIncorrectInput] = useState(null);
const emailFormat = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/;
const setGoodInputInAllStates = () => {
setIsCorrectInput(true);
setIsCorrectInputInForms({emailForm: true});
};
const setWrongInputInAllStates = () => {
setIsCorrectInput(false);
setIsCorrectInputInForms({emailForm: false});
};
//Validation for input data
const checkInputCorrect = (e) => {
if (e.target.value.length === 0){
setWrongInputInAllStates();
setMessageForIncorrectInput("The field cannot be empty");
} else if (!e.target.value.match(emailFormat)){
setWrongInputInAllStates();
setMessageForIncorrectInput("The text in field is not email");
} else {
setGoodInputInAllStates();
setMessageForIncorrectInput(null);
}
};
return (
<Form.Group as={Col} controlId="formGridEmail">
<StylesTextField
onChange={(e) => {
handleChange({email : e.target.value});
if (validation){checkInputCorrect(e)}
}}
name="email"
label={
<TextFieldCustomTypography
primaryLabel={"Adres Email"}
secondaryLabel={"Email"}
/>
}
variant="outlined"
error={!isCorrectInput}
helperText={messageForIncorrectInput}
fullWidth
/>
</Form.Group>)
};<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class UserUUIDAndROLE {
private UUID userUUID;
private String role;
}
<file_sep>package com.clinics.patient.controller;
import com.clinics.common.DTO.request.outer.EditPatientDTO;
import com.clinics.common.DTO.request.outer.RegisterPatientDTO;
import com.clinics.common.DTO.response.outer.PatientRegisterResponseDTO;
import com.clinics.patient.entity.Patient;
import com.clinics.patient.entity.Visit;
import com.clinics.patient.service.PatientService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping(value = "/patients")
public class PatientController {
final private PatientService patientService;
public PatientController(PatientService patientService) {
this.patientService = patientService;
}
@GetMapping
public List<Patient> list() {
return patientService.findAll();
}
@GetMapping(path = "/{patientUUID}")
public Patient getPatientByUUID(@PathVariable UUID patientUUID){
return patientService.findByUuid(patientUUID);
}
@PostMapping
public ResponseEntity<PatientRegisterResponseDTO> registerPatient(@RequestBody RegisterPatientDTO registerPatientDTO, HttpServletRequest request){
return ResponseEntity.status(HttpStatus.CREATED).body(patientService.addPatient(registerPatientDTO, request));
}
@PatchMapping(path = "/{patientUUID}")
public void editPatient(@PathVariable UUID patientUUID, @RequestBody EditPatientDTO patient) {
patientService.editPatient(patientUUID, patient);
}
@GetMapping(path = "/{patientUUID}/visits")
public List<Visit> getAllVisits(@PathVariable UUID patientUUID) {
return patientService.findAllVisits(patientUUID);
}
@DeleteMapping(path = "/{patientUUID}")
public void deletePatient(@PathVariable UUID patientUUID) {
patientService.deleteByUuid(patientUUID);
}
}<file_sep>package com.clinics.medicalunits.data.repositorie;
import com.clinics.medicalunits.data.model.MedicalUnit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface MedicalUnitRepository extends JpaRepository<MedicalUnit, Long> {
@Query("SELECT m FROM medical_unit m")
List<MedicalUnit> getAll();
Optional<MedicalUnit> findByMedicalUnitUUID(UUID medicalUnitUUID);
// Optional<MedicalUnit> findByDoctorsUUID(UUID doctorsUUID);
}
<file_sep>package com.clinics.doctors.ui.controller;
import com.clinics.common.DTO.request.outer.doctor.SpecializationDTO;
import com.clinics.common.DTO.response.outer.SpecializationResponseDTO;
import com.clinics.doctors.ui.service.JPAimpl.SpecializationServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping(value = "/doctors/{doctorUUID}/specializations")
public class DoctorSpecializationController {
final private SpecializationServiceImpl specializationServiceImpl;
public DoctorSpecializationController(
SpecializationServiceImpl specializationServiceImpl) {
this.specializationServiceImpl = specializationServiceImpl;
}
@GetMapping
public ResponseEntity<List<SpecializationResponseDTO>> getAllDoctorSpecializations(
@PathVariable UUID doctorUUID) {
return ResponseEntity.ok().body(specializationServiceImpl.getDoctorSpecializations(doctorUUID));
}
@GetMapping(value = "/{specializationUUID}")
public ResponseEntity<SpecializationResponseDTO> getDoctorSpecialization(
@PathVariable UUID doctorUUID,
@PathVariable UUID specializationUUID) {
return ResponseEntity.ok().body(specializationServiceImpl.getDoctorSpecialization(doctorUUID, specializationUUID));
}
@PostMapping
public ResponseEntity<SpecializationResponseDTO> addExistingSpecializationIntoDoctor(
@Valid @RequestBody SpecializationDTO specializationDTO,
@PathVariable UUID doctorUUID) {
return ResponseEntity.status(HttpStatus.CREATED).body(specializationServiceImpl.saveSpecializationIntoDoctor(doctorUUID, specializationDTO));
}
@PostMapping(value = "/{specializationUUID}")
public ResponseEntity<SpecializationResponseDTO> addExistingSpecializationIntoDoctor(
@PathVariable UUID doctorUUID,
@PathVariable UUID specializationUUID) {
return ResponseEntity.status(HttpStatus.CREATED).body(specializationServiceImpl.saveExistingSpecializationIntoDoctor(doctorUUID, specializationUUID));
}
// @PatchMapping(value = "/{specializationUUID}")
// public ResponseEntity<Void> edit(
// @Valid @RequestBody AddEditSpecializationDTO addEditCalendarDTO,
// @PathVariable UUID specializationUUID) {
// specializationService.edit(addEditCalendarDTO, specializationUUID);
// return ResponseEntity.ok().build();
// }
//
@DeleteMapping(value = "/{specializationUUID}")
public ResponseEntity<Void> removeSpecializationFromDoctor(
@PathVariable UUID specializationUUID,
@PathVariable UUID doctorUUID) {
specializationServiceImpl.removeSpecializationFromDoctor(doctorUUID, specializationUUID);
return ResponseEntity.ok().build();
}
}
<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class SpecializationResponseDTO {
private UUID specializationUUID;
private String name;
}
<file_sep>package com.clinics.patient.repository;
import com.clinics.patient.entity.Disease;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import java.util.UUID;
public interface DiseaseRepository extends JpaRepository<Disease, Long> {
void deleteDiseaseByDiseaseUUID(UUID diseaseUUID);
Optional<Disease> findByDiseaseUUID(UUID diseaseUUID);
}
<file_sep>package com.clinics.zuul.configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Primary
@Component
@EnableSwagger2
public class Swagger2Config implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
return new ArrayList<>(){{
add(swaggerResource("Auth", "/auth-swagger/v2/api-docs", "2.0"));
add(swaggerResource("Doctor", "/doctor-mssc/v2/api-docs", "2.0"));
add(swaggerResource("Medical Unites", "/medical-units-mssc/v2/api-docs", "2.0"));
add(swaggerResource("Patient", "/patient-mssc/v2/api-docs", "2.0"));
}};
}
private SwaggerResource swaggerResource(String name, String location, String version) {
var swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
<file_sep>import {StylesTextFieldLabelTypography} from "../StylesTypography";
import React from "react";
import {Grid} from "@material-ui/core";
const TextFieldCustomTypography = (props) => {
const {
primaryLabel,
secondaryLabel
} = props;
return (
<Grid
container
spacing={1}
direction="row"
justify="flex-start"
alignItems="center"
>
<Grid item>
<StylesTextFieldLabelTypography variant={"h4"} noWrap>
{primaryLabel}
</StylesTextFieldLabelTypography>
</Grid>
<Grid item>
<StylesTextFieldLabelTypography variant={"h2"} noWrap>
({secondaryLabel})
</StylesTextFieldLabelTypography>
</Grid>
</Grid>
)
}
export default TextFieldCustomTypography<file_sep>package com.clinics.doctors.ui.service.JPAimpl;
import com.clinics.common.DTO.request.outer.doctor.CalendarDTO;
import com.clinics.common.DTO.response.outer.CalendarResponseDTO;
import com.clinics.doctors.data.model.Appointment;
import com.clinics.doctors.data.model.Calendar;
import com.clinics.doctors.data.repositorie.CalendarRepository;
import com.clinics.doctors.ui.service.CalendarService;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.spi.MappingContext;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;
@Transactional
@Service
public class CalendarServiceImpl implements CalendarService {
final private CalendarRepository calendarRepository;
final private DoctorServiceImpl doctorServiceImpl;
final private DoctorMedicalUnitClientImpl doctorMedicalUnitClientImpl;
final private ModelMapper modelMapper;
public CalendarServiceImpl(
CalendarRepository calendarRepository,
DoctorServiceImpl doctorServiceImpl,
DoctorMedicalUnitClientImpl doctorMedicalUnitClientImpl,
ModelMapper modelMapper) {
this.calendarRepository = calendarRepository;
this.doctorServiceImpl = doctorServiceImpl;
this.doctorMedicalUnitClientImpl = doctorMedicalUnitClientImpl;
this.modelMapper = modelMapper;
modelMapper.createTypeMap(Calendar.class, CalendarResponseDTO.class).setPostConverter(getCalendarConverter());
}
public List<CalendarResponseDTO> getAllDoctorCalendarsDTO(UUID doctorUUID) {
return calendarRepository
.getCalendarsByDoctor_DoctorUUID(doctorUUID).stream()
.map(doctor -> modelMapper.map(doctor, CalendarResponseDTO.class))
.collect(Collectors.toList());
}
public CalendarResponseDTO getDoctorCalendarDTO(UUID doctorUUID, UUID calendarUUID) {
var calendar = getDoctorCalendar(doctorUUID, calendarUUID);
return modelMapper.map(calendar, CalendarResponseDTO.class);
}
public Calendar getCalendar(UUID calendarUUID) {
var optionalCalendar = calendarRepository.getCalendarByCalendarUUID(calendarUUID);
if (optionalCalendar.isEmpty()) {
throw new NoSuchElementException(String.format("No such calendar in system %s", calendarUUID ));
}
return optionalCalendar.get();
}
public Calendar getDoctorCalendar(UUID doctorUUID, UUID calendarUUID) {
var doctor = doctorServiceImpl.getByUUID(doctorUUID);
var optionalCalendar = doctor.getCalendars().stream().filter(c -> c.getCalendarUUID().equals(calendarUUID)).findFirst();
if (optionalCalendar.isEmpty()) {
throw new NoSuchElementException(String.format("Doctor doesn't have such calendar %s", calendarUUID ));
}
return optionalCalendar.get();
}
public CalendarResponseDTO saveMedicalUniteIntoDoctorCalendar(UUID doctorUUID, CalendarDTO calendarDTO) {
var doctor = doctorServiceImpl.getByUUID(doctorUUID);
var calendar = modelMapper.map(calendarDTO, Calendar.class);
calendar.setCalendarUUID(UUID.randomUUID());
calendar.setDoctor(doctor);
calendarRepository.save(calendar);
return modelMapper.map(calendar, CalendarResponseDTO.class);
}
public CalendarResponseDTO saveMedicalUniteIntoDoctorCalendar(UUID doctorUUID, UUID calendarUUID, UUID medicalUniteUUID) {
doctorServiceImpl.getByUUID(doctorUUID);
doctorMedicalUnitClientImpl.getMedicalUnitResponseDTO(medicalUniteUUID);
var calendar = getCalendar(calendarUUID);
if (calendar.getMedicalUnitUUID() != null) {
throw new NoSuchElementException("Calendar already assigned to medicalUnite");
}
calendar.setMedicalUnitUUID(medicalUniteUUID);
calendarRepository.save(calendar);
return modelMapper.map(calendar, CalendarResponseDTO.class);
}
public void editCalendar(UUID doctorUUID, UUID calendarUUID, CalendarDTO calendarDTO) {
var calendar = getDoctorCalendar(doctorUUID, calendarUUID);
modelMapper.map(calendarDTO, calendar);
calendarRepository.save(calendar);
}
public void editCalendarMedicalUnite(UUID doctorUUID, UUID calendarUUID, UUID medicalUniteUUID) {
var calendar = getDoctorCalendar(doctorUUID, calendarUUID);
if (calendar.getMedicalUnitUUID().equals(medicalUniteUUID)) {
throw new NoSuchElementException("Calendar is assigned to this medicalUnite");
}
calendar.setMedicalUnitUUID(medicalUniteUUID);
doctorMedicalUnitClientImpl.getMedicalUnitResponseDTO(medicalUniteUUID);
calendarRepository.save(calendar);
}
public void deleteDoctorCalendar(UUID doctorUUID, UUID calendarUUID) {
var calendar = getDoctorCalendar(doctorUUID, calendarUUID);
calendarRepository.delete(calendar);
}
public void removeMedicalUniteFromCalendar(UUID doctorUUID, UUID calendarUUID, UUID medicalUniteUUID) {
var calendar = getDoctorCalendar(doctorUUID, calendarUUID);
if (calendar.getMedicalUnitUUID() == null || !calendar.getMedicalUnitUUID().equals(medicalUniteUUID)) {
throw new NoSuchElementException("Calendar isn't assigned to this medicalUnite");
}
calendar.setMedicalUnitUUID(null);
calendarRepository.save(calendar);
}
private Converter<Calendar, CalendarResponseDTO> getCalendarConverter() {
Converter<Calendar, CalendarResponseDTO> converter = new Converter<>() {
@Override
public CalendarResponseDTO convert(MappingContext<Calendar, CalendarResponseDTO> context) {
Collection<Appointment> appointments = context.getSource().getAppointments();
if(appointments == null) return context.getDestination();
context
.getDestination()
.setAppointmentsUUID(appointments
.stream()
.map(Appointment::getAppointmentUUID)
.collect(Collectors.toList()));
return context.getDestination();
}
};
return converter;
}
}<file_sep>package com.clinics.doctors.data.repositorie;
import com.clinics.doctors.data.model.Doctor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface DoctorRepository extends JpaRepository<Doctor, Long> {
Optional<Doctor> findByDoctorUUID(UUID uuid);
boolean existsByDoctorUUID(UUID uuid);
void deleteByDoctorUUID(UUID uuid);
List<Doctor> findAllByMedicalUnitsUUID(UUID medicalUnitesUUID);
}
<file_sep>import {useState} from "react";
export const setStoreUserDetails = userDetails => ({
type: 'SET_USER_DETAILS',
userDetails
});
export const setStoreDoctorInformation = userInformation => ({
type: 'SET_DOCTOR_INFORMATION',
userInformation
});
export const setStorePatientInformation = userInformation => ({
type: 'SET_PATIENT_INFORMATION',
userInformation
});
export const setStoreError = error => ({
type: 'SET_ERROR',
error
});
//USEFUL FUNCTIONS
export const useFormFields = (initialState) => {
const [fields, setValues] = useState(initialState);
return [
fields,
function(event) {
if (event.target) {
setValues({
...fields,
[event.target.name]: event.target.value
});
} else {
setValues(event)
}
}
];
};
export const logOut = (history) => {
localStorage.removeItem("token");
history.push("/");
};<file_sep>package com.clinics.common.DTO.response.outer;
import lombok.*;
import java.util.Collection;
import java.util.UUID;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
public class CalendarResponseDTO {
private UUID calendarUUID;
private String name;
private UUID medicalUnitUUID;
private Collection<UUID> appointmentsUUID;
}
<file_sep>package com.clinics.common.DTO.request.outer.doctor;
import lombok.Data;
import lombok.ToString;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.UUID;
@Data
@ToString
public class RegisterDoctorDTO {
@NotNull(message = "uuid cannot be null")
private UUID doctorUUID;
@NotBlank(message = "fistName is mandatory")
@Size(min = 2, max = 100, message = "firstName length out of range")
private String firstName;
@NotBlank(message = "lastName is mandatory")
@Size(min = 3, max = 100, message = "lastName length out of range")
private String lastName;
@Size(max = 500, message = "photoUrl length out of range ")
private String photoUrl;
// todo @PESEL for test
// @NotBlank(message = "licence is mandatory")
// @Size(max = 100, message = "licence length out of range ")
private String licence;
}
<file_sep>import {TextField, withStyles} from "@material-ui/core";
const StylesTextField = withStyles({
root: {
minWidth: "211px",
'& label.Mui-focused': {
color: "#4d1919",
},
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: "#4d1919",
},
},
}
})(TextField);
export default StylesTextField<file_sep>package com.clinics.doctors.ui.controller;
import com.clinics.common.DTO.request.outer.doctor.AppointmentDTO;
import com.clinics.common.DTO.response.outer.AppointmentResponseDTO;
import com.clinics.doctors.ui.service.JPAimpl.AppointmentServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping(value = "/doctors/{doctorUUID}/calendars/{calendarUUID}/appointments")
public class DoctorAppointmentController {
final private AppointmentServiceImpl appointmentServiceImpl;
public DoctorAppointmentController(
AppointmentServiceImpl appointmentServiceImpl) {
this.appointmentServiceImpl = appointmentServiceImpl;
}
@GetMapping
public ResponseEntity<List<AppointmentResponseDTO>> getAllCalendarAppointments(
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID){
return ResponseEntity.ok().body(appointmentServiceImpl.getAllDoctorAppointments(doctorUUID, calendarUUID));
}
@GetMapping(value = "/{appointmentUUID}")
public ResponseEntity<AppointmentResponseDTO> getCalendarAppointment(
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID,
@PathVariable UUID appointmentUUID){
return ResponseEntity.ok().body(appointmentServiceImpl.getDoctorAppointment(doctorUUID, calendarUUID, appointmentUUID));
}
@PostMapping
public ResponseEntity<AppointmentResponseDTO> addAppointmentIntoCalendar(
@Valid @RequestBody AppointmentDTO appointmentDTO,
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID){
return ResponseEntity.status(HttpStatus.CREATED).body(appointmentServiceImpl.saveAppointment(doctorUUID, calendarUUID, appointmentDTO));
}
@PostMapping(value = "/multiple")
public ResponseEntity<List<AppointmentResponseDTO>> addListAppointmentsIntoCalendar(
@Valid @RequestBody List<AppointmentDTO> addEditAppointmentsDTO,
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID){
return ResponseEntity.status(HttpStatus.CREATED).body(appointmentServiceImpl.saveAppointments(doctorUUID, calendarUUID, addEditAppointmentsDTO));
}
@PatchMapping(value = "/{appointmentUUID}")
public ResponseEntity<Void> editCalendarAppointment(
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID,
@PathVariable UUID appointmentUUID,
@Valid @RequestBody AppointmentDTO appointmentDTO){
appointmentServiceImpl.editAppointment(doctorUUID, calendarUUID, appointmentUUID, appointmentDTO);
return ResponseEntity.ok().build();
}
@DeleteMapping(value = "/{appointmentUUID}")
public ResponseEntity<Void> deleteCalendarAppointment(
@PathVariable UUID doctorUUID,
@PathVariable UUID calendarUUID,
@PathVariable UUID appointmentUUID){
appointmentServiceImpl.deleteAppointment(doctorUUID, calendarUUID, appointmentUUID);
return ResponseEntity.ok().build();
}
}
<file_sep>package com.clinics.patient.repository;
import com.clinics.patient.entity.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface PatientRepository extends JpaRepository<Patient, Long> {
Optional<Patient> findByPatientUUID(UUID patientUUID);
Optional<Patient> findById(Long id);
void deleteByPatientUUID(UUID patientUUID);
List<Patient> findAll();
}
<file_sep>import React from "react";
import {FormForInputUserInformation} from "../../AdditionalComponents/FormForInputUserInfo/FormForInputUserInformation";
import {Container} from "@material-ui/core";
import AlertMessage from "../../AdditionalComponents/Alert/AlertMessage";
import ContainerForFormForInputUserInformation
from "../../AdditionalComponents/FormForInputUserInfo/ContainerForFormForInputUserInformation";
export const LoginPage = (props) => {
const {
userDetails,
dispatchUserState,
sendFetchForLoginUser
} = props;
const styleForMainContainer = {
backgroundColor: "white",
margin: "0px",
padding: "0px"
};
//Main HTML return
return (
<Container
style={styleForMainContainer}
>
<AlertMessage
show={userDetails.isError}
onClose={() => {dispatchUserState({type: "CLOSE_ERROR_MASSAGE"})}}
message="Wrong Login Details"
type="error"
/>
<ContainerForFormForInputUserInformation
{...props}
fetchRequest ={(loginDetails) => {sendFetchForLoginUser(loginDetails)}}
primaryLabel ="Zaloguj"
secondaryLabel ="Log In"
showEmailForm ={true}
showPasswordForm ={true}
showFirstNameForm ={false}
showLastNameForm ={false}
showLicenceForm ={false}
showPhotoURLForm ={false}
>
{({
onSubmit,
showEmailForm,
showPasswordForm,
showFirstNameForm,
showLastNameForm,
showLicenceForm,
showPhotoURLForm,
primaryLabel,
secondaryLabel,
submitButtonAvailable,
validation,
handleChange,
setIsCorrectInputInForms
}) => (
<FormForInputUserInformation
onSubmit={onSubmit}
primaryLabel={primaryLabel}
secondaryLabel={secondaryLabel}
showEmailForm={showEmailForm}
showPasswordForm={showPasswordForm}
showFirstNameForm={showFirstNameForm}
showLastNameForm={showLastNameForm}
showLicenceForm={showLicenceForm}
showPhotoURLForm={showPhotoURLForm}
submitButtonAvailable={submitButtonAvailable}
validation={validation}
handleChange={handleChange}
setIsCorrectInputInForms={setIsCorrectInputInForms}
/>
)}
</ContainerForFormForInputUserInformation>
</Container>
);
};
export default LoginPage
<file_sep>import React from "react";
import {Button} from "@material-ui/core";
import ButtonCustomTypography from "../CustomTypography/TypesOfCustomTypography/ButtonCustomTypography";
export const DelAccountBtn = ({fetchRequest}) => {
const delUserBtnOnClick = () => {
fetchRequest();
};
return(
<Button
variant="contained"
color="primary"
disableElevation
fullWidth
onClick={() => delUserBtnOnClick()}
>
<ButtonCustomTypography
primaryLabel={"Usuń konto"}
secondaryLabel={"Delete account"}
/>
</Button>
)
};<file_sep>package com.clinics.doctors.data.model;
import com.fasterxml.jackson.annotation.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.validator.constraints.URL;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.*;
@Data
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Builder(toBuilder = true)
@ToString(exclude = {"calendars", "specializations"})
@DynamicInsert
@DynamicUpdate
//@Builder(toBuilder = true, builderMethodName = "hiddenBuilder")
@Entity(name = "doctor")
public class Doctor {
// public static DoctorBuilder builder(UUID uuid) {
// return hiddenBuilder().uuid(uuid);
// }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@Column(updatable = false,
nullable = false,
unique = true)
private UUID doctorUUID;
@NotBlank(message = "fistName is mandatory")
@Size(min = 2, max = 100, message = "firstName length out of range")
private String firstName;
@NotBlank(message = "lastName is mandatory")
@Size(min = 3, max = 100, message = "lastName length out of range")
private String lastName;
// private int age;
@URL
@Column(unique = true)
@Size(min = 3, max = 500, message = "photoUrl length out of range ")
private String photoUrl;
@Column(unique = true, nullable = false)
private String licence;
@JsonIdentityReference
@ManyToMany(targetEntity = Specialization.class)
@JoinTable(
name = "doctor_specialization",
joinColumns = {@JoinColumn(name = "doctor_id")},
inverseJoinColumns = {@JoinColumn(name = "spacialization_id")})
private Collection<Specialization> specializations;
@OneToMany(
targetEntity= Calendar.class,
mappedBy="doctor",
cascade={CascadeType.REMOVE},
fetch = FetchType.LAZY,
orphanRemoval=true)
private Collection<Calendar> calendars;
// @JsonIgnore
@ElementCollection
private Collection<UUID> patientsUUID;
@ElementCollection
private Collection<UUID> medicalUnitsUUID;
}
<file_sep>import React from 'react';
import {BrowserRouter} from 'react-router-dom';
import {Route, Switch} from "react-router";
import 'bootstrap/dist/css/bootstrap.min.css';
import {AssistantPage} from "./EmployeeComponents/AssistantPage/AssistantPage";
import MainPage from "./MainComponents/MainPage/MainPage";
import ContainerDoctorPage from "./EmployeeComponents/DoctorPage/ReduxContainerDoctorPage";
import DoctorPage from "./EmployeeComponents/DoctorPage/DoctorPage";
import PatientPage from "./EmployeeComponents/PatientPage/PatientPage";
import ContainerPatientPage from "./EmployeeComponents/PatientPage/ReduxContainerPatientPage";
import ThemeProvider from "@material-ui/styles/ThemeProvider";
import AppTheme from "./AppTheme";
/*
TODO:
1. Zmienić nazwę dla typography z custom na customTab
2. Zrobić nowe typography dla buttonów
3. Zamienić je z tymi Typography co są w przyciskach w formie
4. Zrobić nowe typography dla przypisów w miejscach do wypełnienia
*/
const App = () => (
<ThemeProvider theme={AppTheme}>
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path="/">
<MainPage/>
</Route>
<Route path="/doctor">
<ContainerDoctorPage>
{({
doctorPageState,
fetchForDeleteAccount,
fetchForChangeUserInformation,
onClickChangeTabPanel,
userInformation
}) => (
<DoctorPage
doctorPageState={doctorPageState}
fetchForDeleteAccount={fetchForDeleteAccount}
fetchForChangeUserInformation={fetchForChangeUserInformation}
onClickChangeTabPanel={onClickChangeTabPanel}
userInformation={userInformation}
/>
)}
</ContainerDoctorPage>
</Route>
<Route path="/patient">
<ContainerPatientPage>
{({
patientPageState,
userInformation,
onClickChangeTabPanel,
fetchForChangeUserInformation,
fetchForDeleteAccount
}) => (
<PatientPage
patientPageState={patientPageState}
userInformation={userInformation}
onClickChangeTabPanel={onClickChangeTabPanel}
fetchForChangeUserInformation={fetchForChangeUserInformation}
fetchForDeleteAccount={fetchForDeleteAccount}
/>
)}
</ContainerPatientPage>
</Route>
<Route path="/assistant">
<AssistantPage/>
</Route>
</Switch>
</div>
</BrowserRouter>
</ThemeProvider>
);
export default App;
<file_sep>package com.clinics.common.patient;
public enum DiseaseName {
CORONAVIRUS, FLU, ASTHMA
}
<file_sep>import {useEffect, useReducer} from "react";
const ContainerForFormForInputUserInformation = (props) => {
const {
children,
role,
fetchRequest,
showEmailForm,
showPasswordForm,
showFirstNameForm,
showLastNameForm,
showLicenceForm,
showPhotoURLForm,
showPeselForm,
primaryLabel,
secondaryLabel,
userInformation,
submitButtonAdditionalActions = () => {}
} = props;
const setFormState = (state, action) => {
switch (action.type) {
case "SET_USER_INFORMATION":
return {
...state,
userInformation: {
...state.userInformation,
...action.userInformation
}
};
case "SET_CORRECT_INPUT":
return {
...state,
correctInput: {
...state.correctInput,
...action.correctInput
}
};
case "SET_TRUE_CORRECT_INPUT":
return {
...state,
correctInput: {
emailForm: true,
firstNameForm: true,
lastNameForm: true,
licenceForm: true,
passwordForm: true,
peselForm: true,
photoURLForm: true
}
}
case "SET_INPUTS":
return {
...state,
correctInput: action.inputCorrectness
}
case "SET_ON_VALIDATION":
return {
...state,
validation: true
}
case "SET_OFF_VALIDATION":
return {
...state,
validation: false
}
case "SET_ON_BUTTON":
return {
...state,
submitButtonAvailable: true
}
case "SET_OFF_BUTTON":
return {
...state,
submitButtonAvailable: false
}
default:
return state;
}
};
const init = (initialState) => initialState;
const initialState = {
userInformation: {
firstName: null,
lastName: null,
licence: null,
photoUrl: null,
email: null,
password: <PASSWORD>,
pesel: null,
},
correctInput: {
firstNameForm: !showFirstNameForm,
lastNameForm: !showLastNameForm,
licenceForm: !showLicenceForm,
photoUrlForm: !showPhotoURLForm,
emailForm: !showEmailForm,
passwordForm: !showPasswordForm,
peselForm: !showPeselForm,
},
validation: true,
submitButtonAvailable: false
};
const [formComponentState, dispatchFormComponentState] = useReducer(setFormState, initialState, init)
useEffect(() => {
if (secondaryLabel === "Log In"){
dispatchFormComponentState({type: "SET_OFF_VALIDATION"})
} else if (secondaryLabel === "Edit"){
dispatchFormComponentState({type: "SET_TRUE_CORRECT_INPUT"})
}
}, [secondaryLabel]);
useEffect(() => {
if (userInformation !== null){
dispatchFormComponentState({type: "SET_USER_INFORMATION", userInformation: userInformation})
}
}, [userInformation])
useEffect(() => {
const checkCorrectInputInAllFormsForButtonAvailable = () => {
for (const inputCompatibility in formComponentState.correctInput){
if (formComponentState.correctInput.hasOwnProperty(inputCompatibility)){
if (formComponentState.correctInput[inputCompatibility] === false){
return false;
}
}
}
return true;
};
if (checkCorrectInputInAllFormsForButtonAvailable()){
dispatchFormComponentState({type: "SET_ON_BUTTON"})
}else {
dispatchFormComponentState({type: "SET_OFF_BUTTON"})
}
}, [formComponentState.correctInput]);
const setIsCorrectInputInForms = (isInputCorrectObject) => {
dispatchFormComponentState({type: "SET_CORRECT_INPUT", correctInput:isInputCorrectObject})
};
const handleChange = (userInformation) => {
dispatchFormComponentState({type: "SET_USER_INFORMATION", userInformation: userInformation});
};
const onSubmit = (e) => {
e.preventDefault();
fetchRequest({...formComponentState.userInformation, role: role});
submitButtonAdditionalActions();
};
useEffect(() => {
dispatchFormComponentState({
type: "SET_INPUTS",
inputCorrectness: {
firstNameForm: !showFirstNameForm,
lastNameForm: !showLastNameForm,
licenceForm: !showLicenceForm,
photoUrlForm: !showPhotoURLForm,
emailForm: !showEmailForm,
passwordForm: !showPasswordForm,
peselForm: !showPeselForm,
}
})
}, [role, showFirstNameForm,showLastNameForm, showLicenceForm, showPhotoURLForm, showEmailForm, showPasswordForm, showPeselForm,])
return(children({
onSubmit,
showEmailForm,
showPasswordForm,
showFirstNameForm,
showLastNameForm,
showLicenceForm,
showPhotoURLForm,
showPeselForm,
primaryLabel,
secondaryLabel,
submitButtonAvailable: formComponentState.submitButtonAvailable,
validation: formComponentState.validation,
handleChange,
setIsCorrectInputInForms,
userInformation
}))
};
export default ContainerForFormForInputUserInformation<file_sep>import React from "react";
import {Container} from "@material-ui/core";
import {LogOutButton} from "../../AdditionalComponents/LogOutBtn/LogOutButton";
import DoctorInfoComponent from "./DoctorPageComponents/DoctorInfoComponent";
import EditDataFormComponent from "./DoctorPageComponents/EditDataFormComponent";
import DeleteAccountComponent from "./DoctorPageComponents/DeleteAccountComponent";
import AppBar from "@material-ui/core/AppBar";
import TabPanel from "../../AdditionalComponents/TabPanel/TabPanel";
import VisitsComponent from "./DoctorPageComponents/VisitsComponent";
import {StylesTab, StylesTabs} from "../../AdditionalComponents/CustomTab/StylesTab";
import TabCustomTypography from "../../AdditionalComponents/CustomTypography/TypesOfCustomTypography/TabCustomTypography";
//CSS Stylesheet
export const styleForMainDiv = {
marginTop: '30px',
width: '100%'
};
export const styleForMainContainer = {
marginTop: "50px"
};
export const DoctorPage = (props) => {
const {
doctorPageState,
fetchForDeleteAccount,
fetchForChangeUserInformation,
onClickChangeTabPanel,
userInformation
} = props;
//Main HTML return
return (
<Container style={styleForMainDiv}>
<Container>
<LogOutButton/>
</Container>
<Container>
<Container
style={styleForMainContainer}
>
<AppBar position="static">
<StylesTabs
value={doctorPageState.componentToShow}
onChange={onClickChangeTabPanel}
variant="scrollable"
scrollButtons="auto"
>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Wizyty"}
secondaryLabel={"Visits"}
/>
}
/>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Informacje Użytkownika"}
secondaryLabel={"User Information"}
/>
}
/>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Edytowanie danych użytkownika"}
secondaryLabel={"Edit User Information"}
/>
}
/>
<StylesTab
label={
<TabCustomTypography
primaryLabel={"Usuwanie Konta"}
secondaryLabel={"Delete Account"}
/>
}
/>
</StylesTabs>
</AppBar>
<TabPanel value={doctorPageState.componentToShow} index={0}>
<VisitsComponent
calendars={doctorPageState.calendars}
/>
</TabPanel>
<TabPanel value={doctorPageState.componentToShow} index={1}>
<DoctorInfoComponent
doctorInformation={doctorPageState.doctorInformation}
userInformationHasBeenEdit={doctorPageState.userInformationHasBeenEdit}
/>
</TabPanel>
<TabPanel value={doctorPageState.componentToShow} index={2}>
<EditDataFormComponent
fetchRequest={fetchForChangeUserInformation}
userInformation={userInformation}
/>
</TabPanel>
<TabPanel value={doctorPageState.componentToShow} index={3}>
<DeleteAccountComponent
fetchRequest={fetchForDeleteAccount}
/>
</TabPanel>
</Container>
</Container>
</Container>
)
};
export default DoctorPage<file_sep>import {useEffect, useReducer} from "react";
import {URLs} from "../../../URLs";
import {useHistory} from "react-router";
const ContainerLoginPage = ({setStoreUserDetails, children}) => {
//History
let history = useHistory();
//Here we create reducer
const logInUser = (state, action) => {
switch (action.type) {
case "LOGIN_SUCCESS":
return {
...state,
uuid: action.fetchResults.userUUID,
role: action.fetchResults.role
};
case "LOGIN_FAILED":
return {
...state,
isError: true
};
case "CHECK_LOGIN_USER_FAILED":
return state;
case "CLOSE_ERROR_MASSAGE":
return {
...state,
isError: false
};
default:
return state;
}
};
const initialState = {
uuid: null,
role: null,
isError: false
};
const init = (initialState) => initialState;
const [userDetails, dispatchUserState] = useReducer(logInUser, initialState, init);
//Here we have Effects
useEffect(() => {
const redirectAfterChangeRole = () => {
if (userDetails.role){
setStoreUserDetails(userDetails);
history.push(`/${userDetails.role}`);
}};
redirectAfterChangeRole();
}, [userDetails.role, userDetails, setStoreUserDetails, history]);
useEffect(() => {
const sendFetch = async () => {
if (localStorage.token && !userDetails.role){
try {
const init = {
method: 'GET',
body: null,
headers: {'Authorization': localStorage.token}
};
const response = await fetch(URLs.GET_DETAILS_BY_TOKEN, init);
const result = await response.json();
dispatchUserState({
type: "LOGIN_SUCCESS",
fetchResults: {
userUUID: result.userUUID,
role: result.role
}
})
}catch (e) {
dispatchUserState({type: "CHECK_LOGIN_USER_FAILED"})
}
}
};
sendFetch();
}, [userDetails.role]);
//Here we have additional methods
const sendFetchForLoginUser = async (loginDetails) => {
try {
const body = JSON.stringify({
"email":loginDetails.email,
"password":<PASSWORD>
});
const init = {
method: 'POST',
body: body,
headers: {},
};
const response = await fetch(URLs.LOGIN_USER, init);
const result = await response.json();
localStorage.setItem("token", result.token);
dispatchUserState({
type: "LOGIN_SUCCESS",
fetchResults: {
userUUID: result.userUUID,
role: result.role
}
});
} catch (e) {
dispatchUserState({type: "LOGIN_FAILED"});
}
};
return (
children({
userDetails,
dispatchUserState,
sendFetchForLoginUser
})
)
};
export default ContainerLoginPage;
|
86ba08a34083b8ec7c3c5bcc18c429caf15e7783
|
[
"JavaScript",
"Java",
"Markdown",
"INI"
] | 82
|
Java
|
WojciechAdamowski/Microservices-Clinic
|
d32ddeafb36679aaad71cd43a12fb09462bf0447
|
c4f149dc515dd665b2f8cc4d0744f41b22061a82
|
refs/heads/master
|
<repo_name>yc322/talent-plan<file_sep>/tidb/mergesort/mergesort.go
package main
// MergeSort performs the merge sort algorithm.
// Please supplement this function to accomplish the home work.
//func main() {
// input := []int64{0,1,5,3,4,2}
// MergeSort(input)
// fmt.Println(input)
//}
func MergeSort(src []int64) {
ch := make(chan int, 1)
defer close(ch)
process(src, 0, len(src)-1, ch)
}
func process(src []int64, left int, right int, c chan int) {
if left < right {
ch := make(chan int, 2)
defer close(ch)
mid := left + (right - left) >>1
// fmt.Println(mid)
go process(src, left, mid,ch)
go process(src, mid+1, right,ch)
<- ch
<- ch
merge(src, left, mid, right)
}
c <- 1
}
func merge(src []int64, left int, mid int, right int) {
help := make([]int64, right-left+1)
p1, p2 := left, mid+1
index := 0
for ; p1 <= mid && p2 <= right; {
if src[p1] < src[p2] {
help[index] = src[p1]
index ++
p1++
} else {
help[index] = src[p2]
index ++
p2 ++
}
}
for ; p1 <= mid; {
help[index] = src[p1]
index ++
p1 ++
}
for ; p2 <= right; {
help[index] = src[p2]
index++
p2 ++
}
for j := 0; j < len(help); j++ {
src[left+j] = help[j]
}
}
|
16e69247796ec6cf0a3e4ffb3018ec13b5e0fec1
|
[
"Go"
] | 1
|
Go
|
yc322/talent-plan
|
b02836cdfe8669e11aeeaf3e40e786f9e71e6a8f
|
cd5dcf06c891c832f918a791b719fd8179ab73e5
|
refs/heads/master
|
<file_sep>#include "paths.h"
#include <boost/filesystem/operations.hpp>
#ifdef WIN32
#include <shlobj.h>
// #include <direct.h> <-- to tez?
static std::string get_folder_path(DWORD id) {
char path[MAX_PATH] = { 0 };
SHGetFolderPath(
NULL, // hwnd
id, // CSIDL_FOO
NULL, // access token,
0, // current location
path ); // buffer
return path;
};
#endif
boost::filesystem::path base_path() {
#ifdef WIN32
boost::filesystem::path base(get_folder_path(CSIDL_APPDATA));
return base;
#else
return boost::filesystem::path();
#endif
}
const boost::filesystem::path ekhem::path::sites = base_path()/"sites";
const boost::filesystem::path ekhem::path::output = base_path()/"output";
const boost::filesystem::path ekhem::path::data = base_path()/"data";
void ekhem::path::create_directories() {
namespace bf = boost::filesystem;
if(!bf::exists(sites));
bf::create_directory(sites);
if(!bf::exists(output));
bf::create_directory(output);
if(!bf::exists(data));
bf::create_directory(data);
}
<file_sep>#include "page.h"
#include "exceptions.h"
#include "entity.h"
#include <boost/filesystem/path.hpp>
#include <buffio.h> // Tidy ma zjebane te naglowki
bool is_html(const std::string& content) {
return (content.find("text/html") != std::string::npos);
}
Bool ignore(TidyDoc tdoc, TidyReportLevel lvl, uint line, uint col, ctmbstr mssg ) {
return no;
}
TidyDoc tidy_create() {
TidyDoc ret = tidyCreate();
// Dokumentacja Tidy k#@$@sko dokladnie opisuje wartosci zwracane z tych
// funkcji.
tidySetReportFilter(ret, ignore);
tidySetCharEncoding(ret, "raw");
return ret;
};
Page::Page(const Entity& page) : tree(NULL) {
if(!is_html(page.get_content_type())) {
throw ekhem::entity_is_not_webpage(page.get_content_type() + " " + page.get_url());
}
tree = tidy_create();
tidyParseString(tree, page.get_text().c_str());
}
Page::Page(const boost::filesystem::path& path) : tree(tidy_create()) {
tidyParseFile(tree, path.string().c_str());
}
Page::~Page() {
if(tree)
tidyRelease(tree);
}
const TidyNode Page::root() const {
assert(tree);
return tidyGetRoot(tree);
}
TidyDoc& Page::document() {
return tree;
}
<file_sep>#ifndef EKHEM_URI_H
#define EKHEM_URI_H
#include <string>
namespace ekhem {
std::string build_uri(const std::string& uri, const std::string& base);
} // namespace
#endif
<file_sep>#ifndef EKHEM_EXCEPTIONS_H
#define EKHEM_EXCEPTIONS_H
#include <stdexcept>
namespace ekhem {
class entity_is_not_webpage : public std::runtime_error {
public:
entity_is_not_webpage(const std::string& what) : std::runtime_error(what) {}
};
class configuration_not_found : public std::runtime_error {
public:
configuration_not_found(const std::string& what) : std::runtime_error(what) {}
};
} // namespace
#endif
<file_sep>#ifndef EKHEM_SITE_H
#define EKHEM_SITE_H
#include "page.h"
#include <boost/filesystem/path.hpp>
#include <boost/smart_ptr.hpp>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <tidy.h>
/** Reprezentacja obserwowanej strony.
* Odczytuje konfiguracje strony, pobiera ją i udostępnia nowe linki
*/
class Site {
typedef std::set<std::string> simple_links_container;
typedef std::map<std::string, std::string> links_container;
public:
typedef links_container::const_iterator const_links_iterator;
private:
boost::scoped_ptr<Page> page;
boost::scoped_ptr<Page> pattern;
std::vector<std::string> urls;
std::string links_hash;
links_container new_links;
simple_links_container previous_links;
void find_all_links(TidyNode, const std::string& url);
void load_previous_links();
void prepare_links();
public:
Site(const boost::filesystem::path&);
const_links_iterator links_begin() const;
const_links_iterator links_end() const;
void save_links();
bool has_pattern() const;
const TidyNode get_pattern() const;
};
#endif
<file_sep>#include "uri.h"
#include <libxml/uri.h>
std::string ekhem::build_uri(const std::string& uri, const std::string& base) {
xmlChar* r = xmlBuildURI(reinterpret_cast<const unsigned char*>(uri.c_str()), reinterpret_cast<const unsigned char*>(base.c_str()));
std::string ret(reinterpret_cast<const char*>(r));
xmlFree(r);
return ret;
}
<file_sep>#ifndef EKHEM_PATHS_H
#define EKHEM_PATHS_H
#include <boost/filesystem/path.hpp>
namespace ekhem {
namespace path {
extern const boost::filesystem::path sites;
extern const boost::filesystem::path output;
extern const boost::filesystem::path data;
void create_directories();
}
}
#endif
<file_sep>#include "site.h"
#include "entity.h"
#include "uri.h"
#include "exceptions.h"
#include "utils.h"
#include "search.h"
#include "paths.h"
#include <fstream>
#include <iostream>
#include <boost/filesystem/operations.hpp>
Site::Site(const boost::filesystem::path& path) {
using namespace boost::filesystem;
links_hash = ekhem::hash(path.string());
std::ifstream config((path/"config.txt").string().c_str());
if(!config.good())
throw ekhem::configuration_not_found((path/"config.txt").string());
while(true) {
std::string url;
config >> url;
if(config.good())
urls.push_back(url);
else break;
}
// FIXME: w konfiguracji nie ma adresow, moze inny wyjatek rzucic.
if(urls.empty() || urls[0].empty())
throw ekhem::configuration_not_found((path/"config.txt").string());
if (exists(path/"pattern.html")) {
pattern.reset(new Page(path/"pattern.html"));
}
prepare_links();
}
void Site::find_all_links(TidyNode parent, const std::string& url) {
TidyNode child;
for ( child = tidyGetChild(parent); child; child = tidyGetNext(child) ) {
if(tidyNodeIsA(child)) {
TidyAttr href = tidyAttrGetHREF(child);
if(!href) continue;
if(!tidyAttrValue(href)) continue;
std::string link = ekhem::build_uri(tidyAttrValue(href), url);
if(link.find("http://") != 0)
continue;
std::string title = ekhem::get_node_text(page->document(), child);
if(previous_links.count(link)==0) {
if(new_links[link].empty()) {
new_links[link] = title;
}
}
}
find_all_links( child, url );
}
}
void Site::prepare_links() {
load_previous_links();
for(std::vector<std::string>::const_iterator i = urls.begin(); i!=urls.end(); ++i) {
try {
Entity ent(*i);
page.reset(new Page(ent));
find_all_links(page->root(), ent.get_url());
} catch (const std::runtime_error&e) {
// FIXME: zrobic to jak bozia przykazala
// skip wrong entries
}
}
}
void Site::load_previous_links() {
using namespace boost::filesystem;
path links(ekhem::path::data);
links/=links_hash;
std::cout << links.string() << std::endl;
if(!exists(links))
return;
std::ifstream file(links.string().c_str());
while(file.good()) {
std::string link;
file >> link;
if(!link.empty())
previous_links.insert(link);
}
}
Site::const_links_iterator Site::links_begin() const {
return new_links.begin();
}
Site::const_links_iterator Site::links_end() const {
return new_links.end();
}
bool Site::has_pattern() const {
return pattern;
}
const TidyNode Site::get_pattern() const {
assert(pattern);
return pattern->root();
}
void Site::save_links() {
// FIXME: funkcja nie jest exception safe
using namespace boost::filesystem;
path links(ekhem::path::data);
links/=links_hash;
std::ofstream file(links.string().c_str());
for(const_links_iterator i=new_links.begin(); i!=new_links.end(); ++i) {
previous_links.insert(i->first);
}
for(simple_links_container::const_iterator i=previous_links.begin(); i!=previous_links.end(); ++i) {
file << *i << std::endl;
}
}
<file_sep>#ifndef EKHEM_UTILS_H
#define EKHEM_UTILS_H
#include <string>
#include <boost/lexical_cast.hpp>
namespace ekhem {
std::string hash(const std::string& input) {
const unsigned char* str = reinterpret_cast<const unsigned char*>(input.c_str());
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return boost::lexical_cast<std::string>(hash);
}
} // namespace
#endif
<file_sep>#include <iostream>
#include <fstream>
#include "entity.h"
#include "uri.h"
#include "page.h"
#include "site.h"
#include "search.h"
#include "exceptions.h"
#include "paths.h"
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string/replace.hpp>
class Output {
std::ofstream out;
public:
explicit Output(const boost::filesystem::path& outdir) : out((outdir/"output.html").string().c_str()) {
out << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" << std::endl;
out << " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" << std::endl;
out << "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"pl\" xml:lang=\"pl\">" << std::endl;
out << "<head>" << std::endl;
out << "<meta name=\"robots\" content=\"noindex, nofollow\" />" << std::endl;
out << "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" << std::endl;
out << "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\"/>" << std::endl;
out << "</head>" << std::endl;
out << "<body>" << std::endl;
}
~Output() {
out << "</body>" << std::endl;
out << "</html>" << std::endl;
}
void site_begin(const std::string& site_name) {
out << "<h1>" << site_name << "</h1>" << std::endl;
}
void site_end() {}
void site_no_config() {
out << "<p><em>Nie znaleziono pliku konfiguracji.</em></p>" << std::endl;
}
void not_a_webpage() {
out << "<p><em>Ten link nie wskazuje na strone o zawartosci tex/html.</em></p>" << std::endl;
}
void site_link(const std::string& url, const std::string& title=std::string()) {
out << "<h2><a href=\"" << url << "\">";
if(title.empty())
out << url;
else
out << title;
out << "</a></h2>" << std::endl;
}
void site_text(const std::string& text) {
std::string f(text);
boost::algorithm::replace_all(f, "\n", "<br/>");
out << "<p>" << f << "</p>" << std::endl;
}
void site_images(const std::set<std::string>& images) {
if(images.empty())
return;
out << "<h3>Obrazy</h3>" << std::endl;
for(std::set<std::string>::const_iterator i=images.begin(); i!=images.end(); ++i) {
out << "<a href=\"" << *i << "\">" << *i << "</a>" << std::endl;
}
}
};
void process_site(const Site& site, const std::string& url, const std::string& label, Output& output) {
std::cout << " nowy link: " << url << std::endl;
output.site_link(url, label);
if(site.has_pattern()) {
try {
Entity entity(url);
Page linked(entity);
std::set<std::string> images1, images;
std::string summary = ekhem::extract_summary(linked.document(), site.get_pattern(), images1);
for(std::set<std::string>::const_iterator img=images1.begin(); img!=images1.end(); ++img) {
images.insert(ekhem::build_uri(*img, entity.get_url()));
}
std::cout << " tresc: " << summary;
output.site_text(summary);
std::cout << std::endl;
std::cout << " obrazki: " << std::endl;
std::copy(images.begin(), images.end(), std::ostream_iterator<std::string>(std::cout, "\n "));
output.site_images(images);
} catch (const ekhem::entity_is_not_webpage& e) {
output.not_a_webpage();
std::cout << " to nie jest text/html" << std::endl;
}
}
}
// brzydki-brzydki main
int main() try {
namespace bf = boost::filesystem;
ekhem::path::create_directories();
Output output(ekhem::path::output);
bf::directory_iterator end;
for(bf::directory_iterator i(ekhem::path::sites); i!=end; ++i) {
// FIXME: hidden files under windows
if(i->leaf()[0]=='.') continue;
std::cout << "Przetwarzanie '" << i->leaf() << "'..." << std::endl;
output.site_begin(i->leaf());
try {
Site site(*i);
for(Site::const_links_iterator i = site.links_begin(); i!=site.links_end(); ++i) {
process_site(site, i->first, i->second, output);
}
site.save_links();
} catch(const ekhem::configuration_not_found& e) {
output.site_no_config();
std::cout << " nie znaleziono pliku konfiguracji '" << e.what() << "'" << std::endl;
}
output.site_end();
std::cout << std::endl;
}
} catch (const std::exception& e) {
std::cout << "Wystapil blad, dzialanie programu zostanie zakonczone: " << std::endl;
std::cout << " " << e.what() << std::endl;
}
<file_sep>#include "search.h"
#include <iostream>
#include <buffio.h> // to jest z lib Tidy
std::string ekhem::get_node_text(TidyDoc& input_document, TidyNode input) {
std::string ret;
TidyNode child;
for ( child = tidyGetChild(input); child; child = tidyGetNext(child) ) {
if(tidyNodeIsText(child)) {
TidyBuffer buffer = {0};
tidyNodeGetText(input_document, child, &buffer);
ret += reinterpret_cast<char*>(buffer.bp);
}
ret += get_node_text( input_document, child );
}
return ret;
}
void get_node_images(TidyDoc& input_document, TidyNode input, std::set<std::string>& images) {
TidyNode child;
for ( child = tidyGetChild(input); child; child = tidyGetNext(child) ) {
if(tidyNodeIsIMG(child)) {
if(tidyAttrGetSRC(child)) {
images.insert(tidyAttrValue( tidyAttrGetSRC(child) ) );
}
}
get_node_images( input_document, child, images);
}
}
std::string find_difference(TidyDoc& input_document, TidyNode input_node, TidyNode pattern_node, std::set<std::string>& images) {
std::string ret;
if(!input_node || !pattern_node)
return ret;
TidyNode in_child = tidyGetChild(input_node);
TidyNode pt_child = tidyGetChild(pattern_node);
for(; in_child && pt_child; in_child = tidyGetNext(in_child), pt_child = tidyGetNext(pt_child) ) {
if(tidyNodeIsDIV(pt_child) &&
tidyAttrGetTITLE(pt_child) &&
tidyAttrValue( tidyAttrGetTITLE(pt_child)) == std::string("ekhem-extract"))
{
in_child = tidyGetPrev(in_child); // FIXME: no idea why i have to do it :/
while(in_child) {
ret += ekhem::get_node_text(input_document, in_child);
get_node_images(input_document, in_child, images);
in_child = tidyGetNext(in_child);
}
break;
}
ret += find_difference(input_document, in_child, pt_child, images);
}
return ret;
}
std::string ekhem::extract_summary(TidyDoc& document, TidyNode pattern, std::set<std::string>& images) {
images.clear();
std::string ret = find_difference(document, tidyGetRoot(document), pattern, images);
return ret;
}
<file_sep>#ifndef EKHEM_PAGE
#define EKHEM_PAGE
#include <tidy.h>
namespace boost {
namespace filesystem {
class path;
}
}
class Entity;
/** Strona HTML.
* Pobiera strone i udostępnia jej drzewo HTML.
*/
class Page {
TidyDoc tree;
public:
explicit Page(const Entity& entity);
explicit Page(const boost::filesystem::path& path);
~Page();
const TidyNode root() const;
TidyDoc& document();
};
#endif
<file_sep>#ifndef EKHEM_ENTITY_H
#define EKHEM_ENTITY_H
#include <curl/curl.h>
#include <string>
#include <vector>
/** Obiekt pobierany przez HTTP. */
class Entity {
static const int curl_max_redirs = 5;
static int init_lib_curl;
CURL* handle;
const std::string url;
char error_buffer[CURL_ERROR_SIZE];
std::vector<char> input_buffer;
static size_t write_function(void* ptr, size_t size, size_t nmemb, void* data);
void dealloc();
void throw_on_error(const std::string& where, CURLcode code) const;
public:
Entity(const std::string& url);
~Entity();
std::string get_content_type() const;
std::string get_url() const;
std::string get_text() const;
const std::vector<char>& get_data() const;
};
#endif
<file_sep>#include "entity.h"
#include <stdexcept>
#include <cassert>
#include <boost/lexical_cast.hpp>
/** inicjalizacja curl'a.
* @note nie wolam nigdzie curl_global_cleanup, bo koncze program po zabawie
* z curlem
*/
int Entity::init_lib_curl = curl_global_init(CURL_GLOBAL_WIN32);
void Entity::throw_on_error(const std::string& where, CURLcode code) const {
if(code != CURLE_OK) {
if(code == CURLE_FAILED_INIT)
throw std::runtime_error(where + ", code: CURL_ERROR_FAILED_INIT");
throw std::runtime_error(where + ", code: " + boost::lexical_cast<std::string>(code)+"\n"+error_buffer);
}
}
Entity::Entity(const std::string& url_): handle(NULL), url(url_) {
error_buffer[0]='\x0';
try {
handle = curl_easy_init();
if(!handle)
throw std::runtime_error("Unable to create CURL handle");
curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, error_buffer);
throw_on_error("CURLOPT_WRITEFUNCTION", curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &Entity::write_function));
throw_on_error("CURLOPT_WRITEDATA", curl_easy_setopt(handle, CURLOPT_WRITEDATA, this));
throw_on_error("CURLOPT_NOPROGRESS", curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 1));
throw_on_error("CURLOPT_AUTOREFERER", curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1));
throw_on_error("CURLOPT_FOLLOWLOCATION",curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1));
throw_on_error("CURLOPT_MAXREDIRS", curl_easy_setopt(handle, CURLOPT_MAXREDIRS, curl_max_redirs));
throw_on_error("CURLOPT_URL", curl_easy_setopt(handle, CURLOPT_URL, url.c_str()));
// download data from url
throw_on_error("curl_easy_perform", curl_easy_perform(handle));
} catch(...) {
dealloc();
throw;
}
}
void Entity::dealloc() {
if(handle) {
curl_easy_cleanup(handle);
handle=NULL;
}
}
Entity::~Entity() {
dealloc();
}
size_t Entity::write_function(void* ptr, size_t size, size_t nmemb, void* data) {
assert(data && "Pointer to an Entity object was not given");
Entity& entity = *static_cast<Entity*>(data);
std::vector<char>& buffer = entity.input_buffer;
char* in = static_cast<char*>(ptr);
buffer.insert(buffer.end(), in, in+size*nmemb);
return size*nmemb;
}
std::string Entity::get_text() const {
return std::string(input_buffer.begin(), input_buffer.end());
}
std::string Entity::get_url() const {
assert(handle);
char* effective_url=NULL;
throw_on_error( "CURLINFO_EFFECTIVE_URL", curl_easy_getinfo(handle, CURLINFO_EFFECTIVE_URL, &effective_url) );
return std::string(effective_url);
}
std::string Entity::get_content_type() const {
assert(handle);
char* content=NULL;
throw_on_error( "CURLINFO_CONTENT_TYPE", curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &content) );
return std::string(content);
}
const std::vector<char>& Entity::get_data() const {
return input_buffer;
}
<file_sep>
# Libraries to link against
LIBS=-ltidy -lboost_filesystem
LIBS+=$(shell pkg-config --libs libcurl libxml-2.0)
# Local include paths
INCLUDE=-I.
# Compilation flags
CFLAGS=-Wall
## example:
CFLAGS+=$(shell pkg-config --cflags libcurl libxml-2.0)
# Target binaries
PROGS=ekhem
# Source files' extension
EXT=cc
# Compiler
GCC=g++
######################################
# You shouldn't need to modify these #
######################################
CC=${GCC} ${INCLUDE} ${CFLAGS}
LINK=${GCC}
GENDEP=${GCC} -MM ${INCLUDE} ${CFLAGS}
OBJS:=$(patsubst %.${EXT},%.o, $(wildcard *.${EXT}))
DEPS:=$(patsubst %.${EXT},.%.d, $(wildcard *.${EXT}))
.PHONY: all
all: ${PROGS}
@ echo Build complete
.%.d: %.${EXT}
@ echo DEP $<
@ ${GENDEP} $< | sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' > $@
${PROGS}: ${DEPS} ${OBJS}
@ echo LINK $@
@ ${LINK} ${OBJS} ${LIBS} ${LFLAGS} -o $@
@ strip $@
${OBJS}: %.o: %.${EXT}
@ echo CC $<
@ ${CC} -c $<
REALDEPS:=$(wildcard .*.d)
ifneq ($(strip $(REALDEPS)),)
include ${REALDEPS}
endif
.PHONY: clean
clean:
@ echo CLEAN ${PROGS}
@ rm -f ${PROGS}
@ echo CLEAN ${OBJS}
@ rm -f ${OBJS}
@ echo CLEAN ${DEPS}
@ rm -f ${DEPS}
<file_sep>#ifndef EKHEM_SEARCH_H
#define EKHEM_SEARCH_H
#include <string>
#include <set>
#include <tidy.h> // to jest z lib Tidy
namespace ekhem {
std::string get_node_text(TidyDoc& input_document, TidyNode input);
std::string extract_summary(TidyDoc& document, TidyNode pattern, std::set<std::string>& images);
} // namespace
#endif
|
a0ceaac0f5a29fe9491d7ec8a0556ebf5a4cdd43
|
[
"Makefile",
"C++"
] | 16
|
C++
|
qsorix/ekhem
|
afdb0ba841d50bb985e641d1bd792bc2e4388a9d
|
7400cdee00bfded82e3ba808f8fe75636e8bfe0c
|
refs/heads/main
|
<repo_name>gunn3r71/firstProjectAtDevmedia<file_sep>/calculo.php
<?php
$html = "<div class='container' id='result'>";
if($_POST) {
$distance = $_POST['distance'];
$consumption = $_POST['consumption'];
if(is_numeric($distance) && is_numeric($consumption)){
if($distance > 0 && $consumption > 0) {
$valorGasolina = 4.36;
$valorDiesel = 4.46;
$valorAlcool = 4.05;
$calculoGasolina = number_format(($distance / $consumption) * $valorGasolina,2,',','.');
$calculoDiesel = number_format(($distance / $consumption) * $valorDiesel,2,',','.');
$calculoAlcool = number_format(($distance / $consumption) * $valorAlcool,2,',','.');
$html .= '<table class="table table-dark table-stripped">
<thead>
<tr>
<th scope="col">Gasolina</th>
<th scope="col">Diesel</th>
<th scope="col">Alcool</th>
</tr>
</thead>
<tbody>
<tr>';
$html .= "<td>R$".$calculoGasolina."</td>";
$html .= "<td>R$".$calculoDiesel."</td>";
$html .= "<td>R$".$calculoAlcool."</td>";
$html .= '</tr>
<tr><td colspan="3"><a href="./index.php" role="button" id="voltar" class="btn btn-md">Refazer calculo</a></td></tr>
</tbody>
</table>';
$html .= "</div>";
$html .= "</div>";
$html .= "</div>";
} else {
$html.="<h1>Não é possível realizar o cálculo</h1><p>os valores inseridos são menores ou iguais a zero</p>";
$html.='<a href="./index.php" role="button" id="message-back" class="btn-link">Refazer calculo</a></div>';
}
} else {
$html.="<h1>Valores inválidos</h1><p>Os valores informados não são numéricos</p>";
$html.='<a href="./index.php" role="button" id="message-back" class="btn-link">Refazer calculo</a></div>';
}
} else {
$html.="<h1>Erro</h1><p>Não existem dados para realizar o cálculo</p>";
$html.='<a href="./index.php" role="button" id="message-back" class="btn-link">Refazer calculo</a></div>';
}
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link href="assets/css/index.css" rel="stylesheet">
<title>Projeto DevMedia PHP</title>
</head>
<body>
<?php
echo $html;
?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
|
5446aed98a18771e4de02568475e4fee69fdaede
|
[
"PHP"
] | 1
|
PHP
|
gunn3r71/firstProjectAtDevmedia
|
38061f3b58b7679edfff635a70e4874dc9cd0903
|
10679bea8bcf344caac2b72fa6748b7afd35e894
|
refs/heads/master
|
<repo_name>yurafey/waggr<file_sep>/src/Tests/DataLayerTest.java
package Tests;
import BusinessLogic.User;
import DataAccessLayer.UserGateway;
import org.junit.Test;
import static org.junit.Assert.*;
public class DataLayerTest {
private UserGateway userGateway = new UserGateway();
@Test
public void testNewGetDeleteUser() {
String login = "testUser";
String password = "<PASSWORD>";
String name = "testUserName";
String surname = "testUserSurname";
String cityName = "testUserCity";
String countryName = "testUserCountry";
assertTrue(userGateway.newUser(login, password, name, surname, cityName, countryName));
User checkUser = userGateway.getUser(login);
assertEquals("testUser", checkUser.getUserLogin());
assertEquals("testUserPassword", checkUser.getUserPassword());
assertEquals("testUserName", checkUser.getUserName());
assertEquals("testUserSurname",checkUser.getUserSurname());
assertEquals("testUserCity",checkUser.getUserCity());
assertEquals("testUserCountry", checkUser.getUserCountry());
assertTrue(userGateway.deleteUser(login));
}
@Test
public void testUpdateUser() throws Exception {
User newUser = new User();
newUser.setUserLogin("testUser1");
newUser.setUserPassword("<PASSWORD>");
newUser.setUserName("testUserName1");
newUser.setUserSurname("testUserSurname1");
newUser.setUserCity("testUserCity1");
newUser.setUserCountry("testUserCountry1");
assertTrue(userGateway.newUser("testUser", "1", "2", "3", "4", "5"));
assertTrue(userGateway.updateUser("testUser", newUser));
assertNull(userGateway.getUser("testUser"));
User checkUser = userGateway.getUser("testUser1");
assertEquals("testUser1", checkUser.getUserLogin());
assertEquals("testUserPassword1", checkUser.getUserPassword());
assertEquals("testUserName1", checkUser.getUserName());
assertEquals("testUserSurname1", checkUser.getUserSurname());
assertEquals("testUserCity1",checkUser.getUserCity());
assertEquals("testUserCountry1",checkUser.getUserCountry());
assertTrue(userGateway.deleteUser("testUser1"));
}
}<file_sep>/src/ServiceLayer/WeatherCurrentTableService.java
package ServiceLayer;
import BusinessLogic.RealFeel;
import BusinessLogic.Weather;
import BusinessLogic.WeatherWorker;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by yuraf_000 on 19.09.2014.
*/
public class WeatherCurrentTableService {
private WeatherWorker weatherWorker = null;
private List<RealFeel> realFeelList = null;
private String[] colNames = null;
private List<Object> rows = new ArrayList<>();
private int numOfRealFeels = 1;
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
@Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
public WeatherCurrentTableService(String login, String cityName, String countryName) {
RealFeelService realFeelService = new RealFeelService(login, cityName, countryName);
realFeelList = realFeelService.getRealFeels(numOfRealFeels);
colNames = new String[]{"", "Yandex", "WeatherUA", "RealFeel(ощущается)"};
weatherWorker = new WeatherWorker(cityName, countryName);
TableProcessor();
}
public void TableProcessor (){
Weather currentWeatherYandex = weatherWorker.getCurrentWeatherYandex();
Weather currentWeatherWUA = weatherWorker.getCurrentWeatherWUA();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM HH:mm", myDateFormatSymbols );
rows.clear();
rows.add(Arrays.asList("Дата",(currentWeatherYandex!=null)?dateFormat.format(currentWeatherYandex.getDate()):"N/A", ((currentWeatherWUA!=null)?dateFormat.format(currentWeatherWUA.getDate()):"N/A"), (realFeelList!=null? (dateFormat.format(realFeelList.get(0).getDate())+" от "+realFeelList.get(0).getUserLogin()):"N/A")));
rows.add(Arrays.asList("Температура",(currentWeatherYandex!=null)?currentWeatherYandex.getTemperature():"N/A", ((currentWeatherWUA!=null)?currentWeatherWUA.getTemperature():"N/A"), (realFeelList!=null?(realFeelList.get(0).getTemperature()):"N/A")));
rows.add(Arrays.asList("Влажность", (currentWeatherYandex!=null)?currentWeatherYandex.getHumidity():"N/A", ((currentWeatherWUA!=null)?currentWeatherWUA.getHumidity():"N/A"),(realFeelList!=null?(realFeelList.get(0).getHumidity()):"N/A")));
rows.add(Arrays.asList("Атмосферное давление",(currentWeatherYandex!=null)?currentWeatherYandex.getPressure():"N/A", ((currentWeatherWUA!=null)?currentWeatherWUA.getPressure():"N/A"),(realFeelList!=null?(realFeelList.get(0).getPressure()):"N/A")));
rows.add(Arrays.asList("Скорость ветра", (currentWeatherYandex!=null)?currentWeatherYandex.getWindSpeed():"N/A", ((currentWeatherWUA!=null)?currentWeatherWUA.getWindSpeed():"N/A"),(realFeelList!=null?(realFeelList.get(0).getWindSpeed()):"N/A")));
rows.add(Arrays.asList("Направление ветра", (currentWeatherYandex!=null)?currentWeatherYandex.getWindDirection():"N/A", ((currentWeatherWUA!=null)?currentWeatherWUA.getWindDirection():"N/A"),(realFeelList!=null?(realFeelList.get(0).getWindDirection()):"N/A")));
}
public void setNumOfRealFeels(int numOfRealFeels) {
this.numOfRealFeels = numOfRealFeels;
}
public int getNumOfRealFeels() {
return numOfRealFeels;
}
public Object GetValueAt(int row,int col){
return ((List<Object>)rows.get(row)).get(col);
}
public String[] getColNames() {
return colNames;
}
public List<Object> getRows() {
return rows;
}
public void onClose(){
//
}
}
<file_sep>/src/PresentationLayer/RealFeelForm.java
package PresentationLayer;
import ServiceLayer.RealFeelService;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by URI on 09.01.2015.
*/
public class RealFeelForm extends JFrame{
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JTextField textField4;
private JButton ОКButton;
private JButton cancelButton;
private JPanel rootPanel;
private JLabel label1;
private RealFeelService realFeelService = null;
public RealFeelForm(RealFeelService realFeelService) {
this.realFeelService = realFeelService;
label1.setText(label1.getText() + realFeelService.getCurrentUserCityName());
setTitle("Добавить ощущуение о погоде");
setSize(350,200);
setLocationRelativeTo(null);
setContentPane(rootPanel);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
addListeners();
setVisible(true);
}
private void addListeners() {
ОКButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String temperature = textField1.getText();
String pressure = textField2.getText();
String humidity = textField3.getText();
String windSpeed = textField4.getText();
int temperature1;
int pressure1;
int humidity1;
float windSpeed1;
if (temperature.isEmpty()||pressure.isEmpty()||humidity.isEmpty()||windSpeed.isEmpty()) {
JOptionPane.showMessageDialog(rootPanel,"Заполните все поля!","Ошибка",JOptionPane.INFORMATION_MESSAGE);
return;
}
try {
temperature1 = Integer.parseInt(temperature);
pressure1 = Integer.parseInt(pressure);
humidity1 = Integer.parseInt(humidity);
windSpeed1 = Float.parseFloat(windSpeed);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(rootPanel,"Неправильные данные. Проверьте заполненные поля.","Ошибка",JOptionPane.INFORMATION_MESSAGE);
return;
}
if (!realFeelService.newRealFeel(temperature1,pressure1,humidity1,windSpeed1)) {
JOptionPane.showMessageDialog(rootPanel,"Введенные данные слишком неправдоподобны.","Ошибка",JOptionPane.INFORMATION_MESSAGE);
return;
}
dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
}
<file_sep>/src/BusinessLogic/Admin.java
package BusinessLogic;
import DataAccessLayer.AdminGateway;
/**
* Created by URI on 12.01.2015.
*/
public class Admin {
private AdminGateway adminGateway = new AdminGateway();
public String getCurrentRefreshPeriod() {
return adminGateway.getCurrentPeriod();
}
public String getCurrentCountriesToRefresh() {
return adminGateway.getCurrentCountries();
}
public boolean setCurrentRefreshPeriod(String currentPeriod) {
return adminGateway.setCurrentPeriod(currentPeriod);
}
public boolean setCurrentCountriesToRefresh(String countryNames) {
return adminGateway.setCurrentCountries(countryNames);
}
}
<file_sep>/src/Parsers/CityIdParserWUA.java
package Parsers;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
/**
* Created by yuraf_000 on 05.06.2014.
*/
public class CityIdParserWUA {
private HashMap<Integer,String> CityIdName = new HashMap<>();
private String url;
public CityIdParserWUA(String url){
this.url = url;
try {
URL UrlToParse = new URL(url);
DOMParser p = new DOMParser();
p.parse(new InputSource(UrlToParse.openStream()));
Document doc = p.getDocument();
NodeList nodeLst = doc.getElementsByTagName("city");
for (int i = 1; i < nodeLst.getLength(); i++) {
Element e = (Element) nodeLst.item(i);
Integer CityId = Integer.parseInt(e.getAttribute("id"));
String CityName = (((Element) nodeLst.item(i)).getElementsByTagName("name")).item(0).getTextContent();
//System.out.println(CountryNameId + " " + CountryName);
CityIdName.put(CityId, CityName);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public HashMap<Integer,String> GetCitiesId(){
return CityIdName;
}
}
<file_sep>/src/DataAccessLayer/AdminGateway.java
package DataAccessLayer;
import java.sql.*;
/**
* Created by URI on 14.01.2015.
*/
public class AdminGateway {
private Connection waggrConnection = null;
public AdminGateway() {
try {
Class.forName("org.postgresql.Driver");
waggrConnection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/waggrdb", "waggr",
"waggr");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
return;
}
}
public void connectionClose() {
try {
waggrConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getCurrentCountries() {
try {
Statement CheckLogin = waggrConnection.createStatement();
ResultSet Res = CheckLogin.executeQuery("SELECT country_name FROM users WHERE login ='admin';");
if (Res.next()) return Res.getString(1);
Res.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public String getCurrentPeriod() {
try {
Statement CheckLogin = waggrConnection.createStatement();
ResultSet Res = CheckLogin.executeQuery("SELECT city_name FROM users WHERE login ='admin';");
if (Res.next()) return Res.getString(1);
Res.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean setCurrentCountries(String countriesList) {
try {
String stm = "UPDATE users SET country_name = ? WHERE login = 'admin'";
PreparedStatement pst = waggrConnection.prepareStatement(stm);
pst.setString(1,countriesList);
int i = pst.executeUpdate();
if (i!=0) {
pst.close();
return true;
}
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean setCurrentPeriod(String period) {
try {
String stm = "UPDATE users SET city_name = ? WHERE login = 'admin'";
PreparedStatement pst = waggrConnection.prepareStatement(stm);
pst.setString(1,period);
int i = pst.executeUpdate();
if (i!=0) {
pst.close();
return true;
}
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
<file_sep>/src/ServiceLayer/WeatherForecastTableService.java
package ServiceLayer;
import BusinessLogic.RealFeelWorker;
import BusinessLogic.Weather;
import BusinessLogic.WeatherWorker;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
/**
* Created by yuraf_000 on 24.09.2014.
*/
public class WeatherForecastTableService {
private WeatherWorker weatherWorker = null;
private List<List<Weather>> forecastsList = new ArrayList<>();
private final String[] colNames = {"Дата","Температура","Влажность","Давление воздуха","Скорость ветра","Направление ветра"};
private List<Object> rowsYandex = new ArrayList<>();
private List<Object> rowsWeatherUA = new ArrayList<>();
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
@Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
public WeatherForecastTableService(String cityName, String countryName){
weatherWorker = new WeatherWorker(cityName,countryName);
TableProcessor();
}
// public
private void TableProcessor (){
forecastsList = weatherWorker.getForecastsByCityAndCountyName();
rowsYandex.clear();
rowsWeatherUA.clear();
for (int listCounter = 0; listCounter < forecastsList.size();listCounter++){
List <Weather> forecastList = forecastsList.get(listCounter);
switch (listCounter) {
case 0:
rowsYandex.addAll(getRows(forecastList));
break;
case 1:
rowsWeatherUA.addAll(getRows(forecastList));
break;
default:
}
}
}
private List<Object> getRows(List<Weather> forecastList){
List<Object> resultList = new ArrayList<>();
if (forecastList.size()==0) resultList.add(Arrays.asList("N/A","N/A","N/A","N/A","N/A","N/A"));
else {
for (int i = 0; i < forecastList.size(); i++){
Weather forecastElement = forecastList.get(i);
java.util.Date fdate = forecastElement.getDate();
Calendar cal = Calendar.getInstance();
cal.setTime(fdate);
String partOfDay = "";
switch (cal.get(Calendar.HOUR_OF_DAY)){
case 3: partOfDay = "(ночь)";
break;
case 9: partOfDay = "(утро)";
break;
case 15: partOfDay = "(день)";
break;
case 21: partOfDay = "(вечер)";
break;
default:
}
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols );
resultList.add(Arrays.asList(
dateFormat.format(fdate)+" "+partOfDay,forecastElement.getTemperature(),
forecastElement.getHumidity(),forecastElement.getPressure(),forecastElement.getWindSpeed(),forecastElement.getWindDirection()));
}
}
return resultList;
}
public Object getValueAtYandex(int row, int col){
return ((List<Object>) rowsYandex.get(row)).get(col);
}
public Object getValueAtWeatherUA (int row, int col){
return ((List<Object>) rowsWeatherUA.get(row)).get(col);
}
public String[] getColNames() {
return colNames;
}
public List<Object> getRowsYandex() {
return rowsYandex;
}
public List<Object> getRowsWeatherUA(){
return rowsWeatherUA;
}
public void onClose(){
weatherWorker.onClose();
}
}
<file_sep>/src/PresentationLayer/AuthorizationForm.java
package PresentationLayer;
import ServiceLayer.UsersService;
import ServiceLayer.WeatherForecastUpdateService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* Created by yuraf_000 on 18.06.2014.
*/
public class AuthorizationForm extends JFrame {
private JButton OkButton = new JButton("Вход");
private JButton RegButton = new JButton("Регистрация нового пользователя");
private JLabel Label1 = new JLabel("Авторизация в системе");
private JTextField Field1 = new JTextField("Введите логин");
private JPasswordField Field2 = new JPasswordField("Введите пароль");
UsersService usersService = new UsersService();
private WeatherForecastUpdateService weatherForecastUpdateService = null;
public AuthorizationForm(WeatherForecastUpdateService weatherForecastUpdateService) {
this.weatherForecastUpdateService = weatherForecastUpdateService;
if (this.weatherForecastUpdateService.isNew()) {
this.weatherForecastUpdateService.execute();
}
initComponent();
setVisible(true);
}
private void addActionListeners() {
Field1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Field1.setText("");
}
});
Field2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Field2.setText("");
}
});
OkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
OkClicked();
}
});
RegButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
NewUserDialog dialog = new NewUserDialog();
dialog.pack();
dialog.setVisible(true);
}
});
}
private void initComponent() {
setTitle("WAGGR Authorization");
setSize(300, 250);
setLocationRelativeTo(null);
Container pane = getContentPane();
pane.setLayout(new GridLayout (5, 1));
Label1.setHorizontalAlignment(JTextField.CENTER);
Field1.setHorizontalAlignment(JTextField.CENTER);
Field2.setHorizontalAlignment(JTextField.CENTER);
addActionListeners();
pane.add(Label1);
pane.add(Field1);
pane.add(Field2);
pane.add(OkButton);
pane.add(RegButton);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void OkClicked(){
String login = Field1.getText();
String password = <PASSWORD>.valueOf(Field2.<PASSWORD>());
final Object current = usersService.login(login,password);
if (current==null) {
JOptionPane.showMessageDialog(this,"Неверный логин/пароль","Ошибка",JOptionPane.INFORMATION_MESSAGE);
return;
} else if (login.equals("admin")) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AdminForm adminForm = new AdminForm(weatherForecastUpdateService);
adminForm.setVisible(true);
}
});
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainForm mainForm = new MainForm(current,weatherForecastUpdateService);
}
});
}
usersService.close();
dispose();
}
}
<file_sep>/src/ServiceLayer/CityService.java
package ServiceLayer;
import DataAccessLayer.CityGateway;
import java.util.List;
/**
* Created by yuraf_000 on 25.12.2014.
*/
public class CityService {
CityGateway cityGateway = new CityGateway();
public List<String> checkCityExists(String cityName) {
List<String> checkList = cityGateway.checkCity(cityName);
if (checkList.size()!=0&&checkList!=null) {
return checkList;
} else {
return null;
}
}
public boolean checkCityExists(String cityName, String countryName) {
return cityGateway.checkCity(cityName,countryName);
}
}
<file_sep>/src/BusinessLogic/User.java
package BusinessLogic;
/**
* Created by yuraf_000 on 19.06.2014.
*/
public class User {
private String userName = null;
private String userSurname = null;
private String userCity = null;
private String userCountry = null;
private String userLogin = null;
private String userPassword = null;
private RealFeelWorker userRealFeelWorker = null;
public User() {
//
}
public User (String login, String name, String surname, String cityName, String countryName){
userName = name;
userSurname = surname;
userCity = cityName;
userCountry = countryName;
userLogin = login;
}
public User (String login, String password, String name, String surname, String cityName, String countryName){
userLogin = login;
userPassword = <PASSWORD>;
userName = name;
userSurname = surname;
userCity = cityName;
userCountry = countryName;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserSurname(String userSurname) {
this.userSurname = userSurname;
}
public void setUserCity(String userCity) {
this.userCity = userCity;
}
public void setUserCountry(String userCountry) {
this.userCountry = userCountry;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
public String getUserPassword() {
return <PASSWORD>Password;
}
public String getUserName(){
return userName;
}
public String getUserSurname(){
return userSurname;
}
public String getUserLogin() { return userLogin; }
public String getUserCity(){
return userCity;
}
public String getUserCountry() {
return userCountry;
}
}
<file_sep>/src/PresentationLayer/SetCountryDialog.java
package PresentationLayer;
import javax.swing.*;
import java.awt.event.*;
import java.util.List;
public class SetCountryDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JRadioButton radioButton1;
private JRadioButton radioButton2;
private JRadioButton radioButton3;
private JRadioButton radioButton4;
private JRadioButton radioButton5;
public SetCountryDialog(List<String> countryNames) {
// super((java.awt.Frame) null, true);
// setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
setTitle("Найдены совпадения");
setSize(300,200);
setLocationRelativeTo(null);
radioButton1.setVisible(false);
radioButton2.setVisible(false);
radioButton3.setVisible(false);
radioButton4.setVisible(false);
radioButton5.setVisible(false);
if (countryNames.size()>=2){
radioButton1.setVisible(true);
radioButton1.setText(countryNames.get(0));
radioButton2.setVisible(true);
radioButton2.setText(countryNames.get(1));
}
if (countryNames.size()>=3){
radioButton3.setVisible(true);
radioButton3.setText(countryNames.get(2));
}
if (countryNames.size()>=4){
radioButton4.setVisible(true);
radioButton4.setText(countryNames.get(3));
}
if(countryNames.size()>=5){
radioButton5.setVisible(true);
radioButton5.setText(countryNames.get(4));
}
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
radioButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
radioButton1.setSelected(true);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
}
});
radioButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
radioButton1.setSelected(false);
radioButton2.setSelected(true);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
}
});
radioButton3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
}
});
radioButton4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton5.setSelected(false);
}
});
radioButton5.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
}
});
}
private void onOK() {
dispose();
}
public String getSelectedName (){
if (radioButton1.isSelected()) return radioButton1.getText();
if (radioButton2.isSelected()) return radioButton2.getText();
if (radioButton3.isSelected()) return radioButton3.getText();
if (radioButton4.isSelected()) return radioButton4.getText();
if (radioButton5.isSelected()) return radioButton5.getText();
return null;
}
private void onCancel() {
dispose();
}
}
<file_sep>/src/BusinessLogic/RealFeel.java
package BusinessLogic;
/**
* Created by yuraf_000 on 26.12.2014.
*/
public class RealFeel extends Weather {
private String countryName = null;
private String cityName = null;
private String userLogin = null;
public String getCountryName() {
return countryName;
}
public String getCityName() {
return cityName;
}
public String getUserLogin() {
return userLogin;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
}
<file_sep>/Waagr_v.0.1.properties
path.variable.maven_repository=C\:\\Users\\yuraf_000\\.m2\\repository
jdk.home.1.7=C\:/glassfish4/jdk7
javac2.instrumentation.includeJavaRuntime=false<file_sep>/src/ServiceLayer/UsersTableService.java
package ServiceLayer;
import BusinessLogic.User;
import BusinessLogic.UserWorker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by yuraf_000 on 21.12.2014.
*/
public class UsersTableService {
private final String[] colNames = {"Логин","Пароль", "Имя", "Фамилия", "Город","Страна"};
private List<List<String>> rows = new ArrayList<>();
private List<List<String>> oldRows = new ArrayList<>();
private UsersService userService= new UsersService();
public UsersTableService() {
List<User> usersList = userService.getUsersList();
for (User user:usersList){
if (!user.getUserLogin().equals("admin"))
rows.add(Arrays.asList(user.getUserLogin(), user.getUserPassword(), user.getUserName(), user.getUserSurname(), user.getUserCity(), user.getUserCountry()));
}
try {
oldRows = (List) ObjectClonerService.deepCopy(rows);
} catch (Exception e) {
e.printStackTrace();
}
}
public Object getValueAt (int row,int column){
return rows.get(row).get(column);
}
public void setValueAt (String value, int row,int column) {
List<String> r = rows.get(row);
r.set(column, value);
rows.set(row,r);
}
private String getOldUserLogin (int row) {
return oldRows.get(row).get(0);
}
public boolean deleteUser(int row) {
return userService.deleteUser(getOldUserLogin(row));
}
public Boolean rollBack () {
if (!rows.equals(oldRows)){
try {
rows = (List) ObjectClonerService.deepCopy(oldRows);
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
public Boolean updateDB() {
Boolean diff = false;
for (int i = 0; i < oldRows.size(); i++) {
List<String> oldRow = (List) oldRows.get(i);
List<String> newRow = (List) rows.get(i);
if (!oldRow.equals(newRow)){
User u = new User();
u.setUserLogin(newRow.get(0));
u.setUserPassword(newRow.get(1));
u.setUserName(newRow.get(2));
u.setUserSurname(newRow.get(3));
u.setUserCity(newRow.get(4));
u.setUserCountry(newRow.get(5));
diff = userService.updateUser(oldRow.get(0),u);
}
}
if (diff) {
try {
oldRows = (List) ObjectClonerService.deepCopy(rows);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
else return false;
}
public String[] getColNames() {
return colNames;
}
public List<List<String>> getRows() {
return rows;
}
public void onClose() {
userService.close();
}
}
<file_sep>/src/APILayer/ClientSession.java
package APILayer;
import ServiceLayer.JSONBuilderService;
import org.json.simple.JSONObject;
import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Date;
public class ClientSession implements Runnable {
private Socket socket;
private InputStream in = null;
private OutputStream out = null;
@Override
public void run() {
try {
String header = readHeader();
ProviderCityIdContainer providerAndCityIdFromHeader = getProviderAndCityIdFromHeader(header);
if (providerAndCityIdFromHeader!=null) {
JSONObject jsonObject = JSONBuilderService.prepareAndGetJSON(providerAndCityIdFromHeader.provider,providerAndCityIdFromHeader.cityId);
send(jsonObject);
} else {
send404();
}
socket.close();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public ClientSession(Socket socket) throws IOException {
this.socket = socket;
initialize();
}
private void initialize() throws IOException {
in = socket.getInputStream();
out = socket.getOutputStream();
}
private String readHeader() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String ln = null;
while (true) {
ln = reader.readLine();
if (ln == null || ln.isEmpty()) {
break;
}
builder.append(ln + System.getProperty("line.separator"));
}
return builder.toString();
}
private ProviderCityIdContainer getProviderAndCityIdFromHeader(String header) {
int from = header.indexOf("/")+1;
int to = header.indexOf("/", from);
if (from!=-1 && to !=-1) {
String weatherProvider = header.substring(from, to);
if (!(weatherProvider.equals("WUA") || weatherProvider.equals("Yandex"))) {
return null;
}
int cityIdEndIndex = header.indexOf(" ", to);
if (cityIdEndIndex != to + 1) {
String cityId = header.substring(to + 1, cityIdEndIndex);
ProviderCityIdContainer providerIdCityId = new ProviderCityIdContainer();
providerIdCityId.cityId = Integer.parseInt(cityId);
providerIdCityId.provider = weatherProvider;
return providerIdCityId;
}
}
return null;
}
private void send(JSONObject jsonObject) {
int code;
if (jsonObject != null) {
code = 200;
} else {
code = 404;
}
String header = getHeader(code); // "UTF-8"
PrintStream answer = new PrintStream(out, true);
answer.print(header);
if (code == 200) {
byte[] b = jsonObject.toJSONString().getBytes();
try {
out.write(b, 0, b.length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void send404() throws UnsupportedEncodingException {
String header = getHeader(404); // "UTF-8"
PrintStream answer = new PrintStream(out, true);
answer.print(header);
}
private String getHeader(int code) {
StringBuffer buffer = new StringBuffer();
buffer.append("HTTP/1.1 " + code + " " + getAnswer(code) + "\n");
buffer.append("Date: " + new Date().toGMTString() + "\n");
buffer.append("Accept-Ranges: none\n");
buffer.append("\n");
return buffer.toString();
}
private String getAnswer(int code) {
switch (code) {
case 200:
return "OK";
case 404:
return "Not Found";
default:
return "Internal Server Error";
}
}
}
class ProviderCityIdContainer {
int cityId;
String provider;
}<file_sep>/src/Parsers/CountryCityParserYa.java
package Parsers;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by yuraf_000 on 05.06.2014.
*/
public class CountryCityParserYa {
private ListMultimap<Integer, Integer> CountryCityMap = ArrayListMultimap.create();
private HashMap<Integer,String> CountryIdMap = new HashMap<>();
private HashMap<Integer,String> CityIdMap = new HashMap<>();
private int cityCounter = 0;
public CountryCityParserYa(String url) {
System.out.println("Retrieving lists countries and cities in Yandex DB...");
try {
String resCityId = null;
URL UrlToParse = new URL(url);
DOMParser p = new DOMParser();
System.out.println(url.toString());
p.parse(new InputSource(UrlToParse.openStream()));
Document doc = p.getDocument();
NodeList nodeLst = doc.getElementsByTagName("country");
int CountryId = 0;
for (int i = 0; i < nodeLst.getLength(); i++) {
Node nNode = nodeLst.item(i);
if (nNode.getNodeType()==Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
CountryIdMap.put(CountryId,eElement.getAttribute("name").toString());//создаем карту стран
NodeList CitiesLst = eElement.getElementsByTagName("city");
for (int x = 0; x < CitiesLst.getLength(); x++) {
Element CElement = (Element) CitiesLst.item(x);
//CountryIdMap.put()
int tempCityId = Integer.parseInt(CElement.getAttribute("id"));
switch (eElement.getAttribute("name").toString()) {
case "США":
if (CitiesLst.item(x).getTextContent().indexOf(",") == -1) {
CountryCityMap.put(CountryId, tempCityId);
CityIdMap.put(tempCityId,CitiesLst.item(x).getTextContent());
cityCounter++;
}
else {
CountryCityMap.put(CountryId, tempCityId );
CityIdMap.put(tempCityId,CitiesLst.item(x).getTextContent().substring(0, CitiesLst.item(x).getTextContent().indexOf(",")));
cityCounter++;
}
break;
default:
CountryCityMap.put(CountryId, tempCityId);
CityIdMap.put(tempCityId,CitiesLst.item(x).getTextContent());
cityCounter++;
}
}
CountryId++;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
}
public Integer AllCitiesLength() { return cityCounter; }
public ListMultimap<Integer, Integer> GetCountryCityMapByNames(String Names) {
ListMultimap<Integer, Integer> CountryCityMapLocal = ArrayListMultimap.create();
List<String> inputCountryList = new ArrayList<>();
if (Names.indexOf(',')!=-1) {
while (Names.indexOf(',') != -1) {
int i = Names.indexOf(',');
inputCountryList.add(Names.substring(0, i));
Names = Names.substring(i + 1);
}
inputCountryList.add(Names);
}else {
inputCountryList.add(Names);
}
for(Integer id:CountryIdMap.keySet()){
for (int x=0; x< inputCountryList.size();x++){
if (CountryIdMap.get(id).equals(inputCountryList.get(x))){
CountryCityMapLocal.putAll(id,CountryCityMap.get(id));
}
}
}
return CountryCityMapLocal;
}
public ListMultimap<Integer, Integer> GetCountryCityMap() {
return CountryCityMap;
}
public HashMap<Integer,String> GetCityIdMap() { return CityIdMap; }
public HashMap<Integer,String> GetCountryIdMap (){
return CountryIdMap;
}
}
<file_sep>/src/Tests/BusinessLogicTest.java
package Tests;
import BusinessLogic.User;
import BusinessLogic.UserWorker;
import org.junit.Test;
import static org.junit.Assert.*;
public class BusinessLogicTest {
@Test
public void testNewUser() throws Exception {
UserWorker userWorker = new UserWorker();
String login = "testUser";
String password = "<PASSWORD>";
String name = "testUserName";
String surname = "testUserSurname";
String cityName = "testUserCity";
String countryName = "testUserCountry";
assertTrue(userWorker.newUser(login, password, name, surname, cityName, countryName));
assertFalse(userWorker.newUser(login, password, name, surname, cityName, countryName));
assertTrue(userWorker.deleteUser(login));
}
@Test
public void testAuthorization() throws Exception {
UserWorker userWorker = new UserWorker();
String login = "testUser";
String password = "<PASSWORD>";
String name = "testUserName";
String surname = "testUserSurname";
String cityName = "testUserCity";
String countryName = "testUserCountry";
assertTrue(userWorker.newUser(login, password, name, surname, cityName, countryName));
assertTrue(userWorker.checkAuthorization(login,password));
assertTrue(userWorker.deleteUser(login));
}
@Test
public void testUpdateUser() throws Exception {
UserWorker userWorker = new UserWorker();
String login = "testUser";
String password = "<PASSWORD>";
String name = "testUserName";
String surname = "testUserSurname";
String cityName = "testUserCity";
String countryName = "testUserCountry";
assertTrue(userWorker.newUser(login, password, name, surname, cityName, countryName));
User newUser = new User();
newUser.setUserLogin("testUser1");
newUser.setUserPassword("<PASSWORD>");
newUser.setUserName("testUserName1");
newUser.setUserSurname("testUserSurname1");
newUser.setUserCity("testUserCity1");
newUser.setUserCountry("testUserCountry1");
assertTrue(userWorker.updateUser(login, newUser));
assertNotNull(userWorker.getUser("testUser1"));
assertTrue(userWorker.deleteUser("testUser1"));
}
}<file_sep>/src/DataAccessLayer/UserGateway.java
package DataAccessLayer;
import BusinessLogic.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by URI on 14.01.2015.
*/
public class UserGateway {
private Connection waggrConnection = null;
public UserGateway(){
try {
Class.forName("org.postgresql.Driver");
waggrConnection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/waggrdb", "waggr",
"waggr");
} catch (SQLException e) {
System.out.println("Connection Failed!");
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
return;
}
}
public void connectionClose() {
try {
waggrConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean newUser(String login, String password, String name, String surname, String cityName, String countryName) {
try {
String stm = "INSERT INTO users(login, password, name, surname, city_name, country_name) VALUES(?, ?, ?, ?, ?, ?)";
PreparedStatement tempPst = waggrConnection.prepareStatement(stm);
tempPst.setString(1, login);
tempPst.setString(2, password);
tempPst.setString(3, name);
tempPst.setString(4, surname);
tempPst.setString(5, cityName);
tempPst.setString(6, countryName);
int i = tempPst.executeUpdate();
if (i!=0) {
tempPst.close();
return true;
}
tempPst.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public List<User> getUsersList () {
try {
List<User> usersList = new ArrayList<>();
Statement getUsersList = waggrConnection.createStatement();
String query = "SELECT * FROM users;";
ResultSet res = getUsersList.executeQuery(query);
while (res.next()) {
String userLogin = res.getString(1);
String userPassword = res.getString(2);
String userName = res.getString(3);
String userSurname = res.getString(4);
String userCity = res.getString(5);
String userCountry = res.getString(6);
User newUser = new User(userLogin,userPassword,userName,userSurname,userCity,userCountry);
usersList.add(newUser);
}
return usersList;
} catch (SQLException e) {
System.out.println("getUserList exception");
}
return null;
}
public User getUser (String login){
try {
Statement CheckLogin = waggrConnection.createStatement();
ResultSet Res = CheckLogin.executeQuery("SELECT * FROM users WHERE login ='" + login + "';");
if (Res.next()) {
Res.close();
Statement GetCity = waggrConnection.createStatement();
ResultSet UserData = GetCity.executeQuery("SELECT password, name, surname, city_name, country_name FROM users WHERE login ='" + login + "';");
UserData.next();
return new User(login, UserData.getString(1), UserData.getString(2), UserData.getString(3), UserData.getString(4),UserData.getString(5));
}
Res.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean deleteUser(String userLogin) {
try {
Statement deleteUser = waggrConnection.createStatement();
String del = String.format("DELETE FROM users WHERE login = '%s';", userLogin);
int res = deleteUser.executeUpdate(del);
if (res!=0) {
deleteUser.close();
return true;
}
deleteUser.close();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean updateUser(String userLogin, User newUser) {
try {
String stm = String.format("UPDATE users SET login = '%s', password = '%s',name = '%s', surname = '%s', city_name = '%s', country_name = '%s' WHERE login = '%s';",
newUser.getUserLogin(),newUser.getUserPassword(),newUser.getUserName(),newUser.getUserSurname(),newUser.getUserCity(),newUser.getUserCountry(),userLogin);
Statement updateUser = waggrConnection.createStatement();
int i = updateUser.executeUpdate(stm);
if (i != 0) {
updateUser.close();
return true;
}
updateUser.close();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("update user exception");
}
return false;
}
public boolean updateUserLocation(String userLogin, String cityName, String countryName) {
try {
Statement updateLocation = waggrConnection.createStatement();
String stm = String.format("UPDATE users SET city_name = '%s', country_name = '%s' WHERE login = '%s';",cityName,countryName,userLogin);
int i = updateLocation.executeUpdate(stm);
if (i!=0){
updateLocation.close();
return true;
}
updateLocation.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public Boolean updatePassword(String login, String newPass) {
try {
Statement updatePassword = waggrConnection.createStatement();
String stm = String.format("UPDATE users SET password = '%s' WHERE login = '%s';",newPass,login);
int i = updatePassword.executeUpdate(stm);
if (i==1) {
updatePassword.close();
return true;
}
updatePassword.close();
}catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public String getPassword(String login) {
try {
Statement getPassword = waggrConnection.createStatement();
String stm = String.format("SELECT password FROM users WHERE login = '%s';",login);
ResultSet result = getPassword.executeQuery(stm);
if (result.next()) {
String res = result.getString(1);
getPassword.close();
return res;
}
getPassword.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>/src/Parsers/ForecastParserWUA.java
package Parsers;
import BusinessLogic.Weather;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by yuraf_000 on 05.06.2014.
*/
public class ForecastParserWUA{
private List<Weather> WeatherList = new ArrayList<Weather>();
private String ConvertWindDirection(int degree){
if (degree>=0 && degree<=20) return "n";
if (degree>20 && degree<=35) return "nne";
if (degree>35 && degree<=55) return "ne";
if (degree>55 && degree<=70) return "ene";
if (degree>70 && degree<=110) return "e";
if (degree>110 && degree<=125) return "ese";
if (degree>125 && degree<=145) return "se";
if (degree>145 && degree<=160) return "sse";
if (degree>160 && degree<=200) return "s";
if (degree>200 && degree<=215) return "ssw";
if (degree>215 && degree<=235) return "sw";
if (degree>235 && degree<=250) return "wsw";
if (degree>250 && degree<=290) return "w";
if (degree>290 && degree<=305) return "wnw";
if (degree>305 && degree<=325) return "nw";
if (degree>325 && degree<=340) return "nnw";
if (degree>340 && degree<=360) return "n";
else return "unknown";
}
public List<Weather> GetWeatherList(){
return WeatherList;
}
public ForecastParserWUA(String url) {
try {
URL UrlToParse = new URL(url);
//URL UrlToParse = new URL("http://xml.weather.co.ua/1.2/forecast/62024?dayf=5&lang=ru");
DOMParser p = new DOMParser();
p.parse(new InputSource(UrlToParse.openStream()));
Document doc = p.getDocument();
//parseCurrent
Element current = (Element) doc.getElementsByTagName("current").item(0);
Weather wc = new Weather();
if (current.getChildNodes().getLength() > 1) { //ecли есть current
String currentDate = current.getAttribute("last_updated");
SimpleDateFormat parserSDF = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss", Locale.ENGLISH);
Date d = parserSDF.parse(currentDate);
wc.setDate(d);
wc.setIsPredict(false);
NodeList node0Lst = current.getChildNodes();
//System.out.println("Current node child nodes " + node0Lst.getLength());
for (int z = 0; z < node0Lst.getLength(); z++) {
if (node0Lst.item(z).getNodeType() == Node.ELEMENT_NODE) {
switch (node0Lst.item(z).getNodeName()) {
case "t":
wc.setTemperature(Integer.parseInt(node0Lst.item(z).getTextContent()));
break;
case "p":
wc.setPressure(Integer.parseInt(node0Lst.item(z).getTextContent()));
break;
case "w":
wc.setWindSpeed(Float.parseFloat(node0Lst.item(z).getTextContent()));
break;
case "w_rumb":
wc.setWindDirection(this.ConvertWindDirection(Integer.parseInt(node0Lst.item(z).getTextContent())));
break;
case "h":
wc.setHumidity(Integer.parseInt(node0Lst.item(z).getTextContent()));
break;
default:
continue;
}
}
}
WeatherList.add(wc);
} else {
wc.setIsPredict(true);
}
NodeList nodeLst = doc.getElementsByTagName("forecast");
NodeList node2Lst = ((Element) nodeLst.item(1)).getElementsByTagName("day");
if (node2Lst.getLength() != 1) {
for (int i = 0; i < node2Lst.getLength(); i++) {
if (node2Lst.item(i).getNodeType() == Node.ELEMENT_NODE) {
String date = ((Element) node2Lst.item(i)).getAttribute("date");
String time = ((Element) node2Lst.item(i)).getAttribute("hour");
SimpleDateFormat parserSDF2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
SimpleDateFormat equalParser = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
Date d1 = parserSDF2.parse(date + " " + time + ":00:00");
if (wc.getIsPredict() || !(equalParser.format(d1).equals(equalParser.format(wc.getDate())))) { //проверяем чтобы не записывать прогноз на текущий день
NodeList daynodeLst = node2Lst.item(i).getChildNodes();
Weather wp = new Weather();
wp.setDate(d1);
for (int z = 0; z < daynodeLst.getLength(); z++) {
if (daynodeLst.item(z).getNodeType() == Node.ELEMENT_NODE) {
if (daynodeLst.item(z).getChildNodes().getLength() > 1) {
String min = ((Element) daynodeLst.item(z)).getElementsByTagName("min").item(0).getTextContent();
String max = ((Element) daynodeLst.item(z)).getElementsByTagName("max").item(0).getTextContent();
int mid = (Integer.parseInt(min) + Integer.parseInt(max)) / 2;
Float midf = Float.parseFloat(String.valueOf(mid));
switch (daynodeLst.item(z).getNodeName()) {
case "t":
wp.setTemperature(mid);
break;
case "p":
wp.setPressure(mid);
break;
case "wind":
wp.setWindSpeed(midf);
int rumb = Integer.parseInt(((Element) daynodeLst.item(z)).getElementsByTagName("rumb").item(0).getTextContent());
wp.setWindDirection(this.ConvertWindDirection(rumb));
break;
case "hmid":
wp.setHumidity(mid);
break;
default:
continue;
}
}
}
}
wp.setIsPredict(true);
WeatherList.add(wp);
}
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("PARSERS ERROR: WUAPARSER: Cant load forecast url: "+url);
//e.printStackTrace();
}
}
}
|
637624e05d359169a38f0c5e0d793856dd4d398c
|
[
"Java",
"INI"
] | 19
|
Java
|
yurafey/waggr
|
c6ed145b3d8d8746ab03fe2348a9ded2e777b361
|
1c297debe71d5306a46cb9465d5dbee893068239
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
f-strings(Python 3.6) style literal string interpolation.
"""
from __future__ import absolute_import
import sys
from .fmt import Fmt
version = __version__ = '0.3.1'
version_info = [int(num) for num in version.split('.')]
__author__ = 'damnever (<NAME>)'
__email__ = '<EMAIL>'
__license__ = 'The BSD 3-Clause License'
# Install the Fmt() object in sys.modules,
# so that "import fmt" gives a callable fmt.
sys.modules['fmt'] = Fmt()
<file_sep>f-strings(Python 3.6) style literal string interpolation.
==========================================================
.. image:: https://img.shields.io/travis/damnever/fmt.svg?style=flat-square
:target: https://travis-ci.org/damnever/fmt
.. image:: https://img.shields.io/pypi/v/fmt.svg?style=flat-square
:target: https://pypi.python.org/pypi/fmt
Using `f-strings(PEP 498) <https://www.python.org/dev/peps/pep-0498/>`_ style literal string interpolation without Python 3.6.
Usages
------
- Accessing the globals and locals.
.. code:: python
import os
import fmt as f
g_foo = 'global-foo'
g_bar = 'global-bar'
g_num = 23
g_ls = [1, 2, 3]
def scope():
l_foo = 'local-foo'
l_bar = 'local-bar'
print( f('{l_foo}, {l_bar}') ) # 'local-foo, local-bar'
print( f('{g_foo}, {g_bar!r}') ) # "global-foo, 'global-bar'"
scope()
print( f('{{ }}') ) # '{ }'
print( f('hex: {g_num:#x}') ) # '0x17'
print( f('{os.EX_OK}') ) # '0'
print( f('{g_ls[0]}, {g_ls[1]}, {g_ls[2]}') ) # '1, 2, 3'
- **NOTE**: **Closure** will be a little tricky, must pass the outside scope variables as arguments to f,
which added a reference to inside the closure in order this can work.
.. code:: python
import fmt as f
def outer(x='xx'):
y = 'yy'
def inner():
print( f('{x}, {y}', x, y) ) # "xx, yy"
return inner
outer()()
- Expression evaluation.
.. code:: python
from datetime import datetime
import fmt as f
class S(object):
def __str__(self):
return 'hello'
def __repr__(self):
return 'hi'
def __format__(self, fmt):
return 'abcdefg'[int(fmt)]
print( f('{1234567890:,}') ) # '1,234,567,890'
print( f('{1 + 2}') ) # '3'
print( f('{str(1 + 2)!r}') ) # "'3'"
print( f('{[i for i in range(5)]}') ) # '[0, 1, 2, 3, 4]'
ls = range(5)
print( f('{{i for i in ls}}') ) # 'set([0, 1, 2, 3, 4])' or '{0, 1, 2, 3, 4}'
print( f('{{k:v for k,v in zip(range(3), range(3, 6))}}') ) # '{0: 3, 1: 4, 2: 5}'
print( f('{datetime(1994, 11, 6):%Y-%m-%d}') ) # '1994-11-06'
print( f('{list(map(lambda x: x+1, range(3)))}') ) # '[1, 2, 3]'
print( f('{S()!s}, {S()!r}, {S():1}') ) # 'hello, hi, b'
- Also, you can register some namespaces for convenience.
.. code:: python
import fmt as f
f.mregister({'x': 1, 'y': 2}) # register multiple
f.register('z', 3) # register only one
def func(x, y):
return x + y
print( f('{func(x, y)}') ) # '3'
print( f('{func(x, z)}') ) # '4'
print( f('{func(y, z)}') ) # '5'
- **NOTE**: ``locals()`` maybe cover the ``globals()``, ``globals()`` maybe cover the namespaces that you registered.
Installation
------------
Install by pip: ::
[sudo] pip install fmt -U
LICENSE
-------
`The BSD 3-Clause License <https://github.com/damnever/fmt/blob/master/LICENSE>`_
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import codecs
from setuptools import setup, find_packages
version = ''
with open('fmt/__init__.py', 'r') as f:
version = re.search(r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
f.read(), re.M).group(1)
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='fmt',
version=version,
description='f-strings(Python 3.6) style literal string interpolation.',
long_description=long_description,
url='https://github.com/damnever/fmt',
author='damnever',
author_email='<EMAIL>',
license='The BSD 3-Clause License',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='f-strings, format, literal string interpolation',
packages=find_packages()
)
<file_sep># -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
import ast
import sys
from copy import deepcopy
from functools import partial
PY3 = sys.version_info[0] == 3
if PY3:
fmt_types = str, bytes
else:
fmt_types = basestring, unicode # noqa: F821
class Fmt(object):
def __init__(self):
self._g_ns = {}
self._nodes_cache = {}
def register(self, name, value, update=False):
if not update and name in self._g_ns:
raise ValueError('namespace "{}" already registered'.format(name))
self._g_ns[name] = value
def mregister(self, ns, update=False):
for k, v in ns.items():
self.register(k, v, update)
def __call__(self, f_str, *_args):
if not isinstance(f_str, fmt_types):
raise ValueError('Unsupported type as format '
'string: {}({})'.format(type(f_str), f_str))
frame = sys._getframe(1)
# locals will cover globals
ns = deepcopy(self._g_ns)
ns.update(frame.f_globals)
ns.update(frame.f_locals)
# cache nodes, if already parsed
nodes = self._nodes_cache.get(f_str, None)
if nodes is None:
nodes = Parser(f_str).parse()
self._nodes_cache[f_str] = nodes
try:
return generate(nodes, ns)
finally:
del frame # avoid reference cycle
def generate(nodes, namespace):
contents = []
for node in nodes:
contents.append(node.generate(namespace))
return ''.join(contents)
class Node(object):
# flyweight pattern: cache instances
_instances = {}
def __new__(cls, *args, **kwargs):
key = (cls, args, tuple(kwargs.items()))
instance = cls._instances.get(key, None)
if instance is None:
instance = super(Node, cls).__new__(cls)
instance.__init__(*args, **kwargs)
cls._instances[key] = instance
return instance
def generate(self, ns):
raise NotImplementedError()
class Text(Node):
def __init__(self, *contents):
self._content = ''.join(contents)
def generate(self, _namespace):
return self._content
class Constant(Node):
def __init__(self, name, fmt):
self._name = name
self._fmt = fmt
def generate(self, namespace):
name = self._name
try:
value = namespace[name]
except KeyError:
raise NameError(
'"{}" cannot be found in any namespaces.'.format(name))
return self._fmt.format(**{name: value})
class Expression(Node):
def __init__(self, expr, fmt, name='name'):
self._expr = expr
self._name = name
self._fmt = name.join(s.strip() for s in fmt.split(expr))
def generate(self, namespace):
ns = {}
try:
exec('{}={}'.format(self._name, self._expr), namespace.copy(), ns)
except NameError as e:
name = e.args[0].split("'", 3)[1]
raise NameError(
'"{}" cannot be found in any namespaces.'.format(name))
return self._fmt.format(**ns)
class Parser(object):
_PATTERN_SPEC = re.compile(
r"""
(?P<ltext>[^\{\}]*)
(?P<lbrace>\{)?
(?P<lbraces>(?(lbrace)[\s\{]*))
(?P<mtext>[^\{\}]*)
(?P<rbrace>\})?
(?P<rbraces>(?(rbrace)[\s\}]*))
(?P<rtext>[^\{\}]*)
""", re.S | re.X | re.M
)
_PATTERN_COMP = re.compile(
r'[a-zA-Z0-9_:]+\s+for\s+[a-zA-Z0-9_,]+\s+in\s+.+',
re.S | re.X | re.M)
_ast_parse = partial(ast.parse, filename='<f-strings>', mode='eval')
def __init__(self, f_str):
self._f_str = f_str
def parse(self, _pattern=_PATTERN_SPEC):
f_str = self._f_str
if not f_str or f_str.isspace():
return [Text(f_str)]
nodes = []
for match_obj in _pattern.finditer(f_str):
groups = match_obj.groupdict()
ltext = groups['ltext'] or ''
lbraces = (groups['lbrace'] or '') + (groups['lbraces'] or '')
mtext = (groups['mtext'] or '')
rbraces = (groups['rbrace'] or '') + (groups['rbraces'] or '')
rtext = groups['rtext'] or ''
if lbraces:
raw, lbraces = lbraces, lbraces.rstrip()
mtext = raw[len(lbraces):] + mtext
if rbraces:
raw, rbraces = rbraces, rbraces.rstrip()
rtext = raw[len(rbraces):] + rtext
if all(s == '' for s in (ltext, lbraces, mtext, rbraces, rtext)):
continue
if not lbraces and not rbraces:
nodes.append(Text(ltext, mtext, rtext))
continue
if ltext:
nodes.append(Text(ltext))
if not mtext or mtext.isspace() or not (lbraces and rbraces):
texts = []
if lbraces:
texts.append(self._check_braces(lbraces, True, '{', True))
texts.append(mtext)
if rbraces:
texts.append(self._check_braces(rbraces, True, '}', True))
nodes.append(Text(*texts))
else:
is_comp = self._is_dict_or_set_comp(mtext)
if is_comp:
lbtext = self._check_braces(lbraces, True, '{')
rbtext = self._check_braces(rbraces, True, '}')
if lbtext:
nodes.append(Text(lbtext))
expr = '{{{}}}'.format(self._replace_with_spaces(mtext))
nodes.append(Expression(expr, '{{{}}}'.format(expr)))
if rbtext:
nodes.append(Text(rbtext))
else:
lb_num, rb_num = lbraces.count('{'), rbraces.count('}')
if lb_num == rb_num and lb_num > 0 and lb_num % 2 == 0:
texts = []
if lbraces:
texts.append(
self._check_braces(lbraces, True, '{', True))
texts.append(mtext)
if rbraces:
texts.append(
self._check_braces(rbraces, True, '}', True))
nodes.append(Text(*texts))
else:
lbtext = self._check_braces(lbraces, False, '{')
rbtext = self._check_braces(rbraces, False, '}')
lb_num = lb_num >> 1
if lbtext:
nodes.append(Text(lbtext))
nodes.append(self._parse_node(mtext))
rb_num = rb_num >> 1
if rbtext:
nodes.append(Text(rbtext))
if rtext:
nodes.append(Text(rtext))
return nodes
def _is_dict_or_set_comp(self, text, _pattern=_PATTERN_COMP):
# dict/set comprehensions
if _pattern.match(text):
try:
self._ast_parse('{{{}}}'.format(text))
except SyntaxError:
return False
else:
return True
return False
def _check_braces(self, braces, is_even, symbol, strict_even=False):
# .........
btexts = []
pieces = braces.split()
if symbol == '}':
pieces = pieces[::-1]
braces = braces[::-1]
if len(pieces) == 1:
nbraces = len(braces)
mod = nbraces % 2
if is_even:
if mod != 0:
raise SyntaxError(
'Single "{}" encountered in format string'.format(
symbol))
elif mod != 1:
raise SyntaxError(
'Single "{}" encountered in format string'.format(symbol))
if not strict_even:
nbraces -= 1
return symbol * (nbraces >> 1)
pos, has_rest = 0, False
for idx, piece in enumerate(pieces):
div, mod = divmod(len(piece), 2)
if mod != 0:
if is_even and strict_even:
raise SyntaxError(
'Single "{}" encountered in format string'.format(
symbol)
)
else:
has_rest = True
break
if idx == 0:
pos += len(piece)
else:
end = braces.find(piece, pos)
btexts.append(braces[pos: end])
pos = end + len(piece)
btexts.append(symbol * div)
if has_rest:
end = braces.find(piece, pos)
btexts.append(braces[pos: end])
else:
if not strict_even:
btexts.pop()
rest = len(''.join(pieces[idx:]))
if is_even:
if rest != 2:
raise SyntaxError(
'Single "{}" encountered in format string'.format(symbol))
elif rest != 1:
raise SyntaxError(
'Single "{}" encountered in format string'.format(symbol))
if symbol == '}':
btexts = btexts[::-1]
return ''.join(btexts)
def _replace_with_spaces(self, text, _repl='\t\n\r\f\v'):
text = text.strip()
for r in _repl:
text = text.replace(r, ' ')
return text
def _parse_node(self, node_str):
node_str = self._replace_with_spaces(node_str)
fmt = '{{{}}}'.format(node_str)
expr = self._parse_node_str(node_str)
ast_node = self._ast_parse(expr)
if ast_node.body.__class__.__name__ == 'Name':
return Constant(expr, fmt)
else:
return Expression(expr, fmt)
def _parse_node_str(self, node_str, _cvss=('s', 'r', 'a')):
# f-string: '''... <text> {
# <expression>
# <optional !s, !r, or !a>
# <optional : format specifier>
# } <text> ...'''
expr = None
if ':' in node_str:
if node_str.startswith('('):
brackets = 1
for i, c in enumerate(node_str[1:]):
if c == '(':
brackets += 1
elif c == ')':
brackets -= 1
if brackets == 0:
break
i += 1
if brackets != 0:
raise SyntaxError('unexpected EOF at {}'.format(
node_str[i]))
i += 1
if len(node_str) > i+2 and node_str[i] == '(':
i += 2
if node_str[i] != ':':
raise SyntaxError('unexpected EOF at {}'.format(
node_str[i]))
left, fmt_spec = node_str[:i], node_str[i+1:]
else:
left, fmt_spec = node_str, None
else:
left, fmt_spec = node_str.split(':', 1)
if 'lambda' in left:
left = node_str
if fmt_spec is not None and not fmt_spec:
raise SyntaxError('need format specifier after ":"')
else:
left = node_str
splitd = left.rsplit('!', 1)
if len(splitd) > 1:
expr, cvs_spec = splitd
if cvs_spec not in _cvss:
raise SyntaxError('optional conversions must be one of'
' {}'.format(_cvss))
else:
expr = splitd[0]
return expr.strip()
<file_sep># -*- coding: utf-8 -*-
import sys
from datetime import datetime # noqa
from fmt.fmt import Fmt, Parser, Text
import fmt as f
def test_parsed_nodes_been_cached(monkeypatch):
call_count = []
def _parse(self):
call_count.append(1)
return [Text('baz')]
monkeypatch.setattr(Parser, 'parse', _parse)
fmt = Fmt()
count = 0
for f_str in ('foo', 'bar'):
count += 1
fmt(f_str)
assert f_str in fmt._nodes_cache
assert len(call_count) == count
value = fmt._nodes_cache[f_str][0]
for _ in range(5):
fmt(f_str)
assert f_str in fmt._nodes_cache
assert len(call_count) == count, f_str
assert id(value) == id(fmt._nodes_cache[f_str][0])
g_foo = 'global-foo'
g_bar = 'global-bar'
def func(x, y):
return str(x) + str(y)
def get_namesapce(*_args):
frame = sys._getframe(1)
return frame.f_globals, frame.f_locals
def test_namespace():
l_foo = 'local-foo'
l_bar = 'local-bar'
globals_, locals_ = get_namesapce()
assert 'l_foo' in locals_
assert 'l_bar' in locals_
assert 'g_bar' in globals_
assert 'g_bar' in globals_
assert '@py_builtins' in globals_
assert 'sys' in globals_
assert 'func' in globals_
def test_closure_namespace():
def outer(x):
y = 'yy'
def inner():
z = 'zz'
globals_, locals_ = get_namesapce(x, y)
assert 'x' in locals_
assert 'y' in locals_
assert 'z' in locals_
assert 'g_bar' in globals_
assert 'g_bar' in globals_
assert '@py_builtins' in globals_
assert 'sys' in globals_
assert 'func' in globals_
return inner
outer('xx')()
def test_fmt():
l_foo = 'local-foo'
l_bar = 'local-bar'
ls_num = range(5)
ls_ch = ['a', 'b', 'c', 'd', 'e']
class Baz(object):
def __str__(self):
return 'BAZ'
f.register('x', 13)
f.register('y', 14)
assert '' == f('')
assert '{' == f('{{')
assert '{ {}' == f('{{ {{}}')
assert '}' == f('}}')
assert '{} }' == f('{{}} }}')
assert '{}' == f('{{}}')
assert '{ }' == f('{{ }}')
assert 'local-foo, local-bar' == f('{l_foo}, {l_bar}')
for i in ls_num:
assert str(i) == f('{ls_num[' + str(i) + ']}')
for i, c in enumerate(ls_ch):
assert "'{}'".format(c) == f('{ls_ch[' + str(i) + ']!r}')
assert 'global-foo, global-bar' == f('{g_foo}, {g_bar}')
assert '1314' == f('{func(x, y)}')
def outer(arg):
def inner():
assert '{ outer-arg }' == f('{{ {arg} }}', arg)
return inner
outer('outer-arg')()
# Py3 range return iterator
assert '[0, 1, 2, 3, 4]' == f('{list(range(5))}')
assert '[0, 1, 2, 3, 4]' == f('{[i for i in ls_num]}')
if sys.version_info[0] == 2:
assert 'set([0, 1, 2, 3, 4])' == f('{{i for i in ls_num}}')
else:
assert '{0, 1, 2, 3, 4}' == f('{{i for i in ls_num}}')
assert ("{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}" ==
f('{{k:v for k,v in zip(ls_num, ls_ch)}}'))
assert '[1, 2, 3, 4, 5]' == f('{list(map(lambda x: x+1, ls_num))}')
assert '3' == f('{1+2}')
assert "'1314'" == f('{"13" + "14"!r}')
assert "BAZ" == f('{Baz()!s}')
assert '{}'.format(sys.argv) == f('{sys.argv}')
assert ('int:23, hex:17, oct:0o27, bin:0b10111' ==
f('int:{23:d}, hex:{23:x}, oct:{23:#o}, bin:{23:#b}'))
assert '1,234,567,890' == f('{1234567890:,}')
assert '1994-11-06' == f('{datetime(1994, 11, 6):%Y-%m-%d}')
assert '1994-11-06 00:00:00' == f('{datetime(1994, 11, 6, 0, 0, 0):%Y-%m-%d %H:%M:%S}')
assert 'None' == f('{(lambda: None)()}')
assert '1994:11:06' == f('{(lambda: datetime(1994, 11, 6))():%Y:%m:%d}')
assert '1994-11-06 00:00:00' == f('{(lambda: datetime(1994, 11, 6, 0, 0, 0))():%Y-%m-%d %H:%M:%S}')
assert g_foo not in f._g_ns
assert g_bar not in f._g_ns
assert l_foo not in f._g_ns
assert l_bar not in f._g_ns
<file_sep># -*- coding: utf-8 -*-
import pytest
from fmt.fmt import Text, Constant, Expression
def test_flyweight():
assert id(Text('foo', 'bar')) == id(Text('foo', 'bar'))
assert id(Constant('foo', 'bar')) == id(Constant('foo', 'bar'))
assert id(Expression('foo', 'bar')) == id(Expression('foo', 'bar'))
assert id(Text('foo', 'bar')) != id(Text('bar', 'foo'))
assert id(Constant('foo', 'bar')) != id(Constant('bar', 'foo'))
assert id(Expression('foo', 'bar')) != id(Expression('bar', 'foo'))
assert id(Text('foo', 'bar')) != id(Constant('foo', 'bar'))
assert id(Text('foo', 'bar')) != id(Expression('foo', 'bar'))
assert id(Constant('foo', 'bar')) != id(Expression('foo', 'bar'))
def test_Text():
text = 'I am a good man, /(ㄒoㄒ)/~~'
assert text == Text(text).generate(None)
texts = ['yes', 'or', 'no']
assert ''.join(texts) == Text(*texts).generate(None)
def test_Constant():
name = 'foo'
fmt = '{foo}'
ns = {name: 'bar'}
const = Constant(name, fmt)
assert fmt.format(**ns) == const.generate(ns)
with pytest.raises(NameError):
const.generate({})
def test_Expression():
def func(dd):
return str(dd) + '++'
ns = {'dd': '--', 'func': func}
expr = 'func(dd)'
fmt = '{func(dd) }'
expression = Expression(expr, fmt)
assert '{}'.format(func(ns['dd'])) == expression.generate(ns)
with pytest.raises(NameError):
expression.generate({})
<file_sep>clean:
find . -type f -name '*.pyc' -exec rm -f {} +
find . -type f -name '*.pyo' -exec rm -f {} +
find . -type f -name '*.~' -exec rm -f {} +
find . -type d -name '__pycache__' -exec rm -rf {} +
test:
flake8 fmt
# pylint fmt
pip install -e .
py.test tests -vvv
pkg:
python setup.py bdist_wheel
python setup.py sdist
<file_sep># -*- coding: utf-8 -*-
import pytest
from fmt.fmt import Parser, Text, Constant, Expression
def test_parse_node_str():
parser = Parser('')
assert 'name' == parser._parse_node_str('name ')
assert 'name' == parser._parse_node_str('name!r')
assert 'name' == parser._parse_node_str('name!s')
assert 'name' == parser._parse_node_str('name!a')
assert 'name' == parser._parse_node_str('name:fmt')
assert 'name' == parser._parse_node_str('name!r:fmt')
assert ('map(lambda x: x, ls)' ==
parser._parse_node_str('map(lambda x: x, ls)'))
with pytest.raises(SyntaxError):
parser._parse_node_str('name!n')
with pytest.raises(SyntaxError):
parser._parse_node_str('name:')
def test_parse_node():
parser = Parser('')
node_str = 'name!r:fmt'
node = parser._parse_node(node_str)
assert isinstance(node, Constant)
assert node._fmt == '{' + node_str + '}'
node_strs = ['[i for i in ls]', 'func()', 'map(lambda x: x, ls)']
for node_str in node_strs:
node = parser._parse_node(node_str)
assert isinstance(node, Expression)
assert node._fmt == '{name}'
with pytest.raises(SyntaxError):
parser._parse_node('a = b')
def test_is_dict_or_set_comp():
parser = Parser('')
assert parser._is_dict_or_set_comp('i for i in range(10)')
assert parser._is_dict_or_set_comp('k:v for k,v in d.items()')
assert parser._is_dict_or_set_comp('k:v for k,v in zip(ls1, ls2)')
assert not parser._is_dict_or_set_comp('for')
assert not parser._is_dict_or_set_comp('for_in')
def test_replace_with_spaces():
parser = Parser('')
assert ('a b c d e f g' ==
parser._replace_with_spaces(' a b\nc\rd\fe\vf\n\ng '))
def test_check_braces():
parser = Parser('')
assert '' == parser._check_braces('{', False, '{')
assert '{' == parser._check_braces('{{{', False, '{')
assert '{ ' == parser._check_braces('{{ {', False, '{')
assert '{ { ' == parser._check_braces('{{ {{ {', False, '{')
assert '' == parser._check_braces('{{', True, '{')
assert ' }' == parser._check_braces('} }}', False, '}')
assert '{ ' == parser._check_braces('{{ {{', True, '{')
assert '{ {' == parser._check_braces('{{ {{', True, '{', True)
assert '{{' == parser._check_braces('{{{{', True, '{', True)
with pytest.raises(SyntaxError):
parser._check_braces('{{{', True, '{')
with pytest.raises(SyntaxError):
parser._check_braces('{', True, '{')
with pytest.raises(SyntaxError):
parser._check_braces('{{ {', True, '{')
with pytest.raises(SyntaxError):
parser._check_braces('{ { { {', True, '{', True)
with pytest.raises(SyntaxError):
parser._check_braces('{{', False, '{')
with pytest.raises(SyntaxError):
parser._check_braces('{{ {{', False, '{')
def test_parse_with_only_text():
nodes = Parser('').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Text)
assert '' == nodes[0]._content
nodes = Parser(' ').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Text)
assert ' ' == nodes[0]._content
nodes = Parser('name').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'name' == nodes[0]._content
nodes = Parser('{{}}').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Text)
assert '{}' == nodes[0]._content
nodes = Parser('{{name}}').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Text)
assert '{name}' == nodes[0]._content
nodes = Parser('text{{name}}').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert '{name}' == nodes[1]._content
nodes = Parser('{{name}}text').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert '{name}' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert 'text' == nodes[1]._content
nodes = Parser('{{ name }} ').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert '{ name }' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert ' ' == nodes[1]._content
def test_parse_constant():
nodes = Parser('{name}').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Constant)
assert 'name' == nodes[0]._name
assert '{name}' == nodes[0]._fmt
nodes = Parser('{ name }').parse()
assert 1 == len(nodes)
assert isinstance(nodes[0], Constant)
assert 'name' == nodes[0]._name
assert '{name}' == nodes[0]._fmt
nodes = Parser('text {{{name} text').parse()
assert 4 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert '{' == nodes[1]._content
assert isinstance(nodes[2], Constant)
assert 'name' == nodes[2]._name
assert '{name}' == nodes[2]._fmt
assert isinstance(nodes[3], Text)
assert ' text' == nodes[3]._content
nodes = Parser('text {{ {name} text').parse()
assert 4 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert '{ ' == nodes[1]._content
assert isinstance(nodes[2], Constant)
assert 'name' == nodes[2]._name
assert '{name}' == nodes[2]._fmt
assert isinstance(nodes[3], Text)
assert ' text' == nodes[3]._content
nodes = Parser('text {name}}} text').parse()
assert 4 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Constant)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert isinstance(nodes[2], Text)
assert '}' == nodes[2]._content
assert isinstance(nodes[3], Text)
assert ' text' == nodes[3]._content
nodes = Parser('text {name} }} text').parse()
assert 4 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Constant)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert isinstance(nodes[2], Text)
assert ' }' == nodes[2]._content
assert isinstance(nodes[3], Text)
assert ' text' == nodes[3]._content
nodes = Parser('text {name} text').parse()
assert 3 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Constant)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert isinstance(nodes[2], Text)
assert ' text' == nodes[2]._content
nodes = Parser('text {name}done').parse()
assert 3 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Constant)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert isinstance(nodes[2], Text)
assert 'done' == nodes[2]._content
nodes = Parser('text {{{name}}}').parse()
assert 4 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Text)
assert '{' == nodes[1]._content
assert isinstance(nodes[2], Constant)
assert 'name' == nodes[2]._name
assert '{name}' == nodes[2]._fmt
assert isinstance(nodes[3], Text)
assert '}' == nodes[3]._content
def test_parse_expression():
nodes = Parser('text {{v for v in range(10)}}').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Expression)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert '{v for v in range(10)}' == nodes[1]._expr
nodes = Parser('text {{k:v for k,v in zip(ls1, ls2)}}').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Expression)
assert 'name' == nodes[1]._name
assert '{k:v for k,v in zip(ls1, ls2)}' == nodes[1]._expr
assert '{name}' == nodes[1]._fmt
nodes = Parser('text {map(lambda x: x, ls)}').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Expression)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert 'map(lambda x: x, ls)' == nodes[1]._expr
nodes = Parser('text {func()}').parse()
assert 2 == len(nodes)
assert isinstance(nodes[0], Text)
assert 'text ' == nodes[0]._content
assert isinstance(nodes[1], Expression)
assert 'name' == nodes[1]._name
assert '{name}' == nodes[1]._fmt
assert 'func()' == nodes[1]._expr
def test_parser_with_error():
with pytest.raises(SyntaxError):
Parser('{').parse()
with pytest.raises(SyntaxError):
Parser('}').parse()
with pytest.raises(SyntaxError):
Parser('{}').parse()
with pytest.raises(SyntaxError):
Parser('text {name').parse()
with pytest.raises(SyntaxError):
Parser('text {{name}').parse()
with pytest.raises(SyntaxError):
Parser('text { {name').parse()
with pytest.raises(SyntaxError):
Parser('text {{ { {name').parse()
with pytest.raises(SyntaxError):
Parser('text {name}}').parse()
with pytest.raises(SyntaxError):
Parser('text {name} }').parse()
with pytest.raises(SyntaxError):
Parser('text {name} }} }').parse()
|
772304d2c1346a2ed37a06d368af93d8dfd2fdc6
|
[
"Python",
"Makefile",
"reStructuredText"
] | 8
|
Python
|
damnever/fmt
|
29c8b49a825168d0f9d5ec826275962592ff0f94
|
001cda1f9246bf7939f7011f6e69078b071d37cc
|
refs/heads/master
|
<file_sep>var myPage = {
id: 'XXXXXXXXXXXXX',
access_token: null,
};
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
userLoggedIn();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
userLoggedOut();
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
userLoggedOut();
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function userLoggedIn() {
btn = document.getElementById("loginButton");
btn.className = btn.className.replace("btn-success", "btn-danger");
document.getElementById("buttons_navbar").style.display = "block";
btn.textContent = "Log out";
btn.setAttribute("onclick", "logoutWithButton()");
getPageAccessToken(myPage.id, function(token) {
myPage.access_token = token;
console.log(myPage.access_token);
});
}
function userLoggedOut() {
btn = document.getElementById("loginButton");
btn.className = btn.className.replace("btn-danger", "btn-success");
document.getElementById("buttons_navbar").style.display = "none";
btn.textContent = "Log In";
btn.setAttribute("onclick", "loginWithButton()")
}
function logoutWithButton() {
FB.logout(function(response) {
checkLoginState();
console.log(response);
});
}
function loginWithButton() {
FB.login(function(response) {
if (response.authResponse) {
checkLoginState();
}} , {scope: 'publish_actions,manage_pages,publish_pages'});
}
function postToPage() {
var title = document.getElementById('previewTitle').textContent;
var url = document.getElementById('previewUrl').textContent;
var info = document.getElementById('previewInfo').textContent;
var body = document.getElementById('previewBody').textContent
var img = document.getElementById('previewImg').src;
var msg = title + '\n' + url+ '\n' + info + '\n' + body;
FB.api('/' + myPage.id + '/photos', 'post', {'access_token': myPage.access_token, 'caption': msg, 'url': img}, function(response) {
if (response && !response.error) {
alert("Post succesful!");
}
else
{
alert(response['error']['message']);
}
});
}
function getPageAccessToken(myPageId, callback) {
FB.api('/me/accounts', function(response) {
for (var i=0; i < response.data.length; i++) {
if (response.data[i].id == myPageId) {
console.log(response.data[i].access_token);
callback(response.data[i].access_token);
}
else
{
callback(null);
}
}
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1321362891254036',
xfbml : true,
version : 'v2.8'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<file_sep>var http = require('http');
var request = require('request');
var jsdom = require('jsdom').jsdom;
var port = 3000;
var server = http.createServer((req, res) => {
console.log('Got request!');
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
buildData((data) => {
res.end(JSON.stringify(data));
});
});
server.listen(port, () => {
console.log('Server running at port ' + port);
});
function scrapper(url, callback) {
request(url, (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log('Got: ' + url);
var document = jsdom(body);
callback(document);
}
});
}
function buildData(callback) {
scrapper('http://observatorio.info', (observatorio) => {
scrapper('https://apod.nasa.gov/apod/archivepix.html', (apod_archive) => {
var url = 'https://apod.nasa.gov/apod/' + apod_archive.getElementsByTagName('a')[3].getAttribute('href');
var img = observatorio.getElementsByTagName('img')[1].getAttribute('src');
var body = observatorio.getElementsByTagName('p')[1].textContent;
var title = observatorio.getElementsByClassName('intro')[0].textContent;
var info = observatorio.getElementsByClassName('info')[0];
info.innerHTML = info.innerHTML.replace('<br>', '\n');
info = info.textContent;
callback({'title': title, 'info': info, 'body': body, 'img': img, 'url': url});
});
});
}<file_sep># ApodAutomat
Really alpha project just for myself, It has no real use.
|
32b015126d1e197ba0ea2f5d25a1135b0926417c
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
ekistece/ApodAutomat
|
9631c6f648f948addd529dafdf658c23574fb1d2
|
67f898705d6cc61147654b8718cb60776bfbecd8
|
refs/heads/master
|
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace DesvieDosBuracosSeForCapaz.GameObjects
{
public class Cenario : GameObject2D
{
int _largura;
int _altura;
public Cenario(GraphicsDeviceManager graphics, Vector2 velocidade)
{
Velocidade = velocidade;
_largura = graphics.GraphicsDevice.DisplayMode.Width;
_altura = graphics.GraphicsDevice.DisplayMode.Height;
}
/// <summary>
/// Atualiza a posição Y de acordo com a velocidade Y
/// </summary>
public void Update()
{
Posicao.Y += Velocidade.Y;
if (Posicao.Y >= _altura)
Posicao.Y = 0f;
}
public override void Draw(SpriteBatch spriteBatch)
{
// Desenha o cenario dentro da tela do dispositivo
// Ex.: Eixo X = 0, Eixo Y = 0
spriteBatch.Draw(_textura, new Rectangle(0, (int)Posicao.Y, _largura, _altura), Color.White);
// Desenha o cenario fora da tela do dispositivo
// Ex.: Eixo X = 0, Eixo Y = (0 - alturaDaTelaDoDispositivo)
spriteBatch.Draw(_textura, new Rectangle(0, (int)(Posicao.Y - _altura), _largura, _altura), Color.White);
}
}
}<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace DesvieDosBuracosSeForCapaz.GameObjects
{
/// <summary>
/// Classe base para objetos de jogo em 2D.
/// </summary>
public class GameObject2D
{
protected Texture2D _textura;
public Texture2D Textura { get { return _textura; } }
public Vector2 Posicao;
public Vector2 Velocidade;
public Vector2 Origem = Vector2.Zero;
public Rectangle Limites
{
get
{
if (_textura != null && Posicao != null)
return new Rectangle((int)Posicao.X, (int)Posicao.Y, _textura.Width, _textura.Height);
return Rectangle.Empty;
}
}
public virtual void Load(ContentManager content, string assetName)
{
// Carrega a sprite/imagem é atribui o resultado á variavel _texture
// para ser utilizada posteriomente no método Draw.
_textura = content.Load<Texture2D>(assetName);
}
public virtual void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(
_textura, // A textura que será desenhada.
Posicao, // Um objeto do tipo Vector2 contendo a posição para que a textura seja desenhada.
null, // Uma região especifica na textura que será desenhada. Se null desenha a textura completa.
Color.White, // Máscara de cor.
0f, // Rotaciona a sprite/imagem.
Origem, // Um objeto do tipo Vector2 contendo a origem de movimentação e rotação. O padrão é X = 0 e Y = 0.
Vector2.One, // Dimensionamento da sprite/imagem.
SpriteEffects.None, // Efeito aplicado no momento de desenhar a textura.
0f // Uma profundidade da camada da sprite.
);
}
}
}<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
namespace DesvieDosBuracosSeForCapaz.GameObjects
{
public class BotaoStart : GameObject2D
{
public bool Start(ref TouchCollection touchLocations)
{
bool touchEmCimaDoBotao = false;
foreach (TouchLocation touchLocation in touchLocations)
{
if (touchLocation.State == TouchLocationState.Released)
{
// Condicional para verificar se o touch do usuário
// na tela do dispositivo está ocorrendo em cima do botão start
touchEmCimaDoBotao = Limites.Intersects(new Rectangle(
(int)touchLocation.Position.X,
(int)touchLocation.Position.Y, 0, 0));
}
}
return touchEmCimaDoBotao;
}
/// <summary>
/// Posiciona o botão no centro da tela
/// </summary>
/// <param name="graphics"></param>
public void SetaPosicao(ref GraphicsDeviceManager graphics)
{
var posX = (graphics.GraphicsDevice.DisplayMode.Width / 2 - _textura.Width / 2);
var posY = (graphics.GraphicsDevice.DisplayMode.Height / 2 - _textura.Height / 2);
Posicao = new Vector2(posX, posY);
}
}
}<file_sep>using DesvieDosBuracosSeForCapaz.GameObjects;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
namespace DesvieDosBuracosSeForCapaz
{
public class Game1 : Game
{
GraphicsDeviceManager _graphics;
SpriteBatch _spriteBatch;
// Objetos do jogo.
Carro _carro;
List<Buraco> _buracos;
Cenario _cenario;
SpriteFont _fonte;
SpriteFont _fonteGameOver;
BotaoStart _btnStart;
bool _start = false;
int _descontoIPVA = 0;
// Manipula os conteudos de sons
Song _musica;
SoundEffect _somColisao;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
_graphics.IsFullScreen = true;
}
protected override void Initialize()
{
Vector2 velocidade = new Vector2(0, 11);
// Instância os objetos do jogo.
_carro = new Carro { Resistencia = 100 };
_buracos = new List<Buraco>();
_cenario = new Cenario(_graphics, velocidade);
_btnStart = new BotaoStart();
// Cria os buracos com uma velocidade para o eixo X de Zero
// e eixo Y de 11 adicionando o mesmo na lista.
for (int i = 0; i < 5; i++)
{
_buracos.Add(new Buraco
{
Velocidade = velocidade,
Dano = GetDanoAleatorio()
});
}
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// Carrega os sons
_musica = Content.Load<Song>("Sons/Fringe");
_somColisao = Content.Load<SoundEffect>("Sons/colisao");
// Toca a música repetidamente
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(_musica);
// Carrega o cenário
_cenario.Load(Content, "Sprite/cenario");
// Carrega o arquivo de fonte.
_fonte = Content.Load<SpriteFont>("fonte");
_fonteGameOver = Content.Load<SpriteFont>("fonteGameOver");
// Carrega os sprites/imagens.
// Utilizando o método Load herdado da classe GameObject2D.
_carro.Load(Content, "Sprite/carro");
foreach (var buraco in _buracos)
buraco.Load(Content, "Sprite/buraco");
_btnStart.Load(Content, "Sprite/btn_start");
// Seta a posição inicial dos objetos do jogo.
int i = 0;
do
{
// Posição buraco atual
_buracos[i].SetaPosicaoAleatoria(ref _graphics);
if (i > 0 && _buracos[i].Limites.Intersects(_buracos[i - 1].Limites))
{
i--;
// Posição buraco anterior
_buracos[i].SetaPosicaoAleatoria(ref _graphics);
}
i++;
} while (i < _buracos.Count);
_carro.SetaPosicaoInicial(ref _graphics);
_btnStart.SetaPosicao(ref _graphics);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
TouchCollection touchLocations = TouchPanel.GetState();
if (_btnStart.Start(ref touchLocations) && _carro.Resistencia == 100)
_start = true;
if (_start)
{
#region Movimenta os objetos do jogo.
_carro.Mover(ref touchLocations, ref _graphics);
foreach (var buraco in _buracos)
{
buraco.Posicao.Y += buraco.Velocidade.Y;
// Ações realizadas quando o buraco sai da tela.
if (buraco.Posicao.Y > _graphics.GraphicsDevice.DisplayMode.Height)
{
// Não colidiu com o carro?
if (!buraco.JaColidiu)
_descontoIPVA += 50;
buraco.SetaPosicaoAleatoria(ref _graphics);
buraco.Dano = GetDanoAleatorio();
buraco.JaColidiu = false;
}
// Ocorreu uma colisão?
if (buraco.ColidiuCom(ref _carro))
{
_somColisao.Play();
buraco.JaColidiu = true;
_carro.Resistencia -= buraco.Dano;
}
if (_carro.Resistencia <= 0)
{
_carro.Resistencia = 0;
_start = false;
}
}
#endregion
// Atualiza a posição Y do cenário.
_cenario.Update();
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin(); // Chamada obrigatória antes de desenhar os objetos
// Desenha o cenário
_cenario.Draw(_spriteBatch);
if (!_start && _carro.Resistencia == 100)
_btnStart.Draw(_spriteBatch);
if (_start)
{
// Desenha os objetos do jogo;
// Utilizando o método Draw herdado da classe GameObject2D.
foreach (var buraco in _buracos)
buraco.Draw(_spriteBatch);
_carro.Draw(_spriteBatch);
}
if (!_start && _carro.Resistencia <= 0)
{
var gameOver = "GAME\nOVER";
var tamanhoString = _fonteGameOver.MeasureString(gameOver);
_spriteBatch.DrawString(_fonteGameOver, gameOver,
new Vector2((_graphics.GraphicsDevice.DisplayMode.Width - tamanhoString.X) / 2,
(_graphics.GraphicsDevice.DisplayMode.Height - tamanhoString.Y) / 2),
Color.DarkRed);
}
#region Desenha textos de desconto IPVA e resistência do carro
_spriteBatch.DrawString(_fonte, $"RES. CARRO.: {_carro.Resistencia}", new Vector2(50, 10), Color.White);
_spriteBatch.DrawString(_fonte, $"DESC. IPVA.: {_descontoIPVA:c}", new Vector2(50, 75), Color.White);
#endregion
_spriteBatch.End(); // Chamada obrigatória após desenhar os objetos
base.Draw(gameTime);
}
private int GetDanoAleatorio()
{
var random = new Random();
return random.Next(1, 10);
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
namespace DesvieDosBuracosSeForCapaz.GameObjects
{
public class Buraco : GameObject2D
{
public int Dano { get; set; }
/// <summary>
/// Propriedade para garantir o registro de apenas uma colisão
/// </summary>
public bool JaColidiu { get; set; }
/// <summary>
/// Define uma posição aleatória inicial.
/// </summary>
/// <param name="graphics"></param>
public void SetaPosicaoAleatoria(ref GraphicsDeviceManager graphics)
{
var random = new Random();
// Gera um número aleatório entre 0 e o tamanho da tela menos a largura da textura.
var posX = random.Next(0, graphics.GraphicsDevice.DisplayMode.Width - _textura.Width);
// Gera um número aleatório entre 60% NEGATIVO da altura da tela e 0.
var posY = random.Next((int)(graphics.GraphicsDevice.DisplayMode.Height * -0.6), 0);
Posicao = new Vector2(posX, posY);
}
/// <summary>
/// Verifica se os limites do buraco se intecepta com os limites do carro
/// e se o carro já caiu no buraco
/// </summary>
/// <param name="carro">Objeto carro para validar colisão</param>
/// <returns>Boolean</returns>
public bool ColidiuCom(ref Carro carro)
{
return Limites.Intersects(carro.Limites) && !JaColidiu;
}
}
}<file_sep># MonoGame Tutorial
Repositório com os exemplos do tutorial de MonoGame publicado no [Medium](https://medium.com/@ronildo.souza/monogame-tutorial-parte-1-introdu%C3%A7%C3%A3o-6e1a3f4d973f)
# PLANO DO JOGO
**Nome:**
- <NAME>
**Categoria:**
- Simulação
**Época:**
- Presente
**Personagens:**
- Carro (Jogador), Buracos (Inimigo)
**Cenário:**
- Uma rua esburacada
**História:**
- Após 1 ano de trabalho duro nada melhor que uma bela viagem para curtir os 30 dias de férias, devido ao alto custo das passagens aéreas a melhor opção custo/beneficio será viajar de carro uma forma confortável é tranquila, porém cada quilômetro na estrada é uma surpresa, buracos é mais buracos, mesmo pensando: “Para que server o IPVA!?”, o jogador não desiste é prossegue com a viagem.
**Regras:**
- O carro do jogador possuíra uma resistência de 100% e uma velocidade de 110km/h.
- Os buracos causaram um dano aleatório de 1% á 10%.
- A cada buraco desviado o jogador ganhará desconto no IPVA.
- Para movimentar o carro o usuário deverá manter o dedo pressionado sobre o mesmo e arrastar para a direção desejada.
- O carro se movimenta para todas as direções, porem não pode ultrapassar 80% da tela do dispositivo quando for para a frente.
- Ao "cair" em um buraco o dano deverá ser causado apenas no primeiro
-----
<p align="center">
<img src="./gif/game.gif">
</p>
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
namespace GameTeste
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont fonte;
Vector2 posicao;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 480;
graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
posicao = Vector2.Zero;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
fonte = Content.Load<SpriteFont>("fonte");
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
// TODO: Add your update logic here
TouchCollection touchState = TouchPanel.GetState();
foreach (TouchLocation touch in touchState)
posicao = touch.Position;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.DrawString(fonte, "Hello MonoGame!", posicao, Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
namespace DesvieDosBuracosSeForCapaz.GameObjects
{
public class Carro : GameObject2D
{
public int Resistencia { get; set; }
/// <summary>
/// Move o carro quando o usuário mantem o dedo pressionado na tela e arrasta para a direção desejada.
/// </summary>
/// <param name="touchCollection"></param>
/// <param name="graphics"></param>
public void Mover(ref TouchCollection touchCollection, ref GraphicsDeviceManager graphics)
{
// Variavel criada para armazenar a localização anterior
// da ação de touch do usuário na tela do dispositivo.
TouchLocation touchLocationAnterior = new TouchLocation();
// O objeto touchCollection traz a localização atual
// da ação de touch do usuário na tela do dispositivo.
foreach (TouchLocation touchLocationAtual in touchCollection)
{
touchLocationAtual.TryGetPreviousLocation(out touchLocationAnterior);
if (touchLocationAtual.State != TouchLocationState.Released &&
touchLocationAnterior.State == TouchLocationState.Moved)
{
// Condicional para verificar se o touch do usuário
// na tela do dispositivo está ocorrendo em cima do carro
bool touchEmCimaDoCarro = Limites.Intersects(new Rectangle(
(int)touchLocationAtual.Position.X,
(int)touchLocationAtual.Position.Y, 0, 0));
if (touchEmCimaDoCarro)
{
Posicao.X = MathHelper.Clamp(
(touchLocationAtual.Position.X - _textura.Width / 2), // Posição X do touch do usuário menos a metade da largura da textura;
0, // Valor minimo para X.
graphics.GraphicsDevice.DisplayMode.Width - _textura.Width // Valor maximo para X. Largura da tela do dispositivo menos a largura da textura.
);
Posicao.Y = MathHelper.Clamp(
(touchLocationAtual.Position.Y - _textura.Height / 2), // Posição Y do touch do usuário menos a metade da altura da textura;
(float)(graphics.GraphicsDevice.DisplayMode.Height * 0.2), // Valor minimo para Y. 20% da altura da tela do dispositivo.
(graphics.GraphicsDevice.DisplayMode.Height - _textura.Height) // Valor maximo para Y. Altura da tela do dispositivo menos a altura da textura.
);
}
}
}
}
/// <summary>
/// Posiciona o carro na parte inferior centralizado ao centro da tela.
/// </summary>
/// <param name="graphics"></param>
public void SetaPosicaoInicial(ref GraphicsDeviceManager graphics)
{
var posX = (graphics.GraphicsDevice.DisplayMode.Width / 2 - _textura.Width / 2);
var posY = (graphics.GraphicsDevice.DisplayMode.Height - _textura.Height);
Posicao = new Vector2(posX, posY);
}
}
}
|
90c9db8cfd0689f79957aa6c090a36386ea89c45
|
[
"Markdown",
"C#"
] | 8
|
C#
|
RonildoSouza/MonoGameTutorial
|
c11174c8ef47679f6ba3fefdcb16614d7a2dab19
|
d79ddc92e3a9e9ce1fd023297ae7c6f0db6cdb7a
|
refs/heads/master
|
<repo_name>TBmo7/portfolio-app<file_sep>/myportfolio/src/Components/ProjectCard.js
import React from "react"
import "../Style/ProjectCard.css"
function ProjectCard(props){
console.log(props)
console.log(props.image);
return(
<div className = "card-container">
<div
className = "card-information"
// style = {{ backgroundImage: `url(${props.image})`}}
>
<img src = {props.image} alt = "" />
<div className = "text-update">
<p>{props.name}</p>
<p>Responsibilities: {props.resp}</p>
<p>Technologies used: {props.tech}</p>
<p>{props.desc}</p>
<a href = {props.link}
target = "_blank"
rel = "noopener noreferrer"
>Link: {props.name}</a>
</div>
</div>
</div>
)
}
export default ProjectCard<file_sep>/myportfolio/src/Components/Home.js
import React from "react"
import "../Style/Home.css"
import {Link} from "react-router-dom"
function Home(){
return(
<div className = "home-page-container">
<div className = "content-holder">
<Link to = "/Contact" className = "top-contact-link">
<div className = "top-contact">
<p>Contact</p>
</div>
</Link>
<Link to = "/About" className = "top-Troy-link" >
<div className = "top-Troy">
<p ><NAME></p>
</div>
</Link>
<Link to = "/Projects" className = "top-projects-link">
<div className = "top-projects">
<p> Projects</p>
</div>
</Link>
</div>
<div className = "middle-block">
<div className = "middle-color">
<p>I design unique online experiences</p>
<div className = "image-container">
Thar be images here
<div className = "theLinks"></div>
</div>
</div>
</div>
<div className = "bot-nav-image">
<div className = "bottom-nav">
<Link to = "/About">
<button>About Me</button>
</Link>
<Link to ="/Contact">
<button>Contact</button>
</Link>
<Link to = "/Projects">
<button>Projects</button>
</Link>
</div>
</div>
</div>
)
}
export default Home<file_sep>/myportfolio/src/Components/Contact.js
import React from "react"
import {Link} from "react-router-dom"
import "../Style/Contact.css"
function Contact(){
return(
<div className = "contact-holder">
<div className = "content-holder">
<Link to = "/Contact" className = "top-contact-link">
<div className = "top-contact">
<p>Contact</p>
</div>
</Link>
<Link to = "/" className = "top-Troy-link" >
<div className = "top-Troy">
<p >Home</p>
</div>
</Link>
<Link to = "/Projects" className = "top-projects-link">
<div className = "top-projects">
<p> Projects</p>
</div>
</Link>
</div>
<div className = "middle-block">
<div className = "contact-info">
<p>professional email here</p>
<p>Link to Github here</p>
<p>Link to twitter here</p>
<p>Link to Linked in here</p>
<p>Link to blog</p>
</div>
</div>
<div className = "bot-nav-image">
<div className = "bottom-nav">
<Link to = "/About">
<button>About Me</button>
</Link>
<Link to ="/Contact">
<button>Contact</button>
</Link>
<Link to = "/Projects">
<button>Projects</button>
</Link>
</div>
</div>
</div>
)
}
export default Contact;<file_sep>/myportfolio/src/Components/Projects.js
import React from "react"
import {Link} from "react-router-dom"
import ProjectCard from "./ProjectCard"
import "../Style/Projects.css"
import projImg from "../Images/empowered-conversations.PNG"
import proj2Img from "../Images/sauti-dash.PNG"
function Projects(){
const projectArray = [
{
name:"<NAME>",
technologies:"HTML, CSS, JS, LESS",
responsibilities:"Created a landing page and an about page for an app focused on mental health",
link:"https://atempoweredconversations.netlify.com",
image: projImg,
id:1,
description:"Worked with another front end student to create the design, copy and code for the small site you see here."
},
{
name:"<NAME>",
technologies:"HTML, CSS, JS, React, Axios, Styled Components",
responsibilities:"Created a market listing populated via API call, included searchable forms, and designed the homepage for the app ",
link:"https://sauti-frontend.netlify.com",
image: proj2Img,
id:2,
description: "Worked with a team of react students, and a UI/UX student to create an app that allows East African farmers to find market prices and list their items"
}
]
return(
<div className = "project-container">
<div className = "content-holder">
<Link to = "/Contact" className = "top-contact-link">
<div className = "top-contact">
<p>Contact</p>
</div>
</Link>
<Link to = "/About" className = "top-Troy-link" >
<div className = "top-Troy">
<p ><NAME></p>
</div>
</Link>
<Link to = "/" className = "top-projects-link">
<div className = "top-projects">
<p> Home</p>
</div>
</Link>
</div>
<div className = "middle-block">
<div className = "middle-color">
<div className = "active-projects">
{projectArray.map(item=>(
<ProjectCard
key = {item.id}
name = {item.name}
tech = {item.technologies}
resp = {item.responsibilities}
link = {item.link}
image = {item.image}
desc = {item.description}
/>
))}
</div>
</div>
</div>
<div className = "bot-nav-image">
<div className = "bottom-nav">
<Link to = "/About">
<button>About Me</button>
</Link>
<Link to ="/Contact">
<button>Contact</button>
</Link>
<Link to = "/Projects">
<button>Projects</button>
</Link>
</div>
</div>
<div>
</div>
</div>
)
}
export default Projects;
|
b07bac597d01653c3db4fb20f8eaf5502b921f02
|
[
"JavaScript"
] | 4
|
JavaScript
|
TBmo7/portfolio-app
|
d425e043f2aeb97bf190af22fa9557f809cb4b1d
|
1713bd6e5690d43851345fb1f8c357d5fd456afb
|
refs/heads/master
|
<file_sep>// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package prtree
import (
"math/rand"
"testing"
"time"
"github.com/tidwall/geoindex"
)
func init() {
seed := time.Now().UnixNano()
println("seed:", seed)
rand.Seed(seed)
}
func newWorld() *PRTree {
return New([2]float64{-180, -90}, [2]float64{180, 90})
}
// IsMixedTree is needed for the geoindex.Tests.TestBenchVarious
// Do not remove this function.
func (tr *PRTree) IsMixedTree() bool {
return true
}
func TestGeoIndex(t *testing.T) {
t.Run("BenchVarious", func(t *testing.T) {
geoindex.Tests.TestBenchVarious(t, newWorld(), 1000000)
})
t.Run("RandomRects", func(t *testing.T) {
geoindex.Tests.TestRandomRects(t, newWorld(), 10000)
})
t.Run("RandomPoints", func(t *testing.T) {
geoindex.Tests.TestRandomPoints(t, newWorld(), 10000)
})
t.Run("ZeroPoints", func(t *testing.T) {
geoindex.Tests.TestZeroPoints(t, newWorld())
})
t.Run("CitiesSVG", func(t *testing.T) {
geoindex.Tests.TestCitiesSVG(t, newWorld())
})
}
func BenchmarkRandomInsert(b *testing.B) {
geoindex.Tests.BenchmarkRandomInsert(b, newWorld())
}
<file_sep>// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package prtree
import (
"github.com/tidwall/geoindex/child"
"github.com/tidwall/ptree"
"github.com/tidwall/rtree"
)
// PRTree is a tree for storing points and rects
type PRTree struct {
ptree *ptree.PTree
rtree *rtree.RTree
}
// New returns a new PRTree
func New(min, max [2]float64) *PRTree {
tr := new(PRTree)
tr.ptree = ptree.New(min, max)
tr.rtree = new(rtree.RTree)
return tr
}
// Insert an item into the structure
func (tr *PRTree) Insert(min, max [2]float64, data interface{}) {
if min == max && tr.ptree.InBounds(min) {
tr.ptree.Insert(min, data)
} else {
tr.rtree.Insert(min, max, data)
}
}
// Delete an item from the structure
func (tr *PRTree) Delete(min, max [2]float64, data interface{}) {
if min == max && tr.ptree.InBounds(min) {
tr.ptree.Delete(min, data)
} else {
tr.rtree.Delete(min, max, data)
}
}
// Replace an item in the structure. This is effectively just a Delete
// followed by an Insert. But for some structures it may be possible to
// optimize the operation to avoid multiple passes
func (tr *PRTree) Replace(
oldMin, oldMax [2]float64, oldData interface{},
newMin, newMax [2]float64, newData interface{},
) {
tr.Delete(oldMin, oldMax, oldData)
tr.Insert(newMin, newMax, newData)
}
// Search the structure for items that intersects the rect param
func (tr *PRTree) Search(
min, max [2]float64,
iter func(min, max [2]float64, data interface{}) bool,
) {
var quit bool
tr.ptree.Search(min, max, func(point [2]float64, data interface{}) bool {
if !iter(point, point, data) {
quit = true
return false
}
return true
})
if !quit {
tr.rtree.Search(min, max, iter)
}
}
// Scan iterates through all data in tree in no specified order.
func (tr *PRTree) Scan(iter func(min, max [2]float64, data interface{}) bool) {
var quit bool
tr.ptree.Scan(func(point [2]float64, data interface{}) bool {
if !iter(point, point, data) {
quit = true
return false
}
return true
})
if !quit {
tr.rtree.Scan(iter)
}
}
// Len returns the number of items in tree
func (tr *PRTree) Len() int {
return tr.ptree.Len() + tr.rtree.Len()
}
func expand(amin, amax, bmin, bmax [2]float64) (min, max [2]float64) {
if bmin[0] < amin[0] {
amin[0] = bmin[0]
}
if bmax[0] > amax[0] {
amax[0] = bmax[0]
}
if bmin[1] < amin[1] {
amin[1] = bmin[1]
}
if bmax[1] > amax[1] {
amax[1] = bmax[1]
}
return amin, amax
}
// Bounds returns the minimum bounding box
func (tr *PRTree) Bounds() (min, max [2]float64) {
if tr.ptree.Len() > 0 {
amin, amax := tr.ptree.MinBounds()
if tr.rtree.Len() > 0 {
bmin, bmax := tr.rtree.Bounds()
min, max = expand(amin, amax, bmin, bmax)
} else {
min, max = amin, amax
}
} else if tr.rtree.Len() > 0 {
min, max = tr.rtree.Bounds()
}
return min, max
}
type pChildNode struct {
data interface{}
}
type rChildNode struct {
data interface{}
}
// Children returns all children for parent node. If parent node is nil
// then the root nodes should be returned.
// The reuse buffer is an empty length slice that can optionally be used
// to avoid extra allocations.
func (tr *PRTree) Children(parent interface{}, reuse []child.Child,
) (children []child.Child) {
children = reuse[:0]
switch parent := parent.(type) {
case nil:
// Gather the parent nodes for all PTree and RTree children.
// For all children that are node data (not item data), we'll need to
// wrap the data with a local type to keep track of the which tree the
// node belongs to.
children = tr.ptree.Children(nil, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = pChildNode{children[i].Data}
}
}
mark := len(children)
children = tr.rtree.Children(nil, children)
for i := mark; i < len(children); i++ {
if !children[i].Item {
children[i].Data = rChildNode{children[i].Data}
}
}
return children
case pChildNode:
children = tr.ptree.Children(parent.data, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = pChildNode{children[i].Data}
}
}
case rChildNode:
children = tr.rtree.Children(parent.data, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = rChildNode{children[i].Data}
}
}
default:
panic("invalid node type")
}
return children
}
<file_sep>module github.com/tidwall/prtree
go 1.15
require (
github.com/tidwall/geoindex v1.4.4
github.com/tidwall/ptree v0.1.1
github.com/tidwall/rtree v1.2.8
)
<file_sep># prtree
[](https://godoc.org/github.com/tidwall/prtree)
Just a hybrid data structure that slams my
[rtree](https://github.com/tidwall/rtree) and
[ptree](https://github.com/tidwall/ptree) libraries into one.
|
396c01de1c9f77e38347d940cd72c1c463dd6b9d
|
[
"Markdown",
"Go Module",
"Go"
] | 4
|
Go
|
tidwall/prtree
|
97ee9b06ea95bc2b669137acced591b800829d85
|
645d557c5ac1646bb8f02f7cc9bbebe54b02d1ee
|
refs/heads/master
|
<file_sep>from setuptools import setup, find_packages
setup(
name = "django-template-preprocessor",
url = 'https://github.com/citylive/django-template-preprocessor',
license = 'BSD',
description = "Template preprocessor/compiler for Django",
long_description = open('README.rst','r').read(),
author = '<NAME>, City Live nv',
packages = ['template_preprocessor'], #find_packages('src', exclude=['*.test_project', 'test_project', 'test_project.*', '*.test_project.*']),
package_dir = {'': 'src'},
package_data = {'template_preprocessor': [
'templates/*.html', 'templates/*/*.html', 'templates/*/*/*.html',
'static/*/js/*.js', 'static/*/css/*.css',
],},
include_package_data=True,
zip_safe=False, # Don't create egg files, Django cannot find templates in egg files.
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Framework :: Django',
'Topic :: Software Development :: Internationalization',
],
)
|
7876726c7a10ab5635f05881577499edfa074acb
|
[
"Python"
] | 1
|
Python
|
twidi/django-template-preprocessor
|
ac0e77a29ac29e71eb284b37c674e81f11e172a7
|
62f7d5a97bdb7f0034628310023370d68ca1e9b3
|
refs/heads/master
|
<file_sep>import React from 'react';
const RepoList = (props) => (
<div>
<h4> Repo List Component </h4>
There are {props.repos.length} repos.
</div>
)
export default RepoList;<file_sep>const express = require('express');
const helper = require('../helpers/github.js');
const bodyParser = require('body-parser');
const db = require('../database/index.js');
let app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
//use bodyparser to parse data as string to object
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../client/dist'));
app.post('/repos', function (req, res) {
var githubUser = req.body.user; //tylertuan
helper.getReposByUsername(githubUser, (err, repoData) =>{
if(err){
console.log("error getting data");
res.status(400).end('error');
}else{
db.save(repoData);
res.status(200).end('ok');
}
});
});
app.get('/repos', function (req, res) {
var githubUser = req.query.userid;
//console.log('print: ', req.query);
//db.findReposGt20000(res.json);
db.findReposGt20000(githubUser, res);
});
let port = 1128;
app.listen(port, function() {
console.log(`listening on port ${port}`);
});
// var processRepoData = (err, repoData) => {
// if(err) {
// console.log("error using helper in post request", err);
// }else{
// console.log(repoData);
// return "callback invoked here";
// }
// }
|
06e9e29eac4703fa1f4b503bd3e3e8ca09c1626b
|
[
"JavaScript"
] | 2
|
JavaScript
|
ploratran/fullstack-review
|
357f30036824c48de38f5e3b4de801b5dd758917
|
911eaa3c0c1235c51898f8be48e00f9163f3af6a
|
refs/heads/master
|
<file_sep>/**
*
*/
package com.ssm.service;
import java.util.List;
import com.ssm.pojo.User;
/**
* @author 作者
* @data 2019年7月31日
*/
public interface UserService {
List<User> getAllUser() throws Exception;
}
<file_sep># springboot-dubbo-provider-
springboot整合dubbo,zookeeper集群做协调服务,这个做提供者(服务端)
jdk:1.8,springboot:2.1.6,dubbo:0.2.0
zookeeper:3.4.9,curator:2.12.0
zookeeper集群的其中一个端口:192.168.137.131:2181
```
├─.mvn
│ └─wrapper
│ maven-wrapper.jar
│ maven-wrapper.properties
│ MavenWrapperDownloader.java
│
│
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─ssm
│ │ │ │ DubboProviderApplication.java //启动类
│ │ │ │
│ │ │ ├─mapper
│ │ │ │ UserMapper.java //mybatis接口
│ │ │ │
│ │ │ ├─pojo
│ │ │ │ User.java //bean
│ │ │ │
│ │ │ └─service
│ │ │ │ UserService.java //服务接口
│ │ │ │
│ │ │ └─impl
│ │ │ UserServiceImpl.java //服务实现类
│ │ │
│ │ └─resources
│ │ │ application.yml //全局配置文件
│ │ │
│ │ ├─mapper
│ │ │ UserMapper.xml //mybatis配置文件
│ │ │
│ │ ├─static
│ │ └─templates
```
<file_sep>/**
*
*/
package com.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.alibaba.dubbo.config.annotation.Service;
import com.ssm.mapper.UserMapper;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
/**
* @author 作者
* @data 2019年7月31日
*/
@Service(version = "${demo.service.version}")
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public List<User> getAllUser() throws Exception {
List<User> list = null;
System.out.println("1111111");
try {
list = userMapper.getAllUser();
System.out.println("2222222");
return list;
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return list;
}
}
|
3eee6ac922c05c339328cf22671a44a92de4b9fd
|
[
"Markdown",
"Java"
] | 3
|
Java
|
15254714507/springboot-dubbo-provider-
|
da3e5fce138ba39f85a4458cb7f958a93c60ff10
|
a8d396abcd62f1cca08316744fd2aa6ddeb6b436
|
refs/heads/master
|
<repo_name>EAndreyF/t-shri-2015<file_sep>/parse/public/task3/js/eq.js
$(function() {
window.Equalizer = {
get: function(ctx, panel) {
var eq = new EQ(ctx, panel);
return eq.equalize();
}
};
var EQ = function(ctx, panel) {
var _this = this;
this.ctx = ctx;
this.panel = panel;
var frequencies = [];
this.frequenciesHash = {};
panel.find('.eq-block__range').each(function(i, el) {
var hz = +el.dataset.value;
frequencies.push(hz);
_this.frequenciesHash[hz] = { el: el, $el: $(el) };
});
this.frequencies = frequencies;
this.addListeners();
};
EQ.presets = {
classic: {
32: 5,
64: 4,
125: 3,
250: 2,
500: -2,
1000: -2,
2000: 0,
4000: 2,
8000: 3,
16000: 3
},
jazz: {
32: 4,
64: 3,
125: 1,
250: 2,
500: -2,
1000: -2,
2000: 0,
4000: 1,
8000: 2,
16000: 3
},
pop: {
32: -2,
64: -1,
125: 0,
250: 2,
500: 4,
1000: 4,
2000: 2,
4000: 0,
8000: -1,
16000: -2
},
rock: {
32: 5,
64: 4,
125: 3,
250: 1,
500: -1,
1000: -1,
2000: 0,
4000: 2,
8000: 3,
16000: 4
}
};
EQ.prototype.addListeners = function() {
var _this = this;
var select = $('.eq-type');
var reset = function() {
for(var key in _this.frequenciesHash) {
_this.frequenciesHash[key].filter.gain.value = 0;
_this.frequenciesHash[key].el.value = 0;
}
select.val(0);
};
var applyPreset = function(preset) {
for(var key in preset) {
_this.frequenciesHash[key].filter.gain.value = preset[key];
_this.frequenciesHash[key].el.value = preset[key];
}
};
this.panel.find('.eq-reset').click(function() {
reset();
});
for(var key in this.frequenciesHash) {
this.frequenciesHash[key].$el.on('change', function(e) {
var el = e.target;
var hz = +el.dataset.value;
var val = el.value;
_this.frequenciesHash[hz].filter.gain.value = val;
select.val(0);
});
}
select.on('change', function(e) {
var val = e.target.value;
if (val === '0') {
reset();
} else {
var preset = EQ.presets[val];
if (preset) {
applyPreset(preset);
}
}
});
};
EQ.prototype.createFilters = function () {
var _this = this;
var filters = this.frequencies.map(function(frequency, i) {
var filter = _this.ctx.createBiquadFilter();
filter.type = 'peaking'; // тип фильтра
filter.frequency.value = frequency; // частота
filter.Q.value = 1; // Q-factor
filter.gain.value = 0;
_this.frequenciesHash[frequency].filter = filter;
return filter;
});
filters.reduce(function (prev, curr) {
prev.connect(curr);
return curr;
});
return filters;
};
EQ.prototype.equalize = function () {
var filters = this.createFilters();
// источник цепляем к первому фильтру
// а последний фильтр - к выходу
return [filters[0], filters[filters.length - 1]];
};
});<file_sep>/README.md
# ШРИ 2015
Ссылка для просмотра заданий: http://shri-2015.parseapp.com/
Задание 1
---------
1. Основной упор делался на функциональность, не на дизайн
2. Шаблонизаторы, css препроцессоры, сторонние библиотеки не использовались для демонстрации чистоты решения
3. В некоторых местах структура html не оптимальна и может быть не удобна при натягивании более сложного дизайна
4. Примеры попапов сделаны только для первых двух строк
5. JS используется исключительно как фоллбек для фиксированного позиционирования хедера таблицы
Задание 2
---------
Допущенная ошибка типична для начинающего разработчика. Создается не правильное замыкание.
Переменная request изменяется внутри цикла и последнее её значение вызывается в callback,
в результате в responses находится только один элемент, а не 3 - что требуется для вывода сообщения в консоль.
В дальнейшем нужно быть всегда осторожным при вызове колбеков,
внимательно проверять какие переменные используются внутри и какие переменные могут измениться снаружи,
в случае необходимости создавать корректные замыкания.
По поводу множественных асинхронных запросов. Лучше использовать промисы. Облегчают поддержку, сокращают объем кода.
Задание 3
---------
Использовать тег audio не получается из-за проблем обработки для сафари. Поэтому используются кастомные кнопки
start и stop. Сделан только один способ визуализации. Значения эквалайзера взяты из iTunes.
|
b93228a840e740c3c32e5ef9d892316042065bed
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
EAndreyF/t-shri-2015
|
81e90dd566a03e6315cc889134c9d6b830df4847
|
3fca9bca12ecc8ebf53cfd519862ef604efb542f
|
refs/heads/master
|
<file_sep># internetmarke
[![Build Status][travis-svg]][travis-url]
[![Build Status][coveralls-svg]][coveralls-url]
[![NPM version][npm-svg]][npm-url]
![License][license-svg]
![Dependencies][dependencies-svg]
A node wrapper for the Internetmarke web service of the Deutsche Post
## Installation
```sh
npm install internetmarke
```
## Required accounts
To use the module you have to request a partner account.
You can get one from the website of the Deutsche Post or via mail.
Second, an account is required that is used to pay the vouchers.
## Basic usage
### Declare partner
Init the internetmarke object with your partner credentials.
You can request them on the page of the Deutsche Post.
```javascript
const Partner = require('internetmarke').Partner;
const partner = new Partner({
id: 'PARTNER_ID',
secret: 'SCHLUESSEL_DPWN_MARKTPLATZ'
});
```
### Create internetmarke instance
```javascript
const Internetmarke = require('internetmarke');
const internermarke = new Internetmarke(partner);
```
### Authenticate user
Once the partner credentials have been set, you can login with your account that should be used for the payment.
```javascript
const User = require('internetmarke').User;
const user = new User({
username: '<EMAIL>',
password: '*****'
});
internetmarke.authenticateUser(user)
.then(() => {
// user is authenticated
});
```
### Order vouchers
As soon as the user has been authenticated you can start ordering vouchers.
You can set the `productCode` and the `voucherLayout` (Default is Address Zone) for every single voucher.
To determine the right voucher, you can use the product list.
```javascript
internetmarke.orderVoucher({
productCode: 1,
price: 70
});
```
### Checkout
Once done, you can proceed with the checkout which will buy the vouchers and return the information including a link to the zip file.
```javascript
internetmarke.checkout()
.then(shoppingcart => {
// shoppingcart.orderId
// shoppingcart.link - contains the link to the zip archive
// shoppingcart.vouchers[].id - used to regenerate the voucher
// shoppingcart.vouchers[].trackingCode (depending on product)
});
```
### Add addresses to a voucher
Vouchers that are in `AddressZone` Layout can handle addresses.
You can add a pair of sender / receiver addresses with the AddressFactory.
```javascript
const AddressFactory = require('internetmarke').AddressFactory;
const sender = AddressFactory.create({
firstname: 'Max',
lastname: 'Mustermann',
street: 'Marienplatz',
houseNo: 1,
zip: 80331,
city: 'München'
});
const receiver = AddressFactory.create({
company: 'Studio 42',
firstname: 'John',
lastname: 'Doe',
street: 'Morningside Road',
houseNo: 44,
zip: 'EH10 4BF'
city: 'Edinburgh'
country: 'GBR'
});
const addressBinding = AddressFactory.bind({ receiver, sender});
internetmarke.orderVoucher({
addressBinding
/** further voucher info ... **/
});
```
[npm-url]: https://npmjs.org/package/internetmarke
[npm-svg]: https://img.shields.io/npm/v/internetmarke.svg
[npm-downloads-svg]: https://img.shields.io/npm/dm/internetmarke.svg
[travis-url]: https://travis-ci.org/schaechinger/internetmarke
[travis-svg]: https://img.shields.io/travis/schaechinger/internetmarke/master.svg
[license-svg]: https://img.shields.io/npm/l/internetmarke.svg
[dependencies-svg]: https://img.shields.io/david/schaechinger/internetmarke.svg
[coveralls-url]: https://coveralls.io/github/schaechinger/internetmarke
[coveralls-svg]: https://img.shields.io/coveralls/github/schaechinger/internetmarke.svg
<file_sep>/**
* internetmarke
* Copyright (c) 2018 <NAME>
* MIT Licensed
*/
'use strict';
const Product = require('./Product');
class ProductList {
/**
*
*
* @constructor
*/
constructor() {
}
/**
*
* @param {Promise.<Object>} soapClient
*/
loadProducts(soapClient) {
soapClient.then(client => {
});
}
/**
* Used to get a voucher for the given letter or package.
*
* @param {Object} data
* @param {number} data.weight - The weight of the package in gramms.
* @param {string} data.dimensions - The dimensions of the package in
* milli meters in the LxWxH format.
* @param {boolean} data.domestic - Specifies whether the package is domestic
* or international.
*/
matchProduct({ weight, dimensions, domestic }) {
}
}
module.exports = ProductList;
<file_sep>const Internetmarke = require('../'),
errors = require('../lib/errors'),
{ LAYOUT_ZONES } = require('../lib/constants');
const PARTNER_STUB = require('./stub/partner'),
USER_STUB = require('./stub/user'),
reset = require('./stub/reset');
describe('Internetmarke', () => {
const SERVICE_STUB = {
authenticateUser: sinon.stub().returns(Promise.resolve(true)),
checkout: sinon.stub().returns(Promise.resolve()),
previewVoucher: sinon.stub().returns(Promise.resolve())
};
const ORDER_STUB = {
addPosition: sinon.stub(),
getCheckout: sinon.stub().returns({ total: 145 })
};
/** @type {Internetmarke} */
let internetmarke = null;
beforeEach(() => {
internetmarke = new Internetmarke(PARTNER_STUB.partner);
internetmarke._1C4AService = SERVICE_STUB;
internetmarke._order = ORDER_STUB;
});
afterEach(() => {
reset(PARTNER_STUB.partner);
reset(USER_STUB.user);
reset(SERVICE_STUB);
reset(ORDER_STUB);
});
describe('1C4A', () => {
it('should call service for user authentication', done => {
internetmarke.authenticateUser(USER_STUB.user)
.then(() => {
SERVICE_STUB.authenticateUser.calledOnce.should.be.true();
done();
});
});
it('should call service for voucher preview', done => {
internetmarke.getVoucherPreview({})
.then(() => {
SERVICE_STUB.previewVoucher.calledOnce.should.be.true();
done();
});
});
describe('Order Management', () => {
it('should add a voucher to the order', () => {
const VOUCHER = {
productCode: 1,
price: 70,
voucherLayout: LAYOUT_ZONES.FRANKING
};
internetmarke.orderVoucher(VOUCHER);
ORDER_STUB.addPosition.calledOnce.should.be.true();
ORDER_STUB.addPosition.args[0][0].should.containEql(VOUCHER);
});
it('should not checkout if wallet is empty', () => {
internetmarke.authenticateUser(USER_STUB.user);
(() => {
internetmarke.checkout();
}).should.throw(errors.internetmarke.walletEmpty);
});
it('should call service for checkout', done => {
const getBalance = USER_STUB.user.getBalance;
USER_STUB.user.getBalance = sinon.stub().returns(1000000);
internetmarke.authenticateUser(USER_STUB.user);
internetmarke.checkout()
.then(() => {
SERVICE_STUB.checkout.calledOnce.should.be.true();
USER_STUB.user.getBalance = getBalance;
done();
});
});
});
});
it('should validate voucher layouts', () => {
internetmarke.setDefaultVoucherLayout(LAYOUT_ZONES.FRANKING)
.should.be.true();
internetmarke._config.voucherLayout.should.equal(LAYOUT_ZONES.FRANKING);
internetmarke.setDefaultVoucherLayout('INVALID_ZONE')
.should.be.false();
internetmarke._config.voucherLayout.should.equal(LAYOUT_ZONES.FRANKING);
});
});
|
04630120586ef535bbc156a9f530e45cbc6a1455
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
Vilango/internetmarke
|
37d081f92ff005caba0a102b7b6fba96ae67225e
|
27bcbac9b2eb19b87ae288d1f0abc341094f7e8d
|
refs/heads/main
|
<repo_name>ralenezi/todolist<file_sep>/src/stores/todoStore.js
import { makeAutoObservable } from 'mobx'
// import todos from "../todos";
import axios from 'axios'
import slugify from 'react-slugify'
class TodoStore {
todos = []
constructor() {
makeAutoObservable(this)
}
fetchTodos = async () => {
try {
const response = await axios.get('http://localhost:8000/todos')
this.todos = response.data
} catch (error) {
console.error('todoStore -> fetchTodos -> error', error)
}
}
createTodo = async (newTodo) => {
// newTodo.slug = slugify(newTodo.name)
// newTodo.id = this.todos[this.todos.length - 1].id + 1
// this.todos.push(newTodo)
try {
const response = await axios.post('http://localhost:8000/todos', newTodo)
this.todos.push(response.data)
} catch (error) {
console.log('TodoStore -> createTodo -> error', error)
}
}
deleteTodo = async (todoId) => {
try {
await axios.delete(`http://localhost:8000/todos/${todoId}`)
this.todos = this.todos.filter((todo) => todo.id !== todoId)
} catch (error) {}
}
updateTodo = async (updatedTodo) => {
try {
await axios.put(
`http://localhost:8000/todos/${updatedTodo.id}`,
updatedTodo
)
await this.fetchTodos()
// const todo = this.todos.find((todo) => todo.id === updatedTodo.id)
// todo.status = !todo.status
// for (const key in todo) todo[key] = updatedTodo[key]
} catch (error) {
console.log('TodoStore -> updatedTodo -> error', error)
}
}
//
// updateItem = async (updatedItem) => {
// try {
// await axios.put(
// `http://localhost:8000/items/${updatedItem.id}`,
// updatedItem
// )
// const item = this.items.find((item) => item.id === updatedItem.id)
// for (const key in item) item[key] = updatedItem[key]
// item.slug = slugify(item.name)
// } catch (error) {
// console.error(
// '🚀 ~ file: itemStore.js ~ line 55 ~ ItemStore ~ updateItem= ~ error',
// error
// )
// }
// console.log('ItemStore -> updateItem -> updatedItem', updatedItem)
// }
//
}
const todoStore = new TodoStore()
todoStore.fetchTodos()
export default todoStore
<file_sep>/src/components/buttons/CreateButton.js
import React, { useState } from 'react'
import todoStore from '../../stores/todoStore'
const CreateButton = () => {
const [todo, setTodo] = useState({ name: '', status: false, priority: '' })
const handleChange = (e) =>
setTodo({ ...todo, [e.target.name]: e.target.value })
const handleSubmit = () => todoStore.createTodo(todo)
return (
<div>
<input
name='name'
type='text'
placeholder='enter name of the todo'
onChange={handleChange}
/>{' '}
<br />
<select name='priority' onChange={handleChange}>
<option value='high'>high</option>
<option value='medium'>medium</option>
<option value='low'>low</option>
</select>
<br />
<button onClick={handleSubmit}>Create Todo</button>
</div>
)
}
export default CreateButton
<file_sep>/src/components/TodoItem.jsx
import { observer } from 'mobx-react'
import React from 'react'
import DeleteButton from './buttons/DeleteButton'
import UpdateButton from './buttons/UpdateButton'
const TodoItem = ({ todo }) => {
return (
<div>
<li>
Name: {todo.name} - Status: {todo.status ? 'done' : ' not done'} -
Priority: {todo.priority}
</li>
<DeleteButton todoId={todo.id} />
<UpdateButton todo={todo} />
</div>
)
}
export default observer(TodoItem)
<file_sep>/src/components/TodoList.jsx
import React from "react";
import todoStore from "../stores/todoStore";
import TodoItem from "./TodoItem.jsx";
import { observer } from "mobx-react";
import CreateButton from "./buttons/CreateButton";
const TodoList = () => {
const todoList = todoStore.todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} />
));
return (
<div>
{todoList}
<CreateButton />
</div>
);
};
export default observer(TodoList);
|
7ce8c16298ca8e2f6961294ce6a7403bf42c5c5d
|
[
"JavaScript"
] | 4
|
JavaScript
|
ralenezi/todolist
|
7f7291e7f95071000eaa453f58a30d9d0dd4725a
|
6e14b59bb4ea81579f2be4f66da16b4793a54bd1
|
refs/heads/master
|
<repo_name>WaelHarrath/router_Challenge<file_sep>/src/components/ContactData.js
export const Persons = [
{
name: "Wael",
email: "<EMAIL>",
src:
"https://e7.pngegg.com/pngimages/85/114/png-clipart-avatar-user-profile-male-logo-profile-icon-hand-monochrome.png",
id: Math.random(),
},
{
name: "Ahd",
email: "<EMAIL>",
src:
"https://e7.pngegg.com/pngimages/85/114/png-clipart-avatar-user-profile-male-logo-profile-icon-hand-monochrome.png",
id: Math.random(),
},
{
name: "Oussemma",
email: "<EMAIL>",
src:
"https://e7.pngegg.com/pngimages/85/114/png-clipart-avatar-user-profile-male-logo-profile-icon-hand-monochrome.png",
id: Math.random(),
},
];
|
220fc57ea64e927c22f7a7c4b0082042fead7e17
|
[
"JavaScript"
] | 1
|
JavaScript
|
WaelHarrath/router_Challenge
|
d3f8f4a1eec10a3af1e2ac6210a817221c88eec5
|
082a06321e7a25cb740f7152e826e0741ecd41d4
|
refs/heads/master
|
<file_sep># cc2
TK 👂👂👂 😘
Notes on developing: [DEVELOP.md](DEVELOP.md)
<file_sep>import db from '../db';
export default async function getSubmissions(req, res) {
const { projectName } = req.params;
try {
const submissions = await db('submissions').select({
filterByFormula: `project='${projectName}'`,
sort: [
{ field: 'timestamp', direction: 'asc' },
{ field: 'prompt', direction: 'asc' },
],
}).all();
res.json(submissions);
} catch (err) {
console.error(err);
res.sendStatus(500);
}
}
<file_sep>import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import buble from 'rollup-plugin-buble';
import uglify from 'rollup-plugin-uglify';
import pkg from './package.json';
const production = !process.env.ROLLUP_WATCH;
export default [
{ // Rollup the Svelte client
input: 'client/main.js',
output: {
sourcemap: true,
format: 'iife',
file: 'public/bundle.js',
name: 'app',
},
plugins: [
svelte({
dev: !production,
css: (css) => {
css.write('public/bundle.css');
},
store: true,
cascade: false,
}),
resolve(),
commonjs(),
production && buble({ exclude: 'node_modules/**' }),
production && uglify(),
],
},
{ // Rollup the Express server
input: './server/main.js',
output: {
sourcemap: true,
format: 'cjs',
file: 'server.js',
},
plugins: [
resolve(),
commonjs(),
],
external: id => id in pkg.dependencies || id === 'crypto' || id === 'fs' || id === 'path',
},
];
<file_sep>import fs from 'fs';
// TK make this more secure (user can traverse/delete filesystem ?!)
export default function tempServe(req, res) {
const { filepath, mimetype } = req.query;
res.sendFile(filepath, { headers: { 'Content-Type': mimetype } }, (err) => {
if (err) {
console.error(`Error sending file at ${filepath}`);
console.error(err);
console.error('😞');
return;
}
fs.unlink(filepath, (err2) => {
if (err2) {
console.error(`Error unlinking file at ${filepath}`);
console.error(err2);
console.error('😞');
}
console.log(`Sent and unlinked file from ${filepath}`);
});
});
}
<file_sep># Hello, Project
How to create your first Call-Collect Project.
## Create new project
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea nulla doloremque dolor iste mollitia sunt natus rem qui atque quia dicta accusamus doloribus, amet odio ut praesentium beatae, hic officia.
<file_sep># Developer notes
Running locally:
```sh
$ npm run dev
```
## Setting up the environment
Create a copy of the [.env.sample](.env.sample) template file and rename it `.env`
### Airtable
[Sign up for an Airtable account](https://airtable.com/signup).
In the [Account screen](https://airtable.com/account), an **API key** will be listed. Use this for the `AIRTABLE_KEY` value in `.env`
For the `AIRTABLE_BASE` value, visit this Airtable base template:
https://airtable.com/shrdpMJeeEuMJPkO1/
And make your own **copy** of it by clicking the **Copy base** button in the top right corner.
Now visit the Airbase API dashboard at: https://airtable.com/api
Look for the base that you just copied (should have a name like `cc-template`), and click on it.
Pull the Base ID from the example URL they give in the introduction to the base you chose. (It's the value between / / and looks like apphXmBxHuxynZ2Kf)
Use this value for `AIRTABLE_BASE`
More info here: [Airtable: How to connect](http://help.grow.com/connecting-your-data/airtable/airtable-how-to-connect)
### Twilio
Sign up for a [Twilio account](https://www.twilio.com/try-twilio).
The `.env` values for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` can be found in the Twilio console: https://www.twilio.com/console
<file_sep># Setting up your own instance of Call Collect
Updated 2018-02-27
## Overview
Currently there is no central/"pro" version of Call Collect that exists out on the Internet that you can pay to use. Instead, it's designed so you can run your own copy of the software for your newsroom/organization, easily and with little cost (probably around $2-10 a month). For example, if your publication is called *Hogsmeade Quarterly*, you could host it at [hqcallcollect.now.sh](https://hqcallcollect.now.sh) behind a passphrase that you share with your team.
Call Collect relies on several other Internet services—to store your data, handle phone calls, transcribe audio, and host its web server. This guide will help you set up and retrieve a key (🗝) or two from each one, which you'll input into this page. Then it will spit out your running Call Collect instance! 🔓🎁
This setup webpage **does not store any of the private information** you input! It just combines the keys you provide by running some code in your web browser, on your own computer, and then sends them to a service [Zeit Now](https://zeit.co/now) that will create and host your new web server. *Always be wary of sharing sensitive info like keys.*
The setup process should take you 5-20 minutes total, depending on whether you already have accounts for some of the services. **You don't need any special technical expertise to do this setup!** I know that working with various web services and signing up for new accounts can be intimidating/annoying, but I really hope that this guide makes it as painless as possible. If you run into issues, please feel free to leave a message [through this form](https://github.com/alecglassford/cc2/issues/new) if you have a GitHub account, or [over email](mailto:<EMAIL>).
Ready? Here we go!
## Gathering your keys
### Airtable
Airtable is a product that makes it easy to store data online. It lets you make "bases" which are sort of hybrid databases/spreadsheets, but they also make it easy to store "binary" data (in our case, audio files). This handles much of Call Collect's data storage needs.
[You can read about their pricing here](https://airtable.com/pricing), but you don't need a credit card to sign up and you'll probably be fine with their free plan. We'll only be storing the audio for your prompts (not the recordings your receive from listeners) in Airtable, so the 2GB of space shouldn't be a problem, and if you get more than 1,200 records you can upgrade to a paid plan or swap out your key for a new base. (TK information on this)
Here's what you need to do:
1. Go to [this link, which will attempt to clone a template Call Collect "base"](https://airtable.com/addBaseFromShare/shrNrZaQDNc8VxsKg). If you don't have an Airtable account, you'll be prompted to create one.
2. You may be asked to choose a workspace to add the base to, in which case you can choose any (preferably an empty one). If you just created a new Airtable account, it will probably automatically put it in a workspace called "My First Workspace." You can rename the workspace and base if you want, but you don't need to.
3. Go to [your account page](https://airtable.com/account). Toward the bottom, you'll see blue text that reads "Generate API Key." Click on this, and you should see a string of text that looks something like `keyMBHYWYitmZM92U`—this key will let Call Collect access your base. Copy and paste it into the box below:
<p class="user-input">🗝 Your Airtable API key: <input id="airtable-key" type="text"></p>
4. Now go to [this page, which leads to some documentation](https://airtable.com/api). (You don't actually have to read anything if you don't want; we just need to get an ID that identifies your base.) You should see the base we created somewhere under "Select a base to view API documentation"; it should have a little purple megaphone icon. Click on this.
5. This should take you to a page with a URL like `https://airtable.com/appKnWnJTYPq9Wrxd/api/docs#curl/introduction` (it doesn't matter if the format matches exactly). Copy the ID string in that URL (in my case it would be `appKnWnJTYPq9Wrxd`) and paste it into the box below:
<p class="user-input">🗝 Your Airtable base ID: <input id="airtable-base" type="text"></p>
6. You're done! 🎉
### Twilio
Twilio is a web service that lets you programmatically do all sorts of useful stuff with phones. Call Collect uses it to create digital phone numbers and use them to handle and record calls.
[It does cost a little bit of money.](https://www.twilio.com/voice/pricing/us) You'll pay $1/month for each phone number you create as long as it exists and about 1.1 cents/minute for handling and recording calls. Twilio also stores these recordings for us; the first 10,000 minutes of storage are free, which is more than enough for long time, and then it starts to charge a very small amount per month.
A rough cost estimate here, so you can get an idea: If you have 2 projects active in Call Collect and gather an hour of audio for each one over a month, that's going to cost about $3.50.
Here's what you need to do:
1. [Sign up for a Twilio account](https://www.twilio.com/try-twilio), if you don't have one, or else [log in](https://www.twilio.com/login). While Twilio offers a free trial, it doesn't allow for all the features we need, so you'll need to [load in some money](https://www.twilio.com/console/billing). Twilio requires you load at least $20, but as noted above, this will probably last you months. Thankfully it lets you disable "auto recharge," which means that if you use up all your money it won't automatically bill your credit card; it'll just shut down your phone numbers.
2. Go to [your Twilio console](https://www.twilio.com/console/). In the upper left box, titled "Project Info," you'll see something called "Account SID." (It should look like `ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`.) This identifies your Twilio account for Call Collect. Copy that string of text and paste it into the box below:
<p class="user-input">🗝 Your Twilio account SID: <input id="twilio-account-sid" type="text"></p>
3. In that same "Project Info" box, under the account SID, there should be something called "Auth Token." It will likely be hidden, so you'll need to click a little eye symbol (👁) to display it. (It should look like `04e7e977ead8da315a806288ca162cd5`.) This, together with the Account SID, lets Call Collect access your Twilio account. Copy it and paste it into the box below:
<p class="user-input">🗝 Your Twilio auth token: <input id="twilio-auth-token" type="text"></p>
4. You're done! 🎉
### Google Cloud Platform (optional)
Google's [speech service](https://cloud.google.com/speech/) provides pretty decent audio-to-text transcription affordably. The service currently requires that Call Collect transfers audio from Twilio into Google's own [storage service](https://cloud.google.com/storage/) so we'll need to enable that too.
While these services can incur charges, you get a lot of stuff for free every month, and if you've never used Google's "Cloud Platform" before they'll also give you $300 credit for your first year. So while you'll need to give a credit card number, you probably won't have to pay anything for at least a year. (🔥 tip: Many credit cards let you create "virtual" cards via their websites, with limited amounts of money in them. I made one with a $10 limit, so even if I accidentally use these services more than intended, Google won't be able to charge me much.) (TK more useful pricing info)
This one takes a few steps, and you can skip it if you want; your instance of Call Collect just won't do transcription.
Here's what you need to do:
1. [Go here and create a new project in Google Cloud Platform](https://console.cloud.google.com/projectcreate) You'll be prompted to create a Google account if you don't have one, or to sign in. You can name your project whatever you want (e.g. `hogsmeade-quarterly-call-collect`).
2. [Go to the Speech API page.](https://console.cloud.google.com/apis/library/speech.googleapis.com) The name of your new project should be in the blue bar at the top of the page; if it isn't, you may have to wait a minute or so for it to finish getting created (refresh …). Click the blue "Enable" button to turn on the speech service. If you haven't added a credit card to your account, you'll be directed to "enable billing." Do that, then try this step again, making sure that you see a green checkmark and "API enabled."
3. [Go to the Google Cloud Storage page](https://console.cloud.google.com/storage) and enable Storage as well.
4. Okay, here's the most convoluted part! After this, it's all downhill. Ready? [Go to the credentials page.](https://console.cloud.google.com/apis/credentials), make sure your project is active (in the blue bar at the top), and click "Create credentials" then select "Service account key." Use the "Service account" dropdown to create a new service account. Name it whatever you want (e.g. `call-collect-user`) and from the "Role" dropdown, scroll all the way to the bottom, hover over "Storage" and choose "Storage Admin." What we're doing here is selecting some permissions to give to Call Collect, so it's able to do all the things it needs with your Google account but no more.
Make sure "JSON" is elected under "Key type" and click the blue "Create" button. A file with a name like `hogsmeade-quarterly-62460ff5e214.json` should get downloaded to your computer. Now use the button below to load that file into this web page:
<p class="user-input">🗝 Your Google key file: <input id="google-creds" type="file" accept=".json"></p>
*Please know that the file is not actually getting uploaded anywhere, just loaded into your web browser so we can deploy it to your new Call Collect instance. I promise I'm not saving any of your sensitive information, and I encourage you to view the source of this page and [the code of the project more generally](https://github.com/alecglassford/cc2) to verify this!!!*
5. You're done! 🎉
### Zeit Now
Zeit Now is where your instance of Call Collect will live. It will provide the admin interface that you can use to work with projects and submissions, and it will run all the code that ties together these different pieces. This is the last key, and we're almost done!
This will be totally free. Here's what you need to do:
1. [Create a Zeit account, or login if you already have one.](https://zeit.co/login)
2. [Go to the tokens page in your account settings.](https://zeit.co/account/tokens) Type "call-collect" (or any other memorable name) into the box that says "Create a new token by entering its name…" and hit enter. It should show up in the list above. Click "reveal" next to your new token and copy the "Secret" string of text that shows up (it should look like `oDGiEsH7irIvB5871buaVMzs`) and paste it into the box below:
<p class="user-input">🗝 Your Zeit Now token: <input id="now-token" type="text"></p>
3. You're done! 🎉
### 🎊🎊🎊
You've gathered all your keys! *Phew!* Good work.
## Extra bits for configuration
A couple of last things before we get this show on the road:
* What would you like the URL for your Call Collect instance to be? (e.g. `hqcallcollect.now.sh`) We'll try to get it; if it's not available, we'll get something similar but with random letters or numbers appended to the first part.
<p class="user-input">🔖 Your preferred URL: <input id="subdomain" type="text">.now.sh</p>
* Pick a passphrase that you can share with your whole team (e.g. `<PASSWORD>`). They'll need it to access the admin interface.
<p class="user-input">🔖 Your team's passphrase: <input id="passphrase" type="text"></p>
## Deploy!
When you're ready to go, click this button and we'll try to make you wonderful little thing on the Internet: <button id="deploy">Make it.</button>
<file_sep>import db from '../db';
export default async function getProjects(req, res) {
try {
const projects = await db('projects').select().all();
res.json(projects);
} catch (err) {
res.sendStatus(500);
}
}
<file_sep># Call-Collect Documentation
- [Installation](installation.md)
- [Hello Project](hello-project.md)
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi animi amet porro autem quis minus odit similique voluptate, aliquid. Corporis mollitia repellendus cumque vitae, quas earum quis vero voluptas, id.
|
bc3cef33673f3a9509bce139f4595a96c4ce9a25
|
[
"Markdown",
"JavaScript"
] | 9
|
Markdown
|
dannguyen/cc2
|
efd919d141209f01ecd978729d00e15a2142a8e1
|
3fdc6a8933fd831063a4f9411b44b45685dfeb42
|
refs/heads/master
|
<repo_name>cheapwebmonkey/ruby-basics<file_sep>/hash_iteration.rb
#add hash
character = { "name" => "<NAME>", "location" => "The Death Star" }
#use the each aka each_pair method to iterate over a hash-takes 2 arguements-the key AND the value
character.each do |key, value|
puts "The hash key is #{key} and the value is #{value}."
end
character.each_key do |key|
puts "Key: #{key}"
end
character.each_value do |value|
puts "Value: #{value}"
end
<file_sep>/iteration_each.rb
#The each method is commonly used to iterate over items in an array
array = [0, 1, 2, 3, 4, 5]
#use each method block using do and end keywords sending items into block individually using Ruby syntax of |some item|
array.each do |item|
puts "The current array item is: #{item}"
end
#array = [0, 1, 2, 3, 4, 5]
#i =0
#while i < array.length do
# puts "The current item is #{item}."
# i += 1
#end<file_sep>/address-book/address_book.rb
require "./contact"
class AddressBook
attr_reader :contacts
def initialize
@contacts = []
end
#menu
def run
loop do
puts "Address Book"
puts "a: Add Contact"
puts "p: Print Address Book"
puts "s: Search"
puts "e: Exit"
print "Enter your choice: "
input = gets.chomp.downcase
case input
when 'a'
add_contact
when 'p'
print_contact_list
when 's'
print "Search term: "
search = gets.chomp
find_by_name(search)
find_by_phone_number(search)
find_by_address(search)
when 'e'
break
end
end
end
def add_contact
contact = Contact.new
print "First name: "
contact.first_name = gets.chomp
print "Middle name: "
contact.middle_name = gets.chomp
print "Last name: "
contact.last_name = gets.chomp
loop do
puts "Add phone number or address?"
puts "p: Add phone number"
puts "a: Add address"
puts "(Any other key to go back)"
response = gets.chomp.downcase
case response
when 'p'
phone = PhoneNumber.new
print "Phone number type: (Home, Work, Mobile)"
phone.type = gets.chomp
print "Number: "
phone.number = gets.chomp
contact.phone_numbers.push(phone)
when 'a'
address = Address.new
print "Address type: (Home, Work, etc)"
address.type = gets.chomp
print "Address line 1: "
address.street_1 = gets.chomp
print "Address line 2: "
address.street_2 = gets.chomp
print "City: "
address.city = gets.chomp
print "State: "
address.state = gets.chomp
print "Zip Code: "
address.zipcode = gets.chomp
contact.addresses.push(address)
else
print "\n"
break
end
end
contacts.push(contact)
end
def print_results(search, results)
puts search
#now iterate over the result
results.each do |contact|
puts contact.to_s('full_name')
contact.print_phone_numbers
contact.print_addresses
puts "\n"
end
end
#add search ability - add a method for this
def find_by_name(name)
#iterate over each contact in the contact list and if the name matches the arguemnt to this method we will return that contact
#start w/empty array of search results which = the contacts in our contact list
results = []
#make em all lowercase
search = name.downcase
#iterate thru contact if they match append them to the results []
#add that loop yo
contacts.each do |contact|
#then if the first name (downcase that shite) matches our search...
if contact.full_name.downcase.include?(search)
#append our results
results.push(contact)
end
end
#now print out the results NOT resluts bitches
print_results("Name search results (#{search})", results)
#now iterate over the result
# results.each do |contact|
# puts contact.to_s('full_name')
# contact.print_phone_numbers
# contact.print_addresses
# puts "\n"
# end
end
def find_by_phone_number(number)
results = []
search = number.gsub("-", "")
contacts.each do |contact|
contact.phone_numbers.each do |phone_number|
if phone_number.number.gsub("-", "").include?(search)
results.push(contact) unless results.include?(contact)
end
end
end
print_results("Phone search results (#{search})", results)
# #now iterate over the result
# results.each do |contact|
# puts contact.to_s('full_name')
# contact.print_phone_numbers
# contact.print_addresses
# puts "\n"
end
# end
def find_by_address(query)
results = []
search = query.downcase
contacts.each do |contact|
contact.addresses.each do |address|
if address.to_s('long').downcase.include?(search)
results.push(contact) unless results.include?(contact)
end
end
end
print_results("Address search results (#{search})", results)
end
def print_contact_list
puts "Contacts"
contacts.each do |contact|
puts contact.to_s('last_first')
end
end
end
address_book = AddressBook.new
address_book.run
#add new contact info
#margeaux =Contact.new
#margeaux.first_name = "Margeaux"
#margeaux.last_name = "Spring"
##margeaux.middle_name = "Jean"
#margeaux.add_phone_number("Mobile", "502-555-5544")
#margeaux.add_address("Home:", "111 Yolo Drive", "", "Louisville", "KY", "40202")
###add contact to the list
##address_book.contacts.push(margeaux)
#
##address_book.print_contact_list
#address_book.contacts.push(margeaux)
##address_book.find_by_name("e")
#address_book.find_by_phone_number("222")
#address_book.find_by_address("yolo")<file_sep>/README.txt
This is a colllection of Ruby Basics exercises <file_sep>/number.rb
def get_name()
print "Enter your name, brah: "
return gets.chomp
end
def greet(name)
puts "Hi #{name}!"
if (name == "Margeaux")
puts "That name is awesome!"
end
def get_number()
print "What number would you like to test, brah? "
return gets.chomp.to_i
end
end
def divisible_by_3?(number)
return (number % 3 == 0)
end
name = get_name()
greet(name)
number = get_number()
if divisible_by_3?(number)
puts "That number is divisible by three. brah."
end
<file_sep>/address-book/phone_number.rb
class PhoneNumber
attr_accessor :type, :number
def to_s
"#{type}: #{number}"
end
end
<file_sep>/methods.rb
#print out that we are adding 2 numbers together
def add(a, b)
puts "Adding #{a} and #{b}:"
#return the sum of the 2 numbers
return a+b
end
puts add(2, 3)
puts add(4, 5)
puts add(10, 12)<file_sep>/array_addition.rb
grocery_list = ["coconut milk", "eggs", "bread"]
grocery_list << "carrots"
grocery_list.push("potatoes")
grocery_list.unshift("peppermints")
grocery_list += ["ice cream", "birthday cake"]
grocery_list << 13
puts grocery_list.inspect<file_sep>/hello.rb
print "Enter your name, yo: "
name = gets
puts "Hello #{name}!"
<file_sep>/name.rb
#create a class
class Name
#* using the attr_reader or attribute reader
attr_accessor :title, :first_name, :middle_name, :last_name
#create initialize method which runs when we instantiate an instance of this class.
def initialize(title, first_name, middle_name, last_name)
#create an INSTANCE var which is avaialbe to every method in the class-denote an instance var with @- you set the instance vars and then call them again later-pretty common in Ruby* using the attr_reader or attribute reader
@title = title
@first_name = first_name
@middle_name = middle_name
@last_name = last_name
end
def full_name
@first_name + " " + @middle_name + " " + @last_name
end
def full_name_with_title
@title + " " + full_name()
end
end
#next you instantiate the class
name = Name.new("Ms", "Margeaux", "J", "Spring")
#print out the name by calling a method
puts name.full_name_with_title
vader = Name.new("Sir.", "Darth", "M", "Vader")
puts vader.full_name_with_title
#puts "Title: #{name.title}"
#name.title ="Empress"
#puts "Title: #{name.title}"
<file_sep>/bankacct.rb
#Created BA class
class BankAccount
attr_reader :name
#instantiated it
def initialize(name)
@name = name
@transactions = []
add_transaction("Beginning Balance", 0)
end
def credit(description, amount)
add_transaction(description, amount)
end
def debit(description, amount)
add_transaction(description, -amount)
end
#create emthod for adding a transaction
def add_transaction(description, amount)
@transactions.push(description: description, amount: amount)
end
#method that calc balance using each loop
def balance
balance = 0.0
@transactions.each do |transaction|
balance += transaction[:amount]
end
return balance
end
#try with balance inject
def balance_inject
@transactions.inject(0.0) {|sum, n| sum + n }
sum + transaction[:amount]
end
def to_s
"Name: #{name}, Balance: #{sprintf("%0.2f", balance)}"
end
def print_register
puts "#{name}'s Bank Account"
puts "Description\tAmount"
@transactions.each do |transaction|
puts transaction[:description] + "\t" + sprintf("%0.2f", transaction[:amount])
end
puts "Balance: #{sprintf("%0.2f", balance)}"
end
end
#look at how the BA works
bank_account = BankAccount.new("<NAME>")
bank_account.credit("Paycheck", 200)
bank_account.debit("New light saber", 140)
#use sprintf to print floating point number to 2 decimals or currency
#puts sprintf("%0.2f", bank_account.balance)
puts bank_account
puts "Register:"
bank_account.print_register<file_sep>/loops.rb
#Loops
loop do
#blocks can be do end(more than one line of code for block) or {}less than one line of code for block
print "Do you want to know more? (y/n)"
#get answer no whitespace, lowercase
answer = gets.chomp.downcase
if answer == "n"
break
end
end
#Loop conditionals
<file_sep>/myclass.rb
#RUBY CLASSES: You can think of a class as a blueprint. The blueprint tells Ruby how a class should be structured and what it should do.
#
#For example, a blueprint of a car would show how a car can be made. What it doesn't do is get into the specific details about an individual car, like the color.
#
#Using the variable name set to the string "Margeaux" we have a string class- the name var is the instanace and we call creating an instance of a class INSTANTIATION
#The name is the specific version of the abstract idea of a string.
#
#
#Once an instance of a class is created we call that instance an object.
#
#Classes are referred to and created in Ruby by using a capital letter, and the name of the class. For example, to refer to the string class, we use a capital S, and write out the rest of the word.
#
#Objects are instantiated by using the class name, then a dot, then the word new.
class MyClass
def initialize
puts "This is the initialize method"
end
end
MyClass.new
<file_sep>/simple_bench.rb
class SimpleBenchmarker
def run(description, &block)
start_time=Time.now
block.call
end_time=Time.now
elapsed=end_time - start_time
puts "\n"
puts "#{description} results"
puts "Elapsed time: #{elapsed}"
end
end
#How to run? First, Instatiate the the class & assign it to a var
benchmarker = SimpleBenchmarker.new
benchmarker.run "It takes <NAME> this long to choke a bitch."
do
5.times do
print "."
sleep(rand(0.1..1.0))
end
end<file_sep>/each_addition.rb
array = [0, 1, 2, 3, 4, 5]
array.each do |item|
#anything we do to the item inside the block does not change the original array, it only applies to the var innside the block
item = item + 2
puts "The current item + 2 is #{item}."
end
puts array.inspect<file_sep>/while_loop.rb
#While loops don't need the 'break' keyword
answer = ""
#set condiditon
while answer != "n"
print "Do you want to run the pointless loop again? (y/n) "
#get ans from standard input, remove trailing spaces, lwrcase
answer = gets.chomp.downcase
end<file_sep>/array_hash.rb
#Documentation Links
#
#Ruby Array Documentation
#Ruby Hash Documentation
#Code Samples
#
#Given the following array:
array = [1, 2, 3]
#Array#each
array.each { |item| print "-#{item}-" }
#Prints out:
#
-1--2--3-
#Array#select:
array.select { |item| item > 2 }
This returns a new array with the following:
[3]
#Array#delete_if
array.delete_if { |item| item == 1 }
The array is now:
[2, 3]
#Array#reject
array.reject { |item| item % 3 == 0 }
The above returns a new array: [1, 2]
#Array#count
array.count
#The above returns 3. But count can also be passed a block:
array.count { |item| item % 3 == 0 }
#The above statement returns 1.
#Hashes
#
#Given the following hash:
hash = { 'name' => 'Jason', 'location' => 'Treehouse' }
#Hash#each
hash.each do |key, value|
puts "key: #{key} value: #{value}"
end
Prints the following:
key: name value: Jason
key: location value: Treehouse
#Hash#each_key:
hash.each_key{ |key| puts "key: #{key}" }
Prints the following:
key: name
key: location
#Hash#each_value:
hash.each_value { |val| puts "val: #{val}" }
Prints the following:
val: Jason
val: Treehouse
#Hash#keep_if
hash.keep_if{ |key, val| key == "name" }
#The hash is now:
{ 'name' => 'Jason' }
#Hash#reject
hash.reject { |key, val| key == "name" }
#The hash is now:
{}
#Hash#select
hash.select { |key, val| key == "name" }
#Returns a new hash:
{ 'name' => 'Jason' }<file_sep>/until_number.rb
answer = 0
until answer >= 13 do
print "How many times do you want to print 'Hello'? Enter a number greater than 13 to exit"
#get the answer and convert it to an integer
answer = gets.chomp.to_i
#and then call that method with the answer
print_hello(answer)
end<file_sep>/conditional_ass.rb
#name = "<NAME>"
#new keyword is DEFINED which cks to see if a var exists
#if defined?(name)
# name
#else
# name = "Luke"
#end
# puts name
#exit
#new_name = "Chewie"
#new_name ||= "<NAME>"
#puts new_name
#exit
other_name = (other_name || "Yoda")
puts other_name<file_sep>/speed_sign_methods.rb
def flash_ship_speed(speed)
10.times do
print "\r#{speed}"
sleep 0.45
print "\r "
sleep 0.45
end
puts "\n"
end
def display_ship_speed(speed)
puts speed
end<file_sep>/hash_methods.rb
#Code Samples ie http://ruby-doc.org/core-2.1.2/Hash.html
#For the examples below, we'll be working with the following hash:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Wonder" }
#Print out the hash
puts "Hash: #{hash.inspect}"
#Find the number of things in the hash
print "hash.length:"
#print out the number of things in the hash
puts hash.length
#The #length method will return the number of keys in the hash. In this case, it would be 3:
hash.length
#The #invert method returns a new hash with the keys and values transposed-DOES NOT CHANGE ORIG HASH:
puts "hash.invert"
#run it
puts hash.invert
#That would produce the following new hash:
{"Bread" => "item", 1 => "quantity", "Wonder" => "brand"}
#The #shift method works similar to hashes as it does with arrays. It will remove a key and value pair from the hash and return it as an array:
print "hash.shift: "
puts hash.shift.inspect
print "hash: "
puts hash.inspect
#This would return the following (note that it is an array):
["item", "Bread"]
#The original hash would also be modified:
{"quantity" => 1, "brand" => "Wonder"}
#put the Bread back, yo
hash["item"] = "Bread"
puts "Hash merging: "
print "Original hash: "
puts hash.inspect
puts "Merged with {'calories' => 100 }"
puts hash.merge({'calories' => 100})
print "Original hash: "
puts hash.inspect
puts "Merged with {'item' => 'eggs'}"
puts hash.merge({'item' => 'eggs'})
#The #merge method combines the hash sent in as an argument and returns a new hash with the two combined:
hash.merge({"calories" => 100})
#Would return the following:
{"quantity" => 1, "brand" => "Wonder", "calories" => 100}
#If any key value pairs exist in the original hash, the merge method will overwrite those:
hash.merge({"quantity" => 100})
#Would return:
{"quantity" => 100, "brand" => "Wonder"}<file_sep>/address-book/address.rb
class Address
attr_accessor :type, :street_1, :street_2, :city, :state, :zipcode
#set a defualt address format
def to_s(format = 'short')
#create string to hold address which we will implicitly return
address = ''
#if you leave off the CASE FORMAT your will get a syntax error, unexpected keyword_when, expecting keyword_end when 'short'
case format
#ask why we had to put the long case above the short?
when 'long'
address += street_1 + "\n"
address += street_2 + "\n" if !street_2.nil?
address += "#{city}, #{state} #{zipcode}"
when 'short'
address += "#{type}: "
address += street_1
if street_2
address += " " + street_2
end
address += ", #{city}, #{state}, #{zipcode}"
end
address
end
end
home = Address.new
home.type = "Home"
home.street_1 = "111 Yolo Drive"
home.city = "Louisville"
home.state = "KY"
home.zipcode = "40202"
puts home.to_s('short')
puts "\n"
puts home.to_s('long')<file_sep>/block_examples.rb
#blocks have {} or DO END, {} take precidence, DO END if more than one line, cannot use RETURN inside a block- it will error out
3.times do
puts "Hey Vader!"
puts " Solo, YOLO!"
end<file_sep>/fav_num.rb
print "What is your fav number, brah? "
number = gets.chomp.to_i
if (number == 13) || (number == 23)
puts "That's my fav too, brah!"
elsif (number >10) && (number.even?)
puts "That is a high, even number, brah."
elsif (number.odd?) && (number % 3 == 0)
puts "That number is divisible by 3 brah, and odd."
end<file_sep>/while_numner_loop.rb
def print_hello(number_of_times)
#when writing loops it is convention to use the letter i, j, k to iterate over the loop
#i is the ITERATOR and is currently =0
i = 0
while i < number_of_times
#function will print "Hello"
puts "Hello"
#You have to increent the ITERATOR
i += 1
end
end
#Now lets call the method from above
#Create answer
answer = 0
until answer >= 13 do
print "How many times do you want to print 'Hello'? Enter a number greater than 13 to exit"
#get the answer and convert it to an integer
answer = gets.chomp.to_i
#and then call that method with the answer
print_hello(answer)
end
#The print_hello method takes in number_of_times as a parameter. When you call print_hello with answer you're passing that in as number_of_times just as print_hello(3) would set number_of_times to 3.<file_sep>/contact_list.rb
#create method called ask-We're going to be asking the user for input quite a bit so the ask method will repeat the logic for us. The ask method takes two arguments and defaults to having the kind of answer be a string. This will let us return numeric values if we want.
def ask(question, kind="string")
print question + " "
answer = gets.chomp
answer = answer.to_i if kind == "number"
return answer
end
#Finally, we test the ask method:
#answer = ask("What is your name?")
#puts answer
#Create a method that creats a contact which is a hash and then returns that hash
def add_contact
contact = {"name" => "", "phone_numbers" => []}
#Get the contact name
contact ["name"] = ask("What is the person's name?")
answer = ""
while answer != "n"
answer = ask("Do you want to add a phone number? (y/n)")
if answer == "y"
#ask for the phone number
phone = ask("Enter a phone number:")
#push that answer into the contact phone numbers array
contact["phone_numbers"].push(phone)
end
end
return contact
end
#Set list up as an empty array
contact_list = []
#Now loop thru and ask people to enter contacts
answer = ""
while answer != "n"
#add to our contact list the RESULT of the add contact method
contact_list.push(add_contact())
ask("Do you want to add a new contact? (y/n)")
answer = ask("Do you want to add another? (y/n)")
end
#print out the contact list using iteration
puts "---"
#use each method to iterate over the contact list array
contact_list.each do |contact|
#The contact_list variable is an array. We iterate over each contact using the each method. The array items are passed in to each iteration of the block as a contact variable.
#Each item in the array is a hash. First, we print out the contact's name by accessing the value at the name key.
puts "Name: #{contact["name"]}"
#phone umbers will be array so use each method
if contact["phone_numbers"].size > 0
#It is possible to enter a contact without a phone number. The phone_numbers key is a string which is an array. We check whether or not a contact has any phone numbers by checking whether or not the length of the phone_numbers array is greater than 0.
#Next, we iterate over each phone number and print it out. This only occurs if there are items in the array.
contact["phone_numbers"].each do |phone_number|
puts "Phone: #{phone_number}"
end
#then we close out or loops
end
puts "-----\n"
end
<file_sep>/array_creation.rb
grocery_list = Array.new
grocery_list = []
grocery_list = ["coconut milk", "eggs", "bread"]
grocery_list = %w(coconut milk, eggs, bread)
item = "coconut milk"
grocery_list = %W(#{item} eggs bread)
<file_sep>/car.rb
car1_speed = 50
car2_speed = 60
if !(car1_speed == car2_speed)
puts "Car 1 and Car 2 are not going the same speed."
end
if (car1_speed > 40) && !(car1_speed > car2_speed)
puts "Car 1 is going pretty fast, but not as fast as Car 2, brah."
end<file_sep>/block_method.rb
def block_method
puts "Hey Yoda!"
#yeild calls the method out of the second block
yield
puts "Has anyone seen Luke? He is always doing fuck-all."
end
block_method do
puts "Chewie ate my sandwich!"
end<file_sep>/shopping_list.rb
#Shopping List program in Ruby
#Add method to create the list
def create_list
print "List name, call you? "
#remove whitespace
name = gets.chomp
#create hash that returns the list and items
hash = {"name" => name, "items" => Array.new}
return hash
end
#Create method to add an item to the list
def add_list_item
print "Called what, this item is? "
#Remove whitespace
item_name = gets.chomp
#get quanitiy
print "Quantity needs, have you? "
#call .to_i on the quantity to return a number
quantity = gets.chomp.to_i
#create hash that returns item name
#add quantity into the hash
hash = {"name" => item_name, "quantity" => quantity}
return hash
end
#make a method out of printing out a seperator to keep code DRY
def print_separator(character="-")
#have this method print that character 80 times
puts character * 80
end
def print_list(list)
#print out list name using sting interpolation
puts "List: #{list['name']}"
#print out seperator
print_separator()
#call the method each using new Ruby synatax called a block and passing in an arguement-blocks are written in curly braces or in the words do & end
list["items"].each do |item|
#print out item name using concat and a tab character and put quantity on the same line
puts "\tItem: " + item['name'] + "\t\t\t" +
#print out quantity using concat
"Quantity: " + item['quantity'].to_s
end
#print out seperator
print_separator()
end
#Ask user for their list by calling the method, create_list
list = create_list()
#add item to the list in list view by using the push method-use push BECAUSE items is an ARRAY
puts "Super awesome, you are. Some items to your list, you add."
#this takes each item in the items array and assigns it a variable
list['items'].push(add_list_item())
#add another list item
list['items'].push(add_list_item())
#add another list item
list['items'].push(add_list_item())
puts "Here's your list, Yoda:\n "
print_list(list)
<file_sep>/hash_keys.rb
#Code Samples
#Here is the hash we'll be working with:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
#Keys
#To find out all of the different keys inside of the hash, we can use the keys method:
hash.keys
#This would return an array of the keys in the hash:
["item", "quantity", "brand"]
#To check whether or not a hash contains a key, we can use the has_key? method, which returns true or false. It is aliased as member? and key?:
hash.has_key?("brand") # => true
hash.member?("quantity") # => true
hash.key?("item") # => true
#The store method will add a key and value pair to a hash:
hash.store("calories", 100)
#The hash would then contain the following:
{ "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company", "calories" => 100 }
#Equality
#
#Two hashes are considered equal when they have the same keys and values:
milk = { "item" => "Milk", "quantity" => 1, "brand" => "Treehouse Dairy" }
puts milk == hash # => true
bread = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
puts hash == bread # => false
#Code Samples
#
#For the examples below, we'll be working with this hash:
hash = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
#To return an array of the values in the hash, we can use the values method:
hash.values
#Which would return the following:
["Bread", 1, "Treehouse Bread Company"]
#The has_value? method takes one argument and returns true or false if the value is contained within the hash:
hash.has_value?("brand")
#That would return false since "brand" isn't a value. However, the following would return true:
hash.has_value?("Bread")
#The values_at method takes several arguments and returns the hash values at the specified keys as an array:
hash.values_at("quantity", "brand")
#That would return:
[1, "Treehouse Bread Company"]<file_sep>/todo_list.rb
require "./todo_item"
class TodoList
attr_reader :name, :todo_items
def initialize(name)
@name = name
@todo_items = []
end
def add_item(name)
todo_items.push(TodoItem.new(name))
end
def find_index(name)
index = 0
found = false
todo_items.each do |todo_item|
if todo_item.name == name
found = true
end
if found
break
else
index += 1
end
end
if found
return index
else
return false
end
end
def remove_item(name)
if index = find_index(name)
puts index
todo_items.delete_at(index)
return true
else
return false
end
end
def mark_complete(name)
if index = find_index(name)
todo_items[index].mark_complete!
return true
else
return false
end
end
def print_list(kind='all')
puts "#{name} List - #{kind} items"
puts "-" * 30
todo_items.each do |todo_item|
case kind
when 'all'
puts todo_item
when 'complete'
puts todo_item if todo_item.complete?
when 'incomplete'
puts todo_item unless todo_item.complete?
end
end
end
end
todo_list = TodoList.new("Darth Vader's Shopping")
todo_list.add_item("Light Saber")
todo_list.add_item("New Force Gloves")
todo_list.add_item("Cape")
todo_list.add_item("Boots")
todo_list.add_item("Cookies")
if todo_list.remove_item("More Cookies")
puts "Removed More Cookes"
end
if todo_list.mark_complete("Boots")
puts "You got your boots now, brah."
end
todo_list.mark_complete("Boots")
todo_list.print_list
todo_list.print_list('complete')
todo_list.print_list('incomplete')
<file_sep>/for_loop.rb
#a Ruby for loop is more like an iterator
#Most Ruby programmers don't use the for loop very often, instead preferring to use an "each" loop and do iteration. The reason for this is that the variables used to iterate in the for loop exist outside the for loop, while in other iterators, they exist only inside the block of code that’s running.
#in 1..10 in a RANGE
for item in 1..10 do
puts "The current item is #{item}"
end
#for loops can be used for arrays as well
for item in ["Darth", "Vader", "is", "awesome!"]
puts "The current item is #{item}"
end<file_sep>/address-book/contact.rb
require "./phone_number"
require "./address"
#Define the contact class for the Address Book
class Contact
attr_writer :first_name, :middle_name, :last_name
attr_reader :phone_numbers, :addresses
#initalize phone number in the contact class and make it an empty array, also the addresses
def initialize
@phone_numbers = []
@addresses = []
end
#create a method with 2 arguements to add a phone number to the contact info
def add_phone_number(type, number)
phone_number = PhoneNumber.new
phone_number.type = type
phone_number.number = number
#once we have that we need to append it to the internal @phone_numbers array with:
phone_numbers.push(phone_number)
end
#add addresses method- very similar to phone_numbers method
def add_address(type, street_1, street_2, city, state, zipcode)
#Initialize a new instance of the Address class (why)
address = Address.new
#then set all of the ATTRIBUTES to the ARGUEMENTS of this METHOD
address.type = type
address.street_1 = street_1
address.street_2 = street_2
address.city = city
address.state = state
address.zipcode =zipcode
#then append this to the internal array of addresses-since addresses is a attr_reader we do not have to use the @ sign
addresses.push(address)
end
def first_name
@first_name
end
def middle_name
@middle_name
end
def last_name
@last_name
end
#display first and last name
def first_last
first_name + " " + last_name
end
#Display last name first
def last_first
last_first = last_name
last_first += ", "
last_first += first_name
if !@middle_name.nil?
last_first += " "
#take just first letter of middle name
last_first += middle_name.slice(0,1)
last_first += ". "
end
last_first
end
#Display full name
def full_name
# OR full_name = first_name + " " + last_name
full_name = first_name
if !@middle_name.nil?
full_name += " "
full_name += middle_name
end
full_name += ' '
full_name += last_name
full_name
end
#override the TO STRING method so we can call that
def to_s(format = 'full_name')
#use CASE statement to find the format
case format
when 'full_name'
full_name
when 'last_first'
last_first
when 'first'
first_name
when 'last'
last_name
else
first_last
end
end
#create method to print out phone numbers
def print_phone_numbers
# puts "Phone Numbers: "- i thought this was ugly so I commented it out
#use each because of array and each takes a block with one arguement
phone_numbers.each { |phone_numbers| puts phone_numbers}
end
def print_addresses
addresses.each { |address| puts addresses.to_s('short')}
end
end
#margeaux =Contact.new
#margeaux.first_name = "Margeaux"
#margeaux.last_name = "Spring"
#margeaux.middle_name = "Jean"
#puts margeaux.full_name
#margeaux.add_phone_number("Mobile", "502-555-5544")
##puts margeaux.phone_numbers
#margeaux.print_phone_numbers
#margeaux.print_addresses
##you have to have the same number of arguements here as for above, hence the empty "" for street_2
#margeaux.add_phone_number("Mobile", "502-555-5544")
#margeaux.add_address("Home:", "111 Yolo Drive", "", "Louisville", "KY", "40202")
#puts margeaux.last_first
#puts margeaux.to_s
#puts margeaux.first_last
#puts margeaux.to_s('first')
#puts margeaux.to_s('last')
<file_sep>/starwars_contacts.rb
contact_list = []
<file_sep>/times_iterator.rb
5.times do
puts "Hey Vader!"
end
#times with arguement
5.times do |item|
puts "Hello! #{item}"
end<file_sep>/ship_speed.rb
require "./speed_sign_methods"
warp_speed = 998
ship_speed = 999
if (ship_speed > warp_speed)
flash_ship_speed(ship_speed)
else
display_ship_speed(ship_speed)
end<file_sep>/hello2.rb
name = "Margeaux"
string = <<-STRING
Hey
My name is #{name}
Whaddup playa?
STRING
puts string<file_sep>/hello3.rb
name = "Margeaux"
string = "Hey.\n\tMy name is #{name}.\n\tWhaddup playa?"
puts string
year =2015
future=5
puts "The year is #{year}"
puts "In #{future} years the year will be #{year+future}"<file_sep>/control_structures2.rb
print "Enter name: "
name = gets.chomp
if name == "Margeaux"
puts "That's my name, as well."
else
puts "Nice to meet you, #{name}."
end
print "Modify your name. Type 'uppercase' or 'reverse:' "
answer = gets.chomp.downcase
case answer
when "reverse"
puts "This is your name backwards:"
puts name.reverse
when "uppercase"
puts "Uppercase it is"
puts name.upcase
when "both"
puts name.reverse.upcase
else
puts "Ok, so rude."
end<file_sep>/money_examples.rb
#Gem Money
require "money"
#initlize a new money instance
money = Money.new(1000, "USD")
puts money.inspect
more_money =Money.new(1000, "USD")
#add them together
all_the_money = money + more_money
puts all_the_money.inspect
|
4a287808a9f21b52f7d174ab8043d86877fe20ba
|
[
"Text",
"Ruby"
] | 41
|
Ruby
|
cheapwebmonkey/ruby-basics
|
0454a99079419f75894563722204dbb23ab5587b
|
ec235f11e8e8043ac5eed54e39e5ef50b0d31ce7
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import '../styles/App.css';
class Header extends Component {
render() {
return (
<nav>I am the Navigation Bar</nav>
);
}
}
class Footer extends Component {
render() {
return (
<footer>I am the Footer</footer>
);
}
}
class BaseLayout extends Component {
render() {
return (
<div>This should house Header and Footer components and be able to house any children components.</div>
);
}
}
class ParentComponent extends Component {
constructor(props){
super(props);
//we are really in a *bind* here.... :)
//fix it...
//state lives here
this.state = {
whatToSay: "",
whatWasSaid: "",
}
}
handleInput(e) {
e.preventDefault();
//set the state on input change
this.setState({whatToSay: this.state.whatToSay});
}
handleSubmit(e) {
e.preventDefault();
//check console to see if firing
console.log("fired");
//set the state for props and for value (prevents output from appearing when typing)
this.setState({whatToSay: this.state.whatToSay, whatWasSaid: this.state.whatToSay});
//clear our input by resetting state
this.setState({whatToSay: ""});
}
render() {
return (
<div>Smart Component: I have a function, but something isn't working? I also need to pass that function to the ChildComponent.
<div>
<input onChange={this.handleInput} type="text" placeholder="Say It, Don't Spray It!" />
</div>
<div>
<ChildComponent onClick={"FILL_ME_IN"}/>
<DisplayComponent sayWhat={"FILL_ME_IN"} />
</div>
</div>
);
}
}
class ChildComponent extends Component {
render() {
return (
<div>Dumb Component receiving Props
<div>
<input type="submit" onClick={this.props.onClick}/>
</div>
</div>
);
}
}
class DisplayComponent extends Component {
render() {
return (
<div>{this.props.sayWhat}</div>
);
}
}
class App extends Component {
render() {
return (
<div className="App">
<BaseLayout></BaseLayout>
<Header />
<ParentComponent />
<Footer />
</div>
);
}
}
export default App;
// import React, { Component } from 'react';
// import '../styles/App.css';
// import BaseLayout from './base-layout.js';
// import ParentComponent from './form.js';
//
//
// class App extends Component {
// render() {
// return (
// <div className="App">
// <BaseLayout></BaseLayout>
// <ParentComponent />
// </div>
// );
// }
// }
//
//
// export default App;
<file_sep>In order to get familiar with props, state, passing props to children, and rendering children components, let's fix our application.
-Use create-react-app to generate a new React application.
-Within src, make two new directories: components and styles.
-Move App.js into src/components.
-Move App.css into src/styles.
-Download the provided App.js file.
-Copy the starter file App.js into src/components/App.js
-Import the App component into index.js
-Use npm run start to get your project going and check for errors.
You will need to execute a few major changes to the App.js file to get everything working properly.
-The BaseLayout component should house the Header and Footer components as well as make room for any child components that would be rendered in between.
-The ParentComponent has a lot of the functionality worked out for you, but you will need to make it run properly. Namely in the constructor method and the render method where we pass props down.
After everything is working properly, you will need to move each of the components (except for the App component) into their own separate file within src/components and import and export them properly to make the application still run.
Copy each of the components other than App into their own file within src/components
Export each component from their individual files.
Import all of the other components into the files where they are referenced.
The App component should only render a BaseLayout and ParentComponent.
|
fd5e382925fa7b09bb4c5137f3d6884b6cab0915
|
[
"JavaScript",
"Text"
] | 2
|
JavaScript
|
Foxygen-Prime/state_props_children_functs_react
|
1ae077b2d9b1ce7295f7248cbb155e5bd6718756
|
c9b5807f0d3cf022d26b8c25fc7024623772353b
|
refs/heads/master
|
<repo_name>slin362662/LC_sol<file_sep>/3. Longest Substring Without Repeating Characters/longest_unique_substrings.py
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
uni_char = {}
ans = float('-inf')
i, j = 0, 0
while j < len(s):
if s[j] not in uni_char:
uni_char[s[j]] = 0
j += 1
ans = max(ans, len(uni_char))
else:
del uni_char[s[i]]
i += 1
ans = 0 if ans == float('-inf') else ans
return ans
|
1f38ff24d4ae5fd4b381b86bf1d1c795332f2187
|
[
"Python"
] | 1
|
Python
|
slin362662/LC_sol
|
2a681d1e30630da60fc5467c12a2ea1025fb1430
|
906310339578c37ef4d78720b2069a7ffe02948e
|
refs/heads/main
|
<repo_name>Nasimuddin367/Planner-The-Todo--App<file_sep>/App.js
import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { FlatList, StyleSheet, TouchableWithoutFeedback, Keyboard, View, Alert } from 'react-native';
import Header from './components/header';
import TodoItem from './components/todoItem';
import AddTodo from './components/addTodo';
import Sandbox from './components/Sandbox';
export default function App() {
const [todo, setTodo] = useState([{ name: 'Learn React', key: 1 },
{ name: 'Build App', key: 2 },
{ name: 'Publish App', key: 3 }]);
const pressHandler = (key) => {
setTodo((prevTodos) => {
return prevTodos.filter(todos => todos.key.toString() != key);
});
};
const submitHandler = (textt) => {
if (textt.length > 3) {
setTodo((prevTodo) => {
return [
{ name: textt, key: Math.random().toString() },
...prevTodo
];
});
} else {
Alert.alert('Check', 'TODO must be atleast 4 chars long', [
{ text: 'okay', onPress: () => console.log('okay')}
]);
}
}
return (
// <Sandbox />
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={styles.container}>
<Header />
<View style={styles.content}>
<AddTodo submitHandler={submitHandler} />
<View style={styles.list}>
<FlatList
data={todo}
renderItem={({ item }) => (
<TodoItem
item={item}
pressHandler={pressHandler} />
)} />
</View>
</View>
<StatusBar style="auto" />
</View>
</TouchableWithoutFeedback>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
content: {
padding: 40,
flex: 1,
},
list: {
marginTop: 20,
flex: 1,
}
});
<file_sep>/README.md
# Planner-The-Todo--App
Planner is a Simple Todo app made in React Native.
This app shows the basic structure of a react native app with some styling.
The app is made to add a Todo and click a Todo in order to delete it once the Task is Completed.
|
bd4037510bdc491dcc7286a5f128fbe5d65c18c0
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
Nasimuddin367/Planner-The-Todo--App
|
a46aafb16f557419f127ad913b194ad14b23d965
|
d229becbaea1b297d9db2a3fdf5caa6b408039ec
|
refs/heads/master
|
<repo_name>rafsan2/angular<file_sep>/angularCrud/js/app.js
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope) {
console.log("In myController...");
$scope.newUser = {};
$scope.clickedUser = {};
$scope.message = "";
$scope.users = [
{username: 'Rafsan', fullName: '<NAME>', email: '<EMAIL>'},
{username: 'kawser', fullName: '<NAME>', email: '<EMAIL>'},
{username: 'pial004', fullName: '<NAME>', email: '<EMAIL>'}
];
$scope.saveUser = function() {
//console.log($scope.newUser);
$scope.users.push($scope.newUser);
$scope.newUser = {};
$scope.message = "You have successfully added an user."
};
$scope.selectUser = function(user) {
console.log(user);
$scope.clickedUser = user;
};
$scope.updateUser = function() {
$scope.message = "You have edited an user information."
};
$scope.deleteUser =function() {
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
$scope.message = "You have deleted an user."
};
$scope.clearMessage = function() {
$scope.message = "";
};
});
|
688c71f097cd1c1a34035042ef3386738fd8df5d
|
[
"JavaScript"
] | 1
|
JavaScript
|
rafsan2/angular
|
80d2b917e346d7f33d437d327e4a9c7aea6e90c3
|
9a76e7b1a223681cacfe49017ef0cdccc77976d3
|
refs/heads/master
|
<repo_name>sambeevors/canvasplus<file_sep>/src/classes/Image.js
// We use CanvasImage because Image is a global object
export default class CanvasImage {
// Build an animation based of the passed parameters
constructor(params) {
// GCO defaults to source-over (normal)
this.GCO = typeof params.GCO === 'string' ? params.GCO : 'source-over'
// Creates a new image
this.image = new window.Image()
// Width and height default to whatever the dimensions of the passed image are
this.w = typeof params.w === 'number' ? params.w : this.image.width
this.h = typeof params.h === 'number' ? params.h : this.image.height
// Check if image has loaded
this.loaded = false
this.image.onLoad = () => {
this.loaded = true
}
// If no image src is set, put a placeholder in it's place
this.image.src =
typeof params.src === 'string'
? params.src
: 'http://placehold.it/500x500?text=Image+Must+Be+A+String'
this.canvases = params.canvases
this.canvas = typeof params.canvas === 'number' ? params.canvas : 0
this.animations = params.animations
this.animation = typeof params.animation === 'number' ? params.animation : 0
// Start position must be specified, end position defaults to start
if (
(typeof params.position.start === 'object' &&
typeof params.position.end === 'object') ||
typeof params.position.end === 'undefined'
) {
this.pos = {
start: params.position.start,
end:
typeof params.position.end === 'object'
? params.position.end
: params.position.start
}
this.fill = typeof params.fill === 'string' ? params.fill : '#000000'
} else {
throw new Error(
'New shapes require a starting position (array: [startX, startY])'
)
}
// Rotation defaults to none
this.rot = {
start: 0,
end: 0
}
// End rotation defaults to start
if (typeof params.rotation === 'object') {
if (
(typeof params.rotation.start === 'number' &&
typeof params.rotation.end === 'number') ||
typeof params.rotation.end === 'undefined'
) {
this.rot = {
start: params.rotation.start,
end:
typeof params.rotation.end === 'number'
? params.rotation.end
: params.rotation.start
}
}
}
// Scale defaults to none
this.scale = {
start: 1,
end: 1
}
// End scale defaults to start
if (typeof params.scale === 'object') {
if (
(typeof params.scale.start === 'number' &&
typeof params.scale.end === 'number') ||
typeof params.scale.end === 'undefined'
) {
this.scale = {
start: params.scale.start,
end:
typeof params.scale.end === 'number'
? params.scale.end
: params.scale.start
}
}
}
// Opacity defaults to 1
this.opacity = {
start: 1,
end: 1
}
// End opacity defaults to start
if (typeof params.opacity === 'object') {
if (
(typeof params.opacity.start === 'number' &&
typeof params.opacity.end === 'number') ||
typeof params.opacity.end === 'undefined'
) {
this.opacity = {
start: params.opacity.start,
end:
typeof params.opacity.end === 'number'
? params.opacity.end
: params.opacity.start
}
}
}
}
// Work out current position based on progress
currentPosition(p) {
const x =
this.pos.start[0] +
(this.pos.end[0] - this.pos.start[0]) *
this.animations[this.animation].easing(p)
const y =
this.pos.start[1] +
(this.pos.end[1] - this.pos.start[1]) *
this.animations[this.animation].easing(p)
return [x, y]
}
// Work out current rotation based on progress
currentRotation(p) {
return (
this.rot.start +
(this.rot.end - this.rot.start) *
this.animations[this.animation].easing(p)
)
}
// Work out current scale based on progress
currentScale(p) {
let w = this.w * this.scale.start
let h = this.h * this.scale.start
if (this.scale.start !== this.scale.end) {
w =
this.w +
this.w *
((this.scale.start + (this.scale.end - this.scale.start)) *
this.animations[this.animation].easing(p) -
this.animations[this.animation].easing(p))
h =
this.h +
this.h *
((this.scale.start + (this.scale.end - this.scale.start)) *
this.animations[this.animation].easing(p) -
this.animations[this.animation].easing(p))
}
return [w, h]
}
// Work out current opacity based on progress
currentOpacity(p) {
return (
this.opacity.start +
(this.opacity.end - this.opacity.start) *
this.animations[this.animation].easing(p)
)
}
}
<file_sep>/src/index.js
'use strict'
import { Canvas, Animation } from './classes/Animation.js'
import { Circle, Rectangle } from './classes/Shape.js'
import CanvasImage from './classes/Image.js'
import Color from 'color'
/*
The Ease object contains several functions which take the progress,
and modify it to create an ease in the animation. These can be applied
on a per-canvas basis.
*/
const Ease = {
inQuad: t => t * t,
outQuad: t => t * (2 - t),
inOutQuad: t => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
inCubic: t => t * t * t,
outCubic: t => --t * t * t + 1,
inOutCubic: t =>
t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
inQuart: t => t * t * t * t,
outQuart: t => 1 - --t * t * t * t,
inOutQuart: t => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t),
inQuint: t => t * t * t * t * t,
outQuint: t => 1 + --t * t * t * t * t,
inOutQuint: t =>
t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t
}
const CanvasPlus = (() => {
let canvases = []
let nextFrame
// Position items on the frame
const _positionItems = (items, progress, animation, canvas) => {
// Loop through all the items (items are either shapes or images)
for (let i = 0; i < items.length; i++) {
// Set the GCO
canvas.ctx.globalCompositeOperation = items[i].GCO
canvas.ctx.beginPath()
// Work out the position, rotation, opacity and scale of the item
let pos = items[i].currentPosition(progress)
let r = items[i].currentRotation(progress)
let s = items[i].currentScale(progress)
let o = items[i].currentOpacity(progress)
// Save the current state of the canvas
canvas.ctx.save()
/*
If the item is a rectangle or image, make sure the canvas
works from the center of the shape (like how it does with circles)
*/
if (items[i] instanceof Rectangle || items[i] instanceof CanvasImage) {
canvas.ctx.translate(
items[i].pos.x + items[i].w / 2,
items[i].pos.y + items[i].h / 2
)
}
// Rotate the canvas based on the current shape rotation
canvas.ctx.rotate((r * Math.PI) / 180)
// Draw the item
if (items[i] instanceof CanvasImage) {
canvas.ctx.globalAlpha = o
canvas.ctx.drawImage(items[i].image, pos[0], pos[1], s[0], s[1])
canvas.ctx.globalAlpha = 1
} else {
animation.shapes[i].draw(pos, s)
canvas.ctx.fillStyle = Color(items[i].fill)
.alpha(o)
.rgb()
canvas.ctx.fill()
}
// Restore the canvas to it's original rotation (0)
canvas.ctx.restore()
}
}
// Looping function for drawing each frame
const _draw = () => {
// Draw each canvas
for (let i = 0; i < canvases.length; i++) {
let canvas = canvases[i]
// Clear the frame completely
canvas.ctx.clearRect(
0,
0,
canvas.ctx.canvas.width,
canvas.ctx.canvas.height
)
for (let i = 0; i < canvas.animations.length; i++) {
let animation = canvas.animations[i]
if (animation.play) {
// Work out the current time
const now = window.performance.now()
// If this is the first frame, set the current time to the start time
if (!animation.startTime) {
animation.startTime = now
}
// Work out the progress of the animation (0 - 1)
let p = (now - animation.startTime) / animation.duration
// If the progress has passed one, adjust to be 1
if (p > 1) p = 1
// Set the value of the canvas' progress
animation.progress = p
// Draw the images and shapes
_positionItems(animation.images, p, animation, canvas)
_positionItems(animation.shapes, p, animation, canvas)
// If the animation has ended
if (p >= 1) {
// Reset the start time
animation.startTime = null
// Reset the progress
p = 0
// Reset the GCO
canvas.ctx.globalCompositeOperation = 'source-over'
// Continue playing if animation should loop
animation.play = animation.loop
}
}
}
}
nextFrame = window.requestAnimationFrame(_draw)
}
return {
// Creates a new canvas
addCanvas: obj => {
canvases.push(new Canvas(obj))
},
addAnimation: obj => {
// Make sure we know which canvas we're adding the animatio to
if (typeof obj.canvas === 'number' || canvases.length <= 1) {
let canvas = typeof obj.canvas === 'number' ? obj.canvas : 0
obj.canvases = canvases
canvases[canvas].animations.push(new Animation(obj))
} else {
throw new Error('Canvas ID is not defined.')
}
},
// Add a new shape
addShape: obj => {
// Make sure we know which canvas we're adding the shape to
if (typeof obj.canvas === 'number' || canvases.length <= 1) {
let canvas = typeof obj.canvas === 'number' ? obj.canvas : 0
let animation = typeof obj.animation === 'number' ? obj.animation : 0
// Make sure we're creating a valid shape
if (typeof obj['shape'] === 'string') {
obj.canvases = canvases
obj.animations = canvases[canvas].animations
switch (obj['shape']) {
case 'circ':
canvases[canvas].animations[animation].shapes.push(
new Circle(obj)
)
break
case 'rect':
canvases[canvas].animations[animation].shapes.push(
new Rectangle(obj)
)
break
default:
throw new Error('Provided shape not valid.')
}
} else {
throw new Error(
'Function incorrectly called. Object required with shape property (string).'
)
}
} else {
throw new Error('Canvas ID is not defined.')
}
},
// Add a new image
addImage: obj => {
// Make sure we know which canvas we're adding the image to
if (typeof obj.canvas === 'number' || canvases.length <= 1) {
obj.canvases = canvases
canvases[obj.canvas].animations[obj.animation].images.push(
new CanvasImage(obj)
)
} else {
throw new Error('Canvas ID is not defined.')
}
},
// Remove all the shapes from the specified canvas
clearShapes: (canvas, animation) => {
canvases[canvas].animations[animation].shapes = []
},
// Remove all the images from the specified canvas
clearImages: (canvas, animation) => {
canvases[canvas].animations[animation].images = []
},
// Remove all the shapes, images and animations from the specified canvas
clearCanvas: canvas => {
canvases[canvas].animations = []
},
// Remove all shapes AND images from an animation
clearAnimation: (canvas, animation) => {
canvases[canvas].animations[animation].shapes = []
canvases[canvas].animations[animation].images = []
},
// Run one or all of the canvases
run: (canvas, animation) => {
if (typeof canvas === 'number' || canvases.length <= 1) {
if (typeof canvas !== 'number') canvas = 0
window.cancelAnimationFrame(nextFrame)
if (typeof animation === 'number') {
canvases[canvas].animations[animation].play = true
} else {
for (let i = 0; i < canvases[canvas].animations.length; i++) {
canvases[canvas].animations[i].play = true
}
}
nextFrame = window.requestAnimationFrame(_draw)
} else {
throw new Error('Canvas ID is not defined.')
}
},
// Stop one or all of the canvases
stop: (canvas, animation) => {
if (typeof canvas !== 'undefined') {
if (typeof animation === 'number') {
canvases[canvas].animations[animation].play = false
} else {
for (let i = 0; i < canvases.length; i++) {
canvases[canvas].animations[i].play = false
}
window.cancelAnimationFrame(nextFrame)
}
} else {
throw new Error('Canvas ID is not defined.')
}
},
// Get the dimensions of one or all of the canvases
getCanvasSize: i => {
if (canvases.ctx !== 'undefined') {
if (i) {
return {
width: canvases[i].ctx.canvas.width,
height: canvases[i].ctx.canvas.height
}
} else {
let sizes = []
for (let j = 0; j < canvases.length; j++) {
sizes.push({
width: canvases[j].ctx.canvas.width,
height: canvases[j].ctx.canvas.height
})
}
if (sizes.length === 1) return sizes[0]
return sizes
}
}
throw new Error('Canvas must be set up before this function is called.')
},
// Get the current progress of an animation
getCurrentProgress: (canvas, animation) => {
return canvases[canvas].animations[animation].progress
},
// Return the canvases so they can be accessed publically
canvases
}
})()
export { CanvasPlus as default, Ease }
<file_sep>/src/classes/Shape.js
// Generic shape
class Shape {
constructor(params) {
this.type
this.animations = params.animations
this.GCO = typeof params.GCO === 'string' ? params.GCO : 'source-over'
this.animation = typeof params.animation === 'number' ? params.animation : 0
// Start position must be specified, end position defaults to start
if (
(typeof params.position.start === 'object' &&
typeof params.position.end === 'object') ||
typeof params.position.end === 'undefined'
) {
this.pos = {
start: params.position.start,
end:
typeof params.position.end === 'object'
? params.position.end
: params.position.start
}
this.fill = typeof params.fill === 'string' ? params.fill : '#000000'
} else {
throw new Error(
'New shapes require a starting position (array: [startX, startY] )'
)
}
// Rotation defaults to none
this.rot = {
start: 0,
end: 0
}
// End rotation defaults to start
if (typeof params.rotation === 'object') {
if (
(typeof params.rotation.start === 'number' &&
typeof params.rotation.end === 'number') ||
typeof params.rotation.end === 'undefined'
) {
this.rot = {
start: params.rotation.start,
end:
typeof params.rotation.end === 'number'
? params.rotation.end
: params.rotation.start
}
}
}
// Scale defaults to none
this.scale = {
start: 1,
end: 1
}
// End scale defaults to start
if (typeof params.scale === 'object') {
if (
(typeof params.scale.start === 'number' &&
typeof params.scale.end === 'number') ||
typeof params.scale.end === 'undefined'
) {
this.scale = {
start: params.scale.start,
end:
typeof params.scale.end === 'number'
? params.scale.end
: params.scale.start
}
}
}
// Opacity defaults to 1
this.opacity = {
start: 1,
end: 1
}
// End opacity defaults to start
if (typeof params.opacity === 'object') {
if (
(typeof params.opacity.start === 'number' &&
typeof params.opacity.end === 'number') ||
typeof params.opacity.end === 'undefined'
) {
this.opacity = {
start: params.opacity.start,
end:
typeof params.opacity.end === 'number'
? params.opacity.end
: params.opacity.start
}
}
}
}
// Work out current position based on progress
currentPosition(p) {
const x =
this.pos.start[0] +
(this.pos.end[0] - this.pos.start[0]) *
this.animations[this.animation].easing(p)
const y =
this.pos.start[1] +
(this.pos.end[1] - this.pos.start[1]) *
this.animations[this.animation].easing(p)
return [x, y]
}
// Work out current rotation based on progress
currentRotation(p) {
return (
this.rot.start +
(this.rot.end - this.rot.start) *
this.animations[this.animation].easing(p)
)
}
// Work out current opacity based on progress
currentOpacity(p) {
return (
this.opacity.start +
(this.opacity.end - this.opacity.start) *
this.animations[this.animation].easing(p)
)
}
}
class Circle extends Shape {
constructor(params) {
// Has all the parameters as a generic shape, as well as a radius
super(params)
// Radius defaults to 75px
this.r = typeof params.r === 'number' ? params.r : 75
}
// Work out current scale based on progress
currentScale(p) {
if (this.scale.start !== this.scale.end) {
return (
this.r +
this.r *
((this.scale.start + (this.scale.end - this.scale.start)) *
this.animations[this.animation].easing(p) -
this.animations[this.animation].easing(p))
)
}
return this.r * this.scale.start
}
// Draw the circle on the canvas
draw(pos, r) {
this.animations[this.animation].canvases[
this.animations[this.animation].canvas
].ctx.arc(pos[0], pos[1], r, 0, 2 * Math.PI)
}
}
class Rectangle extends Shape {
constructor(params) {
// Has all the parameters as a generic shape, as well as a width & height
super(params)
// Width and height default to 75px
this.w = typeof params.w === 'number' ? params.w : 75
this.h = typeof params.h === 'number' ? params.h : 75
}
// Work out current scale based on progress
currentScale(p) {
let w = this.w * this.scale.start
let h = this.h * this.scale.start
if (this.scale.start !== this.scale.end) {
w =
this.w +
this.w *
((this.scale.start + (this.scale.end - this.scale.start)) *
this.animations[this.animation].easing(p) -
this.animations[this.animation].easing(p))
h =
this.h +
this.h *
((this.scale.start + (this.scale.end - this.scale.start)) *
this.animations[this.animation].easing(p) -
this.animations[this.animation].easing(p))
}
return [w, h]
}
// Draw the rectangle on the canvas
draw(pos, wh) {
this.animations[this.animation].canvases[
this.animations[this.animation].canvas
].ctx.rect(pos[0], pos[1], wh[0], wh[1])
}
}
export { Circle, Rectangle }
<file_sep>/README.md
# canvasplus
[](https://github.com/sambeevors/canvasplus/issues) [](https://github.com/sambeevors/canvasplus/stargazers) [](https://prettier.io/)
A JavaScript library for creating animations simply within HTML5 canvas.
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Contributing](#contributing)
- [License](#license)
## Installation
Can be installed via npm or yarn
```shell
npm i @sambeevors/canvasplus
```
```shell
yarn add @sambeevors/canvasplus
```
## Usage
To get started, you first need to import `canvasplus` and create a new canvas
```javascript
import { CanvasPlus, Ease } from 'canvasplus'
```
```javascript
CanvasPlus.addCanvas({
el: '#canvas',
size: [300, 150]
})
```
Add an animation
```javascript
CanvasPlus.addAnimation({
duration: 900,
easing: Ease.outQuad,
loop: true
})
```
Then simply add a shape
```javascript
CanvasPlus.addShape({
shape: 'rect',
w: 100,
h: 100,
position: {
start: [0, 0],
end: [300, 150]
}
})
```
You can also add images to the animation in a similar way
```javascript
CanvasPlus.addImage({
src: 'example.jpg',
w: 50,
h: 75,
position: {
start: [150, 150]
}
})
```
Once you are ready you can start your animation
```javascript
CanvasPlus.run()
```
## Contributing
Contributions are welcome! There's so much I want to do with this project but struggle to find the time to do it. If there's any features you want me to add, open an issue or even have a go yourself! PRs are always welcome.
To get the project running locally, simply install dependencies with `yarn`.
## License
This package is covered by the [MIT License](https://opensource.org/licenses/MIT).
|
c559b9d213472ed41234e73977cbbc763b64f5c4
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
sambeevors/canvasplus
|
7a7ffb3875516553d8f009916f2174a3cd27c295
|
56bbbf5714a837a82cf6ab3af765457d7b0e0026
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
/* function Home(){
return view('HomeView');
}
function about(){
return view('AboutView');
}
function contact(){
return view('ContactView');
}*/
function index(){
return view('HomeView');
}
function validation(Request $request){
if($request->username == $request->password){
//session
return redirect('/home');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class LoginController extends Controller
{
function index(){
return view('login.index');
}
function verify(Request $request){
$user = new User();
$data = $user->where('username', $request->username)
->where('password', $request->password)
->get();
if(count($data) > 0 ){
$request->session()->put('username', $request->username);
if($request->username == $data[0]['type']){
$request->session()->put('type', "admin");
}
return redirect('/home');
}else{
$request->session()->flash('msg', 'invalid username/password');
return redirect('/login');
}
}
}
|
1098db6f328f419c9a8c6b9329529ff20596b6f2
|
[
"PHP"
] | 2
|
PHP
|
mahmodulhassan37/Laravel-Final-Assignment
|
9f10d2d291d1cb0e896b427f009ccd24936e91ba
|
b6e7835b7ca3d9523a5a1322a3ef7d0528f9b228
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
import logging
from .messages import *
from .htmlhelpers import *
from .requests import requests
def lintExampleIDs(doc):
if not doc.md.complainAbout['missing-example-ids']:
return
for el in findAll(".example:not([id])", doc):
warn("Example needs ID:\n{0}", outerHTML(el)[0:100], el=el)
def lintBrokenLinks(doc):
if not doc.md.complainAbout['broken-links']:
return
say("Checking links, this may take a while...")
logging.captureWarnings(True) # Silence the requests library :/
for el in findAll("a", doc):
href = el.get('href')
if not href or href[0] == "#":
continue
res = requests.get(href)
if res.status_code >= 400:
warn("Got a {0} status when fetching the link for:\n{1}", res.status_code, outerHTML(el))
say("Done checking links!")
<file_sep># -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
import collections
from . import config
from . import lexers
from .messages import *
from .htmlhelpers import *
from .widlparser.widlparser import parser
ColoredText = collections.namedtuple('ColoredText', ['text', 'color'])
class IDLUI(object):
def warn(self, msg):
die("{0}", msg.rstrip())
class HighlightMarker(object):
# Just applies highlighting classes to IDL stuff.
def markupTypeName(self, text, construct):
return ('<span class=n>', '</span>')
def markupName(self, text, construct):
return ('<span class=nv>', '</span>')
def markupKeyword(self, text, construct):
return ('<span class=kt>', '</span>')
def markupEnumValue(self, text, construct):
return ('<span class=s>', '</span>')
def addSyntaxHighlighting(doc):
try:
import pygments as pyg
from pygments.lexers import get_lexer_by_name
from pygments import formatters
except ImportError:
die("Bikeshed now uses Pygments for syntax highlighting.\nPlease run `$ sudo pip install pygments` from your command line.")
return
customLexers = {
"css": lexers.CSSLexer()
}
def highlight(el, lang):
text = textContent(el)
if lang in ["idl", "webidl"]:
widl = parser.Parser(text, IDLUI())
marker = HighlightMarker()
nested = parseHTML(unicode(widl.markup(marker)))
coloredText = collections.deque()
for n in childNodes(flattenHighlighting(nested)):
if isElement(n):
coloredText.append(ColoredText(textContent(n), n.get('class')))
else:
coloredText.append(ColoredText(n, None))
else:
if lang in customLexers:
lexer = customLexers[lang]
else:
try:
lexer = get_lexer_by_name(lang, encoding="utf-8", stripAll=True)
except pyg.util.ClassNotFound:
die("'{0}' isn't a known syntax-highlighting language. See http://pygments.org/docs/lexers/. Seen on:\n{1}", lang, outerHTML(el), el=el)
return
coloredText = parsePygments(pyg.highlight(text, lexer, formatters.RawTokenFormatter()))
# empty span at beginning
# extra linebreak at the end
mergeHighlighting(el, coloredText)
addClass(el, "highlight")
highlightingOccurred = False
if find("pre.idl, xmp.idl", doc) is not None:
highlightingOccurred = True
def translateLang(lang):
# Translates some names to ones Pygment understands
if lang == "aspnet":
return "aspx-cs"
if lang in ["markup", "svg"]:
return "html"
return lang
# Translate Prism-style highlighting into Pygment-style
for el in findAll("[class*=language-], [class*=lang-]", doc):
match = re.search("(?:lang|language)-(\w+)", el.get("class"))
if match:
el.set("highlight", match.group(1))
# Highlight all the appropriate elements
for el in findAll("xmp, pre, code", doc):
attr, lang = closestAttr(el, "nohighlight", "highlight")
if attr == "nohighlight":
continue
if attr is None:
if el.tag in ["pre", "xmp"] and hasClass(el, "idl"):
if isNormative(el):
# Already processed/highlighted.
continue
lang = "idl"
elif doc.md.defaultHighlight is None:
continue
else:
lang = doc.md.defaultHighlight
highlight(el, translateLang(lang))
highlightingOccurred = True
if highlightingOccurred:
# To regen the styles, edit and run the below
#from pygments import token
#from pygments import style
#class PrismStyle(style.Style):
# default_style = "#000000"
# styles = {
# token.Name: "#0077aa",
# token.Name.Tag: "#669900",
# token.Name.Builtin: "noinherit",
# token.Name.Variable: "#222222",
# token.Name.Other: "noinherit",
# token.Operator: "#999999",
# token.Punctuation: "#999999",
# token.Keyword: "#990055",
# token.Literal: "#000000",
# token.Literal.Number: "#000000",
# token.Literal.String: "#a67f59",
# token.Comment: "#708090"
# }
#print formatters.HtmlFormatter(style=PrismStyle).get_style_defs('.highlight')
doc.extraStyles['style-syntax-highlighting'] += '''
.highlight:not(.idl) { background: hsl(24, 20%, 95%); }
code.highlight { padding: .1em; border-radius: .3em; }
pre.highlight, pre > code.highlight { display: block; padding: 1em; margin: .5em 0; overflow: auto; border-radius: 0; }
.highlight .c { color: #708090 } /* Comment */
.highlight .k { color: #990055 } /* Keyword */
.highlight .l { color: #000000 } /* Literal */
.highlight .n { color: #0077aa } /* Name */
.highlight .o { color: #999999 } /* Operator */
.highlight .p { color: #999999 } /* Punctuation */
.highlight .cm { color: #708090 } /* Comment.Multiline */
.highlight .cp { color: #708090 } /* Comment.Preproc */
.highlight .c1 { color: #708090 } /* Comment.Single */
.highlight .cs { color: #708090 } /* Comment.Special */
.highlight .kc { color: #990055 } /* Keyword.Constant */
.highlight .kd { color: #990055 } /* Keyword.Declaration */
.highlight .kn { color: #990055 } /* Keyword.Namespace */
.highlight .kp { color: #990055 } /* Keyword.Pseudo */
.highlight .kr { color: #990055 } /* Keyword.Reserved */
.highlight .kt { color: #990055 } /* Keyword.Type */
.highlight .ld { color: #000000 } /* Literal.Date */
.highlight .m { color: #000000 } /* Literal.Number */
.highlight .s { color: #a67f59 } /* Literal.String */
.highlight .na { color: #0077aa } /* Name.Attribute */
.highlight .nc { color: #0077aa } /* Name.Class */
.highlight .no { color: #0077aa } /* Name.Constant */
.highlight .nd { color: #0077aa } /* Name.Decorator */
.highlight .ni { color: #0077aa } /* Name.Entity */
.highlight .ne { color: #0077aa } /* Name.Exception */
.highlight .nf { color: #0077aa } /* Name.Function */
.highlight .nl { color: #0077aa } /* Name.Label */
.highlight .nn { color: #0077aa } /* Name.Namespace */
.highlight .py { color: #0077aa } /* Name.Property */
.highlight .nt { color: #669900 } /* Name.Tag */
.highlight .nv { color: #222222 } /* Name.Variable */
.highlight .ow { color: #999999 } /* Operator.Word */
.highlight .mb { color: #000000 } /* Literal.Number.Bin */
.highlight .mf { color: #000000 } /* Literal.Number.Float */
.highlight .mh { color: #000000 } /* Literal.Number.Hex */
.highlight .mi { color: #000000 } /* Literal.Number.Integer */
.highlight .mo { color: #000000 } /* Literal.Number.Oct */
.highlight .sb { color: #a67f59 } /* Literal.String.Backtick */
.highlight .sc { color: #a67f59 } /* Literal.String.Char */
.highlight .sd { color: #a67f59 } /* Literal.String.Doc */
.highlight .s2 { color: #a67f59 } /* Literal.String.Double */
.highlight .se { color: #a67f59 } /* Literal.String.Escape */
.highlight .sh { color: #a67f59 } /* Literal.String.Heredoc */
.highlight .si { color: #a67f59 } /* Literal.String.Interpol */
.highlight .sx { color: #a67f59 } /* Literal.String.Other */
.highlight .sr { color: #a67f59 } /* Literal.String.Regex */
.highlight .s1 { color: #a67f59 } /* Literal.String.Single */
.highlight .ss { color: #a67f59 } /* Literal.String.Symbol */
.highlight .vc { color: #0077aa } /* Name.Variable.Class */
.highlight .vg { color: #0077aa } /* Name.Variable.Global */
.highlight .vi { color: #0077aa } /* Name.Variable.Instance */
.highlight .il { color: #000000 } /* Literal.Number.Integer.Long */
'''
def mergeHighlighting(el, coloredText):
# Merges a tree of Pygment-highlighted HTML
# into the original element's markup.
# This works because Pygment effectively colors each character with a highlight class,
# merging them together into runs of text for convenience/efficiency only;
# the markup structure is a flat list of sibling elements containing raw text
# (and maybe some un-highlighted raw text between them).
def colorizeEl(el, coloredText):
for node in childNodes(el, clear=True):
if isElement(node):
appendChild(el, colorizeEl(node, coloredText))
else:
appendChild(el, *colorizeText(node, coloredText))
return el
def colorizeText(text, coloredText):
nodes = []
while text and coloredText:
nextColor = coloredText.popleft()
if len(nextColor.text) <= len(text):
if nextColor.color is None:
nodes.append(nextColor.text)
else:
nodes.append(E.span({"class":nextColor.color}, nextColor.text))
text = text[len(nextColor.text):]
else: # Need to use only part of the nextColor node
if nextColor.color is None:
nodes.append(text)
else:
nodes.append(E.span({"class":nextColor.color}, text))
# Truncate the nextColor text to what's unconsumed,
# and put it back into the deque
nextColor = ColoredText(nextColor.text[len(text):], nextColor.color)
coloredText.appendleft(nextColor)
text = ''
return nodes
colorizeEl(el, coloredText)
def flattenHighlighting(el):
# Given a highlighted chunk of markup that is "nested",
# flattens it into a sequence of text and els with just text,
# by merging classes upward.
container = E.div()
for node in childNodes(el):
if not isElement(node):
# raw text
appendChild(container, node)
elif not hasChildElements(node):
# el with just text
appendChild(container, node)
else:
# el with internal structure
overclass = el.get("class", "")
flattened = flattenHighlighting(node)
for subnode in childNodes(flattened):
if isElement(subnode):
addClass(subnode, overclass)
appendChild(container, subnode)
else:
appendChild(container, E.span({"class":overclass},subnode))
return container
def parsePygments(text):
tokenClassFromName = {
"Token.Comment": "c",
"Token.Keyword": "k",
"Token.Literal": "l",
"Token.Name": "n",
"Token.Operator": "o",
"Token.Punctuation": "p",
"Token.Comment.Multiline": "cm",
"Token.Comment.Preproc": "cp",
"Token.Comment.Single": "c1",
"Token.Comment.Special": "cs",
"Token.Keyword.Constant": "kc",
"Token.Keyword.Declaration": "kd",
"Token.Keyword.Namespace": "kn",
"Token.Keyword.Pseudo": "kp",
"Token.Keyword.Reserved": "kr",
"Token.Keyword.Type": "kt",
"Token.Literal.Date": "ld",
"Token.Literal.Number": "m",
"Token.Literal.String": "s",
"Token.Name.Attribute": "na",
"Token.Name.Class": "nc",
"Token.Name.Constant": "no",
"Token.Name.Decorator": "nd",
"Token.Name.Entity": "ni",
"Token.Name.Exception": "ne",
"Token.Name.Function": "nf",
"Token.Name.Label": "nl",
"Token.Name.Namespace": "nn",
"Token.Name.Property": "py",
"Token.Name.Tag": "nt",
"Token.Name.Variable": "nv",
"Token.Operator.Word": "ow",
"Token.Literal.Number.Bin": "mb",
"Token.Literal.Number.Float": "mf",
"Token.Literal.Number.Hex": "mh",
"Token.Literal.Number.Integer": "mi",
"Token.Literal.Number.Oct": "mo",
"Token.Literal.String.Backtick": "sb",
"Token.Literal.String.Char": "sc",
"Token.Literal.String.Doc": "sd",
"Token.Literal.String.Double": "s2",
"Token.Literal.String.Escape": "se",
"Token.Literal.String.Heredoc": "sh",
"Token.Literal.String.Interpol": "si",
"Token.Literal.String.Other": "sx",
"Token.Literal.String.Regex": "sr",
"Token.Literal.String.Single": "s1",
"Token.Literal.String.Symbol": "ss",
"Token.Name.Variable.Class": "vc",
"Token.Name.Variable.Global": "vg",
"Token.Name.Variable.Instance": "vi",
"Token.Literal.Number.Integer.Long": "il"
}
coloredText = collections.deque()
for line in text.split("\n"):
if not line:
continue
tokenName,_,tokenTextRepr = line.partition("\t")
tokenText = eval(tokenTextRepr)
if not tokenText:
continue
if tokenName == "Token.Text":
tokenClass = None
else:
tokenClass = tokenClassFromName.get(tokenName, None)
coloredText.append(ColoredText(tokenText, tokenClass))
return coloredText
<file_sep># -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
import glob
import io
import difflib
import subprocess
import pipes
from itertools import *
from .messages import *
from .htmlhelpers import parseDocument, outerHTML, nodeIter, isElement, findAll
from . import config
def runAllTests(constructor, testFiles):
numPassed = 0
if len(testFiles) == 0:
testFolder = config.scriptPath + "/../tests/"
testFiles = glob.glob(testFolder + "*.bs")
if len(testFiles) == 0:
p("No tests were found in '{0}'.".format(testFolder))
return True
total = 0
fails = []
for testPath in testFiles:
_,_,testName = testPath.rpartition("/")
p(testName)
total += 1
doc = constructor(inputFilename=testPath)
doc.preprocess()
outputText = doc.serialize()
with io.open(testPath[:-2] + "html", encoding="utf-8") as golden:
goldenText = golden.read()
if compare(outputText, goldenText):
numPassed += 1
else:
fails.append(testName)
if numPassed == total:
p(printColor("✔ All tests passed.", color="green"))
return True
else:
p(printColor("✘ {0}/{1} tests passed.".format(numPassed, total), color="red"))
p(printColor("Failed Tests:", color="red"))
for fail in fails:
p("* " + fail)
def compare(suspect, golden):
suspectDoc = parseDocument(suspect)
goldenDoc = parseDocument(golden)
for s, g in izip(nodeIter(suspectDoc), nodeIter(goldenDoc)):
if isElement(s) and isElement(g):
if s.tag == g.tag and compareDicts(s.attrib, g.attrib):
continue
elif isinstance(g, basestring) and isinstance(s, basestring):
if equalOrEmpty(s, g):
continue
if isinstance(g, basestring):
fromText = g
else:
fromText = outerHTML(g)
if isinstance(s, basestring):
toText = s
else:
toText = outerHTML(s)
differ = difflib.SequenceMatcher(None, fromText, toText)
for tag, i1, i2, j1, j2 in differ.get_opcodes():
if tag == "equal":
p(fromText[i1:i2])
if tag in ("delete", "replace"):
p("\033[41m\033[30m" + fromText[i1:i2] + "\033[0m")
if tag in ("insert", "replace"):
p("\033[42m\033[30m" + toText[j1:j2] + "\033[0m")
p("")
return False
return True
def compareDicts(a, b):
aKeys = set(a.keys())
bKeys = set(b.keys())
if aKeys != bKeys:
return False
for key in aKeys:
if a[key] != b[key]:
return False
return True
def equalOrEmpty(a, b):
if a == b:
return True
if a is not None and b is not None and "" == a.strip() == b.strip():
return True
return False
def rebase(files=None):
if not files:
files = glob.glob(config.scriptPath + "/../tests/*.bs")
for path in files:
_,_,name = path.rpartition("/")
p("Rebasing {0}".format(name))
subprocess.call("bikeshed -qf spec {0}".format(pipes.quote(path)), shell=True)
|
2f2be289dd6d01bdd276894e77d236d3cadbecbd
|
[
"Python"
] | 3
|
Python
|
gregwhitworth/bikeshed
|
91d148889d0e778597d543b56a886668f45f12a4
|
1a212557dc71111e6568c4f934b6ba3dc4d6f51a
|
refs/heads/master
|
<file_sep>print("stats")
|
59d796a91eaf6a7f0c9f6153dd6c7f796e2803c1
|
[
"Python"
] | 1
|
Python
|
ziqi-ma/evaluation-visualizer
|
2a49040a5abe5161b128c2d524450406be59afc7
|
7b79d9fc344e8f029aee964608353571d65c4c54
|
refs/heads/master
|
<file_sep>import {
Component,
OnInit
}
from '@angular/core';
import {
UsersService
}
from '../users.service';
import {
Router
}
from '@angular/router';
declare var jquery:any;
declare var $ :any;
@Component( {
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
}
) export class LoginComponent implements OnInit {
username='';
password='';
users: any;
error_txt='';
constructor(private usersService: UsersService, private router: Router) {}
ngOnInit() {
sessionStorage.clear();
$('.alert').hide('');
}
async usersLogin() {
if (this.username !=''&& this.password !='') {
this.users=await this.usersService.login(this.username, this.password);
if(this.users !=false) {
sessionStorage.setItem('loginuser', JSON.stringify(this.users));
if(this.users.users_status=='admin') this.router.navigate(['/admin']);
else if(this.users.users_status=='user') this.router.navigate(['/user']);
else {
this.error_txt='Invalid Username or Password';
$('.alert').show();
}
}
else {
this.error_txt='Please enter Username and Password';
$('.alert').show();
}
}
else {
this.error_txt='Please enter Username and Password';
$('.alert').show();
}
}
}
|
38cceb01f184f7c3ab3d824d9bf695e74819c74e
|
[
"TypeScript"
] | 1
|
TypeScript
|
sabitip/netlog
|
49b2ea0ffbc728ce309ba5f8ab72fc5dd6a9e9ca
|
de944d79edf433ef22aac227fe14aea6b17cfbb7
|
refs/heads/master
|
<file_sep> Page({
/**
* 页面的初始数据
*/
data: {
order_content:[{
img:'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846033073.jpg',
commodity_name:'女青年色彩头像示范',
commodity_price:'0.50',
comm_num:'2'
}],
pay_type:0,
selectpay: false,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if ( options.url){
this.setData({
cart_ids: options.url
})
}else{
this.setData({
id: options.id,
count: options.count,
})
}
},
// 单选框点击事件
radioChange: function (e) {
console.log('radio发生change事件,携带value值为:', e.detail.value);
var pay_type = e.detail.value;
console.log(pay_type, 787878);
this.setData({
pay_type: pay_type,
selectpay: false
})
},
//打开支付方式弹出层
pay_style: function () {
this.setData({
selectpay: true
})
},
closepay: function () {
this.setData({
selectpay: false
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/confirmShopOrder`,
data: {
c_user_id: c_user_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
}
})
that.show_shop();
},
/**商品信息 */
show_shop:function(){
var that=this;
console.log(that.data.cart_ids,6666)
if (that.data.cart_ids){
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/cartConfirmOrder`,
data: {
c_user_id: that.data.c_user_id,
cart_ids: that.data.cart_ids
},
header: {},
success: function (res) {
console.log(res.data.data, 8976)
var order_content = res.data.data;
var cartList = order_content.cartList;
var userAddress = order_content.userAddress;
var c_user_vip = order_content.c_user_vip;
var t_coupons = order_content.t_coupons
var b = true;
var coupons_null = 1;
var isShow = false
if (!t_coupons) {
coupons_null = 0
}
if (userAddress) {
b = false;
isShow = true
}
console.log(order_content, 9080)
that.setData({
order_content: order_content,
cartList: cartList,
isNull: b,
isShow: isShow,
userAddress: userAddress,
c_user_vip: c_user_vip,
coupons_null: coupons_null,
t_coupons: t_coupons
})
}
})
}else{
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/commerceConfirmOrder`,
data: {
c_user_id: that.data.c_user_id,
comm_num: that.data.count,
commodity_id: that.data.id
},
header: {},
success: function (res) {
var order_content = res.data.data;
var cartList = order_content.cartList;
var userAddress = order_content.userAddress;
var c_user_vip = order_content.c_user_vip;
var t_coupons = order_content.t_coupons
var b = true;
var coupons_null = 1;
var isShow=false
if (!t_coupons) {
coupons_null = 0
}
if (userAddress) {
b = false;
isShow=true
}
console.log(coupons_null,76767)
console.log(order_content, 90909654)
that.setData({
order_content: order_content,
cartList: cartList,
isNull: b,
isShow: isShow,
userAddress: userAddress,
c_user_vip: c_user_vip,
t_coupons: t_coupons,
coupons_null: coupons_null
})
}
})
}
},
// 单选框点击事件
radioChange: function (e) {
console.log('radio发生change事件,携带value值为:', e.detail.value);
var pay_type = e.detail.value;
console.log(pay_type,787878);
this.setData({
pay_type: pay_type,
selectpay: false
})
},
//打开支付方式弹出层
pay_style:function(){
this.setData({
selectpay: true
})
},
closepay:function(){
this.setData({
selectpay:false
})
},
//添加备注
remarks: function (e) {
this.setData({
remarks:e.detail.value
})
},
preventTouchMove: function () {
},
bindText: function (e) {
this.setData({
remarks: e.detail.value
})
},
// 跳转到'我的地址'
myAddress: function (e) {
wx.navigateTo({
url: '../my_address/my_address',
})
},
/**确认支付 */
toPay:function(e){
var that = this;
var remarks = that.data.remarks;
console.log(that.data)
if (!remarks) {
remarks = '无'
}
if (!that.data.userAddress) {
wx.showModal({
title: '提示',
content: '收货地址不能为空',
})
return false;
}
var t_coupons = that.data.t_coupons;
var coupons_id = '';
if (t_coupons) {
coupons_id = t_coupons.coupons_id;
}
console.log(that.data.count,55555);
var url = `${getApp().globalData.baseUrl}/wechat/order/toCommerceOrder`;
if(that.data.cart_ids){
url = `${getApp().globalData.baseUrl}/wechat/order/toCartOrder`;
}
wx.request({
url: url,
data: {
eat_type: 3,
address_id: that.data.userAddress.address_id,
commodity_id: that.data.id,
comm_num: that.data.count,
coupons_id: coupons_id,
remarks: remarks,
c_user_id: that.data.c_user_id,
pay_type: that.data.pay_type,
cart_ids: that.data.cart_ids
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
wx.showLoading({
title: '支付中...',
})
console.log(res.data.data, 999999)
if (res.data.code == 200) {
var order_id = res.data.data.order_id;
if (that.data.pay_type == 0) {
var openId = (wx.getStorageSync('openId'));
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/pay/weChatPay`,
data: {
openid: openId,
order_id: order_id
},
success: function (param) {
console.log(param.data);
console.log(param.data.data.timeStamp);
console.log(param.data.data.nonceStr);
console.log(param.data.data.package);
console.log(param.data.data.paySign);
wx.requestPayment(
{
'timeStamp': '' + param.data.data.timeStamp,
'nonceStr': '' + param.data.data.nonceStr,
'package': '' + param.data.data.package,
'signType': 'MD5',
'paySign': '' + param.data.data.paySign,
'success': function (res) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPaySuccess`,
data: {
order_id: order_id,
id: getApp().globalData.distributor_id
},
success:function(res){
}
})
console.log(res);
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
});
},
'fail': function (res) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPayFail`,
data: {
order_id: order_id
},
success: function (res) {
}
})
console.log("支付失败");
},
'complete': function (res) {
console.log("pay complete")
wx.hideLoading()
wx.redirectTo({
url: '../order_details/order_details?url=' + order_id,
})
}
})
}
})
} else {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/pay/balancePay`,
data: {
order_id: order_id
},
success: function (param) {
wx.hideLoading()
console.log(param.data,787878)
console.log(order_id, 787878)
if (param.data.code == 200) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPaySuccess`,
data: {
order_id: order_id,
id: getApp().globalData.distributor_id
},
success: function (res) {
}
})
wx.showModal({
title: '提示',
content: '支付成功',
success: function (res) {
wx.redirectTo({
url: '../order_details/order_details?url=' + order_id,
})
}
})
} else if (param.data.code == 501) {
//if (param.data.code = 200) {
wx.showModal({
title: '提示',
content: '余额不足'
});
//}
}
wx.hideLoading()
}
});
}
} else if(res.data.code == 501){
wx.showModal({
title: '提示',
content: '余额不足'
});
wx.hideLoading()
} else if (res.data.code == 503) {
wx.showModal({
title: '提示',
content: '库存不足啦~'
});
wx.hideLoading()
}
}
});
},
check_sure:function(e){
var time = e.target.dataset.time;
this.setData({
time: time
});
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>
Page({
/**
* 页面的初始数据
*/
data: {
order_content: [
{
img: 'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846033073.jpg'
}
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
status: options.status
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**跳转订单详情 */
order_details:function(e){
var aa = e.currentTarget.dataset.id
wx.navigateTo({
url: '../order_details/order_details?url='+aa,
})
},
guangguang:function(){
wx.switchTab({
url: '../store_list/store_list',
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id,
})
console.log(that.data.status,90909)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getCommAndTranOrderList`,
data:{
c_user_id: c_user_id,
status: that.data.status
},
header:{},
success:function(res){
var order_content=res.data.data;
console.log(order_content,888)
var shopNull = 0;
if (!order_content || order_content.length == 0) {
shopNull = 1;
}
var my_arr=[];
for (var i = 0; i < order_content.length; i++) {
my_arr.push(order_content[i].commodity_infoList[0].img_src);
}
that.setData({
order_content: order_content,
shopNull: shopNull,
my_arr: my_arr
})
}
})
},
/**打开所有商品 */
open_order:function(e){
var order_id=e.currentTarget.dataset.order_id;
console.log(order_id)
var order_content=this.data.order_content;
for (var i = 0; i < order_content.length;i++){
var id=order_content[i].order_id;
if (order_id==id){
var reserved1=order_content[i]['reserved1'];
order_content[i]['reserved1'] = reserved1=='1'?'0':'1';
}
}
this.setData({
order_content: order_content
})
},
/**提醒发货 */
remind:function(e){
var that=this;
var c_user_id = (wx.getStorageSync('c_user_id'));
var index=e.currentTarget.dataset.index;
var order_content=that.data.order_content;
order_content[index].store_id=1;
that.setData({
c_user_id: c_user_id,
order_content: order_content
})
var order_id = e.currentTarget.dataset.order_id
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/remindOrder`,
data:{
order_id: order_id,
c_user_id: c_user_id
},
header:{},
success:function(res){
wx.showLoading({
title: '已提醒卖家',
})
setTimeout(function () {
wx.hideLoading()
}, 2000)
}
})
},
//取消订单
quxiao: function (e) {
var that = this;
wx.showModal({
title: '您已取消订单',
success: res => {
if (res.confirm) {
//
var order_id = e.currentTarget.dataset.order_id;
console.log(order_id,1111);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/updateCommerceOrder`,
data: {
status: 7,
order_id: order_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
//在提示的成功函数中初始化当前加载订单页为第一页,清空订单列表数据
//this.setData({ currentPage: 1, orderList: [] });
//用onLoad周期方法重新加载,实现当前页面的刷新
var status = e.target.dataset.status;
console.log(status, 9090)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getCommAndTranOrderList`,
data: {
status: status,
c_user_id: that.data.c_user_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
var order_content = res.data.data;
that.setData({
order_content: order_content
})
// that.order_a();
}
})
}
})
} else {
console.log('用户点击取消')
}
}
});
},
/**待付款付款 */
mypay:function(e){
wx.showLoading({
title: '支付中...',
})
var order_id = e.currentTarget.dataset.order_id;
//var eat_type = e.currentTarget.dataset.eat_type;
var openId = (wx.getStorageSync('openId'));
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/pay/weChatPay`,
data: {
openid: openId,
order_id: order_id
},
success: function (param) {
wx.hideLoading()
wx.requestPayment({
'timeStamp': '' + param.data.data.timeStamp,
'nonceStr': '' + param.data.data.nonceStr,
'package': '' + param.data.data.package,
'signType': 'MD5',
'paySign': '' + param.data.data.paySign,
'success': function (res) {
// console.log(res);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPaySuccess`,
data: {
order_id: order_id,
id: getApp().globalData.distributor_id
},
success: function (res) {
}
})
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
});
},
'fail': function (res) {
console.log("支付失败");
},
'complete': function (res) {
console.log("pay complete");
wx.hideLoading()
wx.navigateTo({
url: '../order_details/order_details?url=' + order_id,
})
}
})
}
})
},
/**确认收货 */
store_sure:function(e){
var that = this;
wx.showModal({
title: '确认收货',
success: res => {
if (res.confirm) {
//
var order_id = e.currentTarget.dataset.order_id;
console.log(order_id, 1111);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/updateCommerceOrder`,
data: {
status: 4,
order_id: order_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
//在提示的成功函数中初始化当前加载订单页为第一页,清空订单列表数据
//this.setData({ currentPage: 1, orderList: [] });
//用onLoad周期方法重新加载,实现当前页面的刷新
var status = e.target.dataset.status;
console.log(status, 9090)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getCommAndTranOrderList`,
data: {
status: status,
c_user_id: that.data.c_user_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
var order_content = res.data.data;
that.setData({
order_content: order_content
})
// that.order_a();
}
})
}
})
} else {
console.log('用户确认收货')
}
}
});
},
/**评价 */
order_evaluate:function(e){
var aa = e.currentTarget.dataset.order_id;
var index = e.currentTarget.dataset.index;
var my_arr=this.data.my_arr;
console.log(my_arr);
wx.navigateTo({
url: '../order_evaluate/order_evaluate?url=' + aa + '&img_url=' + my_arr[index],
})
},
order_a: function () {
var that = this;
var status = that.data.status;
if (status == 9) {
status = '';
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getOrderList`,
data: {
status: status,
c_user_id: that.data.c_user_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
var order_content = res.data.data;
// my_orders.push(new_my_order)
// console.log(new_my_order, 55)
var my_choose = 0;
if (!order_content || order_content.length == 0) {
my_choose = 1;
}
that.setData({
order_content: order_content,
my_choose: my_choose,
})
}
})
},
/**查看物流 */
my_logs: function (e) {
var aa = e.currentTarget.dataset.order_id;
console.log(aa, 88888)
wx.navigateTo({
url: '../my_logs/my_logs?url=' + aa,
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
},
/**跳转详情 */
video_details:function(e){
var aa = e.currentTarget.dataset.id
// console.log(aa, 55555)
wx.navigateTo({
url: '../video_details/video_details?url=' + aa,
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getAllTranslateType`,
data:{},
header:{},
success:function(res){
console.log(res.data.data,878787);
var new_all_type=res.data.data;
var translateList2=[];
for (var i = 0; i < new_all_type.length;i++){
var new_translateList = new_all_type[i].translateList
for (var j = 0; j < new_translateList.length; j++) {
var translateList = new_translateList[j]["create_time"]
new_translateList[j]["create_time"] = util.shortTime(new Date(translateList));
}
translateList2.push(new_translateList);
}
console.log(translateList2,9999)
that.setData({
all_type: new_all_type,
translateList: translateList2
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
pay_type: 0
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
translate_id: options.url
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
// console.log(that.data.translate_id,99999)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getTranslateDetail`,
data:{
translate_id: that.data.translate_id
},
header:{},
success:function(res){
var new_video_pay=res.data.data;
new_video_pay.create_time = util.formatTime(new Date);
that.setData({
video_pay: new_video_pay
})
}
})
},
/**确认支付 */
toPay: function (e) {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
console.log(that.data)
var t_coupons = that.data.t_coupons;
var coupons_id = '';
if (t_coupons) {
coupons_id = t_coupons.coupons_id;
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/translateOrder`,
data: {
eat_type: 4,
coupons_id: coupons_id,
translate_id: that.data.translate_id,
c_user_id:c_user_id,
pay_type: 0,
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data.data, 999999)
if (res.data.code == 200) {
var order_id = res.data.data.order_id;
if (that.data.pay_type == 0) {
var openId = (wx.getStorageSync('openId'));
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/pay/weChatPay`,
data: {
openid: openId,
order_id: order_id
},
success: function (param) {
console.log(param.data);
console.log(param.data.data.timeStamp);
console.log(param.data.data.nonceStr);
console.log(param.data.data.package);
console.log(param.data.data.paySign);
wx.requestPayment(
{
'timeStamp': '' + param.data.data.timeStamp,
'nonceStr': '' + param.data.data.nonceStr,
'package': '' + param.data.data.package,
'signType': 'MD5',
'paySign': '' + param.data.data.paySign,
'success': function (res) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPaySuccess`,
data: {
order_id: order_id
},
success: function (res) {
}
})
console.log(res);
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
});
},
'fail': function (res) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/orderPayFail`,
data: {
order_id: order_id
},
success: function (res) {
}
})
console.log("支付失败");
},
'complete': function (res) {
console.log("pay complete")
// wx.redirectTo({
// url: '../video_details/video_details?url=' + that.data.translate_id,
// })
wx.navigateBack({})
}
})
}
})
} else {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/pay/balancePay`,
data: {
order_id: order_id
},
success: function (param) {
if (param.data.code = 200) {
wx.showModal({
title: '提示',
content: '支付成功',
success: function (res) {
wx.redirectTo({
url: '../video_details/video_details?url=' + that.data.translate_id,
})
}
})
} else if (param.data.code = 501) {
if (param.data.code = 200) {
wx.showModal({
title: '提示',
content: '余额不足'
});
}
}
}
});
}
}
}
});
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
day: '00',
h: '00',
m: '00',
s: '00',
order_content:[
{
img:'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846033073.jpg'
}
],
init:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
order_id: options.url
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
var init = that.data.init;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getCommerceOrderDetails`,
data:{
order_id: that.data.order_id
},
header:{},
success:function(res){
var order_details_con=res.data.data;
var new_t_order = order_details_con.t_order;
var t_store_info = order_details_con.t_store_info;
var recordList = order_details_con.t_order.recordList;
var overtime = order_details_con.overtime;
new_t_order.order_time = util.formatTime(new Date(new_t_order.order_time));
new_t_order.pay_time = util.formatTime(new Date(new_t_order.pay_time));
console.log(order_details_con, 9089);
that.setData({
order_details_con: order_details_con,
t_order: new_t_order,
t_store_info: t_store_info,
recordList:recordList,
overtime: overtime
})
if (init) {
(init);
}
init=setInterval(aaa, 1000);
that.setData({
init:init
})
function aaa() {
//console.log(overtime,878787)
var time = parseInt((overtime - new Date().getTime()) / 1000);
// console.log(time, 222)
if (time > 0) {
var s = parseInt(time % 60);
time = time / 60;
var m = parseInt(time % 60);
time = time / 60;
var h = parseInt(time % 24);
var day = parseInt(time / 24);
//console.log(toNum(day) + ':' + toNum(h) + ':' + toNum(m) + ":" + toNum(s), 98765);
that.setData({
day: toNum(day),
h: toNum(h),
m: toNum(m),
s: toNum(s)
})
}
}
function toNum(num) {
if (num < 10) {
num = "0" + num;
}
return num;
}
}
})
},
/**退款 */
refund: function (e) {
var aa = e.currentTarget.dataset.order_id;
console.log(aa, 88888)
wx.navigateTo({
url: '../refund/refund?url=' + aa,
})
},
/**订单有疑问 */
order_question:function(){
wx.navigateTo({
url: '../order/order',
})
},
/**时间倒计时*/
show_time:function(){
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
min: 0,//最少字数
max: 150, //最多字数 (根据自己需求改变)
loadhidden: true
},
//字数限制
inputs: function (e) {
// 获取输入框的内容
var value = e.detail.value;
// 获取输入框内容的长度
var len = parseInt(value.length);
//最多字数限制
if (len > this.data.max) return;
// 当输入框内容的长度大于最大长度限制(max)时,终止setData()的执行
this.setData({
currentWordNumber: len //当前字数
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
translate_id: options.url
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var c_user_id = (wx.getStorageSync('c_user_id'));
this.setData({
c_user_id: c_user_id
})
var that=this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getTranslateMessage`,
data:{
c_user_id: that.data.c_user_id,
translate_id: that.data.translate_id
},
header:{},
success:function(res){
var new_leave_content=res.data.data;
for (var i = 0; i < new_leave_content.length; i++) {
var leave_content = new_leave_content[i]["create_time"]
new_leave_content[i]["create_time"] = util.formatTime(new Date(leave_content));
}
that.setData({
leave: res.data.data,
leave_content: new_leave_content
})
}
})
},
//添加留言
content: function (e) {
this.setData({
content: e.detail.value
})
},
/**提交留言 */
submit_leave:function(e){
var c_user_id = (wx.getStorageSync('c_user_id'));
this.setData({
c_user_id: c_user_id
})
var that = this;
// that.setData({
// loadhidden: true
// });
var that=this;
const value = e.detail.value;
console.log(value.content, 88888888)
if(value.content){
this.setData({
loadhidden: false
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/addTranslateMessage`,
data: {
'c_user_id': that.data.c_user_id,
'translate_id': that.data.translate_id,
'content': e.detail.value.content
},
header: {},
success: function (res) {
if (res.data.code == 200) {
wx.showModal({
title: '提示',
content: '提交成功',
showCancel: false,
success: function (res) {
that.setData({
content: '',
loadhidden: true
})
}
})
that.onShow();
} else {
wx.showModal({
title: '提示',
content: '提交异常',
showCancel: true,
})
}
}
})
}else{
wx.showModal({
title: '提示',
content: '请填写完整资料',
showCancel: false
})
}
},
/**删除留言 */
leave_del:function(e){
var that=this;
wx.showModal({
title: '提示',
content: '确认要删除吗',
success: function (sm) {
if (sm.confirm) {
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/deleteTranslateMessage`,
data: {
id: e.currentTarget.dataset.id
},
header: {},
success: function (res) {
that.onShow();
}
})
} else if (sm.cancel) {
}
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>//app.js
App({
onLaunch: function() {
//wx.setStorageSync('c_user_id', "123");
var openId = (wx.getStorageSync('openId'));
var c_user_id = (wx.getStorageSync('c_user_id'));
//console.log(c_user_id, 222);
//console.log(openId, 11111);
//console.log(c_user_id, 222);
var that = this;
if (!openId ||!c_user_id) {
wx.login({
success: function (res) {
console.log(res.code)
if (res.code) {
wx.request({
//后台接口地址
url: `${ getApp().globalData.baseUrl }/wechat/home/index`,
data: {
code: res.code
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
// this.globalData.userInfo = JSON.parse(res.data);
console.log(res.data,3333);
wx.setStorageSync('openId', res.data.openid);
wx.setStorageSync('c_user_id', res.data.c_user_id);
c_user_id = res.data.c_user_id;
wx.request({
url: getApp().globalData.baseUrl+'/wechat/distributor/getDistributor',
data:{
c_user_id: c_user_id
},
header:{},
success:function(parms){
var distr=parms.data.data;
if (distr) {
getApp().globalData.my_distributor_id = distr.id;
}
}
})
}
})
}
}
})
}else{
wx.request({
url: 'https://store.vimi66.com/skin/wechat/distributor/getDistributor',
data: {
c_user_id: c_user_id
},
header: {},
success: function (parms) {
var distr = parms.data.data;
//console.log(distr, 7777)
if (distr){
getApp().globalData.my_distributor_id = distr.id;
}
//console.log(getApp().globalData.my_distributor_id,88989);
}
})
}
},
globalData: {
userInfo: null,
baseUrl: 'https://store.vimi66.com/skin',
distributor_id:null,
my_distributor_id:null
}
})<file_sep>Page({
/**
* 页面的初始数据
*/
data: {
all_store: [
{
store_img: 'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846023648.jpg',
store_name: '【助力联考 全场五折】 《造型的高度-素描》',
store_price: '64.00'
},
{
store_img: 'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846013044.jpg',
store_name: '【助力联考 全场五折】 《超越联考色彩》',
store_price: '59.00'
},
{
store_img: 'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846011313.jpg',
store_name: '【助力联考 全场五折】 《精彩色调》',
store_price: '48.00'
}
],
count: 1,
store_pop: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**跳转商品详情 */
store_details: function (e) {
var aa = e.currentTarget.dataset.id
console.log(aa, 87868)
wx.navigateTo({
url: '../shop_details/shop_details?url=' + aa,
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/getUserCollection`,
data: {
c_user_id:c_user_id
},
header: {},
success: function (res) {
var all_store = res.data.data;
console.log(all_store, 8079)
var shopNull=0
if (!all_store || all_store.length==0){
shopNull=1
}
that.setData({
all_store: all_store,
shopNull: shopNull
})
}
})
},
/**弹出层 */
gouwu_pop: function (e) {
this.setData({
store_pop: true
})
var that = this;
var commerce_id = e.currentTarget.dataset.id;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getCommerceDetail`,
data: {
commerce_id: commerce_id
},
header: {},
success: function (res) {
// console.log(res.data.data, 787878);
var store_pop = res.data.data;
that.setData({
store_pop: store_pop
})
}
})
},
preventTouchMove: function () {
},
close_gouwu: function () {
this.setData({
store_pop: false
})
},
/**立即购买 */
buy_now: function (e) {
var count = e.currentTarget.dataset.count;
var id = e.currentTarget.dataset.id
console.log(id, 322)
wx.navigateTo({
url: '../create_order/create_order?count=' + count + '&id=' + id,
})
},
/**添加购物车 */
my_add: function (e) {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
var comm_num = e.currentTarget.dataset.count;
var commodity_id = e.currentTarget.dataset.id
console.log(commodity_id, 1111)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/addShopToCart`,
data: {
comm_num: comm_num,
c_user_id: c_user_id,
commodity_id: commodity_id
},
header: {},
success: function (res) {
wx.showToast({
title: '加入购物车成功',
})
}
})
},
/**加商品 */
addtap: function () {
var that = this;
that.setData({
count: ++that.data.count
})
},
subtracttap: function () {
var that = this;
var count = that.data.count
if (count > 1) {
count--
}
that.setData({
count: count
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/cash_record/cash_record.js
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
inforHasMore: 1,
inforPage: 1,
cash_record: []
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getDrawimgRecordList`,
data: {
distributor_id: getApp().globalData.my_distributor_id,
c_user_id: c_user_id,
page: 1,
rows: 10
},
header: {},
success: function (res) {
console.log(res.data.data)
if (res.data.code = 200) {
var new_cash_record = res.data.data;
console.log(new_cash_record, 87678);
var shopNull=0
if (!new_cash_record || new_cash_record.length==0){
shopNull=1
}
for (var i = 0; i < new_cash_record.length; i++) {
var cash_record = new_cash_record[i]["create_time"];
new_cash_record[i]["create_time"] = util.formatTime(new Date(cash_record))
}
that.setData({
cash_record: new_cash_record,
shopNull: shopNull
})
if (res.data.data.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: 2
})
}
} else {
that.setData({
cash_record: [],
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log('查询失败');
}
})
},
/**分页加载 */
loadingMore: function () {
console.log(88888888)
var that = this;
var inforHasMore = that.data.inforHasMore;
if (inforHasMore == 1) {
wx.showLoading({
title: '正在加载',
})
var pa_cash_record = that.data.cash_record;
var inforPage = that.data.inforPage;
console.log(pa_cash_record, 9999);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getDrawimgRecordList`,
data: {
c_user_id: that.data.c_user_id,
page: inforPage,
rows: 10
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
wx.hideLoading();
if (res.data.code = 200) {
var cash_record = [];
var new_cash_record = pa_cash_record.concat(res.data.data);
for (var i = 0; i < new_cash_record.length; i++) {
cash_record.push(new_cash_record[i])
}
that.setData({
cash_record: cash_record
});
//console.log(res.data.data.cash_record, 555);
if (res.data.data.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: ++inforPage
})
}
} else {
that.setData({
cash_record: pa_cash_record,
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log("加载失败")
},
complete: function (res) {
console.log("加载完成")
}
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>Page({
/**
* 页面的初始数据
*/
data: {
order_type_list: [{
type_img: '../../images/type_one.png',
type_name: '待付款',
status: '0'
},
{
type_img: '../../images/type_two.png',
type_name: '待发货',
status: '2'
},
{
type_img: '../../images/type_three.png',
type_name: '待收货',
status: '3'
},
{
type_img: '../../images/type_four.png',
type_name: '待评价',
status: '4'
},
{
type_img: '../../images/type_five.png',
type_name: '退款/售后',
status: '8'
}
],
person_other_list: [
{
id: 0,
iconfont: 'icon-gouwuche',
other_name: '购物车',
url: '../shop_cart/shop_cart'
},
{
id: 1,
iconfont: 'icon-wodejuhuasuan',
other_name: '分销员中心',
url: '../no_fenxiao/no_fenxiao'
},
{
id: 2,
iconfont: 'icon-jushoucang',
other_name: '我的收藏',
url: '../mylove/mylove'
},
{
id: 3,
iconfont: 'icon-shouhuodizhi',
other_name: '收货地址',
url: '../my_address/my_address'
}
],
card_nums:'0'
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.getUserInfo({
withCredentials: true, //此处设为true,才会返回encryptedData等敏感信息
success: function(res) {
var sex = 'F'
if (res.userInfo.gender == 0) {
sex = "M"
} else {
sex = "F"
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/updateUser`,
data: {
c_user_id: c_user_id,
user_name: res.userInfo.nickName,
sex: sex,
avatar: res.userInfo.avatarUrl
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
//console.log(res.data,89989);
}
})
that.setData({
userInfo: res.userInfo,
my_person: 0
})
},
fail: function(res) {
that.setData({
my_person: 1
})
}
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/order/getCommAndTranOrderNum`,
data: {
c_user_id: c_user_id
},
header: {},
success: function(res) {
//console.log(res.data.data, 2345)
var order_length = res.data.data;
that.setData({
order_length: order_length
})
that.onShow_shop();
}
})
that.show_card();
},
onShow_shop: function() {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/getShopCartNum`,
data: {
c_user_id: c_user_id
},
header: {},
success: function(res) {
var show_shop = res.data.data;
//console.log(show_shop, 9080808)
that.setData({
show_shop: show_shop
})
}
})
},
/**显示积分、余额 */
show_card:function(){
var that=this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/personCenter`,
data:{
c_user_id: c_user_id
},
header:{},
success:function(res){
//console.log(res.data.data,8888);
var person_card=res.data.data;
var card_nums=''
if (person_card.c_user_vip){
card_nums='1'
}
var shopNull = 0;
if (!person_card.c_user_vip) {
shopNull = 1;
}
that.setData({
person_card: person_card,
card_nums: card_nums,
shopNull: shopNull
})
}
})
},
/**跳转优惠券 */
my_coupon:function(e){
wx.navigateTo({
url: '../my_coupon/my_coupon',
})
},
/**跳转余额 */
member:function(e){
wx.navigateTo({
url: '../member/member?type=0',
})
},
/**积分跳转 */
my_integral:function(e){
wx.navigateTo({
url: '../my_integral/my_integral',
})
},
/**跳转购物车 */
person_other: function(e) {
var url = e.currentTarget.dataset.url;
var id = e.currentTarget.dataset.id;
var c_user_id = this.data.c_user_id;
if(id==0){
wx.switchTab({
url: url
})
}else if(id==1){
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getDistributor`,
data: {
c_user_id: c_user_id
},
header: {},
success: function (res) {
console.log(res.data.data, 767678);
if (res.data.data){
url = '../fenxiao/fenxiao'
}
console.log(url, 89898)
wx.navigateTo({
url: url
})
}
});
}else{
wx.navigateTo({
url: url
})
}
},
/**会员卡 */
person_important: function() {
var that = this
var c_user_id = (wx.getStorageSync('c_user_id'));
// console.log(c_user_id, 7777777)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/vip/checkVip`,
data: {
c_user_id: c_user_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
// console.log(res.data.data,8888);
if (!res.data.data) {
wx.navigateTo({
url: '../person_important/person_important',
})
} else {
wx.navigateTo({
url: '../vip_details/vip_details',
})
}
}
})
},
/**跳转订单列表 */
my_order_list: function(e) {
var status = e.currentTarget.dataset.status
//console.log(status, 9087)
wx.navigateTo({
url: '../order_list/order_list?status=' + status,
})
},
/**账号设置跳转 */
my_account: function() {
wx.navigateTo({
url: '../my_account/my_account',
})
},
/**查看全部订单 */
all_order_list: function(e) {
var status = e.currentTarget.dataset.status;
if (status == 9) {
status = ''
}
wx.navigateTo({
url: '../order_list/order_list?status=' + status,
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
})<file_sep>var WxParse = require('../../wxParse/wxParse.js');
var util = require('../../utils/util.js');
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
head: "../../images/logo.png",
search: "../../images/img/search.png",
imgUrls: [
'http://wmdx.vimi66.com:8010/img-video/upload/img//20181105162846023648.jpg'
],
indicatorDots: true,
autoplay: true,
myinterval: 3000,
duration: 1000,
isClick: false,
no_select: '../../images/xinxin_white.png',
xinxin_select: '../../images/xinxin_full.png',
wall: "../../images/img/wall.png",
corner: "../../images/img/corner.png",
right: "../../images/img/right.png",
msg: "../../images/img/msg.png",
car: "../../images/img/car.png",
gift: "../../images/img/gift.png",
star: "../../images/img/star.png",
dianzan: "../../images/img/dianzan.png",
_num: 1,
_praise: 9,
productlist: [],
store_pop: false,
count: 1,
coupon: false,
zhuan:0,
dis_id:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//console.log(options.my_distributor_id,34343434)
if (options.my_distributor_id){
getApp().globalData.distributor_id = options.my_distributor_id
this.setData({
commerce_id: options.url
})
}else{
this.setData({
commerce_id: options.url
})
}
var that=this;
if (options.scene) {
let scene = decodeURIComponent(options.scene);
//&是我们定义的参数链接方式
let distributor_id = scene.split("&")[0];
//console.log(distributor_id, 11111);
distributor_id = distributor_id.split("=")[1];
that.setData({
dis_id: distributor_id
})
//`${getApp().globalData.distributor_id}`
//其他逻辑处理。。。。。
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
var dis_id=that.data.dis_id;
if (dis_id){
wx.request({
url: getApp().globalData.baseUrl + '/wechat/qr/readQr',
data: {
dis_id: dis_id
},
header: {
'content-type': 'application/json' // 默认值
},
async: false,
success: function (res) {
//console.log(res.data.data, 55555);
var distributor = res.data.data;
getApp().globalData.distributor_id = distributor.distributor_id
// that.setData({
// commerce_id: distributor.commer_id
// });
var commerce_id = distributor.commer_id;
//console.log(commerce_id, 9901201)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getCommerceDetail`,
data: {
commerce_id: commerce_id,
c_user_id: c_user_id
},
header: {},
success: function (res) {
var shop_details = res.data.data;
var commerce_details = shop_details.commerce_details;
if (commerce_details) {
WxParse.wxParse('article', 'html', commerce_details, that, 5);
}
//console.log(shop_details, 99999);
var reserved1 = shop_details.reserved1;
var isClick = that.data.isClick
if (reserved1 == '1') {
isClick = true;
}
var my_distributor_id = getApp().globalData.my_distributor_id;
//console.log(my_distributor_id, 8909);
var zhuan = 0
if (my_distributor_id) {
zhuan = 1
}
that.setData({
shop_details: shop_details,
commerce_details: commerce_details,
isClick: isClick,
zhuan: zhuan
})
}
})
}
});
}else{
var commerce_id = that.data.commerce_id;
//console.log(commerce_id, 9901201)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getCommerceDetail`,
data: {
commerce_id: commerce_id,
c_user_id: c_user_id
},
header: {},
success: function (res) {
var shop_details = res.data.data;
var commerce_details = shop_details.commerce_details;
if (commerce_details) {
WxParse.wxParse('article', 'html', commerce_details, that, 5);
}
//console.log(shop_details, 99999);
var reserved1 = shop_details.reserved1;
var isClick = that.data.isClick
if (reserved1 == '1') {
isClick = true;
}
var my_distributor_id = getApp().globalData.my_distributor_id;
//console.log(my_distributor_id, 8909);
var zhuan = 0
if (my_distributor_id) {
zhuan = 1
}
that.setData({
shop_details: shop_details,
commerce_details: commerce_details,
isClick: isClick,
zhuan: zhuan
})
}
})
}
that.same_shop()
that.show_coupon()
that.min_coupon()
},
/**优惠券显示 */
min_coupon: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/coupons/getMinCouspons`,
data: {
c_user_id: c_user_id,
},
header: {},
success: function (res) {
//console.log(res.data.data, 8765432)
var min_coupon = res.data.data;
var show_coupon = 0;
if (min_coupon) {
show_coupon = 1;
}
that.setData({
min_coupon: min_coupon,
show_coupon: show_coupon
})
//console.log(show_coupon, 6666)
}
})
},
my_home:function(){
wx.switchTab({
url: '../home/home',
})
},
/**优惠券 */
show_coupon: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/coupons/getAllCouponsList`,
data: {
c_user_id: c_user_id,
},
header: {},
success: function (res) {
var coupon_list = res.data.data;
//console.log(coupon_list, 9080)
that.setData({
coupon_list: coupon_list
})
}
})
},
/**我的分销员中心 */
fenxiao: function (e) {
wx.navigateTo({
url: '../fenxiao/fenxiao',
})
},
/**优惠券领取 */
my_coupon: function (e) {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
var coupons_id = e.currentTarget.dataset.coupons_id;
var index = e.currentTarget.dataset.index;
var coupon_list = that.data.coupon_list;
coupon_list[index].lq_status = 1;
that.setData({
coupons_id: coupons_id,
coupon_list: coupon_list
})
//console.log(coupons_id, 9999)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/coupons/addCoupons`,
data: {
c_user_id: c_user_id,
coupons_id: coupons_id
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
}
})
},
/**优惠券完成 */
coupon_end:function(e){
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
coupon: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
// 商品详情切换
clickNum: function (e) {
var comment_type = e.target.dataset.num
//console.log(e.target.dataset.num)
this.setData({
_num: comment_type
})
if (comment_type == 2) {
this.comment_num();
this.show_Comment();
}
},
/**加商品 */
addtap: function () {
var that = this;
that.setData({
count: ++that.data.count
})
},
subtracttap: function () {
var that = this;
var count = that.data.count
if (count > 1) {
count--
}
that.setData({
count: count
})
},
/**立即购买 */
buy_now: function (e) {
var count = e.currentTarget.dataset.count;
var id = e.currentTarget.dataset.id
var that = this;
var store_pop = that.data.store_pop;
var commerce_id = e.currentTarget.dataset.id;
if (!store_pop) {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
store_pop: true
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getCommerceDetail`,
data: {
commerce_id: commerce_id
},
header: {},
success: function (res) {
//console.log(res.data.data, 787878);
var store_pop = res.data.data;
that.setData({
store_pop: store_pop
})
}
})
} else {
wx.navigateTo({
url: '../create_order/create_order?count=' + count + '&id=' + id,
})
}
},
/**弹出层 */
gouwu_pop: function (e) {
var that = this;
var store_pop = that.data.store_pop;
var commerce_id = e.currentTarget.dataset.id;
if (!store_pop) {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
store_pop: true
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getCommerceDetail`,
data: {
commerce_id: commerce_id
},
header: {},
success: function (res) {
//console.log(res.data.data, 787878);
var store_pop = res.data.data;
that.setData({
store_pop: store_pop
})
}
})
} else {
var comm_num = e.currentTarget.dataset.count;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/addShopToCart`,
data: {
comm_num: comm_num,
c_user_id: that.data.c_user_id,
commodity_id: commerce_id
},
header: {},
success: function (res) {
wx.showToast({
title: '加入购物车成功',
})
}
})
}
},
/**优惠券 */
coupon: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
coupon: true
})
},
closecoupon: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
coupon: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
preventTouchMove: function () {
},
close_gouwu: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
store_pop: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
/**添加购物车 */
my_add: function (e) {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
var comm_num = e.currentTarget.dataset.count;
var commodity_id = e.currentTarget.dataset.id
//console.log(commodity_id, 1111)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/addShopToCart`,
data: {
comm_num: comm_num,
c_user_id: c_user_id,
commodity_id: commodity_id
},
header: {},
success: function (res) {
wx.showToast({
title: '加入购物车成功',
})
}
})
},
/**购物车 */
gouwu: function () {
wx.switchTab({
url: '../shop_cart/shop_cart',
})
},
/**评价接口 */
show_Comment: function () {
var that = this;
var commerce_id = that.data.commerce_id;
var rank = that.data._praise;
if (rank == 9) {
rank = '';
}
//console.log(rank, 7766)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/evaluate/getEvaluateList`,
data: {
commerce_id: commerce_id,
rank: rank
},
header: {},
success: function (res) {
var new_all_comment = res.data.data;
//console.log(new_all_comment, 989898)
for (var i = 0; i < new_all_comment.length; i++) {
var all_comment = new_all_comment[i]["create_time"];
new_all_comment[i]["create_time"] = util.formatTime(new Date(all_comment))
}
var my_choose = 0;
if (!new_all_comment || new_all_comment.length == 0) {
my_choose = 1;
}
that.setData({
all_comment: new_all_comment,
my_choose: my_choose
})
}
})
},
/**评价数量接口 */
comment_num: function () {
var that = this;
var commerce_id = that.data.commerce_id;
// var rank = that.data._praise;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/evaluate/getEvaluateNum`,
data: {
commerce_id: commerce_id
},
header: {},
success: function (res) {
var comment_num = res.data.data;
//console.log(comment_num, 7878)
that.setData({
comment_num: comment_num
})
}
})
},
clickPraise: function (e) {
//console.log(e.target.dataset.praise, 99999)
this.setData({
_praise: e.target.dataset.praise
})
this.show_Comment();
},
/**喜欢收藏 */
haveSave(e) {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
this.setData({
isClick: !this.data.isClick
})
var commerce_id = e.currentTarget.dataset.commerce_id
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/cranlCollection`,
data: {
c_user_id: c_user_id,
commerce_id: commerce_id
},
header: {},
success: function (res) {
}
})
},
/**同类型推荐商品 */
same_shop: function () {
var that = this;
var commerce_id = that.data.commerce_id;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getSameTypeCommerce`,
data: {
commerce_id: commerce_id
},
header: {
},
success: function (res) {
var productlist = res.data.data;
that.setData({
productlist: productlist
})
}
})
},
home:function(e){
wx.switchTab({
url: '../home/home',
})
},
/**推荐商品跳转详情 */
// jx_shop: function (e) {
// var commerce_id = e.currentTarget.dataset.commerce_id;
// wx.redirectTo({
// url: '../shop_details/shop_details?url=' + commerce_id,
// })
// wx.showLoading({
// title: '加载中...',
// })
// setTimeout(function () {
// wx.hideLoading()
// }, 2000)
// },
zhuan: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
zhuan_info: true
})
},
close_zhuan: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
zhuan_info: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
my_code: function (e) {
this.setData({
zhuan_info: false,
code_info: true
})
var that = this;
var commerce_id = e.currentTarget.dataset.id
//console.log(commerce_id, 976);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/qr/getEwm`,
header: {
'content-type': 'application/json'
},
data: {
commer_id:commerce_id,
page: 'pages/shop_details/shop_details',
distributor_id: getApp().globalData.my_distributor_id
},
success: function (res) {
wx.hideLoading();
var path = res.data.data;
//console.log(res.data.data, 99999)
that.setData({
my_path: path
})
}
})
},
close_code: function () {
this.setData({
code_info: false
})
},
//点击开始的时间
timestart: function (e) {
var _this = this;
_this.setData({ timestart: e.timeStamp });
},
//点击结束的时间
timeend: function (e) {
var _this = this;
_this.setData({ timeend: e.timeStamp });
},
//保存图片
saveImg: function (e) {
var that = this;
var times = that.data.timeend - that.data.timestart;
if (times > 300) {
//console.log("长按");
wx.getSetting({
success: function (res) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: function (res) {
//console.log("授权成功");
var imgUrl = that.data.my_path.path;
wx.downloadFile({//下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径
url: imgUrl,
success: function (res) {
// 下载成功后再保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,//返回的临时文件路径,下载后的文件会存储到一个临时文件
success: function (res) {
wx.showToast({
title: '成功保存到相册',
icon: 'success'
})
}
})
}
})
}
})
}
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function (ops) {
if (ops.from === 'button') {
// 来自页面内转发按钮
//console.log(ops.target)
}
var that=this
var my_distributor_id = getApp().globalData.my_distributor_id
//console.log(my_distributor_id,1111111)
var aa = that.data.commerce_id
return {
title: 'GL好肌友皮肤管理',
path: 'pages/shop_details/shop_details?my_distributor_id=' + my_distributor_id + '&url=' + aa, //点击分享的图片进到哪一个页面
success: function (res) {
// 转发成功
//console.log("转发成功:" + JSON.stringify(res));
},
fail: function (res) {
// 转发失败
//console.log("转发失败:" + JSON.stringify(res));
}
}
}
})<file_sep>Page({
/**
* 页面的初始数据
*/
data: {
swiper_tab_infor:[],
current: 0,
currentTab: 0,
cartData: {},
index: 0,
type_id: null,
tipsshow: "",
windows_out: false, //弹出层
shop_lists: [],
select_shop: [],
minusStatus: 'display',
inforHasMore: 1,
inforPage: 1,
zhuan:0
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//console.log(options.my_distributor_id,5555555555)
if (options.my_distributor_id) {
getApp().globalData.distributor_id = options.my_distributor_id
}
if (options.scene) {
let scene = decodeURIComponent(options.scene);
//&是我们定义的参数链接方式
let distributor_id = scene.split("&")[0];
//console.log(distributor_id, 11111);
distributor_id = distributor_id.split("=")[1];
wx.request({
url: getApp().globalData.baseUrl+'/wechat/qr/readQr',
data:{
dis_id: distributor_id
},
header:{},
success:function(res){
//console.log(res.data.data,55555);
var distributor=res.data.data;
getApp().globalData.distributor_id = distributor.distributor_id
}
});
//`${getApp().globalData.distributor_id}`
//其他逻辑处理。。。。。
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
that.show_type();
//that.show_store();
},
/**获取所有商品类型 */
show_type:function(){
var that=this;
if(!that.data.type_id){
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commodity/getAllCommodityType`,
data: {},
header: {},
success: function (res) {
var new_swiper_tab_infor = []
var newswiper_tab_infor = res.data.data;
var type_id = newswiper_tab_infor[0].type_id;
for (var i = 0; i < newswiper_tab_infor.length; i++) {
new_swiper_tab_infor.push(newswiper_tab_infor[i])
}
var my_distributor_id = getApp().globalData.my_distributor_id;
//console.log(my_distributor_id, 8909);
var zhuan = 0
if (my_distributor_id) {
zhuan = 1
}
that.setData({
swiper_tab_infor: new_swiper_tab_infor,
type_id: type_id,
zhuan: zhuan
})
that.show_store();
}
})
}else{
that.show_store();
}
},
/**获取类型中所有商品 */
show_store:function(){
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getAllCommerce`,
data:{
commerce_type: that.data.type_id,
c_user_id: c_user_id,
page: 1,
rows: 10
},
header:{
},
success:function(res){
if (res.data.code = 200) {
var shop_lists = [];
var new_shop_lists = res.data.data;
for (var i = 0; i < new_shop_lists.length; i++) {
shop_lists.push(new_shop_lists[i])
}
var is_show = 1
if (!shop_lists || shop_lists.length == 0) {
is_show = 0
}
that.setData({
shop_lists: shop_lists,
is_show: is_show
})
if (res.data.data.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: 2
})
}
} else {
that.setData({
shop_lists: [],
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log('查询失败');
}
})
},
//类型列表底色切换
swichNav: function (e) {
// console.log('swichNav')
var that = this;
var index = e.currentTarget.dataset.index;
var type_id = e.currentTarget.dataset.id;
if (that.data.current === e.currentTarget.dataset.current) {
return false;
} else {
that.setData({
currentTab: index,
type_id: type_id
})
//console.log(type_id,212121)
that.show_store();
}
},
/**我的分销员中心 */
fenxiao: function (e) {
wx.navigateTo({
url: '../fenxiao/fenxiao',
})
},
/**分页加载 */
loadingMore: function () {
//console.log(88888888)
var that = this;
var current = that.data.current;
var inforHasMore = that.data.inforHasMore;
if (inforHasMore == 1) {
wx.showLoading({
title: '正在加载',
})
var pa_shop_lists = that.data.shop_lists;
var inforPage = that.data.inforPage;
console.log(inforPage, 9999);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commodity/getAllCommerce`,
data: {
commerce_type: that.data.type_id,
c_user_id: that.data.c_user_id,
page: inforPage,
rows: 10
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
wx.hideLoading();
if (res.data.code = 200) {
var shop_lists = [];
var new_shop_lists = pa_shop_lists.concat(res.data.data);
for (var i = 0; i < new_shop_lists.length; i++) {
shop_lists.push(new_shop_lists[i])
}
that.setData({
shop_lists: shop_lists
});
console.log(res.data.data, 555);
if (res.data.data.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: ++inforPage
})
}
} else {
that.setData({
shop_lists: pa_shop_lists,
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log("加载失败")
},
complete: function (res) {
console.log("加载完成")
}
})
}
},
store_details:function(e){
var aa = e.currentTarget.dataset.commodity_id
//console.log(aa,3333)
wx.navigateTo({
url: '../shop_details/shop_details?url='+aa,
})
},
preventTouchMove: function () {
},
close_gouwu: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
store_pop: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
/**立即购买 */
buy_now: function (e) {
},
zhuan: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
zhuan_info: true
})
},
close_zhuan: function () {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
zhuan_info: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
my_code: function () {
this.setData({
zhuan_info: false,
code_info: true
})
var that = this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/qr/getEwm`,
header: {
'content-type': 'application/json'
},
data: {
commer_id:1,
page: 'pages/store_list/store_list',
distributor_id: getApp().globalData.my_distributor_id
},
success: function (res) {
wx.hideLoading();
var path = res.data.data;
//console.log(res.data.data, 99999)
that.setData({
my_path: path
})
}
})
},
close_code: function () {
this.setData({
code_info: false
})
},
//点击开始的时间
timestart: function (e) {
var _this = this;
_this.setData({ timestart: e.timeStamp });
},
//点击结束的时间
timeend: function (e) {
var _this = this;
_this.setData({ timeend: e.timeStamp });
},
//保存图片
saveImg: function (e) {
var that = this;
var times = that.data.timeend - that.data.timestart;
if (times > 300) {
//console.log("长按");
wx.getSetting({
success: function (res) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: function (res) {
//console.log("授权成功");
var imgUrl = that.data.my_path.path;
wx.downloadFile({//下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径
url: imgUrl,
success: function (res) {
// 下载成功后再保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,//返回的临时文件路径,下载后的文件会存储到一个临时文件
success: function (res) {
wx.showToast({
title: '成功保存到相册',
icon: 'success'
})
}
})
}
})
}
})
}
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function (ops) {
if (ops.from === 'button') {
// 来自页面内转发按钮
//console.log(ops.target)
}
var my_distributor_id = getApp().globalData.my_distributor_id
//console.log(my_distributor_id,343434)
return {
title: 'GL好肌友皮肤管理',
path: `pages/store_list/store_list?my_distributor_id=` + my_distributor_id, //点击分享的图片进到哪一个页面
success: function (res) {
// 转发成功
//console.log("转发成功:" + JSON.stringify(res));
},
fail: function (res) {
// 转发失败
//console.log("转发失败:" + JSON.stringify(res));
}
}
}
})<file_sep>// pages/my_extend/my_extend.js
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
my_extend:[
{
number:'E2018112914345200'
},
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if (options.status){
this.setData({
id: options.url,
status: options.status
})
}else{
this.setData({
id: options.url,
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
qguang:function(){
wx.switchTab({
url: '../store_list/store_list',
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
var status=that.data.status;
if (!status){
status='';
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getAllOrders`,
data:{
id:that.data.id,
status: status
},
header:{},
success:function(res){
var new_my_extend=res.data.data;
console.log(new_my_extend,666)
var shopNull=0
if (!new_my_extend || new_my_extend.length==0){
shopNull=1
}
//var commodity_infoList = new_my_extend.t_order.commodity_infoList
for (var i = 0; i < new_my_extend.length; i++) {
var my_extend = new_my_extend[i]["create_time"]
new_my_extend[i]["create_time"] = util.formatTime(new Date(my_extend));
}
that.setData({
my_extend: new_my_extend,
shopNull: shopNull
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>const app = getApp()
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
data:{
zhuan_info: false,
code_info:false
},
})<file_sep>// pages/my_fenxiao/my_fenxiao.js
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
id:options.url
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
console.log(that.data.id,21212)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getMyFans`,
data:{
id:that.data.id
},
header:{},
success:function(res){
var new_my_fans=res.data.data
console.log(new_my_fans,9999)
var shopNull=0
if (!new_my_fans || new_my_fans.length==0){
shopNull=1
}
for (var i = 0; i < new_my_fans.length; i++) {
var my_fans = new_my_fans[i]["create_time"]
new_my_fans[i]["create_time"] = util.formatTime(new Date(my_fans));
}
that.setData({
my_fans: new_my_fans,
shopNull: shopNull
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>Page({
data: {
num:1,
upd1:'../../images/img/upd1.png',
upd2: '../../images/img/upd2.png',
selectArea:false
},
clickList: function (e) {
var that=this;
console.log(e.target.dataset.num)
if (e.target.dataset.num==4){
that.setData({
selectArea: !that.data.selectArea
})
}
this.setData({
num: e.target.dataset.num,
})
},
})<file_sep>Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/getUserInfo`,
data:{
c_user_id: c_user_id
},
header:{},
success:function(res){
var c_user_info = res.data.data.c_user_info;
var c_user_vip = c_user_info.c_user_vip
console.log(c_user_info,66665);
var no_vip=1
if (!c_user_vip){
no_vip=0
}
that.setData({
c_user_vip: c_user_vip,
c_user_info: c_user_info,
no_vip: no_vip
})
}
})
},
/**跳转我的地址 */
my_address:function(){
wx.navigateTo({
url: '../my_address/my_address',
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
playIndex: null,//用于记录当前播放的视频的索引值
courseList: [{
duration: '你好年后', //视频时长
}],
cover_close: true, //弹出层
discover:'0',
// hidden:true
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
translate_id: options.url,
})
wx.showLoading({
title: '加载中...',
})
},
/**跳转留言页面 */
leave_text:function(e){
var aa = e.currentTarget.dataset.id;
// console.log(aa,65656565)
var reserved1 = e.currentTarget.dataset.reserved1;
console.log(reserved1, 65656565)
if (reserved1==0){
wx.showModal({
title: '提示',
content: '购买后才能写留言哟~',
})
}else{
wx.navigateTo({
url: '../video_leave/video_leave?url=' + aa,
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
//var that=this;
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getTranslateDetail`,
data: {
translate_id: that.data.translate_id,
c_user_id: c_user_id
},
header: {
},
success: function (res) {
wx.hideLoading()
var new_courseList = res.data.data;
console.log(new_courseList, 999999);
new_courseList.create_time = util.formatTime(new Date(new_courseList.create_time));
var discover = new_courseList.reserved1
if (discover == 1) {
that.setData({
cover_close: false
})
}
that.setData({
courseList: new_courseList,
discover: discover
})
}
})
},
/**遮罩层 */
preventTouchMove: function () {
},
cover_video: function () {
},
videoPlay: function (e) {
var curIdx = e.currentTarget.dataset.index;
console.log(curIdx,8888)
// 没有播放时播放视频
if (!this.data.playIndex) {
this.setData({
playIndex: curIdx
})
var videoContext = wx.createVideoContext('video' + curIdx) //这里对应的视频id
videoContext.play()
} else { // 有播放时先将prev暂停,再播放当前点击的current
var videoContextPrev = wx.createVideoContext('video' + this.data.playIndex)
if (this.data.playIndex != curIdx) {
videoContextPrev.pause()
}
this.setData({
playIndex: curIdx
})
var videoContextCurrent = wx.createVideoContext('video' + curIdx)
videoContextCurrent.play()
}
},
/**购买视频跳转 */
video_pay:function(e){
var aa=e.currentTarget.dataset.id;
console.log(aa,777)
wx.navigateTo({
url: '../video_pay/video_pay?url='+aa,
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/my_integral_list/my_integral_list.js
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
inforHasMore: 1,
inforPage: 1
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
});
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/vip/getInteRecordList`,
data: {
c_user_id: c_user_id,
page:1,
rows: 10
},
header: {},
success: function (res) {
if (res.data.code = 200){
var my_integral = res.data.data;
var new_recordList = my_integral.recordList
console.log(my_integral, 87678);
for (var i = 0; i < new_recordList.length;i++){
var recordList = new_recordList[i]["create_time"];
new_recordList[i]["create_time"] = util.formatTime(new Date(recordList))
}
that.setData({
my_integral: my_integral,
recordList: new_recordList,
})
if (res.data.data.recordList.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: 2
})
}
}else{
that.setData({
recordList: [],
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log('查询失败');
}
})
},
/**分页加载 */
loadingMore: function () {
//console.log(88888888)
var that = this;
var inforHasMore = that.data.inforHasMore;
if (inforHasMore == 1) {
wx.showLoading({
title: '正在加载',
})
var pa_recordList = that.data.recordList;
var inforPage = that.data.inforPage;
console.log(pa_recordList, 9999);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/vip/getInteRecordList`,
data: {
c_user_id: that.data.c_user_id,
page: inforPage,
rows:10
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
wx.hideLoading();
if (res.data.code = 200) {
var recordList = [];
var new_recordList = pa_recordList.concat(res.data.data.recordList);
for (var i = 0; i < new_recordList.length; i++) {
recordList.push(new_recordList[i])
}
that.setData({
recordList: recordList
});
//console.log(res.data.data.recordList, 555);
if (res.data.data.recordList.length < 10) {
that.setData({
inforHasMore: 0
})
} else {
that.setData({
inforPage: ++inforPage
})
}
} else {
that.setData({
recordList: pa_recordList,
inforHasMore: 0,
});
}
},
fail: function (res) {
console.log("加载失败")
},
complete: function (res) {
console.log("加载完成")
}
})
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>// pages/no_fenxiao/no_fenxiao.js
Page({
/**
* 页面的初始数据
*/
data: {
fenxiao_pop: false,
disabled: false,
phone_code: '获取验证码',
parent_id:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
if (options.scene) {
let scene = decodeURIComponent(options.scene);
//&是我们定义的参数链接方式
let distributor_id = scene.split("&")[0];
console.log(distributor_id, 11111);
distributor_id=distributor_id.split("=")[1];
getApp().globalData.distributor_id = distributor_id;
//`${getApp().globalData.distributor_id}`
this.setData({
parent_id: distributor_id
})
//其他逻辑处理。。。。。
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getDistributor`,
data: {
c_user_id: c_user_id
},
header: {},
success: function (res) {
console.log(res.data.data, 767678);
if (res.data.data) {
wx.redirectTo({
url: '../fenxiao/fenxiao'
})
}
}
});
},
phone_num: function(e) {
var value = e.detail.value;
console.log(value, 666);
this.setData({
phone: value
})
},
name_text: function(e) {
var value = e.detail.value;
console.log(value, 777);
this.setData({
name: value
})
},
code_num: function(e) {
var value = e.detail.value;
console.log(value, 777);
this.setData({
code: value
})
},
/**获取验证码 */
get_num: function(e) {
var that = this;
var phone = that.data.phone;
if (!phone) {
wx.showModal({
title: '提示',
content: '请填写手机号',
showCancel: false
})
return false;
}
var time = 60;
that.setData({
phone_code: '60秒后重发',
disabled: true
})
var Interval = setInterval(function() {
time--;
if (time > 0) {
that.setData({
phone_code: time + '秒后重发'
})
} else {
clearInterval(Interval);
that.setData({
phone_code: '获取验证码',
disabled: false
})
}
}, 1000)
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/getVerificationCode`,
data: {
'phone': phone,
},
header: {},
success: function(res) {
console.log(res.data, 9898);
if (res.data.code == 200) {
} else if (res.data.code == 201) {
wx.showModal({
title: '提示',
content: '该手机号已被注册',
showCancel: false
})
}
}
})
},
/**打开弹框 */
be_fenxiao: function(e) {
this.setData({
fenxiao_pop: true
})
},
fx_cancle: function() {
this.setData({
fenxiao_pop: false
})
},
/**提交注册信息 */
be_sure: function(e) {
var that = this
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
var name = that.data.name
var phone = that.data.phone
var code = that.data.code
if (name.length>10){
wx.showModal({
title: '提示',
content: '名字必须十位以内哟~',
})
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/distributor/saveDistributor`,
data: {
name: name,
phone: phone,
code: code,
c_user_id: c_user_id,
parent_id: that.data.parent_id
},
header: {},
success: function(res) {
if (res.data.code == 200) {
var dis_id=res.data.data;
console.log(dis_id,89989);
getApp().globalData.my_distributor_id=dis_id;
wx.redirectTo({
url: '../fenxiao/fenxiao',
})
} else if (res.data.code == 201) {
wx.showModal({
title: '提示',
content: '验证码错误',
})
} else if (res.data.code == 202) {
wx.showModal({
title: '提示',
content: '验证码过期',
})
}
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
})<file_sep>var util = require('../../utils/util.js');
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
rollUrls: [
'营业时间:9:00 - 22:00',
'服务电话:400-8998-8898',
'配送条件:1元起送 配送费6元'
],
roll_indicatorDots: false,
roll_interval: 3000,
indicatorDots: true,
autoplay: true,
myinterval: 3000,
duration: 1000,
imgsUrl: [], //轮播
store_digest: [],
store_list: [],
video_list: [],
person_info: false,
no_refuse:false,
refuse:true,
zhuan_info: false,
code_info: false,
zhuan:0
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
if (options.my_distributor_id){
getApp().globalData.distributor_id = options.my_distributor_id
}
//console.log(options.my_distributor_id,6666666)
if (options.scene) {
let scene = decodeURIComponent(options.scene);
//&是我们定义的参数链接方式
let distributor_id = scene.split("&")[0];
//console.log(distributor_id, 11111);
distributor_id = distributor_id.split("=")[1];
wx.request({
url: getApp().globalData.baseUrl + '/wechat/qr/readQr',
data: {
dis_id: distributor_id
},
header: {},
success: function (res) {
//console.log(res.data.data, 55555);
var distributor = res.data.data;
getApp().globalData.distributor_id = distributor.distributor_id
}
});
//`${getApp().globalData.distributor_id}`
//其他逻辑处理。。。。。
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
onShow_img: function() {
var that = this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commodity/getAdver`,
data: {
},
header: {
},
success: function(res) {
var imgUrl = res.data.data;
// console.log(imgUrl, 999999);
that.setData({
imgsUrl: imgUrl
})
}
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id,
})
wx.getUserInfo({
withCredentials: true, //此处设为true,才会返回encryptedData等敏感信息
success: function (res) {
that.setData({
userInfo: res.userInfo,
person_info: false
})
},
fail: function (res) {
that.setData({
person_info: true
})
}
})
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getRecommendComm`,
data: {},
header: {},
success: function(res) {
var store_list = res.data.data;
//console.log(store_list,7676766)
var my_distributor_id = getApp().globalData.my_distributor_id;
//console.log(my_distributor_id, 8909);
var zhuan = 0
if (my_distributor_id) {
zhuan = 1
}
that.setData({
store_list: store_list,
zhuan: zhuan
})
}
})
that.onShow_img();
that.show_run();
that.show_typeone();
that.show_top();
},
/**页面公告 */
show_run: function() {
var that = this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/loadNotice`,
data: {},
header: {},
success: function(res) {
var rollUrls = res.data.data;
//console.log(rollUrls,888899)
var top_roll_show = 1;
if (rollUrls && rollUrls.length>0) {
top_roll_show = 0
}
// console.log(top_roll,6666)
that.setData({
rollUrls: rollUrls,
top_roll_show: top_roll_show
})
}
})
},
getUserInfo: function () {
var that = this;
var c_user_id = (wx.getStorageSync('c_user_id'));
that.setData({
c_user_id: c_user_id
})
wx.getUserInfo({
withCredentials: true, //此处设为true,才会返回encryptedData等敏感信息
success: function (res) {
//console.log(res.userInfo, 999999)
var sex = 'F'
if (res.userInfo.gender == 0) {
sex = "M"
} else {
sex = "F"
}
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/user/updateUser`,
data: {
c_user_id: c_user_id,
user_name: res.userInfo.nickName,
sex: sex,
avatar: res.userInfo.avatarUrl
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
//console.log(res.data,89989);
}
})
that.setData({
userInfo: res.userInfo,
my_person: 0,
person_info:false
})
},
fail: function (res) {
that.setData({
my_person: 1
})
}
})
},
preventTouchMove: function () {
},
/**授权弹出框 */
refuse: function () {
this.setData({
refuse: !this.data.refuse,
no_refuse: !this.data.no_refuse
})
},
/**跳转商品详情 */
shop_details: function (e) {
var aa = e.currentTarget.dataset.id
wx.navigateTo({
url: '../shop_details/shop_details?url=' + aa,
})
},
/**我的分销员中心 */
fenxiao:function(e){
wx.navigateTo({
url: '../fenxiao/fenxiao',
})
},
/**第一行类型跳转 */
store_typeone: function (e) {
var index = e.currentTarget.dataset.index;
var type_id = e.currentTarget.dataset.type_id
wx.navigateTo({
url: '../drawbook/drawbook?url=' + type_id
})
},
/**总类别列表第一行 */
show_typeone: function () {
var that = this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commodity/getCommodityType`,
data: {},
header: {},
success: function (res) {
var all_type = res.data.data
//console.log(all_type, 888)
that.setData({
all_type: all_type
})
}
})
},
/**推荐商品 */
show_top: function () {
var that = this;
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/commerce/getThreeRecommendCommerceList`,
data: {},
header: {},
success: function (res) {
var all_recommend = res.data.data;
//console.log(all_recommend, 7778)
var recommend_one = []
recommend_one.push(all_recommend[0])
var recommend_two = []
recommend_two.push(all_recommend[1])
var recommend_three = []
recommend_three.push(all_recommend[2])
//console.log()
that.setData({
recommend_first: recommend_one,
recommend_second: recommend_two,
recommend_third: recommend_three
})
}
})
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
zhuan:function() {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export()
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
zhuan_info: true
})
},
close_zhuan: function() {
var animation = wx.createAnimation({
duration: 200,
timingFunction: "linear",
delay: 0
})
this.animation = animation
animation.translateY(300).step()
setTimeout(function () {
animation.translateY(0).step()
this.setData({
animationData: animation.export(),
zhuan_info: false
})
}.bind(this), 200)
this.setData({
animationData: animation.export(),
})
},
my_code: function() {
this.setData({
zhuan_info: false,
code_info: true
})
var that = this;
//var distributor_id = that.data.id
var scene = decodeURIComponent("dis_id=" + getApp().globalData.my_distributor_id);
//console.log(scene, 976);
wx.request({
url: `${getApp().globalData.baseUrl}/wechat/qr/getEwm`,
header: {
'content-type': 'application/json'
},
data: {
commer_id:0,
page: 'pages/home/home',
distributor_id: getApp().globalData.my_distributor_id
},
success: function (res) {
wx.hideLoading();
var path = res.data.data;
//console.log(res.data.data, 99999)
that.setData({
my_path: path
})
}
})
},
close_code: function() {
this.setData({
code_info: false
})
},
//点击开始的时间
timestart: function (e) {
var _this = this;
_this.setData({ timestart: e.timeStamp });
},
//点击结束的时间
timeend: function (e) {
var _this = this;
_this.setData({ timeend: e.timeStamp });
},
//保存图片
saveImg: function (e) {
var that = this;
var times = that.data.timeend - that.data.timestart;
if (times > 300) {
//console.log("长按");
wx.getSetting({
success: function (res) {
wx.authorize({
scope: 'scope.writePhotosAlbum',
success: function (res) {
//console.log("授权成功");
var imgUrl = that.data.my_path.path;
wx.downloadFile({//下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径
url: imgUrl,
success: function (res) {
// 下载成功后再保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,//返回的临时文件路径,下载后的文件会存储到一个临时文件
success: function (res) {
wx.showToast({
title: '成功保存到相册',
icon: 'success'
})
}
})
}
})
}
})
}
})
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function(ops) {
if (ops.from === 'button') {
// 来自页面内转发按钮
//console.log(ops.target)
}
var my_distributor_id=getApp().globalData.my_distributor_id
return {
title: 'GL好肌友皮肤管理',
path: `pages/home/home?my_distributor_id=` + my_distributor_id, //点击分享的图片进到哪一个页面
success: function (res) {
// 转发成功
//console.log("转发成功:" + JSON.stringify(res));
},
fail: function (res) {
// 转发失败
//console.log("转发失败:" + JSON.stringify(res));
}
}
}
})
|
33dda5b287d9f37e48ef579f11e7a90cde2e3eeb
|
[
"JavaScript"
] | 21
|
JavaScript
|
MIU0/skin
|
bf8a14a89bf59753309c209ea0c10c6af0cd702a
|
2d5ff35e7ec1fbd02714e92fc2f705104376a70c
|
refs/heads/master
|
<file_sep>sense.kb.addEndpointDescription('_refresh', {
def_method: "GET",
methods: ["GET"],
endpoint_autocomplete: [
"_refresh"
],
indices_mode: "multi"
});
sense.kb.addEndpointDescription('_stats', {
def_method: "GET",
methods: ["GET"],
endpoint_autocomplete: [
"_stats"
],
indices_mode: "multi"
});
sense.kb.addEndpointDescription('_segments', {
def_method: "GET",
methods: ["GET"],
endpoint_autocomplete: [
"_segments"
],
indices_mode: "_segments"
});
|
4d78c5daf90dce294ea27e5adcdfaceac1b0dc83
|
[
"JavaScript"
] | 1
|
JavaScript
|
clintongormley/sense
|
073634a20c66b320affa75169c9f61375b220a7e
|
102b6fd11d774390686815a3c10eb2863a31591f
|
refs/heads/master
|
<file_sep>#ifndef _DEFINES_H_INCLUDED_
#define _DEFINES_H_INCLUDED_
#define NULL ((void *)0)
#define SERIAL_DEFAULT_DEVICE 1
typedef unsigned char uint8;
typedef unsigned short uinit16;
typedef unsigned long uint32;
typedef uint32 kz_thread_id_t;
typedef int (*kz_func_t)(int argc, char *argv[]);
typedef void (*kz_handler_t)(void);
#endif
<file_sep>#ifndef _DEFINES_H_INCLUDED_
#define _DEFINES_H_INCLUDED_
#define NULL ((void *)0)
#define SERIAL_DEFAULT_DEVICE 1
typedef unsigned char uint8;
typedef unsigned short uinit16;
typedef unsigned long unit32;
#endif
<file_sep>#!/usr/bin/bash
WORK=$HOME/dev/12step
BUILD=$WORK/build
SRC=$WORK/src
TOOLS=$WORK/tools
NCORE=`nproc`
TARGET=h8300-elf
if [ -d $WORK ]; then
exit
fi
mkdir -p $WORK && cd $WORK
mkdir -p build src/h8write tools
cd $BUILD
curl -O http://ftp.gnu.org/gnu/binutils/binutils-2.25.tar.gz
curl -O http://ftp.gnu.org/gnu/gmp/gmp-5.1.3.tar.xz
curl -O http://ftp.gnu.org/gnu/mpfr/mpfr-3.1.3.tar.xz
curl -O ftp://ftp.gnu.org/gnu/mpc/mpc-1.0.3.tar.gz
curl -O http://ftp.gnu.org/gnu/gcc/gcc-5.2.0/gcc-5.2.0.tar.bz2
curl -O http://mes.osdn.jp/h8/h8write.c
# binutils
cd $BUILD
tar xzvf binutils-2.25.tar.gz
cd binutils-2.25
./configure --target=$TARGET --disable-nls --prefix=$TOOLS
make -j$NCORE && make check && make install
# gmp
cd $BUILD
tar xJvf gmp-5.1.3.tar.xz
cd gmp-5.1.3
./configure --prefix=$TOOLS/gmp
make -j$NCORE && make check && make install
# mpfr
cd $BUILD
tar xJvf mpfr-3.1.3.tar.xz
cd mpfr-3.1.3
./configure --prefix=$TOOLS/mpfr --with-gmp=$TOOLS/gmp
make -j$NCORE && make check && make install
# mpc
cd $BUILD
tar xzvf mpc-1.0.3.tar.gz
cd mpc-1.0.3
./configure --prefix=$TOOLS/mpc --with-gmp=$TOOLS/gmp --with-mpfr=$TOOLS/mpfr
make -j$NCORE && make check && make install
# gcc
cd $BUILD
tar xjvf gcc-5.2.0.tar.bz2
cd gcc-5.2.0
mkdir $TARGET && cd $TARGET
../configure --target=$TARGET \
--prefix=$TOOLS \
--enable-languages=c \
--disable-nls \
--disable-threads \
--disable-shared \
--disable-libssp \
--with-gmp=$TOOLS/gmp \
--with-mpfr=$TOOLS/mpfr \
--with-mpc=$TOOLS/mpc \
make -j$NCORE && make install
# h8write
cd $BUILD
gcc -Wall -o h8write h8write.c
mv h8write* $SRC/h8write/
cd $WORK
|
6668bb143289a03f4245ca6f79877fa496846aae
|
[
"C",
"Shell"
] | 3
|
C
|
xtanabe/12step
|
ccb609274d91c2be591b9b37dd3d9c7a6361c679
|
32ab5d317786f720a7e4a35242602b0de57b90f1
|
refs/heads/master
|
<file_sep>//----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2016 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#ifndef MBED_CLOUD_CLIENT_USER_CONFIG_H
#define MBED_CLOUD_CLIENT_USER_CONFIG_H
#define MBED_CLOUD_CLIENT_SUPPORT_CLOUD
#define MBED_CLOUD_CLIENT_CLOUD_ADDRESS "identity.mbedcloud.com"
#define MBED_CLOUD_CLIENT_CLOUD_PORT 5683
#define MBED_CLOUD_CLIENT_ENDPOINT_TYPE "default"
#define MBED_CLOUD_CLIENT_TRANSPORT_MODE_TCP
#define MBED_CLOUD_CLIENT_LIFETIME 600
#define MBED_CLOUD_CLIENT_SUPPORT_UPDATE
#define MBED_CLOUD_CLIENT_UPDATE_ID
#define MBED_CLOUD_CLIENT_UPDATE_CERT
#define MBED_CLOUD_CLIENT_UPDATE_BUFFER 2048
#endif /* MBED_CLOUD_CLIENT_USER_CONFIG_H */
<file_sep>unsigned char MBED_ENABLED_LOGO_100X100_96X96_mono_bmp[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xed, 0x68, 0x26, 0x9f, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xff, 0xff,
0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff,
0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff,
0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff,
0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff,
0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff,
0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x07, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xfc, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xfc, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0xf8, 0x3f, 0xe3, 0xc0, 0xf0, 0x08, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0xf8, 0x3f, 0xe1, 0xc0, 0xf0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x01, 0xf8, 0x3c, 0xf3, 0xf1, 0xf0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x01, 0xdc, 0x38, 0x73, 0xf3, 0xf0, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x01, 0xdc, 0x3c, 0xf3, 0xff, 0xf0, 0x00, 0x07, 0xff,
0xff, 0x80, 0x00, 0x03, 0x9e, 0x1f, 0xe1, 0x9f, 0x70, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x03, 0x8e, 0x3f, 0xc3, 0xde, 0x70, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x07, 0x8f, 0x1d, 0xe3, 0x8c, 0xf0, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x07, 0xff, 0x38, 0xf1, 0xc0, 0x70, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x07, 0xff, 0x3c, 0x73, 0x80, 0x70, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x0f, 0x03, 0xb8, 0x73, 0xc0, 0x70, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x0e, 0x03, 0xbc, 0x3b, 0xc0, 0x70, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x04, 0x00, 0x20, 0x18, 0x00, 0x20, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x30, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x10, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x30, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x84, 0x32, 0x02, 0x01, 0xb0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x0f, 0xef, 0x1f, 0x87, 0xc3, 0xf0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x0e, 0x73, 0x39, 0x8c, 0x46, 0x30, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x0c, 0x21, 0x30, 0xc8, 0x6c, 0x30, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x0c, 0x21, 0x30, 0xcf, 0xe4, 0x30, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x0c, 0x61, 0x10, 0xd8, 0x0c, 0x10, 0x00, 0x07, 0xff,
0xff, 0x80, 0x00, 0x04, 0x63, 0x90, 0xcc, 0x04, 0x30, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x0c, 0x21, 0x3b, 0x8e, 0xe7, 0x70, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x0c, 0x21, 0x1f, 0x07, 0xe1, 0xf0, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x03, 0x06, 0x00, 0x20, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x00, 0x00, 0x01, 0x06, 0x00, 0x20, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x23, 0x04, 0x00, 0x70, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x0f, 0x3e, 0x71, 0xe6, 0xf1, 0xe0, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x09, 0xa2, 0x1b, 0x34, 0x8b, 0x30, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x1f, 0xb2, 0x7b, 0x14, 0xfa, 0x20, 0x00, 0x03, 0xff,
0xff, 0x80, 0x00, 0x08, 0x22, 0xc9, 0x36, 0x83, 0x20, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x00, 0x0d, 0x22, 0xdb, 0xe6, 0xd9, 0xb0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x20, 0x02, 0x22, 0x20, 0x40, 0x30, 0xa0, 0x00, 0x03, 0xff,
0xff, 0x80, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0x80, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0x80, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0x80, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x7f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0xc0, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xff,
0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff,
0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff,
0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff,
0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff,
0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff,
0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff,
0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0x01, 0xa5, 0x25, 0x6f, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x1f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
unsigned int MBED_ENABLED_LOGO_100X100_96X96_mono_bmp_len = 1152;
unsigned char ARM_logo_96X96_mono_bmp[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xe0, 0x1f, 0xff, 0x80, 0x00, 0x7f, 0xe0, 0x7f, 0xff, 0xc0, 0xf5,
0xff, 0xc0, 0x0f, 0xff, 0x00, 0x00, 0x3f, 0xe0, 0x3f, 0xff, 0x80, 0xe6,
0xff, 0xc0, 0x0f, 0xff, 0x80, 0x00, 0x0f, 0xc0, 0x1f, 0xff, 0x00, 0xd3,
0xff, 0xc0, 0x07, 0xff, 0x80, 0x00, 0x07, 0xe0, 0x0f, 0xfe, 0x00, 0xee,
0xff, 0x80, 0x07, 0xff, 0x00, 0x00, 0x07, 0xc0, 0x07, 0xfc, 0x00, 0x75,
0xff, 0x80, 0x03, 0xff, 0x80, 0xfc, 0x03, 0xe0, 0x03, 0xfc, 0x00, 0x7b,
0xff, 0x00, 0x03, 0xff, 0x81, 0xfc, 0x03, 0xc0, 0x03, 0xf0, 0x00, 0xff,
0xff, 0x00, 0x03, 0xff, 0x00, 0xfe, 0x03, 0xe0, 0x01, 0xe0, 0x00, 0xff,
0xff, 0x03, 0x01, 0xff, 0x80, 0xfe, 0x03, 0xe0, 0x00, 0xe0, 0x00, 0xff,
0xfe, 0x03, 0x01, 0xff, 0x81, 0xfc, 0x03, 0xe0, 0x00, 0x40, 0x00, 0x7f,
0xfe, 0x03, 0x80, 0xff, 0x00, 0xf8, 0x07, 0xc0, 0x00, 0x00, 0x00, 0xff,
0xfc, 0x07, 0x80, 0xff, 0x80, 0x00, 0x07, 0xe0, 0x60, 0x00, 0x80, 0xff,
0xfc, 0x07, 0xc0, 0x7f, 0x80, 0x00, 0x0f, 0xc0, 0x30, 0x01, 0x80, 0xff,
0xf8, 0x07, 0xc0, 0x7f, 0x00, 0x00, 0x1f, 0xe0, 0x38, 0x01, 0x80, 0xff,
0xf8, 0x0f, 0xc0, 0x3f, 0x80, 0x00, 0x3f, 0xc0, 0x38, 0x03, 0xc0, 0x7f,
0xf8, 0x0f, 0xe0, 0x3f, 0x80, 0x00, 0x1f, 0xe0, 0x7c, 0x07, 0xc0, 0xff,
0xf0, 0x1f, 0xe0, 0x3f, 0x00, 0xe0, 0x0f, 0xe0, 0x3e, 0x0f, 0x80, 0xff,
0xf0, 0x00, 0x00, 0x1f, 0x80, 0xf0, 0x0f, 0xe0, 0x3f, 0x1f, 0x80, 0xff,
0xe0, 0x00, 0x00, 0x0f, 0x81, 0xf8, 0x07, 0xc0, 0x7f, 0xbf, 0x80, 0x7f,
0xe0, 0x00, 0x00, 0x0f, 0x00, 0xfc, 0x03, 0xe0, 0x3f, 0xff, 0x80, 0xff,
0xe0, 0x00, 0x00, 0x0f, 0x80, 0xfc, 0x03, 0xc0, 0x3f, 0xff, 0xc0, 0xff,
0xc0, 0x24, 0x20, 0x07, 0x80, 0xfe, 0x03, 0xe0, 0x3f, 0xff, 0xc0, 0xff,
0xc0, 0x7f, 0xfc, 0x07, 0x01, 0xfe, 0x01, 0xc0, 0x7f, 0xff, 0x80, 0xff,
0x80, 0x7f, 0xfc, 0x03, 0x80, 0xff, 0x01, 0xe0, 0x3f, 0xff, 0x80, 0xff,
0x80, 0xff, 0xfe, 0x03, 0x80, 0xff, 0x00, 0xe0, 0x3f, 0xff, 0x80, 0x7f,
0x80, 0xff, 0xfe, 0x01, 0x81, 0xff, 0x80, 0xe0, 0x3f, 0xff, 0x80, 0xff,
0x01, 0xff, 0xff, 0x01, 0x80, 0xff, 0x80, 0x60, 0x7f, 0xff, 0xc0, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
unsigned int ARM_logo_96X96_mono_bmp_len = 1152;
unsigned char qsg_96X96_mono_bmp[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xff,
0xff, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff,
0xf1, 0x82, 0x47, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xef, 0xff, 0xff, 0xff,
0xf0, 0x92, 0x07, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xe7, 0x7f, 0xff, 0xff,
0xf4, 0x84, 0x07, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xef, 0xff, 0xff, 0xff,
0xe0, 0x82, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xce, 0x7c, 0x7f, 0xff, 0xff,
0xe6, 0x10, 0xe7, 0xff, 0xff, 0xff, 0xff, 0xc2, 0x00, 0xff, 0xff, 0xff,
0xfe, 0x7a, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x01, 0x81, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0x60, 0x47, 0xdf, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe4, 0xf0, 0x1f, 0x9d, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa3, 0xfc, 0x0f, 0x9b, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x4f, 0xff, 0x01, 0xdf, 0x1b, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0x80, 0xfb, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xe0, 0x3b, 0xf3, 0xff,
0xf2, 0xbd, 0xeb, 0xff, 0xff, 0xef, 0xff, 0xff, 0xf8, 0x00, 0x03, 0xff,
0xff, 0xef, 0x7f, 0xff, 0xff, 0x1f, 0xfb, 0xff, 0xfe, 0x00, 0x07, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfc, 0x7b, 0xee, 0x7f, 0xff, 0x01, 0x1d, 0xbf,
0xff, 0xff, 0xff, 0xff, 0xf9, 0x38, 0xfc, 0x3f, 0xff, 0xc3, 0xf2, 0x3f,
0xe1, 0xff, 0xff, 0xff, 0xe0, 0x4f, 0xfd, 0x8f, 0xff, 0xcf, 0xe8, 0xff,
0xc1, 0xff, 0xff, 0xff, 0x80, 0x27, 0xff, 0xc3, 0xff, 0xbf, 0x91, 0xff,
0xc4, 0xde, 0xeb, 0xff, 0x80, 0x0f, 0xfb, 0xf0, 0xff, 0x7f, 0xc7, 0xff,
0xe5, 0xff, 0xff, 0xbf, 0xe0, 0x3f, 0xf3, 0x1d, 0xb9, 0xf9, 0x0f, 0xff,
0xe1, 0xff, 0xff, 0xff, 0xf0, 0xfb, 0x9c, 0x07, 0xe7, 0xf0, 0x77, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfc, 0x78, 0x00, 0x03, 0xff, 0xd8, 0x6e, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0x60, 0x81, 0xb7, 0x23, 0xfe, 0x7f,
0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0x80, 0x01, 0xfe, 0xc7, 0x29, 0xbf,
0xfb, 0xed, 0xef, 0xbd, 0x7f, 0xc3, 0xe0, 0x01, 0xfd, 0x1e, 0x32, 0x3f,
0xe1, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf4, 0x03, 0xcc, 0x30, 0x29, 0xf7,
0xc1, 0xdf, 0xbd, 0xff, 0xff, 0xf0, 0x3c, 0x0f, 0xc1, 0xe0, 0x07, 0xf7,
0xc4, 0xfd, 0xef, 0xff, 0xff, 0xf0, 0x0e, 0x3f, 0xe7, 0x80, 0xdf, 0xe7,
0xe1, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x07, 0xfd, 0x9f, 0x04, 0x3f, 0xdf,
0xf7, 0xfb, 0xbb, 0xff, 0xff, 0xb8, 0x73, 0xfe, 0x3e, 0x10, 0x3f, 0xe7,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xfc, 0xf8, 0xff, 0x05, 0xbf, 0xcf,
0xff, 0xff, 0xff, 0xff, 0xfd, 0xb7, 0xfe, 0x33, 0xfe, 0x5f, 0xbf, 0x3f,
0xf7, 0xff, 0xff, 0xff, 0xfb, 0x7f, 0xff, 0x8f, 0xfe, 0x9f, 0xbe, 0xff,
0xe1, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xf1, 0x7f, 0xb9, 0xff,
0xc1, 0xfb, 0xfd, 0xf7, 0xf5, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xe7, 0xff,
0xcc, 0xff, 0xbf, 0xff, 0xf7, 0xff, 0xff, 0x7f, 0xff, 0xff, 0x8f, 0xff,
0xe1, 0xde, 0xbb, 0xff, 0xf7, 0xbb, 0xfc, 0x7f, 0xff, 0xff, 0x7f, 0xff,
0xe3, 0xff, 0xff, 0xff, 0xfb, 0xe7, 0xf8, 0xff, 0xff, 0xfc, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xed, 0xfe, 0xe0, 0x7f, 0xff, 0xf3, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x87, 0x1d, 0x80, 0x3f, 0xff, 0xcf, 0xff, 0xff,
0xff, 0xff, 0xff, 0xfc, 0x0f, 0xd7, 0x00, 0x1f, 0xff, 0xbf, 0xff, 0xff,
0xff, 0xff, 0xff, 0xf2, 0x1f, 0xc6, 0xc3, 0x3e, 0xfc, 0x7f, 0xff, 0xff,
0xff, 0xff, 0xff, 0xf0, 0x1f, 0xc2, 0x87, 0x1f, 0xfd, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xf8, 0x7f, 0xfe, 0x9f, 0xbf, 0xe3, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xcf, 0xdf, 0xff, 0x9f, 0xfc, 0xcf, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0x9f, 0x77, 0xfe, 0xc3, 0xf7, 0x7f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfe, 0x7d, 0xdd, 0xff, 0xf0, 0xee, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf9, 0xe0, 0xf0, 0xff, 0xff, 0x03, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xc7, 0xc0, 0x71, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x7f, 0xfc, 0x3f, 0x10, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x82, 0x01, 0xfc, 0x04, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xff, 0xf8, 0x02, 0x4f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf0, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf4, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xf0, 0x0f, 0xff, 0xf7, 0xff, 0xd7, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xe2, 0x3f, 0xff, 0xf9, 0x62, 0x9a, 0x56, 0x3f, 0xff, 0xff,
0xfa, 0x5b, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x80, 0x00, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x0f, 0xfd, 0xff, 0xff, 0xff, 0xf9, 0xa5, 0x30, 0x56, 0x91, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xef, 0xff, 0xff, 0x7f, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xf7, 0x9b, 0x5b, 0xa6, 0xba, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
unsigned int qsg_96X96_mono_bmp_len = 1152;
unsigned char black_square_96X96_mono_bmp[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
unsigned int black_square_96X96_mono_bmp_len = 1152;
<file_sep>//----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2016 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#include "update_ui_example.h"
#include <stdio.h>
#include <stdint.h>
#ifdef MBED_APPLICATION_SHIELD
#include "C12832.h"
extern C12832* lcd;
#endif
#ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE
void update_authorize(arm_uc_request_t request)
{
switch (request)
{
/* Cloud Client wishes to download new firmware. This can have a negative
impact on the performance of the rest of the system.
The user application is supposed to pause performance sensitive tasks
before authorizing the download.
Note: the authorization call can be postponed and called later.
This doesn't affect the performance of the Cloud Client.
*/
case ARM_UCCC_REQUEST_DOWNLOAD:
printf("Firmware download requested\r\n");
printf("Authorization granted\r\n");
ARM_UC_Authorize(ARM_UCCC_REQUEST_DOWNLOAD);
#ifdef MBED_APPLICATION_SHIELD
/* clear screen */
lcd->cls();
#endif
break;
/* Cloud Client wishes to reboot and apply the new firmware.
The user application is supposed to save all current work before rebooting.
Note: the authorization call can be postponed and called later.
This doesn't affect the performance of the Cloud Client.
*/
case ARM_UCCC_REQUEST_INSTALL:
printf("Firmware install requested\r\n");
printf("Authorization granted\r\n");
ARM_UC_Authorize(ARM_UCCC_REQUEST_INSTALL);
break;
default:
printf("Error - unknown request\r\n");
break;
}
}
void update_progress(uint32_t progress, uint32_t total)
{
uint8_t percent = progress * 100 / total;
#ifdef MBED_APPLICATION_SHIELD
/* display progress */
uint8_t bar = progress * 90 / total;
lcd->locate(0,3);
lcd->printf("Downloading: %d / %d KiB", progress / 1024, total / 1024);
lcd->rect(0, 15, 90, 22, 1);
lcd->fillrect(0, 15, bar, 22, 1);
lcd->locate(91, 15);
lcd->printf(" %d %%", percent);
#endif
/* only show progress bar if debug trace is disabled */
#if !defined(MBED_CONF_MBED_TRACE_ENABLE) \
&& !ARM_UC_ALL_TRACE_ENABLE \
&& !ARM_UC_HUB_TRACE_ENABLE
printf("\rDownloading: [");
for (uint8_t index = 0; index < 50; index++)
{
if (index < percent / 2)
{
printf("+");
}
else if (index == percent / 2)
{
static uint8_t old_max = 0;
static uint8_t counter = 0;
if (index == old_max)
{
counter++;
}
else
{
old_max = index;
counter = 0;
}
switch (counter % 4)
{
case 0:
printf("/");
break;
case 1:
printf("-");
break;
case 2:
printf("\\");
break;
case 3:
default:
printf("|");
break;
}
}
else
{
printf(" ");
}
}
printf("] %d %%", percent);
fflush(stdout);
#else
printf("Downloading: %d %%\r\n", percent);
#endif
if (progress == total)
{
printf("\r\nDownload completed\r\n");
}
}
#endif // MBED_CLOUD_CLIENT_SUPPORT_UPDATE
<file_sep># mbed-cloud-k64f-example
### requirements
- Python
- Python Virtualenv
- Python-PIP
- Python mbed-cli
- Brew on MacOS
- GCC-none compilers for ARM CortexM
- Imagemagick
- flash.py (optional to make flashing and resetting easier)
mbed target board FRDM-K64F with a .96 OLED Grove Display and mbed cloud client
<!---
mbed new mbed-cloud-k64f-example && cd mbed-cloud-k64f-example
-->
mbed add mbed-os
virtualenv .venv && source .venv/bin/activate
pip install -r mbed-os/requirements.txt
// Add the library for the OLED display
mbed add https://developer.mbed.org/users/danielashercohen/code/SeeedGrayOLED/
// Optionally get the firmware flashing tool
wget https://gist.githubusercontent.com/mbartling/359fe8df6fd785e8960d566fb3c3b479/raw/2d7fd3c131c3e33bfefe1fa12e1024987039b312/flash.py
// Add the library for the motion sensor part on the FRDM-K64F board
mbed add http://developer.mbed.org/teams/Freescale/code/FXOS8700Q
### Header File Generation
All the graphics below can be fetched with the create_h_bitmaps.sh script including header file generation
#### Download graphics for display
// Grab a logo from NXP that says mbed enabled - note it's not really 100x100 rather 530x630
wget http://www.nxp.com/files-static/graphic/logo_external/MBED_ENABLED_LOGO_100X100.jpg
// Grab the ARM logo from a public source
wget http://img.technews.co/wp-content/uploads/2015/05/ARM-logo.jpg
// Grab the IoT ARM image
https://developer.mbed.org/media/uploads/chris/qsg.png
#### BLANK CLEAR SCREEN GRAPHIC
// We need to generate a black bitmap with Imagemagick
convert -size 96x96 xc:#000000 blank.bmp
// Make the black bitmap monochrome with Imagemagick
convert blank.bmp -monochrome -colors 2 blank_96X96.bmp
// We need to strip the bitmap header off the file and get pure binary image data
cat blank_96X96.bmp | dd skip=146 bs=1 of=blank_96X96.img
// Dump a C header file with an array of hexadecimal image payload
xxd -i blank_96X96.img blank.h
#### ARM MBED ENABLED LOGO
// We need to convert the original image we downloaded with wget to a 96x96 to fit on the display
notice it's also filling the edges and flipping it so we fill the display it the orientation is correct
convert MBED_ENABLED_LOGO_100X100.jpg -resize 96x96 -background white -gravity center -extent 96x96 -flip MBED_ENABLED_LOGO_96X96.bmp
// Make the mbed enabled image monochrome with Imagemagick
convert MBED_ENABLED_LOGO_96X96.bmp -monochrome -colors 2 MBED_ENABLED_LOGO_96X96_LOGO.bmp
// We need to strip the bitmap header off the file and get pure binary image data
cat MBED_ENABLED_LOGO_96X96_LOGO.bmp | dd skip=146 bs=1 of=MBED_ENABLED_LOGO_96X96_LOGO.img
// Dump a C header file with an array of hexadecimal image payload
xxd -i MBED_ENABLED_LOGO_96X96_LOGO.img logo.h
#### ARM STARTUP LOGO
convert ARM-logo.jpg -resize 96x96 -background white -gravity center -extent 96x96 -flip ARM-logo_96X96.bmp
convert ARM-logo_96X96.bmp -monochrome -colors 2 ARM-logo_96X96-mono.bmp
cat ARM-logo_96X96-mono.bmp | dd skip=146 bs=1 of=ARM-logo_96X96-mono.img
xxd -i ARM-logo_96X96-mono.img armlogo.h
### BUILD and RUN
// Generate the header files from images
./create_h_bitmaps.sh
// Build the firmware with the GCC compilers
mbed compile -m K64F -t GCC_ARM
// Optional flash tool which copies the firmware binary to the board and sends a serial break
command to reset and start executing the new code. Otherwise just drag over the compiled
binary to the DAPLINK connected USB storage device and reset the board
./flash.py
### LATEST DIRECTIONS
mbed add https://github.com/ARMmbed/mbed-os
mbed add https://developer.mbed.org/users/sam_grove/code/BufferedSerial
mbed add https://developer.mbed.org/teams/Freescale/code/FXOS8700Q
mbed add https://developer.mbed.org/users/danielashercohen/code/SeeedGrayOLED
mbed add https://github.com/ARMmbed/mbed-cloud-client
mbed update
./create_h_bitmaps.sh
cp SOMEPATH/identity_dev_security.c .
mbed compile -m k64f -t gcc_arm -DYOTTA_CFG_MBED_TRACE -c
<file_sep>#ifndef LIB_FACTORY_INJECTION_CLIENT_H
#define LIB_FACTORY_INJECTION_CLIENT_H
#include "NetworkInterface.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
DEVICE_PROVISIONED,
DEVICE_ALREADY_PROVISIONED,
DEVICE_PROVISION_FAILED
} ProvisionStatus_t;
extern ProvisionStatus_t device_provision_status;
extern NetworkInterface * network_handler;
extern volatile bool provisioned;
void provision_device();
#ifdef __cplusplus
}
#endif
#endif // LIB_FACTORY_INJECTION_CLIENT_H
<file_sep>//----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2016 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#ifndef UPDATE_UI_EXAMPLE_H
#define UPDATE_UI_EXAMPLE_H
#include "mbed-cloud-client/MbedCloudClient.h"
#ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE
/**
* @brief Function for authorizing firmware downloads and reboots.
* @param request The request under consideration.
*/
void update_authorize(arm_uc_request_t request);
/**
* @brief Callback function for reporting the firmware download progress.
* @param progress Received bytes.
* @param total Total amount of bytes to be received.
*/
void update_progress(uint32_t progress, uint32_t total);
#endif // MBED_CLOUD_CLIENT_SUPPORT_UPDATE
#endif // UPDATE_UI_EXAMPLE_H
<file_sep>//----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2016 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#include "mbed.h"
#include "EthernetInterface.h"
#include "lib_factory_injection_client.h"
#include "ftd_socket.h"
#include "spv_lib_iot.h"
#include "spv_lib_iot_test_only.h"
#include "identity_client.h"
#include "mbed-trace/mbed_trace.h"
#define TRACE_GROUP "ijtl"
/**
* The mBED device communicates port to the
* Production Line Orchestrator
*/
#define FTD_SERVER_TCP_PORT 7777
FtdSocket *pServer = NULL;
EthernetInterface ethernet;
ProvisionStatus_t device_provision_status = DEVICE_PROVISION_FAILED;
NetworkInterface * network_handler = NULL;
volatile bool provisioned = false;
/**
* Gets the mBED device IP address
*/
static const char *DeviceIpAddrGet(NetworkInterface * handler)
{
int retries = 5;
while (retries--) {
const char *ip = handler->get_ip_address();
if (ip != NULL) {
return ip;
} else {
wait(0.2);
}
}
return NULL; /* failed to retrieve a valid IP address */
}
void provision_device()
{
tr_info("Connecting to Ethernet interface...\r\n");
const char *serverIpAddr = DeviceIpAddrGet(network_handler);
if (serverIpAddr == NULL) {
tr_debug("Failed retrieving device IP address!");
device_provision_status = DEVICE_PROVISION_FAILED;
provisioned = true;
return;
}
printf("\r\nFactory Injection Server IP Address is %s:%d\r\n", serverIpAddr, FTD_SERVER_TCP_PORT);
// Init SPV
//! [SpvInitialization]
SaPvConfiguration_t spvConfig;
SaPvStatus_t status = SaPvIoTInitConfigPrepare(&spvConfig);
if (status != SA_PV_STATUS_OK) {
tr_debug("SaPvIoTInitConfigPrepare failed");
device_provision_status = DEVICE_PROVISION_FAILED;
provisioned = true;
return;
}
status = SaPvIoTInit(&spvConfig);
if (status != SA_PV_STATUS_OK) {
tr_debug("SaPvIoTInit failed");
device_provision_status = DEVICE_PROVISION_FAILED;
provisioned = true;
return;
}
//! [SpvInitialization]
IdcStatus_t idc_status = IDC_STATUS_OK;
idc_status = IdcInit();
bool isDeviceConfigured = false;
if(idc_status == IDC_STATUS_OK) {
idc_status = IdcIsDeviceConfigured(&isDeviceConfigured);
if(idc_status == IDC_STATUS_OK) {
if(isDeviceConfigured) {
device_provision_status = DEVICE_ALREADY_PROVISIONED;
provisioned = true;
return;
}
}
}
// Create the device server object
pServer = new FtdSocket(FTD_SERVER_TCP_PORT);
//! [Initialization]
if (pServer == NULL) {
tr_debug("Failed instantiating FactoryInjectionClientSocket object");
device_provision_status = DEVICE_PROVISION_FAILED;
provisioned = true;
return;
}
//Initializes Ethernet interface and prints its address
bool result;
result = pServer->InitNetworkInterface(network_handler, FTD_IPV4);
if (result == false) {
tr_debug("InitNetworkInterface Failed");
}
//! [Initialization]
printf("\r\nFactory Tool Device Client ready for Provisioning Tool...\n");
// should never return
bool success = pServer->Listen();
//tr_debug("Factory tool work done with result %d", (int)success);
// In case of a failure - disconnect and finalize SPV
status = SaPvIoTFinalize();
if (status != SA_PV_STATUS_OK) {
tr_debug("SaPvIoTInit failed");
device_provision_status = DEVICE_PROVISION_FAILED;
provisioned = true;
return;
}
device_provision_status = DEVICE_PROVISIONED;
provisioned = true;
pServer->Finish();
return;
}
<file_sep>#!/bin/bash
IMAGE_DIR="IMAGES"
IMAGE_HEADER="images.h"
if [ ! -d "$DIRECTORY" ]; then
mkdir $IMAGE_DIR
fi
if [ ! -z "$IMAGE_HEADER" ]; then
rm -f $IMAGE_HEADER
touch $IMAGE_HEADER
fi
inverse=false
for url in http://www.nxp.com/files-static/graphic/logo_external/MBED_ENABLED_LOGO_100X100.jpg \
http://img.technews.co/wp-content/uploads/2015/05/ARM-logo.jpg \
https://developer.mbed.org/media/uploads/chris/qsg.png \
black_square
do
# we need a 96x96 black image to clear the display
if [ "$url" = "black_square" ]; then
filename_orig="$url"".bmp"
convert -size 96x96 xc:#000000 "$IMAGE_DIR""/""$filename_orig"
# otherwise we can just process every other image normally
else
wget --directory-prefix=$IMAGE_DIR $url
filename_orig=$(echo $url | sed 's/.*\///')
fi
# echo $filename_orig
filename_only=$(echo $filename_orig | sed 's/\.[^.]*$//')
# echo $filename_only
filename_one="$filename_only""-96X96.bmp"
# echo $filename_one
filename_two=$(echo $filename_one | sed 's/\.[^.]*$//')"-mono.bmp"
# echo $filename_two
# filename_three=$(echo $filename_two | sed 's/\.[^.]*$//')".img"
# echo $filename_three
filename_header=$(echo $filename_only)".h"
# echo $filename_header
convert "$IMAGE_DIR""/""$filename_orig" -resize 96x96 -background white -gravity center -extent 96x96 -flip "$IMAGE_DIR""/""$filename_one"
convert "$IMAGE_DIR""/""$filename_one" -monochrome -colors 2 "$IMAGE_DIR""/""$filename_two"
# Make the ARM letters white on a black background
if [ "$filename_only" = "ARM-logo" ] || [ "$filename_only" = "MBED_ENABLED_LOGO_100X100" ]; then
if [ "$inverse" = true ]; then
cp $IMAGE_DIR"/"$filename_two $IMAGE_DIR"/"$filename_only"_dexter.bmp"
mogrify +negate "$IMAGE_DIR""/""$filename_two"
fi
fi
# We can skip the filename_three step and dd by using the -s option on xxd
# cat "$IMAGE_DIR""/""$filename_two" | dd skip=146 bs=1 of="$IMAGE_DIR""/""$filename_three"
# xxd -i "$IMAGE_DIR""/""$filename_three" $filename_header
cd $IMAGE_DIR
xxd -s 146 -i $filename_two >> "../"$IMAGE_HEADER && cd ..
done
# Clean up all the images we created
rm -rf $IMAGE_DIR<file_sep>//----------------------------------------------------------------------------
// The confidential and proprietary information contained in this file may
// only be used by a person authorised under and to the extent permitted
// by a subsisting licensing agreement from ARM Limited or its affiliates.
//
// (C) COPYRIGHT 2016 ARM Limited or its affiliates.
// ALL RIGHTS RESERVED
//
// This entire notice must be reproduced on all copies of this file
// and copies of this file may only be made by a person if such person is
// permitted to do so under the terms of a subsisting license agreement
// from ARM Limited or its affiliates.
//----------------------------------------------------------------------------
#include "mbed.h"
#define MYCLOUDAPP
#ifdef MYCLOUDAPP
// OLE42178P Seeed Studio OLED display 96 x 96
#include "SeeedGrayOLED.h"
// FXOS8700Q MotionSensor Accelerometer & Magnetometer
#include "FXOS8700Q.h"
// all the image bitmaps
#include "images.h"
// #define TRACE_GROUP "acc,mac,oled"
#endif
#ifdef MBED_HEAP_STATS_ENABLED
// used by print_heap_stats only
#include "mbed_stats.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include "mbed-client/m2mbase.h"
#endif
#include "mbed-cloud-client/MbedCloudClient.h"
#include "mbed-cloud-client/SimpleM2MResource.h"
#include "mbed-client/m2minterface.h"
#include "lib_factory_injection_client.h"
#include "mbed-trace/mbed_trace.h"
#include "mbed_cloud_client_user_config.h"
#include "memory_tests.h"
#define FACTORY_STACK_SIZE (1024 * 7)
#define ETHERNET 1
#define WIFI 2
#define MESH_LOWPAN_ND 3
#define MESH_THREAD 4
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
#include "ESP8266Interface.h"
ESP8266Interface esp(D1, D0);
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
#include "EthernetInterface.h"
EthernetInterface eth;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_LOWPAN_ND
#define MESH
#include "NanostackInterface.h"
LoWPANNDInterface mesh;
#elif MBED_CONF_APP_NETWORK_INTERFACE == MESH_THREAD
#define MESH
#include "NanostackInterface.h"
ThreadInterface mesh;
#else
#error "No connectivity method chosen. Please add 'config.network-interfaces.value' to your mbed_app.json (see README.md for more information)."
#endif
#ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE
#include "update_ui_example.h"
#endif
#ifdef MBED_APPLICATION_SHIELD
#include "C12832.h"
C12832* lcd;
#endif
#ifdef MYCLOUDAPP
I2C i2c(PTE25, PTE24);
RawSerial pc(USBTX, USBRX);
static Mutex mutex_uart;
Thread t_oled;
Thread t_mag;
Thread t_acc;
#endif
DigitalOut led1(LED_GREEN);
InterruptIn btn(SW2);
InterruptIn cls(SW3);
Semaphore updates(0);
MbedCloudClient client;
volatile bool registered = false;
volatile bool error_occured = false;
volatile bool clicked = false;
static Mutex SerialOutMutex;
void serial_out_mutex_wait()
{
SerialOutMutex.lock();
}
void serial_out_mutex_release()
{
SerialOutMutex.unlock();
}
void patternUpdated(string v) {
pc.printf("New pattern: %s\n", v.c_str());
}
// Note: the mbed-os needs to be compiled with MBED_HEAP_STATS_ENABLED to get
// functional heap stats, or the mbed_stats_heap_get() will return just zeroes.
static void print_heap_stats()
{
#ifdef MBED_HEAP_STATS_ENABLED
mbed_stats_heap_t stats;
mbed_stats_heap_get(&stats);
pc.printf("**** current_size: %" PRIu32 "\n", stats.current_size);
pc.printf("**** max_size : %" PRIu32 "\n", stats.max_size);
#endif // MBED_HEAP_STATS_ENABLED
}
#ifdef MYCLOUDAPP
void uart_print(const char* str) {
mutex_uart.lock();
pc.printf("%s", str);
mutex_uart.unlock();
}
time_t get_current_time() {
return time(NULL);
}
void print_current_time() {
time_t seconds = get_current_time();
// tr_info(, "Current Time is: %s", ctime(&seconds));
}
void oled() {
unsigned char *bitmaps[] = { qsg_96X96_mono_bmp };
i2c.lock();
// Setup OLED with proper i2c clock and data
SeeedGrayOLED SeeedGrayOled(PTE25, PTE24);
SeeedGrayOled.init(); //initialize SEEED OLED display
i2c.unlock();
while (true) {
i2c.lock();
pc.printf("%s:%d-->%s()\n", __FILE__, __LINE__, __func__);
// clear screen
SeeedGrayOled.drawBitmap(black_square_96X96_mono_bmp, 96 * 96 / 8);
SeeedGrayOled.setTextXY(0, 0); //set Cursor to first line, 0th column
SeeedGrayOled.clearDisplay(); //Clear Display.
SeeedGrayOled.setNormalDisplay(); //Set Normal Display Mode
SeeedGrayOled.setVerticalMode();
SeeedGrayOled.setGrayLevel(15); //Set Grayscale level
// clear screen
SeeedGrayOled.drawBitmap(black_square_96X96_mono_bmp, 96 * 96 / 8);
SeeedGrayOled.drawBitmap(ARM_logo_96X96_mono_bmp, 96 * 96 / 8);
wait_ms(500);
// clear screen
SeeedGrayOled.drawBitmap(black_square_96X96_mono_bmp, 96 * 96 / 8);
SeeedGrayOled.setGrayLevel(15); //Set Grayscale level
for (int j = 0; j < (int) (sizeof(bitmaps) / sizeof(unsigned char*)); j++) {
SeeedGrayOled.drawBitmap(bitmaps[j], 96 * 96 / 8);
wait_ms(500);
}
// clear screen
SeeedGrayOled.drawBitmap(black_square_96X96_mono_bmp, 96 * 96 / 8);
SeeedGrayOled.setGrayLevel(15); //Set Grayscale level 15.
SeeedGrayOled.drawBitmap(MBED_ENABLED_LOGO_100X100_96X96_mono_bmp,
96 * 96 / 8);
// clear screen
// SeeedGrayOled.drawBitmap(black_square_96X96_mono_bmp, 96 * 96 / 8);
wait(1);
i2c.unlock();
}
}
void mag() {
i2c.lock();
FXOS8700QMagnetometer mag(i2c, FXOS8700CQ_SLAVE_ADDR1); // Proper Ports and I2C Address for K64F Freedom board
mag.enable(); // enable the FXOS8700Q Magnetometer
i2c.unlock();
while (true) {
print_current_time();
pc.printf("%s:%d-->%s()\n", __FILE__, __LINE__, __func__);
i2c.lock();
motion_data_units_t mag_data;
motion_data_counts_t mag_raw;
float fmX, fmY, fmZ;
int16_t rmX, rmY, rmZ;
char *buf;
size_t sz;
mag.getAxis(mag_raw);
mag.getX(rmX);
mag.getY(rmY);
mag.getZ(rmZ);
mag.getAxis(mag_data);
mag.getX(fmX);
mag.getY(fmY);
mag.getZ(fmZ);
// SeeedGrayOled.setTextXY(2,0); //set Cursor to third line, 0th column
// sz = snprintf(NULL, 0, "Who Am I=%X", mag.whoAmI());
// buf = (char *) malloc(sz + 1); /* make sure you check for != NULL in real code */
// snprintf(buf, sz + 1, "Who Am I=%X", mag.whoAmI());
// SeeedGrayOled.putString(buf);
// pc.printf("buf is %s %s:%d-->%s()\n", buf, __FILE__, __LINE__, __func__);
// free(buf);
sz = snprintf(NULL, 0, "MAG:X=%1.4f Y=%1.4f Z=%1.4f ", mag_data.x,
mag_data.y, mag_data.z);
buf = (char *) malloc(sz + 1); /* make sure you check for != NULL in real code */
snprintf(buf, sz + 1, "MAG:X=%1.4f Y=%1.4f Z=%1.4f ", mag_data.x,
mag_data.y, mag_data.z);
pc.printf("buf is %s %s:%d-->%s()\n", buf, __FILE__, __LINE__, __func__);
free(buf);
i2c.unlock();
}
}
void acc() {
i2c.lock();
// Proper Ports and I2C Address for K64F Freedom board
FXOS8700QAccelerometer acc(i2c, FXOS8700CQ_SLAVE_ADDR1);
acc.enable(); // enable the FXOS8700Q Magnetometer
i2c.unlock();
while (true) {
print_current_time();
pc.printf("%s:%d-->%s()\n", __FILE__, __LINE__, __func__);
i2c.lock();
motion_data_units_t acc_data;
motion_data_counts_t acc_raw;
float faX, faY, faZ;
int16_t raX, raY, raZ;
char *buf;
size_t sz;
acc.getAxis(acc_raw);
acc.getX(raX);
acc.getY(raY);
acc.getZ(raZ);
acc.getAxis(acc_data);
acc.getX(faX);
acc.getY(faY);
acc.getZ(faZ);
// SeeedGrayOled.setTextXY(2,0); //set Cursor to third line, 0th column
// sz = snprintf(NULL, 0, "Who Am I=%X", acc.whoAmI());
// buf = (char *) malloc(sz + 1); /* make sure you check for != NULL in real code */
// snprintf(buf, sz + 1, "Who Am I=%X", acc.whoAmI());
// SeeedGrayOled.putString(buf);
// pc.printf("buf is %s %s:%d-->%s()\n", buf, __FILE__, __LINE__, __func__);
// free(buf);
sz = snprintf(NULL, 0, "ACC:X=%1.4f Y=%1.4f Z=%1.4f ", acc_data.x,
acc_data.y, acc_data.z);
buf = (char *) malloc(sz + 1); /* make sure you check for != NULL in real code */
snprintf(buf, sz + 1, "ACC:X=%1.4f Y=%1.4f Z=%1.4f ", acc_data.x,
acc_data.y, acc_data.z);
pc.printf("buf is %s %s:%d-->%s()\n", buf, __FILE__, __LINE__, __func__);
free(buf);
i2c.unlock();
}
}
#endif
/*
* The Led contains one property (pattern) and a function (blink).
* When the function blink is executed, the pattern is read, and the LED
* will blink based on the pattern.
*/
class LedResource : public MbedCloudClientCallback {
public:
LedResource() {
// create ObjectID with metadata tag of '3201', which is 'digital output'
led_object = M2MInterfaceFactory::create_object("3201");
M2MObjectInstance* led_inst = led_object->create_object_instance();
// 5853 = Multi-state output
M2MResource* pattern_res = led_inst->create_dynamic_resource("5853", "Pattern",
M2MResourceInstance::STRING, false);
// read and write
pattern_res->set_operation(M2MBase::GET_PUT_ALLOWED);
// set initial pattern (toggle every 200ms. 7 toggles in total)
pattern_res->set_value((const uint8_t*)"500:500:500:500:500:500:500", 27);
// there's not really an execute LWM2M ID that matches... hmm...
M2MResource* led_res = led_inst->create_dynamic_resource("5850", "Blink",
M2MResourceInstance::OPAQUE, false);
// we allow executing a function here...
led_res->set_operation(M2MBase::POST_ALLOWED);
// when a POST comes in, we want to execute the led_execute_callback
led_res->set_execute_function(execute_callback(this, &LedResource::blink));
}
M2MObject* get_object() {
return led_object;
}
// implementation of MbedCloudClientCallback
virtual void value_updated(M2MBase *base, M2MBase::BaseType type) {
pc.printf("PUT Request Received!\n");
pc.printf("\nName :'%s',\nPath : '%s',\nType : '%d' (0 for Object, 1 for Resource), \nType : '%s'\n",
base->name(),
base->uri_path(),
type,
base->resource_type());
}
void blink(void *) {
// read the value of 'Pattern'
M2MObjectInstance* inst = led_object->object_instance();
M2MResource* res = inst->resource("5853");
// values in mbed Client are all buffers, and we need a vector of int's
uint8_t* buffIn = NULL;
uint32_t sizeIn;
res->get_value(buffIn, sizeIn);
// turn the buffer into a string, and initialize a vector<int> on the heap
std::string s((char*)buffIn, sizeIn);
std::vector<uint32_t>* v = new std::vector<uint32_t>;
pc.printf("led_execute_callback pattern=%s\n", s.c_str());
// our pattern is something like 500:200:500, so parse that
std::size_t found = s.find_first_of(":");
while (found!=std::string::npos) {
v->push_back(atoi((const char*)s.substr(0,found).c_str()));
s = s.substr(found+1);
found=s.find_first_of(":");
if(found == std::string::npos) {
v->push_back(atoi((const char*)s.c_str()));
}
}
// do_blink is called with the vector, and starting at -1
do_blink(v);
}
private:
M2MObject* led_object;
void do_blink(std::vector<uint32_t>* pattern) {
uint16_t position = 0;
for (;;) {
// blink the LED
led1 = !led1;
// up the position, if we reached the end of the vector
if (position >= pattern->size()) {
// free memory, and exit this function
delete pattern;
return;
}
// how long do we need to wait before the next blink?
uint32_t delay_ms = pattern->at(position);
// Wait requested time, then continue prosessing the blink pattern from next position.
Thread::wait(delay_ms);
position++;
}
}
};
/*
* The button contains one property (click count).
* When `handle_button_click` is executed, the counter updates.
*/
class ButtonResource {
public:
ButtonResource(): counter(0) {
// create ObjectID with metadata tag of '3200', which is 'digital input'
btn_object = M2MInterfaceFactory::create_object("3200");
M2MObjectInstance* btn_inst = btn_object->create_object_instance();
// create resource with ID '5501', which is digital input counter
M2MResource* btn_res = btn_inst->create_dynamic_resource("5501", "Button",
M2MResourceInstance::INTEGER, true /* observable */);
// we can read this value
btn_res->set_operation(M2MBase::GET_ALLOWED);
// set initial value (all values in mbed Client are buffers)
// to be able to read this data easily in the Connector console, we'll use a string
btn_res->set_value((uint8_t*)"0", 1);
}
~ButtonResource() {
}
M2MObject* get_object() {
return btn_object;
}
/*
* When you press the button, we read the current value of the click counter
* from mbed Device Connector, then up the value with one.
*/
void handle_button_click() {
M2MObjectInstance* inst = btn_object->object_instance();
M2MResource* res = inst->resource("5501");
// up counter
counter++;
pc.printf("handle_button_click, new value of counter is %d\n", counter);
// serialize the value of counter as a string, and tell connector
char buffer[20];
int size = sprintf(buffer,"%d",counter);
res->set_value((uint8_t*)buffer, size);
}
private:
M2MObject* btn_object;
uint16_t counter;
};
void fall() {
clicked = true;
updates.release();
}
void unregister() {
registered = false;
updates.release();
}
void error(int error_code) {
registered = false;
error_occured = true;
const char *error;
switch(error_code) {
case MbedCloudClient::IdentityError:
error = "MbedCloudClient::IdentityError";
break;
case MbedCloudClient::IdentityInvalidParameter:
error = "MbedCloudClient::IdentityInvalidParameter";
break;
case MbedCloudClient::IdentityOutofMemory:
error = "MbedCloudClient::IdentityOutofMemory";
break;
case MbedCloudClient::IdentityProvisioningError:
error = "MbedCloudClient::IdentityProvisioningError";
break;
case MbedCloudClient::IdentityInvalidSessionID:
error = "MbedCloudClient::IdentityInvalidSessionID";
break;
case MbedCloudClient::IdentityNetworkError:
error = "MbedCloudClient::IdentityNetworkError";
break;
case MbedCloudClient::IdentityInvalidMessageType:
error = "MbedCloudClient::IdentityInvalidMessageType";
break;
case MbedCloudClient::IdentityInvalidMessageSize:
error = "MbedCloudClient::IdentityInvalidMessageSize";
break;
case MbedCloudClient::IdentityCertOrKeyNotFound:
error = "MbedCloudClient::IdentityCertOrKeyNotFound";
break;
case MbedCloudClient::IdentityRetransmissionError:
error = "MbedCloudClient::IdentityRetransmissionError";
break;
case MbedCloudClient::ConnectErrorNone:
error = "MbedCloudClient::ConnectErrorNone";
break;
case MbedCloudClient::ConnectAlreadyExists:
error = "MbedCloudClient::ConnectAlreadyExists";
break;
case MbedCloudClient::ConnectBootstrapFailed:
error = "MbedCloudClient::ConnectBootstrapFailed";
break;
case MbedCloudClient::ConnectInvalidParameters:
error = "MbedCloudClient::ConnectInvalidParameters";
break;
case MbedCloudClient::ConnectNotRegistered:
error = "MbedCloudClient::ConnectNotRegistered";
break;
case MbedCloudClient::ConnectTimeout:
error = "MbedCloudClient::ConnectTimeout";
break;
case MbedCloudClient::ConnectNetworkError:
error = "MbedCloudClient::ConnectNetworkError";
break;
case MbedCloudClient::ConnectResponseParseFailed:
error = "MbedCloudClient::ConnectResponseParseFailed";
break;
case MbedCloudClient::ConnectUnknownError:
error = "MbedCloudClient::ConnectUnknownError";
break;
case MbedCloudClient::ConnectMemoryConnectFail:
error = "MbedCloudClient::ConnectMemoryConnectFail";
break;
case MbedCloudClient::ConnectNotAllowed:
error = "MbedCloudClient::ConnectNotAllowed";
break;
case MbedCloudClient::ConnectSecureConnectionFailed:
error = "MbedCloudClient::ConnectSecureConnectionFailed";
break;
case MbedCloudClient::ConnectDnsResolvingFailed:
error = "MbedCloudClient::ConnectDnsResolvingFailed";
break;
#ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE
case MbedCloudClient::UpdateWarningCertificateNotFound:
error = "MbedCloudClient::UpdateWarningCertificateNotFound";
break;
case MbedCloudClient::UpdateWarningCertificateInvalid:
error = "MbedCloudClient::UpdateWarningCertificateInvalid";
break;
case MbedCloudClient::UpdateWarningSignatureInvalid:
error = "MbedCloudClient::UpdateWarningSignatureInvalid";
break;
case MbedCloudClient::UpdateWarningVendorMismatch:
error = "MbedCloudClient::UpdateWarningVendorMismatch";
break;
case MbedCloudClient::UpdateWarningClassMismatch:
error = "MbedCloudClient::UpdateWarningClassMismatch";
break;
case MbedCloudClient::UpdateWarningDeviceMismatch:
error = "MbedCloudClient::UpdateWarningDeviceMismatch";
break;
case MbedCloudClient::UpdateWarningURINotFound:
error = "MbedCloudClient::UpdateWarningURINotFound";
break;
#endif
default:
error = "UNKNOWN";
}
pc.printf("\nError occured : %s\n", error);
pc.printf("\nError code : %d\n", error_code);
}
void toggleLed() {
led1 = !led1;
}
void client_registered() {
registered = true;
pc.printf("registered\n");
#ifdef MBED_APPLICATION_SHIELD
static const ConnectorClientServerInfo* server = NULL;
if (server == NULL)
{
server = client.server_info();
char endpoint_buffer[26] = { 0 };
memcpy(endpoint_buffer, server->endpoint_name.c_str(), 25);
lcd->cls();
lcd->locate(0, 3);
lcd->printf("Cloud Client: Ready");
lcd->locate(0, 15);
lcd->printf("%s", endpoint_buffer);
/* Turn off red LED to signal device is ready */
DigitalOut ext_red(D5, 1);
}
#endif
print_heap_stats();
}
void client_unregistered() {
registered = false;
pc.printf("unregistered\n");
}
int main() {
pc.baud(115200);
mbed_trace_init();
mbed_trace_mutex_wait_function_set( serial_out_mutex_wait );
mbed_trace_mutex_release_function_set( serial_out_mutex_release );
#ifdef MYCLOUDAPP
set_time(1486961386);
pc.printf("starting thread1 %s:%d-->%s()\n", __FILE__, __LINE__, __func__);
t_oled.start(oled);
pc.printf("starting thread2 %s:%d-->%s()\n", __FILE__, __LINE__, __func__);
t_mag.start(mag);
pc.printf("starting thread3 %s:%d-->%s()\n", __FILE__, __LINE__, __func__);
t_acc.start(acc);
#endif
#ifdef MBED_APPLICATION_SHIELD
/* Initialize the LCD on the mbed App Shield if present */
lcd = new C12832(D11, D13, D12, D7, D10);
/* Keep the red LED on */
DigitalOut ext_red(D5, 0);
/* Clear screen and write status */
lcd->cls();
lcd->locate(0, 3);
lcd->printf("Cloud Client: Initializing");
#endif
btn.fall(&fall);
cls.fall(&unregister);
// magic string used from testcase too
pc.printf("Starting example client\n");
// Print some statistics of the object sizes and heap memory consumption
// if the MBED_HEAP_STATS_ENABLED is defined.
// print_m2mobject_stats();
print_heap_stats();
int connect_success = -1;
#if MBED_CONF_APP_NETWORK_INTERFACE == WIFI
pc.printf("WiFi is NOT yet supported..Exiting the application\n");
return 1;
#elif MBED_CONF_APP_NETWORK_INTERFACE == ETHERNET
pc.printf("Using Ethernet\n");
connect_success = eth.connect();
network_handler = ð
#endif
#ifdef MESH
pc.printf("Mesh is NOT yet supported..Exiting the application\n");
return 1;
#endif
const char *ip_addr = network_handler->get_ip_address();
const char *mac_addr = network_handler->get_mac_address();
if (ip_addr && mac_addr) {
pc.printf("IP address %s\n", ip_addr);
pc.printf("MAC address %s\n", mac_addr);
} else {
pc.printf("[main] No IP/MAC address\n");
connect_success = -1;
}
if (connect_success == 0) {
pc.printf("Connected to Network successfully\n");
} else {
pc.printf("Connection to Network Failed %d!\n", connect_success);
pc.printf("Exiting application\n");
return 1;
}
print_heap_stats();
Ticker status_ticker;
status_ticker.attach(&toggleLed, 1.0f);
pc.printf("Start simple mbed Cloud Client\n");
print_heap_stats();
#ifndef MBED_CONF_APP_DEVELOPER_MODE
#ifdef MBED_APPLICATION_SHIELD
lcd->cls();
lcd->locate(0, 3);
lcd->printf("Cloud Client: Provisioning");
#endif
/////////// Device Factory Flow ///////////
Thread *factoryFlow;
osStatus rtosStatus;
// kick the factory flow in a new task
factoryFlow = new Thread(osPriorityHigh, FACTORY_STACK_SIZE);
rtosStatus = factoryFlow->start(provision_device);
if (rtosStatus != osOK) {
pc.printf("Failed forking device factory thread (rc = %d)\n", rtosStatus);
return 1;
}
/**
* The main task sits and waits until device is provisioned.
*/
do {
Thread::wait(1000);
} while (provisioned == false);
rtosStatus = factoryFlow->join();
if (rtosStatus != osOK) {
pc.printf("Failed joining device factory thread (rc = %d)\n", rtosStatus);
return 1;
}
if (device_provision_status == DEVICE_PROVISION_FAILED) {
pc.printf("Provisioning Failed. Exiting application...\n");
return 1;
} else if (device_provision_status == DEVICE_PROVISIONED) {
pc.printf("Your device is provisioned. Continuing.\n");
} else if (device_provision_status == DEVICE_ALREADY_PROVISIONED) {
pc.printf("Your device is already provisioned. Continuing.\n");
}
print_heap_stats();
#endif
#ifdef MBED_APPLICATION_SHIELD
lcd->cls();
lcd->locate(0, 3);
lcd->printf("Cloud Client: Connecting");
#endif
print_heap_stats();
bool setup = false;
M2MObjectList obj_list;
// we create our button and LED resources
ButtonResource button_resource;
LedResource led_resource;
#ifdef MBED_CLOUD_CLIENT_UPDATE_ID
/* When this configuration flag is set, the manufacturer, model number
and serial number is taken from update_default_resources.c
*/
#else
M2MDevice *device_object = M2MInterfaceFactory::create_device();
// make sure device object was created successfully
if (device_object) {
// add resourceID's to device objectID/ObjectInstance
device_object->create_resource(M2MDevice::Manufacturer, "Manufacturer");
device_object->create_resource(M2MDevice::DeviceType, "Type");
device_object->create_resource(M2MDevice::ModelNumber, "ModelNumber");
device_object->create_resource(M2MDevice::SerialNumber, "SerialNumber");
obj_list.push_back(device_object);
}
#endif
obj_list.push_back(button_resource.get_object());
obj_list.push_back(led_resource.get_object());
// Add some test resources to measure memory consumption.
// This code is activated only if MBED_HEAP_STATS_ENABLED is defined.
create_m2mobject_test_set(obj_list);
client.add_objects(obj_list);
client.on_registered(&client_registered);
client.on_unregistered(&client_unregistered);
client.on_error(&error);
client.set_update_callback(&led_resource);
pc.printf("Connecting to %s:%d\n", MBED_CLOUD_CLIENT_CLOUD_ADDRESS, MBED_CLOUD_CLIENT_CLOUD_PORT);
print_heap_stats();
setup = client.setup(network_handler);
if (!setup) {
pc.printf("Client setup failed\n");
return 1;
}
#ifdef MBED_CLOUD_CLIENT_SUPPORT_UPDATE
/* Set callback functions for authorizing updates and monitoring progress.
Code is implemented in update_ui_example.cpp
Both callbacks are completely optional. If no authorization callback
is set, the update process will procede immediately in each step.
*/
client.set_update_authorize_handler(update_authorize);
client.set_update_progress_handler(update_progress);
#endif
registered = true;
while (true) {
#ifdef MYCLOUDAPP
print_current_time();
#endif
updates.wait(25000);
if (registered) {
if (!clicked) {
// In case you are using UDP mode, to overcome NAT firewall issue , this example
// application sends keep alive pings every 25 seconds so that the application doesnt
// lose network connection over UDP. In case of TCP, this is not required as long as
// TCP keepalive is properly configured to a reasonable value, default for mbed Cloud
// Client is 300 seconds.
#if defined(MBED_CLOUD_CLIENT_TRANSPORT_MODE_UDP) || \
defined(MBED_CLOUD_CLIENT_TRANSPORT_MODE_UDP_QUEUE)
client.keep_alive();
#endif
}
} else {
break;
}
if (clicked) {
clicked = false;
button_resource.handle_button_click();
}
}
client.close();
status_ticker.detach();
}
|
e11535ddd0f72aae977c9b0b9a6b23b405d1d7b1
|
[
"Markdown",
"C",
"C++",
"Shell"
] | 9
|
C
|
dlfryar-zz/mbed-cloud-k64f-example
|
c636de6f4c8b3c6560d4204f31b236cc9a9616db
|
2f262492af1614c8e427a92c1960a89ae260ec77
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import scrapy
import pandas as pd
import numpy as np
from crawler51job.items import Crawler51JobItem
class Spider51jobSpider(scrapy.Spider):
name = 'spider51job'
allowed_domains = ['51job.com']
start_urls = [
'https://search.51job.com/list/010000,000000,0000,32,9,99,Java%25E5%25BC%2580%25E5%258F%2591,2,1.html']
def parse(self, response):
item = Crawler51JobItem()
item['position'] = response.xpath('//div[@class="el"]/p[@class="t1 "]/span/a/@title').extract()
item['company'] = response.xpath('//div[@class="el"]/span[@class="t2"]/a/@title').extract()
item['place'] = response.xpath('//div[@class="el"]/span[@class="t3"]/text()').extract()
item['salary'] = response.xpath('//div[@class="el"]/span[@class="t4"]/text()').extract()
yield item
<file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from pandas import DataFrame
class Crawler51JobPipeline(object):
def process_item(self, item, spider):
# 将取出的信息放到数据框
jobInfo = DataFrame([item['position'], item['company'], item['place'], item['salary']]).T
# 设置列名
jobInfo.columns = ['职位名', '公司名', '工作地点', '薪资']
# 将数据保存到本地
jobInfo.to_csv('jobInfo.csv', encoding='gbk') # 设置编码格式,防止乱码
return item
|
94f73d42211c2ad029ddecf1d13ab640647d7442
|
[
"Python"
] | 2
|
Python
|
point6013/crawler51job
|
ce96d47e5600e2ab78e0ddd0b14d743c2b18d827
|
44a3f26724a73dfe182f70872336e8bfab9ecc77
|
refs/heads/aaa
|
<repo_name>rachanaahire/Angular-forms<file_sep>/src/app/tdfform/tdfform.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';
@Component({
selector: 'app-tdfform',
templateUrl: './tdfform.component.html',
styleUrls: ['./tdfform.component.css']
})
export class TdfformComponent implements OnInit {
choices = ['IT', 'Sales' , 'Marketing'];
empModel = new Employee('', '', 0 , '', '', true);
onSubmit() {
}
constructor() { }
ngOnInit() {
}
}
<file_sep>/src/app/serviceform.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Employee } from './employee';
@Injectable({
providedIn: 'root'
})
export class ServiceformService {
employees: Array<Employee> = [];
constructor(private _http: HttpClient) { }
/*url= "/assets/emp.json";
getEmp():Observable<Employee[]>{
return this._http.get<Employee[]>(this.url);
}*/
save(emp: Employee) {
this.employees.push(emp);
// console.log(this.employees);
}
getEmp() {
return this.employees;
}
delete(ind) {
this.employees.splice(ind, 1);
}
}
<file_sep>/src/app/viewdata/viewdata.component.ts
import { Component, OnInit } from '@angular/core';
import { ServiceformService } from '../serviceform.service';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-viewdata',
templateUrl: './viewdata.component.html',
styleUrls: ['./viewdata.component.css']
})
export class ViewdataComponent implements OnInit {
emp = [];
ngOnInit() {
// console.warn( localStorage.getItem('hello'))
this.emp = this._empService.getEmp();
}
constructor(private _empService: ServiceformService, private router: Router, private route: ActivatedRoute) { }
onSelect(ind) {
this.router.navigate(['/add_data', ind]);
// this._empService.update(ind);
}
onDelete(ind) {
this._empService.delete(ind);
// console.log
}
}
<file_sep>/src/app/serviceform.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { ServiceformService } from './serviceform.service';
describe('ServiceformService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: ServiceformService = TestBed.get(ServiceformService);
expect(service).toBeTruthy();
});
});
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ViewdataComponent } from './viewdata/viewdata.component';
import { TdfformComponent } from './tdfform/tdfform.component';
import { ReactiveformComponent } from './reactiveform/reactiveform.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'view', component: ViewdataComponent },
{ path: 'add', component: TdfformComponent },
{ path: 'add_data/:id', component: ReactiveformComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/reactiveform/reactiveform.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ServiceformService } from '../serviceform.service';
import { Router, ActivatedRoute } from '@angular/router';
import { format } from 'url';
@Component({
selector: 'app-reactiveform',
templateUrl: './reactiveform.component.html',
styleUrls: ['./reactiveform.component.css']
})
export class ReactiveformComponent implements OnInit {
constructor(private _empService: ServiceformService, private router: Router, private route: ActivatedRoute) { }
public empId:string;
ngOnInit() {
this.empId = this.route.snapshot.paramMap.get('id');
/*this.reactForm.setValue({
name: this.empName,
email: '',
phone: '',
department: '',
timepref: '',
isemployee:false
})*/
//console.log(this.empId)
if (this.empId && this.empId !== 'null' ) {
const emp = this._empService.employees[this.empId];
// console.log(emp);
this.reactForm.setValue(emp);
}
}
choices = ['IT', 'Sales', 'Marketing'];
get f() {
//console.log(this.reactForm.controls)
return this.reactForm.controls
}
reactForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')),
phone: new FormControl('', Validators.required),
department: new FormControl('', Validators.required),
timepref: new FormControl('', Validators.required),
isemployee: new FormControl(null, Validators.required)
});
/*onSubmit() {
console.log(this.reactForm.value)
}*/
loadData() {
this.reactForm.setValue({
name: '<NAME>',
email: '<EMAIL>',
phone: 1234567890,
department: 'Marketing',
timepref: 'evening',
isemployee: true
});
}
submit() {
// const newEmp: Employee= this.reactForm.value;
// let x =this.reactForm.value
// localStorage.setItem('hello', JSON.stringify(x));
if (this.reactForm.valid) {
if (this.empId !== 'null') {
this._empService.employees[this.empId] = this.reactForm.value;
} else {
this._empService.save(this.reactForm.value);
}
}
this.reactForm.reset();
}
}
|
e08958d67d045124e9f77551d2626e414095053c
|
[
"TypeScript"
] | 6
|
TypeScript
|
rachanaahire/Angular-forms
|
ec1a9aafa5c5fbcac2a673d3e23448b19d616f77
|
211b523fd385516f70c3316d9e57588bf0a6a67e
|
refs/heads/master
|
<repo_name>AabhasDhaubanja/unlm<file_sep>/lib/queries.js
import { gql } from "@apollo/client";
export const INDEX_QUERY = gql`
query {
arrivals {
Product {
id
name
price
Images {
url
}
}
}
}
`;
export const GET_PRODUCT = gql`
query Product($id: ID!) {
product(id: $id) {
id
name
price
Images {
id
url
}
categoryId
}
}
`;
export const GET_PRODUCT_PAGE = gql`
query ProductPage($id: ID!) {
productPage(id: $id) {
product {
id
name
price
Images {
url
}
categoryId
}
similar {
id
name
price
Images {
url
}
}
}
}
`;
export const SEARCH_QUERY = gql`
query Products($text: String!) {
search(text: $text) {
id
name
price
Images {
url
}
}
}
`;
export const GET_CATEGORIES = gql`
query {
categories {
id
name
isRoot
superId
}
}
`;
export const GET_CATEGORY = gql`
query Category($id: ID!) {
products(categoryId: $id) {
id
name
price
Images {
url
}
}
}
`;
export const ADD_PRODUCT = gql`
mutation AddProduct(
$name: String!
$price: Int!
$categoryId: ID!
$files: [Upload]
) {
addProduct(
name: $name
price: $price
categoryId: $categoryId
files: $files
) {
name
price
categoryId
}
}
`;
export const UPDATE_PRODUCT = gql`
mutation UpdateProduct(
$id: ID!
$name: String!
$price: Int!
$categoryId: ID!
$files: [Upload]
) {
addProduct(
id: $id
name: $name
price: $price
categoryId: $categoryId
files: $files
) {
name
price
categoryId
}
}
`;
export const DELETE_IMAGE = gql`
mutation DeleteImage($id: ID!) {
deleteImage(id: $id) {
status
code
}
}
`;
export const DELETE_PRODUCT = gql`
mutation DeleteProduct($id: ID!) {
deleteProduct(id: $id) {
status
}
}
`;
<file_sep>/pages/discover/[id].js
import Link from "next/link";
import { useQuery } from "@apollo/client";
import { initializeApollo } from "../../lib/apolloClient";
import Products from "../../client/components/Products";
import { GET_CATEGORY } from "../../lib/queries";
const Discover = ({ id }) => {
const { loading, error, data } = useQuery(GET_CATEGORY, {
variables: { id },
});
if (loading) return "Loading ...";
if (error) return JSON.stringify(error);
const { products } = data;
return (
<div className="pb-5">
<div
className="container py-5 px-5 d-flex justify-content-end"
fluid="true"
>
<Link href="/categories">
<u className="px-5" style={{ cursor: "pointer", fontSize: "1.5rem" }}>
All Categories
</u>
</Link>
</div>
<Products products={products} />
</div>
);
};
export async function getServerSideProps({ params: { id } }) {
const apolloClient = initializeApollo();
await apolloClient.query({
query: GET_CATEGORY,
variables: { id },
});
return {
props: {
initialApolloState: apolloClient.cache.extract(),
id,
},
};
}
export default Discover;
<file_sep>/lib/dataCenter/images.js
const { AuthenticationError } = require("apollo-server-express");
module.exports = (models, user) => {
return {
deleteImage: async ({ id }) => {
if (user.error) throw new AuthenticationError(user.error);
const image = await models.Image.findOne({
where: {
id,
},
});
await image.destroy();
},
};
};
<file_sep>/server/seeders/20200829084213-demo-users.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
/**
* Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: '<NAME>',
* isBetaMember: false
* }], {});
*/
// The passwords are the same as the emails.
await queryInterface.bulkInsert(
"Users",
[
{
username: "john",
email: "<EMAIL>",
password:
<PASSWORD>",
role: "admin",
createdAt: new Date(),
updatedAt: new Date(),
},
{
username: "ben",
email: "<EMAIL>",
password:
<PASSWORD>",
role: "deliverer",
createdAt: new Date(),
updatedAt: new Date(),
},
{
username: "liza",
email: "<EMAIL>",
password:
<PASSWORD>",
role: "user",
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
down: async (queryInterface, Sequelize) => {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
await queryInterface.bulkDelete("Users", null, {});
},
};
<file_sep>/pages/login.js
import Link from "next/link";
import { useState } from "react";
import axios from "axios";
import { loggedIn } from "../client/hocs/redirect";
const Login = () => {
const [state, setState] = useState({
email: null,
password: null,
});
const [loading, setLoading] = useState(false);
const enterHandler = ({ keyCode }) => {
if (keyCode === 13) {
loginHandler();
}
};
const loginHandler = () => {
setLoading(true);
axios
.post(`/auth/login`, { ...state }, { withCredentials: true })
.then((_) => {
window.location.reload();
})
.catch((err) => alert(err))
.finally(() => setLoading(false));
};
const emailHandler = (e) => {
setState({
...state,
email: e.target.value,
});
};
const passwordHandler = (e) => {
setState({
...state,
password: e.target.value,
});
};
return (
<div className="py-5">
<div
style={{
height: "50vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<div className="container">
<div className="mb-3">
<label htmlFor="loginEmail" className="form-label">
Email address
</label>
<input
onChange={emailHandler}
type="email"
className="form-control"
id="loginEmail"
aria-describedby="emailHelp"
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label htmlFor="loginPassword" className="form-label">
Password
</label>
<input
onChange={passwordHandler}
onKeyUp={enterHandler}
type="password"
className="form-control"
id="loginPassword"
aria-describedby="emailHelp"
/>
</div>
<button onClick={loginHandler} className="btn btn-dark">
{loading ? (
<div className="spinner-border text-light" role="status">
<span className="visually-hidden"> </span>
</div>
) : (
<span>SignIn</span>
)}
</button>
<div className="pointer py-5">
<span>Don't have an account?</span>
<Link href="/comming">
<u>
{" "}
<b>Sign up</b> here
</u>
</Link>
</div>
</div>
</div>
</div>
);
};
export default loggedIn(Login);
<file_sep>/client/components/index/MyCarousel.js
const MyCarousel = () => {
return (
<div className="carouselContainer">
<img
className="carouselImage"
src={`/index_page/carousel.jpg`}
alt="Unlm Offcial Image"
/>
</div>
);
};
export default MyCarousel;
<file_sep>/pages/admin/new.js
import { useState } from "react";
import { useMutation, useQuery } from "@apollo/client";
import { initializeApollo } from "../../lib/apolloClient";
import { GET_CATEGORIES, ADD_PRODUCT } from "../../lib/queries";
import { nonAdmin } from "../../client/hocs/redirect";
const New = () => {
const [addProduct] = useMutation(ADD_PRODUCT);
const { loading, error, data } = useQuery(GET_CATEGORIES);
// For the loading animation on create
const [createLoading, setLoading] = useState(false);
const [state, setState] = useState({
name: "<NAME>",
price: 100,
categoryId: "2",
});
const inputHandler = ({ target: { value, name } }) => {
let newState = { ...state };
newState[name] = value;
setState(newState);
};
const imageHandler = ({ target: { validity, files } }) => {
if (validity.valid)
setState({
...state,
files,
});
};
const createHandler = async () => {
setLoading(true);
const product = await addProduct({
variables: {
...state,
price: parseInt(state.price),
categoryId: state.categoryId.toString(),
},
});
setLoading(false);
window.location.href = "/discover/1";
};
// This is for the GraphQl Query GET_CATEGORIES
if (loading) return "Loading...";
if (error) return `Error! ${error.message}`;
// Removing the root category
const { categories } = data;
const cats = categories.filter((cat) => cat.isRoot !== true);
return (
<div className="container py-5 mt-5">
<div className="mb-3">
<label htmlFor="newProductName" className="form-label">
Enter name
</label>
<input
onChange={inputHandler}
placeholder="Enter Name"
name="name"
type="text"
className="form-control"
id="newProductName"
aria-describedby="productName"
/>
</div>
<div className="mb-3">
<label htmlFor="newProductPrice" className="form-label">
Price
</label>
<input
onChange={inputHandler}
placeholder="Enter Price"
name="price"
type="number"
className="form-control"
id="newProductPrice"
aria-describedby="productPrice"
/>
</div>
<div className="mb-3">
<label htmlFor="newProductCategory" className="form-label">
Category
</label>
<select
onChange={inputHandler}
name="categoryId"
className="form-select"
aria-label="Default select example"
>
{cats.map((cat) => (
<option key={cat.id} value={cat.id}>
{cat.name}
</option>
))}
</select>
</div>
<div className="mb-3">
<label htmlFor="newProductImages" className="form-label">
Images
</label>
<input
type="file"
placeholder="Upload Images"
onChange={imageHandler}
id="newProductImages"
className="form-control"
multiple
required
/>
</div>
<button className="btn btn-dark" type="submit" onClick={createHandler}>
{createLoading ? (
<div className="spinner-border text-light" role="status">
<span className="visually-hidden"></span>
</div>
) : (
<span>Create</span>
)}
</button>
</div>
);
};
export async function getServerSideProps() {
const apolloClient = initializeApollo();
await apolloClient.query({
query: GET_CATEGORIES,
});
return {
props: {
initialApolloState: apolloClient.cache.extract(),
},
};
}
export default nonAdmin(New);
<file_sep>/pages/profile.js
import { useState } from "react";
import axios from "axios";
import { FaUserCircle } from "react-icons/fa";
import { loggedOut } from "../client/hocs/redirect";
const Profile = () => {
const [loading, setLoading] = useState(false);
const logoutHandler = () => {
setLoading(true);
axios
.post(`/auth/logout`, {
withCredentials: true,
})
.then((res) => {
console.log(res);
window.location.reload();
})
.catch((err) => {
alert(err);
})
.finally(() => setLoading(false));
};
return (
<div className="d-flex justify-content-center py-5">
<div>
<div className="d-flex justify-content-center py-5 display-1">
<FaUserCircle />
</div>
<div className="d-flex justify-content-center">
<button className="btn btn-danger" onClick={logoutHandler}>
{loading ? (
<div class="spinner-border text-light" role="status">
<span class="visually-hidden"> </span>
</div>
) : (
<span>Logout</span>
)}
</button>
</div>
</div>
</div>
);
};
export default loggedOut(Profile);
<file_sep>/pages/admin/update/[id].js
import { useEffect, useState } from "react";
import { useMutation, useQuery } from "@apollo/client";
import { nonAdmin } from "../../../client/hocs/redirect";
import { initializeApollo } from "../../../lib/apolloClient";
import {
GET_PRODUCT,
UPDATE_PRODUCT,
DELETE_IMAGE,
DELETE_PRODUCT,
} from "../../../lib/queries";
import Loading from "../../../client/components/Loading";
const Update = ({ id, ...rest }) => {
const [updateLoading, setUpdateLoading] = useState(false);
const [deleteLoading, setDeleteLoading] = useState(false);
// The problem right now is that the state isn't set to the product values in the beginning
// also fix the categories
// and finally the image upload
// :)
const [state, setState] = useState({
name: "Default Product",
price: 100,
});
const [updateProduct] = useMutation(UPDATE_PRODUCT);
const [deleteProduct] = useMutation(DELETE_PRODUCT);
const [deleteImage] = useMutation(DELETE_IMAGE);
const { loading, error, data } = useQuery(GET_PRODUCT, {
variables: { id },
});
if (loading) return <Loading />;
if (error) return JSON.stringify(error);
const {
product: { name, price, categoryId, Images },
} = data;
const inputHandler = ({ target: { value, name } }) => {
let newState = { ...state };
newState[name] = value;
setState(newState);
};
const imageHandler = ({ target: { validity, files } }) => {
if (validity.valid)
setState({
...state,
files,
});
};
const updateHandler = async () => {
if (confirm("Are you sure you want to update this product?")) {
await updateProduct({
variables: {
...state,
},
});
}
};
const deleteImageHandler = async (imageId) => {
if (confirm("Are you sure you want to delete this image?")) {
await deleteImage({
variables: {
id: imageId,
},
});
window.location.reload();
}
};
const deleteHandler = async () => {
setDeleteLoading(true);
if (confirm("Are you sure you want to delete this product?")) {
await deleteProduct({
variables: {
id,
},
});
}
setDeleteLoading(false);
window.location.href = "/discover/1";
};
return (
<div className="container py-5 mt-5">
<div className="mb-3">
<label htmlFor="newProductName" className="form-label">
Enter name
</label>
<input
onChange={inputHandler}
placeholder={name}
name="name"
type="text"
className="form-control"
id="newProductName"
aria-describedby="productName"
/>
</div>
<div className="mb-3">
<label htmlFor="newProductPrice" className="form-label">
Price
</label>
<input
onChange={inputHandler}
placeholder={price}
name="price"
type="number"
className="form-control"
id="newProductPrice"
aria-describedby="productPrice"
/>
</div>
<div className="mb-3">
<label htmlFor="newProductCategory" className="form-label">
Category
</label>
<input
onChange={inputHandler}
placeholder={categoryId}
name="categoryId"
type="number"
className="form-control"
id="newProductCategory"
aria-describedby="productCategory"
/>
</div>
<div className="mb-3">
<label htmlFor="newProductImages" className="form-label">
Add Images
</label>
<input
type="file"
placeholder="Upload Images"
onChange={imageHandler}
id="newProductImages"
className="form-control"
multiple
required
/>
</div>
<div className="container py-5 px-0">
<div className="row">
<h4>Current Images</h4>
</div>
{Images.map(({ id, url }) => (
<div key={id} className="row">
<div className="col-6">
<img
src={`/products_page/${url}`}
style={{ width: "100%", objectFit: "cover" }}
/>
</div>
<div className="col-6 d-flex justify-content-center align-items-center">
<button
onClick={() => deleteImageHandler(id)}
className="btn btn-danger ms-3"
>
Delete Image
</button>
</div>
</div>
))}
</div>
<button className="btn btn-dark" type="submit" onClick={updateHandler}>
{updateLoading ? (
<div className="spinner-border text-light" role="status">
<span className="visually-hidden"></span>
</div>
) : (
<span>Update</span>
)}
</button>
<button onClick={deleteHandler} className="btn btn-danger ms-3">
{deleteLoading ? (
<div className="spinner-border text-light" role="status">
<span className="visually-hidden"></span>
</div>
) : (
<span>Delete Product</span>
)}
</button>
</div>
);
};
export async function getServerSideProps({ params: { id } }) {
const apolloClient = initializeApollo();
await apolloClient.query({
query: GET_PRODUCT,
variables: { id },
});
return {
props: {
initialApolloState: apolloClient.cache.extract(),
id,
},
};
}
export default nonAdmin(Update);
<file_sep>/server/seeders/20200829124749-demo-images.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
/**
* Add seed commands here.
*
* Example:
* await queryInterface.bulkInsert('People', [{
* name: '<NAME>',
* isBetaMember: false
* }], {});
*/
await queryInterface.bulkInsert(
"Images",
[
{
url: "/products/_MG_9485.jpg",
imageableId: 1,
imageableType: "product",
createdAt: new Date(),
updatedAt: new Date(),
},
{
url: "/products/_MG_9532.jpg",
imageableId: 2,
imageableType: "product",
createdAt: new Date(),
updatedAt: new Date(),
},
{
url: "/products/_MG_9492.jpg",
imageableId: 3,
imageableType: "product",
createdAt: new Date(),
updatedAt: new Date(),
},
{
url: "/products/_MG_9507-Recovered.jpg",
imageableId: 4,
imageableType: "product",
createdAt: new Date(),
updatedAt: new Date(),
},
],
{}
);
},
down: async (queryInterface, Sequelize) => {
/**
* Add commands to revert seed here.
*
* Example:
* await queryInterface.bulkDelete('People', null, {});
*/
await queryInterface.bulkDelete("Images", null, {});
},
};
<file_sep>/client/components/Products.js
import Link from "next/link";
const Products = ({ title, products }) => {
return (
<>
{title ? (
<div className="container">
<div className="row justify-content-center p-5 mt-5">{title}</div>
</div>
) : null}
{products.length ? (
<div className="container">
<div className="row">
{products.map((product) => (
<div
key={product.id}
className="col-lg-3 col-md-4 col-sm-6 col-12 d-flex justify-content-center pb-5"
>
<Link href="/products/[id]" as={`/products/${product.id}`}>
<div
className="card"
style={{ width: "18rem", cursor: "pointer" }}
>
<div className="d-flex justify-content-center">
<img
style={{
width: "100%",
height: "auto",
}}
src={`/products_page${product.Images[0].url}`}
/>
</div>
<div className="card-body">
<div className="card-title">{product.name}</div>
<div className="card-text">
Some quick example text to build on the card title and
make up the bulk of the card's content.
</div>
<button className="btn btn-primary">View</button>
</div>
</div>
</Link>
</div>
))}
</div>
</div>
) : (
<div
style={{
height: "40vh",
width: "100vw",
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "red",
fontSize: "2rem",
fontWeight: "600",
}}
>
404 - Oops! No products found
</div>
)}
</>
);
};
export default Products;
<file_sep>/server/models/wishlistproduct.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class WishlistProduct extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
}
}
WishlistProduct.init(
{
WishlistId: {
type: DataTypes.INTEGER,
references: {
model: sequelize.models.Wishlist,
key: "id",
},
},
ProductId: {
type: DataTypes.INTEGER,
references: {
model: sequelize.models.Product,
key: "id",
},
},
},
{
sequelize,
modelName: "WishlistProduct",
}
);
return WishlistProduct;
};
<file_sep>/server/models/product.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Product extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
this.hasMany(models.Image, {
foreignKey: "imageableId",
onDelete: "CASCADE",
hooks: true,
scope: {
imageableType: "product",
},
});
this.hasMany(models.Arrival, {
foreignKey: "productId",
onDelete: "CASCADE",
hooks: true,
});
this.belongsTo(models.Category, {
foreignKey: "categoryId",
});
this.belongsToMany(models.Bill, {
through: "BillProducts",
});
this.belongsToMany(models.Cart, {
through: "CartProducts",
});
this.belongsToMany(models.Wishlist, {
through: "WishlistProducts",
});
}
}
Product.init(
{
name: DataTypes.STRING,
price: DataTypes.INTEGER,
categoryId: DataTypes.INTEGER,
},
{
sequelize,
modelName: "Product",
}
);
return Product;
};
<file_sep>/pages/search/[text].js
import { initializeApollo } from "../../lib/apolloClient";
import { useQuery } from "@apollo/client";
import { SEARCH_QUERY } from "../../lib/queries";
import Products from "../../client/components/Products";
import Loading from "../../client/components/Loading";
const Search = ({ text }) => {
const { loading, error, data } = useQuery(SEARCH_QUERY, {
variables: { text },
});
if (loading) return <Loading />;
if (error) return JSON.stringify(error);
const { search } = data;
return (
<div className="pb-5">
<Products
title={<h1>Showing search results for "{text}"</h1>}
products={search}
/>
</div>
);
};
export async function getServerSideProps({ params: { text } }) {
const apolloClient = initializeApollo();
await apolloClient.query({
query: SEARCH_QUERY,
variables: { text },
});
return {
props: {
initialApolloState: apolloClient.cache.extract(),
text,
},
};
}
export default Search;
<file_sep>/lib/helpers/addProducts.js
module.exports = (models) =>
async function addProducts(id) {
let category = await models.Category.findOne({
where: {
id,
},
include: [
{
model: models.Product,
include: {
model: models.Image,
},
},
{
model: models.Category,
},
],
});
if (category) {
const { Products, Categories } = category;
if (Categories.length == 0) {
return [...Products];
}
let products = [];
for (const category of Categories) {
const moreProducts = await addProducts(category.id);
products = [...products, ...moreProducts];
}
return [...products, ...Products];
}
return [];
};
<file_sep>/pages/categories.js
import Link from "next/link";
import { useQuery } from "@apollo/client";
import { initializeApollo } from "../lib/apolloClient";
import { GET_CATEGORIES } from "../lib/queries";
const Categories = () => {
const { loading, error, data } = useQuery(GET_CATEGORIES);
if (loading) return "Loading ...";
if (error) return JSON.stringify(error);
const { categories } = data;
const root = categories.find((cat) => cat.isRoot == true);
// helper function
const findChildren = (id) => {
const array = categories.filter((cat) => {
return cat.superId == id;
});
return array;
};
// traverse function
const traverse = (id, depth) => {
const children = findChildren(id);
const current = categories.find((cat) => cat.id == id);
const style = {
fontSize: `${3 - depth * 0.7}rem`,
listStyleType: "none",
textAlign: "center",
};
// terminating condition
if (children.length == 0)
return (
<div style={style} key={current.id}>
<Link
key={current.id}
href="/discover/[id]"
as={`/discover/${current.id}`}
>
<a className="categoryLink">{current.name}</a>
</Link>
</div>
);
let organizedChildren = [];
for (const child of children) {
organizedChildren = [...organizedChildren, traverse(child.id, depth + 1)];
}
return (
<div style={style} key={current.id}>
<Link
key={current.id}
href="/discover/[id]"
as={`/discover/${current.id}`}
>
<a className="categoryLink">{current.name}</a>
</Link>
<div>{organizedChildren.map((child) => child)}</div>
</div>
);
};
// The actual jsx returned by this component
return (
<div className="py-5 d-flex justify-content-center">
{traverse(root.id, 0)}
</div>
);
};
export async function getServerSideProps() {
const apolloClient = initializeApollo();
await apolloClient.query({
query: GET_CATEGORIES,
});
return {
props: {
initialApolloState: apolloClient.cache.extract(),
},
};
}
export default Categories;
<file_sep>/client/layouts/Default.js
import { useContext } from "react";
import { AuthContext } from "../hocs/AuthProvider";
import Navbar from "../components/navbars/DefaultNavbar";
import AdminNav from "../components/navbars/AdminNav";
import Footer from "../components/Footer";
export default function Default(props) {
const { user } = useContext(AuthContext);
let navbar = <Navbar />;
if (user && user.role) {
if (user.role === "admin" || user.role === "deliverer") {
navbar = <AdminNav />;
}
}
React.useEffect(() => {}, []);
return (
<div>
{navbar}
<div>{props.children}</div>
<Footer />
</div>
);
}
<file_sep>/client/components/index/MyVideo.js
const MyVideo = () => {
return (
<div className="d-flex justify-content-center py-5 my-5">
<video
id="unlmVideo"
className="d-block"
style={{ width: "100vw", border: "none", outline: "none" }}
loop
autoPlay
muted
controls
>
<source src={`/index_page/unlm.mp4`} />
</video>
</div>
);
};
export default MyVideo;
<file_sep>/client/components/index/MenWomenKids.js
const MenWomenKids = () => {
let genders = [
{
name: (
<>
<div className="row justify-content-center">
<h1>Men</h1>
</div>
</>
),
image: "/index/men.jpg",
key: "men",
},
{
name: (
<>
<div className="row justify-content-center">
<h1>Women</h1>
</div>
</>
),
image: "/index/women.jpeg",
key: "women",
},
];
return (
<div className="container-fluid p-5 my-5">
<div>
{genders.map((gender) => (
<div key={gender.key} className="col-6 d-flex justify-content-center">
<div
style={{
background: `url("${process.env.NEXT_PUBLIC_SERVER}${gender.image}")`,
backgroundSize: "cover",
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center",
color: "white",
height: "600px",
}}
>
<div>
<span style={{ fontWeight: "900", textTransform: "uppercase" }}>
{gender.name}
</span>
<div className="row justify-content-center">SHOP NOW</div>
</div>
</div>
</div>
))}
{/* <div className="display-1">SHOP NOW</div> */}
</div>
</div>
);
};
export default MenWomenKids;
<file_sep>/client/components/index/IndexFooter.js
const IndexFooter = () => {
return (
<div className="container">
<div className="row d-flex justify-content-center text-center">
<h1>
<b>
{/* <div className="col-12 py-4">KATHMANDU</div>
<div className="col-12 py-4">TOKYO</div>
<div className="col-12 py-4">SYDNEY</div>
<div className="col-12 py-4">PARIS</div> */}
<div className="col-12 py-4">WORLD WIDE</div>
</b>
<div className="display-4 col-12 py-4">RISE OF UNLM.</div>
</h1>
</div>
</div>
);
};
export default IndexFooter;
<file_sep>/server.js
require("dotenv").config();
const express = require("express");
const next = require("next");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const { ApolloServer } = require("apollo-server-express");
const jwt = require("jsonwebtoken");
const dataCenter = require("./lib/dataCenter");
const models = require("./server/models");
const authRouter = require("./server/routes/auth");
const typeDefs = require("./lib/typeDefs");
const resolvers = require("./lib/resolvers");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
// const app = next({});
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(express.static("public"));
server.use(morgan("dev"));
server.use(express.json());
server.use(cookieParser());
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
let accessToken = null;
if (req.headers.authorization) {
const [_, token] = req.headers.authorization.split(" ");
accessToken = token;
}
let error = null,
user = {};
if (accessToken && accessToken.length > 5) {
jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, (err, usr) => {
error = err;
user = usr;
});
} else {
error = "Token not found!";
}
return {
models,
dataCenter: dataCenter(models, { ...user, error }),
};
},
});
apolloServer.applyMiddleware({ app: server });
server.use("/auth", authRouter);
server.get("*", (req, res) => handle(req, res));
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
<file_sep>/lib/apolloClient.js
// import { useMemo } from "react";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { concatPagination } from "@apollo/client/utilities";
import { createUploadLink } from "apollo-upload-client";
import { setContext } from "@apollo/client/link/context";
import { onError } from "@apollo/client/link/error";
let apolloClient;
function createApolloClient(token) {
const httpLink = createUploadLink({
uri: `http://localhost:3000/graphql`,
credentials: "same-origin",
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
};
});
const link = onError(
({ graphQLErrors, networkError, response, operation }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.error(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.error(`[Network error]: ${networkError}`);
if (response) response.errors = null;
}
);
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: link.concat(authLink.concat(httpLink)),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
},
},
}),
});
}
export function initializeApollo(initialState = null, token) {
const _apolloClient = apolloClient ?? createApolloClient(token);
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// gets hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract();
// Restore the cache using the data passed from getStaticProps/getServerSideProps
// combined with the existing cached data
_apolloClient.cache.restore({ ...existingCache, ...initialState });
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === "undefined") return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function useApollo(initialState, token) {
// const store = useMemo(() => initializeApollo(initialState), [initialState]);
const store = initializeApollo(initialState, token);
return store;
}
<file_sep>/client/hocs/AuthProvider.js
import { useState, useEffect, createContext } from "react";
import axios from "axios";
import { ApolloProvider } from "@apollo/client";
import { useApollo } from "../../lib/apolloClient";
import Loading from "../components/Loading";
export const AuthContext = createContext();
const AuthProvider = ({ children, initialApolloState }) => {
const [state, setState] = useState({
user: null,
accessToken: null,
authenticated: false,
checked: false,
apolloClient: null,
});
const authenticate = (credentials) => {
setState({
...state,
...credentials,
checked: true,
});
};
useEffect(() => {
async function everything() {
let user = null,
accessToken = null,
authenticated = false;
try {
const { data } = await axios.post(
`/auth/check`,
{},
{
withCredentials: true,
}
);
user = data.user;
accessToken = data.accessToken;
authenticated = true;
} catch (err) {
console.log(err);
}
const apolloClient = useApollo(initialApolloState, accessToken);
setState({
...state,
user,
accessToken,
apolloClient,
authenticated,
checked: true,
});
}
// useEffect doesn't want to be async
everything();
const interval = setInterval(everything, 9 * 60000);
return () => clearInterval(interval);
}, []);
return (
<>
{state.apolloClient ? (
<AuthContext.Provider
value={{
...state,
authenticate,
}}
>
<ApolloProvider client={state.apolloClient}>
{state.checked ? children : <Loading />}
</ApolloProvider>
</AuthContext.Provider>
) : (
<>
<Loading />
</>
)}
</>
);
};
export default AuthProvider;
<file_sep>/pages/cart.js
const Cart = () => {
return (
<div>
<h1>Cart</h1>
<p>lorem epsum</p>
</div>
);
};
export default Cart;
<file_sep>/client/components/categories/CategoryMenu.js
import { withRouter } from "next/router";
import { BsChevronRight, BsChevronLeft } from "react-icons/bs";
class CategoryMenu extends React.Component {
state = {
history: [],
};
componentDidMount() {
const temp = [];
temp.push(this.props.superCategories);
this.setState({
history: temp,
});
}
menuClickHandler = (value) => {
const categories = value.Categories;
const subCategories = value.SubCategories;
let newHistory = this.state.history;
if (categories) {
newHistory.push(categories);
} else if (subCategories) {
newHistory.push(subCategories);
} else if (value) {
const { router } = this.props;
router.push("/subcategories/[subid]", `/subcategories/${value.id}`);
}
this.setState({
history: newHistory,
});
};
popHandler = () => {
if (this.state.history.length > 1) {
let history = this.state.history;
history.pop();
this.setState({
history: history,
});
}
};
backFormatHandler = () => {
return this.state.history.length > 1 ? (
<div onClick={this.popHandler} className="col-12 h3 pb-3">
<BsChevronLeft />
Back
</div>
) : (
<div className="col-12 h3 pb-3"> </div>
);
};
menuFormatHandler = (history) => {
const menuItems = history[history.length - 1];
if (!menuItems) {
return <div>Loading ...</div>;
}
return (
<div className="pl-5">
<b>
{menuItems.map((item) => (
<div
key={item.name}
onClick={() => this.menuClickHandler(item)}
className="col-12"
>
<span className="h2 pr-4">{item.name}</span>
<span>
<BsChevronRight />
</span>
</div>
))}
</b>
</div>
);
};
render() {
return (
<div className="row">
<div className="col-xl-6 col-lg-5 col-md-6 col-12">
<div>
{this.backFormatHandler()}
{this.menuFormatHandler(this.state.history)}
</div>
</div>
</div>
);
}
}
export default withRouter(CategoryMenu);
<file_sep>/client/components/Footer.js
import { useRouter } from "next/router";
import { AiFillFacebook } from "react-icons/ai";
import { AiOutlineTwitter } from "react-icons/ai";
import { GrInstagram } from "react-icons/gr";
import { AiFillYoutube } from "react-icons/ai";
const Footer = () => {
const router = useRouter();
return (
<>
<footer className="pt-md-5 pt-3">
<div className="bg-light py-md-4 py-3">
<div className="container">
<div className="row">
<div className="col-md-5 col-12" md={5} xs={12}>
<div className="row">
<div className="col-12 d-flex justify-content-center">
<h3>
BECOME A<b> UNLM.</b>
</h3>
</div>
<div className="col-12 d-flex justify-content-center">
Subscribe for exclusive updates.
</div>
</div>
</div>
<div className="col-md-7 col-12 d-flex justify-content-center align-items-center">
<div className="form-group d-inline-flex">
<input
type="email"
className="form-control"
placeholder="Email address"
/>
<button className="btn btn-dark">Subscribe</button>
</div>
</div>
</div>
</div>
</div>
<div className="bg-dark py-5">
<div className="container text-white">
<div className="row">
<div className="col-md-9 col-12">
<div className="row">
<div className="col-md-4 col-12 d-md-flex d-none justify-content-center">
<h3>
<b>UNLM.</b>
</h3>
</div>
<div className="col-md-4 col-12">
<ul>
<li>
<h5>
<b>UNLM.</b>
</h5>
</li>
<li>About</li>
<li>Careers</li>
<li>Privacy</li>
<li>Cookies</li>
</ul>
</div>
<div className="col-md-4 col-12">
<ul>
<li>
<h5>
<b>NEED HELP?</b>
</h5>
</li>
<li>Orders & Delivery</li>
<li>Returns</li>
<li>FAQ</li>
<li>Terms & Conditions</li>
</ul>
</div>
<div className="col-md-6 col-12 py-5 d-flex justify-content-center">
©UNLM. All rights reserved
</div>
<div className="col-md-6 col-12 py-5">
<div className="d-flex justify-content-around">
<AiFillFacebook />
<AiOutlineTwitter />
<GrInstagram />
<AiFillYoutube />
</div>
</div>
</div>
</div>
<div className="bottomRightButton col-md-3 col-12">
<div>
<div className="col-12 d-flex justify-content-center">
<div className="pb-4">
<button className="btn text-white">CONTACT</button>
</div>
</div>
<div className="col-12 d-flex justify-content-center">
<div>
<button className="btn text-white">STORE</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</footer>
</>
);
};
export default Footer;
<file_sep>/pages/_app.js
import Head from "next/head";
import { useEffect } from "react";
import AuthProvider from "../client/hocs/AuthProvider";
import Default from "../client/layouts/Default";
import "../client/styles/globals.scss";
function MyApp({ Component, pageProps }) {
useEffect(() => {
require("bootstrap/dist/js/bootstrap.bundle.min.js");
});
return (
<div>
<Head>
<title>UNLM Offcial - The offical site for buying fancy clothes.</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<AuthProvider>
<Default>
<Component {...pageProps} />
</Default>
</AuthProvider>
</div>
);
}
export default MyApp;
<file_sep>/pages/comming.js
import { FaCog } from "react-icons/fa";
const Comming = () => {
return (
<div className="commingSoonContainer">
<div>
<div className="d-flex justify-content-center py-5">
<FaCog className="commingCog" />
</div>
<div>
<h1>COMMING SOON</h1>
</div>
</div>
</div>
);
};
export default Comming;
|
c26f3a86c38ed8c1e686ac3083a921b1332f2f6d
|
[
"JavaScript"
] | 28
|
JavaScript
|
AabhasDhaubanja/unlm
|
a1f16a2c8c34aa7435e3fbc5d6cb6fce0cb75727
|
73e64e843615b2f503123a188f88c4ed0e709017
|
refs/heads/master
|
<file_sep><?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
class Twofa extends Base
{
protected $tfa;
public function __construct($setting)
{
$QrCodeProvider = new \RobThree\Auth\Providers\Qr\BaconQrCodeProvider();
$this->tfa = new RobThree\Auth\TwoFactorAuth($setting->getValue('website_name'), 6, 30, 'sha1', $QrCodeProvider);
}
/**
* Return a new generated token
* @return string generated token
*/
public function generateSecret()
{
return $this->tfa->createSecret(160, true);
}
public function getQrCode($username, $secret)
{
return $this->tfa->getQRCodeImageAsDataUri($username, $secret, 300);
}
/**
* Check if a otp code is valid for an user
* @param string $userID id of the user
* @param string $otp one time code
* @return bool Define if the code is valid or not
*/
public function isValid($secret, $otp)
{
return $this->tfa->verifyCode($secret, $otp);
}
/**
* Convenience method to get a token expired message with a token type, and ? image with description
* @param string $tokentype if you want a specific tokentype, set it here
* @param string $dowhat What will be put in the string "Simply $dowhat again to...", default is try
*/
public static function getErrorWithDescriptionHTML($dowhat = "login")
{
switch ($dowhat) {
default:
return "Invalid Two-Factor Authentication, failed to $dowhat. Please try again";
break;
}
}
}
$twofa = new Twofa($setting);
$twofa->setDebug($debug);
$twofa->setMysql($mysqli);
$twofa->setConfig($config);
$twofa->setErrorCodes($aErrorCodes);
$twofa->setSetting($setting);
<file_sep><?php
/*
* This file is part of the smarty-gettext package.
*
* @copyright (c) <NAME>
* @license GNU Lesser General Public License, version 2.1 or any later
* @see https://github.com/smarty-gettext/smarty-gettext/
*
* For the full copyright and license information,
* please see the LICENSE and AUTHORS files
* that were distributed with this source code.
*/
function smarty_function_locale($params, &$smarty) {
static $stack;
// init stack as array
if ($stack === null) {
$stack = array();
}
$path = null;
$template_dirs = method_exists($smarty, 'getTemplateDir') ? $smarty->getTemplateDir() : $smarty->template_dir;
$path_param = isset($params['path']) ? $params['path'] : '';
$domain = isset($params['domain']) ? $params['domain'] : 'messages';
$stack_operation = isset($params['stack']) ? $params['stack'] : 'push';
foreach ((array)$template_dirs as $template_dir) {
$path = $template_dir . $path_param;
if (is_dir($path)) {
break;
}
}
if (!$path && $stack_operation != 'pop') {
trigger_error("Directory for locales not found (path='{$path_param}')", E_USER_ERROR);
}
if ($stack_operation == 'push') {
$stack[] = array($domain, $path);
} elseif ($stack_operation == 'pop') {
if (count($stack) > 1) {
array_pop($stack);
}
list($domain, $path) = end($stack);
} else {
trigger_error("Unknown stack operation '{$stack_operation}'", E_USER_ERROR);
}
bind_textdomain_codeset($domain, 'UTF-8');
bindtextdomain($domain, $path);
textdomain($domain);
}
<file_sep><?php
function run_104()
{
// Ugly but haven't found a better way
global $setting, $config, $coin_address, $user, $mysqli;
// Version information
$db_version_old = '1.0.3'; // What version do we expect
$db_version_new = '1.0.4'; // What is the new version we wish to upgrade to
$db_version_now = $setting->getValue('DB_VERSION'); // Our actual version installed
// Upgrade specific variables
$aSql[] = "ALTER TABLE `accounts` ADD COLUMN `twofa_secret` VARCHAR(255);";
$aSql[] = "ALTER TABLE `accounts` ADD COLUMN `failed_twofa` INT(5) unsigned NOT NULL DEFAULT '0';";
$aSql[] = "ALTER TABLE `accounts` DROP COLUMN `failed_pins`;";
$aSql[] = "ALTER TABLE `accounts` DROP COLUMN `pin`;";
$aSql[] = "UPDATE " . $setting->getTableName() . " SET value = '" . $db_version_new . "' WHERE name = 'DB_VERSION';";
echo $db_version_now;
if ($db_version_now == $db_version_old && version_compare(DB_VERSION, $db_version_new, '<')) {
// Run the upgrade
echo '- Starting database migration to version ' . $db_version_new . PHP_EOL;
foreach ($aSql as $sql) {
echo '- Preparing: ' . $sql . PHP_EOL;
$stmt = $mysqli->prepare($sql);
if ($stmt && $stmt->execute()) {
echo '- success' . PHP_EOL;
} else {
echo '- failed: ' . $mysqli->error . PHP_EOL;
exit(1);
}
}
}
}
?>
<file_sep><?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
// MPOS has issues with version 5.7 so lets fetch this installs version
$mysql_version = $mysqli->query('SELECT VERSION() AS version')->fetch_object()->version;
// This should be set if we are running on 5.7
$mysql_mode = $mysqli->query('SELECT @@GLOBAL.sql_mode AS sql_mode')->fetch_object()->sql_mode;
// see if it includes 5.7
if (strpos($mysql_version, '5.7') !== false && strpos($mysql_mode, 'ONLY_FULL_GROUP_BY') !== false) {
$newerror = array();
$newerror['name'] = "MySQL Version";
$newerror['level'] = 3;
$newerror['description'] = "SQL version not fully supported.";
$newerror['configvalue'] = "db.*";
$newerror['extdesc'] = "You are using MySQL Version $mysql_version which is not fully supported. You may run into issues during payout when using this version of MySQL. Please see our Wiki FAQ on how to workaround any potential issues. This check only matches your version string against `5.7` so you may still be fine.";
$newerror['helplink'] = "";
$error[] = $newerror;
$newerror = null;
}
<file_sep>#!/bin/bash
./tsmarty2c.php -o mpos.pot ../templates/bootstrap/
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"en\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"fr\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"es\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"de\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"it\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"ru\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
echo "" >> mpos.pot
echo "#: ../templates/bootstrap//global/header.tpl:70" >> mpos.pot
echo "msgid \"zh\"" >> mpos.pot
echo "msgstr \"\"" >> mpos.pot
find ../include -iname "*.php" | xargs xgettext --from-code=UTF-8 -k_e -k_x -k__ -j -o mpos.pot
xgettext --from-code=UTF-8 -k_e -k_x -k__ -j -o mpos.pot ../public/index.php
<file_sep><?php
/*
* This file is part of the smarty-gettext package.
*
* @copyright (c) <NAME>
* @license GNU Lesser General Public License, version 2.1 or any later
* @see https://github.com/smarty-gettext/smarty-gettext/
*
* For the full copyright and license information,
* please see the LICENSE and AUTHORS files
* that were distributed with this source code.
*/
/**
* Replaces arguments in a string with their values.
* Arguments are represented by % followed by their number.
*
* @param string $str Source string
* @param mixed mixed Arguments, can be passed in an array or through single variables.
* @return string Modified string
*/
function smarty_gettext_strarg($str/*, $varargs... */) {
$tr = array();
$p = 0;
$nargs = func_num_args();
for ($i = 1; $i < $nargs; $i++) {
$arg = func_get_arg($i);
if (is_array($arg)) {
foreach ($arg as $aarg) {
$tr['%' . ++$p] = $aarg;
}
} else {
$tr['%' . ++$p] = $arg;
}
}
return strtr($str, $tr);
}
/**
* Smarty block function, provides gettext support for smarty.
*
* The block content is the text that should be translated.
*
* Any parameter that is sent to the function will be represented as %n in the translation text,
* where n is 1 for the first parameter. The following parameters are reserved:
* - escape - sets escape mode:
* - 'html' for HTML escaping, this is the default.
* - 'js' for javascript escaping.
* - 'url' for url escaping.
* - 'no'/'off'/0 - turns off escaping
* - plural - The plural version of the text (2nd parameter of ngettext())
* - count - The item count for plural mode (3rd parameter of ngettext())
* - domain - Textdomain to be used, default if skipped (dgettext() instead of gettext())
* - context - gettext context. reserved for future use.
*
* @param array $params
* @param string $text
* @see http://www.smarty.net/docs/en/plugins.block.functions.tpl
* @return string
*/
function smarty_block_t($params, $text) {
if (!isset($text)) {
return $text;
}
// set escape mode, default html escape
if (isset($params['escape'])) {
$escape = $params['escape'];
unset($params['escape']);
} else {
$escape = 'html';
}
// set plural parameters 'plural' and 'count'.
if (isset($params['plural'])) {
$plural = $params['plural'];
unset($params['plural']);
// set count
if (isset($params['count'])) {
$count = $params['count'];
unset($params['count']);
}
}
// get domain param
if (isset($params['domain'])) {
$domain = $params['domain'];
unset($params['domain']);
} else {
$domain = null;
}
// get context param
if (isset($params['context'])) {
$context = $params['context'];
unset($params['context']);
} else {
$context = null;
}
// use plural if required parameters are set
if (isset($count) && isset($plural)) {
// use specified textdomain if available
if (isset($domain) && isset($context)) {
$text = dnpgettext($domain, $context, $text, $plural, $count);
} elseif (isset($domain)) {
$text = dngettext($domain, $text, $plural, $count);
} elseif(isset($context)) {
$text = npgettext($context, $text, $plural, $count);
} else {
$text = ngettext($text, $plural, $count);
}
} else {
// use specified textdomain if available
if (isset($domain) && isset($context)) {
$text = dpgettext($domain, $context, $text);
} elseif (isset($domain)) {
$text = dgettext($domain, $text);
} elseif (isset($context)) {
$text = pgettext($context, $text);
} else {
$text = gettext($text);
}
}
// run strarg if there are parameters
if (count($params)) {
$text = smarty_gettext_strarg($text, $params);
}
switch ($escape) {
case 'html':
$text = nl2br(htmlspecialchars($text));
break;
case 'javascript':
case 'js':
// javascript escape
$text = strtr($text, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', "\r" => '\\r', "\n" => '\\n', '</' => '<\/'));
break;
case 'url':
// url escape
$text = urlencode($text);
break;
}
return $text;
}
<file_sep><?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
// 2fa - set old token so we can use it if an error happens or we need to use post
$oldtoken_ea = (isset($_POST['ea_token']) && $_POST['ea_token'] !== '') ? $_POST['ea_token'] : @$_GET['ea_token'];
$oldtoken_cp = (isset($_POST['cp_token']) && $_POST['cp_token'] !== '') ? $_POST['cp_token'] : @$_GET['cp_token'];
$oldtoken_wf = (isset($_POST['wf_token']) && $_POST['wf_token'] !== '') ? $_POST['wf_token'] : @$_GET['wf_token'];
$updating = (@$_POST['do']) ? 1 : 0;
if ($user->isAuthenticated()) {
if ($updating && $_SESSION['USERDATA']['has_twofa'] && (empty($_POST['otp']) || !$user->isValidTwofa($_POST['otp']))) {
$_SESSION['POPUP'][] = array('CONTENT' => $twofa->getErrorWithDescriptionHTML("edit account"), 'TYPE' => 'alert alert-warning');
} else {
switch (@$_POST['do']) {
case 'cashOut':
$aBalance = $transaction->getBalance($_SESSION['USERDATA']['id']);
$dBalance = $aBalance['confirmed'];
if ($setting->getValue('disable_payouts') == 1 || $setting->getValue('disable_manual_payouts') == 1) {
$_SESSION['POPUP'][] = array('CONTENT' => _('Manual payouts are disabled.'), 'TYPE' => 'alert alert-warning');
} else if ($aBalance['confirmed'] < $config['mp_threshold']) {
$_SESSION['POPUP'][] = array('CONTENT' => _('Account balance must be >= ') . $config['mp_threshold'] . _(' to do a Manual Payout.'), 'TYPE' => 'alert alert-warning');
} else if (!$coin_address->getCoinAddress($_SESSION['USERDATA']['id'])) {
$_SESSION['POPUP'][] = array('CONTENT' => _('You have no payout address set.'), 'TYPE' => 'alert alert-danger');
} else {
$user->log->log("info", $_SESSION['USERDATA']['username'] . " requesting manual payout");
$txfee_manual = $config['txfee_manual'];
if (isset($config['txfee_manual_dynamic']['enabled']) && $config['txfee_manual_dynamic']['enabled']) {
if (isset($config['txfee_manual_dynamic']['coefficient']) && $config['txfee_manual_dynamic']['coefficient'] * $dBalance > $config['txfee_manual']) {
$txfee_manual = round($config['txfee_manual_dynamic']['coefficient'] * $dBalance, 1, PHP_ROUND_HALF_UP);
}
}
if ($dBalance > $txfee_manual) {
if (!$oPayout->isPayoutActive($_SESSION['USERDATA']['id'])) {
if (!$config['csrf']['enabled'] || $config['csrf']['enabled'] && $csrftoken->valid) {
if ($iPayoutId = $oPayout->createPayout($_SESSION['USERDATA']['id'], $oldtoken_wf)) {
$_SESSION['POPUP'][] = array('CONTENT' => _('Created new manual payout request with ID #') . $iPayoutId);
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $iPayoutId->getError(), 'TYPE' => 'alert alert-danger');
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $csrftoken->getErrorWithDescriptionHTML(), 'TYPE' => 'alert alert-warning');
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => _('You already have one active manual payout request.'), 'TYPE' => 'alert alert-danger');
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => _('Insufficient funds, you need more than ') . $txfee_manual . ' ' . $config['currency'] . _(' to cover transaction fees'), 'TYPE' => 'alert alert-danger');
}
}
break;
case 'updateAccount':
if (!$config['csrf']['enabled'] || $config['csrf']['enabled'] && $csrftoken->valid) {
if ($user->updateAccount($_SESSION['USERDATA']['id'], $_POST['paymentAddress'], $_POST['payoutThreshold'], $_POST['donatePercent'], $_POST['email'], $_POST['timezone'], $_POST['is_anonymous'], $oldtoken_ea)) {
$_SESSION['USERDATA']['timezone'] = $_POST['timezone'];
$_SESSION['POPUP'][] = array('CONTENT' => _('Account details updated'), 'TYPE' => 'alert alert-success');
} else {
$_SESSION['POPUP'][] = array('CONTENT' => _('Failed to update your account: ') . $user->getError(), 'TYPE' => 'alert alert-danger');
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $csrftoken->getErrorWithDescriptionHTML(), 'TYPE' => 'alert alert-warning');
}
break;
case 'updatePassword':
if (!$config['csrf']['enabled'] || $config['csrf']['enabled'] && $csrftoken->valid) {
if ($user->updatePassword($_SESSION['USERDATA']['id'], $_POST['currentPassword'], $_POST['<PASSWORD>'], $_POST['<PASSWORD>'], $oldtoken_cp)) {
$_SESSION['POPUP'][] = array('CONTENT' => _('Password updated'), 'TYPE' => 'alert alert-success');
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $user->getError(), 'TYPE' => 'alert alert-danger');
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $csrftoken->getErrorWithDescriptionHTML(), 'TYPE' => 'alert alert-warning');
}
break;
}
}
}
// Grab our timezones
$smarty->assign('TIMEZONES', DateTimeZone::listIdentifiers());
// Fetch donation threshold
$smarty->assign("DONATE_THRESHOLD", $config['donate_threshold']);
// Tempalte specifics
$smarty->assign("CONTENT", "default.tpl");
<file_sep><?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
if ($user->isAuthenticated()) {
if ($user->hasTwofa($_SESSION['USERDATA']['id'])) {
$smarty->assign("CONTENT", "already_enabled.tpl");
} else {
if (!isset($_POST['do'])) {
// Tempalte specifics
$smarty->assign("CONTENT", "getstarted.tpl");
} else {
if (!$config['csrf']['enabled'] || $config['csrf']['enabled'] && $csrftoken->valid) {
if ($_POST['do'] == 'verify') {
if (!$_POST['otp'] || !$user->isValidTwofa($_POST['otp'], true)) {
$_SESSION['POPUP'][] = array('CONTENT' => $twofa->getErrorWithDescriptionHTML("enable"), 'TYPE' => 'alert alert-warning');
$smarty->assign("CONTENT", "getstarted.tpl");
} else {
if (!$user->enableTwofa()) {
$_SESSION['POPUP'][] = array('CONTENT' => "Fail to enable Two-Factor Authentication", 'TYPE' => 'alert alert-warning');
$smarty->assign("CONTENT", "getstarted.tpl");
} else {
$smarty->assign("CONTENT", "empty");
}
}
} else {
$twofaData = $user->initializeTwofa($_SESSION['USERDATA']['id']);
if (!$twofaData['success']) {
$_SESSION['POPUP'][] = array('CONTENT' => "Fail to generate Two-Factor Authentication secret", 'TYPE' => 'alert alert-danger');
$smarty->assign("CONTENT", "getstarted.tpl");
} else {
$smarty->assign("SECRET", $twofaData['secret']);
$smarty->assign("QRCODE", $twofaData['qrcode']);
$smarty->assign("CONTENT", "enable.tpl");
}
}
} else {
$_SESSION['POPUP'][] = array('CONTENT' => $csrftoken->getErrorWithDescriptionHTML(), 'TYPE' => 'alert alert-warning');
$smarty->assign("CONTENT", "getstarted.tpl");
}
}
}
}
|
31bb7a721c2f4224423b8ef0cc9a0eda5e0e345e
|
[
"PHP",
"Shell"
] | 8
|
PHP
|
TnTBass/php-mpos
|
76bcedfabbc34d5b43ab277f20e4e4757b137106
|
c544953c429eb373301c5b307c4fdc7c4bac9b3a
|
refs/heads/master
|
<repo_name>imgcook-dsl/uni-app-size<file_sep>/src/index.js
module.exports = function(schema, options) {
const {
_,
helper,
prettier,
responsive
} = options;
const {
printer,
utils
} = helper;
// 渲染数据
const renderData = {};
// style
const styleMap = {};
// mock data
const mockData = {
properties: {},
data: {}
};
// script
const scriptMap = {
created: '',
lifetimes: {},
methods: {},
data: {},
event: {}
};
// 宽高
let modConfig = responsive || {
width: 750,
height: 1334
};
// 代码缩进
const line = (content, level) =>
utils.line(content, {
indent: {
space: level * 4
}
});
const prettierOpt = {
parser: 'vue',
tabWidth: 4,
printWidth: 120,
singleQuote: true
};
const parseStyleObject = style =>
Object.entries(style)
.filter(([, value]) => value || value === 0)
.map(([key, value]) => {
key = _.kebabCase(key);
return `${key}: ${normalizeStyleValue(key, value, modConfig)};`;
});
const renderStyleItem = (className, style) => [
line(`.${className} {`),
...parseStyleObject(style).map(item => line(item, 1)),
line('}')
];
const renderStyle = map => [].concat(
...Object.entries(map).map(([className, style]) =>
renderStyleItem(className, style)
)
);
const normalizeTemplateAttrValue = ({
key,
value
}) => {
if (typeof value === 'string') {
return JSON.stringify(value);
} else if (key === 'style') {
var str = '"';
Object.entries(value).map(([k, val]) => {
k = _.kebabCase(k);
str += `${k}:${normalizeStyleValue(k, val, modConfig)};`
});
return `${str}"`;
} else {
return `"${JSON.stringify(value)}"`;
}
};
const renderTemplateAttr = (key, value) =>
`${key}=${normalizeTemplateAttrValue({key, value})}`;
let depth = 0;
let {
dataSource,
methods,
lifeCycles,
state
} = schema;
const renderTemplate = (obj, level = 0) => {
depth = depth + 1;
// handle node changetype
const targetName = obj.componentName.toLowerCase();
obj.element = COMPONENT_TYPE_MAP[targetName] || targetName;
if (!obj.props) obj.props = {};
// loop handler
if (obj.loop) {
if (typeof obj.loop === 'string') {
obj.props[WXS_SYNTAX_MAP['for']] = `{{${obj.loop.split('.').pop()}`;
} else {
obj.props[WXS_SYNTAX_MAP['for']] = `{{${JSON.stringify(obj.loop)}}}`
}
obj.props[WXS_SYNTAX_MAP['forItem']] = obj.loopArgs && `${obj.loopArgs[0]}` || 'item';
obj.props[WXS_SYNTAX_MAP['forIndex']] = obj.loopArgs && `${obj.loopArgs[1]}` || 'index';
}
const handlerFuncStr = options => {
let {
value,
item
} = options;
if (value.content && item) {
value.content = value.content.replace(
new RegExp('this.' + item + '.', 'g'),
'e.currentTarget.dataset.'
);
}
return value;
};
// condition handler
if (obj.condition) {
obj.props[WXS_SYNTAX_MAP['condition']] = `${obj.condition}`;
}
// event handler
for (let [key, value] of Object.entries(obj.props)) {
if (COMPONENT_EVENT_MAP[key]) {
obj.props[COMPONENT_EVENT_MAP[key]] = key;
scriptMap.methods[key] = handlerFuncStr({
value: parseFunction(value),
item: obj.props[WXS_SYNTAX_MAP['forItem']]
});
}
if (typeof value === 'string' && value.match(/this\./)) {
obj.props[key] = value.replace(/this\./g, '');
}
}
switch (obj.element) {
case 'view':
obj.element = 'view';
break;
case 'picture':
obj.element = 'img';
obj.children = null;
break;
case 'text':
obj.children = obj.props.text;
break;
}
if (obj.props.className) {
obj.props.class = _.kebabCase(obj.props.className);
delete obj.props.className;
styleMap[obj.props.class] = {
...styleMap[obj.props.class],
...obj.props.style
};
}
if (obj.props.source && obj.props.src) {
obj.props.src = obj.props.source;
delete obj.props.source;
}
let ret = [];
let nextLine = '';
const props = Object.entries(obj.props).filter(([key, value]) => {
if (key === 'style' && obj.props && !obj.props.class) {
return true;
}
return ['style', 'text', 'onClick'].indexOf(key) < 0;
});
if (props.length > 3) {
ret.push(line(`<${obj.element}`, level));
ret = ret.concat(
props.map(([key, value]) => {
return line(renderTemplateAttr(key, value), level + 1);
})
);
} else {
nextLine = `<${obj.element}`;
if (props.length) {
nextLine += ` ${props
.map(([key, value]) => {
return renderTemplateAttr(key, value);
})
.join(' ')}`;
}
}
if (obj.children) {
if (Array.isArray(obj.children) && obj.children.length) {
// Multi-line Child
ret.push(line(`${nextLine}>`, level));
ret = ret.concat(
...obj.children.map(o => {
return renderTemplate(o, level + 1);
})
);
ret.push(line(`</${obj.element}>`, level));
} else {
// Single line Child
ret.push(line(`${nextLine}>${obj.children}</${obj.element}>`, level));
}
} else {
// Self-closing label
ret.push(line(`${nextLine} />`, level));
}
return ret;
};
// methods handler
methods &&
Object.entries(methods).map(([key, value]) => {
scriptMap.methods[key] = parseFunction(value);
});
// lifeCycles handler
lifeCycles &&
Object.entries(lifeCycles).map(([key, value]) => {
scriptMap[COMPONENT_LIFETIMES_MAP[key]] = parseFunction(value);
});
state &&
Object.entries(state).map(([key, value]) => {
if (value instanceof Array) {
scriptMap.data[key] = '[]';
} else {
scriptMap.data[key] = JSON.stringify(value);
}
});
const renderScript = scriptMap => {
const {
attached,
detached,
methods,
created,
data
} = scriptMap;
const properties = [];
return `
export default {
data() {
return {}
},
onLoad() {
console.log('页面加载完成')
},
methods: {}
}
`;
};
const generatorVueTemplate = template => {
template.unshift(line('<template>'));
return template.concat(line(`</template>
<script>
${renderData.js}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>`))
};
renderData.wxml = printer(renderTemplate(schema, 1));
renderData.wxss = printer(renderStyle(styleMap));
renderData.js = prettier.format(renderScript(scriptMap), {
parser: 'babel'
});
renderData.mockData = `var mock = ${JSON.stringify(mockData)}`;
renderData.json = printer([
line('{'),
line('"component": true,', 1),
line('"usingComponents": {}', 1),
line('}')
]);
return {
renderData,
prettierOpt: {},
panelDisplay: [{
panelName: 'index.vue',
panelValue: prettier.format(`
<template>
${renderData.wxml}
</template>
<script>
${renderData.js}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
`, prettierOpt),
panelType: 'vue'
},
{
panelName: 'index.scss',
panelValue: renderData.wxss,
panelType: 'BuilderRaxStyle',
mode: 'css'
},
],
playground: {
info: '前往下载微信开发者工具',
link: 'https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html'
},
noTemplate: true
};
};
const COMPONENT_TYPE_MAP = {
page: 'view',
div: 'view',
block: 'view',
link: 'view',
video: 'video',
expview: 'view',
scroller: 'scroll-view',
slider: 'swiper',
view: 'view',
text: 'text',
picture: 'img',
image: 'img',
};
const COMPONENT_LIFETIMES_MAP = {
_constructor: 'created',
render: '',
componentDidMount: 'attached',
componentDidUpdate: '',
componentWillUnmount: 'detached'
};
const COMPONENT_EVENT_MAP = {
onClick: 'bindtap',
};
const WXS_SYNTAX_MAP = {
for: 'wx:for',
forItem: 'wx:for-item',
forIndex: 'wx:for-index',
condition: 'wx:if'
};
// parse function, return params and content
const parseFunction = func => {
const funcString = func.toString();
const params = funcString.match(/\([^\(\)]*\)/)[0].slice(1, -1);
const content = funcString.slice(
funcString.indexOf('{') + 1,
funcString.lastIndexOf('}')
);
return {
params,
content
};
};
const normalizeStyleValue = (key, value, config) => {
switch (key) {
case 'font-size':
case 'margin-left':
case 'margin-top':
case 'margin-right':
case 'margin-bottom':
case 'padding-left':
case 'padding-top':
case 'padding-right':
case 'padding-bottom':
case 'max-width':
case 'width':
case 'height':
case 'border-width':
case 'border-radius':
case 'top':
case 'left':
case 'right':
case 'bottom':
case 'line-height':
case 'letter-spacing':
case 'border-top-right-radius':
case 'border-top-left-radius':
case 'border-bottom-left-radius':
case 'border-bottom-right-radius':
value = '' + value;
if (value.slice(-1) !== "%") {
value = value.replace(/(rem)|(px)|(rpx)/, '');
value = Number(value) * 2;
value = '' + value;
if (value.length > 3 && value.substr(-3, 3) == 'rem') {
value = value.slice(0, -3) + 'rpx';
} else {
value += 'rpx';
}
}
break;
default:
break;
}
return value;
};
|
ab9ac8ec8202361febbf3bdff14aa74e4f449702
|
[
"JavaScript"
] | 1
|
JavaScript
|
imgcook-dsl/uni-app-size
|
7c184cacf18db83af7f5ddfc2e0886360dc4aa22
|
9a90f9a5c8adc105ecb08b52cf519c02f7052f05
|
refs/heads/master
|
<file_sep>using RelatoriosCongregação.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace RelatoriosCongregação.Controllers
{
//todo: separa a interface para incluir/editar relatório.
//todo: cria campo para identificar que relatório é de outro mês
//todo: colocar totais
//todo: criar relatório totalizando
public class RelatoriosController : Controller
{
private FieldServiceEntities db = new FieldServiceEntities();
public ActionResult DetalhadoIndividual(string anoMes, int? pagina)
{
var data = DateTime.Now.AddMonths(-1);
if (string.IsNullOrEmpty(anoMes))
{
anoMes = data.Year.ToString() + data.Month.ToString().PadLeft(2, '0');
}
if (!pagina.HasValue || pagina.Value <= 0)
{
pagina = 1;
}
var relatorio = db.Relatorios
.Where(r => r.AnoMes == anoMes)
.OrderBy(r => r.Publicadores.Nome)
.Select(r => r)
.Skip(pagina.Value - 1)
.Take(1)
.FirstOrDefault();
ViewBag.QtdTotal = db.Relatorios
.Where(r => r.AnoMes == anoMes)
.Count();
LoadAnos(data.Year);
LoadMeses(data.Month);
ViewBag.anoMes = anoMes;
if (relatorio == null)
{
relatorio = new Relatorios() { AnoMes = anoMes, IdTipo = 1 };
}
return View(relatorio);
}
public List<PublicadoresPorGrupo> GetIrregulares(string anoMes)
{
var publicadores = db.Publicadores
.Where(p => !p.Relatorios.Any(r => r.AnoMes == anoMes) && p.Ativo == true)
.GroupBy(p => p.Grupo.Dirigente)
.Select(p => new PublicadoresPorGrupo
{
Dirigente = p.Key,
Publicadores = p.Select(c => c.Nome).OrderBy(c => c).ToList()
})
.OrderBy(p => p.Dirigente)
.ToList();
return publicadores;
}
public ActionResult Index(string ano, string mes, int? tipo)
{
string anoMes;
if (string.IsNullOrEmpty(ano) || string.IsNullOrEmpty(mes))
{
var data = DateTime.Now.AddMonths(-1);
anoMes = data.Year.ToString() + data.Month.ToString().PadLeft(2, '0');
LoadAnos(data.Year);
LoadMeses(data.Month);
}
else
{
anoMes = ano + mes.PadLeft(2, '0');
LoadAnos(int.Parse(ano));
LoadMeses(int.Parse(mes));
}
LoadPublicadores();
LoadTipos();
var geral = new RelatorioGeral();
geral.Detalhado = GetRelatorioDetalhado(anoMes, tipo);
geral.Totais = GetTotais(anoMes);
geral.Irregulares = GetIrregulares(anoMes);
return View(geral);
}
public IQueryable<Relatorios> GetRelatorioDetalhado(string anoMes, int? tipo)
{
var relatorios = db.Relatorios.Include("Publicadores")
.Include("Tipos")
.Where(r => r.AnoMes == anoMes);
if (tipo.HasValue && tipo != 0)
{
relatorios = relatorios.Where(c => c.IdTipo == tipo);
}
return relatorios
.OrderByDescending(r => r.Horas)
.Select(r => r);
}
public IQueryable<TotaisRelatorio> GetTotais(string anoMes)
{
return db.Relatorios.Include("Tipos")
.Where(r => r.AnoMes == anoMes)
.OrderBy(r => r.Publicadores.Nome)
.GroupBy(r => r.Tipos.Tipo)
.Select(r => new TotaisRelatorio
{
Tipo = r.Key,
QtdPublicadores = r.Count(),
Horas = r.Sum(t => t.Horas),
Publicacoes = r.Sum(t => t.Publicacoes),
Videos = r.Sum(t => t.Videos),
Revisitas = r.Sum(t => t.Revisitas),
Estudos = r.Sum(t => t.Estudos)
});
}
private void LoadTipos()
{
var tipos = db.Tipos
.OrderBy(r => r.Tipo)
.ToList();
tipos.Insert(0, new Tipos { Id = 0, Tipo = "" });
ViewBag.Tipos = new SelectList(tipos, "Id", "Tipo");
}
public void LoadAnos(int selectedAno)
{
var anos = new List<int>();
anos.Add(DateTime.Now.Year);
anos.Add(DateTime.Now.AddYears(-1).Year);
ViewBag.Anos = new SelectList(anos, selectedAno); ;
}
private void LoadMeses(int selectedMonth)
{
var numMeses = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
var nomeMeses = numMeses.Select(n =>
new
{
numMes = n,
Nome = System.Globalization.DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(n)
});
//var selectedItem = nomeMeses.Where(m => m.numMes == selectedMonth).FirstOrDefault();
var listMeses = new SelectList(nomeMeses, "numMes", "Nome", selectedMonth);
//var selected = listMeses.Where(x => x.Value == selectedMonth.ToString()).First();
//listMeses.se= selectedItem.ToString();
ViewBag.Meses = listMeses;
}
public ActionResult AnoMes()
{
var anos = new List<string>();
anos.Add(DateTime.Now.Year.ToString());
anos.Add(DateTime.Now.AddYears(-1).Year.ToString());
return View(anos);
}
private void LoadPublicadores()
{
var publicadores = db.Publicadores
.Where(p => p.Ativo == true)
.OrderBy(r => r.Nome)
.Select(r => new { r.Id, r.Nome })
.ToList();
publicadores.Insert(0, new { Id = 0, Nome = "" });
ViewBag.Publicadores = new SelectList(publicadores, "Id", "Nome");
}
private void LoadPublicadores(string anoMes)
{
var publicadores = db.Publicadores
.Where(p => p.Ativo == true && !p.Relatorios.Any(r => r.AnoMes == anoMes))
.OrderBy(r => r.Nome)
.Select(r => new { r.Id, r.Nome })
.ToList();
publicadores.Insert(0, new { Id = 0, Nome = "" });
ViewBag.Publicadores = new SelectList(publicadores, "Id", "Nome");
}
// GET: Relatorios/Details/5
public ActionResult Details(int id)
{
return View();
}
private void LoadCombosCadastro()
{
DateTime data = DateTime.Today.AddMonths(-1);
LoadAnos(data.Year);
LoadMeses(data.Month);
LoadTipos();
LoadPublicadores();
}
// GET: Relatorios/Create
//public ActionResult Create()
//{
// DateTime data = DateTime.Today.AddMonths(-1);
// LoadAnos(data.Year);
// LoadMeses(data.Month);
// LoadTipos();
// LoadPublicadores(data.Year.ToString() + data.Month.ToString().PadLeft(2, '0'));
// return View();
//}
public ActionResult Create(bool? showAll)
{
if (!showAll.HasValue || showAll.Value == true)
{
LoadCombosCadastro();
}
else
{
DateTime data = DateTime.Today.AddMonths(-1);
LoadAnos(data.Year);
LoadMeses(data.Month);
LoadTipos();
LoadPublicadores(data.Year.ToString() + data.Month.ToString().PadLeft(2, '0'));
}
return View();
}
// POST: Relatorios/Create
[HttpPost]
public ActionResult Create(Relatorios relatorio)
{
try
{
relatorio.AnoMes = relatorio.Ano.ToString() + relatorio.Mes.ToString().PadLeft(2, '0');
db.Relatorios.Add(relatorio);
var publicador = db.Publicadores.Where(p => p.Id == relatorio.IdPublicador).First();
publicador.IdTipo = relatorio.IdTipo;
db.SaveChanges();
return RedirectToAction("Create", new { showAll = false });
}
catch
{
return View();
}
}
// GET: Relatorios/Edit/5
public ActionResult Edit(int id)
{
// LoadCombosCadastro();
var relatorio = db.Relatorios.Find(id);
relatorio.Ano = int.Parse(relatorio.AnoMes.Substring(0, 4));
relatorio.Mes = int.Parse(relatorio.AnoMes.Substring(4, 2));
LoadAnos(relatorio.Ano);
LoadMeses(relatorio.Mes);
LoadTipos();
LoadPublicadores();
return View(relatorio);
}
// POST: Relatorios/Edit/5
[HttpPost]
public ActionResult Edit(int id, Relatorios relatorio)
{
try
{
if (ModelState.IsValid)
{
relatorio.AnoMes = relatorio.Ano.ToString() + relatorio.Mes.ToString().PadLeft(2, '0');
db.Entry(relatorio).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", new
{
Pagina = Request.QueryString["Pagina"],
anoMes = Request.QueryString["anoMes"]
});
}
LoadCombosCadastro();
return View(relatorio);
}
catch (Exception)
{
LoadCombosCadastro();
return View(relatorio);
}
}
// GET: Relatorios/Delete/5
public ActionResult Delete(int id)
{
var relatorio = db.Relatorios.Find(id);
relatorio.Ano = int.Parse(relatorio.AnoMes.Substring(0, 4));
relatorio.Mes = int.Parse(relatorio.AnoMes.Substring(4, 2));
return View(relatorio);
}
// POST: Relatorios/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var relatorio = db.Relatorios.Find(id);
db.Relatorios.Remove(relatorio);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<file_sep>using RelatoriosCongregação.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RelatoriosCongregação.Controllers
{
public class TestController : Controller
{
private FieldServiceEntities db = new FieldServiceEntities();
// GET: Test
public ActionResult Index()
{
LoadGrupos();
LoadPublicadores();
LoadTipos();
return View();
}
private void LoadPublicadores()
{
var publicadores = db.Publicadores
.OrderBy(r => r.Nome)
.ToList();
ViewBag.Publicadores = new SelectList(publicadores, "Id", "Nome");
}
public void LoadGrupos()
{
var grupos = db.Grupos
.OrderBy(r => r.Grupo)
.ToList();
ViewBag.Grupos = new SelectList(grupos, "Id", "Grupo");
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetPublicadoresByGrupo(int id)
{
var publicadores = db.Publicadores
.Where(p => p.IdGrupo == id)
.OrderBy(r => r.Nome)
.Select(r => new { r.Nome, r.Id })
.ToList();
return Json(publicadores, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetTipoPublicador(int id)
{
var idTipo = db.Publicadores
.Where(p => p.Id == id)
.Select(r => r.IdTipo)
.FirstOrDefault();
return Json(idTipo, JsonRequestBehavior.AllowGet);
}
private void LoadTipos()
{
var tipos = db.Tipos
.OrderBy(r => r.Tipo)
.ToList();
ViewBag.Tipos = new SelectList(tipos, "Id", "Tipo");
}
public ActionResult GetRelatorioPublicador(int idPublicador, int ano, int mes)
{
var anoMes = ano.ToString() + mes.ToString().PadLeft(2, '0');
var rel = db.Relatorios
.Where(r => r.IdPublicador == idPublicador && r.AnoMes == anoMes)
.Select(r => r)
.FirstOrDefault();
if (rel == null)
{
rel = new Relatorios();
rel.IdTipo = db.Publicadores.Where(p => p.Id == idPublicador).Select(r => r.IdTipo).FirstOrDefault();
rel.Ano = ano;
rel.Mes = mes;
}
else
{
rel.Mes = int.Parse(rel.AnoMes.Substring(4, 2));
rel.Ano = int.Parse(rel.AnoMes.Substring(0, 4));
}
var result = new
{
IdTipo = rel.IdTipo,
Horas = rel.Horas,
rel.Publicacoes,
rel.Videos,
rel.Revisitas,
rel.Estudos
};
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace RelatoriosCongregação.Models
{
public class TotaisRelatorio
{
public string Tipo { get; set; }
[Display(ShortName = "Qtd. Public.")]
public int QtdPublicadores { get; set; }
[DisplayFormat(DataFormatString = "{0:n0}")]
public int Horas { get; set; }
public int Videos { get; set; }
public int Publicacoes { get; set; }
public int Revisitas { get; set; }
public int Estudos { get; set; }
}
public class RelatorioGeral
{
public IQueryable<TotaisRelatorio> Totais { get; set; }
public IQueryable<Relatorios> Detalhado { get; set; }
public List<PublicadoresPorGrupo> Irregulares { get; set; }
}
public class PublicadoresPorGrupo
{
public string Dirigente { get; set; }
public List<string> Publicadores { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace RelatoriosCongregação
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute("GetPublicadoresByGrupo",
"test/getpublicadoresbygrupo/",
new { controller = "Test", action = "GetPublicadoresByGrupo" },
new[] { "RelatoriosCongregação.Controllers" });
routes.MapRoute("GetTipoPublicador",
"test/gettipopublicador/",
new { controller = "Test", action = "GetTipoPublicador" },
new[] { "RelatoriosCongregação.Controllers" });
routes.MapRoute("GetRelatorioPublicador",
"test/getrelatoriopublicador/",
new { controller = "Test", action = "GetRelatorioPublicador" },
new[] { "RelatoriosCongregação.Controllers" });
}
}
}
<file_sep>namespace RelatoriosCongregação.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class FieldServiceEntities : DbContext
{
public FieldServiceEntities()
: base("name=FieldServiceModel")
{
}
public virtual DbSet<Grupos> Grupos { get; set; }
public virtual DbSet<Publicadores> Publicadores { get; set; }
public virtual DbSet<Relatorios> Relatorios { get; set; }
public virtual DbSet<Tipos> Tipos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Grupos>()
.Property(e => e.Grupo)
.IsUnicode(false);
modelBuilder.Entity<Grupos>()
.Property(e => e.Dirigente)
.IsUnicode(false);
modelBuilder.Entity<Grupos>()
.HasMany(e => e.Publicadores)
.WithRequired(e => e.Grupo)
.HasForeignKey(e => e.IdGrupo)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Publicadores>()
.Property(e => e.Nome)
.IsUnicode(false);
modelBuilder.Entity<Publicadores>()
.HasMany(e => e.Relatorios)
.WithRequired(e => e.Publicadores)
.HasForeignKey(e => e.IdPublicador)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Relatorios>()
.Property(e => e.AnoMes)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<Tipos>()
.Property(e => e.Tipo)
.IsUnicode(false);
modelBuilder.Entity<Tipos>()
.HasMany(e => e.Publicadores)
.WithRequired(e => e.Tipos)
.HasForeignKey(e => e.IdTipo)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Tipos>()
.HasMany(e => e.Relatorios)
.WithRequired(e => e.Tipos)
.HasForeignKey(e => e.IdTipo)
.WillCascadeOnDelete(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RelatoriosCongregação.Models;
namespace RelatoriosCongregação.Controllers.Cadastros
{
public class PublicadoresController : Controller
{
private FieldServiceEntities db = new FieldServiceEntities();
// GET: Publicadores
public ActionResult Index(string search)
{
var publicadores = db.Publicadores.Include(p => p.Grupo).Include(p => p.Tipos);
if (!string.IsNullOrWhiteSpace(search))
{
publicadores = publicadores.Where(p => p.Nome.Contains(search) || p.Grupo.Grupo.Contains(search));
}
return View(publicadores.OrderBy(p => p.Nome).ToList());
}
// GET: Publicadores/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Publicadores publicadores = db.Publicadores.Find(id);
if (publicadores == null)
{
return HttpNotFound();
}
return View(publicadores);
}
// GET: Publicadores/Create
public ActionResult Create()
{
ViewBag.IdGrupo = new SelectList(db.Grupos, "Id", "Grupo");
ViewBag.IdTipo = new SelectList(db.Tipos, "Id", "Tipo");
ViewBag.Ativo = true;
return View();
}
// POST: Publicadores/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Nome,IdGrupo,IdTipo")] Publicadores publicadores)
{
if (ModelState.IsValid)
{
publicadores.Id = db.Publicadores.Max(p => p.Id) + 1;
publicadores.Ativo = true;
db.Publicadores.Add(publicadores);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IdGrupo = new SelectList(db.Grupos, "Id", "Grupo", publicadores.IdGrupo);
ViewBag.IdTipo = new SelectList(db.Tipos, "Id", "Tipo", publicadores.IdTipo);
return View(publicadores);
}
// GET: Publicadores/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Publicadores publicadores = db.Publicadores.Find(id);
if (publicadores == null)
{
return HttpNotFound();
}
ViewBag.IdGrupo = new SelectList(db.Grupos, "Id", "Grupo", publicadores.IdGrupo);
ViewBag.IdTipo = new SelectList(db.Tipos, "Id", "Tipo", publicadores.IdTipo);
return View(publicadores);
}
// POST: Publicadores/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Nome,IdGrupo,IdTipo,Ativo")] Publicadores publicadores)
{
if (ModelState.IsValid)
{
db.Entry(publicadores).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.IdGrupo = new SelectList(db.Grupos, "Id", "Grupo", publicadores.IdGrupo);
ViewBag.IdTipo = new SelectList(db.Tipos, "Id", "Tipo", publicadores.IdTipo);
return View(publicadores);
}
// GET: Publicadores/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Publicadores publicadores = db.Publicadores.Find(id);
if (publicadores == null)
{
return HttpNotFound();
}
return View(publicadores);
}
// POST: Publicadores/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Publicadores publicadores = db.Publicadores.Find(id);
db.Publicadores.Remove(publicadores);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RelatoriosCongregação.Models
{
[Table("Grupos")]
public class Grupos
{
[Key(), DatabaseGenerated( DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(50), Required(AllowEmptyStrings = false, ErrorMessage = "Nome do grupo obrigatório")]
public string Grupo { get; set; }
[StringLength(50), Required(AllowEmptyStrings = false, ErrorMessage = "Nome do Dirigente obrigatório")]
public string Dirigente { get; set; }
public virtual ICollection<Publicadores> Publicadores { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace RelatoriosCongregação.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
public partial class Relatorios
{
public int Id { get; set; }
public string AnoMes { get; set; }
[NotMapped]
public int Ano { get; set; }
[NotMapped]
public int Mes { get; set; }
[Display(Description = "Publicador")]
public int IdPublicador { get; set; }
public int IdTipo { get; set; }
public int Horas { get; set; }
public int Videos { get; set; }
[Display(Name = "Publicações")]
public int Publicacoes { get; set; }
public int Revisitas { get; set; }
public int Estudos { get; set; }
public string Observacoes { get; set; }
public virtual Publicadores Publicadores { get; set; }
public virtual Tipos Tipos { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace RelatoriosCongregação.Models
{
public class RelatoriosContext : DbContext
{
public RelatoriosContext(): base("name=CampoEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Grupos> Grupos { get; set; }
}
}
|
50ea9cc8cfaea74621f87ddaeca14e46ff2504db
|
[
"C#"
] | 9
|
C#
|
robsonab/Relatorios
|
525dfc9bcd10d1f5da66f77722f175c0ef06c6af
|
c762fb2e9e399be2f393cd0fc7b35a8cb6bd588d
|
refs/heads/master
|
<repo_name>vladique00/Quest-Tsekh-1<file_sep>/TCP/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO.Ports;
using System.IO;
namespace TCP
{
class Program
{
const int port = 800; // порт для прослушивания подключений
static string[] ports = SerialPort.GetPortNames();
static SerialPort serialPort = new SerialPort(ports[1], 9600);
static void SerialListenerThread()
{
while(true)
{
try
{
String str = serialPort.ReadLine();
DateTime now = DateTime.Now;
Console.WriteLine(now.ToShortDateString() + " " + now.ToShortTimeString());
Console.WriteLine(str);
File.AppendAllText(@"c:\log.txt", now.ToShortDateString()+" "+now.ToShortTimeString()+ "\r\n");
File.AppendAllText(@"c:\log.txt", " "+str+"\r\n"+"\r\n");
}
catch
{
}
}
}
static void Main(string[] args)
{
reconnect:
try
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
if (!serialPort.IsOpen)
{
serialPort.Open();
Console.WriteLine(ports[1] + " is open");
}
}
catch
{
Console.WriteLine("Ports not exists");
goto reconnect;
}
TcpListener server = null;
try
{
IPAddress localAddr = IPAddress.Parse("0.0.0.0");
server = new TcpListener(localAddr, port);
// запуск слушателя
server.Start();
Byte[] bytes = new Byte[256];
String _data = null;
Thread myThread = new Thread(SerialListenerThread);
myThread.Start();
while (true)
{
Console.WriteLine("Ожидание подключений... ");
// получаем входящее подключение
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("\r\n" + "Подключен клиент. Выполнение запроса...");
// получаем сетевой поток для чтения и записи
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
_data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", _data);
String str = "";
if (_data == "r0s0t\n")
{
try
{
serialPort.WriteLine("\r\n:r#!\r\n");
serialPort.WriteLine("\r\n");
str = "Рестарт";
}
catch
{
goto reconnect;
}
}
if (_data == "d1r1\n")
{
try
{
serialPort.WriteLine("\r\n:1#!\r\n");
serialPort.WriteLine("\r\n");
str = "Команда открытия двери №1";
}
catch
{
goto reconnect;
}
}
if (_data == "d1r2\n")
{
try
{
serialPort.WriteLine("\r\n:2#!\r\n");
serialPort.WriteLine("\r\n");
str = "Команда открытия двери №2";
}
catch
{
goto reconnect;
}
}
if (_data == "d1r3\n")
{
try
{
serialPort.WriteLine("\r\n:3#!\r\n");
serialPort.WriteLine("\r\n");
str = "Команда открытия двери №3";
}
catch
{
goto reconnect;
}
}
if (_data == "d1r4\n")
{
try
{
serialPort.WriteLine("\r\n:4#!\r\n");
serialPort.WriteLine("\r\n");
str = "Команда открытия двери №4";
}
catch
{
goto reconnect;
}
}
DateTime now = DateTime.Now;
Console.WriteLine(now.ToShortDateString() + " " + now.ToShortTimeString());
Console.WriteLine(str);
File.AppendAllText(@"c:\log.txt", now.ToShortDateString()+" "+ now.ToShortTimeString() + "\r\n");
File.AppendAllText(@"c:\log.txt", " " + str +"\r\n"+"\r\n");
//byte[] msg = System.Text.Encoding.ASCII.GetBytes(_data);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//Console.WriteLine("Sent: {0}", _data);
}
// закрываем подключение
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
if (server != null)
server.Stop();
}
}
}
}
<file_sep>/README.md
# Quest-Tsekh-1
|
57818d5ff262e84752bfe69fbce33d0b8dff8c5a
|
[
"Markdown",
"C#"
] | 2
|
C#
|
vladique00/Quest-Tsekh-1
|
e2e78a4ea9546b7c59fe9e2365de9a1dc8859937
|
4f449f16385bcfe49e1c927475c8d1ba95bf16f2
|
refs/heads/master
|
<repo_name>ginsbar76/dupfinder<file_sep>/src/esx_acceptor/FileExtension_Acceptor.java
package esx_acceptor;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class FileExtension_Acceptor implements I_Acceptor {
Collection<String> extension_collection = new ArrayList<String>();
public boolean match_extensions(String txt) {
Iterator<String> it = extension_collection.iterator();
while (it.hasNext()) {
boolean okExtension = txt.toLowerCase().endsWith(it.next());
if (okExtension) {
return true;
}
}
return false;
}
public void add_extension(String txt) {
extension_collection.add(txt);
// System.out.println("not yey implemented");
}
public void remove_extension(String txt) {
if (extension_collection.contains(txt)) {
extension_collection.remove(txt);
}
}
public FileExtension_Acceptor(String[] extensions) {
if (extensions != null) {
int length = extensions.length;
for (String s : extensions) {
add_extension(s);
}
} else {
extensions = null;
}
}
public FileExtension_Acceptor() {
// TODO Auto-generated constructor stub
}
@Override
public boolean Accept(File f) {
if (f.isDirectory()){
return true;
}
else if (extension_collection.size() != 0) { // extensions!=null
return match_extensions(f.getName());
} else {
return true; // tous les fichiers sont acceptés
}
}
@Override
public String getText() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setText() {
// TODO Auto-generated method stub
}
}
<file_sep>/src/esx_model/I_collecFunction.java
package esx_model;
public interface I_collecFunction {
public void execFunc();
public static void log(String s) {
}
}
<file_sep>/src/esx_acceptor/DirFile_Acceptor.java
package esx_acceptor;
import java.io.File;
import esx_enums.DirFile_Selector;
public class DirFile_Acceptor implements I_Acceptor {
DirFile_Selector filtre;
public DirFile_Acceptor() {
// TODO Auto-generated constructor stub
}
public DirFile_Acceptor(DirFile_Selector filtre) {
super();
this.filtre = filtre;
}
@Override
public String getText() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setText() {
// TODO Auto-generated method stub
}
public void setSelection(DirFile_Selector filtre) {
this.filtre = filtre;
}
@Override
public boolean Accept(File f) {
switch (filtre) { // FILES_n_DIR, FILES_ONLY, DIR_ONLY
case FILES_n_DIR: {
return true;
}
case FILES_ONLY: {
if (!f.isDirectory())return true;
break;
}
case DIR_ONLY: {
if (f.isDirectory())return true;
break;
}
}
return false;
}
@Override
public String toString() {
String ret;
switch (filtre) { // FILES_n_DIR, FILES_ONLY, DIR_ONLY
case FILES_n_DIR: {
logTitre("Affichage des fichiers et directories");
break;
}
case FILES_ONLY: {
logTitre("Affichage des fichiers uniquement");
break;
}
case DIR_ONLY: {
logTitre("Affichage des directories uniquement");
break;
}
}
return "DirFile_Acceptor []";
}
public static void log(String s) {
System.out.println(s);
}
public static void logTitre(String s) {
System.out.println("---------------------------------------------------------");
System.out.println(s);
System.out.println("---------------------------------------------------------");
}
}
<file_sep>/src/esx_collection/Ix_DirCollection.java
package esx_collection;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
/**
* Interface pour un gestionnaire d'objets implémentant l'interface Ix_DirItem
*
* Chaque classe qui implémente cette interface est responsable
* de créer une collection d'objets qui associe:
* un entier (la clé),
* un objet de classe implémentant l'interface Ix_DirItem.
*
* Interface Ix_DirItem, possède une référence pour cet objet et une référence pour un objet parent.
*
* Méthodes del'interface:
* AddItem: insertion d'un objet dans la collection implémentée par les classes qui implémentent cette interface.
*
*
* BuildDico, construit un lexique à partir des objets de la collection des classes impléntées.
* Le lexique implémente l'interface Ix_Dico
* Le lexique découpe chaque élément de la collection en éléments simples grace à un regex.
*
* Ix_DirCollection { Key, Text }
*
* Ix_Dico
* Text -> constitué de {items}
* Ix_Dico, collection de {items, {Key vers les éléments de (Ix_DirCollection)} }
*
* Autres Méthodes del'interface:
* getAllDuplicates(int minFreq), retourne une liste des items de notre lexiqueque qui ont une frequence supérieure à un seuil donné.
* getAllRef(String item),retourne une liste des ref de notre item, on pourra retrouver les éléments originaux de notre collection pour effectuer des comparaisons.
* @author macbooksadler
*
*/
public interface Ix_DirCollection {
/**
* Ajoute un item
* @param E: ajoute au container un élément qui implémente l'iterface Ix_DirItem
* @return la clé de l'élément ajouté au container
*/
public int AddItem(Ix_DirItem E);//obsolete
public int AddItem(int index_parent, File file);
public Ix_DirItem getItem(int K);
/**
*
* @return une collection d'objets (les directories)
*/
public ArrayList<Ix_DirItem> getAllDir();
/**
*
* @return une collection d'objets (les directories
*/
public ArrayList<Ix_DirItem> getAllFiles();
public Collections GetAllItems();
//public int getInsertedRef(); //
// iterator getDirIterator();
// iterator getFileIterator();
public void BuildDico();
public ArrayList<String> getAllItems();
public ArrayList<Integer> getAllRef(String item);
public ArrayList<String> getAllDuplicates(int minFreq);
public void ShowFrequencies();
public void ShowFrequentItems(int minFreg);
public void setRegex(String string);
}
<file_sep>/src/esx_model/Dico_Interface2.java
package esx_model;
public class Dico_Interface2 implements I_collecFunction{
public Dico_Interface2() {
// TODO Auto-generated constructor stub
}
@Override
public void execFunc() {
log(".............. V 2 ");
}
//_____________________________________________________________________________________
public static void log(String s){
System.out.println(s);
}
}
<file_sep>/src/esx_collection/Ix_DirItem.java
package esx_collection;
public interface Ix_DirItem {
/**
* <p> retourne une chaine de titre pour cet objet </p>
* @return
*/
public String toTitle();//retourne un titre pour l'objet (chane de caractère pour comparaison)
public int setRef(int ref);
public int setRefParent(int refParent);
public boolean isDirectory();
}
<file_sep>/src/esx_acceptor/I_Acceptor.java
package esx_acceptor;
import java.io.File;
public interface I_Acceptor {
boolean Accept(File f);
public String getText();
public void setText();
}
<file_sep>/src/esx_tools/VolumeTool.java
package esx_tools;
import java.io.File;
import esx_collection.Ix_DirItem;
public class VolumeTool {
int ref;
int refParent;
VolumeData data = null;
//_____________________________________________________________________________________
public VolumeTool() {
// TODO Auto-generated constructor stub
}
public VolumeTool(int refParent, File f) {
this.refParent = refParent;
data = new VolumeData(f);
}
//_____________________________________________________________________________________
public int setRef(int ref) {
this.ref = ref;
return 0;
}
public int setRefParent(int refParent) {
this.refParent = refParent;
return 0;
}
public int getRefParent(){
return refParent;
}
public int getRef(){
return ref;
}
// -------------------------------------------------------------------------------------------------------
boolean isdir;
public boolean isDir(){
return data.isDirectory();
}
// -------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------
/**
* @return the index_owner
*/
public int getIndex_owner() {
return refParent;
}
/**
* @return the data
*/
public VolumeData getData() {
return data;
}
// -------------------------------------------------------------------------------------------------------
/**
* @param index_owner the index_owner to set
*/
public void setIndex_owner(int index_owner) {
this.refParent = index_owner;
}
/**
* @param data the data to set
*/
public void setData(VolumeData data) {
this.data = data;
}
// -------------------------------------------------------------------------------------------------------
}
|
18d793b19cc3b578908bcb07e2f67da0ef634fc1
|
[
"Java"
] | 8
|
Java
|
ginsbar76/dupfinder
|
d90e72ca9163741790fc2a6b48f1311d58ecfa4f
|
63a72d3b31bd754727115a39181448cf9266b3f9
|
refs/heads/master
|
<repo_name>smallsnail-wh/example-camunda-custom-identity-service<file_sep>/src/main/java/example/camunda/web/GroupController.java
package example.camunda.web;
import example.camunda.domain.Group;
import example.camunda.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by ashlah on 31/07/17.
*/
@RestController
@RequestMapping("/groups")
public class GroupController {
private final GroupService groupService;
@Autowired
public GroupController(GroupService groupService) {
this.groupService = groupService;
}
@RequestMapping(method = RequestMethod.POST)
Group postGroup(@RequestBody Group group) {
return groupService.save(group);
}
}
<file_sep>/src/main/java/example/camunda/domain/Group.java
package example.camunda.domain;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
* Created by ashlah on 28/07/17.
*/
@Entity
@Table(name = "`group`")
@Setter @Getter
public class Group implements org.camunda.bpm.engine.identity.Group {
@Id
// @Column(columnDefinition = "char(36)")
// @GeneratedValue(generator = "system-uuid")
// @GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;
@Column(name = "`name`")
private String name;
@Column(name = "`type`")
private String type;
}
<file_sep>/src/main/java/example/camunda/domain/GroupRepository.java
package example.camunda.domain;
import org.springframework.data.repository.CrudRepository;
/**
* Created by ashlah on 28/07/17.
*/
public interface GroupRepository extends CrudRepository<Group, String> {
Group findById(String id);
}
<file_sep>/settings.gradle
rootProject.name = 'example-camunda-custom-identity-service'
<file_sep>/src/main/java/example/camunda/domain/User.java
package example.camunda.domain;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
/**
* Created by ashlah on 28/07/17.
*/
@Entity
@Setter @Getter
public class User implements org.camunda.bpm.engine.identity.User {
@Id
// @Column(columnDefinition = "char(36)")
// @GeneratedValue(generator = "system-uuid")
// @GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToOne
private Group group;
}
|
ecea24f21e63dcdab90581a2895bd9555a5cae35
|
[
"Java",
"Gradle"
] | 5
|
Java
|
smallsnail-wh/example-camunda-custom-identity-service
|
010c178032efdc200823a187502bb69981aa5010
|
dda9a980e5433722b99723bac5a1e424c4276da6
|
refs/heads/master
|
<repo_name>mikelval82/MULTI_GEERT<file_sep>/DYNAMIC/dynamic.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
import sys
import os
from PyQt5 import QtCore
from os import listdir
from os.path import isfile, join
import importlib
#from importlib import reload
class dynamic(QtCore.QThread):
log_emitter = QtCore.pyqtSignal(str)
def __init__(self, current_GUI, listWidget, RawCode):
super(dynamic, self).__init__(None)
self.current_GUI = current_GUI
self.RawCode = RawCode
self.listWidget = listWidget
self.current_row = 0
def load_module(self, fileName):
########### separo path y nombre del modulo ##############
aux = fileName.split("/")
path = ''
for i in range(1, len(aux)-1):
path += aux[i] + '/'
module_name = aux[-1][:-3]
#---------------------------------------------------------
sys.path.append(os.path.realpath('./AUXILIAR_CODE/'))
try:
module = importlib.import_module(module_name)
my_class = getattr(module, 'MyClass')
self.my_instance = my_class(self.current_GUI)
self.my_instance.start()
self.log_emitter.emit('DONE!')
except:
self.log_emitter.emit('Cannot load the module!')
def save_script(self):
script = self.listWidget.currentItem().text()
code = self.RawCode.toPlainText()
# open file in write mode
f=open("./AUXILIAR_CODE/" + script, "w")
f.write(code)
f.flush()
f.close()
# update values
self.load_auxiliar_code()
self.edited = True
def load_auxiliar_code(self):
self.listWidget.clear()
mypath = './AUXILIAR_CODE/'
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in onlyfiles:
self.listWidget.addItem(file)
self.listWidget.itemClicked.connect(self.show_code)
self.listWidget.setCurrentRow(self.current_row)
self.show_code(self.listWidget.currentItem())
def show_code(self, scriptItem):
# read the file
f=open("./AUXILIAR_CODE/" + scriptItem.text(), "r")
contents =f.read()
f.close()
# update code viewer
self.RawCode.setPlainText( contents )
self.current_row = self.listWidget.currentRow()
<file_sep>/DATA_MANAGER/file_IO.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from EDF.writeEDFFile import edf_writter
from multiprocessing import Process
class io_manager:
def __init__(self):
self.edf = edf_writter()
self.fileName = 'unknown'
self.Trial = 0
self.file_created = False
def create_file(self):
self.edf.new_file(self.fileName + '_Trial_' + str(self.Trial) + '.edf')
self.file_created = True
def close_file(self):
self.edf.close_file()
self.Trial+=1
self.file_created = False
def append_to_file(self, stream):
self.edf.append(stream)
p = Process(target=self.edf.writeToEDF())
p.start()
def online_annotation(self, event, instant, duration = -1):
self.edf.annotation(instant, duration, event)
<file_sep>/EDF/writeEDFFile.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from __future__ import division, print_function, absolute_import
import os
import pyedflib
class edf_writter:
def __init__(self, CHANNELS=8, CHANNEL_IDS=['Fp1','Fp2','T1','T2','O1','O2','P1','P2'], SAMPLE_RATE=250):
self.CHANNELS = CHANNELS
self.CHANNEL_IDS = CHANNEL_IDS
self.SAMPLE_RATE = SAMPLE_RATE
def new_file(self,path):
data_file = os.path.join('.', path)
self.file = pyedflib.EdfWriter(data_file, self.CHANNELS, file_type=pyedflib.FILETYPE_EDFPLUS)
self.channel_info = []
self.data_list = []
def append(self, all_data_store):
for channel in range(self.CHANNELS):
ch_dict = {'label': self.CHANNEL_IDS[channel], 'dimension': 'uV', 'sample_rate': self.SAMPLE_RATE, 'physical_max': all_data_store[channel,:].max(), 'physical_min': all_data_store[channel,:].min(), 'digital_max': 32767, 'digital_min': -32768, 'transducer': '', 'prefilter':''}
self.channel_info.append(ch_dict)
self.data_list.append(all_data_store[channel,:])
def writeToEDF(self):
self.file.setSignalHeaders(self.channel_info)
self.file.writeSamples(self.data_list)
def annotation(self, instant, duration, event):
self.file.writeAnnotation(instant, duration, event)
def close_file(self):
self.file.close()
del self.file
def __del__(self):
print("deleted")
<file_sep>/QTDesigner/Monitor_EEG_plotter.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>)s
@email: %(<EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED))
@DOI:
"""
import pyqtgraph as pg
from pyqtgraph import Point
import numpy as np
class Monitor_EEG_plotter(pg.GraphicsWindow):
pg.setConfigOption('background', 'k')
pg.setConfigOption('foreground', 'm')
def __init__(self, parent=None, **kargs):
pg.GraphicsWindow.__init__(self, **kargs)
self.setParent(parent)
def set_params(self, channels, contador, num_channels=8, x_dim=250, y_dim=900):
self.num_channels = num_channels
self.x_dim = x_dim
self.y_dim = y_dim
self.curves = []
self.lines = {'lines':[], 'points':[], 'counter':[]}
self.scale = 50
self.positions = [(i+1)*100 for i in range(self.num_channels)]
self.channels = channels
self.contador = contador
def set_scale(self, value):
self.scale = value
def set_space(self, value):
self.positions = [(i+1)*100*(value/100+1)for i in range(self.num_channels)]
def set_scroll(self, value):
max0 = (self.num_channels+1)*100
x = self.positions[-1] - (self.num_channels+1)*100
desp = (value/100)*x
self.plotter.setYRange(value + desp, max0 + desp + value)
def redraw(self, value):
self.x_dim = value
self.plotter.setXRange(0, self.x_dim)
def draw_vertical_line(self, label):
item = pg.InfiniteLine(movable=True, angle=90, label=label, pen=pg.mkPen('y', width=3),
labelOpts={'position':.9, 'color': (100,255,100), 'fill': (100,255,100,30), 'movable': True})
self.plotter.addItem(item)
self.lines['lines'].append( item )
self.lines['points'].append( Point(0,0) )
self.lines['counter'].append( self.contador.value )
def create_plot(self):
self.setWindowTitle('EEG')
self.plotter = self.addPlot()
self.plotter.setLabel('left', 'Voltage', units='mV')
self.plotter.setLabel('bottom', "Time", units='seg')
self.plotter.showGrid(True, True, alpha = 0.5)
self.plotter.setYRange(0, (self.num_channels+1)*100)
self.plotter.setXRange(0, self.x_dim)
###### !!!!!! aqui falta sacar del inlet del damanager los nombres de los canales, y calcular las posiciones de forma automatica segun el y_dim!!!!!!!!!!1
# self.plotter.getAxis('left').setTicks([ [(100, 'FP1'), (200, 'FP2'), (300, 'C1'), (400, 'C2'), (500, 'P1'), (600, 'P2'), (700, 'O1'), (800, 'O2')] ])
self.plotter.getAxis('left').setTicks([[(pos, channel) for pos,channel in zip(self.positions, self.channels) ]])
for i in range(self.num_channels):
self.curves.append( self.plotter.plot([], pen=(i,self.num_channels*1.3)) )
def normalize(self, sample):
return (sample-np.mean(sample))/np.std(sample)
def remove_lines(self):
if self.lines['lines']:
for line in self.lines['lines']:
self.plotter.removeItem(line)
def update(self, sample):
sample = self.normalize(sample)
self.plotter.getAxis('left').setTicks([[(pos, channel) for pos,channel in zip(self.positions, self.channels) ]])
#----- draw curves ---------------------------
for i in range(self.num_channels):
self.curves[i].setData(sample[i] * self.scale + self.positions[i])
#--------- draw markers -----------------------
if self.lines:
for line, point, counter in zip(self.lines['lines'], self.lines['points'], self.lines['counter']):
point[0] = self.contador.value-counter
line.setPos(point)
if point[0] >= self.x_dim:
self.plotter.removeItem(line)
<file_sep>/GUI/EEG_monitor_shortcuts_manager.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from PyQt5.QtWidgets import QShortcut
from PyQt5.QtGui import QKeySequence
class EEG_shortcuts:
def __init__(self, parent):
self.sequences = []
self.parent = parent
def define_local_shortcuts(self, run_callback, add_marker_callback):
sequence = {
'Ctrl+s': lambda: run_callback('SHOW'),
'Ctrl+r': lambda: run_callback('RECORD'),
'Alt+0': lambda: add_marker_callback('Label_0'),
'Alt+1': lambda: add_marker_callback('Label_1'),
'Alt+2': lambda: add_marker_callback('Label_2'),
'Alt+3': lambda: add_marker_callback('Label_3'),
'Alt+4': lambda: add_marker_callback('Label_4'),
'Alt+5': lambda: add_marker_callback('Label_5'),
'Alt+6': lambda: add_marker_callback('Label_6'),
'Alt+7': lambda: add_marker_callback('Label_7'),
'Alt+8': lambda: add_marker_callback('Label_8'),
'Alt+9': lambda: add_marker_callback('Label_9'),
}
for key, value in list(sequence.items()):
s = QShortcut(QKeySequence(key),self.parent, value)
self.sequences.append(s)
<file_sep>/DATA_MANAGER/data_acquirer.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from multiprocessing import Process, Value
from multiprocessing.managers import BaseManager
from DATA_MANAGER.EEG_data_manager import EEG_data_manager
import numpy as np
#import time
#from datetime import datetime
class data_acquirer(Process):
class MyManager(BaseManager):
pass
def Manager(self):
m = self.MyManager()
m.start()
return m
def __init__(self, inlets):
Process.__init__(self)
self.inlets = inlets
self.buffers = {'inlet':[], 'buffer':[], 'counter':[], 'streaming':[], 'active':[]}
# self.old = datetime.now().timestamp() * 1000
def call_method(self, o, name, inlet, type):
if type =='EEG':
return getattr(o, name)(num_channels=inlet.channel_count, srate=inlet.info().nominal_srate())
def set_up(self):
for index, inlet in enumerate(self.inlets):
if inlet.info().type() == 'EEG':
self.MyManager.register('buffer_'+str(index), EEG_data_manager)
# ---- set buffers -----
self.buffers['inlet'].append( inlet )
self.buffers['buffer'].append ( self.call_method(self.Manager(), 'buffer_'+str(index), inlet, inlet.info().type()) )
self.buffers['counter'].append( Value('i',0) )
self.buffers['streaming'].append( Value('i',0) )
self.buffers['active'].append( Value('i',1) )
def run(self):
while True:
# time.sleep(1)
if not np.any([is_active.value for is_active in self.buffers['active']]):
break
else:
for index in range(len(self.inlets)):
sample, timestamp = self.buffers['inlet'][index].pull_sample(timeout=0.0)
# monitors_streaming = [is_streaming.value for is_streaming in self.buffers['streaming']]
if sample and self.buffers['streaming'][index].value:
self.buffers['buffer'][index].append(sample, timestamp)
self.buffers['counter'][index].value += 1
# new = datetime.now().timestamp() * 1000
# print(' acquire: ', new-self.old)
# self.old = new
#
<file_sep>/GUI/M_GEERT_gui.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
import os
from PyQt5.QtWidgets import QMainWindow, QFileDialog
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
from QTDesigner.M_GEERT_QT import Ui_M_GEERT as UI
from GUI.EEG_monitor_wrapper import EEG_monitor_wrapper
from UTILITIES.GLOBAL import constants
from LOGGING.logger import logger
from COM.trigger_server_2 import trigger_server
from DYNAMIC.dynamic import dynamic
from LSL.mystreamerlsl import StreamerLSL
from DATA_MANAGER.data_acquirer import data_acquirer
class GUI(QMainWindow, UI):
def __init__(self):
QMainWindow.__init__(self, parent=None)
#----- gui settings -----------
self.setupUi(self)
self.log = logger(self.Logger)
self.constants = constants()
self.dyn = dynamic(self, self.Scripts_List, self.Code_TextEdit)#None hay que cambiarlo por el acceso a los streams!!!!!!
self.dyn.log_emitter.connect(self.log.myprint)
self.dyn.load_auxiliar_code()
self.lsl = StreamerLSL()
self.lsl.log_emitter.connect(self.log.myprint)
#-------- Monitors List ---
self.monitors = []
#-------- controls --------
self.trigger_server_activated = False
#-------- connections ----
self.Experiment_btn.clicked.connect(self.saveFileDialog)
self.MainRecord_btn.clicked.connect(self.main_recording)
self.TCPIP_checkBox.toggled.connect(self.launch_trigger_server)
self.Host_LineEdit.textChanged.connect(lambda: self.constants.update('ADDRESS', self.Host_LineEdit.text()))
self.Port_LineEdit.textChanged.connect(lambda: self.constants.update('PORT', self.Port_LineEdit.text()))
self.ResolveStreaming_btn.clicked.connect(self.launch_lsl)
self.Activate_btn.clicked.connect(self.launch_monitor)
self.Hide_btn.clicked.connect(self.hide)
self.Run_btn.clicked.connect(lambda: self.dyn.load_module(self.Scripts_List.currentItem().text()))
self.Save_btn.clicked.connect(self.dyn.save_script)
#-------- slots -----------
self.constants.log_emitter.connect(self.log.myprint)
#------ show ----------
self.show()
def launch_lsl(self):
self.Streamings_List.clear()
for inlet in self.lsl.create_lsl():
item = QtGui.QListWidgetItem(inlet.info().name())
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
item.setCheckState(Qt.Unchecked)
self.Streamings_List.addItem(item)
def main_recording(self):
if self.monitors:
for monitor in self.monitors:
monitor.run(('RECORD'))
def launch_monitor(self):
if not self.monitors and self.lsl.inlets:
# -- check inlets selected ---
self.inlets = []
for inlet, index in zip(self.lsl.inlets, range(len(self.lsl.inlets))):
if self.Streamings_List.item(index).checkState():
self.inlets.append( inlet )
# -- run data acquirer ---
self.acq = data_acquirer(self.inlets)
self.acq.set_up()
self.acq.start()
# --- run monitors to visualice signals ----
for i in range(len(self.acq.buffers['inlet'])):
if self.acq.buffers['inlet'][i].info().type() == 'EEG':
monitor = EEG_monitor_wrapper(self.log, self.acq.buffers['inlet'][i], self.acq.buffers['buffer'][i],
self.acq.buffers['counter'][i], self.acq.buffers['streaming'][i],
self.acq.buffers['active'][i])
monitor.show()
self.monitors.append( monitor )
else:
#---- kill data acquirer and close all activef monitors -----
for monitor in self.monitors:
try:
monitor.closeEvent(None)
except:
print('No monitor!!')
self.monitors=[]
def hide(self):
if self.monitors:
for monitor in self.monitors:
if monitor.is_shown:
monitor.hide()
monitor.is_shown = False
self.Hide_btn.setStyleSheet('QPushButton {background-color: #424242; color: #fff;}')
self.Hide_btn.setText('Show')
elif not monitor.is_shown:
monitor.show()
monitor.is_shown = True
self.Hide_btn.setStyleSheet('QPushButton {background-color: #transparent; color: #ff732d;}')
self.Hide_btn.setText('Hide')
def launch_trigger_server(self):
if self.trigger_server_activated:
self.trigger_server.close_socket()
del self.trigger_server
self.trigger_server_activated = False
else:
self.trigger_server = trigger_server(self.constants)
self.trigger_server.log_emitter.connect(self.log.myprint_out)
self.trigger_server.socket_emitter.connect(self.main_recording)
self.trigger_server_activated = self.trigger_server.create_socket()
if self.trigger_server_activated:
self.trigger_server.start()
else:
del self.trigger_server
self.TCPIP_checkBox.setChecked(False)
def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, filetype = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","(*.npy)", options=options)
try:
os.mkdir(fileName)
self.constants.update('experiment', fileName)
except OSError:
self.log.myprint_error ("Creation of the directory %s failed" % fileName)
else:
self.log.myprint_out ("Successfully created the directory %s " % self.constants.experiment)
<file_sep>/LOGGING/logger.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
#%%
from PyQt5 import QtGui, QtCore
class logger():
def __init__(self, logger):
self.logger = logger
self.logger.setCenterOnScroll(True)
self.tf = QtGui.QTextCharFormat()
self.tf_yellow = QtGui.QTextCharFormat()
self.tf_green = QtGui.QTextCharFormat()
self.tf_red = QtGui.QTextCharFormat()
self.tf_yellow.setForeground(QtGui.QBrush(QtCore.Qt.yellow))
self.tf_green.setForeground(QtGui.QBrush(QtCore.Qt.green))
self.tf_red.setForeground(QtGui.QBrush(QtCore.Qt.red))
def myprint(self, text):
self.logger.setCurrentCharFormat(self.tf)
self.logger.appendPlainText(text)
self.logger.centerCursor()
def myprint_in(self, text):
self.logger.setCurrentCharFormat(self.tf_yellow)
self.logger.appendPlainText("< "+text)
self.logger.centerCursor()
def myprint_out(self, text):
self.logger.setCurrentCharFormat(self.tf_green)
self.logger.appendPlainText("> "+text)
self.logger.centerCursor()
def myprint_error(self, text):
self.logger.setCurrentCharFormat(self.tf_red)
self.logger.appendPlainText(text)
self.logger.centerCursor()
def clear(self):
self.logger.clear()<file_sep>/EDF/plot_EDFfile.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import pyedflib
import matplotlib.pyplot as plt
if __name__ == '__main__':
f = pyedflib.edfreader.EdfReader('./experimento_1/openbci_sujeto_1_0.edf')
n = f.signals_in_file
signal_labels = f.getSignalLabels()
n_min = f.getNSamples()[0]
sigbufs = [np.zeros(f.getNSamples()[i]) for i in np.arange(n)]
for i in np.arange(n):
sigbufs[i] = f.readSignal(i)
if n_min < len(sigbufs[i]):
n_min = len(sigbufs[i])
f._close()
del f
n_plot = np.min((n_min, 2000))
sigbufs_plot = np.zeros((n, n_plot))
for i in np.arange(n):
sigbufs_plot[i,:] = sigbufs[i][:n_plot]
plt.plot(sigbufs_plot[:, :n_plot].T)
<file_sep>/UTILITIES/GLOBAL.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from PyQt5 import QtCore
class constants(QtCore.QThread):
log_emitter = QtCore.pyqtSignal(str)
def __init__(self):
super(constants, self).__init__(None)
self.experiment = './experiment'
self.ADDRESS = 'localhost'
self.PORT = 10000
def update(self, param, value):
if param == 'experiment':
self.experiment = value
elif param == 'ADDRESS':
self.ADDRESS = value
elif param == 'PORT':
self.PORT = value
self.log_emitter.emit('Updated param: ' + param + ' value: ' + value)
<file_sep>/MULTI_GEERT.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Biomedical Neuroengineering Research Group (UMH); Biomedical Neuroengineering Research Group (UMH) )
@DOI:
"""
from GUI.M_GEERT_gui import GUI
from PyQt5.QtWidgets import QApplication
import sys
class MULTI_GEERT(QApplication):
def __init__(self):
QApplication.__init__(self,[''])
self.load_style()
#--- Launch GUI ---
self.gui = GUI()
#--- exec ---
sys.exit(self.exec_())
def load_style(self):
with open("QTDesigner/CSS/Fibrary.qss") as f:
self.setStyleSheet(f.read())
if __name__ == '__main__':
main = MULTI_GEERT()
<file_sep>/QTDesigner/Monitor_CARROUSEL_plotter.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>)s
@email: %(<EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED))
@DOI:
"""
import pyqtgraph as pg
from PyQt5.QtCore import QRectF
class Monitor_CARROUSEL_plotter(pg.GraphicsWindow):
pg.setConfigOption('background', 'k')
pg.setConfigOption('foreground', 'm')
def __init__(self, parent=None, **kargs):
pg.GraphicsWindow.__init__(self, **kargs)
self.setParent(parent)
self.height = 480
self.width = 640
def create_plot(self):
self.show()
self.view = self.addViewBox()
self.view.setAspectLocked(True)
self.img = pg.ImageItem(border='w')
self.view.addItem(self.img)
self.view.setRange(QRectF(0, 0, self.width, self.height ))
def update(self, sample):
self.img.setImage( sample )
<file_sep>/EEG_generator.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from pylsl import StreamInfo, StreamOutlet
import numpy as np
import time
import sys
def main(*args):
# first create a new stream info (here we set the name to BioSemi,
# the content-type to EEG, 8 channels, 100 Hz, and float-valued data) The
# last value would be the serial number of the device or some other more or
# less locally unique identifier for the stream as far as available (you
# could also omit it but interrupted connections wouldn't auto-recover)
info = StreamInfo(args[0][0], 'EEG', 8, 250, 'float32', 'myuid34234')
# now attach some meta-data (in accordance with XDF format,
# see also code.google.com/p/xdf)
chns = info.desc().append_child("channels")
for label in ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]:
ch = chns.append_child("channel")
ch.append_child_value("label", label)
ch.append_child_value("unit", "microvolts")
ch.append_child_value("type", "EEG")
info.desc().append_child_value("manufacturer", "SCCN")
cap = info.desc().append_child("cap")
cap.append_child_value("name", "EasyCap")
cap.append_child_value("size", "54")
cap.append_child_value("labelscheme", "10-20")
# next make an outlet
outlet = StreamOutlet(info)
while True:
outlet.push_sample(np.random.rand(8)*100)
time.sleep(1/250)
if __name__ == '__main__':
main(sys.argv[1:])<file_sep>/QTDesigner/ui_to_py.sh
pyuic5 EEG_monitor.ui -o EEG_monitor.py
pyuic5 M_GEERT_QT.ui -o M_GEERT_QT.py
<file_sep>/LSL/mystreamerlsl.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from PyQt5 import QtCore
from pylsl import StreamInlet, resolve_stream
class StreamerLSL(QtCore.QThread):
log_emitter = QtCore.pyqtSignal(str)
def __init__(self):
super(StreamerLSL, self).__init__(None)
def create_lsl(self):
self.inlets = []
streams = resolve_stream()
if streams:
self.inlets = [StreamInlet(stream) for stream in streams]
self.log_emitter.emit('Streams resolved!')
return self.inlets
<file_sep>/EDF/readEDFFile.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
import numpy as np
import pyedflib
import matplotlib.pyplot as plt
if __name__ == '__main__':
# f = pyedflib.data.test_generator()
f = pyedflib.edfreader.EdfReader('./experimento_1/openbci_sujeto_1_0.edf')
annotations = f.readAnnotations()
for n in np.arange(f.annotations_in_file):
print("annotation: onset is %f duration is %s description is %s" % (annotations[0][n],annotations[1][n],annotations[2][n]))
buf = f.readSignal(0)
plt.plot(buf)
f._close()
del f
<file_sep>/FILTERS/spectrum.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
#%%
import numpy as np
#from scipy import signal
from neurodsp import spectral
from lspopt.lsp import spectrogram_lspopt
class spectrum:
def __init__(self, SAMPLE_RATE=250, CHANNELS=8):
self.SAMPLE_RATE = SAMPLE_RATE
self.CHANNELS = CHANNELS
def get_spectrum(self, samples):
spectrums = []
for i in range(self.CHANNELS):
freqs, spectre = spectral.compute_spectrum(samples[i,:], self.SAMPLE_RATE)
spectrums.append(spectre)
return freqs, np.asarray(spectrums)
def get_spectrogram(self, samples):
# _, _, Sxx = signal.spectrogram(samples, self.constants.SAMPLE_RATE)
_,_, Sxx = spectrogram_lspopt(samples, self.SAMPLE_RATE, c_parameter=20.0)
return Sxx
<file_sep>/DATA_MANAGER/EEG_data_processing.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from multiprocessing import Process
from FILTERS.filter_bank_manager import filter_bank_class
from FILTERS.spectrum import spectrum
#from datetime import datetime
#import time
class EEG_data_processing(Process):
def __init__(self, event, buffer, spectrogram_channel, Spectrogram_radioButton_isChecked, srate, num_channels, order, lowcut, highcut):
Process.__init__(self)
self.event = event
self.spectrogram_channel = spectrogram_channel
self.Spectrogram_radioButton_isChecked = Spectrogram_radioButton_isChecked
self.buffer = buffer
self.filter_bank = filter_bank_class(srate, order, lowcut, highcut)
self.spectrum = spectrum(SAMPLE_RATE=srate, CHANNELS=num_channels)
# self.old = datetime.now().timestamp() * 1000
def run(self):
while self.event.wait():
# time.sleep(1)
#################### DEFAULT FILTERING PROCESS ####################
sample = self.buffer.get()
filtered = self.default_filtering( sample )
self.buffer.set_filtered(filtered)
###################################################################
#*************** Compute Frequency Properties *********************
if self.Spectrogram_radioButton_isChecked.value:
data = self.spectrum.get_spectrogram( filtered[self.spectrogram_channel.value,:]).T
else:
data = self.spectrum.get_spectrum(filtered)
self.buffer.set_spectral(data)
#******************************************************************
# new = datetime.now().timestamp() * 1000
# print(self.name, ' processing: ', new-self.old)
# self.old = new
def default_filtering(self, data):
self.filter_bank.update_filters()
return self.filter_bank.pre_process( data )
<file_sep>/COM/trigger_server_2.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from PyQt5 import QtCore
import socket
class trigger_server(QtCore.QThread):
socket_emitter = QtCore.pyqtSignal(str)
log_emitter = QtCore.pyqtSignal(str)
def __init__(self, constants):
super(trigger_server, self).__init__(None)
self.constants = constants
self.activated = False
self.server_address = None
def create_socket(self):
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
self.server_address = (self.constants.ADDRESS, self.constants.PORT)
self.log_emitter.emit(' starting up on %s port %s' % self.server_address)
try:
self.sock.bind(self.server_address)
self.activated = True
except socket.gaierror:
self.log_emitter.emit('[Errno -2] Unknown name or service')
finally:
self.log_emitter.emit('DONE!')
return self.activated
def run(self):
# Listen for incoming connections
self.log_emitter.emit('Socket is listening!')
self.sock.listen(1)
while self.activated:
self.log_emitter.emit('Waiting for a connection')
try:
self.connection, client_address = self.sock.accept()
self.log_emitter.emit('Connection accepted from %s port %s ' % client_address)
except:
self.log_emitter.emit('Cannot accept connection due to a closed socket state.')
break
try:
# Receive the data in small chunks and retransmit it
while True:
data = self.connection.recv(128)
if data != b'':
self.socket_emitter.emit(data.decode())
# INCOMMING DATA
if data:
self.log_emitter.emit('Received "%s"' % data)
else:
self.log_emitter.emit('No more data from ' + client_address)
break
except:
self.log_emitter.emit('Error while listening')
finally:
self.close_socket()
def close_socket(self):
self.activated = False
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.log_emitter.emit('Socket is closed!')
<file_sep>/GUI/EEG_monitor_wrapper.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from multiprocessing import Value, Event
from PyQt5.QtWidgets import QMainWindow, QFileDialog
from PyQt5 import QtCore
from PyQt5 import QtWidgets
import xml.etree.ElementTree as ET
from QTDesigner.EEG_monitor import Ui_EEG_Viewer as UI
from DATA_MANAGER.EEG_data_processing import EEG_data_processing
from DYNAMIC.dynamic import dynamic
from DATA_MANAGER.file_IO import io_manager
from GUI.EEG_monitor_shortcuts_manager import EEG_shortcuts
class EEG_monitor_wrapper(QMainWindow, UI):
def __init__(self, log, inlet, buffer, counter, streaming, active):
QMainWindow.__init__(self, parent=None)
#---- GUI setup ----------
self.setupUi(self)
self.setWindowTitle(inlet.info().name())
# --- buffer related data structures ----
self.log = log
self.inlet = inlet
self.buffer = buffer
self.counter = counter
self.streaming = streaming
self.recording = False
self.active = active
self.is_shown = True
#--- global params -----
self.name = self.inlet.info().name()
self.srate = int(self.inlet.info().nominal_srate())
self.num_channels = self.inlet.channel_count
self.win_size = int(self.srate * int(self.WindowsSize_LineEdit.text()))
self.channels = []
self.get_labels(ET.fromstring(self.inlet.info().as_xml()))
#----- shared variables ------------
self.order = Value('i',5)
self.lowcut = Value('i',1)
self.highcut = Value('i', 75)
self.spectrogram_channel = Value('i',0)
self.Spectrogram_radioButton_isChecked = Value('b',0)
self.event = Event()
#---- IO -----
self.io = io_manager()
#-----------------------------------------------------------------------------------------------------------
self.shortcuts = EEG_shortcuts(self)
self.shortcuts.define_local_shortcuts(self.run, self.add_marker)
#---- streaming processing ----
self.processing = EEG_data_processing(self.event, self.buffer, self.spectrogram_channel, self.Spectrogram_radioButton_isChecked, self.srate, self.num_channels, self.order, self.lowcut, self.highcut)
self.processing.start()
#---- setup monitors ------
self.EEG_monitor.set_params( self.channels, self.counter, num_channels=self.num_channels, x_dim=self.win_size, y_dim=(self.num_channels+1)*100)
self.EEG_monitor.create_plot()
self.Frequency_monitor.set_params(num_channels=self.num_channels)
self.Frequency_monitor.create_fft_plot()
#---- dynamic imports ------------
self.dyn = dynamic(self, None, None)#el primer None hay que cambiarlo por el acceso a los streams!!!!!!
#---- callbacks ------
self.Filename_btn.clicked.connect(self.saveFileDialog)
self.Import_btn.clicked.connect(self.openFileNameDialog)
self.Start_btn.clicked.connect(lambda: self.run('SHOW'))
self.Record_btn.clicked.connect(lambda: self.run('RECORD'))
self.ButterOrder_LineEdit.textChanged.connect(lambda: self.update('FREQ', 'ORDER', self.ButterOrder_LineEdit.text() ))
self.WindowsSize_LineEdit.textChanged.connect(lambda: self.update('TIME', 'LENGTH', self.WindowsSize_LineEdit.text() ))
self.FrequencyRange_ComboBox.currentIndexChanged.connect(lambda: self.update('FREQ', 'BAND', self.FrequencyRange_ComboBox.currentText() ))
self.FiletringMethod_ComboBox.currentIndexChanged.connect(lambda: self.update('FREQ', 'METHOD', self.FiletringMethod_ComboBox.currentText() ))
self.Spectrogram_radioButton.toggled.connect(self.select_mode)
self.Spectrogram_radioButton.toggled.connect(lambda: self.Frequency_monitor.select_mode(self.Spectrogram_radioButton))
self.Channels_ComboBox.addItems(self.channels)
self.Channels_ComboBox.currentIndexChanged.connect(lambda: self.update( 'FREQ', 'CHANNEL', self.Channels_ComboBox.currentIndex() ))
self.AddMarker_btn.clicked.connect(lambda: self.add_marker(self.Markers_ComboBox.currentText()) )
self.scale_Slider.valueChanged.connect(lambda: self.EEG_monitor.set_scale(self.scale_Slider.value()))
self.space_Slider.valueChanged.connect(lambda: self.EEG_monitor.set_space(self.space_Slider.value()))
self.verticalScrollBar.valueChanged.connect(lambda: self.EEG_monitor.set_scroll(self.verticalScrollBar.value()))
#--- visualize timer ----
self.timer = QtCore.QTimer()
self.timer.setTimerType(QtCore.Qt.PreciseTimer)
self.timer.timeout.connect(self.visualize)
self.refresh_rate = 50
#---- close the sub-app -------
self.actionQuit = QtWidgets.QAction("Quit", self)
self.actionQuit.triggered.connect(QtWidgets.QApplication.quit)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
def run(self, action):
if not self.streaming.value and not self.recording and action == 'SHOW':
self.streaming.value = True
self.EEG_monitor.remove_lines()
self.event.set()
self.timer.start(self.refresh_rate)
elif not self.streaming.value and not self.recording and action == 'RECORD':
self.streaming.value = True
self.recording = True
self.EEG_monitor.remove_lines()
self.buffer.set_recording(True)
try:
self.io.create_file()
self.io.online_annotation(action, self.buffer.get_current_instant())
self.log.myprint_in('File created at device: ' + self.name + ' subject: ' + self.io.fileName + ' Trial: ' + str(self.io.Trial))
except:
self.log.myprint_error('Cannot create subject data file at device: ' + self.name)
finally:
self.event.set()
self.timer.start(self.refresh_rate)
elif self.streaming.value and not self.recording and action == 'SHOW':
self.streaming.value = False
self.event.clear()
self.timer.stop()
self.buffer.reset(self.win_size)
elif self.streaming.value and not self.recording and action == 'RECORD':
self.recording = True
self.buffer.set_recording(True)
try:
self.io.create_file()
self.io.online_annotation(action, self.buffer.get_current_instant())
self.log.myprint_in('File created at device: '+ self.name + ' subject: ' + self.io.fileName + ' Trial: ' + str(self.io.Trial))
except:
self.log.myprint_error('Cannot create subject data file at device: ' + self.name)
elif self.streaming.value and self.recording:
self.streaming.value = False
self.recording = False
self.event.clear()
self.timer.stop()
try:
self.io.online_annotation(action, self.buffer.get_current_instant())
self.io.append_to_file(self.buffer.get_stream())
self.io.close_file()
self.log.myprint_out('File saved at device: ' + self.name + ' subject: ' + self.io.fileName + ' Trial: ' + str(self.io.Trial-1))
except:
self.log.myprint_error('Cannot close subject data file at device: ' + self.name)
finally:
self.buffer.reset(self.win_size)
self.buffer.set_recording(False)
def get_labels(self, elem):
if elem.tag == 'label':
self.channels.append(elem.text)
for child in elem.findall('*'):
self.get_labels(child)
def closeEvent(self, event):
self.active.value = False
self.processing.kill()
self.close()
def update(self, which, param, value):
if value != '':
if which == 'FREQ':
if param == 'BAND':
if param == 'ORDER':
self.order.value = int(value)
elif value == 'All':
self.lowcut.value = 1
self.highcut.value = int(self.srate/2 - 1)
elif value == 'Delta':
self.lowcut.value = 1
self.highcut.value = 5
elif value == 'Theta':
self.lowcut.value = 5
self.highcut.value = 10
elif value == 'Alpha':
self.lowcut.value = 10
self.highcut.value = 15
elif value == 'Beta':
self.lowcut.value = 15
self.highcut.value = 30
elif value == 'Gamma':
self.lowcut.value = 30
self.highcut.value = int(self.srate/2 - 1)
elif param == 'CHANNEL':
self.spectrogram_channel.value = value
elif which == 'TIME':
if param == 'LENGTH':
self.length = int(value)
elif param == 'SRATE':
self.srate = int(value)
self.win_size = self.srate * self.length
self.buffer.reset(self.win_size)
self.EEG_monitor.redraw( self.win_size )
def add_marker(self, mark):
if self.io.file_created:
self.io.online_annotation(mark, self.buffer.get_current_instant())
self.EEG_monitor.draw_vertical_line(mark)
def visualize(self):
self.EEG_monitor.update(self.buffer.get_filtered())
self.Frequency_monitor.update(self.buffer.get_spectral())
def select_mode(self):
self.Spectrogram_radioButton_isChecked.value = self.Spectrogram_radioButton.isChecked()
def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.io.fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","EDF Files (*.edf)", options=options)
def openFileNameDialog(self, btn):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileType = "PYTHON Files (*.py)"
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()","",fileType, options=options)
#----------------- LOAD AND EXECUTE THE MODULE -----#
self.dyn.load_module(fileName)
<file_sep>/QTDesigner/M_GEERT_QT.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'M_GEERT_QT.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_M_GEERT(object):
def setupUi(self, M_GEERT):
M_GEERT.setObjectName("M_GEERT")
M_GEERT.resize(1472, 922)
self.centralwidget = QtWidgets.QWidget(M_GEERT)
self.centralwidget.setObjectName("centralwidget")
self.formLayout = QtWidgets.QFormLayout(self.centralwidget)
self.formLayout.setObjectName("formLayout")
self.verticalLayout_8 = QtWidgets.QVBoxLayout()
self.verticalLayout_8.setObjectName("verticalLayout_8")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.Experiment_btn = QtWidgets.QPushButton(self.centralwidget)
self.Experiment_btn.setObjectName("Experiment_btn")
self.horizontalLayout_5.addWidget(self.Experiment_btn)
self.MainRecord_btn = QtWidgets.QPushButton(self.centralwidget)
self.MainRecord_btn.setObjectName("MainRecord_btn")
self.horizontalLayout_5.addWidget(self.MainRecord_btn)
self.verticalLayout_8.addLayout(self.horizontalLayout_5)
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setMinimumSize(QtCore.QSize(0, 0))
self.groupBox.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.groupBox.setObjectName("groupBox")
self.verticalLayout_11 = QtWidgets.QVBoxLayout(self.groupBox)
self.verticalLayout_11.setObjectName("verticalLayout_11")
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.ResolveStreaming_btn = QtWidgets.QPushButton(self.groupBox)
self.ResolveStreaming_btn.setObjectName("ResolveStreaming_btn")
self.horizontalLayout_2.addWidget(self.ResolveStreaming_btn)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem)
self.Activate_btn = QtWidgets.QPushButton(self.groupBox)
self.Activate_btn.setObjectName("Activate_btn")
self.horizontalLayout_2.addWidget(self.Activate_btn)
self.Hide_btn = QtWidgets.QPushButton(self.groupBox)
self.Hide_btn.setObjectName("Hide_btn")
self.horizontalLayout_2.addWidget(self.Hide_btn)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.Streamings_List = QtWidgets.QListWidget(self.groupBox)
self.Streamings_List.setTabletTracking(False)
self.Streamings_List.setProperty("isWrapping", False)
self.Streamings_List.setSelectionRectVisible(True)
self.Streamings_List.setObjectName("Streamings_List")
self.verticalLayout_2.addWidget(self.Streamings_List)
self.verticalLayout_11.addLayout(self.verticalLayout_2)
self.verticalLayout_8.addWidget(self.groupBox)
self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_4.setMinimumSize(QtCore.QSize(0, 0))
self.groupBox_4.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.groupBox_4.setObjectName("groupBox_4")
self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.groupBox_4)
self.verticalLayout_6.setObjectName("verticalLayout_6")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.TCPIP_checkBox = QtWidgets.QCheckBox(self.groupBox_4)
self.TCPIP_checkBox.setObjectName("TCPIP_checkBox")
self.horizontalLayout.addWidget(self.TCPIP_checkBox)
self.Host_LineEdit = QtWidgets.QLineEdit(self.groupBox_4)
self.Host_LineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.Host_LineEdit.setObjectName("Host_LineEdit")
self.horizontalLayout.addWidget(self.Host_LineEdit)
self.Port_LineEdit = QtWidgets.QLineEdit(self.groupBox_4)
font = QtGui.QFont()
font.setUnderline(False)
self.Port_LineEdit.setFont(font)
self.Port_LineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
self.Port_LineEdit.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Port_LineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.Port_LineEdit.setObjectName("Port_LineEdit")
self.horizontalLayout.addWidget(self.Port_LineEdit)
self.verticalLayout_6.addLayout(self.horizontalLayout)
self.verticalLayout_8.addWidget(self.groupBox_4)
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setMinimumSize(QtCore.QSize(0, 0))
self.groupBox_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.groupBox_2.setObjectName("groupBox_2")
self.verticalLayout_5 = QtWidgets.QVBoxLayout(self.groupBox_2)
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.Run_btn = QtWidgets.QPushButton(self.groupBox_2)
self.Run_btn.setObjectName("Run_btn")
self.horizontalLayout_3.addWidget(self.Run_btn)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem1)
self.Save_btn = QtWidgets.QPushButton(self.groupBox_2)
self.Save_btn.setObjectName("Save_btn")
self.horizontalLayout_3.addWidget(self.Save_btn)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.Scripts_List = QtWidgets.QListWidget(self.groupBox_2)
self.Scripts_List.setObjectName("Scripts_List")
self.verticalLayout.addWidget(self.Scripts_List)
self.verticalLayout_5.addLayout(self.verticalLayout)
self.verticalLayout_8.addWidget(self.groupBox_2)
self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_3.setMinimumSize(QtCore.QSize(0, 0))
self.groupBox_3.setObjectName("groupBox_3")
self.verticalLayout_7 = QtWidgets.QVBoxLayout(self.groupBox_3)
self.verticalLayout_7.setObjectName("verticalLayout_7")
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.Logger = QtWidgets.QPlainTextEdit(self.groupBox_3)
self.Logger.setObjectName("Logger")
self.verticalLayout_3.addWidget(self.Logger)
self.verticalLayout_7.addLayout(self.verticalLayout_3)
self.verticalLayout_8.addWidget(self.groupBox_3)
self.formLayout.setLayout(0, QtWidgets.QFormLayout.LabelRole, self.verticalLayout_8)
self.groupBox_5 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_5.setMinimumSize(QtCore.QSize(0, 0))
self.groupBox_5.setObjectName("groupBox_5")
self.verticalLayout_9 = QtWidgets.QVBoxLayout(self.groupBox_5)
self.verticalLayout_9.setObjectName("verticalLayout_9")
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.Code_TextEdit = QtWidgets.QPlainTextEdit(self.groupBox_5)
self.Code_TextEdit.setObjectName("Code_TextEdit")
self.verticalLayout_4.addWidget(self.Code_TextEdit)
self.verticalLayout_9.addLayout(self.verticalLayout_4)
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.groupBox_5)
M_GEERT.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(M_GEERT)
self.statusbar.setObjectName("statusbar")
M_GEERT.setStatusBar(self.statusbar)
self.retranslateUi(M_GEERT)
QtCore.QMetaObject.connectSlotsByName(M_GEERT)
def retranslateUi(self, M_GEERT):
_translate = QtCore.QCoreApplication.translate
M_GEERT.setWindowTitle(_translate("M_GEERT", "SIGNALINO"))
self.Experiment_btn.setText(_translate("M_GEERT", "Experiment"))
self.MainRecord_btn.setText(_translate("M_GEERT", "Record"))
self.groupBox.setTitle(_translate("M_GEERT", "Lab Streaming Layer"))
self.ResolveStreaming_btn.setText(_translate("M_GEERT", "Resolve Streaming"))
self.Activate_btn.setText(_translate("M_GEERT", "Activate"))
self.Hide_btn.setText(_translate("M_GEERT", "Hide"))
self.groupBox_4.setTitle(_translate("M_GEERT", "TCP/IP Remote Control"))
self.TCPIP_checkBox.setText(_translate("M_GEERT", "Trigger Server"))
self.Host_LineEdit.setText(_translate("M_GEERT", "localhost"))
self.Port_LineEdit.setText(_translate("M_GEERT", "10000"))
self.groupBox_2.setTitle(_translate("M_GEERT", "Python Scripts"))
self.Run_btn.setText(_translate("M_GEERT", "RUN"))
self.Save_btn.setText(_translate("M_GEERT", "SAVE"))
self.groupBox_3.setTitle(_translate("M_GEERT", "Log Viewer"))
self.groupBox_5.setTitle(_translate("M_GEERT", "PYTHON RAW CODE"))
<file_sep>/FILTERS/filter_bank_manager.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
#%%
from scipy.signal import butter, iirnotch, filtfilt
import numpy as np
class filter_bank_class:
def __init__(self, srate, order, lowcut, highcut):
#---- constants -----
self.LOWCUT = lowcut
self.HIGHCUT = highcut
self.ORDER = order
self.SAMPLE_RATE = srate
self.NOTCH = 50
def update_filters(self):
self.b0, self.a0 = self.notch_filter()
self.b, self.a = self.butter_bandpass()
def pre_process(self, sample):
sample = np.array(sample)
[fil,col] = sample.shape
sample_processed = np.zeros([fil,col])
for i in range(fil):
data = sample[i,:]
data = data - np.mean(data)
if self.LOWCUT.value != None and self.HIGHCUT.value != None: #
data = self.butter_bandpass_filter(data)
data = data + (i+1)*100 ### CUIDADO HARDCODING!!!!
sample_processed[i,:] = data
return sample_processed
def notch_filter(self): # f0 50Hz, 60 Hz
Q = 30.0 # Quality factor
b0, a0 = iirnotch(self.NOTCH, Q, self.SAMPLE_RATE)#
return b0,a0
def butter_bandpass(self):
nyq = int(0.5 * self.SAMPLE_RATE)
low = self.LOWCUT.value / nyq
high = self.HIGHCUT.value / nyq
b, a = butter(self.ORDER.value, [low, high], btype='band')
return b, a
def butter_bandpass_filter(self, data):
noth_data = filtfilt(self.b0, self.a0, data)
band_passed_data = filtfilt(self.b, self.a, noth_data)
return band_passed_data
def butter_bandpass_specific_filter(self, data, lowcut, highcut, Fs, order):
# -- notch filter --
noth_data = filtfilt(self.b0, self.a0, data)
# -- butterworth filter --
nyq = 0.5 * Fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order , [low, high], btype='band')
band_passed_data = filtfilt(b, a, noth_data)
return band_passed_data
def filter_bank(self, signal, Fs, filter_ranges, order=5):
filterbank = []
for [lowcut,highcut] in filter_ranges:
y = self.butter_bandpass_specific_filter(signal, lowcut, highcut, Fs, order)
filterbank.append(y)
return np.asarray(filterbank)
<file_sep>/AUXILIAR_CODE/GLOBAL_online_processing_example.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
from PyQt5 import QtCore
from FILTERS.filter_bank_manager import filter_bank_class
from multiprocessing import Value
import pyqtgraph as pg
import numpy as np
import time
class simple_plot:
pg.setConfigOption('background', 'k')
pg.setConfigOption('foreground', 'm')
def __init__(self, num_channels, scale, spacing):
self.num_channels = num_channels
self.scale = scale
self.spacing = spacing
self.win = pg.GraphicsWindow(title="Basic plotting examples")
self.win.resize(1000,600)
self.win.setWindowTitle('pyqtgraph example: Plotting')
pg.setConfigOptions(antialias=True)
self.plotter = self.win.addPlot(title="Updating plot")
self.curves = []
for i in range(self.num_channels):
self.curves.append( self.plotter.plot([], pen=(i,self.num_channels*1.3)) )
def normalize(self, sample):
return (sample-np.mean(sample))/np.std(sample)
def update(self, sample):
for i in range(self.num_channels):
self.curves[i].setData( self.normalize(sample)[i]*self.scale + i*self.spacing)
class MyClass(QtCore.QThread):
def __init__(self, current_GUI):
super(MyClass, self).__init__(None)
self.current_GUI = current_GUI
#--- filter example --
self.filter_bank = filter_bank_class(250, Value('i',5), Value('i',5), Value('i', 10))
self.filter_bank.update_filters()
#--- visualize ---
self.plotters = []
for _ in range(len(self.current_GUI.monitors)):
self.plotters.append( simple_plot(8, 10, 2) )
def run(self):
while True:
time.sleep(.01)
streamings = [monitor.streaming.value for monitor in self.current_GUI.monitors]
if np.all(streamings):
for index, monitor in enumerate(self.current_GUI.monitors):
sample = monitor.buffer.get()
filtered = self.myfilter( sample )
self.plotters[index].update(filtered)
def myfilter(self, sample):
return self.filter_bank.pre_process( sample )
<file_sep>/QTDesigner/EEG_monitor.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EEG_monitor.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EEG_Viewer(object):
def setupUi(self, EEG_Viewer):
EEG_Viewer.setObjectName("EEG_Viewer")
EEG_Viewer.resize(1496, 421)
self.centralwidget = QtWidgets.QWidget(EEG_Viewer)
self.centralwidget.setObjectName("centralwidget")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(10, 10, 251, 381))
self.groupBox.setObjectName("groupBox")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.groupBox)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 2, 0, 1, 1)
self.WindowsSize_LineEdit = QtWidgets.QLineEdit(self.groupBox)
self.WindowsSize_LineEdit.setObjectName("WindowsSize_LineEdit")
self.gridLayout.addWidget(self.WindowsSize_LineEdit, 3, 1, 1, 1)
self.ButterOrder_LineEdit = QtWidgets.QLineEdit(self.groupBox)
self.ButterOrder_LineEdit.setObjectName("ButterOrder_LineEdit")
self.gridLayout.addWidget(self.ButterOrder_LineEdit, 2, 1, 1, 1)
self.Import_btn = QtWidgets.QPushButton(self.groupBox)
self.Import_btn.setObjectName("Import_btn")
self.gridLayout.addWidget(self.Import_btn, 0, 1, 1, 1)
self.Channels_ComboBox = QtWidgets.QComboBox(self.groupBox)
self.Channels_ComboBox.setObjectName("Channels_ComboBox")
self.gridLayout.addWidget(self.Channels_ComboBox, 6, 1, 1, 1)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem, 1, 1, 1, 1)
self.Record_btn = QtWidgets.QPushButton(self.groupBox)
self.Record_btn.setObjectName("Record_btn")
self.gridLayout.addWidget(self.Record_btn, 8, 1, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem1, 1, 0, 1, 1)
self.label_2 = QtWidgets.QLabel(self.groupBox)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
self.FiletringMethod_ComboBox = QtWidgets.QComboBox(self.groupBox)
self.FiletringMethod_ComboBox.setObjectName("FiletringMethod_ComboBox")
self.FiletringMethod_ComboBox.addItem("")
self.gridLayout.addWidget(self.FiletringMethod_ComboBox, 5, 1, 1, 1)
self.FrequencyRange_ComboBox = QtWidgets.QComboBox(self.groupBox)
self.FrequencyRange_ComboBox.setObjectName("FrequencyRange_ComboBox")
self.FrequencyRange_ComboBox.addItem("")
self.FrequencyRange_ComboBox.addItem("")
self.FrequencyRange_ComboBox.addItem("")
self.FrequencyRange_ComboBox.addItem("")
self.FrequencyRange_ComboBox.addItem("")
self.FrequencyRange_ComboBox.addItem("")
self.gridLayout.addWidget(self.FrequencyRange_ComboBox, 4, 1, 1, 1)
self.Spectrogram_radioButton = QtWidgets.QRadioButton(self.groupBox)
self.Spectrogram_radioButton.setObjectName("Spectrogram_radioButton")
self.gridLayout.addWidget(self.Spectrogram_radioButton, 6, 0, 1, 1)
self.Filename_btn = QtWidgets.QPushButton(self.groupBox)
self.Filename_btn.setObjectName("Filename_btn")
self.gridLayout.addWidget(self.Filename_btn, 0, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.groupBox)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 1)
self.AddMarker_btn = QtWidgets.QPushButton(self.groupBox)
self.AddMarker_btn.setObjectName("AddMarker_btn")
self.gridLayout.addWidget(self.AddMarker_btn, 9, 0, 1, 1)
self.Start_btn = QtWidgets.QPushButton(self.groupBox)
self.Start_btn.setObjectName("Start_btn")
self.gridLayout.addWidget(self.Start_btn, 8, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.groupBox)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 5, 0, 1, 1)
self.Markers_ComboBox = QtWidgets.QComboBox(self.groupBox)
self.Markers_ComboBox.setObjectName("Markers_ComboBox")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.Markers_ComboBox.addItem("")
self.gridLayout.addWidget(self.Markers_ComboBox, 9, 1, 1, 1)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem2, 7, 0, 1, 1)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem3, 7, 1, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(270, 10, 751, 381))
self.groupBox_2.setObjectName("groupBox_2")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.groupBox_2)
self.horizontalLayout.setObjectName("horizontalLayout")
self.EEG_monitor = Monitor_EEG_plotter(self.groupBox_2)
self.EEG_monitor.setObjectName("EEG_monitor")
self.horizontalLayout.addWidget(self.EEG_monitor)
self.verticalScrollBar = QtWidgets.QScrollBar(self.groupBox_2)
self.verticalScrollBar.setProperty("value", 0)
self.verticalScrollBar.setOrientation(QtCore.Qt.Vertical)
self.verticalScrollBar.setObjectName("verticalScrollBar")
self.horizontalLayout.addWidget(self.verticalScrollBar)
self.scale_Slider = QtWidgets.QSlider(self.centralwidget)
self.scale_Slider.setGeometry(QtCore.QRect(1040, 10, 20, 160))
self.scale_Slider.setProperty("value", 50)
self.scale_Slider.setOrientation(QtCore.Qt.Vertical)
self.scale_Slider.setObjectName("scale_Slider")
self.space_Slider = QtWidgets.QSlider(self.centralwidget)
self.space_Slider.setGeometry(QtCore.QRect(1040, 210, 20, 160))
self.space_Slider.setProperty("value", 0)
self.space_Slider.setOrientation(QtCore.Qt.Vertical)
self.space_Slider.setObjectName("space_Slider")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(1030, 170, 41, 18))
self.label_5.setAlignment(QtCore.Qt.AlignCenter)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(1030, 370, 41, 18))
self.label_6.setAlignment(QtCore.Qt.AlignCenter)
self.label_6.setObjectName("label_6")
self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox_3.setGeometry(QtCore.QRect(1080, 10, 401, 381))
self.groupBox_3.setObjectName("groupBox_3")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.groupBox_3)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.Frequency_monitor = Monitor_Frequency_plotter(self.groupBox_3)
self.Frequency_monitor.setObjectName("Frequency_monitor")
self.horizontalLayout_2.addWidget(self.Frequency_monitor)
EEG_Viewer.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(EEG_Viewer)
self.statusbar.setObjectName("statusbar")
EEG_Viewer.setStatusBar(self.statusbar)
self.retranslateUi(EEG_Viewer)
QtCore.QMetaObject.connectSlotsByName(EEG_Viewer)
def retranslateUi(self, EEG_Viewer):
_translate = QtCore.QCoreApplication.translate
EEG_Viewer.setWindowTitle(_translate("EEG_Viewer", "MainWindow"))
self.groupBox.setTitle(_translate("EEG_Viewer", "Settings"))
self.label.setText(_translate("EEG_Viewer", "Butter Order"))
self.WindowsSize_LineEdit.setText(_translate("EEG_Viewer", "6"))
self.ButterOrder_LineEdit.setText(_translate("EEG_Viewer", "5"))
self.Import_btn.setText(_translate("EEG_Viewer", "Import Script"))
self.Record_btn.setText(_translate("EEG_Viewer", "Record"))
self.label_2.setText(_translate("EEG_Viewer", "Windows Size"))
self.FiletringMethod_ComboBox.setItemText(0, _translate("EEG_Viewer", "Butterworth"))
self.FrequencyRange_ComboBox.setItemText(0, _translate("EEG_Viewer", "All"))
self.FrequencyRange_ComboBox.setItemText(1, _translate("EEG_Viewer", "Gamma"))
self.FrequencyRange_ComboBox.setItemText(2, _translate("EEG_Viewer", "Beta"))
self.FrequencyRange_ComboBox.setItemText(3, _translate("EEG_Viewer", "Alpha"))
self.FrequencyRange_ComboBox.setItemText(4, _translate("EEG_Viewer", "Theta"))
self.FrequencyRange_ComboBox.setItemText(5, _translate("EEG_Viewer", "Delta"))
self.Spectrogram_radioButton.setText(_translate("EEG_Viewer", "Spect&rogram"))
self.Filename_btn.setText(_translate("EEG_Viewer", "File Name"))
self.label_3.setText(_translate("EEG_Viewer", "Frequency Range"))
self.AddMarker_btn.setText(_translate("EEG_Viewer", "Add Marker"))
self.Start_btn.setText(_translate("EEG_Viewer", "Start"))
self.label_4.setText(_translate("EEG_Viewer", "Filtering Method"))
self.Markers_ComboBox.setItemText(0, _translate("EEG_Viewer", "label_0"))
self.Markers_ComboBox.setItemText(1, _translate("EEG_Viewer", "label_1"))
self.Markers_ComboBox.setItemText(2, _translate("EEG_Viewer", "label_2"))
self.Markers_ComboBox.setItemText(3, _translate("EEG_Viewer", "label_3"))
self.Markers_ComboBox.setItemText(4, _translate("EEG_Viewer", "label_4"))
self.Markers_ComboBox.setItemText(5, _translate("EEG_Viewer", "label_5"))
self.Markers_ComboBox.setItemText(6, _translate("EEG_Viewer", "label_6"))
self.Markers_ComboBox.setItemText(7, _translate("EEG_Viewer", "label_7"))
self.Markers_ComboBox.setItemText(8, _translate("EEG_Viewer", "label_8"))
self.Markers_ComboBox.setItemText(9, _translate("EEG_Viewer", "label_9"))
self.groupBox_2.setTitle(_translate("EEG_Viewer", "EEG Monitor"))
self.label_5.setText(_translate("EEG_Viewer", "Scale"))
self.label_6.setText(_translate("EEG_Viewer", "Space"))
self.groupBox_3.setTitle(_translate("EEG_Viewer", "Spectral Monitor"))
from QTDesigner.Monitor_EEG_plotter import Monitor_EEG_plotter
from QTDesigner.Monitor_Frequency_plotter import Monitor_Frequency_plotter
<file_sep>/DATA_MANAGER/EEG_data_manager.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
import numpy as np
class EEG_data_manager(object):
def __init__(self, num_channels=8, win_size=1500, srate=250):
# --- constants -----
self.num_channels = num_channels
self.srate = srate
self.win_size = win_size
#--- data containers ---
self.data = np.zeros((self.num_channels,self.win_size))
self.filtered = np.zeros((self.num_channels,self.win_size))
self.spectral = None
self.stream_data = {'samples':[], 'timestamps':[]}
#----- control params ----
self.cur = 0
self.recording = False
def set_recording(self, recording):
self.recording = recording
def reset(self, win_size):
self.win_size = win_size
self.data = np.zeros((self.num_channels,self.win_size))
self.filtered = np.zeros((self.num_channels,self.win_size))
self.stream_data = {'samples':[], 'timestamps':[]}
self.cur = 0
def append(self, sample, timestamp):
"""append an element at the end of the buffer"""
self.cur = self.cur % self.win_size
self.data[:,self.cur] = np.asarray(sample).transpose()
self.cur = self.cur+1
if self.recording:
self.stream_data['samples'].append(np.asarray(sample).transpose())
self.stream_data['timestamps'].append(timestamp)
def get(self):
""" Return a list of elements from the oldest to the newest. """
return list(self.data)
def get_stream(self):
return np.asarray(self.stream_data['samples'])
def set_filtered(self,x):
self.filtered = x
def get_filtered(self):
return self.filtered
def set_spectral(self,x):
self.spectral = x
def get_spectral(self):
return self.spectral
def get_current_instant(self):
return self.cur
<file_sep>/COM/trigger_client.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>, <NAME>, <NAME>)
@email: %(<EMAIL>, <EMAIL>, <EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED); Center for Biomedical Technology, Universidad Politécnica, Madrid, Spain; Neuroengineering medical group (UMH) )
@DOI:
"""
#%%
import socket
import sys
class trigger_client():
def __init__(self, address, port):
self.address = address
self.port = port
def create_socket(self):
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
# Connect the socket to the port where the server is listening
server_address = (self.address, self.port)
print (sys.stderr, 'connecting to %s port %s' % server_address)
self.sock.connect(server_address)
def send_msg(self, message):
try:
# Send data
print(sys.stderr, 'sending "%s"' % message)
self.sock.sendall(message)
except:
print('Error sending the message tcp/ip')
def close_socket(self):
print(sys.stderr, 'closing socket')
self.sock.close()
<file_sep>/QTDesigner/Monitor_Frequency_plotter.py
# -*- coding: utf-8 -*-
"""
@author: %(<NAME>)s
@email: %(<EMAIL>)
@institution: %(Dpto. de Inteligencia Artificial, Universidad Nacional de Educación a Distancia (UNED))
@DOI:
"""
import pyqtgraph as pg
import numpy as np
class Monitor_Frequency_plotter(pg.GraphicsWindow):
pg.setConfigOption('background', 'k')
pg.setConfigOption('foreground', 'm')
def __init__(self, parent=None, **kargs):
pg.GraphicsWindow.__init__(self, **kargs)
self.setParent(parent)
self.curves = []
self.Spectrogram_radioButton_isChecked = False
def set_params(self, num_channels=8):
self.num_channels = num_channels
def create_spectrogram_plot(self):
self.setWindowTitle('Spectrogram')
self.plotter = self.addPlot()
self.plotter.setLabel('left', 'Frequency', units='Hz')
self.plotter.setLabel('bottom', "Samples", units='n')
self.plotter.showGrid(True, True, alpha = 0.5)
self.plotter.setLogMode(False, False)
self.spectrogram_Img = pg.ImageItem()
self.plotter.addItem(self.spectrogram_Img)
pos = np.array([0.0, 0.5, 1.0])
color = np.array([[0,0,0,255], [255,128,0,255], [255,255,0,255]], dtype=np.ubyte)
map = pg.ColorMap(pos, color)
lut = map.getLookupTable(0.0, 1.0, 256)
self.spectrogram_Img.setLookupTable(lut)
def create_fft_plot(self):
self.setWindowTitle('Spectrogram')
self.plotter = self.addPlot()
self.plotter.setLabel('left', 'Amplitude', units='dB')
self.plotter.setLabel('bottom', "Frequency", units='Hz')
self.plotter.showGrid(True, True, alpha = 0.5)
self.plotter.setLogMode(False, True)
for i in range(self.num_channels):
c = pg.PlotCurveItem(pen=(i,self.num_channels*1.3))
self.plotter.addItem(c)
self.curves.append(c)
def select_mode(self, radioButton):
self.removeItem(self.plotter)
if radioButton.isChecked():
self.create_spectrogram_plot()
self.Spectrogram_radioButton_isChecked = True
else:
self.curves = []
self.create_fft_plot()
self.Spectrogram_radioButton_isChecked = False
def update(self, sample):
if self.Spectrogram_radioButton_isChecked:
self.spectrogram_Img.setImage(np.asarray(sample), autoLevels=True)
else:
for i in range(self.num_channels):
self.curves[i].setData(np.asarray(sample[0]),np.log10(np.asarray(sample[1])[i,:]))
|
05c655ad3ddadfd6924d188206396d302df912dd
|
[
"Python",
"Shell"
] | 27
|
Python
|
mikelval82/MULTI_GEERT
|
c360415c33f9df1bbc7686a4e1232cb486cc5eef
|
8c46b6c89afeddf8fd630b1e41a37737b103dfa4
|
refs/heads/master
|
<repo_name>vul3vm06/tools<file_sep>/mac-to
#!/bin/bash
BUILD_FILE_SYSTEM="$HOME/workspace/"
PWD=$(pwd)"/"
if [[ $# -eq 1 ]] && [[ $PWD != $BUILD_FILE_SYSTEM*/KaiOS* ]];
then
UBUNTU_TO=/mnt/md0/to
if [ -f $UBUNTU_TO ];
then
source $UBUNTU_TO;
SRC_RET=$?;
if [ $SRC_RET == 0 ];
then
return
fi
fi
fi
QRD_PATH=$BUILD_FILE_SYSTEM"QRD/KaiOS"
GF2_PATH=$BUILD_FILE_SYSTEM"GF2/KaiOS"
RT_PATH=$BUILD_FILE_SYSTEM"Runtime/KaiOS"
#PRJ_PATH=${PWD%%KaiOS*}
#BASE_PATH=${PWD##*KaiOS/}
PRJ_PATH=${PWD/KaiOS*/KaiOS\/}
BASE_PATH=${PWD/*\/KaiOS\//}
if [[ $PRJ_PATH == $BASE_PATH ]] ;
then
PRJ_PATH=$GF2_PATH"/"
BASE_PATH=""
fi
OUT_PATH=$PRJ_PATH"out/"
GONK_PATH=$PRJ_PATH"gonk-misc/"
GECKO_PATH=$PRJ_PATH"gecko/"
GAIA_PATH=$PRJ_PATH"gaia/"
APPS_PATH=$GAIA_PATH"apps/"
PRODUCT_PATH=$PRJ_PATH"out/target/product/"
OBJDIR_PATH=$PRJ_PATH"objdir-gecko/"
MANIFESTS_PATH=$PRJ_PATH".repo/manifests/"
KOOST_PATH=$GECKO_PATH"koost/"
DOM_PATH=$GECKO_PATH"dom/"
SYSAPP_PATH=$APPS_PATH"system/"
SETAPP_PATH=$APPS_PATH"settings/"
function check_exist_and_cd {
PRJ_PATH=$1
BASE_PATH=$2
DST_PATH=$PRJ_PATH"/$BASE_PATH"
if [ -d "$DST_PATH" ]
then
cd $DST_PATH
else
cd $PRJ_PATH
fi
}
case "$1" in
u)
ssh claire@claire.local
;;
xu)
ssh -X claire@claire.local -Y
;;
pu)
ssh claire@ubuntu.local
;;
u14)
ssh claire@ubuntu14.local
;;
u16)
ssh claire@ubuntu16.local
;;
qa)
ssh kaios-ci@kaios-test-08.local
;;
all)
cd $BUILD_FILE_SYSTEM
;;
bugs)
cd ~/Documents/bugs
;;
the)
cd ~/Documents/bugs/the-bugs
;;
ui)
cd ~/Documents/bugs/ui-utils
;;
qrd)
check_exist_and_cd $QRD_PATH $BASE_PATH
;;
gf2)
check_exist_and_cd $GF2_PATH $BASE_PATH
;;
rt)
check_exist_and_cd $RT_PATH $BASE_PATH
;;
top)
cd $PRJ_PATH
;;
out)
cd $OUT_PATH
;;
gonk)
cd $GONK_PATH
;;
gecko)
cd $GECKO_PATH
;;
gaia)
cd $GAIA_PATH
;;
apps)
cd $APPS_PATH
;;
mani)
cd $MANIFESTS_PATH
;;
product)
if [ 1 -eq "$(find $PRODUCT_PATH -maxdepth 1 -type d ! -path $PRODUCT_PATH | wc -l)" ]
then
cd "$(find $PRODUCT_PATH -maxdepth 1 -type d ! -path $PRODUCT_PATH)"
else
cd $PRODUCT_PATH
fi
;;
objdir)
cd $OBJDIR_PATH
;;
koost)
cd $KOOST_PATH
;;
sysapp)
cd $SYSAPP_PATH
;;
*)
if [ -d "$1" ]
then
cd "$1"
else
echo "mac Invalid Destination $1"
fi
;;
esac
<file_sep>/ubuntu-to
#!/bin/bash
UNAME=`uname`
if [ $UNAME == "Darwin" ];
then
BUILD_FILE_SYSTEM="/mnt/md0"
elif [ $UNAME == "Linux" ];
then
BUILD_FILE_SYSTEM="/mnt/md0"
else
echo "Unknown OS $UNAME"
return
fi
B2G_PROJ_PATH=$BUILD_FILE_SYSTEM"/b2g"
GF2_PATH=$B2G_PROJ_PATH"/go_flip2_new"
QUOIN_PATH=$B2G_PROJ_PATH"/quoin"
QUADRO_Q_SFP_PATH=$B2G_PROJ_PATH"/quadro_q_sfp"
QUADRO_Q_SFP_3_0_PATH=$B2G_PROJ_PATH"/quadro_q_sfp-v3.0"
QUADRO_Q_ST_PATH=$B2G_PROJ_PATH"/quadro_q_st"
MODRIC_M_PATH=$B2G_PROJ_PATH"/modric_m_st"
MODRIC_Q_PATH=$B2G_PROJ_PATH"/modric_q_st"
RT_PATH=$B2G_PROJ_PATH"/kaiosrt_next"
RT_3_0_PATH=$B2G_PROJ_PATH"/kaiosrt_next-v3.0"
PWD=$(pwd)"/"
declare -a ALL_PRJ_PATHS=(
$GF2_PATH
$QUOIN_PATH
$QUADRO_Q_SFP_PATH
$QUADRO_Q_SFP_3_0_PATH
$QUADRO_Q_ST_PATH
)
PRJ_PATH=$QUADRO_Q_SFP_PATH"/KaiOS/"
unset BASE_PATH
# or: for p in "${ALL_PRJ_PATHS[@]}" ;
for p in $B2G_PROJ_PATH/* ;
do
# Must use [[ ]] , not [ ] .
if [[ $PWD == $p/* ]] ;
then
BASE_PATH=${PWD#$p}
PRJ_PATH=$p"/KaiOS/"
break
fi
done
OUT_PATH=$PRJ_PATH"out/"
GONK_PATH=$PRJ_PATH"gonk-misc/"
GECKO_PATH=$PRJ_PATH"gecko/"
GAIA_PATH=$PRJ_PATH"gaia/"
APPS_PATH=$GAIA_PATH"apps/"
PRODUCT_PATH=$PRJ_PATH"out/target/product/"
OBJDIR_PATH=$PRJ_PATH"objdir-gecko/"
BIN_PATH=$PRJ_PATH"objdir-gecko/dist/bin"
MANIFESTS_PATH=$PRJ_PATH".repo/manifests/"
KOOST_PATH=$GECKO_PATH"koost/"
SYSAPP_PATH=$APPS_PATH"system/"
function check_exist_and_cd {
PRJ_PATH=$1
BASE_PATH=$2
DST_PATH=$PRJ_PATH"/$BASE_PATH"
if [ ! -z $BASE_PATH ] && [ -d "$DST_PATH" ]
then
cd $DST_PATH
else
cd $PRJ_PATH"/KaiOS"
fi
}
case "$1" in
u)
ssh claire@claire.local
;;
bugs)
cd ~/Documents/bugs
;;
the)
cd ~/Documents/bugs/the-bugs
;;
ui)
cd ~/Documents/bugs/ui-utils
;;
all)
cd $BUILD_FILE_SYSTEM
;;
sidl)
cd $BUILD_FILE_SYSTEM/sidl
;;
sidl-d)
cd $BUILD_FILE_SYSTEM/sidl-desktop
;;
gf2)
check_exist_and_cd $GF2_PATH $BASE_PATH
;;
quoin)
check_exist_and_cd $QUOIN_PATH $BASE_PATH
;;
qq)
check_exist_and_cd $QUADRO_Q_SFP_PATH $BASE_PATH
;;
qqf)
check_exist_and_cd $QUADRO_Q_SFP_PATH $BASE_PATH
;;
qqt)
check_exist_and_cd $QUADRO_Q_ST_PATH $BASE_PATH
;;
3.0)
check_exist_and_cd $QUADRO_Q_SFP_3_0_PATH $BASE_PATH
;;
rt)
check_exist_and_cd $RT_PATH $BASE_PATH
;;
rt3.0)
check_exist_and_cd $RT_3_0_PATH $BASE_PATH
;;
mq)
check_exist_and_cd $MODRIC_Q_PATH $BASE_PATH
;;
mm)
check_exist_and_cd $MODRIC_M_PATH $BASE_PATH
;;
top)
cd $PRJ_PATH
;;
gitroot)
cd `git rev-parse --show-toplevel`
;;
out)
cd $OUT_PATH
;;
gonk)
cd $GONK_PATH
;;
gecko)
cd $GECKO_PATH
;;
next)
cd $QUADRO_Q_SFP_PATH"/KaiOS/gecko"
;;
gaia)
cd $GAIA_PATH
;;
apps)
cd $APPS_PATH
;;
mani)
cd $MANIFESTS_PATH
;;
product)
if [ 1 -eq "$(find $PRODUCT_PATH -maxdepth 1 -type d ! -path $PRODUCT_PATH | wc -l)" ];
then
cd "$(find $PRODUCT_PATH -maxdepth 1 -type d ! -path $PRODUCT_PATH)"
else
cd $PRODUCT_PATH
fi
;;
objdir)
cd $OBJDIR_PATH
;;
bin)
cd $BIN_PATH
;;
koost)
cd $KOOST_PATH
;;
b2g)
cd $BUILD_FILE_SYSTEM"/b2g"
;;
sysapp)
cd $SYSAPP_PATH
;;
*)
if [ -d "$1" ];
then
cd "$1"
elif [ -d "$B2G_PROJ_PATH/$1" ];
then
check_exist_and_cd "$B2G_PROJ_PATH/$1" $BASE_PATH
else
if [ $UNAME == "Linux" ];
then
echo "ubuntu Invalid Destination $1"
fi
return 1
fi
;;
esac
<file_sep>/README.md
This repository is to collect some tools.
<file_sep>/vimtabdiff.py
#! /usr/bin/env python
from __future__ import division # ensure / does NOT truncate
import os
import pexpect
import psutil
import string
import subprocess
import sys
import tempfile
if sys.version_info[0] == 2:
def trans(s):
return s.translate(string.maketrans("", ""), string.printable)
elif sys.version_info[0] == 3:
def trans(s):
return s.translate(str.maketrans("", "", string.printable))
else:
def trans(s):
return s
# Adapt from Python Cookbook <NAME>
def istext(s, threshold=0.30):
# if s contains any null, it's not text:
if "\0" in s:
return False
# an "empty" string is "text" (arbitrary but reasonable choice):
if not s:
return True
# Get the substring of s made up of non-text characters
t = trans(s)
# s is 'text' if less than 30% of its characters are non-text ones:
return len(t)/len(s) <= threshold
def tabdiff_with_vim(root1, root2, filelist):
cmd = ['vim', '-p']
non_text_filelist = []
for file_path in filelist:
if file_path.endswith('.pyc') or file_path.endswith('.swp'):
continue
file_path_in_root1 = os.path.join(root1, file_path)
if os.path.exists(file_path_in_root1):
if os.path.isdir(file_path_in_root1):
print('skip directory ' + os.path.join(root1, file_path))
non_text_filelist.append(file_path)
continue
with open(file_path_in_root1) as fp:
if not istext(fp.read(1024)):
print('skip non-text file ' + os.path.join(root1, file_path))
non_text_filelist.append(file_path)
else:
cmd.append(file_path_in_root1)
else:
cmd.append(os.devnull)
script_content = ''
for file_path in filelist:
if file_path.endswith('.pyc') or file_path.endswith('.swp'):
continue
if file_path in non_text_filelist:
print('skip non-text file ' + os.path.join(root2, file_path))
continue
file_path_in_root2 = os.path.join(root2, file_path)
if os.path.exists(file_path_in_root2):
script_content += ":vertical diffsplit %s\n" % file_path_in_root2
else:
script_content += ":vertical diffsplit %s\n" % os.devnull
script_content += ':wincmd l\n'
script_content += ':tabn\n'
with tempfile.NamedTemporaryFile(suffix = '_' + os.path.basename(__file__), mode = 'w') as fp:
fp.write(script_content)
fp.flush()
cmd += ['-s', fp.name]
try:
subprocess.check_call(cmd)
#print(' '.join(cmd))
#print(script_content)
except Exception as e:
print('Failed: ' + str(e))
print(' '.join(cmd))
print(script_content)
def list_diff_files(parent, dcmp):
diff_files = [os.path.join(parent, x) for x in dcmp.diff_files]
diff_files += [os.path.join(parent, x) for x in dcmp.left_only]
diff_files += [os.path.join(parent, x) for x in dcmp.right_only]
#diff_files += [os.path.join(parent, x) for x in dcmp.funny_files]
if dcmp.same_files:
print ("Warning: dcmp.same_files: " + str(dcmp.same_files))
if dcmp.left_only:
print(parent + ' Left Only:\n\t' + '\n\t'.join(dcmp.left_only))
pass
if dcmp.right_only:
print(parent + ' Right Only:\n\t' + '\n\t'.join(dcmp.right_only))
pass
if dcmp.funny_files:
print(parent + ' Files cannot be compared:\n\t' + '\n\t'.join(dcmp.funny_files))
pass
for subdir, sub_dcmp in dcmp.subdirs.items():
diff_files += list_diff_files(os.path.join(parent, subdir), sub_dcmp)
return diff_files
def diff_two_roots(root1, root2):
if os.path.isdir(root1) and os.path.isdir(root2):
dcmp = dircmp(os.path.realpath(root1), os.path.realpath(root2))
filelist = list_diff_files('', dcmp)
elif os.path.isfile(root1) and os.path.isfile(root2):
subprocess.check_call(['vimdiff', root1, root2])
sys.exit(0)
else:
raise ValueError('Please assign two directories or two files!')
if filelist:
if len(filelist) > 50:
print('Too many diff files to display. Total [%d] files' % len(filelist))
sys.exit(-1)
tabdiff_with_vim(root1, root2, filelist)
else:
print('No difference')
sys.exit(0)
if '__main__' == __name__:
from argparse import ArgumentParser
from filecmp import dircmp
bin_name = os.path.basename(sys.argv[0])
if bin_name.startswith('vimtabdiff') or bin_name.startswith('tdf'):
parser = ArgumentParser(description='Diff by vim, switching with tabs')
parser.add_argument('root1', help='right tab', type=str)
parser.add_argument('root2', help='left tab', type=str)
opt = parser.parse_args(sys.argv[1:])
diff_two_roots(opt.root2, opt.root1)
else:
child = pexpect.spawn('git difftool --dir-diff --no-prompt ' + ' '.join(sys.argv[1:]))
print('spawn git difftool pid ' + str(child.pid))
child.expect('\"')
if not child.isalive():
print('Error. child is not alive. pid ' + child.pid)
children = psutil.Process(child.pid).children(recursive=True)
# possible example of children:
# /usr/lib/git-core/git difftool--helper /tmp/git-difftool.DxqQaw/left/ /tmp/git-difftool.DxqQaw/right/
# /bin/sh /usr/lib/git-core/git-difftool--helper /tmp/git-difftool.DxqQaw/left/ /tmp/git-difftool.DxqQaw/right/
# vim -R -f -d -c wincmd l -c cd $GIT_PREFIX /tmp/git-difftool.DxqQaw/left/ /tmp/git-difftool.DxqQaw/right/
# /bin/bash -c diff -a /tmp/vzECZxX/0 /tmp/vzECZxX/1 >/tmp/vzECZxX/2 2>&1
for c in children:
if c.name() == 'vim':
root1 = c.cmdline()[-1]
root2 = c.cmdline()[-2]
break
else:
continue
else:
print('Error. unexpected children:\n' +
'\n'.join([' '.join(c.cmdline()) for c in children]))
sys.exit(-1)
diff_two_roots(root1, root2)
child.kill(0)
<file_sep>/gdf.py
#! /usr/bin/env python
import sys
import os
import subprocess
import tempfile
if '__main__' == __name__:
file_list = subprocess.check_output(['git', 'diff', '--name-only'] + sys.argv[1:]).split()
if not file_list:
print "No diff found."
sys.exit(0)
proj_path = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).strip()
subprocess.check_call(['git', 'config', 'core.worktree', proj_path])
cmd = ['vim', '-p'] + [os.path.join(proj_path, i) for i in file_list]
bin_name = os.path.basename(sys.argv[0])
if bin_name in ['gdf', 'gdfs']:
script_content = ''
vim_gdf_cmd = ':Gvdiffsplit\r\n' if bin_name == 'gdf' else ':Gdiffsplit\r\n'
for i in xrange(len(file_list)):
script_content += vim_gdf_cmd
script_content += ':wincmd l\n'
script_content += ':tabn\n'
with tempfile.NamedTemporaryFile(suffix = '_' + bin_name) as fp:
fp.write(script_content)
fp.flush()
cmd += ['-s', fp.name]
try:
subprocess.check_call(cmd)
except Exception, e:
print 'Failed: ' + str(e)
print ' '.join(cmd)
print script_content
elif bin_name == 'vdf':
try:
print cmd
subprocess.check_call(cmd)
except Exception, e:
print 'Failed: ' + str(e)
print ' '.join(cmd)
|
4b04641a4cc223cfe99457b207d3a806978c8b48
|
[
"Markdown",
"Python",
"Shell"
] | 5
|
Shell
|
vul3vm06/tools
|
d13d6283106b5da25e54acd8d39dc6c96f47774c
|
e8c635e331d6cb7f36cb2f878fc4e0751af1227b
|
refs/heads/master
|
<repo_name>embeddedmz/qwt_spectrogram_issue_example<file_sep>/plot.h
#include <qwt_plot.h>
#include <qwt_plot_spectrogram.h>
class SpectrogramData: public QwtRasterData
{
public:
SpectrogramData()
{
setInterval( Qt::XAxis, QwtInterval( -1.5, 1.5 ) );
setInterval( Qt::YAxis, QwtInterval( -1.5, 1.5 ) );
setInterval( Qt::ZAxis, QwtInterval( 0.0, 10.0 ) );
}
virtual double value( double x, double y ) const
{
const double c = 0.842;
//const double c = 0.33;
const double v1 = x * x + ( y - c ) * ( y + c );
const double v2 = x * ( y + c ) + x * ( y + c );
return 1.0 / ( v1 * v1 + v2 * v2 );
}
};
class Plot: public QwtPlot
{
Q_OBJECT
public:
enum ColorMap
{
RGBMap,
IndexMap,
HueMap,
AlphaMap
};
Plot( QWidget * = NULL );
QwtPlotSpectrogram *d_spectrogram;
public Q_SLOTS:
void showContour( bool on );
void showSpectrogram( bool on );
void setColorMap( int );
void setAlpha( int );
#ifndef QT_NO_PRINTER
void printPlot();
#endif
private:
int d_mapType;
int d_alpha;
};
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(QwtExample)
find_package(Qt5Widgets REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Core REQUIRED)
find_package(Qt5SerialPort REQUIRED)
find_package(Qt5PrintSupport REQUIRED)
# QWT : temporary solution
INCLUDE(FindQwt.cmake)
find_library(Qwt REQUIRED)
include_directories( ${QWT_INCLUDE_DIR} )
# ==============================================================================
# Source
# ==============================================================================
set(APP_SOURCE plot.cpp
main.cpp)
#set(UI_FILES qtMapCoordinatesWidget.ui qtWeatherStations.ui)
#set(QT_WRAP qtMapCoordinatesWidget.h qtWeatherStations.h)
# ==============================================================================
# Target
# ==============================================================================
add_executable(qwtexample
${APP_SOURCE}
${UISrcs}
${MOCSrcs})
set_target_properties(qwtexample PROPERTIES
AUTOMOC TRUE
AUTORCC TRUE
AUTOUIC TRUE)
target_link_libraries(qwtexample Qt5::Core Qt5::Gui Qt5::Widgets Qt5::SerialPort Qt5::PrintSupport
${QWT_LIBRARY})
target_include_directories(qwtexample PRIVATE
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR})
|
97b469e44cd1a4b6074ddce1b107facd3f1d6ae6
|
[
"CMake",
"C++"
] | 2
|
C++
|
embeddedmz/qwt_spectrogram_issue_example
|
cd4deb4d9497818f48a6a4afb70dacc6ce9ad9be
|
e5ccc3e625a05dfe1cd7101a0dbd65b620ff9249
|
refs/heads/master
|
<file_sep>todays_years =input("1. What year is it?: " )
todays_month =input("2. What month is it? Write full month, first letter capitalized. ")
todays_day = input("3. What day of the month is this month? Just type the number. ")
print("Today is " + todays_month + " " + todays_day + "," + " " + todays_years + ".")
year = input("4. What year were you born?: ")
month = input("5. What month were you born?: ")
day= input("6. What day of the month were you born: ")
print("You were born " + month + " " + day + "," + " " + year + ".")
month_dictionary = {'January': 1, 'February': '2', 'March': 3, 'April': 4, 'May': 5, 'June': 6,
'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12}
#age = 2019- int(year)
#print("You are " + str(age) + " " + "years old, as of Dec 2019. ")
birth_month = month_dictionary[month]
birth_month = int(birth_month)
todays_month = month_dictionary[todays_month]
todays_month = int(todays_month)
new_month_age = 12 -int(birth_month) + int(todays_month)
new_year_age_notyet = int(todays_years) -1 -int(year)
new_year_age = int(todays_years) -int(year)
if birth_month > todays_month:
print("You haven't had a birthday yet this year :(")
print("You are " + str(new_year_age_notyet) + " "+ "years old and" + " " + str(new_month_age) + " " + "months.")
elif birth_month == todays_month and todays_day == day:
print("Happy Birthday! You are " + str(new_year_age) + " " + "years old today!")
elif birth_month == todays_month and todays_day > day:
print("You are " + str(new_year_age) + " " + "years old. Happy Belated Birthday!")
elif birth_month == todays_month and todays_day < day:
print("You are " + str(new_year_age_notyet) + " " + "years old. Your birthday is coming up soon!")
elif birth_month < todays_month:
print ("It seems that your birthday has already passed, Happy Belated. You are " + " " + str(new_year_age) + " " + " years old and"
+ str(new_month_age) + " " + "months.")
#print(birth_month)
#print(todays_month)
#print(str(new_month_age))
#print(new_year_age)
|
cdf3281131737caeaeb313e9f3f1361d223d00c3
|
[
"Python"
] | 1
|
Python
|
m2angie94/BirthdayCalculator
|
4ce4f6b8f6b30efae51749212c2a6e51680aab73
|
76c076f3fa414ff4c356f5e93e1224109d1c8ab5
|
refs/heads/master
|
<file_sep>import logging
main_logger = logging.getLogger('main_logger')
task_logger = logging.getLogger('task_logger')
def config_loggers():
log_format = '%(asctime)s [P%(process)s] %(levelname)-8s : %(module)s - %(message)s'
formatter = logging.Formatter(log_format)
main_logger.setLevel(logging.ERROR)
file_handler = logging.FileHandler('logs/main.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
main_logger.addHandler(file_handler)
main_logger.addHandler(stream_handler)
task_logger.setLevel(logging.ERROR)
task_file_handler = logging.FileHandler('logs/task.log')
task_file_handler.setLevel(logging.DEBUG)
task_file_handler.setFormatter(formatter)
main_logger.addHandler(task_file_handler)
<file_sep># -*- coding: utf-8 -*-
'''
XMPP Bots
'''
import logging
import sleekxmpp
from models import WorkTask
class ServerXMPPBot(sleekxmpp.ClientXMPP):
'''
ServerXMPPBot
'''
def __init__(self, jid, password, task_queue):
self.name = jid.split('@')[0]
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("connected", self.connect_handler)
self.add_event_handler("disconnected", self.disconnect_handler)
self.add_event_handler("session_start", self.session_start_handler)
self.add_event_handler("message", self.message_handler)
self.auto_authorize = True
self.auto_reconnect = True
self.task_queue = task_queue
self.protokol = None
def message_handler(self, message):
logging.debug('%s receive message: %s' % (self.name, str(message.values)))
work_task = WorkTask(message.getFrom(), message['body'])
self.task_queue.put(work_task)
def disconnect_handler(self, event):
logging.info('[HANDLER] %s was disconnected' % self.name)
def connect_handler(self, event):
logging.info('[HANDLER] %s was connected' % self.name)
def session_start_handler(self, event):
logging.info('[HANDLER] %s session was started' % self.name)
self.send_presence()
self.get_roster()
def disconnect_from_server(self):
self.disconnect(wait=False)
def send_msg(self, recipient, msg):
logging.debug('%s send to %s message: %s' % (self.name, recipient, msg))
self.send_message(recipient, msg)
<file_sep>import logging
import sqlalchemy
import models
from sqlalchemy.orm import sessionmaker
READ_OPERATIONS = [
'get_messages',
'get_consultants',
'get_categories'
]
WRITE_OPERATIONS = [
'ask_question',
'send_chat_message'
]
class DatabaseManager(object):
def __init__(self):
#self.engine = sqlalchemy.create_engine('sqlite:///:memory:')
self.engine = sqlalchemy.create_engine('sqlite:///temp.db', echo=False)
self.connection = self.engine.connect()
self.session_maker = sessionmaker(bind=self.engine)
self.create_all()
def create_all(self):
models.register_models(self.engine)
def add_categories(self):
models.create_categories(self.session_maker())
def drop_all(self):
models.unregister_models(self.engine)
def get_session(self):
return self.session_maker()
class CallStatController(object):
def __init__(self):
pass
def __enter__(self):
logging.debug('Enter into CallStatManager')
def __exit__(self):
logging.debug('Exit from CallStatManager')
<file_sep>'''
Controllers
'''
import logging
import multiprocessing
import pool
HANDLER_WORK_COUNT = 40
class PoolController(object):
'''
PoolController
'''
def __init__(self, task_handler_queue, send_message_queue):
'''
Init
'''
self.task_handler_pool = pool.TaskHandlerPool(HANDLER_WORK_COUNT)
self.server_bot_pool = pool.ServerBotPool()
self.task_queue = task_handler_queue
self.send_queue = send_message_queue
self.state = False
def start(self):
'''
Start
'''
if self.state is False:
logging.info('Pool Controller - Start pools')
self.state = True
self.task_handler_pool.start(self.task_queue, self.send_queue)
self.server_bot_pool.start(self.task_queue, self.send_queue)
logging.info('Pool Controller - All pools are started')
else:
logging.debug('Pools are already started')
def stop(self):
'''
Stop
'''
if self.state is True:
logging.debug('Pool Controller - Stop pools')
self.state = False
self.task_handler_pool.stop()
self.server_bot_pool.stop()
logging.debug('Pool Controller - All pools are stopped')
else:
logging.debug('Pools are already stopped')
def get_state(self):
'''
Get State
'''
task_pool_info = 'TaskHandlerPool:\n' + str(self.task_handler_pool.work_pool) + '\n'
bot_pool_info = 'ServerBotPool:\n' + str(self.server_bot_pool.work_pool) + '\n'
return task_pool_info + bot_pool_info
class QueueController(object):
'''
QueueController
'''
def __init__(self):
'''
Init
'''
self.task_handler_queue = multiprocessing.Queue()
self.send_message_queue = multiprocessing.Queue()
def get_state(self):
'''
Get State
'''
task_info = 'Task handler queue length = %i' % \
self.task_handler_queue.qsize() + '\n'
send_info = 'Send handler queue length = %i' % \
self.send_message_queue.qsize() + '\n'
return task_info + send_info
<file_sep>PROJECT IN DEVELOPMENT...
CRIVIE RUKI: ACTIVATED!
BIDLO STYLE: ACTIVATED!
SHITOCOD : ACTIVATED!
CONTROL CODA: OFF
TRUE MODE: OFF
MOZG: NE NAIDEN!
<file_sep>"""
Config file
"""
IP = '172.16.31.10'
PORT = '15222'
VIRTUAL_HOST = 'cons-jabber'
RECEIVER_BOTS = {
'server-recv001@' + VIRTUAL_HOST : '111',
#'server-recv002@' + VIRTUAL_HOST : '111',
#'server-recv003@' + VIRTUAL_HOST : '111',
#'server-recv004@' + VIRTUAL_HOST : '111',
}
SENDER_BOTS = {
'server-send001@' + VIRTUAL_HOST : '111',
'server-send002@' + VIRTUAL_HOST : '111',
'server-send003@' + VIRTUAL_HOST : '111',
'server-send004@' + VIRTUAL_HOST : '111',
#'server-send005@' + VIRTUAL_HOST : '111',
#'server-send006@' + VIRTUAL_HOST : '111',
#'server-send007@' + VIRTUAL_HOST : '111',
#'server-send008@' + VIRTUAL_HOST : '111',
#'server-send009@' + VIRTUAL_HOST : '111',
#'server-send010@' + VIRTUAL_HOST : '111',
}
QUEUE_GET_TIMEOUT = 10
CATEGORIES_LIST = 'utils/categories.txt'
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
if sys.version_info < (3, 0):
reload(sys)
sys.setdefaultencoding('utf8')
else:
raw_input = input
class EchoBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.start)
self.add_event_handler("message", self.message)
def start(self, event):
print 'Session start'
self.send_presence()
self.get_roster()
def message(self, msg):
print msg
print "%(body)s" % msg
"""
def send_message(self, mto, mbody, msubject=None, mtype=None,
mhtml=None, mfrom=None, mnick=None):
self.make_message(mto, mbody, msubject, mtype,
mhtml, mfrom, mnick).send() """
if __name__ == '__main__':
optp = OptionParser()
optp.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
optp.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
optp.add_option("-j", "--jid", dest="jid",
help="JID to use")
optp.add_option("-p", "--password", dest="password",
help="password to use")
opts, args = optp.parse_args()
logging.basicConfig(level=opts.loglevel,
format='%(levelname)-8s %(message)s')
opts.jid = "testuser@cons-jabber"
opts.password = "<PASSWORD>"
xmpp = EchoBot(opts.jid, opts.password)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0004') # Data Forms
xmpp.register_plugin('xep_0060') # PubSub
xmpp.register_plugin('xep_0199') # XMPP Ping
# If you are working with an OpenFire server, you may need
# to adjust the SSL version used:
# xmpp.ssl_version = ssl.PROTOCOL_SSLv3
# If you want to verify the SSL certificates offered by a server:
# xmpp.ca_certs = "path/to/ca/cert"
if xmpp.connect(('192.168.3.11', '15222')):
xmpp.process(block=False)
print 'Try to get receivers...'
xmpp.send_message('server-recv001@cons-jabber', 'get_recvs')
while True:
msg_list = raw_input().split()
if len(msg_list) == 2:
message, num = msg_list
else:
message = msg_list[0]
num = 1
for i in range(int(num)):
xmpp.send_message('server-recv001@cons-jabber', message)
else:
print("Unable to connect.")
<file_sep>'''
Server
'''
import optparse
import logging
import database
from controllers import QueueController, PoolController
from utils.statistics import Statistics
from utils.misc import main_logger
class ServerComponent(object):
'''
ServerComponent
'''
def __init__(self):
self.statistics = Statistics()
self.db_controller = database.DatabaseManager()
self.queue_controller = None
self.pool_controller = None
self.is_started = False
def start(self):
main_logger.info('Starting server...')
self.db_controller.add_categories()
self.queue_controller = QueueController()
self.pool_controller = PoolController(
self.queue_controller.task_handler_queue,
self.queue_controller.send_message_queue)
self.pool_controller.start()
self.is_started = True
main_logger.info('Server succesfully started!')
def stop(self):
main_logger.info('Stopping server...')
self.pool_controller.stop()
self.is_started = False
main_logger.info('Server succesfully stopped!')
def run(self):
try:
while True:
message = unicode(raw_input())
if message.startswith('quit'):
self.stop()
break
elif message.startswith('stat'):
print self.pool_controller.get_state()
print self.queue_controller.get_state()
print self.statistics.avg_time()
elif message.startswith('restart'):
main_logger.info('Restarting ServerComponent...')
self.stop()
self.start()
main_logger.info('Server succesfully restarted!')
else:
main_logger.info('Wrong command')
except KeyboardInterrupt:
main_logger.info('Got KeyboardInterrupt... stopping server...')
self.stop()
def parse_args():
opt = optparse.OptionParser()
opt.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
opt.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
opt.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
opts, args = opt.parse_args()
log_format = '%(asctime)s [P%(process)s] %(levelname)-8s : %(module)s - %(message)s'
main_logger.info('Got args: %s' % str(opts))
return (opts, args)
if __name__ == '__main__':
opts, args = parse_args()
server_component = ServerComponent()
server_component.start()
server_component.run()
<file_sep>'''
WORKERS
'''
import multiprocessing
import logging
import utils.config
import time
import xmpp_bots
import models
import database
from multiprocessing.queues import Empty
from utils.misc import main_logger, task_logger
class BasicWorker(multiprocessing.Process, object):
'''
BasicWorker
'''
def __init__(self):
super(BasicWorker, self).__init__()
self.db_manager = database.DatabaseManager()
self.session = self.db_manager.get_session()
self.process = multiprocessing.current_process()
self.work = True
class TaskHandler(BasicWorker):
'''
TaskHandler
'''
def __init__(self, task_handler_queue, send_message_queue):
super(TaskHandler, self).__init__()
self.task_queue = task_handler_queue
self.send_queue = send_message_queue
def stop(self):
main_logger.debug('Turn off')
self.work = False
def run(self):
task_logger.info('Process %s is ready to work' % self.name)
main_logger.info('Process %s is ready to work' % self.name)
get_timeout = utils.config.QUEUE_GET_TIMEOUT
while self.work:
try:
task_logger.info('%s is trying to get a task...' % self.name)
task = self.task_queue.get(block=True, timeout=get_timeout)
task_logger.info('%s got task [%s]' % (self.name,
str(task)))
self.handle_task(task)
except Empty:
task_logger.info('%s timeouted...' % self.name)
task_logger.info('Process %s is ending...' % self.name)
main_logger.info('Process %s is ready to work' % self.name)
def handle_task(self, work_task):
message = work_task.body
send_task = None
if message == 'get_categories':
data = '|'.join(map(str, self.db_manager.get_session().query(models.models.Category).all()))
send_task = models.SendTask(work_task.jid, data)
elif message == 'get_recvs':
send_task = models.SendTask(work_task.jid,
str(utils.config.RECEIVER_BOTS.keys()))
elif message == 'get_sends':
send_task = models.SendTask(work_task.jid,
str(utils.config.SENDER_BOTS.keys()))
elif message == 'question':
question = models.Question(message, work_task.jid, 777)
self.session.add(question)
self.session.commit()
send_task = models.SendTask(work_task.jid, str(question.id))
else:
time.sleep(1)
self.session.add(work_task)
if send_task:
self.session.add(send_task)
self.send_queue.put(send_task)
work_task.finish()
self.session.commit()
main_logger.info('Handle task [%f] seconds...' % work_task.handle_time)
class ServerBotWorker(BasicWorker):
'''
ServerBotWorker
'''
def __init__(self, jid, passwd, task_queue, send_queue):
super(ServerBotWorker, self).__init__()
self.work_bot = None
self.jid = jid
self.passwd = <PASSWORD>
self.conn_params = (utils.config.IP, utils.config.PORT)
self.task_queue = task_queue
self.send_queue = send_queue
def xmpp_connect(self):
if self.work_bot.connect(self.conn_params, use_tls=False):
main_logger.info('%s succesfully connected to server' % self.work_bot.name)
else:
main_logger.error('%s failed connection to server' % self.work_bot.name)
assert False
def xmpp_disconnect(self):
main_logger.info('%s trying to disconnect from server...' % self.work_bot.name)
self.work_bot.disconnect_from_server()
def stop(self):
self.work = False
self.xmpp_disconnect()
def init_worker(self):
main_logger.info('Init xmpp worker')
self.work_bot = xmpp_bots.ServerXMPPBot(self.jid, self.passwd,
self.task_queue)
self.work_bot.register_plugin('xep_0030') # Service Discovery
self.work_bot.register_plugin('xep_0004') # Data Forms
self.work_bot.register_plugin('xep_0060') # PubSub
self.work_bot.register_plugin('xep_0199') # XMPP Ping
self.xmpp_connect()
self.work_bot.process(block=False)
def run(self):
self.init_worker()
main_logger.info('Process %s is ready to work' % self.name)
task_logger.info('Process %s is ready to work' % self.name)
while self.work:
try:
task_logger.debug('%s is trying to get a task...' % self.name)
send_task = self.send_queue.get(block=True, timeout=utils.config.QUEUE_GET_TIMEOUT)
task_logger.info('%s got send task [%s, %s]' % (self.name, send_task.jid, send_task.body))
self.work_bot.send_msg(send_task.jid, send_task.body)
send_task.finish()
except Empty:
task_logger.debug('%s timeouted...' % self.name)
task_logger.info('Process %s is ending...' % self.name)
main_logger.info('Process %s is ending...' % self.name)
<file_sep>import datetime
import logging
from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import ForeignKey
# make it as sep class
Base = declarative_base()
class DeclarativeBase():
def __init__(self):
pass
def __repr__(self):
printed = {k: v for k, v in self.__dict__.iteritems() if k in self.__class__.__dict__}
print printed
#return "<WorkTask('{body:s}', '{jid:s}', '{task_type:s}', '{create_dt:s}', '{finish_dt:s}', '{handle_time:f}')>".format(self.__dict__)
class WorkTask(Base, DeclarativeBase):
__tablename__ = 'work_tasks'
id = Column(Integer, primary_key=True)
body = Column(String)
jid = Column(String)
task_type = Column(String)
create_dt = Column(DateTime)
finish_dt = Column(DateTime)
handle_time = Column(Integer)
def __init__(self, sender, body):
self.body = body
self.jid = str(sender)
self.task_type = 'work_task'
self.create_dt = datetime.datetime.utcnow()
self.finish_dt = None
self.handle_time = None
def finish(self):
self.finish_dt = datetime.datetime.utcnow()
self.handle_time = (self.finish_dt - self.create_dt).total_seconds()
class SendTask(Base, DeclarativeBase):
__tablename__ = 'send_tasks'
id = Column(Integer, primary_key=True)
body = Column(String)
jid = Column(String)
task_type = Column(String)
create_dt = Column(DateTime)
finish_dt = Column(DateTime)
handle_time = Column(Integer)
def __init__(self, receiver, body):
self.body = body
self.jid = str(receiver)
self.task_type = 'send_task'
self.create_dt = datetime.datetime.utcnow()
self.finish_dt = None
self.handle_time = None
def finish(self):
self.finish_dt = datetime.datetime.utcnow()
self.handle_time = (self.finish_dt - self.create_dt).total_seconds()
def get_info(self):
return (self.jid, self.body)
class Chat(Base, DeclarativeBase):
__tablename__ = 'chats'
id = Column(Integer, primary_key=True)
question_id = Column(Integer, ForeignKey('questions.id'))
consultant_id = Column(Integer, ForeignKey('consultants.id'))
create_dt = Column(DateTime)
def __init__(self, question_id, consultant_id):
self.question_id = question_id
self.consultant_id = consultant_id
self.create_dt = datetime.datetime.utcnow()
class ChatMessage(Base, DeclarativeBase):
__tablename__ = 'chat_messages'
id = Column(Integer, primary_key=True)
chat_id = Column(Integer, ForeignKey('chats.id'))
message = Column(String)
create_dt = Column(DateTime)
def __init__(self, chat_id, message):
self.chat_id = chat_id
self.message = message
self.create_dt = datetime.datetime.utcnow()
class CallStat(Base, DeclarativeBase):
__tablename__ = 'call_stats'
id = Column(Integer, primary_key=True)
user = Column(String)
resource = Column(String)
call_dt = Column(DateTime)
def __init__(self, user, resource):
self.user = user
self.resource = resource
self.call_dt = datetime.datetime.utcnow()
class Category(Base, DeclarativeBase):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
name = Column(String)
is_active = Column(Boolean)
add_dt = Column(DateTime)
def __init__(self, name):
self.name = name
self.is_active = True
self.add_dt = datetime.datetime.utcnow()
def disable(self):
self.is_active = False
class Consultant(Base, DeclarativeBase):
__tablename__ = 'consultants'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name):
self.name = name
#class ConsultantCategory(Base, DeclarativeBase):
# __table__ = 'consultant_categories'
# id = Column(Integer, primary_key=True)
# consultant_id = Column(Integer, ForeignKey('consultants.id'))
# category_id = Column(Integer, ForeignKey('categories.id'))
#
# def __init__(self, cons_id, cat_id):
# self.consultant_id = cons_id
# self.category_id = cat_id
#
# def __repr__(self):
# return "<Category('{name:s}', '{is_active:b}', '{add_dt:s}')>".format(**self.__dict__)
class Question(Base, DeclarativeBase):
__tablename__ = 'questions'
id = Column(Integer, primary_key=True)
message = Column(String)
from_jid = Column(String)
category_id = Column(Integer) #foreign key
create_dt = Column(DateTime)
is_active = Column(Boolean)
def __init__(self, message, from_jid, category_id):
self.message = message
self.from_jid = from_jid
self.category_id = category_id
self.create_dt = datetime.datetime.utcnow()
self.is_active = True
def close(self):
pass
_models = [WorkTask, SendTask, Question, Category, Chat, ChatMessage]
def register_models(engine):
logging.debug('Models: {0}'.format(repr(_models)))
for model in _models:
model.metadata.create_all(engine)
def unregister_models(engine):
logging.debug('Drop all models')
for model in _models:
model.metadata.drop_all(engine)
def create_categories(session):
logging.debug('Create categories')
with open('utils/categories.txt') as cat_file:
for row in cat_file:
category = Category(unicode(row.strip()))
session.add(category)
session.commit()
<file_sep>'''
Pool
'''
import logging
import multiprocessing
import workers
from utils import config
class BasicPool(object):
'''
Basic Pool
'''
def __init__(self, work_num=None):
self.worker_number = work_num
if not self.worker_number:
self.worker_number = multiprocessing.cpu_count() * 2
self.name = ''
self.work_pool = []
def stop(self):
logging.info('Stopping [%s]...' % self.name)
for worker in self.work_pool:
logging.info('Stopping [%s]...' % worker.name)
worker.stop()
worker.terminate()
class ServerBotPool(BasicPool):
'''
Server Bot Pool
'''
def __init__(self):
super(ServerBotPool, self).__init__(len(config.RECEIVER_BOTS.keys()))
self.name = 'ServerBotPool'
def start(self, task_queue, send_queue):
logging.info('Starting ServerBotPool with %i workers...' % self.worker_number)
for (jid, passwd) in config.RECEIVER_BOTS.iteritems():
worker = workers.ServerBotWorker(jid, passwd,
task_queue, send_queue)
worker.init_worker()
worker.start()
self.work_pool.append(worker)
logging.debug('Process start: %s [%s]' % (worker.name, worker.pid))
class TaskHandlerPool(BasicPool):
'''
Task Handler Pool
'''
def __init__(self, worker_num):
super(TaskHandlerPool, self).__init__()
self.name = 'TaskHandlerPool'
self.worker_number = worker_num
def start(self, task_queue, send_queue):
logging.info('Starting TaskHandlerPool with %i workers...' % self.worker_number)
for i in range(self.worker_number):
worker = workers.TaskHandler(task_queue, send_queue)
worker.start()
self.work_pool.append(worker)
logging.debug('Process start: %s [%s]' % (worker.name, worker.pid))
<file_sep>import misc
misc.config_loggers()
<file_sep>import subprocess
import config
REGISTER_CMD = 'sudo ejabberdctl register %s %s %s'
def register_users():
users = dict(config.RECEIVER_BOTS.items() + config.SENDER_BOTS.items())
for (login, passwd) in users.iteritems():
username, host = login.split('@')
print 'Register [%s]...' % username
proc = subprocess.call(REGISTER_CMD % (username, host, passwd), shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if __name__ == '__main__':
register_users()
<file_sep>import logging
class Statistics:
_dict = {
'task_count' : 0,
'total_handler_time' : 0.0,
}
def __init__(self):
self.__dict__ = Statistics._dict
def add_call(self, time):
logging.info('Add call with %f time' % time)
self.task_count += 1
self.total_handler_time += time
def avg_time(self):
try:
return self.task_count / self.total_handler_time
except ZeroDivisionError:
return 'Stat is empty - 0.0'
|
56baadb926a286b17934f7b584bac9459432af08
|
[
"Markdown",
"Python"
] | 14
|
Python
|
Skydreamer/consultant-backend
|
e56ab281df4c843e8757caf53beff6f2a41990f4
|
b9376e3133f9648f5b7169e3dbfc17bc8dcfd43a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.