language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 10,371
| 3.046875
| 3
|
[] |
no_license
|
using Model.Entity;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace Model.Dao
{
public class AtendenteDao : ICrud<Atendente> //Realiza uma interface que recebe a classe atendente
{
//Objetos de conexão com banco de dados
private ConexaoDB objConexaoDB;
private SqlCommand comando = null;
public AtendenteDao()
{
objConexaoDB = ConexaoDB.saberEstado();
}
public void alterar(Atendente objAtendente)
{
//Comando SQL para atualizar dados na tabela empresa
string update = "UPDATE analista SET nome='" + objAtendente.Nome + "', cpf='" + objAtendente.Cpf + "', funcao='" + objAtendente.Funcao +"' where mat_analista ='"+objAtendente.Matricula+"'";
try
{
comando = new SqlCommand(update, objConexaoDB.getCon());
objConexaoDB.getCon().Open(); //Abre uma nova conexao
comando.ExecuteNonQuery();
}
catch (Exception)
{
objAtendente.EstadoCon = 1; //Erro ao tentar inserir
}
finally
{
objConexaoDB.getCon().Close(); //Fecha a conexão
objConexaoDB.closeDB();
}
}
public bool buscar(Atendente objAtendente)
{
bool temRegistros;
// Comando SQL para buscar dados na tabela empresa
string find = "SELECT * FROM analista WHERE mat_analista = '" + objAtendente.Matricula + "';";
try
{
comando = new SqlCommand(find, objConexaoDB.getCon());
objConexaoDB.getCon().Open(); //Abre uma nova conexao
SqlDataReader reader = comando.ExecuteReader();
temRegistros = reader.Read();
if (temRegistros)
{
objAtendente.Matricula = Convert.ToInt32(reader[0]);
objAtendente.Nome = reader[1].ToString();
objAtendente.Cpf = reader[2].ToString();
objAtendente.Funcao = reader[3].ToString();
objAtendente.EstadoCon = 99; //Registro foi encontrado
}
else
{
objAtendente.EstadoCon = 1; //Não foi encontrado nenhum registro
}
}
catch (Exception)
{
throw;
}
finally
{
objConexaoDB.getCon().Close(); //Fecha a conexão
objConexaoDB.closeDB();
}
return temRegistros;
}
public List<Atendente> buscarTudo()
{
List<Atendente> listaAtendente = new List<Atendente>();
// Comando SQL para buscar dados na tabela analista
string findAll = "SELECT * FROM analista ORDER BY nome ASC;";
try
{
comando = new SqlCommand(findAll, objConexaoDB.getCon());
objConexaoDB.getCon().Open(); //Abre uma nova conexao
SqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
Atendente atendente = new Atendente();
atendente.Matricula = Convert.ToInt32(reader[0].ToString()); //Pegando um valor inteiro e convertendo para String
atendente.Nome = reader[1].ToString();
atendente.Cpf = reader[2].ToString();
atendente.Funcao = reader[3].ToString();
//Adicionando o objeto de empresa à lista
listaAtendente.Add(atendente);
}
}
catch (Exception)
{
throw;
}
finally
{
objConexaoDB.getCon().Close(); //Fecha a conexão
objConexaoDB.closeDB();
}
return listaAtendente;
}
public void cadastrar(Atendente objAtendente)
{
//Comando SQL para inserir dados na tabela empresa
string create = "INSERT INTO analista(nome, cpf, funcao) VALUES('" + objAtendente.Nome + "', '" + objAtendente.Cpf + "', '" + objAtendente.Funcao + "');";
try
{
comando = new SqlCommand(create, objConexaoDB.getCon());
objConexaoDB.getCon().Open(); //Abre uma nova conexao
comando.ExecuteNonQuery();
}
catch (Exception)
{
objAtendente.EstadoCon = 1; //Erro ao tentar inserir
}
finally
{
objConexaoDB.getCon().Close(); //Fecha a conexão
objConexaoDB.closeDB();
}
}
public void excluir(Atendente objAtendente)
{
//Comando SQL para excluir dados na tabela atendente
string delete = "DELETE FROM analista WHERE mat_analista = '" + objAtendente.Matricula + "';";
try
{
comando = new SqlCommand(delete, objConexaoDB.getCon());
objConexaoDB.getCon().Open(); //Abre uma nova conexao
comando.ExecuteNonQuery();
}
catch (Exception)
{
objAtendente.EstadoCon = 1; //Erro ao tentar inserir
}
finally
{
objConexaoDB.getCon().Close(); //Fecha a conexão
objConexaoDB.closeDB();
}
}
//Busca atendente por CPF
public bool buscarAtendentePorCpf(Atendente objAtendente)
{
bool temRegistros;
string find = "select * from analista where cpf='" + objAtendente.Cpf + "';";
try
{
comando = new SqlCommand(find, objConexaoDB.getCon());
objConexaoDB.getCon().Open();
SqlDataReader reader = comando.ExecuteReader();
temRegistros = reader.Read();
if (temRegistros)
{
objAtendente.Nome = reader[1].ToString();
objAtendente.Cpf = reader[2].ToString();
objAtendente.Funcao = reader[3].ToString();
objAtendente.EstadoCon = 99;
}
else
{
objAtendente.EstadoCon = 1;
}
}
catch (Exception)
{
throw;
}
finally
{
objConexaoDB.getCon().Close();
objConexaoDB.closeDB();
}
return temRegistros;
}
//Busca dados do analista por CPF ou nome
public List<Atendente> buscarTudoAtendente(Atendente objAtendente)
{
List<Atendente> listaAtendentes = new List<Atendente>();
string findAll = "SELECT * FROM analista WHERE nome like '%" + objAtendente.Nome + "%' or cpf like '%" + objAtendente.Cpf + "%' or funcao like '%" + objAtendente.Funcao + "%' ;";
try
{
comando = new SqlCommand(findAll, objConexaoDB.getCon());
objConexaoDB.getCon().Open();
SqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
Atendente atendente = new Atendente();
atendente.Matricula = Convert.ToInt32(reader[0].ToString());
atendente.Nome = reader[1].ToString();
atendente.Cpf = reader[2].ToString();
atendente.Funcao = reader[3].ToString();
//Adicionando na lista
listaAtendentes.Add(atendente);
}
}
catch (Exception)
{
throw;
}
finally
{
objConexaoDB.getCon().Close();
objConexaoDB.closeDB();
}
return listaAtendentes;
}
public Atendente buscarPorMatricula(int matricula)
{
Atendente objAtendente = new Atendente();
string find = "select * from analista where mat_analista=" + matricula + ";";
try
{
comando = new SqlCommand(find, objConexaoDB.getCon());
objConexaoDB.getCon().Open();
SqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
objAtendente.Matricula = Convert.ToInt32(reader[0].ToString());
objAtendente.Nome = reader[1].ToString();
objAtendente.Cpf = reader[2].ToString();
objAtendente.Funcao = reader[3].ToString();
}
}
catch (Exception)
{
objAtendente.EstadoCon = 1000;
}
finally
{
objConexaoDB.getCon().Close();
objConexaoDB.closeDB();
}
return objAtendente;
}
//Busca atendente por CPF e retorna o id
public int buscarMatriculaPorCpf(string cpf)
{
int matricula;
string find = "select mat_analista from analista where cpf='" + cpf + "';";
try
{
comando = new SqlCommand(find, objConexaoDB.getCon());
objConexaoDB.getCon().Open();
SqlDataReader reader = comando.ExecuteReader();
if (reader.Read())
{
matricula = Convert.ToInt32(reader[0].ToString());
}
else
{
matricula = -1;
}
}
catch (Exception)
{
matricula = 0;
}
finally
{
objConexaoDB.getCon().Close();
objConexaoDB.closeDB();
}
return matricula;
}
}
}
|
Java
|
UTF-8
| 3,708
| 2.015625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import client.Chucnang;
import client.G;
/**
*
* @author minhduc
*/
public class Nhomchuathamgia extends javax.swing.JPanel {
public Nhomchuathamgia() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
dsnhomchuathamgia = new javax.swing.JList<>();
jLabel1 = new javax.swing.JLabel();
dsnhomchuathamgia.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
dsnhomchuathamgiaMouseClicked(evt);
}
});
jScrollPane1.setViewportView(dsnhomchuathamgia);
jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jLabel1.setText("Danh sach nhom chua tham gia");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(119, 119, 119)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(279, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(110, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void dsnhomchuathamgiaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dsnhomchuathamgiaMouseClicked
// TODO add your handling code here:
try {
String value = Nhomchuathamgia.dsnhomchuathamgia.getSelectedValue();
if(value!=null){
Chucnang.Tatluong();
int x=javax.swing.JOptionPane.showConfirmDialog(Index.nhomchuathamgiaPanel,"Tham gia nhom "+ value);
if(x==javax.swing.JOptionPane.YES_OPTION){
boolean thamgianhom = G.iControl.thamgianhom(G.tennguoidung,value);
}
Chucnang.Batluongnhomchuathamgia();
}
} catch (Exception e) {
System.out.println("Loi tham gia nhom!");
}
}//GEN-LAST:event_dsnhomchuathamgiaMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
public static javax.swing.JList<String> dsnhomchuathamgia;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
|
C++
|
UTF-8
| 18,657
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#include <list>
#include <optional>
#include <spdlog/fmt/fmt.h>
#include "kaacore/easings.h"
#include "kaacore/exceptions.h"
#include "kaacore/log.h"
#include "kaacore/nodes.h"
#include "kaacore/transitions.h"
namespace kaacore {
TransitionWarping::TransitionWarping(uint32_t loops, bool back_and_forth)
: loops(loops), back_and_forth(back_and_forth)
{
KAACORE_ASSERT(
this->loops >= 0, "Number of loop must be greater or equal to zero.");
}
double
TransitionWarping::duration_factor() const
{
if (this->loops == 0) {
return INFINITY;
} else {
return double(this->loops) * (1 + int(this->back_and_forth));
}
}
TransitionTimePoint
TransitionWarping::warp_time(
const TransitionTimePoint& tp, const Duration internal_duration) const
{
double duration_factor = (1 + int(this->back_and_forth));
Duration warped_abs_t = Duration(glm::mod(
tp.abs_t.count(), (internal_duration * duration_factor).count()));
// prevent floating errors from resetting cycle
uint32_t cycle_index = tp.abs_t / (internal_duration * duration_factor);
if (this->loops > 0 and cycle_index >= this->loops) {
warped_abs_t = internal_duration * duration_factor;
cycle_index--;
}
if (this->back_and_forth and warped_abs_t > internal_duration) {
warped_abs_t = std::chrono::abs(2 * internal_duration - warped_abs_t);
return TransitionTimePoint{warped_abs_t, (tp.is_backing != true),
cycle_index};
} else {
return TransitionTimePoint{warped_abs_t, (tp.is_backing != false),
cycle_index};
}
}
NodeTransitionBase::NodeTransitionBase()
: duration(std::nan("")), internal_duration(std::nan(""))
{}
NodeTransitionBase::NodeTransitionBase(
const Duration dur, const TransitionWarping& warping)
: duration(dur * warping.duration_factor()), internal_duration(dur),
warping(warping)
{}
std::unique_ptr<TransitionStateBase>
NodeTransitionBase::prepare_state(NodePtr node) const
{
return nullptr;
}
NodeTransitionCustomizable::NodeTransitionCustomizable() {}
NodeTransitionCustomizable::NodeTransitionCustomizable(
const Duration duration, const TransitionWarping& warping,
const Easing easing)
: NodeTransitionBase(duration, warping), _easing(easing)
{}
void
NodeTransitionCustomizable::process_time_point(
TransitionStateBase* state, NodePtr node,
const TransitionTimePoint& tp) const
{
KAACORE_ASSERT(
this->duration >= 0.s, "Duration must be greater than zero.");
const TransitionTimePoint local_tp =
this->warping.warp_time(tp, this->internal_duration);
KAACORE_LOG_TRACE(
"NodeTransitionCustomizable({})::process_time_point - node: {}, abs_t: "
"{}, local_abs_t: {}, internal_duration: {}",
fmt::ptr(this), fmt::ptr(node.get()), tp.abs_t.count(),
local_tp.abs_t.count(), this->internal_duration.count());
if (this->duration > 0.s) {
const double warped_t = local_tp.abs_t / this->internal_duration;
this->evaluate(state, node, ease(this->_easing, warped_t));
} else {
this->evaluate(state, node, tp.is_backing ? 0. : 1.);
}
}
struct _NodeTransitionsGroupSubState {
NodeTransitionHandle handle;
std::unique_ptr<TransitionStateBase> state;
bool state_prepared;
Duration starting_abs_t;
Duration ending_abs_t;
_NodeTransitionsGroupSubState(
const NodeTransitionHandle& transition_handle,
const Duration starting_abs_t, const Duration ending_abs_t)
: handle(transition_handle), starting_abs_t(starting_abs_t),
ending_abs_t(ending_abs_t), state(nullptr), state_prepared(false)
{}
};
NodeTransitionsGroupBase::NodeTransitionsGroupBase(
const std::vector<NodeTransitionHandle>& transitions) noexcept(false)
{
KAACORE_ASSERT(transitions.size(), "At least one transition is required.");
}
struct _NodeTransitionsSequenceState : TransitionStateBase {
TransitionTimePoint prev_tp;
std::list<_NodeTransitionsGroupSubState> sub_states;
std::list<_NodeTransitionsGroupSubState>::iterator sub_state_it;
};
NodeTransitionsSequence::NodeTransitionsSequence(
const std::vector<NodeTransitionHandle>& transitions,
const TransitionWarping& warping) noexcept(false)
: NodeTransitionsGroupBase(transitions)
{
Duration total_duration = 0.s;
bool has_infinite_subs = false;
for (const auto& tr : transitions) {
KAACORE_CHECK(
tr->duration >= 0.s, "Duration must be greater than zero.");
Duration sub_duration;
if (has_infinite_subs) {
throw exception("NodeTransitionsSequence has infinite "
"subtransition on non last position");
}
if (tr->duration.count() == INFINITY) {
sub_duration = tr->internal_duration;
has_infinite_subs = true;
} else {
sub_duration = tr->duration;
}
this->_sub_transitions.emplace_back(
tr, total_duration, total_duration + tr->duration);
total_duration += sub_duration;
}
this->has_infinite_sub_transitions = has_infinite_subs;
this->warping = warping;
if (has_infinite_subs) {
// TODO force user to set those implicitly?
this->warping.loops = 0;
this->warping.back_and_forth = false;
}
this->duration = total_duration * this->warping.duration_factor();
this->internal_duration = total_duration;
KAACORE_LOG_DEBUG(
"NodeTransitionsSequence({}) constructed - duration: {}, "
"internal_duration: {}",
fmt::ptr(this), this->duration.count(),
this->internal_duration.count());
}
std::unique_ptr<TransitionStateBase>
NodeTransitionsSequence::prepare_state(NodePtr node) const
{
auto sequence_state = std::make_unique<_NodeTransitionsSequenceState>();
for (const auto& sub_tr : this->_sub_transitions) {
sequence_state->sub_states.emplace_back(
sub_tr.handle, sub_tr.starting_time, sub_tr.ending_time);
}
sequence_state->sub_state_it = sequence_state->sub_states.begin();
return sequence_state;
}
void
NodeTransitionsSequence::process_time_point(
TransitionStateBase* state_b, NodePtr node,
const TransitionTimePoint& tp) const
{
const TransitionTimePoint warped_tp =
this->has_infinite_sub_transitions
? tp
: this->warping.warp_time(tp, this->internal_duration);
auto state = static_cast<_NodeTransitionsSequenceState*>(state_b);
auto it = state->sub_state_it;
uint32_t cur_cycle_index = state->prev_tp.cycle_index;
bool is_backing = state->prev_tp.is_backing;
KAACORE_LOG_TRACE(
"NodeTransitionsSequence({})::process_time_point - node: {}, abs_t: "
"{}, warped_abs_t: {}",
fmt::ptr(this), fmt::ptr(node.get()), tp.abs_t.count(),
warped_tp.abs_t.count());
while (cur_cycle_index <= warped_tp.cycle_index) {
if (not it->state_prepared) {
KAACORE_LOG_TRACE(
"NodeTransitionsSequence({})::process_time_point - preparing "
"state",
fmt::ptr(this));
it->state = it->handle->prepare_state(node);
it->state_prepared = true;
}
const Duration sub_abs_t = std::clamp<Duration>(
warped_tp.abs_t - it->starting_abs_t, 0.s, it->handle->duration);
const TransitionTimePoint sub_tp =
TransitionTimePoint{sub_abs_t, is_backing};
KAACORE_LOG_TRACE(
"NodeTransitionsSequence({})::process_time_point - processing "
"sub-transition, "
"sub_abs_t: {}",
fmt::ptr(this), sub_abs_t.count());
it->handle->process_time_point(it->state.get(), node, sub_tp);
if (node.is_marked_to_delete()) {
return;
}
if (cur_cycle_index == warped_tp.cycle_index and
is_backing == warped_tp.is_backing and
it->starting_abs_t <= warped_tp.abs_t and
it->ending_abs_t > warped_tp.abs_t) {
KAACORE_LOG_TRACE(
"NodeTransitionsSequence({})::process_time_point - met "
"breaking condition",
fmt::ptr(this));
break;
}
if (not is_backing) {
it++;
if (it == state->sub_states.end()) {
if (this->warping.back_and_forth or tp.is_backing) {
is_backing = true;
it--;
} else {
it = state->sub_states.begin();
cur_cycle_index++;
}
}
} else {
if (it == state->sub_states.begin()) {
is_backing = false;
cur_cycle_index++;
} else {
it--;
}
}
}
state->prev_tp = warped_tp;
state->sub_state_it = it;
}
struct _NodeTransitionsParallelSubState : _NodeTransitionsGroupSubState {
bool sleeping;
_NodeTransitionsParallelSubState(
const NodeTransitionHandle& transition_handle,
const Duration starting_abs_t, const Duration ending_abs_t)
: _NodeTransitionsGroupSubState(
transition_handle, starting_abs_t, ending_abs_t),
sleeping(false)
{}
};
struct _NodeTransitionsParallelState : TransitionStateBase {
TransitionTimePoint prev_tp;
std::vector<_NodeTransitionsParallelSubState> sub_states;
};
NodeTransitionsParallel::NodeTransitionsParallel(
const std::vector<NodeTransitionHandle>& transitions,
const TransitionWarping& warping) noexcept(false)
: NodeTransitionsGroupBase(transitions)
{
Duration max_sub_internal_duration = 0.s;
bool has_infinite_subs = false;
for (const auto& tr : transitions) {
Duration sub_duration;
KAACORE_CHECK(
tr->duration >= 0.s, "Duration must be greater than zero.");
if (tr->duration.count() == INFINITY) {
sub_duration = tr->internal_duration;
has_infinite_subs = true;
} else {
sub_duration = tr->duration;
}
max_sub_internal_duration =
std::max(max_sub_internal_duration, sub_duration);
this->_sub_transitions.emplace_back(tr, 0.s, tr->duration);
}
this->has_infinite_sub_transitions = has_infinite_subs;
this->warping = warping;
if (has_infinite_subs) {
// TODO force user to set those implicitly?
this->warping.loops = 0;
this->warping.back_and_forth = false;
}
this->duration =
max_sub_internal_duration * this->warping.duration_factor();
this->internal_duration = max_sub_internal_duration;
KAACORE_LOG_DEBUG(
"NodeTransitionsParallel({}) constructed - duration: {}, "
"internal_duration: {}",
fmt::ptr(this), this->duration.count(),
this->internal_duration.count());
}
std::unique_ptr<TransitionStateBase>
NodeTransitionsParallel::prepare_state(NodePtr node) const
{
auto sequence_state = std::make_unique<_NodeTransitionsParallelState>();
for (const auto& sub_tr : this->_sub_transitions) {
sequence_state->sub_states.emplace_back(
sub_tr.handle, sub_tr.starting_time, sub_tr.ending_time);
}
return sequence_state;
}
void
NodeTransitionsParallel::process_time_point(
TransitionStateBase* state_b, NodePtr node,
const TransitionTimePoint& tp) const
{
auto state = static_cast<_NodeTransitionsParallelState*>(state_b);
const TransitionTimePoint warped_tp =
this->has_infinite_sub_transitions
? tp
: this->warping.warp_time(tp, this->internal_duration);
uint32_t cur_cycle_index = state->prev_tp.cycle_index;
bool is_backing = state->prev_tp.is_backing;
KAACORE_LOG_TRACE(
"NodeTransitionsParallel({})::process_time_point - node: {}, abs_t: "
"{}, warped_abs_t: {}",
fmt::ptr(this), fmt::ptr(node.get()), tp.abs_t.count(),
warped_tp.abs_t.count());
while (cur_cycle_index <= warped_tp.cycle_index) {
for (auto& sub_state : state->sub_states) {
if (not sub_state.state_prepared) {
sub_state.state = sub_state.handle->prepare_state(node);
sub_state.state_prepared = true;
}
Duration sub_abs_t;
bool sub_fits;
if (cur_cycle_index < state->prev_tp.cycle_index) {
if (is_backing) {
sub_abs_t = 0.s;
} else {
sub_abs_t = sub_state.handle->duration;
}
sub_fits = true;
} else {
sub_abs_t = std::clamp<Duration>(
warped_tp.abs_t - sub_state.starting_abs_t, 0.s,
sub_state.handle->duration);
sub_fits =
(warped_tp.abs_t > sub_state.starting_abs_t and
warped_tp.abs_t < sub_state.ending_abs_t);
}
const TransitionTimePoint sub_tp =
TransitionTimePoint{sub_abs_t, is_backing};
if (not sub_state.sleeping) {
sub_state.handle->process_time_point(
sub_state.state.get(), node, sub_tp);
if (not sub_fits) {
sub_state.sleeping = true;
}
} else {
if (sub_fits) {
// TODO consider calling sub-transition edges
sub_state.handle->process_time_point(
sub_state.state.get(), node, sub_tp);
sub_state.sleeping = false;
}
}
if (node.is_marked_to_delete()) {
return;
}
}
if (this->warping.back_and_forth) {
if (is_backing) {
cur_cycle_index++;
}
is_backing = !is_backing;
if (!warped_tp.is_backing and is_backing) {
break;
}
} else {
cur_cycle_index++;
}
}
state->prev_tp = warped_tp;
}
NodeTransitionDelay::NodeTransitionDelay(const Duration duration)
: NodeTransitionBase(duration)
{}
void
NodeTransitionDelay::process_time_point(
TransitionStateBase* state, NodePtr node,
const TransitionTimePoint& tp) const
{}
NodeTransitionCallback::NodeTransitionCallback(
const NodeTransitionCallbackFunc& func)
: callback_func(func), NodeTransitionBase(0.s)
{}
void
NodeTransitionCallback::process_time_point(
TransitionStateBase* state, NodePtr node,
const TransitionTimePoint& tp) const
{
KAACORE_LOG_TRACE(
"NodeTransitionCallback({})::process_time_point - node: {}, abs_t: "
"{}",
fmt::ptr(this), fmt::ptr(node.get()), tp.abs_t.count());
KAACORE_ASSERT(this->callback_func, "No callback set.");
this->callback_func(node);
}
NodeTransitionRunner::NodeTransitionRunner(
const NodeTransitionHandle& transition)
{
this->setup(transition);
}
NodeTransitionRunner&
NodeTransitionRunner::operator=(const NodeTransitionHandle& transition)
{
this->setup(transition);
return *this;
}
void
NodeTransitionRunner::setup(const NodeTransitionHandle& transition)
{
this->transition_handle = transition;
this->transition_state.reset();
this->transition_state_prepared = false;
this->current_time = 0us;
}
bool
NodeTransitionRunner::step(NodePtr node, const HighPrecisionDuration dt)
{
KAACORE_ASSERT(bool(*this), "Invalid internal stet of transition runner.");
if (not this->transition_state_prepared) {
this->transition_state = this->transition_handle->prepare_state(node);
this->transition_state_prepared = true;
}
this->current_time += dt;
this->transition_handle->process_time_point(
this->transition_state.get(), node,
TransitionTimePoint{this->current_time});
if (this->current_time >= this->transition_handle->duration) {
return true;
}
return false;
}
NodeTransitionRunner::operator bool() const
{
return bool(this->transition_handle);
}
NodeTransitionHandle
NodeTransitionsManager::get(const std::string& name)
{
if (not this->_enqueued_updates.empty()) {
for (auto it = this->_enqueued_updates.rbegin();
it != this->_enqueued_updates.rend(); it++) {
const auto& [q_name, q_transition] = *it;
if (name == q_name) {
return q_transition;
}
}
}
const auto it = this->_transitions_map.find(name);
if (it != this->_transitions_map.end()) {
return std::get<NodeTransitionRunner>(*it).transition_handle;
}
return NodeTransitionHandle();
}
void
NodeTransitionsManager::set(
const std::string& name, const NodeTransitionHandle& transition)
{
if (not this->_is_processing) {
if (transition) {
this->_transitions_map.insert_or_assign(name, transition);
} else {
this->_transitions_map.erase(name);
}
} else {
this->_enqueued_updates.emplace_back(name, transition);
}
}
void
NodeTransitionsManager::step(NodePtr node, const HighPrecisionDuration dt)
{
KAACORE_ASSERT(
not node.is_marked_to_delete(), "Node is marked for deletion.");
KAACORE_ASSERT(
this->_is_processing == false,
"Invalid internal state of transition manager.");
this->_is_processing = true;
for (auto& [name, runner] : this->_transitions_map) {
bool finished = runner.step(node, dt);
if (node.is_marked_to_delete()) {
return;
}
if (finished) {
// if transition is finished destroy it's runner,
// use `_enqueued_updates` to not break for iteration.
this->_enqueued_updates.emplace(
this->_enqueued_updates.begin(), name, NodeTransitionHandle());
}
}
if (not this->_enqueued_updates.empty()) {
for (const auto& [name, transition] : this->_enqueued_updates) {
if (transition) {
this->_transitions_map.insert_or_assign(name, transition);
} else {
this->_transitions_map.erase(name);
}
}
this->_enqueued_updates.clear();
}
this->_is_processing = false;
}
NodeTransitionsManager::operator bool() const
{
return not(
this->_transitions_map.empty() and this->_enqueued_updates.empty());
}
} // namespace kaacore
|
Swift
|
UTF-8
| 631
| 2.609375
| 3
|
[] |
no_license
|
//
// MessageInputView.swift
// playground
//
// Created by dsxs on 2019/03/30.
// Copyright © 2019 dsxs. All rights reserved.
//
import UIKit
class MessageInputView: UIView {
@IBOutlet weak var textField: UITextField!
var onNewMessage: ((String) ->Void)? {
didSet {
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func sendMessage(_ sender: UIButton) {
guard let text = textField.text, !text.isEmpty else {
return
}
textField.text = nil
onNewMessage?(text)
}
}
|
PHP
|
UTF-8
| 486
| 2.71875
| 3
|
[
"0BSD",
"BSD-3-Clause"
] |
permissive
|
<?php
declare(strict_types=1);
namespace App\Comment\Application\Command;
use App\Shared\Application\Command\AbstractCommand;
final class DeleteCommentCommand extends AbstractCommand
{
private int $commentId;
public function __construct(int $commentId, int $userId, int $occurredOn)
{
parent::__construct($userId, $occurredOn);
$this->commentId = $commentId;
}
public function getCommentId(): int
{
return $this->commentId;
}
}
|
TypeScript
|
UTF-8
| 2,467
| 2.921875
| 3
|
[] |
no_license
|
import { getOptions, getTextures } from './level-mapping';
import levelsOriginCode from './level-config';
type optionType = {
width?: number;
height?: number;
texture: {
default: {
sx: number,
sy: number,
sWidth: number,
sHeight: number
},
[k: string]: any
}
};
function getConfig(shortName: string) {
let configList = shortName.split('-');
let textureName = configList[0];
let counts = configList[1] || 1;
return {
textureName,
counts
}
}
/**
* get texture by a shortcut name
* @param nameCoded eg: b1-10 => options: TEXTURE_NAME.background[0], counts: 10
*/
function getTextureOption(nameCode: string): {
width?: number,
height?: number,
texture: {
default: {
sx: number,
sy: number,
sWidth: number,
sHeight: number,
},
[k: string]: {
sx: number,
sy: number,
sWidth: number,
sHeight: number,
}
},
[k: string]: any
} {
let config = getConfig(nameCode);
let textures = getTextures(config.textureName[0])
let optionName = textures[config.textureName[1]];
let option = JSON.parse(JSON.stringify(getOptions(optionName)));
option.code = nameCode;
return option;
}
function shortNameToList(shortName: string): string[] {
let config = getConfig(shortName);
let list = [];
for (let i = 0; i < config.counts; i++) {
list.push(config.textureName);
}
return list;
}
function elementsCodeToOptions(elementsCode: string[][]): optionType[][] {
let elementsOptions: optionType[][] = [];
for (let r = 0; r < elementsCode.length; r++) {
const row = elementsCode[r];
elementsOptions[r] = [];
for (let c = 0; c < row.length; c++) {
elementsOptions[r][c] = getTextureOption(row[c]);
}
}
return elementsOptions
}
function getLevelCode (levelIndex: number): null | {bg: string, elements: string[][]} {
if (levelIndex >= 0 && levelIndex < levelsOriginCode.length) {
let level = levelsOriginCode[levelIndex];
let bg: string = level[0][0] as string;
let elements: string[][] = [];
for (let r = 0; r < level[1].length; r++) {
const row = level[1][r];
elements[r] = [];
for (let c = 0; c < row.length; c++) {
let condeList = shortNameToList(row[c]);
elements[r] = elements[r].concat(condeList);
}
}
return {
bg,
elements
}
}
return null;
}
export { getLevelCode, elementsCodeToOptions, getTextureOption};
|
JavaScript
|
UTF-8
| 241
| 2.828125
| 3
|
[] |
no_license
|
export const addImage = (image) => {
const img = document.createElement("img");
img.src = image;
img.style.width = "50%";
img.style.height = "auto";
img.style.margin = "auto";
document.querySelector("body").appendChild(img);
};
|
Java
|
UTF-8
| 681
| 2.90625
| 3
|
[] |
no_license
|
package com.zhangshixu.java.demo.designpattern.creation.factory.v1;
import com.zhangshixu.java.demo.designpattern.creation.factory.v0.Circle;
import com.zhangshixu.java.demo.designpattern.creation.factory.v0.Rectangle;
import com.zhangshixu.java.demo.designpattern.creation.factory.v0.Shape;
/**
* This is {@link Main2}.
*
* @author Zhang Shixu
* @since 0.0.1
*/
public class Main2 {
public static void main(String[] args) {
ShapeFactoryV2 shapeFactory = new ShapeFactoryV2();
Shape shape = (Circle)shapeFactory.getShape(Circle.class);
shape.draw();
shape = (Rectangle) shapeFactory.getShape(Rectangle.class);
shape.draw();
}
}
|
C#
|
UTF-8
| 5,720
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace Horsesoft.Horsify.Resource.Windows.CustomControls
{
public partial class RatingControl : Control
{
public RatingControl()
{
}
static RatingControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(RatingControl), new FrameworkPropertyMetadata(typeof(RatingControl)));
}
public int RatingValue
{
get { return (int)GetValue(RatingValueProperty); }
set { SetValue(RatingValueProperty, value); }
}
public static readonly DependencyProperty RatingValueProperty =
DependencyProperty.Register("RatingValue", typeof(int), typeof(RatingControl), new FrameworkPropertyMetadata()
{
BindsTwoWayByDefault = true
});
public double StarWidth
{
get { return (double)GetValue(StarWidthProperty); }
set { SetValue(StarWidthProperty, value); }
}
// Using a DependencyProperty as the backing store for StarWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StarWidthProperty =
DependencyProperty.Register("StarWidth", typeof(double), typeof(RatingControl), new PropertyMetadata(90.0));
public double StarRotation
{
get { return (double)GetValue(StarRotationProperty); }
set { SetValue(StarRotationProperty, value); }
}
// Using a DependencyProperty as the backing store for StarWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StarRotationProperty =
DependencyProperty.Register("StarRotation", typeof(double), typeof(RatingControl), new PropertyMetadata(0.0));
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />
/// </summary>
/// <remarks>
/// Finds the buttons inside the template and assigns handlers to set the rating
/// </remarks>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
//Return if this rating is null
//TODO: Create PArt_Rating1 etc in template.
ToggleButton rating1 = GetTemplateChild("rating1") as ToggleButton;
Button clearrating = GetTemplateChild("clearrating") as Button;
if (rating1 == null || clearrating == null) return;
ToggleButton rating2 = GetTemplateChild("rating2") as ToggleButton;
ToggleButton rating3 = GetTemplateChild("rating3") as ToggleButton;
ToggleButton rating4 = GetTemplateChild("rating4") as ToggleButton;
ToggleButton rating5 = GetTemplateChild("rating5") as ToggleButton;
clearrating.Click += (s, e) => { RatingIconClicked(0, e); };
rating1.Click += (s, e) => { RatingIconClicked(1, e); };
rating2.Click += (s, e) => { RatingIconClicked(64, e); };
rating3.Click += (s, e) => { RatingIconClicked(128, e); };
rating4.Click += (s, e) => { RatingIconClicked(196, e); };
rating5.Click += (s, e) => { RatingIconClicked(255, e); };
}
private void RatingIconClicked(byte btnIndex, RoutedEventArgs e)
{
if (RatingValue != btnIndex)
SetValue(RatingValueProperty, (int)btnIndex);
else
SetValue(RatingValueProperty, (int)RatingValue);
}
}
public class RatingRangeControl : RatingControl
{
public RatingRangeControl()
{
}
static RatingRangeControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(RatingRangeControl), new FrameworkPropertyMetadata(typeof(RatingRangeControl)));
}
public int RangeLower
{
get { return (int)GetValue(RangeLowerProperty); }
set { SetValue(RangeLowerProperty, value); }
}
// Using a DependencyProperty as the backing store for RangeLower. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RangeLowerProperty =
DependencyProperty.Register("RangeLower", typeof(int), typeof(RatingRangeControl), new FrameworkPropertyMetadata() {
DefaultValue = 1,
BindsTwoWayByDefault = true
});
public int RangeUpper
{
get { return (int)GetValue(RangeUpperProperty); }
set { SetValue(RangeUpperProperty, value); }
}
// Using a DependencyProperty as the backing store for RangeUpper. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RangeUpperProperty =
DependencyProperty.Register("RangeUpper", typeof(int), typeof(RatingRangeControl), new FrameworkPropertyMetadata()
{
DefaultValue = 1,
BindsTwoWayByDefault = true
});
public bool Enabled
{
get { return (bool)GetValue(EnabledProperty); }
set { SetValue(EnabledProperty, value); }
}
// Using a DependencyProperty as the backing store for Enabled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.Register("Enabled", typeof(bool), typeof(RatingRangeControl), new PropertyMetadata(true));
}
}
|
Markdown
|
UTF-8
| 986
| 2.984375
| 3
|
[] |
no_license
|
Nicholas Vrontakis, Patrick Kwong, and Cas Donoghue
# CS325-400 Group 31 Project 2 README
## Running the Program
1. Put the makeChange.py program file in the same directory as your input file.
2. Run makeChange.py on the command line with your specific [input filename].txt
```
python makeChange.py Amount.txt
```
3. The program will write the results to a file named: [input filename]change.txt
NOTE: The Algorithm changeslow is very slow. We recommend using amount values 40 and lower. For example with coin demonations of 1, 5, 10, 25, 50, it took about 75 seconds to make change for amount of 65.
## Input File Format
NOTE: The input file has to be in the following format. The Amount.txt file has been included as an example. It contains sample values from the example and the Testing for correctness section. The algorithms were tested and all the algorithms returned the correct output.
```
[array of coin values separated by a comma and a space]
amount of change to make
```
|
Java
|
UTF-8
| 768
| 3.671875
| 4
|
[] |
no_license
|
interface VehicleDispInfo{
void vehicleDisplay();
}
class Vehicle implements VehicleDispInfo{
public void vehicleDisplay(){
final String regNo = "TN04102021";
final String vehicleNo = "TN-21-2108";
String vehicleType = "2 Tyre";
System.out.println("Vehicle Registration Number is "+regNo+"\n");
System.out.println("The Vehicle Number is "+vehicleNo+"\n");
System.out.println("Vehicle Type is "+vehicleType+"\n");
}
void vehiclePrice(){
double price = 75000;
System.out.println("The price of this Vehicle is "+price+"\n");
}
}
class MainClass{
public static void main(String[] args)
{
VehicleDispInfo refObj = new Vehicle();
refObj.vehicleDisplay();
Vehicle obj = new Vehicle();
obj.vehiclePrice();
}
}
|
Python
|
UTF-8
| 2,069
| 2.6875
| 3
|
[] |
no_license
|
import threading
from datetime import datetime
from django.core.cache import cache
import time
class CacheLock:
def __init__(self, key, default=[], timeout=5):
t = datetime.now().strftime('%s')
thread_id = threading.current_thread().ident
sign = "{}_{}".format(t, thread_id)
self.sign = sign
self.key = key
self.lock_name = "__{}__lock".format(key)
self.timeout = timeout
self.default = default
def __enter__(self):
while True:
if not cache.get(self.lock_name, None):
if cache.get_or_set(self.lock_name, self.sign, self.timeout) == self.sign:
return cache.get(self.key) or self.default
time.sleep(0.01)
def __exit__(self, type, value, traceback):
cache.delete(self.lock_name)
class PullQueue:
@staticmethod
def push(topic_key, value, unique=False):
with CacheLock(topic_key) as v:
if not(unique and value in v):
v.append(value)
cache.set(topic_key, v)
@staticmethod
def push_multi(topic_key, values, unique=False):
with CacheLock(topic_key) as v:
for value in values:
if not(unique and values in v):
v.append(value)
cache.set(topic_key, v)
@staticmethod
def pull(topic_key):
with CacheLock(topic_key) as v:
s, v = v[:1], v[1:]
cache.set(topic_key, v)
return s[0]
@staticmethod
def pull_multi(topic_key, length=-1):
with CacheLock(topic_key) as v:
if length != -1:
s, v = v[:length], v[length:]
else:
s, v = v, []
cache.set(topic_key, v)
return s
@staticmethod
def get_len(topic_key):
return len(cache.get(topic_key, []))
@staticmethod
def read(topic_key, length=-1):
if length != -1:
return cache.get(topic_key, [])
else:
return cache.get(topic_key, [])[:length]
|
Markdown
|
UTF-8
| 807
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Tensorflow.js Regression
An online canvas where we can interactively work with different types of Regression and two different types of Optimizer is along with it. <br>
Types of regression: <br>
1. Linear Regression
https://en.wikipedia.org/wiki/Linear_regression
2. Binomial Regression
https://en.wikipedia.org/wiki/Binomial_regression
3. Trinomial Regression
https://en.wikipedia.org/wiki/Multinomial_logistic_regression
Optimizer types:
1. Stochaistic Gradient Decent (SGD)
http://ruder.io/optimizing-gradient-descent/index.html#stochasticgradientdescent
2. ADAM Optimizer
https://machinelearningmastery.com/adam-optimization-algorithm-for-deep-learning/
For more information about Linear regression. Read this article <br>
https://towardsdatascience.com/linear-regression-detailed-view-ea73175f6e86
|
C#
|
UTF-8
| 1,904
| 3.703125
| 4
|
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleAppCodingPractice.Concepts
{
/// <summary>
/// Check that string is balanced
/// [{()}] = balanced string
/// [{)} = not balanced string
/// </summary>
class BalancedString : IStartMain
{
public void BootStrap( )
{
string inputString = "[{({()})}]";
Console.WriteLine($"Input string data: {inputString}");
var result = IsBalanced ( inputString.ToCharArray() );
Console.WriteLine($"Balanced: {result}");
inputString = "[{({(()))}]";
Console.WriteLine( $"Input string data: {inputString}" );
result = IsBalanced( inputString.ToCharArray() );
Console.WriteLine( $"Balanced: {result}" );
}
private bool IsBalanced( char[] data)
{
Stack<char> stack = new Stack<char>();
foreach(var c in data)
{
if(IsOpening(c))
{
stack.Push( c );
}
else {
if( !( stack.Count > 0 && IsMatchingClose( stack.Pop(), c ) ) )
return false;
}
}
return stack.Count == 0;
}
private bool IsOpening(char c)
{
return c == '[' || c == '{' || c == '(' ;
}
private bool IsMatchingClose( char openBracket, char closeBracket )
{
switch(openBracket)
{
case '[':
return ']' == closeBracket;
case '{':
return '}' == closeBracket;
case '(':
return ')' == closeBracket;
default:
return false;
}
}
}
}
|
Python
|
UTF-8
| 2,109
| 2.65625
| 3
|
[] |
no_license
|
from flask_restful import Resource, reqparse
from models.usuario import UserModel
from flask_jwt_extended import create_access_token, jwt_required, get_raw_jwt
from werkzeug.security import safe_str_cmp
from blacklist import BLACKLIST
attributes = reqparse.RequestParser()
attributes.add_argument('login', type=str, required=True, help="The field 'login' cannot be left in blank!")
attributes.add_argument('password', type=str, required=True, help="The field 'password' cannot be left in blank!")
class User(Resource):
def get(self, user_id):
user = UserModel.find_user(user_id)
if user:
return user.json()
return {'message': 'User not found'}, 404 # not found
@jwt_required
def delete(self, user_id):
user = UserModel.find_user(user_id)
if user:
try:
user.delete_user()
except:
return {'message': 'Internal Server Error ocurred trying to delete user'}, 500
return {'message': 'User deleted!'}
return {'message': 'User not found'}
class UserRegister(Resource):
# CREATING A USER
def post(self):
data = attributes.parse_args()
if UserModel.find_by_login(data['login']):
return {"message": "The login '{}' already exists".format(data['login'])}
user = UserModel(**data)
user.save_user()
return {'message': 'User created succesfully!'}, 201 # CREATED
class UserLogin(Resource):
@classmethod
def post(cls):
data = attributes.parse_args()
user = UserModel.find_by_login(data['login'])
if user and safe_str_cmp(user.password, data['password']):
token_access = create_access_token(identity=user.user_id)
return {'access_token': token_access}, 200
return {'message': 'The username or password is incorrect.'}, 401
class UserLogout(Resource):
@jwt_required
def post(self):
jwt_id = get_raw_jwt()['jti'] # JWT Token Identifier
BLACKLIST.add(jwt_id)
return {'message': 'Loggedout successfully'}, 200
|
Java
|
UTF-8
| 106,864
| 1.59375
| 2
|
[] |
no_license
|
/*
* Copyright 2003-2010 Tufts University Licensed under the
* Educational Community 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.osedu.org/licenses/ECL-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.
*/
// TODO: see http://publicobject.com/glazedlists/ as a possible baseline for a much
// fancier data interface -- tabular, and big, but may have enough flexibility
// to still be handy.
package tufts.vue.ds;
import tufts.vue.LWSelection;
import tufts.vue.MapViewer;
import tufts.vue.VUE;
import tufts.vue.DEBUG;
import tufts.vue.Resource;
import tufts.vue.VueResources;
import tufts.vue.LWComponent;
import tufts.vue.LWNode;
import tufts.vue.LWLink;
import tufts.vue.LWMap;
import tufts.vue.LWKey;
import tufts.vue.gui.GUI;
import tufts.vue.gui.Widget;
import tufts.Util;
import tufts.vue.VueConstants;
import java.util.List;
import java.util.*;
import java.net.URL;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.geom.Point2D;
import java.awt.geom.RectangularShape;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import com.google.common.collect.*;
/**
* UI component for browsing the Fields and Rows of a fully loaded
* Schema, providing the status of data elements releative to the
* currently active map, code for adding new nodes to the current map,
* and initiating drags of fields or rows destined for a map.
*
* @version $Revision: 1.109 $ / $Date: 2010-02-03 19:13:16 $ / $Author: mike $
* @author Scott Fraize
*/
public class DataTree extends javax.swing.JTree
implements DragGestureListener
{
private static final org.apache.log4j.Logger Log = org.apache.log4j.Logger.getLogger(DataTree.class);
protected final Schema mSchema;
private DataNode mRootNode;
protected DataNode mAllRowsNode;
private DataNode mSelectedSearchNode;
private final JLabel mNewRowsLabel = new JLabel();
private final JLabel mChangedRowsLabel = new JLabel();
private final JCheckBox mNewRowsCheckBox = new JCheckBox();
private final JCheckBox mChangedRowsCheckBox = new JCheckBox();
private final AbstractButton mUpdateButton = new JButton(VueResources.getString("dockWindow.contentPanel.sync.updateMap"));
private final AbstractButton mSendToMapButton = new JButton("Send to Map");
private final DefaultTreeModel mTreeModel;
private final static Color MEDIUM_DARK_GRAY = new Color(96, 96, 96);
private final static boolean DEBUG_LOCAL = false;
private Thread mAnnotateThread;
private static final MapListener ActiveMapListener = new MapListener();
private static final java.util.concurrent.atomic.AtomicBoolean FirstInstance = new java.util.concurrent.atomic.AtomicBoolean(true);
private static final Collection<DataTree> ActiveTrees = new java.util.concurrent.CopyOnWriteArrayList();
private static volatile DataTree ForegroundTree;
private static volatile LWMap mActiveMap;
private static volatile MapViewer mActiveViewer;
private static volatile Collection<LWComponent> ActiveMapDataNodes = Collections.EMPTY_LIST;
public static final class MapListener implements LWComponent.Listener, LWSelection.Listener {
private static boolean mDataEventWasSeen;
/** if the active map changes, we need to wake the annotation thread to re-annotate against the newly active map,
* as well as start listening for changes in the active map for running future annotation updates */
public void activeChanged(tufts.vue.ActiveEvent e, final LWMap map)
{
if (mActiveMap == map)
return;
if (mActiveMap != null)
{
mActiveMap.removeLWCListener(this);
mActiveViewer.getSelection().removeListener(this);
}
mActiveMap = map;
mActiveViewer = VUE.getActiveViewer();
if (map == null)
return;
kickOffAnnotations();
mActiveMap.addLWCListener(this);
mActiveViewer.getSelection().addListener(this);
}
public void LWCChanged(tufts.vue.LWCEvent e) {
if (mActiveMap == null) {
Log.warn("LWCEvent w/no active map: " + e);
return;
}
//if (DEBUG.ANNOTATE) Log.debug("SCANNING DATA EVENT: " + e + "; seenOne=" + mDataEventWasSeen);
// TODO: pull one copy of all the active map's descendents, once, in the AWT thread,
// before all the annotate's kick off. Will probably need to have a single active map
// listener with a list of all active data-tree's instead of each tree listening
// to the active map itself.
if (e.key == LWKey.UserActionCompleted && mDataEventWasSeen) {
// technically, don't need to check after ANY action has been completed:
// only if a data node was added/removed from the map. todo: we'll need
// a data-changed LWCEvent.
if (DEBUG.ANNOTATE) Log.debug("RUNNING ANNOTATE on: " + e);
kickOffAnnotations();
mDataEventWasSeen = false;
} else if (isDataEvent(e)) {
mDataEventWasSeen = true;
if (DEBUG.ANNOTATE) Log.debug(" FOUND DATA EVENT: " + e + "; seenOne=" + mDataEventWasSeen);
}
}
private void kickOffAnnotations() {
if (DEBUG.ANNOTATE) Log.debug("kicking off annotations for: " + Util.tags(ActiveTrees));
if (ActiveTrees.size() > 0) {
loadGlobalDataForAnnotations();
for (DataTree tree : ActiveTrees)
tree.kickAnnotate();
}
}
public void selectionChanged(LWSelection selection) {
if (selection.isEmpty())
{
if (ActiveTrees.size() > 0) {
for (DataTree tree : ActiveTrees)
tree.setSelectionPath(null);
}
}
}
}
// note: this should be called from the AWT thread as it's going to access the main map model
private static void loadGlobalDataForAnnotations()
{
if (mActiveMap == null)
{
mActiveMap = VUE.getActiveMap();
mActiveViewer = VUE.getActiveViewer();
}
if (DEBUG.Enabled) Log.debug("loading global annotation data from map " + mActiveMap);
if (mActiveMap != null) {
final Collection<LWComponent> allNodes = mActiveMap.getAllDescendents();
final Collection<LWComponent> dataNodes = new ArrayList(allNodes.size());
for (LWComponent c : allNodes) {
if (c.isDataNode() && c instanceof LWNode) // leave out data-links for now
dataNodes.add(c);
}
ActiveMapDataNodes = dataNodes;
} else {
ActiveMapDataNodes = Collections.EMPTY_LIST;
}
}
private static boolean isDataEvent(tufts.vue.LWCEvent e) {
// we need to check for any childrenAdded/childrenRemoved right now, just in case ANY of them were data nodes
return e.key == LWKey.DataUpdate
|| e.key == LWKey.HierarchyChanging
|| e.key == LWKey.Created;
}
// note: this is usually NOT called from the AWT thread -- is called from a data-source load thread
public static JComponent create(Schema schema) {
final DataTree tree = new DataTree(schema);
//tree.setBorder(new LineBorder(Color.red, 4));
try {
tree.restoreAnyExpandedState();
} catch (Throwable t) {
Log.warn(t); // an assistave measure only -- non fatal
}
GUI.invokeOnEDT(new Runnable() { public void run() {
if (FirstInstance.getAndSet(false)) {
if (DEBUG.ANNOTATE) Log.debug("FIRST RUN");
// Listen for changes to the ActiveMap
VUE.addActiveListener(LWMap.class, ActiveMapListener);
// Simulate an active-map changed event to make sure we're listening to the active map.
ActiveMapListener.activeChanged(null, VUE.getActiveMap());
// ensure the global data is loaded 1st time from the ActiveMap
loadGlobalDataForAnnotations();
}
tree.kickAnnotate();
ActiveTrees.add(tree); // make sure to do this last -- activeChanged above will kick all 1st time
}});
return buildControllerUI(tree);
}
private void sendSelectedToMap() {
sendToMap(getSelectedNode(), mActiveMap);
}
private void addMissingRowsToMap() {
// failsafe: tho the Schema and our tree nodes should already
// be updated, make absolutely certian we're current to the
// active map by running adding new rows based on our detection
// of the rows already in the map.
VUE.activateWaitCursor();
try {
annotateForMap(mActiveMap);
addMissingRowsToMap(mActiveMap);
} catch (Throwable t) {
Log.warn("addMissingRowsToMap", t);
} finally {
VUE.clearWaitCursor();
}
}
private void applyChangesToMap() {
// failsafe: tho the Schema and our tree nodes should already
// be updated, make absolutely certian we're current to the
// active map by running adding new rows based on our detection
// of the rows already in the map.
VUE.activateWaitCursor();
try {
annotateForMap(mActiveMap);
applyDataUpdatesToMap(mActiveMap);
} catch (Throwable t) {
Log.warn("applyChangesToMap", t);
} finally {
VUE.clearWaitCursor();
}
}
private void updateMap() {
// failsafe: tho the Schema and our tree nodes should already
// be updated, make absolutely certian we're current to the
// active map by running adding new rows based on our detection
// of the rows already in the map.
VUE.activateWaitCursor();
try {
annotateForMap(mActiveMap);
if (mNewRowsCheckBox.isSelected()) {
addMissingRowsToMap(mActiveMap);
final LWSelection newNodes = VUE.getSelection().clone();
if (mSchema.isMatrixDataSet)
{
GUI.invokeAfterAWT(new Runnable() { public void run() {
applyMatrixRelations(newNodes);
}});
}
}
if (mChangedRowsCheckBox.isSelected()) {
applyDataUpdatesToMap(mActiveMap);
final LWSelection newNodes = VUE.getSelection().clone();
if (newNodes != null) {
VUE.getSelection().add(newNodes);
}
if (mSchema.isMatrixDataSet)
GUI.invokeAfterAWT(new Runnable() { public void run() {
applyMatrixRelations(newNodes);
}});
}
} catch (Throwable t) {
Log.warn("updateMap", t);
} finally {
VUE.clearWaitCursor();
}
}
int call =0;
public synchronized void applyMatrixRelations(List<LWComponent> newNodes)
{
//System.out.println("APPLY MATRIX RELATIONS : " + call++);
List<MatrixRelationship> relations = mSchema.matrixRelations;
//for (MatrixRelationship relation: relations)
// System.out.println("Relations : " + relation.getFromLabel() + ", " + relation.getToLabel());
for (LWComponent newNode: newNodes)
{
String trueName = newNode.getRawData().getString(Schema.MATRIX_NAME_FIELD);
for (MatrixRelationship relation: relations)
{
if (relation.getFromLabel().equals(trueName) || relation.getToLabel().equals(trueName))
{
for (DataNode n : mAllRowsNode.getChildren()) {
RowNode rn = (RowNode)n;
if (rn.isMapPresent()) {
String potentialTargetName = rn.getRow().getValue(Schema.MATRIX_NAME_FIELD);
if (potentialTargetName.equals(relation.getToLabel()) || potentialTargetName.equals(relation.getFromLabel()))
{
//System.out.println("Relation : " + relation.getFromLabel() + "," + relation.getToLabel());
//try to find a place to draw it.
final Collection<LWComponent> searchSet = VUE.getActiveViewer().getMap().getAllDescendents(LWComponent.ChildKind.EDITABLE);
final Criteria criteria = dataNodeToSearchCriteria(rn);
SmartSearch currentSearch = new SmartSearch();
currentSearch.addCriteria(criteria);
List<LWComponent> hits = currentSearch.search(searchSet);
for (LWComponent hit: hits)
{
LWLink link = null;
LWLink link2 = null;
if (newNode.getLabel().equals(hit.getLabel()))
continue;
if (relation.getFromLabel().equals(trueName) && !newNode.hasDirectedLinkTo(hit))
link = new LWLink(newNode,hit);
if (relation.getToLabel().equals(trueName) && !hit.hasDirectedLinkTo(newNode))
link2 = new LWLink(hit,newNode);
LWSelection sel = VUE.getSelection();
VUE.getSelection().clear();
if (link !=null)
{
link.setLabel(relation.getRelationLabel());
link.setAsDataLink(relation.getRelationLabel());
VUE.getActiveViewer().getMap().add(link);
VUE.getSelection().add(link);
//System.out.println("Add Link 1 : " + link.toString() + " :: " + call + " :: " + newNode.toString() + " ::: " + hit.toString());
}
if (link2 !=null)
{
link2.setLabel(relation.getRelationLabel());
link2.setAsDataLink(relation.getRelationLabel());
VUE.getActiveViewer().getMap().add(link2);
VUE.getSelection().add(link2);
//System.out.println("Add Link 2 : " + link2.toString() + " :: " + call + " :: " + newNode.toString() + " ::: " + hit.toString());
}
if (hit.hasMultipleLinksTo(newNode) && VUE.getSelection().size() >0)
tufts.vue.Actions.LinkMakeQuadCurved.act();
}
}
}
} // for each data node
}
}
}
}
private void enableUpdateButton() {
mUpdateButton.setEnabled((mNewRowsCheckBox.isEnabled() && mNewRowsCheckBox.isSelected()) ||
(mChangedRowsCheckBox.isEnabled() && mChangedRowsCheckBox.isSelected()));
}
/*
* This will find all nodes on the map where fresher/newer data is in the given
* data-set and update those nodes with the new data. When done, it will leave the
* selection set to all nodes that have been updated with new data.
*/
private void applyDataUpdatesToMap(final LWMap map)
{
final Map<String,DataRow> freshData = new HashMap();
final Field keyField = mSchema.getKeyField();
final String keyFieldName = keyField.getName();
for (DataNode n : mAllRowsNode.getChildren()) {
final DataRow row = n.getRow();
if (row.isContextChanged()) {
//Log.debug("Context changed: " + Util.tag(row));
String keyValue = row.getValue(keyField);
freshData.put(keyValue, row);
}
}
if (DEBUG.Enabled) Log.debug("Found " + freshData.size() + " data rows with newer data for map");
final Collection<LWComponent> nodes = map.getAllDescendents();
final Collection<LWComponent> patched = new ArrayList();
for (LWComponent c : nodes) {
if (c.isDataRow(mSchema)) {
DataRow newRow = freshData.get(c.getDataValue(keyFieldName));
if (newRow != null) {
//Log.debug("patching " + c);
c.setDataMap(newRow.getData());
patched.add(c);
}
}
}
if (DEBUG.Enabled) Log.debug("Updated " + patched.size() + " nodes with fresh data");
// Note: kicking the annotation may no longer be required, as we also listen for
// changes to the map to kick annotations, but that code isn't as smart as it
// could be (though actually, it generally does overkill -- annotation happens
// more often than it need be).
kickAnnotate();
VUE.getSelection().setTo(patched);
map.getUndoManager().mark(String.format("Update %d Data Nodes", patched.size()));
}
private static JComponent buildControllerUI(final DataTree tree)
{
final Schema schema = tree.mSchema;
final JPanel wrap = new JPanel(new BorderLayout()) {
@Override public void firePropertyChange(String property, boolean oldVal, boolean newVal) {
if (tufts.vue.gui.GUI.FINALIZE.equals(property)) {
if (DEBUG.Enabled) Log.debug("firePropertyChange: " + property);
tree.destroy();
} else {
super.firePropertyChange(property, oldVal, newVal);
}
}
};
tree.mUpdateButton.setOpaque(false);
tree.mSendToMapButton.setOpaque(false);
tree.mUpdateButton.setFont(tufts.vue.gui.GUI.LabelFace);
tree.mSendToMapButton.setFont(tufts.vue.gui.GUI.LabelFace);
tree.mNewRowsCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.enableUpdateButton();
}
});
tree.mChangedRowsCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.enableUpdateButton();
}
});
tree.mUpdateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.updateMap();
}
});
tree.mSendToMapButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.sendSelectedToMap();
}
});
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.setBorder(GUI.makeSpace(3,0,0,0));
JLabel dataSourceLabel = null;
String imagePath = schema.getSingletonValue("rss.channel.image.url");
if (imagePath == null)
imagePath = schema.getSingletonValue("rdf:RDF.image.url");
if (imagePath != null) {
URL imageURL = Resource.makeURL(imagePath);
if (imageURL != null) {
dataSourceLabel = new JLabel(new ImageIcon(imageURL));
dataSourceLabel.setBorder(GUI.makeSpace(2,2,1,0));
}
//addNew.setIcon(new ImageIcon(imageURL));
//addNew.setLabel(imageURL);
}
// JComboBox keyBox = new JComboBox(schema.getPossibleKeyFieldNames());
// keyBox.setOpaque(false);
// keyBox.setSelectedItem(schema.getKeyField().getName());
// keyBox.addItemListener(new ItemListener() {
// public void itemStateChanged(ItemEvent e) {
// if (e.getStateChange() == ItemEvent.SELECTED) {
// String newKey = (String) e.getItem();
// //Log.debug("KEY FIELD SELECTED: " + newKey);
// schema.setKeyField(newKey);
// tree.refreshRoot();
// }
// }
// });
// toolbar.add(keyBox, BorderLayout.WEST);
// toolbar.add(addNew, BorderLayout.EAST);
final int GUTTER = 4;
JPanel toolbar = new JPanel(),
remainderPanel = new JPanel(),
newRowsPanel = new JPanel(),
changedRowsPanel = new JPanel();
Insets noInset = new Insets(0, 0, 0, 0), //top, left, bottom, right
panelInset = new Insets(0, 0, 0, GUTTER),
buttonInset = new Insets(0, 0, GUTTER, GUTTER);
GridBagConstraints gbcCheckBox = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, noInset, 0, 0),
gbcTextArea = new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, noInset, 0, 0),
gbcPanel = new GridBagConstraints(0, 0, 3, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, panelInset, 0, 0),
gbcRemainder = new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.REMAINDER, buttonInset, 0, 0),
gbcButton = new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, buttonInset, 0, 0);
int checkBoxHeight = tree.mNewRowsCheckBox.getPreferredSize().height;
toolbar.setLayout(new GridBagLayout());
newRowsPanel.setLayout(new GridBagLayout());
changedRowsPanel.setLayout(new GridBagLayout());
tree.mNewRowsLabel.setFont(tufts.vue.gui.GUI.LabelFace);
tree.mNewRowsLabel.setOpaque(false);
newRowsPanel.add(tree.mNewRowsCheckBox, gbcCheckBox);
newRowsPanel.add(tree.mNewRowsLabel, gbcTextArea);
toolbar.add(newRowsPanel, gbcPanel);
gbcPanel.gridy = 1;
tree.mChangedRowsLabel.setFont(tufts.vue.gui.GUI.LabelFace);
tree.mChangedRowsLabel.setOpaque(false);
changedRowsPanel.add(tree.mChangedRowsCheckBox, gbcCheckBox);
changedRowsPanel.add(tree.mChangedRowsLabel, gbcTextArea);
toolbar.add(changedRowsPanel, gbcPanel);
toolbar.add(remainderPanel, gbcRemainder);
toolbar.add(tree.mUpdateButton, gbcButton);
if (DEBUG_LOCAL) {
toolbar.setOpaque(true);
toolbar.setBackground(Color.CYAN);
newRowsPanel.setOpaque(true);
newRowsPanel.setBackground(Color.CYAN);
changedRowsPanel.setOpaque(true);
changedRowsPanel.setBackground(Color.CYAN);
remainderPanel.setOpaque(true);
remainderPanel.setBackground(Color.YELLOW);
tree.mNewRowsCheckBox.setOpaque(true);
tree.mNewRowsCheckBox.setBackground(Color.YELLOW);
tree.mNewRowsLabel.setOpaque(true);
tree.mNewRowsLabel.setBackground(Color.YELLOW);
tree.mChangedRowsCheckBox.setOpaque(true);
tree.mChangedRowsCheckBox.setBackground(Color.YELLOW);
tree.mChangedRowsLabel.setOpaque(true);
tree.mChangedRowsLabel.setBackground(Color.YELLOW);
tree.mUpdateButton.setOpaque(true);
tree.mUpdateButton.setBackground(Color.YELLOW);
}
if (dataSourceLabel != null)
wrap.add(dataSourceLabel, BorderLayout.SOUTH);
// if (dataSourceLabel == null) {
// // dataSourceLabel = new JLabel(schema.getName());
// // dataSourceLabel.setFont(tufts.vue.VueConstants.SmallFont);
// // dataSourceLabel.setBorder(GUI.makeSpace(0,2,0,0));
// // toolbar.add(dataSourceLabel, BorderLayout.WEST);
// // toolbar.add(addNew, BorderLayout.EAST);
// toolbar.add(addNew, BorderLayout.CENTER);
// } else {
// toolbar.add(dataSourceLabel, BorderLayout.WEST);
// toolbar.add(addNew, BorderLayout.EAST);
// }
toolbar.setBorder(new MatteBorder(0,0,1,0, Color.gray));
wrap.add(toolbar, BorderLayout.NORTH);
// todo: if save entire schema with map, include date of creation (last refresh before save)
wrap.add(tree, BorderLayout.CENTER);
return wrap;
}
@Override
protected void setExpandedState(final TreePath path, final boolean expanded) {
final DataNode treeNode = path == null ? null : (DataNode) path.getLastPathComponent();
if (DEBUG.Enabled) Log.debug("setExpandedState " + path + " = " + expanded + "; " + Util.tags(treeNode));
// we can interrupt tree expansion here on our double-clicks for searches
// (which may obviate part of the workaround we needed with the ClearSearchMouseListener,
// tho not for the JScrollPane problem if that is really happening)
if (treeNode != null && treeNode.isField()) {
// we record the expanded state in the visibility bit of the style node
// so we can restore it later from the skeletal Schema's saved with maps
treeNode.getField().getStyleNode().setVisible(expanded);
}
GUI.invokeAfterAWT(new Runnable() { public void run() {
if (!inDoubleClick) {
if (DEBUG.FOCUS) Log.debug("setExpandedState " + path + " = " + expanded + " RELAYING");
DataTree.super.setExpandedState(path, expanded);
} else
if (DEBUG.FOCUS) Log.debug("setExpandedState " + path + " = " + expanded + " SKIPPING");
inDoubleClick = false;
}});
}
private boolean inDoubleClick;
private class ClickHandler extends tufts.vue.MouseAdapter
{
private TreePath mClickPath;
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
mClickPath = getPathForLocation(e.getX(), e.getY());
if (DEBUG.Enabled) {
//Log.debug("MOUSE PRESSED ON " + Util.tags(mClickPath));
if (mClickPath != null)
Log.debug("MOUSE PRESSED ON: " + Util.tags(mClickPath.getLastPathComponent()));
else
Log.debug("MOUSE PRESSED ON: nothing");
}
// it's possible that the node under the mouse changes from the time of the
// first press, to the time mouseClicked is called (e.g., due to tree
// expansion and/or possible scrolling of the entire tree component), so we
// capture it here. Could make this a class a generic subclassable helper
// class for JTree's.
inDoubleClick = GUI.isDoubleClick(e);
if (DEBUG.Enabled) Log.debug("IN DOUBLE CLICK = " + inDoubleClick);
}
@Override
public void mouseClicked(java.awt.event.MouseEvent e)
{
if (mClickPath == null)
return;
final DataNode treeNode = (DataNode) mClickPath.getLastPathComponent();
// TODO: below selectMatchingNodes is often a repeat run after the one trigger in TreeSelectionListener.valueChanged
// if (GUI.isSingleClick(e)) {
// if (mSelectedSearchNode == treeNode) {
// // re-run search: we're clicking on already selected, and can't select it again
// selectMatchingNodes(treeNode, false);
// }
// return;
// }
if (!GUI.isDoubleClick(e))
return;
if (DEBUG.Enabled) Log.debug("ACTIONABLE DOUBLE CLICK ON " + Util.tags(treeNode));
// if (treeNode.hasStyle()) {
// final tufts.vue.LWSelection selection = VUE.getSelection();
// selection.setSource(DataTree.this);
// // prevents from ever drawing through on map:
// selection.setSelectionSourceFocal(null);
// selection.setTo(treeNode.getStyle());
// } else
if (treeNode.isRow() ||
(treeNode.getField() != null && treeNode.getField().isPossibleKeyField())) {
selectMatchingNodes(treeNode, false);
}
}
}
private void selectMatchingNodes(final DataNode treeNode, final boolean extendSearch)
{
if (mActiveMap == null)
return;
// we search only amongst EDITBALE nodes, so that we ignore hidden/locked layers & nodes, etc
final Collection<LWComponent> searchSet = mActiveMap.getAllDescendents(LWComponent.ChildKind.EDITABLE);
if (DEBUG.Enabled) Log.debug("SEARCH:\n\nSEARCHING ALL EDITABLE DESCENDENTS of " + mActiveMap
+ "; count=" + searchSet.size()
+ "; treeNode=" + Util.tags(treeNode));
//,new Throwable("HERE"));
findAndSelectMatchingNodes(searchSet, treeNode, extendSearch);
}
private SmartSearch mCurrentSearch;
private Criteria mLastCriteria;
/**
* Note: This method also has the side effect of picking an active style record for
* the selection if the DataNode represents a Field (the style for all enumerated
* values on the map from that Field), as well as setting a description in the
* selection of the search that produced it.
*/
private void findAndSelectMatchingNodes(final Collection<LWComponent> searchSet,
final DataNode treeNode,
final boolean extendSearch)
{
Field field = treeNode.getField();
LWComponent styleRecord = null;
if (field == null) {
if (treeNode == mAllRowsNode || treeNode instanceof RowNode) {
field = mSchema.getKeyField();
if (treeNode == mAllRowsNode)
styleRecord = mSchema.getRowNodeStyle();
} else {
// todo: must be root node: select a row-node items
return;
}
}
if (extendSearch) {
// only use the style record for single criteria searches; otherwise
// makes no sense -- can't hang a style off a search, only single Fields
styleRecord = null;
} else {
if (treeNode.isField() && styleRecord == null)
styleRecord = field.getStyleNode();
}
final String fieldName = field.getName();
final Criteria criteria = dataNodeToSearchCriteria(treeNode);
final List<LWComponent> hits;
String desc;
if (extendSearch) {
if (mCurrentSearch == null) {
mCurrentSearch = new SmartSearch();
mCurrentSearch.addCriteria(mLastCriteria);
mLastCriteria = null;
}
mCurrentSearch.addCriteria(criteria);
Log.debug("Running search " + mCurrentSearch);
hits = mCurrentSearch.search(searchSet);
desc = mCurrentSearch.toString();
} else {
// if we've got a single Criteria, no need to mess with a SmartSearch
mCurrentSearch = null;
hits = new ArrayList();
Log.debug("SEARCHING WITH CRITERIA " + criteria);
for (LWComponent c : searchSet)
if (criteria.matches(c))
hits.add(c);
mLastCriteria = criteria;
desc = criteria.description();
}
desc = "matching<br>" + desc;
if (DEBUG.Enabled) {
if (hits.size() == 1)
Log.debug("hits=" + hits.get(0) + " [single hit]");
else
Log.debug("hits=" + hits.size());
Log.debug("styleRecord: " + styleRecord);
//if (styleRecord != null) desc += "<p>style: " + styleRecord;
}
final tufts.vue.LWSelection selection = VUE.getSelection();
// make sure selection bounds are drawn in MapViewer:
selection.setSelectionSourceFocal(VUE.getActiveFocal());
// now set the selection, along with a description
selection.setWithStyle(hits, desc, styleRecord);
}
public Criteria dataNodeToSearchCriteria(final DataNode treeNode) {
final Field field = treeNode.getField();
final String fieldName = field == null ? null : field.getName();
Criteria criteria = null;
if (treeNode == mAllRowsNode) {
// search for ANY row-node in the schema
if (DEBUG.Enabled) Log.debug("searching for all data records in schema " + mSchema);
criteria = new SchemaMatch(mSchema);
}
else if (treeNode.isRow()) {
// search for a particular row-node in the schema based on the key field -- this will
// normally only find a single node on the map, unless there are duplicate nodes on
// the map referencing the same row
final String keyField = ((RowNode)treeNode).getSchema().getKeyFieldName();
final String keyValue = treeNode.getRow().getValue(keyField);
criteria = new ValueMatch(keyField, keyValue);
}
else if (treeNode.isField()) {
// search for all nodes anchoring a particular value for the given Field
if (DEBUG.Enabled) Log.debug("searching for any enumerated value from a field named " + fieldName);
criteria = new FieldMatch(field);
//criteria = new KeyMatch(fieldName);
}
else if (treeNode.isValue()) {
// search for a particular key=value
final String fieldValue = treeNode.getValue();
if (DEBUG.Enabled) Log.debug(String.format("searching for %s=[%s]", fieldName, fieldValue));
criteria = new ValueMatch(fieldName, fieldValue);
}
return criteria;
}
// todo: better to move all this Search stuff to a DataSearch.java or some such.
public abstract static class Criteria {
boolean matches(LWComponent c) {
throw new UnsupportedOperationException("unimplemented matches in " + this);
}
abstract String description();
String getKey() { return null; }
public List<LWComponent> search(final Collection<LWComponent> searchSet) {
final List<LWComponent> hits = new ArrayList();
for (LWComponent c : searchSet)
if (matches(c))
hits.add(c);
return hits;
}
@Override public String toString() {
return String.format("%s[%s]", getClass().getSimpleName(), description());
}
}
public static final class SchemaMatch extends Criteria {
final Schema schema;
public SchemaMatch(Schema s) {
schema = s;
}
@Override public boolean matches(LWComponent c) {
return c.isDataRow(schema);
}
@Override public String description() {
return String.format("in data set: <i>%s</i>", schema.getName());
}
}
public static final class FieldMatch extends Criteria {
final Field field;
public FieldMatch(Field f) {
field = f;
}
@Override public boolean matches(LWComponent c) {
return c.isDataValueNode(field);
}
@Override public String description() {
return String.format("enumerated values of: <b>%s</b>", field);
}
//@Override String getKey() { return key; }
@Override public String toString() {
return String.format("enumerated values of <i>%s</i>", field);
}
}
public static final class KeyMatch extends Criteria {
final String key;
public KeyMatch(String fieldName) {
key = fieldName;
}
@Override public boolean matches(LWComponent c) {
return c.isDataValueNode(key);
}
@Override public String description() {
return String.format("any enumerated values of: <b>%s</b>", key);
}
//@Override String getKey() { return key; }
@Override public String toString() {
return String.format("any enumerated values of <i>%s</i>", key);
}
}
public static final class ValueMatch extends Criteria {
final String key;
final String value;
public ValueMatch(String k, String v) {
key = k;
value = v;
}
@Override public boolean matches(LWComponent c) {
return c.hasDataValue(key, value);
}
@Override public String description() {
return String.format("<b>%s: <i>%s</i>", key, valueText(value));
}
@Override String getKey() { return key; }
@Override public String toString() {
return String.format("%s=%s", key, value);
}
}
/**
* A multiple criteria search that is automagically smart about how to create boolean
* AND and OR groups to create reasonable searches.
*/
public static final class SmartSearch /*extends Crtieria*/ {
/** a boolean AND group of OR lists for each key used in any key=value searches present */
final Multimap<String,Criteria> criteriaByKey = Multimaps.newHashMultimap();
/** a special OR group that takes priority: anything matching criteria in this group
* is "hit" no matter what */
final Collection<Criteria> globalBooleanOr = new ArrayList();
public void addCriteria(Criteria criteria) {
if (DEBUG.Enabled) Log.debug("SmartSearch adding " + criteria);
if (criteria == null)
return;
final String key = criteria.getKey();
if (key != null) {
criteriaByKey.put(key, criteria);
} else {
// note: this impl means any search containing a SchemaMatch will match ALL
// rows in the schema, and it will only be meaninful to add Fields to
// the search (not values selecting particular rows, as they'll allready
// be all selected).
globalBooleanOr.add(criteria);
}
}
public List<LWComponent> search(final Collection<LWComponent> searchSet) {
final List<LWComponent> hits = new ArrayList();
if (DEBUG.Enabled) {
for (Criteria c : globalBooleanOr)
Log.debug("GlobalOR: " + c);
final Collection<Map.Entry<String,Collection<Criteria>>> allKeyEntries = criteriaByKey.asMap().entrySet();
for (Map.Entry e : allKeyEntries) {
Log.debug(String.format("Key: %-12s criteria=%s", e.getKey(), e.getValue()));
}
}
final Collection<Collection<Criteria>> keyBasedCriteria;
if (criteriaByKey.size() > 0)
keyBasedCriteria = criteriaByKey.asMap().values();
else
keyBasedCriteria = null;
if (globalBooleanOr.size() > 0) {
// search method 1: includes the global OR tests
for (LWComponent c : searchSet) {
if (anyCriteriaMatches(c, globalBooleanOr))
hits.add(c);
else if (keyBasedCriteria != null && allGroupsMatch(c, keyBasedCriteria))
hits.add(c);
}
} else if (keyBasedCriteria != null) {
// search method 2: just the AND'd group of OR tests
for (LWComponent c : searchSet) {
if (allGroupsMatch(c, keyBasedCriteria)) {
hits.add(c);
}
}
}
return hits;
}
/** perform a boolean AND of a bunch of OR groups: at least one criteria must match from each collection of criteria
* Note: if the group is empty (no collections of Criteria), this will always return TRUE */
private boolean allGroupsMatch(final LWComponent c,
final Collection<Collection<Criteria>> booleanAndGroup)
{
for (Collection<Criteria> booleanOrGroup : booleanAndGroup) {
boolean atLeastOneMatched = false;
//Log.debug(c.getUniqueComponentTypeLabel() + "; against " + booleanOrGroup);
// todo: could make this even faster by exploiting the underlying
// Multimap impl in the LWComponent MetaMap to have it pull all values
// for the key, which should be a Set, and just check for set membership
// for each of the values we're looking for under that key. Could pull
// the key to use from the first criteria in the group, or just pass in
// Map.Entry's of the keys and their collections of criteria. We'd
// abandon the matches(c) API and manually pull the value from key=value
// criteria to check the set membership.
for (Criteria criteria : booleanOrGroup) {
if (criteria.matches(c)) {
//Log.debug(c.getUniqueComponentTypeLabel() + "; ok");
atLeastOneMatched = true;
break;
}
}
if (!atLeastOneMatched) {
// nothing matched in this or group: entire search immediately fails
//Log.debug(c.getUniqueComponentTypeLabel() + " failed; no values matched in key");
return false; // immediate boolean short-circuit
}
}
return true;
}
/** perform a boolean OR for a group of criteria */
private boolean anyCriteriaMatches(final LWComponent c, final Collection<Criteria> booleanOrGroup)
{
for (Criteria criteria : booleanOrGroup) {
if (criteria.matches(c)) {
//Log.debug(criteria + " hit " + c);
return true; // immediate boolean short-circuit
}
}
return false;
}
@Override
public String toString() {
final Collection<Collection<Criteria>> groupedByKey = criteriaByKey.asMap().values();
StringBuilder b = new StringBuilder("search terms:<br>");
for (Criteria c : globalBooleanOr) {
b.append(c.description());
b.append("<br>");
}
for (Collection<Criteria> eachKey : groupedByKey) {
for (Criteria c : eachKey) {
b.append(c.description());
b.append("<br>");
}
}
return b.toString();
}
}
private void debug(String s) {
Log.debug(String.format("%s%-20s%s %s", Util.TERM_PURPLE, "[" + mSchema.getName() + "]", Util.TERM_CLEAR, s));
}
// For annotations, we create a single handler for listening to user changes to the
// current map (UseActionCompleted), that keeps background threads running for the
// annotations for each loaded DataTree. It is designed so that the annotate thread
// for the currently visible DataTree(s) runs at a higher priority, and the loaded
// but not currently displated DataTree's run at a lower priority. If a second
// update comes through before the current pass is completed, the prior update can
// be aborted.
private void kickAnnotate() {
GUI.invokeOnEDT(new Runnable() { public void run() {
mUpdateButton.setEnabled(false);
}});
if (DEBUG.THREAD) debug("WAKING-> ANNOTATION THREAD " + mAnnotateThread);
// note: if we're already on a thread that's NOT the AWT EDT, we could
// assume we're in a builder thread and instead of waking the annotation
// thread just run in the builder thread, tho better to keep all that
// done there as sometimes that can take a while to run, and this will
// allow initial tree creations to run faster.
synchronized (mAnnotateThread) {
mAnnotateThread.notify();
}
if (DEBUG.THREAD||DEBUG.ANNOTATE) debug("NOTIFIED ANNOTATION THREAD " + mAnnotateThread);
}
// TODO: add another kind of annotation pass that runs after a search, and greys out enumerated
// values that have dropped out of the search set. (?)
/** @return true if interrupted */
private boolean annotateForMap() {
return annotateForMap(mActiveMap);
}
/** @return true if interrupted */
private boolean annotateForMap(final LWMap map)
{
if (DEBUG.THREAD || DEBUG.SCHEMA || DEBUG.ANNOTATE) Log.debug("ANNOTATING against " + map + "; " + Util.tags(ActiveMapDataNodes));
mSchema.annotateFor(ActiveMapDataNodes);
// note: the map isn't actually needed by any of the below annotation calls
if (map != null) {
final String annot = map.getLabel();
for (DataNode n : mRootNode.getChildren()) {
if (Thread.interrupted()) return true;
n.annotate(map);
if (!n.isLeaf())
for (DataNode cn : n.getChildren()) {
if (Thread.interrupted()) return true;
cn.annotate(map);
}
}
}
int _newRowCount = 0;
int _changedRowCount = 0;
// if (mAllRowsNode.getChildren() !=null)
for (DataNode n : mAllRowsNode.getChildren()) {
if (!n.isMapPresent())
_newRowCount++;
if (n.isContextChanged())
_changedRowCount++;
}
final int newRowCount = _newRowCount;
final int changedRowCount = _changedRowCount;
if (DEBUG.THREAD || DEBUG.SCHEMA) Log.debug("annotateForMap: newRows " + newRowCount + "; changedRows " + changedRowCount);
if (Thread.interrupted()) return true;
GUI.invokeOnEDT(new Runnable() { public void run() {
String newRowsMessage = "",
changedRowsMessage = "";
newRowsMessage = (newRowCount == 0 ? VueResources.getString("dockWindow.contentPanel.sync.noNewRecords") :
(newRowCount == 1 ? VueResources.getString("dockWindow.contentPanel.sync.oneNewRecord") :
String.format(VueResources.getString("dockWindow.contentPanel.sync.manyNewRecords"), newRowCount)));
changedRowsMessage = (changedRowCount == 0 ? VueResources.getString("dockWindow.contentPanel.sync.noChangedRecords") :
(changedRowCount == 1 ? VueResources.getString("dockWindow.contentPanel.sync.oneChangedRecord") :
String.format(VueResources.getString("dockWindow.contentPanel.sync.manyChangedRecords"), changedRowCount)));
mNewRowsLabel.setText(newRowsMessage);
mNewRowsLabel.setToolTipText(newRowsMessage);
mNewRowsLabel.setForeground(newRowCount != 0 ? Color.BLACK : MEDIUM_DARK_GRAY);
mNewRowsCheckBox.setEnabled(newRowCount != 0);
mChangedRowsLabel.setText(changedRowsMessage);
mChangedRowsLabel.setToolTipText(changedRowsMessage);
mChangedRowsLabel.setForeground(changedRowCount != 0 ? Color.BLACK : MEDIUM_DARK_GRAY);
mChangedRowsCheckBox.setEnabled(changedRowCount != 0);
enableUpdateButton();
// TODO: don't bother with refresh if annotations didn't change at all
refreshAll();
}});
return false;
}
// private void refreshRoot() {
// if (DEBUG.Enabled) Log.debug("REFRESHING " + Util.tags(mRootNode));
// refreshAllChildren(mRootNode);
// }
private void refreshTopLevel() {
refreshAllChildren(mRootNode);
}
private void refreshAllStyleNodes() {
refreshTopLevel();
}
private void refreshAll()
{
//mTreeModel.reload(mRootNode);
// using nodesChanged instead of reload preserves the expanded state of nodes in the tree
if (DEBUG.THREAD) Log.debug("REFRESHING " + Util.tags(mRootNode.getChildren()));
refreshTopLevel();
for (TreeNode n : mRootNode.getChildren())
if (!n.isLeaf())
refreshAllChildren(n);
if (DEBUG.THREAD) Log.debug(" REFRESHED " + Util.tags(mRootNode.getChildren()));
// This gets close, but doesn't always handle updating NON expanded nodes, plus
// it often leaves labels truncated with "..."
// invalidate();
// super.treeDidChange();
}
private void restoreAnyExpandedState()
{
int i = 0;
for (TreeNode n : mRootNode.getChildren()) {
if (n instanceof FieldNode) {
//Log.debug("found field node " + Util.tags(n));
Field f = ((FieldNode)n).getField();
if (f != null) {
//Log.debug("found field " + f);
LWComponent style = ((FieldNode)n).getField().getStyleNode();
if (style != null && style.isVisible()) {
final TreePath path = getPathForRow(i);
if (DEBUG.Enabled) Log.debug("EXPAND " + Util.tags(n) + " " + Util.tags(path));
GUI.invokeOnEDT(new Runnable() { public void run() {
DataTree.super.setExpandedState(path, true);
}});
}
}
}
i++;
}
}
private void refreshAllChildren(TreeNode node)
{
final int[] childIndexes = new int[node.getChildCount()];
for (int i = 0; i < childIndexes.length; i++)
childIndexes[i] = i; // why there's isn't an API to do this automatically, i don't know...
// using nodesChanged instead of mTreeModel.reload preserves the expanded state of nodes in the tree
if (DEBUG.META) Log.debug("refreshing " + childIndexes.length + " children of " + node);
mTreeModel.nodesChanged(node, childIndexes);
}
private void refreshRootNode() {
mTreeModel.nodesChanged(mRootNode, new int[] { 0 });
}
@Override
public String toString() {
return String.format("DataTree[%s]", mSchema.toString());
}
private static volatile int AnnotationThreadCount = 0;
private void destroy() {
if (DEBUG.Enabled) Log.debug("destroying w/" + mAnnotateThread);
mAnnotateThread.interrupt();
mAnnotateThread = null;
// it's crucial to flush the old schema so that if it isn't reloaded with new
// data (a new Schema instance is created when/if this schema is reloaded), the
// old schema will be empty and will no longer match to any nodes on any map.
// todo: the XmlDataSource impl current decides which happens (e.g., re-loaded
// for .csv, new instances for XML) -- if we keep the new-instance
// functionality, eventually we should actually remove the defunct schema's from
// the Schema global instance lists, instead of just leaving them in there but
// empty.
mSchema.flushData();
ActiveTrees.remove(this);
// if (mActiveMap != null)
// mActiveMap.removeLWCListener(this);
// VUE.removeActiveListener(LWMap.class, this);
}
private DataTree(final Schema schema) {
mSchema = schema;
setCellRenderer(new DataRenderer());
//setSelectionModel(null);
setModel(mTreeModel = new DefaultTreeModel(buildTree(schema), false));
final int ac = AnnotationThreadCount++;
mAnnotateThread = new Thread(String.format("Annotate%d: %-20.20s", ac, schema.getName())) {
{ setPriority(MAX_PRIORITY); }
public synchronized void run() {
while (true) {
try {
// must be careful: if we get a notify before the 1st time we go to
// sleep, we'll never wake up! So we start this thread at high
// priority, and kick it off ("start()") immediately, because as soon
// as the DataTree is done constructing, we're going to get notified
// the first time -- still theoretically risky but it appears to
// be working reliably.
if (DEBUG.THREAD || DEBUG.ANNOTATE) Log.debug("annotation thread sleeping, pri=" + getPriority());
wait();
} catch (InterruptedException e) {
Log.error("interrupted; exiting; " + schema);
return;
}
if (DataTree.this == ForegroundTree && !VUE.isApplet()) // referring to NORM_PRIORITY can fail in Applets
setPriority(NORM_PRIORITY - 1);
else
setPriority(MIN_PRIORITY);
if (DEBUG.THREAD || DEBUG.ANNOTATE) Log.debug("annotation thread woke, pri=" + getPriority() + "; running...");
final boolean interrupted = annotateForMap();
if (DEBUG.Enabled) {
if (interrupted)
Log.debug("annotation aborted");
else if (DEBUG.THREAD)
Log.debug("annotation completed");
}
}
}
};
if (DEBUG.THREAD) Log.debug("STARTING " + mAnnotateThread + "; (tree constructing)");
mAnnotateThread.start();
setRowHeight(0);
setRootVisible(false);
setShowsRootHandles(true);
java.awt.dnd.DragSource.getDefaultDragSource()
.createDefaultDragGestureRecognizer
(this,
java.awt.dnd.DnDConstants.ACTION_COPY |
java.awt.dnd.DnDConstants.ACTION_MOVE |
java.awt.dnd.DnDConstants.ACTION_LINK,
this);
addMouseListener(new ClickHandler());
addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
//final TreePath[] paths = e.getPaths();
final TreePath[] paths = getSelectionModel().getSelectionPaths();
if (DEBUG.Enabled) Log.debug("valueChanged: isAddedPath=" + e.isAddedPath() + "; PATHS:");
if (DEBUG.Enabled) Util.dump(paths);
//if (DEBUG.Enabled) Log.debug("OLD LeadPath: " + e.getOldLeadSelectionPath());
//if (DEBUG.Enabled) Log.debug("NEW LeadPath: " + e.getNewLeadSelectionPath());
// TODO: change from checking getPaths to model.getSelectionPaths & ignoring isAddedPath
// if (!e.isAddedPath() || e.getPath().getLastPathComponent() == null)
// return;
final DataNode treeNode = (DataNode) e.getPath().getLastPathComponent();
if (treeNode instanceof RowNode) {
VUE.setActive(tufts.vue.MetaMap.class,
DataTree.this,
treeNode.getRow().getData());
}
else if (treeNode instanceof ValueNode && treeNode.getField().isPossibleKeyField()) {
DataRow row = mSchema.findRow(treeNode.getField(), treeNode.getValue());
if (row!=null)
{
VUE.setActive(tufts.vue.MetaMap.class,
DataTree.this,
row.getData());
}
else
{
Log.warn("Row is NULL while trying to set active in tree selection value changed");
}
}
// else if (treeNode.hasStyle()) {
// final tufts.vue.LWSelection selection = VUE.getSelection();
// selection.setSource(DataTree.this);
// // prevents from ever drawing through on map:
// selection.setSelectionSourceFocal(null);
// selection.setTo(treeNode.getStyle());
// }
else if (paths != null) {
boolean multipleSearchTerms = false;
DataNode node = null;
for (TreePath path : paths) {
node = (DataNode) path.getLastPathComponent();
selectMatchingNodes(node, multipleSearchTerms);
multipleSearchTerms = true;
}
if (paths.length == 1)
mSelectedSearchNode = node;
else
mSelectedSearchNode = null;
} else {
if (DEBUG.Enabled) Log.warn("null search path from selection model");
}
// else if (treeNode instanceof ValueNode) {
// if (treeNode.getField().isPossibleKeyField()) {
// DataRow row = mSchema.findRow(treeNode.getField(), treeNode.getValue());
// VUE.setActive(tufts.vue.MetaMap.class,
// DataTree.this,
// row.getData());
// } else {
// selectMapForNode(treeNode, false);
// }
// }
//VUE.setActive(LWComponent.class, this, node.styleNode);
}
});
}
@Override
public void addNotify() {
ForegroundTree = this;
super.addNotify();
}
@Override
public void removeNotify() {
if (ForegroundTree == this)
ForegroundTree = null;
super.removeNotify();
}
private static String HTML(String s) {
//if (true) return s;
final StringBuilder b = new StringBuilder(s.length() + 6);
//b.append("<html>");
// we add space before and after to widen the painted background selection around the text a bit
b.append("<html> ");
b.append(s);
b.append(" ");
return b.toString();
}
private static int sortPriority(Field f) {
if (f.isSingleton())
return -4;
else if (f.isSingleValue())
return -3;
else if (f.isUntrackedValue())
return -2;
else if (f.getName().contains(":") && !f.getName().startsWith("dc:"))
return -1;
else
return 0;
}
/** build the model and return the root node */
private TreeNode buildTree(final Schema schema)
{
mAllRowsNode = new AllRowsNode(schema, this);
final DataNode root =
new DataNode("Data Set: " + schema.getName());
//new VauleNode("Data Set: " + schema.getName());
// new DataNode(null, null,
// String.format("%s [%d %s]",
// schema.getName(),
// schema.getRowCount(),
// "items"//isCSV ? "rows" : "items"));
final Field keyField = schema.getKeyField();
Field labelField = schema.getField("title");
if (labelField == null)
labelField = keyField;
for (DataRow row : schema.getRows()) {
mAllRowsNode.add(new RowNode(row, labelField));
//String label = row.getValue(labelField);
//rowNodeTemplate.add(new ValueNode(keyField, row.getValue(keyField), label));
}
root.add(mAllRowsNode);
mRootNode = root;
final Field sortedFields[] = new Field[schema.getFieldCount()];
schema.getFields().toArray(sortedFields);
Arrays.sort(sortedFields, new Comparator<Field>() {
public int compare(Field f1, Field f2) {
return sortPriority(f2) - sortPriority(f1);
}
});
final LWComponent.Listener styleRepainter = new LWComponent.Listener() {
// todo: schema style nodes are currently parentless, which means
// their property change events don't go up through the map to
// the undo-manager, making changes to them not undoable -- either
// manually relay style property change events up through the appropriate
// map, or have a way for a map to have hidden list of style children.
public void LWCChanged(tufts.vue.LWCEvent e) {
if (DEBUG.EVENTS) Log.debug("REPAINTER UPDATE ON " + e);
if (e.getKey() == LWKey.FillColor) {
DataTree.this.refreshAllStyleNodes();
}
}
};
//The current data model doesn't make sense for matrix data and so it's not going to make a ton of sense
if (!DataTree.this.mSchema.isMatrixDataSet)
for (Field field : sortedFields) {
// if (field.isSingleton())
// continue;
DataNode fieldNode = new FieldNode(field, styleRepainter, null);
root.add(fieldNode);
// if (field.uniqueValueCount() == schema.getRowCount()) {
// //Log.debug("SKIPPING " + f);
// continue;
// }
final Set values = field.getValues();
// could add all style nodes to the schema node to be put in an internal layer for
// persistance: either that or store them with the datasources, which
// probably makes more sense.
if (values.size() > 1) {
try {
buildValueChildren(field, fieldNode);
} catch (Throwable t) {
Log.error("building child values for: " + Util.tags(field) + "; " + Util.tags(fieldNode), t);
}
}
}
return root;
}
private static final boolean SORT_BY_COUNT = false;
private static final boolean SORT_BY_VALUE = !SORT_BY_COUNT;
private static void buildValueChildren(Field field, DataNode fieldNode)
{
final Multiset<String> valueCounts = field.getValueSet();
final Set<Multiset.Entry<String>> entrySet = valueCounts.entrySet();
final Iterable<Multiset.Entry<String>> valueEntries;
if (field.isQuantile() || (SORT_BY_COUNT && field.isPossibleKeyField())) {
// cases we don't need to bother sorting: (1) quantiles, which are
// pre-sorted (2) possible key fields: if sorting by counts (frequency)
// don't need to bother sorting if field is a possible key field, as all
// value counts == 1
valueEntries = entrySet;
} else {
final ArrayList<Multiset.Entry<String>> sortedValues = new ArrayList(entrySet);
Collections.sort(sortedValues, new Comparator<Multiset.Entry<String>>() {
public int compare(final Multiset.Entry<String> e1, final Multiset.Entry<String> e2) {
// always put any empty value item last, otherwise sort on frequency
if (e1.getElement() == Field.EMPTY_VALUE)
return 1;
else if (e2.getElement() == Field.EMPTY_VALUE)
return -1;
else if (SORT_BY_COUNT)
return e2.getCount() - e1.getCount();
else // SORT_BY_VALUE
return tufts.Strings.compareNaturalIgnoreCaseAscii(e1.getElement(), e2.getElement());
}
});
valueEntries = sortedValues;
}
//-----------------------------------------------------------------------------
// Add the enumerated values
//-----------------------------------------------------------------------------
for (Multiset.Entry<String> e : valueEntries) {
final String value = e.getElement();
final String display;
int nValues = e.getCount();
if (field.isQuantile() && value != Field.EMPTY_VALUE) {
// non-empty Quantile values always have an extra count,
// which was the "init" count to enforce quantile-order
// on the values list.
nValues--;
}
if (field.isPossibleKeyField()) {
display = field.valueDisplay(value);
} else {
final String countTxt = String.format("%3d", nValues).replaceAll(" ", " ");
final String color;
if (nValues <= 0)
display = String.format(HTML("<font color=#AAAAAA><code>%s</code> %s"),
countTxt,
valueText(value));
else
display = String.format(HTML("<code><font color=#888888>%s</font></code> %s"),
countTxt,
valueText(value));
}
final ValueNode valueNode = new ValueNode(field, value, display, nValues);
fieldNode.add(valueNode);
}
for (String comment : field.getDataComments()) {
fieldNode.add(new DataNode(HTML("<font color=#AAAAAA>" + comment)));
}
}
public void dragGestureRecognized(DragGestureEvent e) {
if (getSelectionPath() == null) {
Log.debug("dragGestureRecognized: no selection path; " + e);
return;
}
Log.debug("SELECTED: " + Util.tags(getSelectionPath().getLastPathComponent()));
final DataNode treeNode = (DataNode) getSelectionPath().getLastPathComponent();
//if (resource != null)
//GUI.startRecognizedDrag(e, resource, this);
//tufts.vue.gui.GUI.startRecognizedDrag(e, Resource.instance(node.value), null);
final LWComponent dragNode;
final Field field = treeNode.getField();
boolean stylesAlreadyApplied = false;
if (treeNode.isValue()) {
if (treeNode.getCount() <= 0)
dragNode = null;
else
dragNode = DataAction.makeValueNode(field, treeNode.getValue());
}
else if (treeNode.isField()) {
//if (field.isPossibleKeyField())
//return;
dragNode = new LWNode(String.format(" %d unique \n '%s' \n values ",
field.uniqueValueCount(),
field.getName()));
//dragNode.setClientData(java.awt.datatransfer.DataFlavor.stringFlavor,
//" ${" + field.getName() + "}");
}
else if (treeNode instanceof RowNode) {
final DataRow row = ((RowNode)treeNode).getRow();
final List<LWComponent> nodes = DataAction.makeSingleRowNode(treeNode.getSchema(), row);
if (DEBUG.Enabled) Log.debug("made row nodes: " + Util.tags(nodes));
if (nodes.isEmpty()) {
Log.error("no row node made from row: " + row);
dragNode = null;
} else
dragNode = nodes.get(0);
stylesAlreadyApplied = true;
}
else {
//assert treeNode instanceof TemplateNode;
final Schema schema = treeNode.getSchema();
dragNode = new LWNode(String.format(" '%s' \n dataset \n (%d items) ",
schema.getName(),
schema.getRowCount()
));
}
if (dragNode == null) {
Log.warn("Unable to create nodes from drag of " + treeNode);
return;
}
dragNode.copyStyle(treeNode.getStyle(), ~LWKey.Label.bit);
//dragNode.setFillColor(null);
//dragNode.setStrokeWidth(0);
if (!treeNode.isValue()) {
dragNode.mFontSize.setTo(24);
dragNode.mFontStyle.setTo(java.awt.Font.BOLD);
// dragNode.setClientData(LWComponent.ListFactory.class,
// new NodeProducer(treeNode));
}
dragNode.setFlag(LWComponent.Flag.INTERNAL);
dragNode.setClientData(tufts.vue.MapDropTarget.DropHandler.class,
new DataDropHandler(treeNode, DataTree.this));
dragNode.setClientData(Field.class, treeNode.getField()); // for associations panel
tufts.vue.gui.GUI.startRecognizedDrag(e, dragNode);
}
private static String valueText(Object value) {
return DataAction.valueText(value);
}
private DataNode getSelectedNode() {
return (DataNode) getLastSelectedPathComponent();
}
private void sendToMap(final DataNode treeNode, final LWMap map) {
if (map == null || treeNode == null)
return;
Log.debug("SENDING TO MAP: " + treeNode);
}
private static final Ordering<Multiset.Entry> ByDecreasingFrequency = new Ordering<Multiset.Entry>() {
/*@Override*/ public int compare(Multiset.Entry a, Multiset.Entry b) {
return b.getCount() - a.getCount();
}
};
/*
* This will find all rows of data in this given data-set that are NOT in the map,
* create row-nodes for them, and send them to the map. This also kicks off an
* annotation run to update the tree after the nodes have been added to the map.
*/
// For NEW DATA CLUSTERING: whenever new nodes are added to the map and there is no
// layout specified / going to be applied, we want to place nodes near items their
// related to. We do this based on the links.
//
// There are many versions of this. E.g.:
//
// 1 - re-clustering around the last clustered nodes as marked by the clustering
// time-stamp for row-node additions
//
// 2 - placing new value-nodes most near the nodes their related to based on links
/** adding more than this # of new row-nodes to the map permits a map-reorg */
private static final int NEW_ROW_NODE_MAP_REORG_THRESHOLD = 20;
private void addMissingRowsToMap(final LWMap map)
{
// todo: we'll want to merge some of this code w/DropHandler code, as
// this is somewhat of a special case of doing a drop
final List<DataRow> newRows = new ArrayList();
for (DataNode n : mAllRowsNode.getChildren()) {
if (!n.isMapPresent()) {
//Log.debug("ADDING TO MAP: " + n);
newRows.add(n.getRow());
}
}
final List<LWComponent> newRowNodes = DataAction.makeRowNodes(mSchema, newRows);
Multiset<LWComponent> targetsUsed = null;
List<LWLink> linksAdded = Collections.EMPTY_LIST;
try {
final Object[] result
= DataAction.addDataLinksForNodes(map,
newRowNodes,
(Field) null);
targetsUsed = (Multiset) result[0];
linksAdded = (List) result[1];
} catch (Throwable t) {
Log.error("problem creating links on " + map + " for new nodes: " + Util.tags(newRowNodes), t);
}
if (DEBUG.Enabled && targetsUsed != null) {
final Set entries = targetsUsed.entrySet();
Log.debug("TARGETS USED: " + targetsUsed.size() + " / " + entries.size());
Util.dump(entries);
}
if (newRowNodes.size() > 0) {
// we cannot run setXYByClustering before adding to the map w/out refactoring projectNodes
// (or for that matter, centroidCluster, which also uses projectNodes). E.g. -- we
// can't use this as an initial fallback/failsafe.
//tufts.vue.VueUtil.setXYByClustering(map, nodes);
//-----------------------------------------------------------------------------
// add all the "missing" / newly-arrived rows to the map
//-----------------------------------------------------------------------------
map.getOrCreateLayer("New Data Nodes").addChildren(newRowNodes);
// PROBLEM/BUG: the above add to a special layer appears to be failing (to
// the user) somtimes and the nodes wind up in the same layer as the
// relating nodes -- this is when ArrangeAction.clusterLinked is then used
// below. It does some reparenting which it needs to do in case nodes had
// been collected as children, but in some cases, it doesn't need doing and
// ends up just pulling the nodes right back out of the "New Data Nodes"
// layer after we just moved them there.
// -----------------------------------------------------------------------------
if (newRowNodes.size() > NEW_ROW_NODE_MAP_REORG_THRESHOLD) {
if (targetsUsed.size() > 0) { // Note: won't currently trigger for cross-schema joins, as targesUsed aren't reported
//-------------------------------------------------------
// RE-CLUSTER THE ENTIRE MAP
//-------------------------------------------------------
// If there is was more than one value-node link per row-node created (e.g.,
// multiple sets of value nodes are already on the map), prioritizing those
// targets with the most first spreads the nodes out the most as the targets
// with the fewest links would are at least be guaranteed to get some of the
// row nodes. Using the push-method in this case would be far too slow -- we'd
// have to push based on every row node.
final List<Multiset.Entry<LWComponent>> ordered
= ByDecreasingFrequency.sortedCopy(targetsUsed.entrySet());
for (Multiset.Entry<LWComponent> e : ordered) {
tufts.vue.Actions.ArrangeAction.clusterLinked(e.getElement());
}
// note: if we wished, we could also decide here
// what to cluster on based on what targets are
// selected (currently have the selection bit set)
} else {
// fallback: randomly layout anything that isn't first XY clustered:
tufts.vue.LayoutAction.random.act
(tufts.vue.VueUtil.setXYByClustering(newRowNodes));
}
}
else {
//-------------------------------------------------------
// Centroid cluster
//-------------------------------------------------------
DataAction.centroidCluster(map, newRowNodes, true);
//-------------------------------------------------------
}
VUE.getSelection().setTo(newRowNodes);
}
map.getUndoManager().mark("Add New Data Nodes");
}
private static String makeFieldLabel(final Field field)
{
if (field.isQuantile())
return HTML(field.getName());
//return HTML("<font color=gray>" + field.getName());
final Set values = field.getValues();
//Log.debug("EXPANDING " + colNode);
//LWComponent schemaNode = new LWNode(schema.getName() + ": " + schema.getSource());
// add all style nodes to the schema node to be put in an internal layer for
// persistance: either that or store them with the datasources, which
// probably makes more sense.
String label = field.toString();
if (values.size() == 0) {
if (field.getMaxValueLength() == 0) {
//label = String.format("<html><b><font color=gray>%s", field.getName());
label = String.format(HTML("<font color=gray>%s"), field.getName());
} else {
//label = String.format("<html><b>%s (max size: %d bytes)",
label = String.format(HTML("%s (max size: %d bytes)"),
field.getName(), field.getMaxValueLength());
}
} else if (values.size() == 1) {
label = String.format(HTML("%s: <font color=green>%s"),
field.getName(), field.getValues().toArray()[0]);
} else if (values.size() > 1) {
//final Map<String,Integer> valueCounts = field.getValueMap();
// if (field.isPossibleKeyField())
// //label = String.format("<html><i><b>%s</b> (%d)", field.getName(), field.uniqueValueCount());
// else
// // we add space before and after to widen the painted background selection around the text a bit
// label = String.format(HTML(" %s (%d) "), field.getName(), field.uniqueValueCount());
label = String.format(HTML("%s (%d)"), field.getName(), field.uniqueValueCount());
}
return label;
}
static class DataNode extends DefaultMutableTreeNode {
String display;
protected DataNode(String description) {
setDisplay(description);
}
protected DataNode() {}
Vector<DataNode> getChildren() {
return super.children;
}
Schema getSchema() {
Util.printStackTrace("getSchema: unimplemented");
return null;
}
DataRow getRow() {
Util.printStackTrace("getRow: unimplemented");
return null;
}
/** @return false -- override for row nodes */
boolean isRow() { return false; }
/** @return null -- override for value nodes */
String getValue() { return null; }
/** @return null -- override for field nodes */
Field getField() { return null; }
/** @return -1 -- override for value nodes */
int getCount() {
return -1;
}
/** @return true if this node represents the collection of all possible values found in a column of data */
boolean isField() { return false; }
/** @return true if this node represents a paricular enumerated value from a given column */
boolean isValue() { return !isField(); }
LWComponent getStyle() { return null; }
boolean hasStyle() { return false; }
/** set the label visually displayed in the tree (unannotated) */
void setDisplay(String s) {
display = s;
setUserObject(s); // sets display label
}
public String getDisplay() {
return (String) getUserObject();
}
/** noop -- override to provide annotations againast the given map */
void annotate(LWMap map) {}
void setAnnotation(String s) {
setPostfix(s);
}
void setPostfix(String s) {
//Log.debug("postfix " + this + " with [" + s + "]");
if (s == null || s.length() == 0) {
setUserObject(display);
} else {
setUserObject(display + " " + s);
}
}
void setPrefix(String s) {
//Log.debug("prefix " + this + " with [" + s + "]");
if (s == null || s.length() == 0) {
setUserObject(display);
} else {
//final String cs = (String) getUserObject();
if (display.startsWith("<html>")) {
setUserObject("<html>" + s + " " + display.substring(6));
} else
setUserObject(s + " " + display);
}
}
/** @return true if this node is tracked for presence in the active map */
boolean isMapTracked() {
return false;
//return isValue();
}
boolean isRowNode() {
return getField() == null;
}
/** @return false -- override for semantics */
boolean isMapPresent() {
return false;
}
/** @return false -- override for semantics */
boolean isContextChanged() {
return false;
}
}
final class RowNode extends DataNode {
final DataRow row;
boolean isMapPresent;
RowNode(DataRow row, Field labelField) {
this.row = row;
//setDisplay(row.getValue(labelField));
setDisplay(row.toString());
}
@Override boolean isRow() { return true; }
@Override DataRow getRow() { return row; }
@Override boolean isMapPresent() { return isMapPresent; }
@Override boolean isContextChanged() { return row.isContextChanged(); }
@Override
void annotate(LWMap map) {
// final Field keyField = getSchema().getKeyField();
// final String keyValue = row.getValue(keyField);
// isMapPresent = keyField.countContextValue(keyValue) > 0;
isMapPresent = row.getContextCount() > 0;
}
@Override boolean isMapTracked() { return true; }
@Override boolean isField() { return false; }
@Override boolean isValue() { return false; }
@Override Schema getSchema() {
// return row.getSchema() -- row's don't currently encode the schema
// if pull a schema stored in the root template node from parent.parent,
// could skip making this an inner class, and save 4 bytes per row-node at runtime
return mSchema;
}
}
/**
* A "field" is really a column from a particular data set, with the additional
* semantics that we usually always keep around an enumerated list of all the possible
* unique values that appear in that column. A FieldNode node will have a list of ValueNodes
* as children to represent these values.
*/
private static class FieldNode extends DataNode {
final Field field;
FieldNode(Field field, LWComponent.Listener repainter, String description) {
this.field = field;
if (description == null) {
if (field != null)
setDisplay(makeFieldLabel(field));
} else
setDisplay(description);
//if (field != null && field.isEnumerated() && !field.isPossibleKeyField())
//if (field != null && !field.hasStyleNode() && !field.isSingleValue() && field.isEnumerated()) {
if (field != null && field.hasStyleNode() && !field.isSingleValue() && field.isEnumerated()) {
// TODO: this means on refresh, the old style node will be pointing via repainter to
// an AWT component that is no longer displayed, breaking updates!
// DO NOT CREATE THE STYLE NODE HERE: DO SO IN FIELD -- just UPDATE it with
// the new repainter here
//field.setStyleNode(DataAction.makeStyleNode(field, repainter));
field.getStyleNode().addLWCListener(repainter);
}
}
protected FieldNode(Field field) {
this.field = field;
}
@Override Field getField() { return field; }
@Override Schema getSchema() { return field.getSchema(); }
@Override LWComponent getStyle() { return field == null ? null : field.getStyleNode(); }
@Override boolean hasStyle() { return field != null && field.getStyleNode() != null; }
@Override boolean isField() { return field != null; }
}
private static final class ValueNode extends FieldNode {
final String value;
final int dataSetCount;
boolean isMapPresent;
ValueNode(Field field, String value, String label, int dataSetValueCount) {
super(field);
setDisplay(label);
this.value = value;
this.dataSetCount = dataSetValueCount;
}
@Override final boolean isMapTracked() {
return true;
}
@Override String getValue() {
return value;
}
@Override int getCount() {
return dataSetCount;
}
@Override void annotate(LWMap map) {
final int mapCount = field.countContextValue(value);
if (mapCount > 0) {
isMapPresent = true;
if (mapCount != dataSetCount)
setPostfix(String.format("[%+d]", mapCount - dataSetCount));
else
setPostfix(null);
//setPrefix("=");
} else {
isMapPresent = false;
setPostfix(null);
//setPrefix("-");
}
// // TODO: INCLUDE CURRENT MAP COUNTS
// if (field.hasContextValue(value))
// setPrefix("=");
// //setAnnotation(null);
// else
// setPrefix("+");
// //setAnnotation("<font color=red>(new)");
}
@Override
public boolean isField() { return false; }
@Override
public boolean hasStyle() { return false; }
// @Override
// public LWComponent getStyle() { return null; }
@Override
boolean isMapPresent() {
return isMapPresent;
}
// @Override
// public String toString() { return "ValueNode[" + super.toString() + "; value=" + getValue() + "]"; }
}
final class AllRowsNode extends FieldNode {
final Schema schema;
//AllRowsNode(Schema schema, LWComponent.Listener _repainter_ignored) {
AllRowsNode(Schema schema, Object _repainter_ignored) {
super(null, /*repainter*/null, "All Rows");
//String.format(HTML("<b><u>All Records in %s (%d)"), schema.getName(), schema.getRowCount()));
this.schema = schema;
if (schema.getRowNodeStyle() == null)
schema.setRowNodeStyle(DataAction.makeStyleNode(schema));
schema.getRowNodeStyle().addLWCListener(new LWComponent.Listener() {
public void LWCChanged(tufts.vue.LWCEvent e) {
if (DEBUG.EVENTS) Log.debug("ALL-ROWS-NODE UPDATE " + e);
DataTree.this.refreshRootNode();
//updateLabel(true);
}
});
updateLabel(false);
}
private void updateLabel(boolean refresh) {
// as it currently stands, this never actually needs updating
setDisplay(String.format(HTML("All Records (%d)"), schema.getRowCount()));
// String labelFormat = schema.getRowNodeStyle().getLabel().trim();
// if (labelFormat.startsWith("${") && labelFormat.endsWith("}"))
// labelFormat = labelFormat.substring(2, labelFormat.length()-1);
// setDisplay(String.format(HTML("<b>All Records</b> (%d) : <b><font color=red>%s"),
// schema.getRowCount(),
// labelFormat));
if (refresh)
DataTree.this.refreshRootNode();
}
@Override void annotate(LWMap map) {
//if (DEBUG.Enabled) setAnnotation(String.format("[%s]", map.getLabel()));
}
@Override Schema getSchema() { return schema; }
@Override boolean isField() { return false; }
@Override boolean isValue() { return false; }
@Override boolean hasStyle() { return true; }
@Override LWComponent getStyle() { return schema.getRowNodeStyle(); }
}
private static final int IconWidth = 27;
private static final int IconHeight = 20;
//private static final Border TopBorder = BorderFactory.createLineBorder(Color.gray);
// private static final Border TopBorder = new CompoundBorder(new MatteBorder(3,0,3,0, Color.white),
// new CompoundBorder(new LineBorder(Color.gray),
// GUI.makeSpace(1,0,1,2)));
//private static final Border TopBorder = GUI.makeSpace(3,0,2,0);
//private static final Border TopBorder = GUI.makeSpace(0,0,2,0);
//private static final Border TopBorder = new CompoundBorder(GUI.makeSpace(0,0,10,0), new MatteBorder(0,0,1,0, Color.gray));
private static final Border TopBorderCollapsed = new CompoundBorder(new CompoundBorder(GUI.makeSpace(0,0,7,0),
new MatteBorder(0,0,1,0, Color.gray)),
GUI.makeSpace(0,0,7,0));
private static final Border TopBorderExpanded = null;
private static final Border TopTierBorder = GUI.makeSpace(0,0,2,0);
private static final Border LeafBorder = GUI.makeSpace(0,IconWidth-16,2,0);
//private static final Icon IncludedInMapIcon = VueResources.getIcon(VUE.class, "images/data_onmap.png");
//private static final Icon IncludedInMapIcon = GUI.reframeIcon(VueResources.getIcon(VUE.class, "images/data_onmap.png"), 8, 16);
//private static final Icon NewToMapIcon = VueResources.getIcon(VUE.class, "images/data_offmap.png");
private static final int RIPS = Util.isMacPlatform() ? 20 : 16; // RowIconPointSize
private static final Icon RowHasChangedIcon = makeIcon(0x229B, RIPS, Color.green.darker(), -2, -1);
private static final Icon RowOnMapIcon = makeIcon(0x229B, RIPS, VueConstants.COLOR_SELECTION, -2, -1);
private static final Icon RowOffMapIcon = makeIcon(0x229B, RIPS, Color.lightGray, -2, -1);
private static final Icon ValueOnMapIcon = makeIcon(0x25C9, 12, VueConstants.COLOR_SELECTION, 0, 0);
private static final Icon ValueOffMapIcon = makeIcon(0x25C9, 12, Color.lightGray, 0, 0);
// private static final Icon RowOnMapIcon = makeIcon(0x25C9, 14, VueConstants.COLOR_SELECTION);
// private static final Icon RowOffMapIcon = makeIcon(0x25C9, 14, Color.lightGray);
// private static final Icon ValueOnMapIcon = makeIcon(0x229B, 18, VueConstants.COLOR_SELECTION, 0, -1);
// private static final Icon ValueOffMapIcon = makeIcon(0x229B, 18, Color.lightGray, 0, -1);
//private static final Icon UniqueValueOnMapIcon = makeIcon(0x29BF, 16, VueConstants.COLOR_SELECTION, 0, -1);
//private static final Icon UniqueValueOffMapIcon = makeIcon(0x29BF, 16, Color.lightGray, 0, -1);
private static final Icon UniqueValueOnMapIcon = makeIcon(0x229A, 16, VueConstants.COLOR_SELECTION, 0, 0);
private static final Icon UniqueValueOffMapIcon = makeIcon(0x229A, 16, Color.lightGray, 0, 0);
// 29BE: ⦾
// 29BF: ⦿
// 25C9: â—‰
// 25CE: â—Ž
// 229A: ⊚
// 25E6: â—¦
// 229D: �
// 229B: ⊛
private static Icon makeIcon(int code, int pointSize, Color color) {
return makeIcon(code, pointSize, color, 0, 0);
}
private static Icon makeIcon(int code, int pointSize, Color color, int xoff, int yoff) {
return GUI.makeUnicodeIcon(code,
pointSize,
color,
16, // fixed width
16, // fixed height
4+xoff, // xoff
4+yoff // yoff
);
}
// private static final GUI.ResizedIcon NewToMapIcon =
// new GUI.ResizedIcon(VueResources.getIcon(GUI.class, "icons/MacSmallCloseIcon.gif"), 16, 16);
private static final Color KeyFieldColor = Color.green.darker();
private static final Icon TestIcon = VueResources.getImageIcon("dataSourceRSS");
private class DataRenderer extends DefaultTreeCellRenderer {
{
//setIconTextGap(2);
//setBorder(LeafBorder);
setVerticalTextPosition(SwingConstants.CENTER);
//setTextSelectionColor(Color.blue); // text color selected
//setTextNonSelectionColor(Color.green); // text color normal
//setBackgroundSelectionColor(VueConstants.COLOR_SELECTION.brighter());
setBackgroundSelectionColor(VueResources.getColor("dataTree.selected.background", Color.blue));
setBorderSelectionColor(VueConstants.COLOR_SELECTION);
//setBackgroundSelectionColor(VueConstants.COLOR_HIGHLIGHT);
//setFont(tufts.vue.VueConstants.SmallFixedFont);
}
//@Override public int getWidth() { return 500; }
public Component getTreeCellRendererComponent(
final JTree tree,
final Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus)
{
//Log.debug(Util.tags(value));
//Log.debug(Util.tags(value));
if (!(value instanceof DataNode))
return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
final DataNode treeNode = (DataNode) value;
final Field field = treeNode.getField();
//setIconTextGap(4); // pre standard HTML
setIconTextGap(1);
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
setForeground(Color.black); // must do every time for some reason, or de-selected text goes invisible
if (treeNode.hasStyle()) {
//setIconTextGap(4);
// Note: icons at top level do not get the background selection color painted
// behind them for some reason, whereas leaf node icons do, so this icon
// needs to take that into account, and should be careful not to paint over
// the selected & focus-active border of the row item.
setIcon(FieldIconPainter.load(treeNode.getStyle(),
selected ? backgroundSelectionColor : null));
} else {
if (field != null && field.isSingleton()) {
setIcon(null);
} else if (!treeNode.isMapTracked()) {
setIcon(null);
} else {
setIconTextGap(1);
if (treeNode.isRow()) {
if (treeNode.isContextChanged())
setIcon(RowHasChangedIcon);
else if (treeNode.isMapPresent())
setIcon(RowOnMapIcon);
else
setIcon(RowOffMapIcon);
} else {
if (field != null && field.isPossibleKeyField()) {
if (treeNode.isMapPresent())
setIcon(UniqueValueOnMapIcon);
else
setIcon(UniqueValueOffMapIcon);
// } else if (field != null && field.isQuantile() && treeNode.getCount() <= 0) {
// setIcon(null);
} else {
if (treeNode.isMapPresent())
setIcon(ValueOnMapIcon);
else
setIcon(ValueOffMapIcon);
}
}
}
}
if (row == 0) {
if (expanded)
setBorder(TopBorderExpanded);
else
setBorder(TopBorderCollapsed);
//setBorder(TopBorder);
//setBackgroundNonSelectionColor(Color.lightGray);
//setFont(EnumFont);
} else {
//setBackgroundNonSelectionColor(null);
//setFont(null);
//setBorder(leaf ? LeafBorder : null);
if (leaf) {
if (treeNode.isField() && treeNode.getField().isSingleton())
setBorder(TopTierBorder);
else
setBorder(LeafBorder);
} else {
setBorder(null);
}
}
return this;
}
}
private static final java.awt.geom.Rectangle2D IconSize
= new java.awt.geom.Rectangle2D.Float(0,0,IconWidth,IconHeight);
// private static final java.awt.geom.Rectangle2D IconInsetSize
// = new java.awt.geom.Rectangle2D.Float(1,2,IconWidth-2,IconHeight-4);
private static final NodeIconPainter FieldIconPainter = new NodeIconPainter();
private static final Icon EmptyIcon = new GUI.EmptyIcon(IconWidth, IconHeight);
private static final double ViewScaleDown = 0.5;
private static final double ViewScale = 1 / ViewScaleDown;
private static final java.awt.geom.Rectangle2D IconViewSize
= new java.awt.geom.Rectangle2D.Double(2*ViewScale,
4*ViewScale+0.5,
(IconWidth-4) * ViewScale,
(IconHeight-8) * ViewScale);
private static final Stroke NodeIconBorder = new BasicStroke(0.5f);
private static class NodeIconPainter implements Icon {
LWComponent node;
Color fill;
public Icon load(LWComponent c, Color fill) {
if (c == null)
Log.error("null node; fill=" + fill, new Throwable("HERE"));
this.node = c;
this.fill = fill;
return this;
}
public int getIconWidth() { return IconWidth; }
public int getIconHeight() { return IconHeight; }
public void paintIcon(Component c, Graphics _g, int x, int y) {
//Log.debug("x="+x+", y="+y);
if (node == null) {
if (DEBUG.Enabled) Log.warn("null node in " + getClass().getName());
return;
}
java.awt.Graphics2D g = (java.awt.Graphics2D) _g;
g.setRenderingHint
(java.awt.RenderingHints.KEY_ANTIALIASING,
java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
if (fill != null) {
if (DEBUG.BOXES) {
g.setColor(Color.red);
g.fillRect(x,y,IconWidth,IconHeight);
} else {
// g.setColor(fill);
// g.setColor(Color.red);
// // add to width to also fill the IconTextGap
// // TODO: this is painting over edge of active selected border color
// g.fillRect(0,0,IconWidth+8,IconHeight+8);
}
}
// we should only be seeing LWNode's, which always have RectanularShape
final RectangularShape shape = (RectangularShape) node.getZeroShape();
shape.setFrame(IconViewSize);
g.setColor(node.getFillColor());
g.scale(ViewScaleDown, ViewScaleDown);
g.fill(shape);
g.setStroke(NodeIconBorder);
g.setColor(Color.gray);
g.draw(shape);
g.scale(ViewScale, ViewScale);
//node.setSize(IconSize);
// node.drawFit(new DrawContext(g.create(), node),
// IconSize,
// 2);
// //node.drawFit(g, x, y);
}
}
}
// // this type of node was only for intial prototype
// private static LWComponent makeDataNodes(Schema schema, Field field)
// {
// Log.debug("PRODUCING KEY FIELD NODES " + field);
// int i = 0;
// for (DataRow row : schema.getRows()) {
// n = new LWNode();
// n.setClientData(Schema.class, schema);
// n.getMetadataList().add(row.entries());
// if (field != null) {
// final String value = row.getValue(field);
// n.setLabel(makeLabel(field, value));
// } else {
// //n.setLabel(treeNode.getStyle().getLabel()); // applies initial style
// }
// nodes.add(n);
// //Log.debug("setting meta-data for row " + (++i) + " [" + value + "]");
// // for (Map.Entry<String,String> e : row.entries()) {
// // // todo: this is slow: is updating UI components, setting cursors, etc, every time
// // n.addMetaData(e.getKey(), e.getValue());
// // }
// }
// Log.debug("PRODUCED META-DATA IN " + field);
// }
// private static LWComponent makeDataNode(Schema schema)
// {
// int i = 0;
// LWNode node;
// for (DataRow row : schema.getRows()) {
// node = new LWNode();
// node.setClientData(Schema.class, schema);
// node.getMetadataList().add(row.entries());
// node.setStyle(schema.getStyleNode()); // must have meta-data set first to pick up label template
// nodes.add(n);
// //Log.debug("setting meta-data for row " + (++i) + " [" + value + "]");
// // for (Map.Entry<String,String> e : row.entries()) {
// // // todo: this is slow: is updating UI components, setting cursors, etc, every time
// // n.addMetaData(e.getKey(), e.getValue());
// // }
// }
// Log.debug("PRODUCED META-DATA IN " + field);
// }
|
C++
|
UTF-8
| 498
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <QWidget>
class TrackingColor : public QWidget
{
Q_OBJECT
public:
TrackingColor() : _trackingColor(QColor::fromHsv(303,255,255)) {} // 303 pink, 143 green
void paintEvent(QPaintEvent* /*event*/) override;
QColor const & GetColor(){return _trackingColor;}
void SetHue(int hue);
int GetHue();
void SetSaturation(int sat);
void SetValue(int value);
signals:
void ColorChanged(QColor const &);
private:
QColor _trackingColor;
};
|
Shell
|
UTF-8
| 279
| 3.390625
| 3
|
[] |
no_license
|
#!/bin/bash
echo -e "Today’s date is: \c"
date
echo -e "\nThe people logged into the system include:"
who
echo -e "\nWould you like to see the contents of /?(y/n)-->\c"
read ANSWER
if [ $ANSWER = "y" ]; then
echo -e "\nThe contents of the / directory are:"
ls -F /
fi
|
Shell
|
UTF-8
| 326
| 2.734375
| 3
|
[] |
no_license
|
#!/bin/bash
# *** Usage: ./gen.py <number_of_airports> <density> <min f/od> <max f/od> <max_hops> <alfa_error>
# Ex: ./gen.py 10 100 1 3 4 2
for n in 4; do
echo "generating instance with $n airports"
./gen.py $n 100 1 2 4 5
mkdir $n
mv *.csv ./$n/
done
|
C++
|
UTF-8
| 1,074
| 3.171875
| 3
|
[] |
no_license
|
#include <iostream>
# include <string>
# include <vector>
using namespace std;
void prefix_func(const string &str, vector<int> &z) {
z.resize(str.size());
z[0] = 0;
for (int i=1;i<z.size();++i) {
int pos = z[i-1];
while (pos > 0 && str[pos] != str[i])
pos = z[pos-1];
z[i] = pos + (str[pos] == str[i] ? 1 : 0);
}
}
vector<int> kmp(const string &text, const string &str) {
vector<int> answer;
vector<int> z;
prefix_func(str,z);
int pos = 0;
for (int i=0; i<text.size(); ++i) {
while (pos > 0 && (pos >= str.size() || str[pos] != text[i]) )
pos = z[pos-1];
if (text[i] == str[pos]) pos++;
if (pos == str.size())
answer.push_back(i - pos + 1);
}
return answer;
}
int main() {
string P, T;
vector<int> answer;
cin >> P;
cin >>T;
answer = kmp(T,P);
if (answer.size() == 0) {cout << "-1"; return 0;}
for (int i = 0; i < answer.size() - 1; i++)
cout << answer[i] << ",";
cout << answer.back();
return 0;
}
|
Shell
|
UTF-8
| 181
| 3.375
| 3
|
[] |
no_license
|
#!/bin/bash
echo “To compute the sum”
num=$1
sum=0
while [ $num -gt 0 ]
do
rem=`expr $num % 10`
num=`expr $num / 10`
sum=`expr $rem + $sum`
done
echo “The result is $sum”
|
Markdown
|
UTF-8
| 1,162
| 2.609375
| 3
|
[] |
no_license
|
---
copyright:
years: 2015, 2017
lastupdated: "2017-11-16"
---
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:new_window: target="_blank"}
{:tip: .tip}
# Working with users
{: #iamusermanage}
Depending on the access options that you are authorized to manage, you can view and manage users across the account or organizations that you own or manage. From the Users list for your account, you can see both platform and infrastructure users.
{:shortdesc}
To manage users in your account, complete the following steps:
1. From the menu bar, click **Manage** > **Account** > **Users**. The Users window displays a list of users with their email addresses for the currently selected account.
2. Select the user name, or click **Manage user** from the **Actions** menu.
3. Then, depending on what action you need to take, you can choose to remove the user, assign access, or edit the user's existing access.
For details on the CLI commands that are used to manage accounts, orgs, and spaces, see [Commands for managing accounts, orgs, and roles](/docs/cli/reference/bluemix_cli/bx_cli.html#bx_commands_acctorg).
{: tip}
|
Java
|
WINDOWS-1252
| 2,485
| 2.71875
| 3
|
[] |
no_license
|
package apps.projectmanagement.component.staffnode;
import java.awt.Color;
import java.awt.Font;
import java.util.List;
import synergynetframework.appsystem.contentsystem.items.utils.IDrawableContent;
import com.jmex.awt.swingui.ImageGraphics;
/**
* The Class StaffNodeDrawableContent.
*/
public class StaffNodeDrawableContent implements IDrawableContent {
/** The heigth. */
int heigth = 150;
/** The name. */
String name;
/** The notes. */
List<String> notes;
/** The position. */
String position;
/** The salary. */
String salary;
/** The width. */
int width = 150;
/** The work experience. */
String workExperience;
/**
* Instantiates a new staff node drawable content.
*
* @param staffModel
* the staff model
* @param width
* the width
* @param height
* the height
*/
public StaffNodeDrawableContent(StaffModel staffModel, int width, int height) {
super();
this.name = staffModel.getName();
this.position = staffModel.getPosition();
this.workExperience = staffModel.getWorkExperience();
this.salary = staffModel.getSalary();
this.notes = staffModel.getNotes();
this.width = width;
this.heigth = height;
}
/*
* (non-Javadoc)
* @see
* synergynetframework.appsystem.contentsystem.items.utils.IDrawableContent
* #drawContent(java.lang.Object)
*/
@Override
public void drawContent(Object drawingHandle) {
ImageGraphics gfx = (ImageGraphics) drawingHandle;
gfx.setColor(Color.WHITE);
gfx.fillRect(0, 0, width, heigth);
gfx.setColor(Color.gray);
Font font = new Font("Arial", Font.BOLD, 10);
gfx.setFont(font);
int rowHeigth = 15;
gfx.drawString("Name:", 5, rowHeigth * 2);
gfx.drawString("Position:", 5, rowHeigth * 3);
gfx.drawString("Work Exp.:", 5, rowHeigth * 4);
gfx.drawString("Salary:", 5, rowHeigth * 5);
gfx.drawString("Notes:", 5, rowHeigth * 6);
gfx.setColor(Color.BLACK);
font = new Font("Arial", Font.PLAIN, 9);
gfx.setFont(font);
gfx.drawString(name, 37, rowHeigth * 2);
gfx.drawString(this.position, 50, rowHeigth * 3);
gfx.drawString(this.workExperience + " yrs", 62, rowHeigth * 4);
gfx.drawString("" + this.salary + " per hour", 42, rowHeigth * 5);
if (notes == null) {
return;
}
for (int i = 0; i < notes.size(); i++) {
gfx.drawString(notes.get(i), 5, rowHeigth * (7 + i));
}
}
}
|
PHP
|
UTF-8
| 2,949
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Repositories\ParseArchiveRepository;
use App\Repositories\ParseCategoryRepository;
use App\Repositories\ParseItemRepository;
use App\Repositories\ParseMenuRepository;
use App\Repositories\ParseSubCategoryRepository;
use Illuminate\Http\Request;
class ItemsController extends Controller
{
private $items;
private $archives;
private $menu;
private $categories;
private $subcategories;
public function __construct(ParseItemRepository $items, ParseArchiveRepository $archives, ParseMenuRepository $menu, ParseCategoryRepository $categories, ParseSubCategoryRepository $subcategories)
{
$this->subcategories = $subcategories;
$this->items = $items;
$this->archives = $archives;
$this->menu = $menu;
$this->categories = $categories;
$this->middleware('auth');
}
public function positions(Request $request)
{
foreach($request->order as $key => $objectId){
$this->items->update($objectId, ['position' => intval($key)+1]);
}
flash()->success('Your items order has been updated correctly', '');
return response()->json(['Message' => 'Item order updated.'], 200);
}
public function update(Request $request, $objectId)
{
$this->items->update($request->input('objectId'), [ 'relatedText' => $request->input('relatedText')]);
flash()->success('Your item has been updated correctly', '');
return response()->json(['Message' => 'Item updated.'], 200);
}
public function store(Request $request)
{
// dd([$this->menu->find($request->input('menu')), $request->all(), $request->menu, strcmp($request->input('menu'), 'BeQYNaR0Gc') == 0]);
if(strcmp($request->input('menu'), 'BeQYNaR0Gc') == 0){
$subcategory = $this->subcategories->find($request->input('subcategory'));
$position = $this->items->findAllBy('subcategory', $subcategory)->count();
$item = [
'position' => $position,
'subcategory' => $subcategory,
'relatedText' => $request->input('relatedText'),
'menu' => $this->menu->find($request->input('menu')),
];
}
else{
$category = $this->categories->find($request->input('category'));
$position = $this->items->findAllBy('category', $category)->count();
$item = [
'position' => $position,
'category' => $category,
'relatedText' => $request->input('relatedText'),
'menu' => $this->menu->find($request->input('menu')),
];
}
$this->items->create($item);
flash()->success('Your item has been created correctly', '');
return response()->json(['Message' => 'Item created.'], 200);
}
public function destroy($objectId)
{
$this->items->delete($objectId);
flash()->success('Your item has been deleted correctly', '');
return response()->json(['Message' => 'Item deleted.'], 200);
}
}
|
C#
|
UTF-8
| 883
| 2.859375
| 3
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
using System.ComponentModel;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace TestWcfDto
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
[DataMember(Order=1)]
public bool BoolValue {get;set;}
[DataMember(Order = 2)]
public string StringValue {get;set;}
}
}
|
C++
|
UTF-8
| 3,059
| 3.21875
| 3
|
[] |
no_license
|
#pragma once
#include <utility>
#include <unordered_map>
#include <fstream>
/**
* A mutable unordered bimap for std::wstring and int values
*/
class mutable_word_mapping
{
public:
std::unordered_map<std::wstring, int> word_to_int_map;
std::unordered_map<int, const std::wstring> int_to_word_map;
mutable_word_mapping() = default;
void insert(std::wstring&& word, int number)
{
const auto it = word_to_int_map.emplace(std::pair<std::wstring, int>(word, number));
int_to_word_map.emplace(std::pair<int, const std::wstring>(number, it.first->first));
#ifdef DEBUG
std::wcout << L"Word To Int Map address: " << &(word_to_int_map_.cbegin()->first)
<< L", Word To Int Map word: " << (word_to_int_map_.cbegin()->first) << L"\n";
std::wcout << L"Int To Word Map address: " << int_to_word_map_.cbegin()->second
<< L", Int To Word Map word: " << *(int_to_word_map_.cbegin()->second) << L"\n";
#endif
}
int word_to_int(std::wstring& word)
{
const auto return_val = word_to_int_map[word];
if (return_val)
return return_val;
return 0;
}
const std::wstring& int_to_word(const int number)
{
return int_to_word_map[number];
}
};
/**
* An immutable unordered bimap for std::wstring and int values\n
* Instances are created by making a copy of an existing mutable_word_mapping object
*/
class word_mapping
{
const std::unordered_map<std::wstring, int> word_to_int_map_;
const std::unordered_map<int, const std::wstring> int_to_word_map_;
public:
word_mapping() = default;
explicit word_mapping(mutable_word_mapping&& wm) : word_to_int_map_(wm.word_to_int_map),
int_to_word_map_(wm.int_to_word_map)
{
}
int word_to_int(std::wstring& word) const
{
const auto return_val = word_to_int_map_.find(word);
if (return_val != word_to_int_map_.end())
return return_val->second;
return 0;
}
const std::wstring* int_to_word(const int number) const
{
return &int_to_word_map_.find(number)->second;
}
};
/**
* An immutable hashtable for words in int format and line offset values\n
*/
class mutable_offset_table
{
public:
std::unordered_map<int, int> compressed_model;
void insert(int key, int count)
{
compressed_model.insert(std::pair<int, int>(key, count));
}
int get_value(const int key)
{
return compressed_model[key];
}
size_t size() const
{
return compressed_model.size();
}
};
/**
* An immutable hashtable for words in int format and line offset values\n
* Instances are created by making a copy of an existing mutable_model object
*/
class offset_table
{
const std::unordered_map<int, int> compressed_model_;
public:
offset_table() = default;
explicit offset_table(mutable_offset_table&& m) : compressed_model_(m.compressed_model)
{
}
int get_value(const int key) const
{
return compressed_model_.find(key)->second;
}
size_t size() const
{
return compressed_model_.size();
}
};
|
Java
|
UTF-8
| 455
| 1.890625
| 2
|
[] |
no_license
|
package com.lym.mechanical.dao.mapper;
import com.lym.mechanical.bean.entity.PaymentDO;
import org.springframework.stereotype.Component;
@Component
public interface PaymentDOMapper {
int deleteByPrimaryKey(Integer id);
int insert(PaymentDO record);
int insertSelective(PaymentDO record);
PaymentDO selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(PaymentDO record);
int updateByPrimaryKey(PaymentDO record);
}
|
Markdown
|
UTF-8
| 860
| 2.625
| 3
|
[] |
no_license
|
- I spent 8 hours to finish this project.
- I finished below stories:
. Enter bill amount in a simpler way
I introduced something more convenient instead of built-in keyboard view.
. Enter tip rate via a Slider
Slider has stop points (0%, 10%, 12%, 15%, 20%, 25%, 30%, 50%);
i.e. you don't get 44%, which doesn't make sense.
Slider animates automatically between points.
. View bill, tip rate, tip amount, geand total.
. Two page app (read below)
* I didn't use storyboard as I don't like .NIB files either.
I like to see all logic & design in my code files.
Therefore view implementations are kinda custom.
* I skipped to watch the Swift version of TipCalculator (was not intentional)
Therefore, my UI might look somehow different what instructor has done.
- See EasyTip.gif in the root folder for the LiceCap
|
C
|
UTF-8
| 1,355
| 3.03125
| 3
|
[] |
no_license
|
#include "gbk.h"
/**
*findd - finds the number occurance of tof in str
*@str: string to be searched
*@tof: string to fid
*Return: the number of times teh delimeter ocures
*/
int findd(char *str, char *tof)
{
char *tokenized = NULL, *new = NULL;
int i = 0;
if (_strlen(tof) > _strlen(str))
return (0);
new = _strdup(str);
tokenized = _strtok(new, tof, 1);
while (tokenized != NULL)
{
i++;
tokenized = _strtok(NULL, tof, 1);
}
free(new);
/*icase tofind is at th end*/
if (_strcmps(str + _strlen(str) - _strlen(tof), tof) == 1)
i++;
return (i - 1);
}
/**
*fnrep - finds and replaces part of a string
*@str: manipulated string (must be malloced)
* this string should also be freed by the caller
*@torep: subset of str to be replaced
*@repwith: string to replace torep
*Return: 0 on sucess and -1 on faliure
*/
int fnrep(char **str, char *torep, char *repwith)
{
char *tokenized = NULL, *tmp, *new = smalloc(1);
int rep = 0, tor = findd(*str, torep), newlen = 0;
tokenized = _strtok(*str, torep, 1);
*new = '\0';
while (tokenized != NULL)
{
newlen = _strlen(new) + _strlen(tokenized) + _strlen(repwith);
tmp = srealloc(new, newlen + 2);
new = tmp;
_strcat(new, tokenized);
if (rep < tor)
_strcat(new, repwith);
rep++, tokenized = _strtok(NULL, torep, 1);
}
free(*str);
*str = new;
return (0);
}
|
Markdown
|
UTF-8
| 860
| 2.734375
| 3
|
[] |
no_license
|
bulk_ttl_update
======================
An example script that that updates the TTL value for a list of hostnames. The input is through a CSV file containing the zone, owner, record type and new TTL (see example.csv). This script requires the [UltraDNS REST API Client](https://github.com/ultradns/python_rest_api_client) library.
```
$ python bulk_ttl_update.py help
Expected use: python bulk_ttl_update.py username password example.csv [url]
Argument 1:
bulk_ttl_update.py -- The name of your python file
Argument 2:
username -- Username of the UltraDNS account
Argument 3:
password -- UltraDNS account password
Argument 4:
example.csv -- The CSV file containing your update information (see example.csv)
Argument 5 (optional):
url -- The url of your test environment (Example: https://test-restapi.ultradns.com)
```
|
Java
|
UTF-8
| 940
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
import java.util.*;
import static java.lang.Math.*;
public class _10721_BarCodes {
public static void main(String[] args) {
String data = "7 4 3\n7 4 2";
String data2 = "7 1 3";
Scanner scanner = new Scanner(data);
while(scanner.hasNext()){
int n = scanner.nextInt();
int k = scanner.nextInt();
int m = scanner.nextInt();
memo = new long[n + 1][k + 1];
for(int i = 0; i < memo.length; i++){
for(int j = 0; j < memo[0].length; j++){
memo[i][j] = -1;
}
}
System.out.println(count(n, k, m));
}
scanner.close();
}
static long[][] memo;
static long count(int n, int k, int m){
if(k == 1 && n > 0 && n <= m) return 1;
if(k == 1 && (n == 0 || n > m)) return 0;
if(memo[n][k] != -1) return memo[n][k];
long totalCount = 0;
for(int i = 1; i <= m; i++){
if(i <= n){
totalCount += count(n - i, k - 1, m);
}
}
return memo[n][k] = totalCount;
}
}
|
TypeScript
|
UTF-8
| 3,000
| 3.578125
| 4
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/**
* MHub Message class.
*/
/**
* Headers are key-value pairs that carry meta-information
* about a message.
*/
export interface Headers {
[name: string]: string | boolean | number;
}
/**
* Interface describing what a 'raw' object should look like
* if it is to be converted to a Message using `Message.fromObject()`.
*/
export interface MessageLike {
topic: string;
data?: any;
headers?: Headers;
}
/**
* Message to be sent or received over MHub network.
*/
export class Message {
/**
* Create a Message object from a plain object, by taking its topic, data and
* headers properties.
*
* Note that the data is not deep-cloned.
*
* @param o Input object. Must at least contain a `.topic` property.
* @return New `Message` instance, with given topic, same data, and clone of headers.
*/
public static fromObject(o: MessageLike): Message {
if (!o || typeof o !== "object") {
throw new TypeError(
`cannot create message from object, got ${typeof o}`
);
}
return new Message(o.topic, o.data, o.headers);
}
/**
* Topic of message.
* Can be used to determine routing between pubsub Nodes.
*/
public topic: string;
/**
* Optional message data, can be null.
* Must be JSON serializable.
*/
public data: any;
/**
* Optional message headers.
*/
public headers: Headers;
/**
* Construct message object.
*
* Note: headers are cloned, but data is NOT cloned, so don't change data after you've
* passed it to the pubsub framework!
*/
constructor(topic: string, data?: any, headers?: Headers) {
this.topic = topic;
this.data = data;
this.headers = { ...headers }; // clone
}
/**
* Perform a shallow clone of the message.
*
* I.e. the new message will share the same `data` as the source message,
* so be careful when the data is an object: making changes to it will be
* reflected in the old and new message.
*
* The headers (if any) are cloned into a new headers object.
*
* @return New message with same topic, same data and shallow clone of headers.
*/
public clone(): Message {
return new Message(this.topic, this.data, this.headers);
}
/**
* Validate correctness of message properties, e.g. that topic is a string,
* and header is either undefined or key-values.
*/
public validate(): void {
if (typeof this.topic !== "string") {
throw new TypeError(
`invalid topic: expected string, got ${typeof this.topic}`
);
}
const headers = this.headers;
if (headers !== undefined && typeof headers !== "object") {
throw new TypeError(
`invalid headers: expected object or undefined, got ${typeof headers}`
);
}
for (const key in headers) {
if (!headers.hasOwnProperty(key)) {
continue;
}
const t = typeof headers[key];
if (t !== "string" && t !== "boolean" && t !== "number") {
throw new TypeError(
`invalid headers: expected string, boolean or number for header '${key}', got ${t}`
);
}
}
}
}
export default Message;
|
Java
|
UTF-8
| 523
| 2.09375
| 2
|
[] |
no_license
|
package com.github.feedly.util;
import android.content.Context;
import com.github.feedlyclient.R;
public class GetFeedlyCategories extends WebApiRequest {
public GetFeedlyCategories(Context context, String categoryName, String numberFeeds)
{
super(context.getResources().getString(R.string.feedly_api_url), "GET", context);
setMethod(R.string.feedly_api_get_categories);
addParam(R.string.feedly_api_get_categories_param, categoryName);
addParam(R.string.feedly_api_get_categories_number, numberFeeds);
}
}
|
Java
|
UTF-8
| 8,653
| 2.671875
| 3
|
[] |
no_license
|
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class View {
/** The label array */
private String[] labelArr;
/** The search button. */
private JButton searchButton;
/** The main frame. */
private JFrame mainFrame;
/** The main panel. */
private JPanel mainPanel;
/** The summoner text field. */
private JTextField summonerTextField;
/** The summoner name label. */
private JLabel summonerNameLabel;
/** The server location. */
private JTextField serverLocation;
/** The server location label. */
private JLabel serverLocationLabel;
/** The game number. */
private JLabel[] gameNumber;
/** The blank fields. */
private JTextField[] blankFields;
/** The count. */
private int count;
/** The summoner ID. */
private int summonerID;
/** The champion ID. */
private int championID;
/** The kills. */
private int kills;
/** The deaths. */
private int deaths;
/** The assists. */
private int assists;
/** The team color ID. */
private int teamColorID;
/** The minions killed. */
private int minionKills;
/** The neutral minions killed. */
private int neutralMinions;
/** The kills/deaths/assists in string form. */
private String kda;
/** The champion name. */
private String championName;
/** The sub game type. */
private String subType;
/** The game type. */
private String gameType;
/** The win or loss. */
private String winLoss;
/** The team color. */
private String teamColor;
/** The server that is played on. */
private String server;
/**
* Main window.
*/
public void mainWindow() {
count = 0;
gameNumber = new JLabel[10];
blankFields = new JTextField[70];
for (int i = 0; i < 70; i++) {
blankFields[i] = new JTextField();
blankFields[i].setEditable(false);
blankFields[i].setBorder(javax.swing.BorderFactory.createEmptyBorder());
}
// mainPanel is the panel that contains everything with the gui
mainFrame = new JFrame("League of Legends Summoner Search");
mainPanel = new JPanel();
mainFrame.setLayout(new FlowLayout());
mainPanel.setLayout(new GridLayout(0, 8));
mainPanel.setSize(600, 300);
// Creating the summoner name and server locations text fields and labels
summonerTextField = new JTextField();
summonerNameLabel = new JLabel("Summoner Name");
summonerNameLabel.setSize(1, 1);
serverLocation = new JTextField();
serverLocationLabel = new JLabel("Server Location (e.g., na, eu)");
serverLocationLabel.setSize(1, 1);
searchButton = new JButton("Search for Statistics");
labelArr = new String[] { "Game Type", "Sub Game Type", "Wins/Loss", "Champion Played", "Kills/Deaths/Assists",
"Minion Kills", "Team Color" };
serverLocationLabel = new JLabel("Server Location");
serverLocation = new JTextField();
// adding to the main panel
mainPanel.add(new JLabel(" "));
mainPanel.add(serverLocationLabel);
mainPanel.add(serverLocation);
mainPanel.add(new JLabel(" "));
mainPanel.add(summonerNameLabel);
mainPanel.add(summonerTextField);
mainPanel.add(new JLabel(" "));
mainPanel.add(searchButton);
mainPanel.add(new JLabel(" "));
// for loop to add the labels of summoner info searched
for (int i = 0; i < labelArr.length; i++) {
mainPanel.add(new JLabel(labelArr[i]));
}
for (int i = 0; i < 10; i++) {
gameNumber[i] = new JLabel("Game " + (i + 1));
mainPanel.add(gameNumber[i]);
for (int j = 0; j < 7; j++) {
mainPanel.add(blankFields[count]);
count++;
}
}
// making the frame visible
mainPanel.setOpaque(false);
mainFrame.add(mainPanel);
mainFrame.setSize(750, 750);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setVisible(true);
searchButton.addActionListener(new searchButtonHandler());
}
/**
* Read URL.
*
* @param webservice
* string
* @return a string
* @throws Exception
*/
public String readURL(String webservice) throws Exception {
URL oracle = new URL(webservice);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result + inputLine;
}
in.close();
return result;
}
/**
* The Class searchButtonHandler.
*/
// Action handler to do all of the work for the code.
public class searchButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
String summoner = summonerTextField.getText();
summoner = summoner.replaceAll("\\s+", "").toLowerCase();
server = serverLocation.getText();
try {
String JSonString = readURL("https://" + server + ".api.pvp.net/api/lol/" + server
+ "/v1.4/summoner/by-name/" + summoner + "?api_key=47ed153d-9890-427c-99e9-0679cffd651d");
JSONObject summName = JSONObject.fromObject(JSonString);
JSONObject summonerName = (JSONObject) summName.get(summoner);
summonerID = (int) summonerName.get("id");
String JSonRecentGames = readURL(
"https://" + server + ".api.pvp.net/api/lol/" + server + "/v1.3/game/by-summoner/" + summonerID
+ "/recent?api_key=47ed153d-9890-427c-99e9-0679cffd651d");
JSONObject recentGames = JSONObject.fromObject(JSonRecentGames);
JSONArray recentGameStats = recentGames.getJSONArray("games");
count = 0;
for (int games = 0; games < 10; games++) {
// Changing the most recent game throughout the for loop
JSONObject game = recentGameStats.getJSONObject(games);
championID = game.getInt("championId");
// Finding the game mode that was played during this game
gameType = game.getString("gameMode");
blankFields[count].setText(gameType);
count++;
// Finding the game mode that was played during this game
subType = game.getString("subType");
blankFields[count].setText(subType);
count++;
JSONObject gameStats = game.getJSONObject("stats");
// Finding if the summoner won or lost the game
winLoss = gameStats.getString("win");
if (winLoss == "true") {
winLoss = "Victory";
} else {
winLoss = "Defeat";
}
blankFields[count].setText(winLoss);
count++;
// Finding the name and the ID of the champion played in the
// game
String JSonChampName = readURL("https://global.api.pvp.net/api/lol/static-data/" + server
+ "/v1.2/champion/" + championID + "?api_key=47ed153d-9890-427c-99e9-0679cffd651d");
JSONObject champion = JSONObject.fromObject(JSonChampName);
championName = champion.getString("name");
championName += " " + champion.getString("title");
blankFields[count].setText(championName);
count++;
// Finding the kills, deaths, and assists in this game
if (gameStats.has("championsKilled"))
kills = gameStats.getInt("championsKilled");
else
kills = 0;
if (gameStats.has("numDeaths"))
deaths = gameStats.getInt("numDeaths");
else
deaths = 0;
if (gameStats.has("assists"))
assists = gameStats.getInt("assists");
else
assists = 0;
kda = kills + "/" + deaths + "/" + assists;
blankFields[count].setText(kda);
count++;
// Finding the number of minions killed in this game
if (gameStats.has("minionsKilled"))
minionKills = gameStats.getInt("minionsKilled");
else
minionKills = 0;
if (gameStats.has("neutralMinionsKilled")) {
neutralMinions = gameStats.getInt("neutralMinionsKilled");
minionKills += neutralMinions;
blankFields[count].setText(minionKills + "");
count++;
} else {
neutralMinions = 0;
blankFields[count].setText(minionKills + "");
count++;
}
// Finding the team color of the player during this game
teamColorID = game.getInt("teamId");
if (teamColorID == 100) {
teamColor = "Blue";
} else {
teamColor = "Red";
}
blankFields[count].setText(teamColor);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
Python
|
UTF-8
| 255
| 2.875
| 3
|
[] |
no_license
|
import collections
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = [0] * (n + 1)
for i in range(n):
b[i + 1] = b[i] + a[i]
d = collections.Counter(x % m for x in b)
ans = sum(v * (v - 1) // 2 for v in d.values())
print(ans)
|
Shell
|
UTF-8
| 566
| 3.6875
| 4
|
[] |
no_license
|
#!/bin/sh
# HDMI switcher:
# 80: PIO10.0 - S1 SoC
# 81: PIO10.1 - S2 HDMI in2
# 82: PIO10.2 - S3 HDMI in3
usage() {
echo "Usage:"
echo "${0##*/} input"
echo -e "\tvalid inputs:"
echo -e "\t\t0 - from SoC"
echo -e "\t\t1 - hdmi in 2"
echo -e "\t\t2 - hdmi in 3"
}
if [ -z "$1" ]; then
usage
exit 1
fi
if [ "$1" -lt 0 -o "$1" -gt 2 ]; then
usage
exit 2
fi
cd /sys/class/gpio/
for gpio in 80 81 82; do
if [ ! -e gpio${gpio} ]; then
echo $gpio >export
fi
echo out >gpio${gpio}/direction
echo 0 >gpio${gpio}/value
done
echo 1 >gpio8$1/value
|
JavaScript
|
UTF-8
| 6,158
| 2.515625
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import {
Form, Select, Input, Button,
} from 'antd';
import styled from 'styled-components';
import axios from 'axios';
const { TextArea } = Input;
const Option = Select.Option;
const Container = styled.div`
margin: 0 auto;
width: 50%;
text-align:center;
`;
class Admin extends Component{
state = {
name: null,
recept: null,
img_address: null,
time_id: null,
type_id: null,
user_type_id: null
}
handleNameChange = (event) =>{
this.setState({ name: event.target.value })
}
handleReceptChange = (event) =>{
this.setState({ recept: event.target.value })
}
handleImgChange = (event) =>{
this.setState({ img_address: event.target.value })
}
handleTimeChange = (event) =>{
console.log("event: ", event)
this.setState({ time_id: event })
}
handleTypeChange = (event) =>{
console.log("event: ", event)
this.setState({ type_id: event })
}
handleUserTypeChange = (event) =>{
console.log("event: ", event)
this.setState({ user_type_id: event })
}
handleSubmit = (e) => {
e.preventDefault();
const { name, recept, img_address, time_id ,type_id,user_type_id } = this.state;
const time = parseInt(time_id)
const type = parseInt(type_id)
const userType = parseInt(user_type_id)
const tamaq = {
name: name,
recept: recept,
img_address: img_address,
time_id: time,
type_id: type,
user_type_id: userType,
}
console.log(tamaq);
axios.post('http://localhost/back/api/create_food.php', tamaq)
.then(res => {
console.log(res);
this.props.history.push('/admin')
})
.catch(res => {
console.log('Tamaq add is failed ', res)
})
}
render(){
const { getFieldDecorator } = this.props.form;
return (
<div>
<Container>
<Form labelCol={{ span: 5 }} wrapperCol={{ span: 12 }} onSubmit={this.handleSubmit}>
<h4>Добавить блюдо</h4><br/>
<Form.Item label="Название:">
{getFieldDecorator('name', {
rules: [{ required: true, message: 'Please input your note!' }],})(
<Input name="name" onChange={this.handleNameChange}/> )}
</Form.Item>
<Form.Item label="Рецепт:">
{getFieldDecorator('recept', {
rules: [{ required: true, message: 'Please input your note!' }],})(
<TextArea placeholder="" name="recept" autosize={{ minRows: 2, maxRows: 6 }} onChange={this.handleReceptChange}/> )}
</Form.Item>
<Form.Item label="Изображение (url):">
{getFieldDecorator('img_address', {
rules: [{ required: true, message: 'Please input your note!' }],})(
<Input name="img_address" onChange={this.handleImgChange}/>)}
</Form.Item>
<Form.Item label="Время:">
<Select
placeholder="Выберите время"
name="time_id"
onChange={this.handleTimeChange}
>
<Option value="1">Завтрак</Option>
<Option value="2">Обед</Option>
<Option value="3">Ужин</Option>
<Option value="4">Поздний завтрак</Option>
<Option value="5">Полдник</Option>
<Option value="6">Поздний ужин</Option>
</Select>
</Form.Item>
<Form.Item label="Тип еды:">
<Select
placeholder="Выберите тип еды"
name="type_id"
onChange={this.handleTypeChange}
>
<Option value="1">Суп</Option>
<Option value="2">Жаренное</Option>
<Option value="3">Тушонное</Option>
<Option value="4">Напитки</Option>
<Option value="5">Салаты</Option>
<Option value="6">Кашы</Option>
</Select>
</Form.Item>
<Form.Item label="Тип пользователя:">
<Select
placeholder="Выберите тип пользователя"
name="user_type_id"
onChange={this.handleUserTypeChange}
>
<Option value="1">Спорт</Option>
<Option value="2">Диета</Option>
<Option value="3">Беременная</Option>
<Option value="4">Больные</Option>
<Option value="5">Ежедневные</Option>
</Select>
</Form.Item>
<Form.Item wrapperCol={{ span: 12, offset: 5 }}>
<Button type="submit" htmlType="submit">Submit</Button>
</Form.Item>
</Form>
</Container>
</div>
)
}
}
export default Form.create()(Admin);
|
C++
|
UTF-8
| 666
| 3.03125
| 3
|
[] |
no_license
|
#include "iostream"
// #include "algorithm"
#include "math.h"
using namespace std;
int main(){
int n;
cout<<"\nEnter number of observations : ";
cin>>n;cout<<endl;
float x[n+1],x1 =0,mean=0;
x[0]=0;
cout<<"Enter X :";
for (int i = 1; i <=n; i++)
{
/* code */
cin>>x[i];
x1+=x[i];
}
cout<<endl;
mean = x1/(float)n;
//now find absolute deviation
float ab[n+1],absDev=0;
ab[0]=0;
for (size_t i = 1; i <=n; i++)
{
absDev += abs(x[i]-mean);
}
float MeanDev = absDev/n;
cout<<"Mean Deviation is : "<<MeanDev<<endl;
return 0;
}
|
C#
|
UTF-8
| 3,000
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Reactive.Disposables;
using System.Reactive.Subjects;
using System.Text;
namespace slimCODE.Models
{
/// <summary>
/// Holds a list of <see cref="ObservableValue{T}"/> accessible by name.
/// </summary>
public class ObservableValues : IObservable<string>, IDisposable
{
private readonly ObservableValues _alternateValues;
private readonly Dictionary<string, Func<object>> _valueGetters = new Dictionary<string, Func<object>>();
private readonly Dictionary<string, Action<object>> _valueSetters = new Dictionary<string, Action<object>>();
private Func<string, object> _designTimeHandler;
private CompositeDisposable _subscriptions = new CompositeDisposable();
private readonly Subject<string> _propertyChanged = new Subject<string>();
public ObservableValues(Func<string, object> designTimeHandler = null)
{
_designTimeHandler = designTimeHandler;
}
public ObservableValues(ObservableValues alternateValues, Func<string, object> designTimeHandler = null)
: this(designTimeHandler)
{
_alternateValues = alternateValues;
}
public void AddValue<T>(string name, ObservableValue<T> observableValue)
{
_valueGetters.Add(name, () => observableValue.Latest);
_valueSetters.Add(name, value => observableValue.OnNext((T)value));
_subscriptions.Add(observableValue.Subscribe(_ => _propertyChanged.OnNext(name)));
}
public object GetValue(string name)
{
if ((_designTimeHandler != null) && Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
return _designTimeHandler(name);
}
if (_valueGetters.TryGetValue(name, out Func<object> getter))
{
return getter();
}
else if (_alternateValues != null)
{
return _alternateValues.GetValue(name);
}
else
{
//Logs.UseLogger(l => l.ReportError($"Bound property {name} not found."));
return null;
}
}
public void SetValue(string name, object value)
{
if (_valueSetters.TryGetValue(name, out Action<object> setter))
{
setter(value);
}
else if (_alternateValues != null)
{
_alternateValues.SetValue(name, value);
}
else
{
throw new ArgumentException("Unknown value name.");
}
}
public IDisposable Subscribe(IObserver<string> observer)
{
return _propertyChanged.Subscribe(observer);
}
public void Dispose()
{
_propertyChanged.Dispose();
_subscriptions.Dispose();
}
}
}
|
Markdown
|
UTF-8
| 3,259
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
# Game of Drones
Conquer your enemy!
## **Synopsis**
In Game of Drones there are two players trying to conquer each other.
Players take turns to make their move, choosing Paper, Rock or Scissors. Each move beats another, just like the game “Paper, rock, scissors”.
Like so:
* Paper beats Rock
* Rock beats scissors
* Scissors beat Paper
### **Note**: The first player to beat the other player 3 times wins the battle.
<table>
<tr>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen1.png">
</td>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen6.png">
</td>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen2.png">
</td>
</tr>
<tr>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen3.png">
</td>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen4.png">
</td>
<td>
<img width="242px" height="411px" src="FrontEnd/gh-pages/images/screen5.png">
</td>
</tr>
</table>
## **Installation**
* Install **[Node.js](https://nodejs.org)**.
* Install **[MongoDB](https://www.mongodb.com/)**.
### **1. FrontEnd**:
* To run the application on browser, you can execute the following commands using CLI:
- npm install
- gulp
- ionic serve
* To run the application on mobile devices via USB, you can execute the following commands using CLI:
**On Android**
- ionic platform add android
- ionic run android
**On iOS (Mac)**
- ionic platform add ios
- ionic run ios
*To debug the application, you can use some tools:*
- **[GapDebug](https://www.genuitec.com/products/gapdebug/)**
- **[Ionic View App](http://view.ionic.io/)**
### **2. BackEnd**:
* To run the application using CLI, you can execute the following commands:
- npm install
- npm start
*To debug the application, you can use:*
- **[Visual Studio Code](https://code.visualstudio.com/)**
## Template Structure
Path | Explanation
---------- | -------------
`./app/img/` | Images in the app.
`./app/js/` | Scripts (Controllers, Services, Directives, etc).
`./app/scss/` | The styles of the app using Sass.
`./app/templates/` | Views in the app.
`./app/index.html` | The init page.
`./www/css/` | Other css styles like **[Animate.css](https://daneden.github.io/animate.css/)**, etc.
`./www/lib` | Scripts downloaded using bower.
## Tests
**1. Unit Tests With Jasmine & Karma**:
To run the unit tests, you can execute the following commands using CLI:
* cd tests
* karma start unit-tests.conf.js
**2. End-To-End Tests With Jasmine & Protractor**:
* To run the E2E tests on Chrome, you can execute the following commands using CLI:
- ionic serve --nobrowser
* Using another command line
- cd tests
- protractor e2e-tests.conf.js
## Supporting
I believe in Unicorns 🦄
Support [me](http://www.paypal.me/jdnichollsc/2), if you do too.
## Happy coding
Made with <3
<img width="150px" src="https://github.com/jdnichollsc/jdnichollsc.github.io/blob/master/assets/nicholls.png?raw=true" align="right">
|
Rust
|
UTF-8
| 860
| 2.609375
| 3
|
[] |
no_license
|
use crate::node::Node;
use crate::node_descriptor::{NodeDescriptor, NodeId};
use crate::slots::node_slot::NodeSlot;
use std::fmt;
pub struct RootNode {
descriptor: NodeDescriptor,
pub slot: NodeSlot,
}
impl Node for RootNode {
fn new(id: NodeId) -> RootNode {
let slot = NodeSlot::new("all_nodes");
let slots = vec![slot.slot.clone()];
let providers = vec![];
RootNode {
descriptor: NodeDescriptor::new(id, "root", slots, providers),
slot,
}
}
fn descriptor(&self) -> &NodeDescriptor {
&self.descriptor
}
fn descriptor_mut(&mut self) -> &mut NodeDescriptor {
&mut self.descriptor
}
fn run(&mut self) {}
}
impl fmt::Debug for RootNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.descriptor.fmt(f)
}
}
|
JavaScript
|
UTF-8
| 2,094
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
var albnam="";
$(document.body).on('click', '#createAlbum', function(){
albname = $("#albumName").val();
if(albname == ""){
alert("please enter albumName");
}
else {
$("#txt").css("display", "none");
$("#albumName").css("display", "none");
$("#createAlbum").css("display", "none");
$("#albtxt").css("display", "block");
$("#outer").css("display", "block");
$("#img-prev").css("display", "block");
$("#thumbContainer").css("display", "block");
$("#albname").text(albname);
}
});
var i=0;
var file;
$('#uploadBtn').on('click',function(){
if(i==9){
alert("Maximum 9 Pictures can be added to an album");
}else {
$("#fileUpload").trigger("click");
}
});
$("#fileUpload").change(function(event) {
file = event.target.files[0];
sendAlbName();
});
function sendAlbName(){
$.ajax({
url: "/albumname",
type: "POST",
data : {
'albname' : albname,
'imgno' : i
},
success:function(data){
console.log(data);
sendFile();
}
});
}
function sendFile(){
var formData = new FormData();
var xhr = new XMLHttpRequest();
formData.append("userFile", file, file.name);
//formData.set("albumname", albname);
//console.log(formData);
xhr.open("POST", "/api/file", true);
//xhr.setRequestHeader('x-auth', X_PID_AUTH);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
thumb();
i+=1;
if (xhr.status === 200) {
console.log(xhr.responseText);
if(xhr.responseText.message == 'success'){
// alert('Profile photo uploaded');
}
} else {
console.error(xhr.statusText);
alert('Error uploading file');
}
}
};
xhr.send(formData);
}
function thumb(){
var thumbs = $(`<div id="thumb-${i}" class="img-prev"></div>`);
$('#thumbContainer').append(thumbs);
$(`#thumb-${i}`).css('background-image', `url('./Uploads/sayak_${albname}_img_${i}.png')`);
}
|
Markdown
|
UTF-8
| 1,016
| 3.15625
| 3
|
[] |
no_license
|
---
layout: page
title: Meta-data manipulation
comments: true
permalink: /meta-data-manipulation/
---
# Inspecting data structures
The _glimpse()_ function is a great alternative for the _str()_ function: is shows data-types in a compacter way, and the screen size is taken into consideration for the output.
# Column renaming
After importing files I usually rename the columns so they adhere to the in-script conventions, to prevent messy data joining and searching for column names forever. You can rename all column names at once by using:
```r
names(table) <- c("column_a", "column_b", "column_c", "column_d", "column_e")
```
Renaming a single column or select columns using the **dplyr** library:
```r
rename(mtcars, spam_mpg = mpg, cylinders = cyl)
```
# Re-ordering columns
You can reorder all columns by _select_ing them one by one, but by making use of the _everything()_ function you can put all columns, except the re-ordered in at once:
```r
mtcars %<>% select(cyl, disp, hp, everything())
```
|
Java
|
UTF-8
| 382
| 2.1875
| 2
|
[] |
no_license
|
package com.mindlin.jjsbridge.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark an object to hold a generated prototype
* @author wfeehery17
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface JSPrototype {
}
|
Java
|
UTF-8
| 4,242
| 1.90625
| 2
|
[] |
no_license
|
package com.example.abodimazen.ChildCare;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.abodimazen.fahad.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BookingDates extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking_dates);
spinner = findViewById(R.id.spinner2);
final Button save = findViewById(R.id.saveDate);
final List<String> idlist = new ArrayList<>();
final List<Integer> priorityList = new ArrayList<>();
final List<String> list = new ArrayList<>();
//list.add("Choose a Date");
db.collection("BookingDates").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.get("Date").toString());
priorityList.add(document.getLong("priority").intValue());
idlist.add(document.getId());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<>(BookingDates.this, android.R.layout.simple_spinner_item
,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, final int i, long l) {
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id = idlist.get(i);
int priority = priorityList.get(i);
String ddate = list.get(i);
Intent b = getIntent();
final Bundle c = b.getExtras();
String n = (String) c.get("id");
Map<String, Object> date = new HashMap<>();
date.put("date", ddate);
date.put("datePriority", priority);
date.put("dateStatus","yes");
db.collection("Child").document(n).update(date);
db.collection("BookingDates").document(id).delete();
Intent i = new Intent(BookingDates.this, Plan.class);
i.putExtra("id", n);
startActivity(i);
}
});
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} else {
Toast.makeText(BookingDates.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
Java
|
UTF-8
| 3,355
| 2.59375
| 3
|
[] |
no_license
|
package util;
import Models.Alarm;
import Models.Event;
import Models.EventParticipant;
import Models.Group;
import interfaces.PersistencyInterface;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
public class Persistency extends PersistencyGetMethods implements PersistencyInterface {
public Persistency() {
query = new DBQuery();
}
public void closeConnection(){
if (query != null)
query.close();
System.out.println("closed.");
}
@Override
public int requestLogin(String username, String password) {
int id = -1;
try {
id = query.requestLogin(username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return id;
}
@Override
public boolean addEvent(Event event, ArrayList<Integer> participantIDs) {
boolean success = false;
try {
success = query.addEvent(event, participantIDs);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
@Override
public boolean removeEvent(Event event) {
boolean success = false;
try {
query.removeEvent(event);
success = true;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
@Override
public void changeEvent(Event event) {
try {
query.updateEvent(event);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
@Override
public boolean addEventParticipant(int eventID, int participantID) {
boolean success = false;
try {
success = query.addEventParticipant(eventID, participantID);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
@Override
public void removeEventParticipant(int eventID, int participantID) {
try {
query.removeEventParticipant(eventID, participantID);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
@Override
public void changeEventParticipantResponse(EventParticipant participant) {
try {
query.changeEventParticipant(participant);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
@Override
public boolean addAlarm(EventParticipant participant, Alarm alarm) {
boolean success = false;
try {
success = query.addAlarm(participant, alarm);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
@Override
public boolean removeAlarm(Alarm alarm) {
boolean success = false;
try {
success = query.removeAlarm(alarm);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
@Override
public boolean changeAlarm(Alarm alarm) {
boolean success = false;
try {
success = query.changeAlarm(alarm);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return success;
}
}
|
Java
|
UTF-8
| 1,280
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package application.view;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class Visualisointi extends Canvas {
@FXML
private Canvas canvas;
private GraphicsContext gc;
double i = 20;
double j = 20;
public Visualisointi(int w, int h) {
super(w, h);
gc = this.getGraphicsContext2D();
tyhjennaNaytto();
}
public void tyhjennaNaytto() {
System.out.println("Näyttö tyhjennettiin");
gc.setFill(Color.GREEN);
}
public void piirraPallo(int x, int y) {
gc.setFill(Color.DARKGOLDENROD);
gc.fillOval(x,y,10,10);
}
public void avaaKassa(int x, int y) {
gc.setFill(Color.BLACK);
gc.fillOval(x-2,y-2,24,24);
gc.setFill(Color.GREEN);
gc.fillOval(x,y,20,20);
}
public void varaaKassa(int x, int y) {
gc.setFill(Color.BLACK);
gc.fillOval(x-2,y-2,24,24);
gc.setFill(Color.YELLOW);
gc.fillOval(x,y,20,20);
}
public void suljeKassa(int x, int y) {
gc.clearRect(x, y, 20, 20);
}
public void pyyhiPallo(int x, int y) {
gc.clearRect(x, y, 10, 10);
}
public void uusiAsiakas() {
gc.setFill(Color.BROWN);
gc.fillOval(i,j,10,10);
i = (i + 12) % this.getWidth();
j = (j + 12) % this.getHeight();
}
}
|
Java
|
UTF-8
| 1,032
| 3.0625
| 3
|
[] |
no_license
|
package cars.truck_auto;
public class Kia extends TruckAuto {
private String countryOfProduction;
private String model;
public Kia(String engine, int liftingCapacity, String countryOfProduction, String model) {
super(engine, liftingCapacity);
this.countryOfProduction = countryOfProduction;
this.model = model;
}
public String getCountryOfProduction() {
return countryOfProduction;
}
public void setCountryOfProduction(String countryOfProduction) {
this.countryOfProduction = countryOfProduction;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@Override
public String getInfo(){
return "Грузовой автомобиль " + getModel()+ " двигатель " + super.getEngine() +
" грузоподъемность "+ super.getLiftingCapacity() + " страна производитель "+ getCountryOfProduction();
}
}
|
TypeScript
|
UTF-8
| 108
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
export const toTitleCase = (title: string) => {
return title.charAt(0).toUpperCase() + title.slice(1);
};
|
Java
|
UTF-8
| 496
| 2.109375
| 2
|
[] |
no_license
|
package com.nicloud.workflowclient.tasklist.main;
import com.nicloud.workflowclient.data.data.Task;
/**
* Created by logicmelody on 2016/1/29.
*/
public class TaskListItem {
public Task task;
public boolean showDueDate;
public boolean showDueDateUnderline;
public TaskListItem(Task task, boolean showDueDate, boolean showDueDateUnderline) {
this.task = task;
this.showDueDate = showDueDate;
this.showDueDateUnderline = showDueDateUnderline;
}
}
|
Shell
|
UTF-8
| 3,047
| 3.390625
| 3
|
[] |
no_license
|
#!/bin/bash
function pause(){
read -p "Press [Enter] to continue"
}
export UNAME=`uname`
echo Welcome to the opportunity to free your Thrive!
echo Originally developed by TYBAR at the Thrive forums,
echo this tool pushes several files onto your device,
echo then flashes the unlocked bootloader, then
echo installs the SU binary and Superuser app.
echo I am not responsible if you break your tablet, you
echo were the one that ran this. In the off chance that
echo something does happen, please PM me, pio_masaki,
echo or dalepl for help. Also, I am completely not
echo responsible for pixies flying out of your HDMI
echo port, either. \;\)
echo Please connect your tablet now, or exit to keep
echo a full stock Thrive. Also, either be plugged in,
echo or have at least 30% battery.
pause()
echo At this time, a screen will pop up on your device
echo asking for a restore. Press it. A whole bunch of
echo errors will appear on your comupter. Those are
echo also normal. Don\'t panic.
pause()
cd roottool
$UNAME/adb wait-for-device
$UNAME/adb restore fakebackup.ab
$UNAME/adb shell "while ! ln -s /data/local.prop /data/data/com.android.settings/a/file99; do :; done"
$UNAME/adb reboot
$UNAME/adb wait-for-device
echo Pushing unlocked bootloader....
$UNAME/adb push blob /mnt/sdcard/blob
echo Pushing CWM...
adb push recovery.img /mnt/sdcard/recovery.img
echo Flashing unlocked bootloader....
$UNAME/adb shell dd if=/mnt/sdcard/blob of=/dev/block/mmcblk0p6
echo Flashing rootable boot image...
$UNAME/adb shell dd if=/mnt/sdcard/boot.img of=/dev/block/mmcblk0p2
echo Flashing CWM....
$UNAME/adb shell dd if=/mnt/sdcard/recovery.img of=/dev/block/mmcblk0p1
echo Rebooting to take effect...
adb reboot
$UNAME/adb wait-for-device
echo Pushing files....
$UNAME/adb wait-for-device
$UNAME/adb shell "mkdir /data/x-root"
$UNAME/adb shell "mkdir /data/x-root/bin"
$UNAME/adb push busybox /data/x-root/bin/busybox
$UNAME/adb push su /data/x-root/bin/su
echo Setting up BusyBox and SU....
adb shell "chmod 755 /data/x-root/bin/busybox"
echo Mounting /System
$UNAME/adb remount
echo Pushing su binary into system....
$UNAME/adb shell "./busybox cp /data/x-root/bin/su /dev/tmpdir/bin/"
$UNAME/adb shell "chmod 4555 /dev/tmpdir/bin/su"
$UNAME/adb shell "umount /dev/tmpdir"
$UNAME/adb shell sync
echo Editing local.prop. for stable use....
$UNAME/adb shell "echo "ro.kernel.qemu=0" > /data/local.prop"
$UNAME/adb reboot
echo Now we need to install \"SuperUser\" from the Play store.
echo Free version is fine.
echo Please run it in order for root to work. We need
echo it to continue.
echo If it does not install, please let us know on the
echo Thrive forums.
echo If you do continue, make sure that both your computer
echo and tablet don\'t power off. What we are doing, if
echo interrupted, could fry your tablet permanently.
pause()
$UNAME/adb reboot
echo Grats, should now be running a fully open system.
echo Flash away!
echo Credit goes to pio_masaki, Walking_corpse, and AmEv for
echo testing and building this script.
pause
|
C
|
UTF-8
| 4,381
| 3.40625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include "image.h"
float get_pixel(image im, int x, int y, int c)
{
// TODO Fill this in
x = (x < 0) ? 0 : ((x >= im.w) ? im.w - 1 : x);
y = (y < 0) ? 0 : ((y >= im.h) ? im.h - 1 : y);
return im.data[x + y*im.w + c*im.w*im.h];
}
void set_pixel(image im, int x, int y, int c, float v)
{
// TODO Fill this in
if (x >= 0 && x < im.w && y >= 0 && y < im.h) {
im.data[x + y*im.w + c*im.w*im.h] = v;
}
}
image copy_image(image im)
{
image copy = make_image(im.w, im.h, im.c);
// TODO Fill this in
memcpy(copy.data, im.data, im.w*im.h*im.c*sizeof(float));
return copy;
}
image rgb_to_grayscale(image im)
{
assert(im.c == 3);
image gray = make_image(im.w, im.h, 1);
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
float r = get_pixel(im, j, i, 0);
float g = get_pixel(im, j, i, 1);
float b = get_pixel(im, j, i, 2);
set_pixel(gray, j, i, 0, 0.299*r+0.587*g+0.114*b);
}
}
return gray;
}
void shift_image(image im, int c, float v)
{
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
set_pixel(im, j, i, c, get_pixel(im, j, i, c)+v);
}
}
}
void clamp_image(image im)
{
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
for (int k = 0; k < im.c; k++) {
float value = get_pixel(im, j, i, k);
value = (value < 0) ? 0 : ((value > 1) ? 1: value);
set_pixel(im, j, i, k, value);
}
}
}
}
// These might be handy
float three_way_max(float a, float b, float c)
{
return (a > b) ? ( (a > c) ? a : c) : ( (b > c) ? b : c) ;
}
float three_way_min(float a, float b, float c)
{
return (a < b) ? ( (a < c) ? a : c) : ( (b < c) ? b : c) ;
}
void rgb_to_hsv(image im)
{
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
float r = get_pixel(im, j, i, 0);
float g = get_pixel(im, j, i, 1);
float b = get_pixel(im, j, i, 2);
float V = three_way_max(r, g, b);
float m = three_way_min(r, g, b);
float C = V - m;
float S = V == 0 ? 0 : C / V;
float h = (V == r) ? (g - b)/C : ((V == g) ? (b - r)/C+2 : (r - g)/C+4);
float H = (C == 0) ? 0 : ((h < 0) ? h/6+1 : h/6);
set_pixel(im, j, i, 0, H);
set_pixel(im, j, i, 1, S);
set_pixel(im, j, i, 2, V);
}
}
}
void hsv_to_rgb(image im)
{
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
float H = get_pixel(im, j, i, 0)*360;
float S = get_pixel(im, j, i, 1);
float V = get_pixel(im, j, i, 2);
float h = H/60;
float C = V*S;
float X = C*(1-fabs(fmod(h, 2)-1));
float r, g, b;
if (h >= 0 && h <= 1) {
r = C;
g = X;
b = 0;
} else if (h >= 1 && h <= 2) {
r = X;
g = C;
b = 0;
} else if (h >= 2 && h <= 3) {
r = 0;
g = C;
b = X;
} else if (h >= 3 && h <= 4) {
r = 0;
g = X;
b = C;
} else if (h >= 4 && h <= 5) {
r = X;
g = 0;
b = C;
} else if (h >= 5 && h <= 6) {
r = C;
g = 0;
b = X;
} else {
r = 0;
g = 0;
b = 0;
}
float m = V - C;
float R = r + m;
float G = g + m;
float B = b + m;
set_pixel(im, j, i, 0, R);
set_pixel(im, j, i, 1, G);
set_pixel(im, j, i, 2, B);
}
}
}
void scale_image(image im, int c, float v)
{
// TODO Fill this in
for (int i = 0; i < im.h; i++) {
for (int j = 0; j < im.w; j++) {
set_pixel(im, j, i, c, get_pixel(im, j, i, c)*v);
}
}
}
|
C
|
UTF-8
| 710
| 3.46875
| 3
|
[] |
no_license
|
//https://www.interviewbit.com/problems/add-one-to-number/
int* plusOne(int* A, int n1, int *len1) {
int* arr=(int*)malloc(sizeof(int*)*(n1+1));
int i=0;
int carry=1;
for(i=n1-1;i>=0;i--)
{
arr[i+1]=A[i]+carry;
carry=0;
if(arr[i+1]>=10)
{
arr[i+1]=arr[i+1]%10;
carry=1;
}
}
i=0;
if(carry>0)
{
arr[0]=1;
*len1=n1+1;
}
else
{
for(i=0;i<n1;i++)
{
arr[i]=arr[i+1];
}
*len1=n1;
}
i=0;
if(arr[0]==0)
{
for(i=0;i<n1-1;i++)
{
arr[i]=arr[i+1];
}
*len1=n1-1;
}
return arr;
}
|
Java
|
UTF-8
| 1,798
| 2.359375
| 2
|
[] |
no_license
|
package com.example.mystudyapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.mystudyapp.R;
import com.example.mystudyapp.models.FoodMenu;
import com.github.chrisbanes.photoview.PhotoView;
import java.util.List;
public class ImageSlider_Adapter extends RecyclerView.Adapter<ImageSlider_Adapter.MyViewHolder> {
private Context context;
private String[] sliderImage;
public ImageSlider_Adapter(Context context, String[] sliderImage) {
this.context = context;
this.sliderImage = sliderImage;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_image_slider, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.bindSliderImage(sliderImage[position]);
}
@Override
public int getItemCount() {
return sliderImage.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private PhotoView mPhotoView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mPhotoView = itemView.findViewById(R.id.photoView);
}
public void bindSliderImage(String imageURL) {
Glide.with(context)
.load(imageURL)
.into(mPhotoView);
}
}
}
|
JavaScript
|
UTF-8
| 1,607
| 3.390625
| 3
|
[] |
no_license
|
/*
* Constructor function for a WeatherWidget instance.
*
* container_element : a DOM element inside which the widget will place its UI
*
*/
function WeatherWidget(container_element){
//declare the data properties of the object
/**
//declare an inner object literal to represent the widget's UI
//write a function to create and configure the DOM elements for the UI
var _createUI = function(container){
}
*/
//add any other methods required for the functionality
/**
* private method to intialise the widget's UI on start up
* this method is complete
*/
var _initialise = function(container_element){
_createUI(container_element);
}
/*********************************************************
* Constructor Function for the inner WLine object to hold the
* full weather data for a town
********************************************************/
var WLine = function(wtown, woutlook, wmin, wmax){
//declare the data properties for the object
//declare an inner object literal to represent the widget's UI
//write a function to create and configure the DOM elements for the UI
var _createUI = function(container){
}
//Add any remaining functions you need for the object
//_createUI() method is called when the object is instantiated
_createUI();
}; //this is the end of the constructor function for the WLine object
// _initialise method is called when a WeatherWidget object is instantiated
_initialise(container_element);
}
//end of constructor function for WeatherWidget
|
C
|
UTF-8
| 716
| 3.90625
| 4
|
[] |
no_license
|
#include <stdio.h>
int main( void ){
/* Step 1: Create two doubles with values 0.3 and 0.1 */
/* Step 2: Subtract 0.2 from the first double */
/* Step 3: Print both their values and register addresses to stdout using fprintf */
/* Step 4: Write a conditional statement if the two values are equal */
/* Step 5: If true, print "They are equal" and the address of stdout to stdout */
/* using fprintf */
/* Step 6: If false, print "They are not equal" and the address of stderr to stderr */
/* using fprintf */
/* Step 7: After the if-else, print both the values to 23 decimal points */
/* as well as their IEEE 754 values using the %la output specifier */
return 0;
}
|
Java
|
UTF-8
| 283
| 1.65625
| 2
|
[
"MIT"
] |
permissive
|
package dk.kleistsvendsen;
import com.google.inject.AbstractModule;
public class GameClockModule extends AbstractModule {
@Override
protected void configure() {
bind(IGameTimer.class).to(GameTimer.class);
bind(ITicSource.class).to(TicSource.class);
}
}
|
Java
|
UTF-8
| 1,056
| 2.078125
| 2
|
[] |
no_license
|
/**
* 版权声明:lion 版权所有 违者必究 2016
* Copyright: Copyright (c) 2016
*
* @project_name: lion-rpc
* @Title: EndpointFactory.java
* @Package com.alacoder.lion.rpc
* @Description:
* @author jimmy.zhong
* @date 2016年9月23日 上午10:36:40
* @version V1.0
*/
package com.alacoder.lion.rpc;
import com.alacoder.lion.common.extension.Scope;
import com.alacoder.lion.common.extension.Spi;
import com.alacoder.lion.common.url.LionURL;
import com.alacoder.lion.remote.Client;
import com.alacoder.lion.remote.MessageHandler;
import com.alacoder.lion.remote.Server;
/**
* @ClassName: EndpointFactory
* @Description:
* @author jimmy.zhong
* @date 2016年9月23日 上午10:36:40
*
*/
@Spi(scope = Scope.SINGLETON)
public interface EndpointFactory {
Server createServer(LionURL url, MessageHandler messageHandler);
Client createClient(LionURL url, MessageHandler messageHandler);
void safeReleaseResource(Server server, LionURL url);
void safeReleaseResource(Client client, LionURL url);
}
|
Java
|
UTF-8
| 2,479
| 2.703125
| 3
|
[] |
no_license
|
package com.tryouts.chris2pple.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
/*AttractionArrayAdapter is the ArrayAdapter that provides the layout for each list item
* populated by a data source that is a list of Attraction objects
* */
public class AttractionArrayAdapter extends ArrayAdapter<Attraction>
{
/*Create a new AttractionArrayAdapter object
* where the context is the current context that the adapter is being created in
* and object is the list of Attraction objects to be displayed
* */
public AttractionArrayAdapter(Context context, List<Attraction> object) {
super(context, 0, object);
}
/*The view for the AdapterView
*position is The position in the list of data that should be displayed in the list item view.
* convertView is The recycled view to populate.
* parent is The parent ViewGroup that is used for inflation.
* return convertView is the View for the position in the AdapterView
* */
@NonNull
@Override
public View getView(int position, @Nullable View convertView,@NonNull ViewGroup parent )
{
if(convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
/*Get the Attraction object located at this position in the list */
Attraction currentAttraction = (Attraction)getItem(position);
/*Find the TextView in the layout resource file list_item and set it to the place name*/
TextView leftTextView = convertView.findViewById(R.id.textleft);
leftTextView.setText(currentAttraction.getmPlaceName());
/*Find the ImageView in the layout resource file list_item and set it to the image*/
ImageView ImageView = convertView.findViewById(R.id.imageView);
ImageView.setImageResource(currentAttraction.getmPlaceImage());
/*Find the TextView in the layout resource file list_item and set it to the type name*/
TextView rightTextView = convertView.findViewById(R.id.textright);
rightTextView.setText(currentAttraction.getmPlaceType());
return convertView;
}
}
|
Python
|
UTF-8
| 422
| 2.6875
| 3
|
[] |
no_license
|
# -*- coding:utf-8 _*_
class Solution:
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n==0:
return [0]
ans=[0]
for i in range(n):
add=pow(2,i)
tem=[]
for j in range(len(ans)-1,-1,-1):
tem.append(ans[j]+add)
ans+=tem
return ans
o=Solution()
print(o.grayCode(2))
|
C++
|
UTF-8
| 694
| 2.953125
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <set>
using namespace std;
int main(int argc, char** argv) {
ifstream in(argv[1]);
string line;
while (getline(in, line)) {
stringstream ss(line);
string token;
vector<string> tokens;
set<int> mySet;
while (getline(ss, token, ';'))
tokens.push_back(token);
stringstream ss2(tokens[1]);
while (getline(ss2, token, ',')) {
if (mySet.find(stoi(token)) != mySet.end())
cout << *mySet.find(stoi(token));
else
mySet.insert(stoi(token));
}
cout << endl;
}
}
|
Java
|
UTF-8
| 498
| 2.1875
| 2
|
[] |
no_license
|
package enterprises.orbital.impl.evexmlapi.map;
import java.util.ArrayList;
import java.util.List;
import enterprises.orbital.evexmlapi.map.IFacWarSystem;
import enterprises.orbital.impl.evexmlapi.ApiResponse;
public class FacWarSystemsResponse extends ApiResponse {
private final List<IFacWarSystem> systems = new ArrayList<IFacWarSystem>();
public void addSystem(ApiFacWarSystem system) {
systems.add(system);
}
public List<IFacWarSystem> getSystems() {
return systems;
}
}
|
Python
|
UTF-8
| 720
| 3
| 3
|
[] |
no_license
|
import sys
if __name__ == '__main__':
T = int(sys.stdin.readline());
cases = 1
while T != 0:
T -= 1
input = sys.stdin.readline().split()
K, C, S = map(int, input[0:3])
if (K + C - 1) / C > S:
output = 'Case #{0}: {1}'.format(cases, 'IMPOSSIBLE')
print(output)
cases += 1
continue
l = range(0, K)
i = 0
ii = 0
r = 0
answer = []
ll = []
for i in range(0, K, C):
ll.append(l[i:i+C])
#print (ll)
for k in ll:
ii = 0
for i in k:
ii = ii * K + i
answer.append(ii+1)
answer = list(map(str, answer))
output = 'Case #{0}: {1}'.format(cases, ' '.join(answer))
print(output)
cases += 1
|
Python
|
UTF-8
| 524
| 3.875
| 4
|
[] |
no_license
|
"""
Create a solution that checks if a given string contains a sub-string pattern
repeated multiple times to return `True` or `False`.
### Examples
repeated("a") ➞ False
repeated("ababab") ➞ True
repeated("aba") ➞ False
repeated("abcabcabcabc") ➞ True
repeated("aaxxtaaxztaaxxt") ➞ False
### Notes
Adroit programmers can solve this in one line.
"""
def repeated(s):
a=0
for i in range(2,len(s)):
n=s[:i]
if n*(len(s)//i)==s:
a=a+1
return a!=0
|
Python
|
UTF-8
| 1,319
| 2.9375
| 3
|
[] |
no_license
|
#!/usr/bin/env python3
"""Program that performs the backward algorithm
for a hidden markov model"""
import numpy as np
def backward(Observation, Emission, Transition, Initial):
"""Function that performs the backward algorithm
for a hidden markov model"""
if type(Observation) is not np.ndarray or len(Observation.shape) != 1:
return (None, None)
if type(Emission) is not np.ndarray or len(Emission.shape) != 2:
return None, None
if type(Transition) is not np.ndarray or len(Transition.shape) != 2:
return None, None
if Transition.shape[0] != Transition.shape[1]:
return None, None
if type(Initial) is not np.ndarray or len(Initial.shape) != 2:
return None, None
if Emission.shape[0] != Transition.shape[0] != Transition.shape[0] !=\
Initial.shape[0]:
return None, None
if Initial.shape[1] != 1:
return None, None
T = Observation.shape[0]
N, M = Emission.shape
B = np.empty([N, T], dtype='float')
B[:, T - 1] = 1
for t in reversed(range(T - 1)):
B[:, t] = np.dot(Transition,
np.multiply(Emission[:,
Observation[t + 1]], B[:, t + 1]))
P = np.dot(Initial.T, np.multiply(Emission[:, Observation[0]], B[:, 0]))
return (P, B)
|
JavaScript
|
UTF-8
| 801
| 2.578125
| 3
|
[] |
no_license
|
function Props({ posts }) {
return (
<div>
<div style={{ margin: '1rem' }}>
이 페이지는 전달 받은 params가 없습니다.
</div>
{posts.map((post, idx) => (
<div key={idx} style={{ margin: '1rem' }}>
{post}
</div>
))}
</div>
);
}
export async function getStaticPaths() {
return {
paths: [
{
// 아래는 / 로 매칭됩니다.
// false 외에 `[]`, `null`, `undefined`를 반환해도 동일한 결과입니다.
params: {
catchAll: false,
},
},
],
fallback: false,
};
}
export async function getStaticProps({ params }) {
console.log(params);
const res = await fetch(`https://baconipsum.com/api/?type=meat-and-filler`);
const posts = await res.json();
return {
props: {
posts,
},
};
}
export default Props;
|
Markdown
|
UTF-8
| 1,152
| 3.8125
| 4
|
[] |
no_license
|
# Promise
## the Constructor
* The constructor of the Promise object takes a function
* This function receives two arguments: resolve, and reject
```
const myPromise = new Promise((resolve, reject) => {
...
})
```
## the Value
* The promise value represents its status which can be “rejected”, “fulfilled”, or “pending”.
* The promise value changes when the resolve or reject functions are called
```
const myPromise = new Promise((resolve, reject) => {
// value -> pending
...
resolve() // value -> fulfilled
...
reject() // value -> rejected
})
```
## the Prototype methods (then or catch)
* resolve is called -> value is fulfilled -> then() of the prototype is called
* reject is called -> value is rejected -> catch() of the prototype is called
```
myPromise
.then(x => x)
.catch(err => err)
```
* The **then** method of the promise prototype **receives a function** (so it’s an **higher order function**)
* That function receives what is passed to the resolve methods (that is the first argument of the function passed to the promise constructor, when the promise has been instantiated)
|
C
|
ISO-8859-1
| 3,284
| 3.65625
| 4
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//Gustavo da Silva Braghin
//uc19201375
struct tabelaHash {
int codigo; // chave de ordenao
char descricao[30];
}hash[10];
//*** MENU *******************************************************
int menu(void) {
int op;
printf("\n\n*** MENU ***\n\n");
printf("1. inserir\n");
printf("2. excluir\n");
printf("3. consultar\n");
printf("4. listar\n");
printf("0. Sair\n\n");
printf("Escolha sua opcao: ");
scanf("%d", &op);
return op;
}
void inicializar(){
int i;
for(i=0; i<=10; i++){
hash[i].codigo = -1;
}
}
int hashIncluir(int key){
if(hash[key%10].codigo<0){
return (key%10);
}else{
return hashIncluir(key+1);
}
}
int hashExcluir(int key, int cod){
if(hash[key%10].codigo == cod){
return key%10;
}else{
if(hash[key%10].codigo == -1){
return -3;
}else{
return hashExcluir(key+1, key);
}
}
}
void excluir(int key){
if(key == -3){
printf("CODIGO NAO ENCONTRADO");
}else{
hash[key].codigo = -2;
strcpy(hash[key].descricao, "");
printf("Exclusao concluida");
}
}
void consulta(int key){
if(key == -3){
printf("CODIGO NAO ENCONTRADO");
}else{
printf("\nPosicao: %i\n", key);
printf("CODIGO: %i DESCRICAO: %s\n", hash[key].codigo, hash[key].descricao);
}
}
void listar(){
int i;
for(i=0; i<10; i++){
printf("Posicao: %i\n",i);
if(hash[i].codigo >= 0){
printf("codigo: %i descricao: %s\n\n", hash[i].codigo, hash[i].descricao);
}else{
if(hash[i].codigo == -1){
printf("VAZIO\n\n");
}else{
printf("DELETADO\n\n");
}
}
}
}
main(){
int opcao, codigo, key;
char descricao[30];
inicializar();
do{
opcao = menu();
switch (opcao){
case 1:
printf("\n\n*** Inclusao ***\n\n");
printf("Digite o codigo...: ");
scanf("%d", &codigo);
printf("Digite a descricao: ");
fflush(stdin);
gets(descricao);
key = hashIncluir(codigo); //gerar key do vetor e passar os dados para o vetor
hash[key].codigo = codigo;
strcpy(hash[key].descricao, descricao);
printf("Inclusao concluida\n");
break;
case 2:
printf("\n\n*** Exclusao ***\n\n");
// Consultar pelo codigo e, caso encontre, excluir o no da lista.
printf("Digite o codigo: ");
scanf("%d", &codigo);
key = hashExcluir(codigo,codigo);
excluir(key);
break;
case 3:
printf("\n\n*** Consulta ***\n\n");
printf("Digite o codigo: ");
scanf("%d", &codigo);
// Pesquisar um produto com este codigo
key = hashExcluir(codigo, codigo);
consulta(key);
break;
case 4:
printf("\n\n*** Listagem ***\n\n");
listar();
break;
}
printf("\n");
system("pause");
system("cls");
}while(opcao != 0);
}
|
Markdown
|
UTF-8
| 783
| 2.953125
| 3
|
[] |
no_license
|
# UFO
## Overview of Project
The purpose of this project was to create a webpage with a dynamic table to provide UFO sighting analysis as filtered by the user. This dynamic table allows for multiple filter inputs for a more robust analysis.
## Results
The user can input analysis criteria into any of the 5 created filters. This will filter the dynamic table allowing for the user to analyze the data.
## Summary
In summary, this webpage is the cutting edge in dynamic tables. By using multiple filters at once, the user can take a deeper-dive into the data. One draw back is that there is no way to view any graphic data based on the filters by region. Two improvements would be to add in a search history setting, and an area map of sightings based on the filtered inputs.
|
Python
|
UTF-8
| 2,682
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
from abstract_view import AbstractView
class ZoneView(AbstractView):
__offset = None
__length = None
__range_dictionary = None
def __init__(self, range_dictionary, start, end):
self.__range_dictionary = range_dictionary
self.__offset = start
self.__length = end - start
def __iter__(self):
return self.__range_dictionary.iter_by_zone(self.__start, self.__end)
def __len__(self):
return self.__range_dictionary.len_by_zone(self.__start, self.__end)
def __getitem__(self, key):
return self.__range_dictionary.getitem_by_zone(self.__start,
self.__end, key)
def __setitem__(self, key, value):
return self.__range_dictionary.setitem_by_zone(self.__start,
self.__end, key, value)
def _check_range(self, start, end):
if start < 0:
raise Exception("Start must not be negative")
if end < 0:
raise Exception("End must not be negative")
if start > end:
raise Exception("Start must be less than or equal to end")
if end > self.__length:
raise Exception("End too high {} is greater than {}"
"".format(end, self.__length))
def set_range(self, start, end, key, value):
self._check_range(start, end)
self.__range_dictionary.setitem_by_zone(start + self.__offset,
end + self.__offset,
key, value)
def _check_index(self, index):
if index < 0:
raise Exception("Index must not be negative")
if index > self.__length:
raise Exception("Index too high {} is greater than {}"
"".format(index, self.__length))
def set_value(self, index, key, value):
self._check_index(index)
self.__range_dictionary.setitem_by_zone(index + self.__offset, key,
value)
def get_by_index(self, index):
self._check_index(index)
return self.__range_dictionary.get_by_index(index + self.offset)
def has_key(self, index, key):
self._check_index(index)
return (index + self.offset, key) in self.__range_dictionary
def get_value(self, index, key):
self._check_index(index)
return self.__range_dictionary.get_value(index + self.offset, key)
def get_view_by_index(self, index):
self._check_index(index)
return self.__range_dictionary.get_view_by_index(index + self.offset)
|
Python
|
UTF-8
| 4,958
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
import pygame
import game_functions as func
class Settings():
"""A class to store all settings for Space Invaders."""
def __init__(self):
"""Initialize game settings."""
# Screen settings
self.screen_width = 768
self.screen_height = 672
self.caption = "Space Invaders"
# FPS settings
self.fps = 60
# Font settings
self.font = "fonts/space_invaders.ttf"
self.font_size = 24
# Game sounds
self.player_shoot = pygame.mixer.Sound("sounds/player_shoot.wav")
self.player_shoot.set_volume(0.2)
self.invader_killed = pygame.mixer.Sound("sounds/invaderkilled.wav")
# Color settings
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.red = (255, 0, 0)
self.green = (0, 255, 0)
self.blue = (0, 0, 255)
# Player settings
self.player_speed = 3
self.player_offsetx = 102
self.player_y = self.screen_height - 96
self.player_ship_image = pygame.image.load("images/ships/player.png")
self.player_lives = 3
# Invader settings
self.invader_start_x = 126
self.invader_start_y = 120
self.invader_move_x = 6
self.invader_height = 24
self.invader_left_boundary = 72
self.invader_right_boundary = 690
self.invader_move_time = 1000
self.invader_1_score = 30
self.invader_2_score = 20
self.invader_3_score = 10
# Fleet settings
self.fleet_rows = 5
self.fleet_columns = 11
self.fleet_direction = 1
# Block settings
self.block_size = 3
# Shot settings
self.playershot_speed = 12
self.playershot_limit = 1
self.invadershot_speed = 12
self.invadershot_limit = 3
# Ground settings
self.ground_y = self.screen_height - 54
self.ground_offsetx = 48
# Life settings
self.life_y = self.screen_height - 48
self.life_text_offsetx = 75
self.life_ship_offsetx = 126
self.life_ship_spacing = 9
# Score settings
# Text
self.score_text_y = 24
# Numbers
self.player1_score_x = 123
self.hi_score_x = 315
self.score_y = 48
# Explosion settings
self.player_shot_explode_rows = 8
self.player_shot_explode_columns = 8
self.player_shot_explode_array = [
['b', '.', '.', '.', 'b', '.', '.', 'b'],
['.', '.', 'b', '.', '.', '.', 'b', '.'],
['.', 'b', 'b', 'b', 'b', 'b', 'b', '.'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['.', 'b', 'b', 'b', 'b', 'b', 'b', '.'],
['.', '.', 'b', '.', '.', 'b', '.', '.'],
['b', '.', '.', 'b', '.', '.', '.', 'b']]
self.invader_shot_explode_rows = 8
self.invader_shot_explode_columns = 6
self.invader_shot_explode_array = [
['.', '.', 'b', '.', '.', '.'],
['b', '.', '.', '.', 'b', '.'],
['.', '.', 'b', 'b', '.', 'b'],
['.', 'b', 'b', 'b', 'b', '.'],
['b', '.', 'b', 'b', 'b', '.'],
['.', 'b', 'b', 'b', 'b', 'b'],
['b', '.', 'b', 'b', 'b', '.'],
['.', 'b', '.', 'b', '.', 'b']]
# Shield settings
self.shield_rows = 16
self.shield_columns = 22
self.shield_x = 144
self.shield_y = self.screen_height - 168
# '.' == nothing
# 'b' == Block()
self.shield_array = [
['.', '.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', '.', '.', '.', '.'],
['.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', '.', '.', '.'],
['.', '.', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', '.', '.'],
['.', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', '.'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', 'b', '.', '.', '.', '.', '.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', 'b', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b'],
['b', 'b', 'b', 'b', 'b', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'b', 'b', 'b', 'b', 'b', 'b']]
|
Python
|
UTF-8
| 868
| 3.28125
| 3
|
[] |
no_license
|
n=int(input())
arr=[list(map(int,input().split())) for _ in range(n)]
white,blue=0,0
def recursiveDC(y,x,n):
global white,blue
#첫 컬러 지정.
color=arr[y][x]
check=True
for i in range(y,y+n):
#이미 어긋난 숫자가 있어서 뒤까지 살피는건 무의미. 그래서 for문 탈출
if not check:
break
for j in range(x,x+n):
if color!=arr[i][j]:
check=False
recursiveDC(y,x,n//2)#1사분면
recursiveDC(y,x+n//2, n//2 )#2사분면
recursiveDC(y+n//2,x, n//2)#3사분면
recursiveDC(y+n//2 , x+n//2, n//2)#4사분면
break
if check:
if color==1:
blue+=1
else:
white+=1
recursiveDC(0,0,n)
print(white)
print(blue)
|
Java
|
UTF-8
| 846
| 1.960938
| 2
|
[] |
no_license
|
package com.mvnikitin.itracker.rest.resources;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.mvnikitin.itracker.rest.entities.UserEntity;
import lombok.*;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.hateoas.server.core.Relation;
import static com.fasterxml.jackson.annotation.JsonInclude.Include;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@JsonRootName(value = "project")
@Relation(collectionRelation = "projects")
@JsonInclude(Include.NON_NULL)
public class ProjectModel extends RepresentationModel<ProjectModel> {
private Long id;
private String name;
private String description;
private String unit;
private UserEntity admin;
private UserEntity owner;
}
|
Markdown
|
UTF-8
| 2,977
| 3.171875
| 3
|
[] |
no_license
|
# Systems design interview questions
## Systems design interview tips
When doing design questions in person be sure to **ask a lot of questions**
before jumping in to writing a solution. Treat this interview as a conversation
with the interviewer.
While answering design questions you should cover:
1. **User interaction flow:** Describe the main pages of your app. What actions
can users take on each page? How do users get from one page to another?
1. **Schema and query patterns:** Describe all your models. How to models connect
to eachother? What queries do you need to run on your models?
1. **System overview:** What components is your system going to contain? You'll most
likely have a web server and a database. Are you going to use caching? What technologies
are you going to use for your server vs your database? Why?
## Messaging
Design a messaging app.
### Stage 1: Direct messages
- Users login with username and password
- Every user can message every other user
- All conversations are 1-1
- Users can find users by username
- Messages are grouped by user
### Stage 2: Group chat
- Users can message many users at the same time
- Sending a message to a group, should send a message to
every member of the group
### Stage 3: Chat rooms
- A chat room is like a group chat
- Chat rooms can be made private, in which case the room is
invite-only.
- Each chat room has one or more admins who can kick people
out of the room.
## Email filters
Design an email filtering system.
- What kind of email filters would you have?
- What sort of actions can people perform on filtered emails?
- How would you represent email filters?
- What happens when an email matches multiple filters?
## Multiplayer Poker
Build an online multi-player poker game with play money.
### Stage 1: Single poker game
Go into how to represent a hand, game state, table state.
- Players login with username and password
- Each player starts with 100 credits when they register
- There's a single game
- Players can spectate or join the game
- When player runs out of money they are out
- No limit, Texas hold-em rules
### Stage 2: Multiple games
- There are multiple games
- Players can see all active games
- Players can spectate and join games
## Team calendar app
Implement a calendaring app for people working in teams.
### Stage 1: One team
- Every user belongs to the same team
- Everyone can see each others' calendars
### Stage 2: Multiple teams
- Each person belongs to a single team
- Each team has a team admin that can add more people to the team
- Calendars are only visible to people on the same team.
### Stage 3: Recurring events
- How would you implement recurring events?
## Further reading
- [Comprehensive resources for systems design interviews](https://github.com/checkcheckzz/system-design-interview)
- [Palantir: How to ace a systems design interview](http://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/)
|
C#
|
UTF-8
| 1,760
| 3.265625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NetIMDB.Repository
{
public class MergedEnumerator<TModel>:IEnumerator<TModel>
{
IEnumerator<TModel>[] enumerators;
int current_enumerator = 0;
public MergedEnumerator(IEnumerator<TModel>[] enumerators)
{
this.enumerators = enumerators;
}
public TModel Current
{
get
{
return enumerators[current_enumerator].Current;
}
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get
{
return enumerators[current_enumerator].Current;
}
}
public bool MoveNext()
{
bool r = false;
while (!r)
{
r = enumerators[current_enumerator].MoveNext();
if (!r)
{
if (current_enumerator == enumerators.Length-1)
{
return false; //hemos llegado al final.
}
else
{
current_enumerator++;
}
}
}
return true;
}
public void Reset()
{
current_enumerator = 0;
foreach (var enumerator in enumerators)
enumerator.Reset();
}
//truco para permitir recorrer el enumerador con un foreach.
public IEnumerator<TModel> GetEnumerator()
{
return this;
}
}
}
|
C++
|
UTF-8
| 6,551
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
#include "StdAfx.h"
#include "d3d11.h"
#include "DirectXMath.h"
#include "D3Dcompiler.h"
#include "ColorShader.h"
#include "ShaderResource.h"
#include "Graphics\Mesh.h"
#include "utils\assert.h"
#include <stddef.h>
ColorShader::ColorShader(void)
{
m_vertexShader = NULL;
m_pixelShader = NULL;
m_layout = NULL;
m_matrixBuffer = NULL;
}
ColorShader::~ColorShader()
{
}
void ColorShader::Shutdown()
{
ShutdownShader();
}
bool ColorShader::Render(ID3D11DeviceContext* _context, DirectX::XMMATRIX& _worldMatrix, DirectX::XMMATRIX& _viewMatrix, DirectX::XMMATRIX& _projectionMatrix)
{
bool result = false;
result = SetShaderParameters(_context, _worldMatrix, _viewMatrix, _projectionMatrix);
if (result)
{
RenderShader(_context);
result = true;
}
return result;
}
bool ColorShader::InitShader(ID3D11Device* _device, HWND _hwnd, ShaderResource* _vertexShader, ShaderResource* _pixelShader)
{
ASSERT(_vertexShader != nullptr);
ASSERT(_pixelShader != nullptr);
HRESULT result;
ID3D10Blob* vertexShaderBuffer = _vertexShader->GetShader();
ID3D10Blob* pixelShaderBuffer = _pixelShader->GetShader();
D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
unsigned int numElements;
D3D11_BUFFER_DESC matrixBufferDesc;
// Create the vertex shader from the buffer.
result = _device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
if(FAILED(result))
return false;
// Create the pixel shader from the buffer.
result = _device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
if(FAILED(result))
return false;
// Now setup the layout of the data that goes into the shader.
// This setup needs to match the VertexType stucture in the ModelClass and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = offsetof(PositionNormalUVLayout, Position);
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "NORMAL";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = offsetof(PositionNormalUVLayout, Normal);
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
polygonLayout[2].SemanticName = "TEXCOORD";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = offsetof(PositionNormalUVLayout, UV);
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;
// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// Create the vertex input layout.
result = _device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
vertexShaderBuffer->GetBufferSize(), &m_layout);
if(FAILED(result))
return false;
// Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
vertexShaderBuffer->Release();
vertexShaderBuffer = 0;
pixelShaderBuffer->Release();
pixelShaderBuffer = 0;
// Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
// Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
result = _device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
if(FAILED(result))
return false;
return true;
}
void ColorShader::RenderShader(ID3D11DeviceContext* _context)
{
// Set the vertex and pixel shaders that will be used to render this triangle.
_context->VSSetShader(m_vertexShader, NULL, 0);
_context->PSSetShader(m_pixelShader, NULL, 0);
}
void ColorShader::ShutdownShader()
{
// Release the matrix constant buffer.
if(m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = 0;
}
// Release the layout.
if(m_layout)
{
m_layout->Release();
m_layout = 0;
}
// Release the pixel shader.
if(m_pixelShader)
{
m_pixelShader->Release();
m_pixelShader = 0;
}
// Release the vertex shader.
if(m_vertexShader)
{
m_vertexShader->Release();
m_vertexShader = 0;
}
}
bool ColorShader::SetShaderParameters(ID3D11DeviceContext* _context, DirectX::XMMATRIX& _worldMatrix, DirectX::XMMATRIX& _viewMatrix, DirectX::XMMATRIX& _projectionMatrix)
{
HRESULT result;
D3D11_MAPPED_SUBRESOURCE mappedResource;
MatrixBufferType* dataPtr;
unsigned int bufferNumber;
DirectX::XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
// Transpose the matrices to prepare them for the shader.
worldMatrix = XMMatrixTranspose(_worldMatrix);
viewMatrix = XMMatrixTranspose(_viewMatrix);
projectionMatrix = XMMatrixTranspose(_projectionMatrix);
// Lock the constant buffer so it can be written to.
result = _context->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if(FAILED(result))
return false;
// Get a pointer to the data in the constant buffer.
dataPtr = (MatrixBufferType*)mappedResource.pData;
// Copy the matrices into the constant buffer.
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;
// Unlock the constant buffer.
_context->Unmap(m_matrixBuffer, 0);
// Set the position of the constant buffer in the vertex shader.
bufferNumber = 0;
// Finanly set the constant buffer in the vertex shader with the updated values.
_context->VSSetConstantBuffers(bufferNumber, 1, &m_matrixBuffer);
return true;
}
|
Java
|
UTF-8
| 429
| 2.375
| 2
|
[] |
no_license
|
package tion.ua.es;
import java.util.Date;
public class Periodico extends Publicacion{
private Date fecha;
public Periodico(Date fecha) {
super();
this.fecha = fecha;
}
public Periodico(String titulo, String autor, Date fecha) {
super(titulo,autor);
this.fecha = fecha;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
}
|
C++
|
UTF-8
| 978
| 2.609375
| 3
|
[] |
no_license
|
/*
* SetShooterState.cpp
*
* Created on: Mar 6, 2017
* Author: Brin Harper
*/
#include "SetShooterState.h"
#include "../Robot.h"
SetShooterState::SetShooterState(int state, double duration, vector<shared_ptr<dependency>> dependencies, shared_ptr<Robot> robot) :
Action (dependencies, robot),
m_state(state),
m_duration(duration)
{
}
SetShooterState::SetShooterState(json& action, shared_ptr<Robot> robot) :
Action(),
m_state(action["state"]),
m_duration(action["duration"])
{
initAction(action, robot);
}
void SetShooterState::run() {
m_robot->setFeederState(m_state);
m_robot->setFlywheelState(m_state);
if(getCondition() == dependency::NotStarted)
{
m_timer.Reset();
m_timer.Start();
start();
}
else if (m_timer.Get() > m_duration)
{
finish();
m_timer.Start();
}
}
void SetShooterState::reset()
{
resetCondition();
m_timer.Stop();
m_timer.Reset();
}
|
C#
|
UTF-8
| 4,876
| 2.828125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using GeoAPI.Geometries;
using USGS.Puma.NTS.IO;
using USGS.Puma.NTS.Features;
using USGS.Puma.NTS.Geometries;
namespace USGS.Puma.IO
{
/// <summary>
/// Imports and exports ESRI shapefiles
/// </summary>
public static class EsriShapefileIO
{
/// <summary>
/// Exports a collection of 3D features to an ESRI shapefile
/// </summary>
/// <param name="features"></param>
/// <param name="directory"></param>
/// <param name="basename"></param>
public static void Export(FeatureCollection features, string directory, string basename)
{
ShapefileDataWriter writer = null;
try
{
if (features != null)
{
if (features.Count > 0)
{
string filename = System.IO.Path.Combine(directory, basename);
if (ShapefileInfo.TryDelete(directory, basename))
{
writer = new ShapefileDataWriter(filename);
writer.Write(features);
}
else
{
throw new Exception("Shapefile '" + filename + "' could not be exported because the existing copy could not be deleted.");
}
}
}
}
catch (Exception e)
{
throw new Exception("Error writing shapefile.", e);
}
finally
{
// Note: We should call Dispose here, but right now the ShapefileDataWriter
// class does not support IDisposable. That needs to be fixed. For now, just
// set writer to null (which should happen anyway, but at least is serves
// as placeholder code until Dispose is available.
if (writer != null)
{
// writer.Dispose();
writer = null;
}
}
}
/// <summary>
/// Reads an ESRI shapefile and imports a collection of 3D features.
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static FeatureCollection Import(string filename)
{
FeatureCollection featureList = new FeatureCollection();
ShapefileDataReader shpDataReader = null;
try
{
shpDataReader = new ShapefileDataReader(filename, new GeometryFactory());
if (shpDataReader.RecordCount > 0)
{
bool moreRecords;
IGeometry geometry = null;
string attributeName = null;
object attributeValue = null;
string[] attributeNames = null;
Feature feature = null;
AttributesTable attributes = null;
int count = 0;
while (true)
{
moreRecords = shpDataReader.Read();
if (moreRecords)
{
count++;
geometry = shpDataReader.Geometry;
attributes = new AttributesTable();
attributeNames = shpDataReader.GetAllNames();
for (int i = 0; i < attributeNames.Length; i++)
{
//Process attributes for all fields except the
//Geometry field.
if (attributeNames[i] != "Geometry")
{
attributeName = attributeNames[i];
attributeValue = shpDataReader[attributeNames[i]];
attributes.AddAttribute(attributeName, attributeValue);
}
}
feature = new Feature(geometry, attributes);
featureList.Add(feature);
}
else
{ break; }
}
}
}
catch (Exception e)
{
throw new Exception("Error importing shapefile:" + Environment.NewLine + filename, e);
}
finally
{
if (shpDataReader != null)
{ shpDataReader.Close(); }
}
return featureList;
}
}
}
|
C++
|
UTF-8
| 5,231
| 3.0625
| 3
|
[] |
no_license
|
//////////////////////////////////////////////////
// OLIVER LOGUSH //
// 2015 //
// DISPLAY DRIVER FOR A 32x32 RGB LED DISPLAY //
// //
// Version 1.0 //
// //
// //
//////////////////////////////////////////////////
//This is the interval timer that calls an iterrupt
IntervalTimer displayInterrupt;
//Defining all of the pins locations on each port register
# define clockPin 0
# define latchPin 6
# define outputEnable 7
# define redData 0
# define blueData 4
# define greenData 2
# define redData1 1
# define greenData1 3
# define blueData1 5
# define rowSelectA 1
# define rowSelectB 2
# define rowSelectC 3
# define rowSelectD 4
//These are the variables that keep track of where the bit angle modulation is at
uint8_t bamBit;
uint8_t bamCounter;
//These are the arrays for each colour value of each pixel
uint8_t red[32][32];
uint8_t green[32][32];
uint8_t blue[32][32];
//This keeps track of the row that the program is updating
uint8_t row = 0;
//{|THIS IS A TABLE TO KEEP TRACK OF WHICH PIN IS WHERE ON EACH PORT|}
//RED DATA PD0
//RED DATA1 PD1
//GREEN DATA PD2
//GREEN DATA1 PD3
//BLUE DATA PD4
//BLUE DATA1 PD5
//LATCH PIN PD6
//OUTPUT ENABLE PD7
//CLOCK PIN PC0
//ROWSELECT A PC1
//ROWSELECT B PC2
//ROWSELECT C PC3
//ROWSELECT D PC4
void setup() {
//Begins the serial communication
Serial.begin(9600);
//Setting all of the pins used in PORTC as GPIO pins
PORTC_PCR0 = (1 << 8);
PORTC_PCR1 = (1 << 8);
PORTC_PCR2 = (1 << 8);
PORTC_PCR3 = (1 << 8);
PORTC_PCR4 = (1 << 8);
//Setting all of the pins used in PORTD as GPIO pins
PORTD_PCR0 = (1 << 8);
PORTD_PCR1 = (1 << 8);
PORTD_PCR2 = (1 << 8);
PORTD_PCR3 = (1 << 8);
PORTD_PCR4 = (1 << 8);
PORTD_PCR5 = (1 << 8);
PORTD_PCR6 = (1 << 8);
PORTD_PCR7 = (1 << 8);
//Setting the appropriate pins as outputs
GPIOC_PDDR = B00011111;
GPIOD_PDDR = B11111111;
//call contactProcessing which does not allow the program to start until it has recieved communication from processing
contactProcessing();
//Initialize the displayInterrupt calling it every 50 microseconds to call the displayToMatrix function
displayInterrupt.begin(displayToMatrix, 50);
}
void loop() {
//If it recieves something over the serial port it will begin these loops to recieve the data and store it
if (Serial.available() > 0)
{
for (int i = 0; i < 32; i++)
{
for (int j = 0; j < 32; j++)
{
int k = 0;
while (k < 3)
{
if (Serial.available() > 0)
{
switch (k)
{
case 0:
red[i][j] = Serial.read();
break;
case 1:
green[i][j] = Serial.read();
break;
case 2:
blue[i][j] = Serial.read();
break;
}
k++;
}
}
}
}
}
}
void displayToMatrix()
{
//This increments the bamBit once the bamCounter reaches the appropriate value to move on
if (bamCounter == 16 || bamCounter == 48 || bamCounter == 112) bamBit++;
//Increments the bam counter once per cycle
bamCounter++;
//This sets the latchPin low and outputEnable high to allow new data to be shifted in
GPIOD_PSOR = (1 << outputEnable);
GPIOD_PCOR = (1 << latchPin);
//Setting the row demux to the row number it is on
GPIOC_PDOR = (row << 1);
//This loop shifts out all of the data in the right bam bit to the right row
for (int i = 0; i < 32; i++)
{
//This writes the clockPin low
GPIOC_PCOR = (1 << clockPin);
//This clears the data pins
GPIOD_PCOR = B00111111;
//This snippet of code sets the data pins to the values they need to be based on the row count and the bamBit
GPIOD_PSOR = (((red[i][row] >> bamBit) & 1) | (((red[i][row + 16] >> bamBit) & 1) << redData1) | (((green[i][row] >> bamBit) & 1) << greenData) | (((green[i][row + 16] >> bamBit) & 1) << greenData1) | (((blue[i][row] >> bamBit) & 1) << blueData) | (((blue[i][row + 16] >> bamBit) & 1) << blueData1));
//This sets the clockPin high
GPIOC_PSOR = (1 << clockPin);
}
//Set the latchPin high and outputEnable low to allow the pixels to be displayed
GPIOD_PSOR = (1 << latchPin);
GPIOD_PCOR = (1 << outputEnable);
//If the bamCounter has reached the max value reset it and the bamBit to 0
if (bamCounter == 240)
{
bamBit = 0;
bamCounter = 0;
}
//Increment the row counter
row++;
//If the row has reached 16 reset it
if (row == 16) row = 0;
}
//The function to write individual pixels (used mainly for debugging)
void writePixel(uint8_t x, uint8_t y, uint8_t r, uint8_t g, uint8_t b)
{
red[x][y] = r;
green[x][y] = g;
blue[x][y] = b;
}
//This is the function that halts the program until processing has sent something to confirm the connection
void contactProcessing()
{
while (Serial.available() <= 0)
{
Serial.println("Y");
delay(250);
}
}
|
Python
|
UTF-8
| 365
| 2.8125
| 3
|
[] |
no_license
|
#create date: 2020-06-29 13:18
import sys
stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))
def main():
n = ni()
v = na()
c = na()
ans = 0
for vi, ci in zip(v, c):
ans += max(0, vi-ci)
print(ans)
if __name__ == "__main__":
main()
|
Java
|
UTF-8
| 921
| 3.21875
| 3
|
[] |
no_license
|
package com.linearsearch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class DryWetClothes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =3; //sc.nextInt();
int m =3; //sc.nextInt();
int g =2; //sc.nextInt();
int iter=0,count=0;
//sc.nextLine();
Integer[] rainTimes= {3,3,2};//new Integer[n];
List<Integer> dryTimes=new ArrayList<>();
dryTimes.add(4);
dryTimes.add(1);
dryTimes.add(3);
/* for(int i =0;i<n;i++) {
rainTimes[i]=sc.nextInt();
}
sc.nextLine();
for(int i =0;i<m;i++) {
dryTimes.add(sc.nextInt());
}*/
Collections.sort(dryTimes);
int t = rainTimes[0];
while(iter<=g && iter<n-1 && iter<m-1) {
t=(dryTimes.get(iter) -rainTimes[iter+1])+t;
if(t>=0) {
count++;
}
iter++;
}
System.out.println(count);
}
}
|
Java
|
UTF-8
| 6,694
| 2
| 2
|
[] |
no_license
|
package com.tooflya.bubblefun.managers;
import android.annotation.TargetApi;
import android.view.View;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;
import com.tooflya.bubblefun.Game;
import com.tooflya.bubblefun.Options;
import com.tooflya.bubblefun.R;
import com.tooflya.bubblefun.screens.AdvertisimentScreen;
import com.tooflya.bubblefun.screens.Screen;
public class AdvertisementManager {
private final AdView mSmallAdvertisiment;
private final AdView mBigAdvertisiment;
protected final View mNoSmallAdsView;
protected final View mNoBigAdsView;
protected final View mProgressBar;
private final AdRequest mAdsRequest;
private boolean isAdvertisementDisabled = false;
private boolean isSAdvertisementAvailable = false;
private boolean isBAdvertisementAvailable = false;
private final Runnable mShowSmallRunnable = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if (isSAdvertisementAvailable) {
mSmallAdvertisiment.setVisibility(View.VISIBLE);
} else {
mNoSmallAdsView.setVisibility(View.VISIBLE);
}
}
};
private final Runnable mHideSmallRunnable = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if (isSAdvertisementAvailable) {
mSmallAdvertisiment.setVisibility(View.GONE);
} else {
mNoSmallAdsView.setVisibility(View.GONE);
}
mSmallAdvertisiment.stopLoading();
mSmallAdvertisiment.loadAd(mAdsRequest);
}
};
private final Runnable mShowBigRunnable = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if (isBAdvertisementAvailable) {
mBigAdvertisiment.setVisibility(View.VISIBLE);
} else {
mNoBigAdsView.setVisibility(View.VISIBLE);
}
((AdvertisimentScreen) Game.mScreens.get(Screen.ADS)).mClose.setVisible(true);
mProgressBar.setVisibility(View.GONE);
}
};
private final Runnable mHideBigRunnable = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
if (isBAdvertisementAvailable) {
mBigAdvertisiment.setVisibility(View.GONE);
} else {
mNoBigAdsView.setVisibility(View.GONE);
}
}
};
private final Runnable mLoadBigRunnable = new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
mProgressBar.setVisibility(View.VISIBLE);
mBigAdvertisiment.loadAd(mAdsRequest);
}
};
/**
*
*/
@TargetApi(11)
public AdvertisementManager() {
this.mAdsRequest = new AdRequest();
this.mAdsRequest.addTestDevice(AdRequest.TEST_EMULATOR);
this.mAdsRequest.addTestDevice("75FB804D31DDACC071B1AAF9A074D67A");
this.mAdsRequest.addTestDevice("2A1EBFDEA347D99BD1F7FBB84433AD72");
this.mAdsRequest.addTestDevice("FA02AC6CC21C807191ED1A07863CD045");
this.mAdsRequest.addTestDevice("D964D0EE15FC33E6A1678227284CFA70");
this.mSmallAdvertisiment = (AdView) Game.mInstance.findViewById(R.id.adView);
this.mBigAdvertisiment = (AdView) Game.mInstance.findViewById(R.id.adViewBig);
this.mNoSmallAdsView = Game.mInstance.findViewById(R.id.noAdsSmall);
this.mNoBigAdsView = Game.mInstance.findViewById(R.id.noAdsBig);
this.mProgressBar = Game.mInstance.findViewById(R.id.progressBar);
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= 11) {
this.mBigAdvertisiment.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
this.mSmallAdvertisiment.setAdListener(new SmallAdListener());
this.mBigAdvertisiment.setAdListener(new BigAdListener());
this.isAdvertisementDisabled = Game.mDatabase.isAdvertisimentDisabled();
if (!this.isAdvertisementDisabled()) {
this.mSmallAdvertisiment.loadAd(this.mAdsRequest);
Screen.ADS_PADDING = 60f;
}
}
public boolean isAdvertisementDisabled() {
if (Options.DEBUG) {
return true;
}
return this.isAdvertisementDisabled;
//return true;
}
public void showSmall() {
if (!this.isAdvertisementDisabled()) {
Game.mInstance.runOnUiThread(this.mShowSmallRunnable);
}
}
public void hideSmall() {
Game.mInstance.runOnUiThread(this.mHideSmallRunnable);
}
public void showBig() {
if (!this.isAdvertisementDisabled()) {
Game.mInstance.runOnUiThread(this.mLoadBigRunnable);
}
}
public void hideBig() {
Game.mInstance.runOnUiThread(this.mHideBigRunnable);
}
private final class SmallAdListener implements AdListener {
/* (non-Javadoc)
* @see com.google.ads.AdListener#onDismissScreen(com.google.ads.Ad)
*/
@Override
public void onDismissScreen(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onFailedToReceiveAd(com.google.ads.Ad, com.google.ads.AdRequest.ErrorCode)
*/
@Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
AdvertisementManager.this.isSAdvertisementAvailable = false;
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onLeaveApplication(com.google.ads.Ad)
*/
@Override
public void onLeaveApplication(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onPresentScreen(com.google.ads.Ad)
*/
@Override
public void onPresentScreen(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onReceiveAd(com.google.ads.Ad)
*/
@Override
public void onReceiveAd(Ad arg0) {
AdvertisementManager.this.isSAdvertisementAvailable = true;
}
}
private final class BigAdListener implements AdListener {
/* (non-Javadoc)
* @see com.google.ads.AdListener#onDismissScreen(com.google.ads.Ad)
*/
@Override
public void onDismissScreen(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onFailedToReceiveAd(com.google.ads.Ad, com.google.ads.AdRequest.ErrorCode)
*/
@Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
AdvertisementManager.this.isBAdvertisementAvailable = false;
Game.mInstance.runOnUiThread(AdvertisementManager.this.mShowBigRunnable);
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onLeaveApplication(com.google.ads.Ad)
*/
@Override
public void onLeaveApplication(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onPresentScreen(com.google.ads.Ad)
*/
@Override
public void onPresentScreen(Ad arg0) {
}
/* (non-Javadoc)
* @see com.google.ads.AdListener#onReceiveAd(com.google.ads.Ad)
*/
@Override
public void onReceiveAd(Ad arg0) {
AdvertisementManager.this.isBAdvertisementAvailable = true;
Game.mInstance.runOnUiThread(AdvertisementManager.this.mShowBigRunnable);
}
}
}
|
Markdown
|
UTF-8
| 3,826
| 2.9375
| 3
|
[] |
no_license
|
# Dockerfile
Sirve para crear una imagen siguiendo una serie de instrucciones
FROM: Para descargar una imagen: imagen : version_imagen
```shell
FROM ubuntu:14.04
```
RUN: Ejecutar comandos (apt-get, yum install)
ENV: Para variables de entorno
En este ejemmplo vemos como se inicia un servicio nginx con:
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website# cat Dockerfile
FROM nginx:latest
WORKDIR /usr/share/nginx/html
COPY . .
```
Lo que hace es crear una imagen nginx, la ultima version: FROM nginx:latest
luego se define el directorio de trabajo donde se ejecuta cualquier comando de accion como: RUN, CMD, ADD, COPY
Despues copia todo el contenido de la direccion actual donde se encuentra el Dockerfile, que en este caso tiene: about, index, services
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# cd /home/website/
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website# ls
Dockerfile about.html index.html services.html
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website#
```
To build the Dockerfile:
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website# docker build -t websitebuilt .
Sending build context to Docker daemon 4.608kB
Step 1/3 : FROM nginx:latest
---> 62d49f9bab67
Step 2/3 : WORKDIR /usr/share/nginx/html
---> Running in 8a9728afb509
Removing intermediate container 8a9728afb509
---> ea0d1e698fec
Step 3/3 : COPY . .
---> 64dd0fc98714
Successfully built 64dd0fc98714
Successfully tagged websitebuilt:latest
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website#
```
To be sure image websitebuilt were created:
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
websitebuilt latest 64dd0fc98714 46 seconds ago 133MB
nginx latest 62d49f9bab67 3 days ago 133MB
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:/home/website#
```
Until here we have the image created but not the container
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ef5613acd594 nginx "/docker-entrypoint.…" 4 hours ago Up 4 hours 0.0.0.0:3000->80/tcp, :::3000->80/tcp website
```
To run the container using the recently created image websitebuilt:
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker run -p 7000:80 -d --name websiteapp websitebuilt
6ba79df6f00e48b651eff2bc6a2ded06df19f4488c233c6180e1f8ebe1a8d1a8
```
- port: 7000 externally,
- internally port: 80
- -d: run in background
- container name: websiteapp (name doesnt accept uppercase)
- the last variable is the image name: website build

Optionally we can remove the current container
```shell
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6ba79df6f00e websitebuilt "/docker-entrypoint.…" 23 minutes ago Up 23 minutes 0.0.0.0:7000->80/tcp, :::7000->80/tcp websiteapp
ef5613acd594 nginx "/docker-entrypoint.…" 4 hours ago Up 4 hours 0.0.0.0:3000->80/tcp, :::3000->80/tcp website
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker stop websiteapp
websiteapp
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker rm websiteapp
websiteapp
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ef5613acd594 nginx "/docker-entrypoint.…" 4 hours ago Up 4 hours 0.0.0.0:3000->80/tcp, :::3000->80/tcp website
root@ubuntu-s-1vcpu-1gb-intel-sfo3-01:~#
```
|
Markdown
|
UTF-8
| 6,014
| 2.59375
| 3
|
[] |
no_license
|
# OC对象原理下
## 1. OC 对象的本质
### 1.1 clang
`clang` 是 LLVM 框架下 C/C++/Objective_C的编译器前端。
```sh
// 将 OC 源文件 重写为 C++ 源文件
clang --rewrite-objc main.m -o main.cpp
```
### 1.2 OC类就是Struct


经过Clang的重写,我们可以看到 OC类其实就是结构体 struct,OC类中的属性就是结构体的变量。结构体中还包括了 `NSObject_IVARS` 变量, 其实就是 `NSObject` 的 `isa` 属性,保存了 类的信息(类对象的指针) 以及 对象的信息(包括引用计数,关联对象等等)。
## 2. initInstanceIsa
在调用 `calloc` 函数分配了对象的内存,就需要设置对象类的相关信息,即初始化 `isa` 属性。
```
isa_t::setClass(objc_class*,objc_object*)
objc_object::initIsa(objc_class*,bool,bool)
objc_object::initInstanceIsa(objc_class*,bool)
_class_createInstanceFromZone()
```

```c
// objc4-818.2
struct objc_object {
private:
isa_t isa;
};
union isa_t {
uintptr_t bits;
private:
Class cls;
public:
#if defined(ISA_BITFIELD)
struct {
ISA_BITFIELD; // defined in isa.h
};
#endif
};
// arm 64
# define ISA_BITFIELD \
uintptr_t nonpointer : 1; \
uintptr_t has_assoc : 1; \
uintptr_t has_cxx_dtor : 1; \
uintptr_t shiftcls : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \
uintptr_t magic : 6; \
uintptr_t weakly_referenced : 1; \
uintptr_t unused : 1; \
uintptr_t has_sidetable_rc : 1; \
uintptr_t extra_rc : 19
// x86_64
# define ISA_BITFIELD \
uintptr_t nonpointer : 1; \
uintptr_t has_assoc : 1; \
uintptr_t has_cxx_dtor : 1; \
uintptr_t shiftcls : 44; /*MACH_VM_MAX_ADDRESS 0x7fffffe00000*/ \
uintptr_t magic : 6; \
uintptr_t weakly_referenced : 1; \
uintptr_t unused : 1; \
uintptr_t has_sidetable_rc : 1; \
uintptr_t extra_rc : 8
```

可以看到在 objc4-818.2 的实现中,`isa` 属性是 `isa_t` 类型。 `isa_t` 是一个联合体,`bits`和`ISA_BITFIELD` 位域结构体共享一块内存, 在这块内存中保存着类和对象的信息。
关于[C位域](https://www.runoob.com/cprogramming/c-bit-fields.html)。
- **nonpointer** :
占1位,表示是否对 isa 指针开启指针优化 ;0:纯isa指针,表示isa仅保存类的信息 1:不⽌是类对象地址,isa 中包含了类信息、对象的引⽤计数等
- **has_assoc**:
占1位,是否有关联对象
- **has_cxx_dtor**:
该对象是否有 C++ 或者 Objc 的析构器,如果有析构函数,则需要做析构逻辑, 如果没有,则可以更快的释放对象。
- **shiftcls**:
存储类指针的值。开启指针优化的情况下,在 arm64 架构中有 33 位⽤来存储类指针。
- **magic**:
⽤于调试器判断当前对象是真的对象还是没有初始化的空间
- **weakly_referenced**:
对象是否被指向或者曾经指向⼀个 ARC 的弱变量,没有弱引⽤的对象可以更快释放。
- **deallocating**:
标志对象是否正在释放内存
- **has_sidetable_rc**:
当对象引⽤技术⼤于 10 时,则需要借⽤该变量存储进位
- **extra_rc**:
当表示该对象的引⽤计数值,实际上是引⽤计数值减 1,
例如,如果对象的引⽤计数为 10,那么 extra_rc 为 9。如果引⽤计数⼤于 10,则需要使⽤到下⾯的 has_sidetable_rc
`shiftcls` 才是实际保存类地址的部分,仅占用`isa`的一部分。
```c++
// objc4-818.2
// 设置class 信息
isa_t::setClass(Class newCls, UNUSED_WITHOUT_PTRAUTH objc_object *obj)
{
#if __has_feature(ptrauth_calls) || TARGET_OS_SIMULATOR
// 模拟器
shiftcls_and_sig = signedCls >> 3;
#elif SUPPORT_INDEXED_ISA
// Indexed isa only uses this method to set a raw pointer class.
// Setting an indexed class is handled separately.
cls = newCls;
#else
// 一般自定义类型都是 Nonpointer, 将class地址赋给 shiftcls
// Nonpointer isa, no ptrauth
shiftcls = (uintptr_t)newCls >> 3;
#endif
}
// 获取class
inline Class
isa_t::getClass(MAYBE_UNUSED_AUTHENTICATED_PARAM bool authenticated) {
#if SUPPORT_INDEXED_ISA
return cls;
#else
uintptr_t clsbits = bits;
# if __has_feature(ptrauth_calls)
# if ISA_SIGNING_AUTH_MODE == ISA_SIGNING_AUTH
clsbits &= objc_debug_isa_class_mask;
# endif
# else
// 与 ISA_MASK 与操作,获取 class 地址
clsbits &= ISA_MASK;
# endif
return (Class)clsbits;
#endif
}
```

|
Java
|
UTF-8
| 1,926
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
package pl.mmorpg.prototype.server.objects.monsters.spells.objects;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import pl.mmorpg.prototype.server.communication.PacketsSender;
import pl.mmorpg.prototype.server.objects.MovableGameObject;
import pl.mmorpg.prototype.server.objects.monsters.Monster;
import pl.mmorpg.prototype.server.states.GameObjectsContainer;
public abstract class ThrowableObject extends MovableGameObject
{
private Monster target = null;
private GameObjectsContainer linkedContainer;
private PacketsSender packetSender;
private final Vector2 flyingVector = new Vector2();
public ThrowableObject(Texture lookout, long id, GameObjectsContainer linkedContainer, PacketsSender packetSender)
{
super(lookout, id, packetSender);
this.linkedContainer = linkedContainer;
this.packetSender = packetSender;
this.setCollideable(false);
}
@Override
public void update(float deltaTime)
{
if (!hasTarget() || !targetIsAlive())
{
removeItself(linkedContainer, packetSender);
return;
}
chaseTarget(deltaTime, target);
if (isNearTarget(target))
{
removeItself(linkedContainer, packetSender);
onHit(target);
return;
}
super.update(deltaTime);
}
private boolean targetIsAlive()
{
return target.isInGame();
}
public abstract void onHit(Monster target);
private boolean hasTarget()
{
return target != null;
}
public Monster getTarget()
{
return target;
}
public void setTarget(Monster target)
{
this.target = target;
}
@Override
protected void chaseTarget(float deltaTime, Monster target)
{
flyingVector.x = getX() - target.getX();
flyingVector.y = getY() - target.getY();
float angle = flyingVector.angle();
flyingVector.set(getMoveSpeed() / 70, getMoveSpeed() / 70);
flyingVector.setAngle(angle);
setPosition(getX() - flyingVector.x, getY() - flyingVector.y);
sendRepositionPacket();
}
}
|
Markdown
|
UTF-8
| 2,183
| 2.625
| 3
|
[] |
no_license
|
{{Unreferenced|time=2013-04-25T12:11:53+00:00 }}
'''水解'''是一种[[化工单元过程|化工单元过程]],是物質與水反應,利用水形成新的物质的过程。通常是指[[鹽類|鹽類]]的水解平衡。
==無機物的水解==
[[无机物|无机物]]在水中分解通常是双分解过程,属于[[复分解反应|复分解反应]]。[[水|水]]分子也被分解成[[氢离子|氢离子]]和[[氢氧根|氢氧根]],和被水解的物质残片结合形成新物质,如:
*[[氯|氯气]]在水中分解,一个氯[[離子|離子]]和一个水被分解的[[氢離子|氢離子]]结合成[[盐酸|盐酸]],水分子的另一个氢氧根離子与另一个[[氯|氯]]離子结合成[[次氯酸|次氯酸]]:
:<chem>Cl2 -> Cl+ + Cl-</chem>
:<chem>H2O -> H+ + OH-</chem>
:<chem>Cl- + H+ -> HCl</chem>
:<chem>Cl+ + OH- -> HClO</chem>
*[[碳酸钠|碳酸钠]]水解会产生[[碳酸氢钠|碳酸氢钠]]:
:<chem>Na2CO3 -> 2Na+ + CO3^{2-}</chem>
:<chem>H2O -> H+ + OH-</chem>
:<chem>Na+ + OH- ->NaOH</chem>
:<chem>Na+ + H+ + CO3^{2-} -> NaHCO3</chem>
*[[氯化铵|氯化铵]]水解会产生[[盐酸|盐酸]]和[[氨水|氨水]]:
:<chem>NH4Cl -> NH4+ + Cl-</chem>
:<chem>H2O -> H+ + OH-</chem>
:<chem>NH4+ + OH- -> NH3*H2O</chem>
==有機物的水解==
[[有机物|有机物]]的分子一般都比较大,水解时需要[[酸|酸]]或[[碱|碱]]作为[[催化剂|催化剂]],有时也用生物活性[[酶|酶]]作为催化剂。在酸性水溶液(稀釋鹽酸溶液)中[[脂肪|脂肪]]会水解成[[甘油|甘油]]和[[脂肪酸|脂肪酸]];[[淀粉|淀粉]]会水解成[[葡萄糖|葡萄糖]];[[蛋白质|蛋白质]]会水解成[[氨基酸|氨基酸]]等分子量比较小的物质。
在鹼性水溶液中,[[脂肪|脂肪]]會分解成[[甘油|甘油]]和固體脂肪酸鹽(即[[香皂|香皂]]),因此這種水解也叫作[[皂化反應|皂化反應]]。
== 参见 ==
{{Portalbox|化学}}
* [[水合|水合]]
* [[脫水縮合|脫水縮合]]
* [[水解酶|水解酶]]
{{Authority control}}
[[Category:平衡化学|Category:平衡化学]]
[[Category:化學反應|Category:化學反應]]
[[Category:风化作用|Category:风化作用]]
|
Java
|
UTF-8
| 5,557
| 1.914063
| 2
|
[
"MIT"
] |
permissive
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.exoplayer2.ui;
import android.graphics.Bitmap;
import android.os.Handler;
// Referenced classes of package com.google.android.exoplayer2.ui:
// PlayerNotificationManager
public final class PlayerNotificationManager$BitmapCallback
{
public void onBitmap(final Bitmap bitmap)
{
if(bitmap != null)
//* 0 0:aload_1
//* 1 1:ifnull 24
PlayerNotificationManager.access$500(PlayerNotificationManager.this).post(new Runnable() {
public void run()
{
if(PlayerNotificationManager.access$000(this$0) != null && notificationTag == PlayerNotificationManager.access$200(this$0) && PlayerNotificationManager.access$300(this$0))
//* 0 0:aload_0
//* 1 1:getfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
//* 2 4:getfield #33 <Field PlayerNotificationManager PlayerNotificationManager$BitmapCallback.this$0>
//* 3 7:invokestatic #37 <Method com.google.android.exoplayer2.Player PlayerNotificationManager.access$000(PlayerNotificationManager)>
//* 4 10:ifnull 61
//* 5 13:aload_0
//* 6 14:getfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
//* 7 17:invokestatic #41 <Method int PlayerNotificationManager$BitmapCallback.access$100(PlayerNotificationManager$BitmapCallback)>
//* 8 20:aload_0
//* 9 21:getfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
//* 10 24:getfield #33 <Field PlayerNotificationManager PlayerNotificationManager$BitmapCallback.this$0>
//* 11 27:invokestatic #45 <Method int PlayerNotificationManager.access$200(PlayerNotificationManager)>
//* 12 30:icmpne 61
//* 13 33:aload_0
//* 14 34:getfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
//* 15 37:getfield #33 <Field PlayerNotificationManager PlayerNotificationManager$BitmapCallback.this$0>
//* 16 40:invokestatic #49 <Method boolean PlayerNotificationManager.access$300(PlayerNotificationManager)>
//* 17 43:ifeq 61
PlayerNotificationManager.access$400(this$0, bitmap);
// 18 46:aload_0
// 19 47:getfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
// 20 50:getfield #33 <Field PlayerNotificationManager PlayerNotificationManager$BitmapCallback.this$0>
// 21 53:aload_0
// 22 54:getfield #24 <Field Bitmap val$bitmap>
// 23 57:invokestatic #53 <Method android.app.Notification PlayerNotificationManager.access$400(PlayerNotificationManager, Bitmap)>
// 24 60:pop
// 25 61:return
}
final PlayerNotificationManager.BitmapCallback this$1;
final Bitmap val$bitmap;
{
this$1 = PlayerNotificationManager.BitmapCallback.this;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #22 <Field PlayerNotificationManager$BitmapCallback this$1>
bitmap = bitmap1;
// 3 5:aload_0
// 4 6:aload_2
// 5 7:putfield #24 <Field Bitmap val$bitmap>
super();
// 6 10:aload_0
// 7 11:invokespecial #27 <Method void Object()>
// 8 14:return
}
}
);
// 2 4:aload_0
// 3 5:getfield #17 <Field PlayerNotificationManager this$0>
// 4 8:invokestatic #34 <Method Handler PlayerNotificationManager.access$500(PlayerNotificationManager)>
// 5 11:new #9 <Class PlayerNotificationManager$BitmapCallback$1>
// 6 14:dup
// 7 15:aload_0
// 8 16:aload_1
// 9 17:invokespecial #37 <Method void PlayerNotificationManager$BitmapCallback$1(PlayerNotificationManager$BitmapCallback, Bitmap)>
// 10 20:invokevirtual #43 <Method boolean Handler.post(Runnable)>
// 11 23:pop
// 12 24:return
}
private final int notificationTag;
final PlayerNotificationManager this$0;
/*
static int access$100(PlayerNotificationManager$BitmapCallback playernotificationmanager$bitmapcallback)
{
return playernotificationmanager$bitmapcallback.notificationTag;
// 0 0:aload_0
// 1 1:getfield #22 <Field int notificationTag>
// 2 4:ireturn
}
*/
private PlayerNotificationManager$BitmapCallback(int i)
{
this$0 = PlayerNotificationManager.this;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #17 <Field PlayerNotificationManager this$0>
super();
// 3 5:aload_0
// 4 6:invokespecial #20 <Method void Object()>
notificationTag = i;
// 5 9:aload_0
// 6 10:iload_2
// 7 11:putfield #22 <Field int notificationTag>
// 8 14:return
}
PlayerNotificationManager$BitmapCallback(int i, PlayerNotificationManager._cls1 _pcls1)
{
this(i);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:iload_2
// 3 3:invokespecial #26 <Method void PlayerNotificationManager$BitmapCallback(PlayerNotificationManager, int)>
// 4 6:return
}
}
|
Markdown
|
UTF-8
| 3,183
| 2.78125
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: '配置组指标: Exchange 2013 Help'
TOCTitle: 配置组指标
ms:assetid: 76ccd6a7-e2ec-42f4-9ab3-e8cc257ac896
ms:mtpsurl: https://technet.microsoft.com/zh-cn/library/JJ649327(v=EXCHG.150)
ms:contentKeyID: 50490859
ms.date: 05/21/2018
mtps_version: v=EXCHG.150
ms.translationtype: MT
---
# 配置组指标
_**适用于:**Exchange Server 2013_
_**上一次修改主题:**2015-04-08_
提供有关通讯组及动态通讯组大小的信息的邮件提示依赖于组指标数据。在指定的邮箱服务器上生成组指标数据。有关组指标的详细信息,请参阅[组的指标和邮件提醒](group-metrics-and-mailtips-exchange-2013-help.md)。
可以在邮箱服务器上启用或禁用组指标生成。
## 在开始之前,您需要知道什么?
- 估计完成每个步骤时间:10 分钟
- 您必须先获得权限,然后才能执行此过程或多个过程。若要查看所需的权限,请参阅 [收件人权限](recipients-permissions-exchange-2013-help.md)主题中的\"组指标\"条目。
- 组指标数据仅用于邮件提示。请确保在您的组织中已启用组指标邮件提示。有关详细步骤,请参阅[针对组织关系管理邮件提示](manage-mailtips-for-organization-relationships-exchange-2013-help.md)。
- 只能使用命令行管理程序执行此过程。
- 若要了解可能适用于此主题中过程的键盘快捷键,请参阅 [Exchange 管理中心内的键盘快捷键](keyboard-shortcuts-in-the-exchange-admin-center-exchange-online-protection-help.md)。
<table>
<thead>
<tr class="header">
<th><img src="images/Bb124558.tip(EXCHG.150).gif" title="提示" alt="提示" />提示:</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>遇到问题了吗?请在 Exchange 论坛中寻求帮助。 请访问以下论坛:<a href="https://go.microsoft.com/fwlink/p/?linkid=60612">Exchange Server</a>、 <a href="https://go.microsoft.com/fwlink/p/?linkid=267542">Exchange Online</a> 或 <a href="https://go.microsoft.com/fwlink/p/?linkid=285351">Exchange Online Protection</a>。</td>
</tr>
</tbody>
</table>
## 使用命令行管理程序启用或禁用组指标生成
<table>
<thead>
<tr class="header">
<th><img src="images/Bb124558.note(EXCHG.150).gif" title="注意" alt="注意" />注意:</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>默认情况下,在负责生成脱机通讯簿 (OAB) 的任何服务器上都会生成组指标数据。这些示例仅是不使用 OAB 的组织所需的。</td>
</tr>
</tbody>
</table>
要在邮箱服务器上启用或禁用组指标生成,请运行以下命令:
Set-MailboxServer <ServerIdentity> -ForceGroupMetricsGeneration <$true | $false>
此示例在名为 MBX1 的邮箱服务器上启用组指标生成。
Set-MailboxServer MBX1 -ForceGroupMetricsGeneration $true
## 您如何知道这有效?
要验证是否成功在不使用 OAB 的组织中启用或禁用了组指标生成,请执行以下操作:
1. 运行以下命令:
Get-MailboxServer <ServerIdentity> | Format-List ForceGroupMetricsGeneration
2. 验证显示的设置是否为您配置的设置。
|
Java
|
UTF-8
| 5,106
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.android.sunshine.app.wearable;
import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.example.android.sunshine.app.Utility;
import com.example.android.sunshine.app.data.WeatherContract;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import java.io.ByteArrayOutputStream;
/**
* This service is triggered to update the wearable watch face when weather data is sync
*
* Created by perklun on 1/17/2016.
*/
public class WearableIntentService extends IntentService implements DataApi.DataListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private static final String TAG = "LIST";
private static final String[] FORECAST_COLUMNS = {
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP
};
// these indices must match the projection
private static final int INDEX_WEATHER_ID = 0;
private static final int INDEX_MAX_TEMP = 2;
private static final int INDEX_MIN_TEMP = 3;
String formattedMaxTemperature;
String formattedMinTemperature;
int resourceID;
private GoogleApiClient mGoogleApiClient;
public WearableIntentService() {
super("WearableIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Get today's data from the ContentProvider
String location = Utility.getPreferredLocation(this);
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
location, System.currentTimeMillis());
Cursor data = getContentResolver().query(weatherForLocationUri, FORECAST_COLUMNS, null,
null, WeatherContract.WeatherEntry.COLUMN_DATE + " ASC");
if (data == null) {
return;
}
if (!data.moveToFirst()) {
data.close();
return;
}
// Extract the weather data from the Cursor
int weatherId = data.getInt(INDEX_WEATHER_ID);
double maxTemp = data.getDouble(INDEX_MAX_TEMP);
double minTemp = data.getDouble(INDEX_MIN_TEMP);
formattedMaxTemperature = Utility.formatTemperature(this, maxTemp);
formattedMinTemperature = Utility.formatTemperature(this, minTemp);
resourceID = Utility.getIconResourceForWeatherCondition(weatherId);
data.close();
sendNewWeatherData();
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void sendNewWeatherData(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/weather_data").setUrgent();
//Send image
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceID);
Asset asset = createAssetFromBitmap(bitmap);
putDataMapRequest.getDataMap().putAsset("IMAGE", asset);
//Send temperature
putDataMapRequest.getDataMap().putString("MAX", formattedMaxTemperature);
putDataMapRequest.getDataMap().putString("MIN", formattedMinTemperature);
PutDataRequest request = putDataMapRequest.asPutDataRequest();
Log.i(TAG, "Updating wearable app:" + formattedMaxTemperature + " " + formattedMinTemperature);
Wearable.DataApi.putDataItem(mGoogleApiClient, request).setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
@Override
public void onResult(DataApi.DataItemResult dataItemResult) {
Log.i(TAG, "Data sent...");
}
});
mGoogleApiClient.disconnect();
}
private static Asset createAssetFromBitmap(Bitmap bitmap) {
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
return Asset.createFromBytes(byteStream.toByteArray());
}
}
|
Python
|
UTF-8
| 258
| 3.640625
| 4
|
[] |
no_license
|
list = [942,423,394,435,543,504]
insert = int(input('can you insert a number here?: '))
#2. Create a for loop to test assumption:
for index, num in enumerate(list):
if num == insert:
print ("Found")
break
else:
print ("Not found")
|
Python
|
UTF-8
| 6,561
| 3.046875
| 3
|
[] |
no_license
|
#try it out ----> http://www.codeskulptor.org/#user33_ybIjaqqMaO_15.py
# Blackjack - with rules simplified a bit
import simplegui
import random
# load card sprite - 949x392 - source: jfitz.com
CARD_SIZE = (73, 98)
CARD_CENTER = (36.5, 49)
card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")
CARD_BACK_SIZE = (71, 96)
CARD_BACK_CENTER = (35.5, 48)
card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png")
cardB_loc = [CARD_BACK_SIZE[0]+CARD_BACK_CENTER[0], CARD_BACK_SIZE[1]+CARD_BACK_CENTER[1]]
# initialize some useful global variables
in_play = False
outcome = "Start new game - deal"
score = 0
# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}
# define card class
class Card:
def __init__(self, suit, rank):
if (suit in SUITS) and (rank in RANKS):
self.suit = suit
self.rank = rank
else:
self.suit = None
self.rank = None
print "Invalid card: ", suit, rank
def __str__(self):
return self.suit + self.rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
def draw(self, canvas, pos):
card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank),
CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
# define hand class
class Hand:
def __init__(self):
self.hand = [] # create Hand object
self.value = 0
self.word = "Hand contains"
def __str__(self):
# return a string representation of a hand
return self.word
def add_card(self, card):
self.word += " " + str(card)
self.hand.append(card) # add a card object to a hand
def get_value(self):
# count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust
self.value = 0
Ace = 0
for crd in self.hand:
self.value += VALUES[crd.rank] # default +1 for Ace
if crd.rank == 'A' :
Ace += 1
if (Ace >= 1) and (self.value + 10 < 21) : # if Ace already in hand and + 10 < 21
self.value += 10
return self.value
def draw(self, canvas, pos):
k = 0
for crd in self.hand : # draw a hand on the canvas, use the draw method for cards
crd.draw(canvas,[pos[0] + k*100,pos[1]])
k +=1
DEALER = Hand()
PLAYER = Hand()
# define deck class
class Deck:
def __init__(self):
# create a Deck object
self.cards = []
for i in SUITS :
for j in RANKS :
self.cards.append(Card(i,j))
self.count = 0
def shuffle(self):
# shuffle the deck
random.shuffle(self.cards)
def deal_card(self):
# deal a card object from the deck
self.count +=1
if self.count > 52:
self.cards = []
for i in SUITS :
for j in RANKS :
self.cards.append(Card(i,j))
return self.cards.pop()
def __str__(self):
# return a string representing the deck
word = "Deck contains"
print len(self.cards)
for k in range(len(self.cards)) :
word += " " + str(self.cards[k])
return word
# defintion of global Deck
DECK = Deck()
#define event handlers for buttons
def deal():
global outcome, in_play, DEALER, PLAYER
in_play = True
DECK = Deck()
DECK.shuffle()
DEALER = Hand()
PLAYER = Hand()
PLAYER.add_card(DECK.deal_card())
DEALER.add_card(DECK.deal_card())
PLAYER.add_card(DECK.deal_card())
DEALER.add_card(DECK.deal_card())
print "Dealer :", DEALER
print "Player :", PLAYER
outcome = "Hit or stand?"
def hit():
global in_play, outcome, score
PLAYER.add_card(DECK.deal_card())
print "Player value : ", PLAYER.get_value()
# if the hand is in play, hit the player
if PLAYER.get_value() <= 21 :
in_play = True
outcome = "Hit or stand?"
else :
in_play = False
print "Bust"
outcome = "You have busted..."
score -= 1
print "Dealer :", DEALER
print "Player :", PLAYER
def stand():
global in_play, outcome, score
# if hand is in play, repeatedly hit dealer until his hand has value 17 or more
if PLAYER.get_value() <= 21 :
in_play = False
while DEALER.get_value() < 17 :
DEALER.add_card(DECK.deal_card())
if DEALER.get_value() > 21 :
outcome = "Dealer is bust, you win!"
score += 1
else:
if PLAYER.get_value() <= DEALER.get_value() :
outcome = "Dealer wins"
score = score -1
else :
outcome = "You win!"
score += 1
else :
in_play = False
outcome = "You have busted"
score -= 1
print "Dealer :", DEALER
print "Player :", PLAYER
# draw handler
def draw(canvas):
global outcome
canvas.draw_text('BLACK',[50,60],30,"White")
canvas.draw_text('JACK',[155,60],30,"Black")
canvas.draw_text(outcome,[50,120],20,"Yellow")
if score >= 0 :
canvas.draw_text(str(score),[450,90],40,"lime")
else :
canvas.draw_text(str(score),[450,90],40,"red")
PLAYER.draw(canvas,[100,400])
DEALER.draw(canvas,[100,200])
if in_play:
canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [100 + CARD_BACK_SIZE[0]/2, 200 + CARD_BACK_SIZE[1]/2], CARD_BACK_SIZE)
# initialization frame
frame = simplegui.create_frame("Blackjack", 600, 600)
frame.set_canvas_background("Green")
#create buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit", hit, 200)
frame.add_button("Stand", stand, 200)
frame.set_draw_handler(draw)
# get things rolling
frame.start()
|
C++
|
UTF-8
| 811
| 2.71875
| 3
|
[] |
no_license
|
#include<iostream>
using namespace std;
int main()
{ int t;
cin>>t;
while(t--)
{ string output;
cin>>output;
int q;
cin>>q;
int count=0;
while(q--)
{
int output_freq[26]={0};
for(int i=0; i<output.length(); i++)
{ output_freq[output[i]-'a']++;
}
string input;
cin>>input;
int input_freq[26]={0};
for(int i=0; i<input.length(); i++)
{ input_freq[input[i]-'a']++;
}
bool ans=1;
for(int i=0; i<26; i++)
{ if(input_freq[i] != output_freq[i])
ans=0;
}
if(ans)
count++;
}
cout<<count<<endl;
}
return 0;
}
|
Java
|
UTF-8
| 1,190
| 3.4375
| 3
|
[] |
no_license
|
package br.com.gatto.assessment;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* The key to understanding this code is to notice that our thread pool size is
* only 2, but our CyclicBarrier limit is 3. Even though 12 tasks are all
* successfully submitted to the thread executor service by way of the stream
* forEach() method, the first two tasks will use up both available threads and
* wait indefinitely. Since a third await() is never executed, the barrier is
* never broken and the program hangs
*/
public class BabyPandaBathManager {
public static void await(CyclicBarrier cb) {
try {
cb.await();
} catch (InterruptedException | BrokenBarrierException e) {
// Handle exception
}
}
public static void main(String[] args) {
final CyclicBarrier cb = new CyclicBarrier(3, () -> System.out.println("Clean!"));
ExecutorService service = Executors.newScheduledThreadPool(2);
IntStream.iterate(1, i -> 1).limit(12).forEach(i -> service.submit(() -> await(cb)));
service.shutdown();
}
}
|
Java
|
UTF-8
| 1,916
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package com.tongming.manga.cusview;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by Tongming on 2016/8/11.
*/
public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
private int space;
private boolean isGrid;
public SpaceItemDecoration(int space) {
this.space = space;
}
public SpaceItemDecoration(int space, boolean isGrid) {
this.isGrid = isGrid;
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
int count = parent.getAdapter().getItemCount();
if (isGrid) {
count += count % 3 == 1 ? 2 : (count % 3 == 0 ? 0 : 1);
int row = count / 3;
if ((position + 1) % 3 == 1) {
//每一行的第一个
outRect.left = space;
outRect.right = space / 2;
} else if ((position + 1) % 3 == 0) {
//第三个
outRect.left = space / 2;
outRect.right = space;
} else {
outRect.left = space / 2;
outRect.right = space / 2;
}
if (position / 3 == 0) {
//第一行
outRect.top = space;
outRect.bottom = space / 2;
} else if (position / 3 == row - 1) {
//最后一行
outRect.top = space / 2;
outRect.bottom = space;
} else {
outRect.bottom = space / 2;
outRect.top = space / 2;
}
} else {
if (position != 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
}
|
C
|
UTF-8
| 460
| 2.8125
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int open_file = 0;
// buffer for writing to open_file
char *write_buffer_open_file = "ABCDEFG";
char *read_from_scanf = (char *) malloc(sizeof(char)*7);
if (write(open_file, write_buffer_open_file, 7) >= 0)
{
printf("%s\n", "");
return 0;
}
perror("Write");
exit(1);
}
|
C#
|
UTF-8
| 1,005
| 2.609375
| 3
|
[] |
no_license
|
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using System.Collections.Generic;
using NarouViewer.API;
namespace NarouViewer
{
public class UniqueUserLabel : Label, INovelData
{
private NovelData _model;
public NovelData model
{
set
{
_model = value;
OnChangeModel();
}
get
{
return _model;
}
}
public UniqueUserLabel(NovelData model)
{
this.Font = new Font("MS Pゴシック", 12F, FontStyle.Regular, GraphicsUnit.Point, 128);
this.Name = "UniqueUser";
this.Size = new Size(215, 18);
// model
this.model = model;
}
private void OnChangeModel()
{
if (model == null) return;
this.Text = "週別ユニークユーザ: " + model.weekly_unique + "人";
}
}
}
|
C
|
UTF-8
| 858
| 3.390625
| 3
|
[] |
no_license
|
typedef struct Snode
{
int data;
Snode *next;
}Snode,*PSnode;
void BinaryAddOne(PSnode&L)
{ //链表表头到表尾依次为高位到低位
PSnode Temp, q, p, s;
q = L->next; //遍历查找的头指针
p = L;
s = NULL; //查找0位的标记指针
while (q)
{
if (q->data==0)
s = q; //记录从最高位开始的最后一个0位的位置
q = q->next;
}
if (s)
{
s->data = 1; //记录的位置变为1
s = s->next;
while (s)
{
s->data = 0;//其后边的1位全变为0
s = s->next;
}
}
else
{//Temp 为二进制位满1时新进位空间开辟指针 形如1 3 7 15等二进制表示的下一个高位
Temp = new Snode;
Temp->data = 1; //采用头插法进行新进位的添加
Temp->next = p->next;
p->next = Temp;
Temp = Temp->next;
while (Temp) //新进位后的所有1位全变为0
{
Temp->data = 0;
Temp = Temp->next;
}
}
}
|
Java
|
GB18030
| 3,787
| 2.21875
| 2
|
[] |
no_license
|
package com.imanager.consume.service.impl;
import java.util.List;
import com.imanager.consume.dao.IConsumeItemDao;
import com.imanager.consume.dao.IConsumeTypeDao;
import com.imanager.consume.domain.ConsumeItem;
import com.imanager.consume.domain.ConsumeType;
import com.imanager.consume.domain.input.ConsumeSearchObj;
import com.imanager.consume.service.IConsumeService;
public class ConsumeServiceImpl implements IConsumeService {
private IConsumeItemDao consumeItemDao;
private IConsumeTypeDao consumeTypeDao;
/**
* һѼ¼
* @param consumeItem
*/
public void insertConsumeItem(ConsumeItem consumeItem) {
consumeItemDao.insertConsumeItem(consumeItem);
}
/**
* LoginIdͲѯб
* @param loginId
* @param searchObj
* @return
*/
@SuppressWarnings("unchecked")
public List<ConsumeItem> getConsumeItemListBySearch(ConsumeSearchObj searchObj) {
return consumeItemDao.getConsumeItemListBySearch(searchObj);
}
/**
* LoginIdͲѯбܶ
* @param loginId
* @param searchObj
* @return
*/
@SuppressWarnings("unchecked")
public double getConsumeItemListSumBySearch(ConsumeSearchObj searchObj) {
return consumeItemDao.getConsumeItemListSumBySearch(searchObj);
}
/**
* ItemIdѼ¼
* @param itemId
* @return
*/
public ConsumeItem getConsumeItemById(String consumeItemId){
return consumeItemDao.getConsumeItemById(consumeItemId);
}
/**
* һѼ¼
* @param consumeItem
* @return
*/
public boolean updateConsumeItem(ConsumeItem consumeItem){
return consumeItemDao.updateConsumeItem(consumeItem);
}
/**
* ɾѼ¼
* @param consumeItemId
* @param loginId
* @return
*/
public boolean logicDeleteConsumeItemById(String consumeItemId, String loginId){
return consumeItemDao.logicDeleteConsumeItemById(consumeItemId, loginId);
}
/* (non-Javadoc)
* @see com.imanager.consume.dao.IConsumeTypeDao#insertConsumeType(com.imanager.consume.domain.ConsumeType)
*/
public void insertConsumeType(ConsumeType consumeType) {
consumeTypeDao.insertConsumeType(consumeType);
}
/* (non-Javadoc)
* @see com.imanager.consume.dao.IConsumeTypeDao#getConsumeTypeListByLoginId(java.lang.String)
*/
@SuppressWarnings("unchecked")
public List<ConsumeType> getConsumeTypeListByLoginId(String loginId) {
return consumeTypeDao.getConsumeTypeListByLoginId(loginId);
}
/* (non-Javadoc)
* @see com.imanager.consume.dao.IConsumeTypeDao#getConsumeTypeByTypeId(java.lang.String)
*/
public ConsumeType getConsumeTypeById(String consumeTypeId) {
return consumeTypeDao.getConsumeTypeById(consumeTypeId);
}
/* (non-Javadoc)
* @see com.imanager.consume.dao.IConsumeTypeDao#updateConsumeType(com.imanager.consume.domain.ConsumeType)
*/
public boolean updateConsumeType(ConsumeType consumeType) {
return consumeTypeDao.updateConsumeType(consumeType);
}
/* (non-Javadoc)
* @see com.imanager.consume.dao.IConsumeTypeDao#logicDeleteConsumeTypeByTypeId(java.lang.String, java.lang.String)
*/
public boolean logicDeleteConsumeTypeById(String consumeTypeId, String loginId) {
return consumeTypeDao.logicDeleteConsumeTypeById(consumeTypeId, loginId);
}
public IConsumeItemDao getConsumeItemDao() {
return consumeItemDao;
}
public void setConsumeItemDao(IConsumeItemDao consumeItemDao) {
this.consumeItemDao = consumeItemDao;
}
public IConsumeTypeDao getConsumeTypeDao() {
return consumeTypeDao;
}
public void setConsumeTypeDao(IConsumeTypeDao consumeTypeDao) {
this.consumeTypeDao = consumeTypeDao;
}
}
|
C++
|
UTF-8
| 6,899
| 3.109375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "constants.h"
using namespace std;
// convert coordinates from global to car (the car is always at 0,0).
vector<double> global_to_car(double x, double y, double ref_x, double ref_y, double ref_yaw) {
double shift_x = x - ref_x;
double shift_y = y - ref_y;
double x_car = shift_x * cos(0-ref_yaw) - shift_y * sin(0-ref_yaw);
double y_car = shift_x * sin(0-ref_yaw) + shift_y * cos(0-ref_yaw);
return {x_car, y_car};
}
// convert car coordinates to global.
vector<double> car_to_global(double x, double y, double ref_x, double ref_y, double ref_yaw) {
double x_global = x * cos(ref_yaw) - y * sin(ref_yaw);
double y_global = x * sin(ref_yaw) + y * cos(ref_yaw);
x_global += ref_x;
y_global += ref_y;
return {x_global, y_global};
}
int d_to_lane(double d) {
return floor(d / LANEWIDTH);
}
double lane_to_d(int lane) {
return lane*LANEWIDTH+LANEWIDTH/2;
}
// represents the action to take.
// data is used for trajectory design.
struct action {
int lane;
double velocity;
};
// returns the speed of the nearest car in the specified lane in a given space.
// returns MAXVAL if there is no other car there.
double lane_is_busy(vector<vector<double>> sensor_fusion, int lane, double car_s, int prev_size,
double dist_behind, double dist_ahead) {
double min_dist = MAXVAL;
double speed_next = MAXVAL;
for (int i = 0; i < sensor_fusion.size(); i++) {
int lane_other = d_to_lane(sensor_fusion[i][6]);
if (lane_other == lane) {
double vx_other = sensor_fusion[i][3];
double vy_other = sensor_fusion[i][4];
double v_other = sqrt(vx_other*vx_other+vy_other*vy_other);
double s_other = sensor_fusion[i][5];
s_other += ((double)prev_size)*POINTSPEED*v_other;
double distance = s_other - car_s;
double other_speed = MS2MPH(v_other);
if (distance > dist_behind && distance < dist_ahead) {
if (min_dist > abs(distance)) {
min_dist = abs(distance);
speed_next = other_speed;
}
}
}
}
// if (min_dist < MAXVAL)
// cout << "lane: " << lane << " | speed: " << speed_next << ", dist: " << min_dist << endl;
return speed_next;
}
// returns the speed of the nearest car ahead.
// returns MAXVAL if there is no other car.
double lane_is_busy_ahead(vector<vector<double>> sensor_fusion, int lane, double car_s, int prev_size) {
return lane_is_busy(sensor_fusion, lane, car_s, prev_size, BUSYAHEADMIN, BUSYAHEADMAX);
}
// cost for keeping the same lane.
double cost_KEEP_LANE(vector<vector<double>> sensor_fusion, int car_lane, double car_s, int prev_size, bool busy_ahead) {
double cost = 0;
if (busy_ahead) cost += .4; // penalty to keep lane if there's a car ahead.
if (car_lane != 1) cost += .3; // prefer center lane.
return cost;
}
// cost for changing to the lane at the left.
double cost_LANE_CHANGE_LEFT(vector<vector<double>> sensor_fusion, int car_lane, double car_s, int prev_size, bool busy_ahead) {
double cost = 0.1; // basic penalty for turning
if (car_lane == 0) cost += 1; // don't go left if in leftmost lane
bool lbusy = lane_is_busy(sensor_fusion, car_lane-1, car_s, prev_size, BUSYCHANGEMIN, BUSYCHANGEMAX) < MAXVAL;
if (lbusy) cost += 1; // don't turn left if occupied
return cost;
}
// cost for changing to the lane at the right.
double cost_LANE_CHANGE_RIGHT(vector<vector<double>> sensor_fusion, int car_lane, double car_s, int prev_size, bool busy_ahead) {
double cost = 0.2; // basic penalty for turning right. prefers overtake through the left.
if (car_lane == 2) cost += 1; // don't go left if in right-most lane
bool lbusy = lane_is_busy(sensor_fusion, car_lane+1, car_s, prev_size, BUSYCHANGEMIN, BUSYCHANGEMAX) < MAXVAL;
if (lbusy) cost += 1; // don't turn right if occupied
return cost;
}
typedef double (*cost_type)(vector<vector<double>>, int, double, int, bool);
cost_type cost_functions[] = {
cost_KEEP_LANE,
cost_LANE_CHANGE_LEFT,
cost_LANE_CHANGE_RIGHT
};
string state_name(int state) {
string names[] = { "KEEP LANE", "LANE CHANGE LEFT", "LANE CHANGE RIGHT" };
return names[state];
}
// Simple Finite State Machine.
int get_next_state(vector<vector<double>> sensor_fusion, int car_lane, double car_s, int prev_size, bool busy_ahead) {
int next_state = KEEP_LANE;
double lowest_cost = 10;
for (int i = 0; i < 3; i++) {
double newcost = cost_functions[i](sensor_fusion, car_lane, car_s, prev_size, busy_ahead);
// cout << "state: " << state_name(i) << " cost: " << newcost << " | ";
if (newcost < lowest_cost) {
lowest_cost = newcost;
next_state = i;
}
}
// cout << endl;
return next_state;
}
// get the next car action (lane and velocity)
action next_action(vector<vector<double>> sensor_fusion,
double car_s, int prev_size, int lane_mine, double velocity) {
// cache some processing
double speed_ahead = lane_is_busy_ahead(sensor_fusion, lane_mine, car_s, prev_size);
bool busy_ahead = speed_ahead < MAXVAL;
// FSM
int next_state = get_next_state(sensor_fusion, lane_mine, car_s, prev_size, busy_ahead);
switch (next_state) {
case KEEP_LANE:
if (busy_ahead && velocity > (speed_ahead * SAFETYMARGIN)) {
// match the speed of car ahead
velocity -= NOJERKACC;
} else if (velocity < MAXVELOCITY) {
velocity += NOJERKACC;
}
break;
case LANE_CHANGE_RIGHT:
lane_mine += 1;
break;
case LANE_CHANGE_LEFT:
lane_mine -= 1;
break;
}
return { lane_mine, velocity };
}
// interpolate using the spline and convert back to global coordinates.
void interpolate_next_vals(vector<double> & next_x_vals, vector<double> &next_y_vals, tk::spline s,
int prev_size, double ref_x, double ref_y, double ref_yaw, double ref_vel) {
double x_target = SPLINESTEP;
double y_target = s(x_target);
double path = sqrt((x_target*x_target) + (y_target*y_target));
double x_addon = 0;
for (int k = 1; k < PATHPOINTS - prev_size; ++k) {
double N = path / (POINTSPEED * MPH2MS(ref_vel));
double x_point = x_addon + (x_target/N);
double y_point = s(x_point);
x_addon = x_point ;
vector<double> xy = car_to_global(x_point, y_point, ref_x, ref_y, ref_yaw);
next_x_vals.push_back(xy[0]);
next_y_vals.push_back(xy[1]);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.