code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.17"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>BlenderFDS: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="blenderfds_128.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">BlenderFDS </div> <div id="projectbrief">BlenderFDS, the open user interface for NIST Fire Dynamics Simulator (FDS), as an addon for Blender 2.8x</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.17 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>blenderfds28x</b></li><li class="navelem"><b>bl</b></li><li class="navelem"><a class="el" href="namespaceblenderfds28x_1_1bl_1_1operators.html">operators</a></li><li class="navelem"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">WM_OT_bf_dialog</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">blenderfds28x.bl.operators.WM_OT_bf_dialog Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>bl_description</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>bl_idname</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>bl_label</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>default</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>description</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html#a8db29ef502a85d192c3a60d01b7a6602">draw</a>(self, context)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>execute</b>(self, context) (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>invoke</b>(self, context, event) (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>items</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>name</b> (defined in <a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a>)</td><td class="entry"><a class="el" href="classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog.html">blenderfds28x.bl.operators.WM_OT_bf_dialog</a></td><td class="entry"><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.17 </small></address> </body> </html>
firetools/blenderfds
docs/html/classblenderfds28x_1_1bl_1_1operators_1_1_w_m___o_t__bf__dialog-members.html
HTML
gpl-3.0
8,008
andCA ===== AndCA is a a small Android application to capture videos and ingest them into Matterhorn. Its purpose in the long run is to become a complete [Opencast Matterhorn](http://opencast.org/matterhorn) Capture Agent for which recordings can be schedules automatically.
lkiesow/andCA
readme.md
Markdown
gpl-3.0
277
var panfeedModule = angular.module('panfeedModule', []); panfeedModule.config(function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.endSymbol(']]'); }); /* https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax */ jQuery(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } }); $(function() { $('#confirmDeleteModal .button-close').click(function() { $('#confirmDeleteModal').modal("hide"); }); $("input[name=_method][value=DELETE] + button[type=submit]").click(function(event) { event.preventDefault(); var button = $(this); $('#confirmDeleteModal .button-delete').unbind("click").click(function() { button.parent("div").parent("form").submit(); $('#confirmDeleteModal').modal("hide"); }); $('#confirmDeleteModal').modal("show"); }); });
Landric/PANFeed
panfeed/static/panfeed/scripts/initapp.js
JavaScript
gpl-3.0
2,447
/* * VITacademics * Copyright (C) 2015 Aneesh Neelam <neelam.aneesh@gmail.com> * Copyright (C) 2015 Gaurav Agerwala <gauravagerwala@gmail.com> * Copyright (C) 2015 Karthik Balakrishnan <karthikb351@gmail.com> * Copyright (C) 2015 Pulkit Juneja <pulkit.16296@gmail.com> * Copyright (C) 2015 Hemant Jain <hemanham@gmail.com> * * This file is part of VITacademics. * VITacademics is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VITacademics is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VITacademics. If not, see <http://www.gnu.org/licenses/>. */ package com.karthikb351.vitinfo2.fragment.details; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.karthikb351.vitinfo2.R; import com.karthikb351.vitinfo2.contract.Attendance; import com.karthikb351.vitinfo2.contract.AttendanceDetail; import com.karthikb351.vitinfo2.contract.Course; import com.karthikb351.vitinfo2.utility.DateTimeCalender; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AttendanceListAdapter extends RecyclerView.Adapter<AttendanceListAdapter.AttendanceViewHolder> { private int layoutId; private Context context; private Course course; private Attendance attendance; private List<AttendanceDetail> attendanceDetails; private int conducted, attended, classLength, miss = 0, attend = 0; public AttendanceListAdapter(Context context, Course course) { this.context = context; this.course = course; if (course.getAttendance().isSupported()) { this.attendance = course.getAttendance(); this.attendanceDetails = attendance.getDetails(); this.conducted = attendance.getTotalClasses(); this.attended = attendance.getAttendedClasses(); if (!(this.attendanceDetails == null || this.attendanceDetails.isEmpty())) { Collections.reverse(this.attendanceDetails); } } else { this.attendanceDetails = new ArrayList<>(); this.attendance = new Attendance(context.getString(R.string.registration_date_unavailable), 0, 0, 0, attendanceDetails, true); } classLength = course.getClassLength(); } @Override public AttendanceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(viewType, parent, false); return new AttendanceViewHolder(view); } @SuppressWarnings("deprecation") private void setProgressBarDrawable(ProgressBar progressBar) { if (getPercentage() >= 80) { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_green)); } else if (getPercentage() >= 75 && getPercentage() < 80) { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_orange)); } else { progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.ring_attendance_red)); } } private void updateHolder(AttendanceViewHolder holder) { holder.attendanceClasses.setText(context.getString(R.string.label_attendance_classes, attended + attend, conducted + attend + miss)); holder.txtAttend.setText(context.getString(R.string.label_class_go, attend)); holder.txtMiss.setText(context.getString(R.string.label_class_miss, miss)); holder.attendancePercent.setText(Integer.toString(getPercentage())); holder.progressBarAttendance.setProgress(getPercentage()); setProgressBarDrawable(holder.progressBarAttendance); } private int getPercentage() { return ((int) Math.ceil((double) (attended + attend) / (conducted + attend + miss) * 100)); } @Override public void onBindViewHolder(final AttendanceViewHolder holder, int position) { if (position == 0) { View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { if (view == holder.attendPlus) { attend += classLength; if (!holder.attendMinus.isClickable()) holder.attendMinus.setClickable(true); } else if (view == holder.attendMinus) { if (attend == 0) holder.attendMinus.setClickable(false); else attend -= classLength; } else if (view == holder.missPlus) { miss += classLength; if (!holder.missMinus.isClickable()) holder.missMinus.setClickable(true); } else if (view == holder.missMinus) { if (miss == 0) holder.missMinus.setClickable(false); else miss -= classLength; } updateHolder(holder); } }; updateHolder(holder); holder.courseName.setText(course.getCourseTitle()); holder.courseCode.setText(course.getCourseCode()); holder.attendPlus.setOnClickListener(onClickListener); holder.attendMinus.setOnClickListener(onClickListener); holder.missPlus.setOnClickListener(onClickListener); holder.missMinus.setOnClickListener(onClickListener); } else { try { holder.date.setText(DateTimeCalender.parseISO8601Date(attendanceDetails.get(position - 1).getDate())); } catch (ParseException ex) { ex.printStackTrace(); holder.date.setText(attendanceDetails.get(position - 1).getDate()); } holder.detailStatus.setText(attendanceDetails.get(position - 1).getStatus()); holder.classUnits.setText(context.getString(R.string.attendance_class_units_earned, attendanceDetails.get(position - 1).getClassUnits())); holder.reason.setText(attendanceDetails.get(position - 1).getReason()); } } @Override public int getItemCount() { if (attendanceDetails == null || attendanceDetails.isEmpty()) { return 1; } return (attendanceDetails.size() + 1); } @Override public int getItemViewType(int position) { if (position == 0) { layoutId = R.layout.card_attendance_summary; } else { layoutId = R.layout.card_attendance_detail; } return layoutId; } public class AttendanceViewHolder extends RecyclerView.ViewHolder { public TextView date, detailStatus, classUnits, reason, txtMiss, txtAttend; public TextView courseName, courseCode, attendanceClasses, attendancePercent; public ProgressBar progressBarAttendance; public Button attendPlus, attendMinus, missPlus, missMinus; public AttendanceViewHolder(View view) { super(view); attendPlus = (Button) view.findViewById(R.id.button_attend_plus); attendMinus = (Button) view.findViewById(R.id.button_attend_minus); missPlus = (Button) view.findViewById(R.id.button_miss_plus); missMinus = (Button) view.findViewById(R.id.button_miss_minus); txtMiss = (TextView) view.findViewById(R.id.txt_miss); txtAttend = (TextView) view.findViewById(R.id.txt_attend); date = (TextView) view.findViewById(R.id.date); detailStatus = (TextView) view.findViewById(R.id.detail_status); classUnits = (TextView) view.findViewById(R.id.class_units); reason = (TextView) view.findViewById(R.id.reason); courseName = (TextView) view.findViewById(R.id.course_name); courseCode = (TextView) view.findViewById(R.id.course_code); attendanceClasses = (TextView) view.findViewById(R.id.attendance_classes); attendancePercent = (TextView) view.findViewById(R.id.attendance_percent); progressBarAttendance = (ProgressBar) view.findViewById(R.id.progress_bar_attendance); } } }
CollegeCODE/VITacademics-Android
app/src/main/java/com/karthikb351/vitinfo2/fragment/details/AttendanceListAdapter.java
Java
gpl-3.0
9,017
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.items; import java.util.Arrays; import java.util.List; import net.minecraft.block.Block; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public abstract class ItemForestryTool extends ItemForestry { private final ItemStack remnants; protected float efficiencyOnProperMaterial; private final List<Block> blocksEffectiveAgainst; protected ItemForestryTool(Block[] blocksEffectiveAgainst, ItemStack remnants) { this.blocksEffectiveAgainst = Arrays.asList(blocksEffectiveAgainst); this.maxStackSize = 1; efficiencyOnProperMaterial = 6F; setMaxDamage(200); this.remnants = remnants; } @Override public float func_150893_a(ItemStack itemstack, Block block) { if (blocksEffectiveAgainst.contains(block)) { return efficiencyOnProperMaterial; } return 1.0F; } @Override public float getDigSpeed(ItemStack itemstack, Block block, int md) { if (ForgeHooks.isToolEffective(itemstack, block, md)) { return efficiencyOnProperMaterial; } return func_150893_a(itemstack, block); } @SubscribeEvent public void onDestroyCurrentItem(PlayerDestroyItemEvent event) { if (event.original == null || event.original.getItem() != this) { return; } if (!event.entityPlayer.worldObj.isRemote && remnants != null) { EntityItem entity = new EntityItem(event.entityPlayer.worldObj, event.entityPlayer.posX, event.entityPlayer.posY, event.entityPlayer.posZ, remnants.copy()); event.entityPlayer.worldObj.spawnEntityInWorld(entity); } } @Override public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, int j, int k, int l, EntityLivingBase entityliving) { itemstack.damageItem(1, entityliving); return true; } @Override public boolean isFull3D() { return true; } }
AnodeCathode/ForestryMC
src/main/java/forestry/core/items/ItemForestryTool.java
Java
gpl-3.0
2,632
<?php // Array type declaration - PHP 5.1+ function foo(array $a) {} function foo( array $a ) {} // Test extra spacing. // Callable type declaration - PHP 5.4+ function foo(callable $a) {} // Scalar type declarations - PHP 7.0+ function foo(bool $a) {} function foo(int $a) {} function foo(float $a) {} function foo(string $a) {} // Iterable type declaration - PHP 7.1+ function foo(iterable $a) {} // (Very likely) Invalid type declarations - will be treated as class/interface names. function foo(boolean $a) {} function foo(integer $a) {} class MyOtherClass extends MyClass { function foo(parent $a) {} function bar(static $a) {} } // Class/interface type declaration - PHP 5.0+ function foo(stdClass $a) {} // Class/interface type declaration with self keyword - PHP 5.0+ class MyClass { function foo(self $a) {} } function foo(self $a) {} // Invalid - not within a class. namespace test { class foo { function foo(self $a) {} } function foo(self $a) {} // Invalid - not within a class. } // Ok: No function parameters or no type hints. function foo() {} function foo( $a, $b ) {} // Type hints in closures. function (callable $a) {} function(int $a) {} // Deal with nullable type hints. function foo(?callable $a) {} function foo(?int $a) {}
AmrataRamchandani/moodle
local/codechecker/PHPCompatibility/Tests/sniff-examples/new_scalar_type_declarations.php
PHP
gpl-3.0
1,296
\chapter{Execute Test Suite} \label{execute_test_suite} Este capítulo apresenta a especificação do caso de uso \emph{Execute Test Suite}. \section{Breve Descrição} Os \foreign{suites} de testes são conjuntos de testes que devem ser executados juntos. A execução de um \foreign{suite} de testes, seja ele unitário ou não, corresponde à principal funcionalidade do sistema, uma vez que é através da execução de testes que se comprova a qualidade do modelo desenvolvido para a aplicação em questão. No entanto, a execução de um vasto conjunto de testes pode ter um custo computacional alto. Sendo assim, a possibilidade de empregar diversos nós computacionais (diferentes máquinas em uma rede de computadores) e diversos processos de testes em paralelo constituí um recurso valioso da ferramenta. O usuário configura como deseja executar o conjunto como um todo e as configurações de execução dos testes que formam o \foreign{suite} e comanda o início da execução. No caso da execução distribuída do \foreign{suite}, o sistema irá distribuir os vários testes entre os nós de acordo com seus recursos, e o resultados centralizados enviados de volta para consolidação. A funcionalidade representada pelo caso de uso \emph{Execute Teste Suite} possibilita que o usuário solicite a execução de todos os testes contidos no conjunto de testes indicado, obtendo os resultados dos testes e do conjunto como um todo. \section{Diagrama Parcial do Caso de Uso} \begin{figure}[h] \centering \includegraphics[scale=0.8]{images/execute_test_suite_partial_use_case_diagram} \caption{Diagrama parcial do caso de uso \foreign{Execute Test Suite}} \end{figure} \section{Fluxo Básico} A seguir são enumerados os passos do fluxo básico do caso de uso \emph{Execute Test Suite}. \begin{enumerate} \item O usuário informa o sistema que deseja executar um conjunto de testes. \item O sistema apresenta a tela de execução de conjunto de testes. \item O sistema apresenta a lista de conjuntos de testes cadastrados no projeto. \hyperref[A1_execute_test_suite]{\emph{A1}} \item O usuário seleciona na lista o conjunto de testes que deseja executar. \item O usuário informa que deseja executar o conjunto de testes selecionado. \item O sistema apresenta a tela de configuração de execução de conjunto de testes. \item O sistema invoca o caso de uso \emph{Configure Test Suite Execution} para que o usuário configure como se dará a execução do conjunto de testes. \hyperref[A2_execute_test_suite]{\emph{A2}} \item O sistema planeja a distribuição e execução dos testes de acordo com a configuração fornecida. \hyperref[A3_execute_test_suite]{\emph{A3}}. \item O sistema apresenta ao usuário o planejamento e distribuição dos testes e informa que está pronto para iniciar a execução. \item O usuário comanda o início da execução do conjunto de testes. \hyperref[A6_execute_test_suite]{\emph{A6}}, \hyperref[A7_execute_test_suite]{\emph{A7}} \item O sistema invoca o caso de uso \emph{Execute Test} para cada teste a ser executado. \hyperref[A8_execute_test_suite]{\emph{A8}}, \hyperref[A10_execute_test_suite]{\emph{A10}} \item O sistema recebe o resultado das execuções de todos os testes do conjunto de testes. \item O sistema apresenta o resultado das execuções ao usuário.\hyperref[A11_execute_test_suite]{\emph{A11}}, \hyperref[A12_execute_test_suite]{\emph{A12}} \item Caso de uso encerrado com sucesso. \end{enumerate} \section{Fluxos Alternativos} A seguir são apresentados os passos de fluxos do sistema que se desviam do fluxo básico do caso de uso \emph{Execute Test Suite}. \subsection{A1 - Falha ao obter a lista de conjuntos de testes do projeto} \label{A1_execute_test_suite} \begin{enumerate} \item O sistema informa que não foi possível obter a lista de conjuntos de testes do projeto e o motivo do erro. \item O sistema retorna ao estado de execução de conjuntos de testes. \item Caso de uso encerrado com falha. \end{enumerate} \subsection{A2 - Interrupção da configuração da execução do conjunto de testes} \label{A2_execute_test_suite} \begin{enumerate} \item O usuário interrompe a configuração da execução do conjunto de testes. \item O sistema ao item 2 do fluxo básico. \item Caso de uso interrompido. \end{enumerate} \subsection{A3 - Impossibilidade de execução de teste} \label{A3_execute_test_suite} \begin{enumerate} \item O sistema informa que não é capaz de executar o teste com a configuração fornecida e o motivo da impossibilidade. \item O sistema questiona se o teste deve ser ignorado ou se o usuário deseja alterar as configurações. \hyperref[A4_execute_test_suite]{\emph{A4}} \item O usuário informa que deseja alterar as configurações de execução do conjunto de testes. \item O sistema retorna ao item 5 do fluxo básico. \end{enumerate} \subsection{A4 - Remoção de teste do conjunto de teste a ser executado} \label{A4_execute_test_suite} \begin{enumerate} \item O usuário informa que o teste deve ser removido do conjunto de teste a ser executado naquele momento. \hyperref[A5_execute_test_suite]{\emph{A5}} \item O sistema retorna ao item 8 do fluxo básico e replaneja a execução do conjunto de testes sem o teste removido. \end{enumerate} \subsection{A5 - Conjunto de testes vazio} \label{A5_execute_test_suite} \begin{enumerate} \item O sistema detecta que não há mais nenhum teste a ser executado naquele momento. \item O sistema informa o usuário que não há testes possíveis de serem executados. \item O sistema retorna ao item 2 do fluxo básico. \item Caso de uso interrompido. \end{enumerate} \subsection{A6 - Alteração de configuração} \label{A6_execute_test_suite} \begin{enumerate} \item O usuário informa que deseja alterar as configurações de execução do conjunto de testes. \item O sistema retorna ao item 6 do fluxo básico. \end{enumerate} \subsection{A7 - Cancelamento da execução do conjunto de testes} \label{A7_execute_test_suite} \begin{enumerate} \item O usuário informa que deseja cancelar a execução do conjunto de testes. \item O sistema retorna ao item 2 do fluxo básico. \item Caso de uso interrompido. \end{enumerate} \subsection{A8 - Falha ao se comunicar com nó de execução de teste} \label{A8_execute_test_suite} \begin{enumerate} \item O sistema informa que não foi possível completar a comunicação com o nó de execução de testes o motivo do erro. \item O sistema verifica se há outro nó onde os testes podem ser executados. \item O sistema identifica outro nó onde os testes podem ser executados e os adiciona aos testes já alocados a este nó. \hyperref[A9_execute_test_suite]{\emph{A9}} \item Sistema retorna ao item 11 do fluxo básico. \end{enumerate} \subsection{A9 - Impossibilidade de realocação de testes} \label{A9_execute_test_suite} \begin{enumerate} \item O sistema informa que não foi possível realocar os testes. \item O sistema registra falha em todos os testes não realocados. \item Sistema retorna ao item 11 do fluxo básico. \end{enumerate} \subsection{A10 - Interrupção da execução dos testes} \label{A10_execute_test_suite} \begin{enumerate} \item O usuário informa que deseja interromper a execução dos testes. \item O sistema solicita confirmação da interrupção dos testes. \item O usuário confirma a interrupção dos testes. \item O sistema invoca o caso de uso \emph{Abort Test Suite Execution}. \item O sistema retorna ao item 2 do fluxo básico. \item Caso de uso interrompido. \end{enumerate} \subsection{A11 - Exportação de dados de testes} \label{A11_execute_test_suite} \begin{enumerate} \item O usuário informa que deseja exportar os dados dos testes. \item O sistema invoca o caso de uso \emph{Export Test Data}. \item O sistema retorna ao item 13 do fluxo básico. \end{enumerate} \subsection{A12 - Geração de relatório de execução de conjunto de testes} \label{A12_execute_test_suite} \begin{enumerate} \item O usuário informa que deseja gerar um relatório de execução do conjunto de testes. \item O sistema invoca o caso de uso \emph{Generate Report}. \item O sistema retorna ao item 13 do fluxo básico. \end{enumerate} \section{Pré-condições} \begin{itemize} \item Projeto de testes aberto no sistema. \item Projeto com ao menos um conjunto de testes cadastrado. \end{itemize} \section{Pós-condições} Nenhuma. \section{Atores} O ator principal do caso de uso é o testador (\foreign{Tester}). Não há atores secundários. \section{Cenário chave} O testador deseja executar um conjunto de testes, informando tal desejo ao sistema. O sistema apresenta a lista de conjuntos de testes existentes no projeto, e o testador solicita o conjunto a ser executado. O testador informa que está pronto para configurar a execução dos testes, e o sistema apresenta as telas correspondentes à configuração da execução do conjunto de testes como um todo e de cada teste em particular. Após finalizar as configurações de execução, o usuário solicita o início dos testes e aguarda enquanto o sistema planeja a execução e a leva a cabo empregando os nós computacionais selecionados. Ao final da execução dos testes o sistema apresenta os resultados, encerrando com sucesso o caso de uso. \section{Regras de negócio} Não aplicável. \section{Pontos de extensão} \begin{enumerate} \item Interrupção da execução do conjunto de testes (\foreign{Abort Test Suite Execution}). \hyperref[A10_execute_test_suite]{\emph{A10}} \item Exportação de dados de teste (\foreign{Export Test Data}). \hyperref[A11_execute_test_suite]{\emph{A11}} \item Geração de relatório (\foreign{Generate Report}). \hyperref[A12_execute_test_suite]{\emph{A12}} \end{enumerate} \section{Requisitos especiais} \begin{itemize} \item O tempo de planejamento da distribuição e execução dos testes deve crescer apenas proporcionalmente ao número de testes do conjunto. \item O sistema deve manter comunicação periódica com os nós remotos de execução de testes para confirmar que a execução continua sendo executada. \item O sistema deverá suportar falhas de comunicação entre nós de execução, redirecionando os testes a outros nós quando possível e informando as falhas quando não haver outro nó capaz de executá-los. \end{itemize} \section{Informações adicionais} Nós de execução remota devem possuir o serviço de execução de testes do sistema instalado e ativo.
ftovar/TCC
Documentos/CasosUso/capitulos/execute_test_suite.tex
TeX
gpl-3.0
10,795
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class cz_muni_fi_ode_NodeFactory */ #ifndef _Included_cz_muni_fi_ode_NodeFactory #define _Included_cz_muni_fi_ode_NodeFactory #ifdef __cplusplus extern "C" { #endif /* * Class: cz_muni_fi_ode_NodeFactory * Method: getNativePredecessors * Signature: ([ILcz/muni/fi/modelchecker/graph/ColorSet;Ljava/util/Map;)Ljava/util/Map; */ JNIEXPORT jobject JNICALL Java_cz_muni_fi_ode_NodeFactory_getNativePredecessors (JNIEnv *, jobject, jintArray, jobject, jobject); /* * Class: cz_muni_fi_ode_NodeFactory * Method: getNativeSuccessors * Signature: ([ILcz/muni/fi/modelchecker/graph/ColorSet;Ljava/util/Map;)Ljava/util/Map; */ JNIEXPORT jobject JNICALL Java_cz_muni_fi_ode_NodeFactory_getNativeSuccessors (JNIEnv *, jobject, jintArray, jobject, jobject); /* * Class: cz_muni_fi_ode_NodeFactory * Method: getNativeInit * Signature: (Ljava/lang/String;IDLjava/util/List;Ljava/util/Map;)Ljava/util/Map; */ JNIEXPORT jobject JNICALL Java_cz_muni_fi_ode_NodeFactory_getNativeInit (JNIEnv *, jobject, jstring, jint, jdouble, jobject, jobject); /* * Class: cz_muni_fi_ode_NodeFactory * Method: cacheAllNodes * Signature: (Ljava/util/List;)V */ JNIEXPORT void JNICALL Java_cz_muni_fi_ode_NodeFactory_cacheAllNodes (JNIEnv *, jobject, jobject); #ifdef __cplusplus } #endif #endif
sybila/biodivineCTL
ODE Abstraction/src/main/cpp/jni_include/NodeFactory.h
C
gpl-3.0
1,403
from ert_gui.models import ErtConnector from ert_gui.models.mixins import SpinnerModelMixin class LocalMaxRunning(ErtConnector, SpinnerModelMixin): def getMaxValue(self): """ @rtype: int """ return 1000 def getMinValue(self): """ @rtype: int """ return 1 def getSpinnerValue(self): """ @rtype: int """ return self.ert().siteConfig().getMaxRunningLocal() def setSpinnerValue(self, value): self.ert().siteConfig().setMaxRunningLocal(value)
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert_gui/models/connectors/queue_system/local_max_running.py
Python
gpl-3.0
519
BEGIN; DROP TABLE IF EXISTS hpd_business_addresses; CREATE TABLE hpd_business_addresses AS ( SELECT BusinessHouseNumber, BusinessStreetName, BusinessZip, BusinessApartment, count (*) as numberOfContacts, anyarray_remove_null(array_agg(CorporationName)) as corporationnames, anyarray_remove_null(array_agg(concat(firstname, ' ', lastname))) as ownernames, array_agg(registrationID) as regids, anyarray_uniq(array_agg(registrationID)) as uniqregids FROM hpd_contacts WHERE (BusinessHouseNumber IS NOT NULL AND BusinessStreetName IS NOT NULL AND BusinessZip IS NOT NULL) GROUP BY BusinessHouseNumber, BusinessStreetName, BusinessZip, BusinessApartment); ALTER TABLE hpd_business_addresses ADD COLUMN id serial; UPDATE hpd_business_addresses SET id = DEFAULT; ALTER TABLE hpd_business_addresses ADD PRIMARY KEY (id); ALTER TABLE hpd_business_addresses ADD COLUMN uniqcorpnames text[]; ALTER TABLE hpd_business_addresses ADD COLUMN uniqownernames text[]; -- remove blank fields from owner columns UPDATE hpd_business_addresses SET ownernames = array_remove(ownernames, ' '); UPDATE hpd_business_addresses SET uniqcorpnames = corporationnames; UPDATE hpd_business_addresses SET uniqownernames = ownernames; UPDATE hpd_business_addresses SET uniqregids = anyarray_uniq(regids); -- there appears to be at least row that causes an error with anyarray_unique, which is 'fixed' by the WHERE clause here. UPDATE hpd_business_addresses SET uniqcorpnames = anyarray_uniq(corporationnames) WHERE array_length(corporationnames, 1) > 0; UPDATE hpd_business_addresses SET uniqownernames = anyarray_uniq(ownernames) WHERE array_length(ownernames, 1) > 0; -- Add Lat, Lng. ALTER TABLE hpd_business_addresses ADD COLUMN lat numeric; ALTER TABLE hpd_business_addresses ADD COLUMN lng numeric; COMMIT;
aepyornis/hpd
sql/business_addrs.sql
SQL
gpl-3.0
1,957
package l2s.gameserver.network.l2.s2c; import java.util.ArrayList; import java.util.Collection; import l2s.gameserver.data.xml.holder.ProductDataHolder; import l2s.gameserver.model.Player; import l2s.gameserver.templates.item.product.ProductItem; import l2s.gameserver.templates.item.product.ProductItemComponent; public class ExBR_RecentProductListPacket extends L2GameProductPacket { private Collection<ProductItem> products; public ExBR_RecentProductListPacket(Player activeChar) { this.products = new ArrayList<>(); int[] products = activeChar.getRecentProductList(); if (products != null) { for (int productId : products) { ProductItem product = ProductDataHolder.getInstance().getProduct(productId); if (product == null) { continue; } this.products.add(product); } } } @Override protected void writeImpl() { writeD(0x01); // UNK writeD(products.size()); for (ProductItem product : products) { writeD(product.getId()); //product id writeH(product.getCategory()); //category 1 - enchant 2 - supplies 3 - decoration 4 - package 5 - other writeD(product.getPrice(true)); //points writeD(product.getTabId()); // show tab 2-th group - 1 показывает окошко про итем writeD(product.getSection()); // категория главной страницы (0 - не показывать на главное (дефолт), 1 - верхнее окно, 2 - рекомендуемый товар, 3 - неизвестно, 4 - популярные товары) // Glory Days 488 writeD((int) (product.getStartTimeSale() / 1000)); // start sale unix date in seconds writeD((int) (product.getEndTimeSale() / 1000)); // end sale unix date in seconds writeC(127); // day week (127 = not daily goods) writeC(product.getStartHour()); // start hour writeC(product.getStartMin()); // start min writeC(product.getEndHour()); // end hour writeC(product.getEndMin()); // end min writeD(0); // stock writeD(-1); // max stock // Glory Days 488 writeD(product.getDiscount()); // % скидки //writeD(1); // Увеличение уровня (Дефолт = 1) writeD(product.getComponents().size()); // Количество итемов в продукте. writeComponents(product); } } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ExBR_RecentProductListPacket.java
Java
gpl-3.0
2,625
!======================================================================== ! ! S P E C F E M 2 D Version 7 . 0 ! -------------------------------- ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! CNRS, France ! and Princeton University, USA ! (there are currently many more authors!) ! (c) October 2017 ! ! This software is a computer program whose purpose is to solve ! the two-dimensional viscoelastic anisotropic or poroelastic wave equation ! using a spectral-element method (SEM). ! ! This program is free software; you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation; either version 3 of the License, or ! (at your option) any later version. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License along ! with this program; if not, write to the Free Software Foundation, Inc., ! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ! ! The full text of the license is available in file "LICENSE". ! !======================================================================== ! for viscoelastic solver subroutine compute_coupling_viscoelastic_po() use constants, only: CUSTOM_REAL,IRIGHT,ILEFT,IBOTTOM,ITOP,NGLLX,NGLLZ,TWO,ZERO use specfem_par, only: SIMULATION_TYPE,num_solid_poro_edges, & ibool,wxgll,wzgll,xix,xiz,gammax,gammaz,jacobian,ivalue,jvalue,ivalue_inverse,jvalue_inverse, & hprime_xx,hprime_zz, & solid_poro_elastic_ispec,solid_poro_elastic_iedge, & solid_poro_poroelastic_ispec,solid_poro_poroelastic_iedge, & kmato,poroelastcoef, & assign_external_model,c11ext,c13ext,c15ext,c33ext,c35ext,c55ext,c12ext,c23ext,c25ext,anisotropy, & displ_elastic,b_displ_elastic,displs_poroelastic,displw_poroelastic, & b_displs_poroelastic,b_displw_poroelastic, & accel_elastic,b_accel_elastic implicit none !local variables integer :: inum,ispec_elastic,iedge_elastic,ispec_poroelastic,iedge_poroelastic, & i,j,k,ipoin1D,iglob,ii2,jj2 double precision :: phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f,mu_fr,kappa_fr,rho_bar double precision :: D_biot,H_biot,C_biot,M_biot double precision :: c11,c13,c15,c33,c35,c55,c12,c23,c25 double precision :: mul_unrelaxed_elastic,lambdal_unrelaxed_elastic,lambdaplus2mu_unrelaxed_elastic real(kind=CUSTOM_REAL) :: mu_G,lambdal_G,lambdalplus2mul_G real(kind=CUSTOM_REAL) :: dux_dxi,dux_dgamma,duz_dxi,duz_dgamma real(kind=CUSTOM_REAL) :: dwx_dxi,dwx_dgamma,dwz_dxi,dwz_dgamma real(kind=CUSTOM_REAL) :: dux_dxl,duz_dxl,dux_dzl,duz_dzl real(kind=CUSTOM_REAL) :: dwx_dxl,dwz_dxl,dwx_dzl,dwz_dzl real(kind=CUSTOM_REAL) :: b_dux_dxi,b_dux_dgamma,b_duz_dxi,b_duz_dgamma real(kind=CUSTOM_REAL) :: b_dux_dxl,b_duz_dxl,b_dux_dzl,b_duz_dzl real(kind=CUSTOM_REAL) :: b_dwx_dxi,b_dwx_dgamma,b_dwz_dxi,b_dwz_dgamma real(kind=CUSTOM_REAL) :: b_dwx_dxl,b_dwz_dxl,b_dwx_dzl,b_dwz_dzl real(kind=CUSTOM_REAL) :: sigma_xx,sigma_xz,sigma_zz real(kind=CUSTOM_REAL) :: b_sigma_xx,b_sigma_xz,b_sigma_zz real(kind=CUSTOM_REAL) :: xxi,zxi,xgamma,zgamma,jacobian1D,nx,nz,weight real(kind=CUSTOM_REAL) :: xixl,xizl,gammaxl,gammazl ! loop on all the coupling edges do inum = 1,num_solid_poro_edges ! get the edge of the elastic element ispec_elastic = solid_poro_elastic_ispec(inum) iedge_elastic = solid_poro_elastic_iedge(inum) ! get the corresponding edge of the poroelastic element ispec_poroelastic = solid_poro_poroelastic_ispec(inum) iedge_poroelastic = solid_poro_poroelastic_iedge(inum) ! implement 1D coupling along the edge do ipoin1D = 1,NGLLX ! get point values for the poroelastic side, which matches our side in the inverse direction i = ivalue_inverse(ipoin1D,iedge_poroelastic) j = jvalue_inverse(ipoin1D,iedge_poroelastic) iglob = ibool(i,j,ispec_poroelastic) ! gets poroelastic material call get_poroelastic_material(ispec_poroelastic,phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f, & mu_fr,kappa_fr,rho_bar) ! Biot coefficients for the input phi call get_poroelastic_Biot_coeff(phi,kappa_s,kappa_f,kappa_fr,mu_fr,D_biot,H_biot,C_biot,M_biot) mu_G = mu_fr lambdal_G = H_biot - 2._CUSTOM_REAL*mu_fr lambdalplus2mul_G = lambdal_G + TWO*mu_G ! derivative along x and along z for u_s and w dux_dxi = ZERO duz_dxi = ZERO dux_dgamma = ZERO duz_dgamma = ZERO dwx_dxi = ZERO dwz_dxi = ZERO dwx_dgamma = ZERO dwz_dgamma = ZERO if (SIMULATION_TYPE == 3) then b_dux_dxi = ZERO b_duz_dxi = ZERO b_dux_dgamma = ZERO b_duz_dgamma = ZERO b_dwx_dxi = ZERO b_dwz_dxi = ZERO b_dwx_dgamma = ZERO b_dwz_dgamma = ZERO endif ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ do k = 1,NGLLX dux_dxi = dux_dxi + displs_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) duz_dxi = duz_dxi + displs_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dux_dgamma = dux_dgamma + displs_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displs_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) dwx_dxi = dwx_dxi + displw_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dwz_dxi = dwz_dxi + displw_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dwx_dgamma = dwx_dgamma + displw_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) dwz_dgamma = dwz_dgamma + displw_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) if (SIMULATION_TYPE == 3) then b_dux_dxi = b_dux_dxi + b_displs_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_duz_dxi = b_duz_dxi + b_displs_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dux_dgamma = b_dux_dgamma + b_displs_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_duz_dgamma = b_duz_dgamma + b_displs_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_dwx_dxi = b_dwx_dxi + b_displw_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dwz_dxi = b_dwz_dxi + b_displw_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dwx_dgamma = b_dwx_dgamma + b_displw_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_dwz_dgamma = b_dwz_dgamma + b_displw_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) endif enddo xixl = xix(i,j,ispec_poroelastic) xizl = xiz(i,j,ispec_poroelastic) gammaxl = gammax(i,j,ispec_poroelastic) gammazl = gammaz(i,j,ispec_poroelastic) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl dux_dzl = dux_dxi*xizl + dux_dgamma*gammazl duz_dxl = duz_dxi*xixl + duz_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl dwx_dxl = dwx_dxi*xixl + dwx_dgamma*gammaxl dwx_dzl = dwx_dxi*xizl + dwx_dgamma*gammazl dwz_dxl = dwz_dxi*xixl + dwz_dgamma*gammaxl dwz_dzl = dwz_dxi*xizl + dwz_dgamma*gammazl if (SIMULATION_TYPE == 3) then b_dux_dxl = b_dux_dxi*xixl + b_dux_dgamma*gammaxl b_dux_dzl = b_dux_dxi*xizl + b_dux_dgamma*gammazl b_duz_dxl = b_duz_dxi*xixl + b_duz_dgamma*gammaxl b_duz_dzl = b_duz_dxi*xizl + b_duz_dgamma*gammazl b_dwx_dxl = b_dwx_dxi*xixl + b_dwx_dgamma*gammaxl b_dwx_dzl = b_dwx_dxi*xizl + b_dwx_dgamma*gammazl b_dwz_dxl = b_dwz_dxi*xixl + b_dwz_dgamma*gammaxl b_dwz_dzl = b_dwz_dxi*xizl + b_dwz_dgamma*gammazl endif ! compute stress tensor (include attenuation or anisotropy if needed) ! no attenuation sigma_xx = lambdalplus2mul_G*dux_dxl + lambdal_G*duz_dzl + C_biot*(dwx_dxl + dwz_dzl) sigma_xz = mu_G*(duz_dxl + dux_dzl) sigma_zz = lambdalplus2mul_G*duz_dzl + lambdal_G*dux_dxl + C_biot*(dwx_dxl + dwz_dzl) if (SIMULATION_TYPE == 3) then b_sigma_xx = lambdalplus2mul_G*b_dux_dxl + lambdal_G*b_duz_dzl + C_biot*(b_dwx_dxl + b_dwz_dzl) b_sigma_xz = mu_G*(b_duz_dxl + b_dux_dzl) b_sigma_zz = lambdalplus2mul_G*b_duz_dzl + lambdal_G*b_dux_dxl + C_biot*(b_dwx_dxl + b_dwz_dzl) endif ! get point values for the elastic domain, which matches our side in the inverse direction ii2 = ivalue(ipoin1D,iedge_elastic) jj2 = jvalue(ipoin1D,iedge_elastic) iglob = ibool(ii2,jj2,ispec_elastic) ! get elastic properties lambdal_unrelaxed_elastic = poroelastcoef(1,1,kmato(ispec_elastic)) mul_unrelaxed_elastic = poroelastcoef(2,1,kmato(ispec_elastic)) lambdaplus2mu_unrelaxed_elastic = poroelastcoef(3,1,kmato(ispec_elastic)) ! derivative along x and along z for u_s and w dux_dxi = ZERO duz_dxi = ZERO dux_dgamma = ZERO duz_dgamma = ZERO if (SIMULATION_TYPE == 3) then b_dux_dxi = ZERO b_duz_dxi = ZERO b_dux_dgamma = ZERO b_duz_dgamma = ZERO endif ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ do k = 1,NGLLX dux_dxi = dux_dxi + displ_elastic(1,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) duz_dxi = duz_dxi + displ_elastic(2,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) dux_dgamma = dux_dgamma + displ_elastic(1,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) duz_dgamma = duz_dgamma + displ_elastic(2,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) if (SIMULATION_TYPE == 3) then b_dux_dxi = b_dux_dxi + b_displ_elastic(1,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) b_duz_dxi = b_duz_dxi + b_displ_elastic(2,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) b_dux_dgamma = b_dux_dgamma + b_displ_elastic(1,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) b_duz_dgamma = b_duz_dgamma + b_displ_elastic(2,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) endif enddo xixl = xix(ii2,jj2,ispec_elastic) xizl = xiz(ii2,jj2,ispec_elastic) gammaxl = gammax(ii2,jj2,ispec_elastic) gammazl = gammaz(ii2,jj2,ispec_elastic) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl dux_dzl = dux_dxi*xizl + dux_dgamma*gammazl duz_dxl = duz_dxi*xixl + duz_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl if (SIMULATION_TYPE == 3) then b_dux_dxl = b_dux_dxi*xixl + b_dux_dgamma*gammaxl b_dux_dzl = b_dux_dxi*xizl + b_dux_dgamma*gammazl b_duz_dxl = b_duz_dxi*xixl + b_duz_dgamma*gammaxl b_duz_dzl = b_duz_dxi*xizl + b_duz_dgamma*gammazl endif ! compute stress tensor ! full anisotropy if (kmato(ispec_elastic) == 2) then ! implement anisotropy in 2D if (assign_external_model) then c11 = c11ext(ii2,jj2,ispec_elastic) c13 = c13ext(ii2,jj2,ispec_elastic) c15 = c15ext(ii2,jj2,ispec_elastic) c33 = c33ext(ii2,jj2,ispec_elastic) c35 = c35ext(ii2,jj2,ispec_elastic) c55 = c55ext(ii2,jj2,ispec_elastic) c12 = c12ext(ii2,jj2,ispec_elastic) c23 = c23ext(ii2,jj2,ispec_elastic) c25 = c25ext(ii2,jj2,ispec_elastic) else c11 = anisotropy(1,kmato(ispec_elastic)) c13 = anisotropy(2,kmato(ispec_elastic)) c15 = anisotropy(3,kmato(ispec_elastic)) c33 = anisotropy(4,kmato(ispec_elastic)) c35 = anisotropy(5,kmato(ispec_elastic)) c55 = anisotropy(6,kmato(ispec_elastic)) c12 = anisotropy(7,kmato(ispec_elastic)) c23 = anisotropy(8,kmato(ispec_elastic)) c25 = anisotropy(9,kmato(ispec_elastic)) endif sigma_xx = sigma_xx + c11*dux_dxl + c15*(duz_dxl + dux_dzl) + c13*duz_dzl sigma_zz = sigma_zz + c13*dux_dxl + c35*(duz_dxl + dux_dzl) + c33*duz_dzl sigma_xz = sigma_xz + c15*dux_dxl + c55*(duz_dxl + dux_dzl) + c35*duz_dzl else ! no attenuation sigma_xx = sigma_xx + lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl sigma_xz = sigma_xz + mul_unrelaxed_elastic*(duz_dxl + dux_dzl) sigma_zz = sigma_zz + lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl endif if (SIMULATION_TYPE == 3) then b_sigma_xx = b_sigma_xx + lambdaplus2mu_unrelaxed_elastic*b_dux_dxl + lambdal_unrelaxed_elastic*b_duz_dzl b_sigma_xz = b_sigma_xz + mul_unrelaxed_elastic*(b_duz_dxl + b_dux_dzl) b_sigma_zz = b_sigma_zz + lambdaplus2mu_unrelaxed_elastic*b_duz_dzl + lambdal_unrelaxed_elastic*b_dux_dxl endif ! compute the 1D Jacobian and the normal to the edge: for their expression see for instance ! O. C. Zienkiewicz and R. L. Taylor, The Finite Element Method for Solid and Structural Mechanics, ! Sixth Edition, electronic version, www.amazon.com, p. 204 and Figure 7.7(a), ! or Y. K. Cheung, S. H. Lo and A. Y. T. Leung, Finite Element Implementation, ! Blackwell Science, page 110, equation (4.60). if (iedge_poroelastic == ITOP) then xxi = + gammaz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zxi = - gammax(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xxi**2 + zxi**2) nx = - zxi / jacobian1D nz = + xxi / jacobian1D weight = jacobian1D * wxgll(i) else if (iedge_poroelastic == IBOTTOM) then xxi = + gammaz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zxi = - gammax(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xxi**2 + zxi**2) nx = + zxi / jacobian1D nz = - xxi / jacobian1D weight = jacobian1D * wxgll(i) else if (iedge_poroelastic == ILEFT) then xgamma = - xiz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zgamma = + xix(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xgamma**2 + zgamma**2) nx = - zgamma / jacobian1D nz = + xgamma / jacobian1D weight = jacobian1D * wzgll(j) else if (iedge_poroelastic == IRIGHT) then xgamma = - xiz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zgamma = + xix(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xgamma**2 + zgamma**2) nx = + zgamma / jacobian1D nz = - xgamma / jacobian1D weight = jacobian1D * wzgll(j) endif accel_elastic(1,iglob) = accel_elastic(1,iglob) - weight * (sigma_xx*nx + sigma_xz*nz)/2.d0 accel_elastic(2,iglob) = accel_elastic(2,iglob) - weight * (sigma_xz*nx + sigma_zz*nz)/2.d0 if (SIMULATION_TYPE == 3) then b_accel_elastic(1,iglob) = b_accel_elastic(1,iglob) - weight * (b_sigma_xx*nx + b_sigma_xz*nz)/2.d0 b_accel_elastic(2,iglob) = b_accel_elastic(2,iglob) - weight * (b_sigma_xz*nx + b_sigma_zz*nz)/2.d0 endif !if (SIMULATION_TYPE == 3) then enddo enddo end subroutine compute_coupling_viscoelastic_po ! !======================================================================== ! ! for viscoelastic solver subroutine compute_coupling_viscoelastic_po_backward() use constants, only: CUSTOM_REAL,IRIGHT,ILEFT,IBOTTOM,ITOP,NGLLX,NGLLZ,TWO,ZERO use specfem_par, only: SIMULATION_TYPE,num_solid_poro_edges, & ibool,wxgll,wzgll,xix,xiz,gammax,gammaz,jacobian,ivalue,jvalue,ivalue_inverse,jvalue_inverse, & hprime_xx,hprime_zz, & solid_poro_elastic_ispec,solid_poro_elastic_iedge, & solid_poro_poroelastic_ispec,solid_poro_poroelastic_iedge, & kmato,poroelastcoef, & assign_external_model,c11ext,c13ext,c15ext,c33ext,c35ext,c55ext,c12ext,c23ext,c25ext,anisotropy, & displ_elastic,b_displ_elastic,displs_poroelastic,displw_poroelastic, & b_displs_poroelastic,b_displw_poroelastic, & accel_elastic,b_accel_elastic implicit none !local variables integer :: inum,ispec_elastic,iedge_elastic,ispec_poroelastic,iedge_poroelastic, & i,j,k,ipoin1D,iglob,ii2,jj2 double precision :: phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f,mu_fr,kappa_fr,rho_bar double precision :: D_biot,H_biot,C_biot,M_biot double precision :: c11,c13,c15,c33,c35,c55,c12,c23,c25 double precision :: mul_unrelaxed_elastic,lambdal_unrelaxed_elastic,lambdaplus2mu_unrelaxed_elastic real(kind=CUSTOM_REAL) :: mu_G,lambdal_G,lambdalplus2mul_G real(kind=CUSTOM_REAL) :: dux_dxi,dux_dgamma,duz_dxi,duz_dgamma real(kind=CUSTOM_REAL) :: dwx_dxi,dwx_dgamma,dwz_dxi,dwz_dgamma real(kind=CUSTOM_REAL) :: dux_dxl,duz_dxl,dux_dzl,duz_dzl real(kind=CUSTOM_REAL) :: dwx_dxl,dwz_dxl,dwx_dzl,dwz_dzl real(kind=CUSTOM_REAL) :: b_dux_dxi,b_dux_dgamma,b_duz_dxi,b_duz_dgamma real(kind=CUSTOM_REAL) :: b_dux_dxl,b_duz_dxl,b_dux_dzl,b_duz_dzl real(kind=CUSTOM_REAL) :: b_dwx_dxi,b_dwx_dgamma,b_dwz_dxi,b_dwz_dgamma real(kind=CUSTOM_REAL) :: b_dwx_dxl,b_dwz_dxl,b_dwx_dzl,b_dwz_dzl real(kind=CUSTOM_REAL) :: sigma_xx,sigma_xz,sigma_zz real(kind=CUSTOM_REAL) :: b_sigma_xx,b_sigma_xz,b_sigma_zz real(kind=CUSTOM_REAL) :: xxi,zxi,xgamma,zgamma,jacobian1D,nx,nz,weight real(kind=CUSTOM_REAL) :: xixl,xizl,gammaxl,gammazl ! loop on all the coupling edges do inum = 1,num_solid_poro_edges ! get the edge of the elastic element ispec_elastic = solid_poro_elastic_ispec(inum) iedge_elastic = solid_poro_elastic_iedge(inum) ! get the corresponding edge of the poroelastic element ispec_poroelastic = solid_poro_poroelastic_ispec(inum) iedge_poroelastic = solid_poro_poroelastic_iedge(inum) ! implement 1D coupling along the edge do ipoin1D = 1,NGLLX ! get point values for the poroelastic side, which matches our side in the inverse direction i = ivalue_inverse(ipoin1D,iedge_poroelastic) j = jvalue_inverse(ipoin1D,iedge_poroelastic) iglob = ibool(i,j,ispec_poroelastic) ! get poroelastic domain paramters ! gets poroelastic material call get_poroelastic_material(ispec_poroelastic,phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f, & mu_fr,kappa_fr,rho_bar) ! Biot coefficients for the input phi call get_poroelastic_Biot_coeff(phi,kappa_s,kappa_f,kappa_fr,mu_fr,D_biot,H_biot,C_biot,M_biot) mu_G = mu_fr lambdal_G = H_biot - 2._CUSTOM_REAL*mu_fr lambdalplus2mul_G = lambdal_G + TWO*mu_G ! derivative along x and along z for u_s and w b_dux_dxi = ZERO b_duz_dxi = ZERO b_dux_dgamma = ZERO b_duz_dgamma = ZERO b_dwx_dxi = ZERO b_dwz_dxi = ZERO b_dwx_dgamma = ZERO b_dwz_dgamma = ZERO ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ do k = 1,NGLLX dux_dxi = dux_dxi + displs_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) duz_dxi = duz_dxi + displs_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dux_dgamma = dux_dgamma + displs_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displs_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) dwx_dxi = dwx_dxi + displw_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dwz_dxi = dwz_dxi + displw_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) dwx_dgamma = dwx_dgamma + displw_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) dwz_dgamma = dwz_dgamma + displw_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) if (SIMULATION_TYPE == 3) then b_dux_dxi = b_dux_dxi + b_displs_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_duz_dxi = b_duz_dxi + b_displs_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dux_dgamma = b_dux_dgamma + b_displs_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_duz_dgamma = b_duz_dgamma + b_displs_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_dwx_dxi = b_dwx_dxi + b_displw_poroelastic(1,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dwz_dxi = b_dwz_dxi + b_displw_poroelastic(2,ibool(k,j,ispec_poroelastic))*hprime_xx(i,k) b_dwx_dgamma = b_dwx_dgamma + b_displw_poroelastic(1,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) b_dwz_dgamma = b_dwz_dgamma + b_displw_poroelastic(2,ibool(i,k,ispec_poroelastic))*hprime_zz(j,k) endif enddo xixl = xix(i,j,ispec_poroelastic) xizl = xiz(i,j,ispec_poroelastic) gammaxl = gammax(i,j,ispec_poroelastic) gammazl = gammaz(i,j,ispec_poroelastic) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl dux_dzl = dux_dxi*xizl + dux_dgamma*gammazl duz_dxl = duz_dxi*xixl + duz_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl dwx_dxl = dwx_dxi*xixl + dwx_dgamma*gammaxl dwx_dzl = dwx_dxi*xizl + dwx_dgamma*gammazl dwz_dxl = dwz_dxi*xixl + dwz_dgamma*gammaxl dwz_dzl = dwz_dxi*xizl + dwz_dgamma*gammazl if (SIMULATION_TYPE == 3) then b_dux_dxl = b_dux_dxi*xixl + b_dux_dgamma*gammaxl b_dux_dzl = b_dux_dxi*xizl + b_dux_dgamma*gammazl b_duz_dxl = b_duz_dxi*xixl + b_duz_dgamma*gammaxl b_duz_dzl = b_duz_dxi*xizl + b_duz_dgamma*gammazl b_dwx_dxl = b_dwx_dxi*xixl + b_dwx_dgamma*gammaxl b_dwx_dzl = b_dwx_dxi*xizl + b_dwx_dgamma*gammazl b_dwz_dxl = b_dwz_dxi*xixl + b_dwz_dgamma*gammaxl b_dwz_dzl = b_dwz_dxi*xizl + b_dwz_dgamma*gammazl endif ! compute stress tensor (include attenuation or anisotropy if needed) ! no attenuation sigma_xx = lambdalplus2mul_G*dux_dxl + lambdal_G*duz_dzl + C_biot*(dwx_dxl + dwz_dzl) sigma_xz = mu_G*(duz_dxl + dux_dzl) sigma_zz = lambdalplus2mul_G*duz_dzl + lambdal_G*dux_dxl + C_biot*(dwx_dxl + dwz_dzl) if (SIMULATION_TYPE == 3) then b_sigma_xx = lambdalplus2mul_G*b_dux_dxl + lambdal_G*b_duz_dzl + C_biot*(b_dwx_dxl + b_dwz_dzl) b_sigma_xz = mu_G*(b_duz_dxl + b_dux_dzl) b_sigma_zz = lambdalplus2mul_G*b_duz_dzl + lambdal_G*b_dux_dxl + C_biot*(b_dwx_dxl + b_dwz_dzl) endif ! get point values for the elastic domain, which matches our side in the inverse direction ii2 = ivalue(ipoin1D,iedge_elastic) jj2 = jvalue(ipoin1D,iedge_elastic) iglob = ibool(ii2,jj2,ispec_elastic) ! get elastic properties lambdal_unrelaxed_elastic = poroelastcoef(1,1,kmato(ispec_elastic)) mul_unrelaxed_elastic = poroelastcoef(2,1,kmato(ispec_elastic)) lambdaplus2mu_unrelaxed_elastic = poroelastcoef(3,1,kmato(ispec_elastic)) ! derivative along x and along z for u_s and w dux_dxi = ZERO duz_dxi = ZERO dux_dgamma = ZERO duz_dgamma = ZERO if (SIMULATION_TYPE == 3) then b_dux_dxi = ZERO b_duz_dxi = ZERO b_dux_dgamma = ZERO b_duz_dgamma = ZERO endif ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ do k = 1,NGLLX dux_dxi = dux_dxi + displ_elastic(1,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) duz_dxi = duz_dxi + displ_elastic(2,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) dux_dgamma = dux_dgamma + displ_elastic(1,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) duz_dgamma = duz_dgamma + displ_elastic(2,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) if (SIMULATION_TYPE == 3) then b_dux_dxi = b_dux_dxi + b_displ_elastic(1,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) b_duz_dxi = b_duz_dxi + b_displ_elastic(2,ibool(k,jj2,ispec_elastic))*hprime_xx(ii2,k) b_dux_dgamma = b_dux_dgamma + b_displ_elastic(1,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) b_duz_dgamma = b_duz_dgamma + b_displ_elastic(2,ibool(ii2,k,ispec_elastic))*hprime_zz(jj2,k) endif enddo xixl = xix(ii2,jj2,ispec_elastic) xizl = xiz(ii2,jj2,ispec_elastic) gammaxl = gammax(ii2,jj2,ispec_elastic) gammazl = gammaz(ii2,jj2,ispec_elastic) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl dux_dzl = dux_dxi*xizl + dux_dgamma*gammazl duz_dxl = duz_dxi*xixl + duz_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl if (SIMULATION_TYPE == 3) then b_dux_dxl = b_dux_dxi*xixl + b_dux_dgamma*gammaxl b_dux_dzl = b_dux_dxi*xizl + b_dux_dgamma*gammazl b_duz_dxl = b_duz_dxi*xixl + b_duz_dgamma*gammaxl b_duz_dzl = b_duz_dxi*xizl + b_duz_dgamma*gammazl endif ! compute stress tensor ! full anisotropy if (kmato(ispec_elastic) == 2) then ! implement anisotropy in 2D if (assign_external_model) then c11 = c11ext(ii2,jj2,ispec_elastic) c13 = c13ext(ii2,jj2,ispec_elastic) c15 = c15ext(ii2,jj2,ispec_elastic) c33 = c33ext(ii2,jj2,ispec_elastic) c35 = c35ext(ii2,jj2,ispec_elastic) c55 = c55ext(ii2,jj2,ispec_elastic) c12 = c12ext(ii2,jj2,ispec_elastic) c23 = c23ext(ii2,jj2,ispec_elastic) c25 = c25ext(ii2,jj2,ispec_elastic) else c11 = anisotropy(1,kmato(ispec_elastic)) c13 = anisotropy(2,kmato(ispec_elastic)) c15 = anisotropy(3,kmato(ispec_elastic)) c33 = anisotropy(4,kmato(ispec_elastic)) c35 = anisotropy(5,kmato(ispec_elastic)) c55 = anisotropy(6,kmato(ispec_elastic)) c12 = anisotropy(7,kmato(ispec_elastic)) c23 = anisotropy(8,kmato(ispec_elastic)) c25 = anisotropy(9,kmato(ispec_elastic)) endif sigma_xx = sigma_xx + c11*dux_dxl + c15*(duz_dxl + dux_dzl) + c13*duz_dzl sigma_zz = sigma_zz + c13*dux_dxl + c35*(duz_dxl + dux_dzl) + c33*duz_dzl sigma_xz = sigma_xz + c15*dux_dxl + c55*(duz_dxl + dux_dzl) + c35*duz_dzl else ! no attenuation sigma_xx = sigma_xx + lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl sigma_xz = sigma_xz + mul_unrelaxed_elastic*(duz_dxl + dux_dzl) sigma_zz = sigma_zz + lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl endif if (SIMULATION_TYPE == 3) then b_sigma_xx = b_sigma_xx + lambdaplus2mu_unrelaxed_elastic*b_dux_dxl + lambdal_unrelaxed_elastic*b_duz_dzl b_sigma_xz = b_sigma_xz + mul_unrelaxed_elastic*(b_duz_dxl + b_dux_dzl) b_sigma_zz = b_sigma_zz + lambdaplus2mu_unrelaxed_elastic*b_duz_dzl + lambdal_unrelaxed_elastic*b_dux_dxl endif ! compute the 1D Jacobian and the normal to the edge: for their expression see for instance ! O. C. Zienkiewicz and R. L. Taylor, The Finite Element Method for Solid and Structural Mechanics, ! Sixth Edition, electronic version, www.amazon.com, p. 204 and Figure 7.7(a), ! or Y. K. Cheung, S. H. Lo and A. Y. T. Leung, Finite Element Implementation, ! Blackwell Science, page 110, equation (4.60). if (iedge_poroelastic == ITOP) then xxi = + gammaz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zxi = - gammax(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xxi**2 + zxi**2) nx = - zxi / jacobian1D nz = + xxi / jacobian1D weight = jacobian1D * wxgll(i) else if (iedge_poroelastic == IBOTTOM) then xxi = + gammaz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zxi = - gammax(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xxi**2 + zxi**2) nx = + zxi / jacobian1D nz = - xxi / jacobian1D weight = jacobian1D * wxgll(i) else if (iedge_poroelastic == ILEFT) then xgamma = - xiz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zgamma = + xix(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xgamma**2 + zgamma**2) nx = - zgamma / jacobian1D nz = + xgamma / jacobian1D weight = jacobian1D * wzgll(j) else if (iedge_poroelastic == IRIGHT) then xgamma = - xiz(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) zgamma = + xix(i,j,ispec_poroelastic) * jacobian(i,j,ispec_poroelastic) jacobian1D = sqrt(xgamma**2 + zgamma**2) nx = + zgamma / jacobian1D nz = - xgamma / jacobian1D weight = jacobian1D * wzgll(j) endif accel_elastic(1,iglob) = accel_elastic(1,iglob) - weight * (sigma_xx*nx + sigma_xz*nz)/2.d0 accel_elastic(2,iglob) = accel_elastic(2,iglob) - weight * (sigma_xz*nx + sigma_zz*nz)/2.d0 if (SIMULATION_TYPE == 3) then b_accel_elastic(1,iglob) = b_accel_elastic(1,iglob) - weight * (b_sigma_xx*nx + b_sigma_xz*nz)/2.d0 b_accel_elastic(2,iglob) = b_accel_elastic(2,iglob) - weight * (b_sigma_xz*nx + b_sigma_zz*nz)/2.d0 endif !if (SIMULATION_TYPE == 3) then enddo enddo end subroutine compute_coupling_viscoelastic_po_backward
geodynamics/specfem2d
src/specfem2D/compute_coupling_viscoelastic_po.f90
FORTRAN
gpl-3.0
30,279
!======================================================================== ! ! S P E C F E M 2 D Version 7 . 0 ! -------------------------------- ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! CNRS, France ! and Princeton University, USA ! (there are currently many more authors!) ! (c) October 2017 ! ! This software is a computer program whose purpose is to solve ! the two-dimensional viscoelastic anisotropic or poroelastic wave equation ! using a spectral-element method (SEM). ! ! This program is free software; you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation; either version 3 of the License, or ! (at your option) any later version. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License along ! with this program; if not, write to the Free Software Foundation, Inc., ! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ! ! The full text of the license is available in file "LICENSE". ! !======================================================================== subroutine compute_pressure_whole_medium(i_field) ! compute pressure in acoustic elements and in elastic elements use specfem_par, only: CUSTOM_REAL,NGLLX,NGLLZ,nspec,ibool,displ_elastic,displs_poroelastic,displw_poroelastic, & potential_dot_dot_acoustic,potential_acoustic,b_displ_elastic,b_displs_poroelastic, & b_displw_poroelastic,b_potential_dot_dot_acoustic,b_potential_acoustic use specfem_par_movie, only: vector_field_display implicit none ! forwrad or adjoint wavefield) integer :: i_field ! local parameters integer :: i,j,ispec,iglob ! pressure in an element real(kind=CUSTOM_REAL), dimension(NGLLX,NGLLZ) :: pressure_element ! loop over spectral elements do ispec = 1,nspec ! compute pressure in this element if (i_field == 1) then call compute_pressure_one_element(ispec,pressure_element,displ_elastic,displs_poroelastic,displw_poroelastic, & potential_dot_dot_acoustic,potential_acoustic) else call compute_pressure_one_element(ispec,pressure_element,b_displ_elastic,b_displs_poroelastic,b_displw_poroelastic, & b_potential_dot_dot_acoustic,b_potential_acoustic) endif ! use vector_field_display as temporary storage, store pressure in its second component do j = 1,NGLLZ do i = 1,NGLLX iglob = ibool(i,j,ispec) vector_field_display(2,iglob) = pressure_element(i,j) enddo enddo enddo end subroutine compute_pressure_whole_medium ! !===================================================================== ! subroutine compute_pressure_one_element(ispec,pressure_element,displ_elastic,displs_poroelastic,displw_poroelastic, & potential_dot_dot_acoustic,potential_acoustic) ! compute pressure in acoustic elements and in elastic elements use constants, only: CUSTOM_REAL,NGLLX,NGLLZ,NGLJ,ZERO,TWO,NDIM use specfem_par, only: N_SLS,nglob,ispec_is_elastic,ispec_is_acoustic,ispec_is_poroelastic, & ispec_is_anisotropic,kmato,poroelastcoef,assign_external_model,vpext,vsext,rhoext, & ATTENUATION_VISCOELASTIC,AXISYM,is_on_the_axis, & anisotropy,c11ext,c12ext,c13ext,c15ext,c23ext,c25ext,c33ext,c35ext,c55ext, & hprimebar_xx,hprime_xx,hprime_zz,xix,xiz,gammax,gammaz,jacobian,ibool,coord,e1,e11,USE_TRICK_FOR_BETTER_PRESSURE implicit none integer,intent(in) :: ispec ! pressure in an element real(kind=CUSTOM_REAL), dimension(NGLLX,NGLLZ),intent(out) :: pressure_element real(kind=CUSTOM_REAL), dimension(nglob),intent(in) :: potential_dot_dot_acoustic,potential_acoustic real(kind=CUSTOM_REAL), dimension(NDIM,nglob),intent(in) :: displ_elastic,displs_poroelastic,displw_poroelastic ! local variables real(kind=CUSTOM_REAL) :: e1_sum,e11_sum integer :: i_sls integer :: i,j,k,iglob real(kind=CUSTOM_REAL) :: sigma_yy !! ,sigmap real(kind=CUSTOM_REAL) :: sigma_thetatheta ! material properties of the elastic medium real(kind=CUSTOM_REAL) :: denst real(kind=CUSTOM_REAL) :: cpl,csl real(kind=CUSTOM_REAL) :: mu_G,lambdal_G,lambdalplus2mul_G ! for anisotropy double precision :: c11,c15,c13,c33,c35,c55,c12,c23,c25 ! Jacobian matrix and determinant double precision :: xixl,xizl,gammaxl,gammazl ! to evaluate cpI, cpII, and cs, and rI (poroelastic medium) double precision :: phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f,mu_fr,kappa_fr,rho_bar double precision :: D_biot,H_biot,C_biot,M_biot double precision :: mul_unrelaxed_elastic,lambdal_unrelaxed_elastic,lambdaplus2mu_unrelaxed_elastic double precision :: sigma_xx,sigma_zz double precision :: dux_dxi,dux_dgamma,duz_dxi,duz_dgamma double precision :: dwx_dxi,dwx_dgamma,dwz_dxi,dwz_dgamma double precision :: dux_dxl,duz_dxl,dux_dzl,duz_dzl double precision :: dwx_dxl,dwz_dzl double precision :: xxi ! initializes pressure_element(:,:) = 0._CUSTOM_REAL ! if elastic element ! ! from L. S. Bennethum, Compressibility Moduli for Porous Materials Incorporating Volume Fraction, ! J. Engrg. Mech., vol. 132(11), p. 1205-1214 (2006), below equation (5): ! for a 3D isotropic solid, pressure is defined in terms of the trace of the stress tensor as ! p = -1/3 (t11 + t22 + t33) where t is the Cauchy stress tensor. ! to compute pressure in 3D in an elastic solid, one uses pressure = - trace(sigma) / 3 ! sigma_ij = lambda delta_ij trace(epsilon) + 2 mu epsilon_ij ! = lambda (epsilon_xx + epsilon_yy + epsilon_zz) + 2 mu epsilon_ij ! sigma_xx = lambda (epsilon_xx + epsilon_yy + epsilon_zz) + 2 mu epsilon_xx ! sigma_yy = lambda (epsilon_xx + epsilon_yy + epsilon_zz) + 2 mu epsilon_yy ! sigma_zz = lambda (epsilon_xx + epsilon_yy + epsilon_zz) + 2 mu epsilon_zz ! pressure = - trace(sigma) / 3 = - (lambda + 2/3 mu) trace(epsilon) = - kappa * trace(epsilon) ! ! to compute pressure in 2D in an elastic solid in the plane strain convention i.e. in the P-SV case, ! one still uses pressure = - trace(sigma) / 3 but taking into account the fact ! that the off-plane strain epsilon_zz is zero by definition of the plane strain convention ! but thus the off-plane stress sigma_zz is not equal to zero, ! one has instead: sigma_zz = lambda * (epsilon_xx + epsilon_yy), thus ! sigma_ij = lambda delta_ij trace(epsilon) + 2 mu epsilon_ij ! = lambda (epsilon_xx + epsilon_yy) + 2 mu epsilon_ij ! sigma_xx = lambda (epsilon_xx + epsilon_yy) + 2 mu epsilon_xx ! sigma_yy = lambda (epsilon_xx + epsilon_yy) + 2 mu epsilon_yy ! sigma_zz = lambda * (epsilon_xx + epsilon_yy) ! pressure = - trace(sigma) / 3 = - (lambda + 2*mu/3) (epsilon_xx + epsilon_yy) if (ispec_is_elastic(ispec)) then ! elastic element ! get relaxed elastic parameters of current spectral element lambdal_unrelaxed_elastic = poroelastcoef(1,1,kmato(ispec)) mul_unrelaxed_elastic = poroelastcoef(2,1,kmato(ispec)) lambdaplus2mu_unrelaxed_elastic = poroelastcoef(3,1,kmato(ispec)) do j = 1,NGLLZ do i = 1,NGLLX !--- if external medium, get elastic parameters of current grid point if (assign_external_model) then cpl = vpext(i,j,ispec) csl = vsext(i,j,ispec) denst = rhoext(i,j,ispec) mul_unrelaxed_elastic = denst*csl*csl lambdal_unrelaxed_elastic = denst*cpl*cpl - TWO*mul_unrelaxed_elastic endif ! derivative along x and along z dux_dxi = ZERO duz_dxi = ZERO dux_dgamma = ZERO duz_dgamma = ZERO ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ if (AXISYM) then if (is_on_the_axis(ispec)) then do k = 1,NGLJ dux_dxi = dux_dxi + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) duz_dxi = duz_dxi + displ_elastic(2,ibool(k,j,ispec))*hprimeBar_xx(i,k) dux_dgamma = dux_dgamma + displ_elastic(1,ibool(i,k,ispec))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displ_elastic(2,ibool(i,k,ispec))*hprime_zz(j,k) enddo else do k = 1,NGLJ dux_dxi = dux_dxi + displ_elastic(1,ibool(k,j,ispec))*hprime_xx(i,k) duz_dxi = duz_dxi + displ_elastic(2,ibool(k,j,ispec))*hprime_xx(i,k) dux_dgamma = dux_dgamma + displ_elastic(1,ibool(i,k,ispec))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displ_elastic(2,ibool(i,k,ispec))*hprime_zz(j,k) enddo endif else do k = 1,NGLLX dux_dxi = dux_dxi + displ_elastic(1,ibool(k,j,ispec))*hprime_xx(i,k) duz_dxi = duz_dxi + displ_elastic(2,ibool(k,j,ispec))*hprime_xx(i,k) dux_dgamma = dux_dgamma + displ_elastic(1,ibool(i,k,ispec))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displ_elastic(2,ibool(i,k,ispec))*hprime_zz(j,k) enddo endif xixl = xix(i,j,ispec) xizl = xiz(i,j,ispec) gammaxl = gammax(i,j,ispec) gammazl = gammaz(i,j,ispec) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl if (AXISYM .and. is_on_the_axis(ispec) .and. i == 1) then ! d_uz/dr=0 on the axis duz_dxl = 0.d0 endif ! compute diagonal components of the stress tensor (include attenuation or anisotropy if needed) if (ATTENUATION_VISCOELASTIC) then ! attenuation is implemented following the memory variable formulation of ! J. M. Carcione, Seismic modeling in viscoelastic media, Geophysics, ! vol. 58(1), p. 110-120 (1993). More details can be found in ! J. M. Carcione, D. Kosloff and R. Kosloff, Wave propagation simulation in a linear ! viscoelastic medium, Geophysical Journal International, vol. 95, p. 597-611 (1988). ! When implementing viscoelasticity according to the Carcione 1993 paper, attenuation is ! non-causal rather than causal i.e. wave speed up instead of slowing down ! when attenuation is turned on. We fixed that issue (which is not incorrect but non traditional) ! by taking the unrelaxed state (infinite frequency) as a reference instead of the relaxed state (zero frequency) ! and also using equations in Carcione's 2007 book. ! See file doc/old_problem_attenuation_reference_Specfem2D_fixed_by_Xie_Zhinan.pdf ! and doc/how_we_modified_Carcione_1993_to_make_it_causal_and_include_the_missing_1_over_L_factor.pdf ! See also J. M. Carcione, Seismic modeling in viscoelastic media, Geophysics, ! vol. 58(1), p. 110-120 (1993) for two memory-variable mechanisms (page 112). ! and J. M. Carcione, D. Kosloff and R. Kosloff, Wave propagation simulation ! in a linear viscoelastic medium, Geophysical Journal International, ! vol. 95, p. 597-611 (1988) for two memory-variable mechanisms (page 604). if (AXISYM) then if (is_on_the_axis(ispec)) then if (is_on_the_axis(ispec) .and. i == 1) then ! First GLJ point sigma_xx = 0._CUSTOM_REAL sigma_zz = 0._CUSTOM_REAL sigma_thetatheta = 0._CUSTOM_REAL xxi = + gammaz(i,j,ispec) * jacobian(i,j,ispec) do k = 1,NGLJ sigma_xx = sigma_xx + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) sigma_zz = sigma_zz + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) sigma_thetatheta = sigma_thetatheta + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) enddo sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*sigma_xx/xxi sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*sigma_zz/xxi sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic*sigma_thetatheta/xxi else ! Not first GLJ point sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic & * displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) endif else ! Not on the axis sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic & * displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) endif sigma_yy = sigma_thetatheta else ! Not axisym ! compute the stress using the unrelaxed Lame parameters (Carcione 2007 page 125) sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation sigma_yy = lambdal_unrelaxed_elastic*(dux_dxl + duz_dzl) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl endif ! add the memory variables using the relaxed parameters (Carcione 2007 page 125) ! beware: there is a bug in Carcione's equation (2c) of his 1993 paper for sigma_zz, we fixed it in the code below e1_sum = 0._CUSTOM_REAL e11_sum = 0._CUSTOM_REAL do i_sls = 1,N_SLS e1_sum = e1_sum + e1(i_sls,i,j,ispec) e11_sum = e11_sum + e11(i_sls,i,j,ispec) enddo sigma_xx = sigma_xx + (lambdal_unrelaxed_elastic + mul_unrelaxed_elastic) * e1_sum & + TWO * mul_unrelaxed_elastic * e11_sum ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation sigma_yy = sigma_yy + (lambdal_unrelaxed_elastic + mul_unrelaxed_elastic) * e1_sum sigma_zz = sigma_zz + (lambdal_unrelaxed_elastic + mul_unrelaxed_elastic) * e1_sum & - TWO * mul_unrelaxed_elastic * e11_sum else ! no attenuation if (AXISYM) then if (is_on_the_axis(ispec)) then if (is_on_the_axis(ispec) .and. i == 1) then ! First GLJ point sigma_xx = 0._CUSTOM_REAL sigma_zz = 0._CUSTOM_REAL sigma_thetatheta = 0._CUSTOM_REAL xxi = + gammaz(i,j,ispec) * jacobian(i,j,ispec) do k = 1,NGLJ sigma_xx = sigma_xx + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) sigma_zz = sigma_zz + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) sigma_thetatheta = sigma_thetatheta + displ_elastic(1,ibool(k,j,ispec))*hprimeBar_xx(i,k) enddo sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*sigma_xx/xxi sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*sigma_zz/xxi sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic*sigma_thetatheta/xxi else ! Not first GLJ point sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic & * displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) endif else ! Not on the axis sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdal_unrelaxed_elastic*displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) sigma_thetatheta = lambdal_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl & + lambdaplus2mu_unrelaxed_elastic & * displ_elastic(1,ibool(i,j,ispec))/coord(1,ibool(i,j,ispec)) endif sigma_yy = sigma_thetatheta else ! Not axisym sigma_xx = lambdaplus2mu_unrelaxed_elastic*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation sigma_yy = lambdal_unrelaxed_elastic*(dux_dxl + duz_dzl) sigma_zz = lambdaplus2mu_unrelaxed_elastic*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl endif endif ! full anisotropy if (ispec_is_anisotropic(ispec)) then if (assign_external_model) then c11 = c11ext(i,j,ispec) c15 = c15ext(i,j,ispec) c13 = c13ext(i,j,ispec) c33 = c33ext(i,j,ispec) c35 = c35ext(i,j,ispec) c55 = c55ext(i,j,ispec) c12 = c12ext(i,j,ispec) c23 = c23ext(i,j,ispec) c25 = c25ext(i,j,ispec) else c11 = anisotropy(1,kmato(ispec)) c13 = anisotropy(2,kmato(ispec)) c15 = anisotropy(3,kmato(ispec)) c33 = anisotropy(4,kmato(ispec)) c35 = anisotropy(5,kmato(ispec)) c55 = anisotropy(6,kmato(ispec)) c12 = anisotropy(7,kmato(ispec)) c23 = anisotropy(8,kmato(ispec)) c25 = anisotropy(9,kmato(ispec)) endif duz_dxl = duz_dxi*xixl + duz_dgamma*gammaxl dux_dzl = dux_dxi*xizl + dux_dgamma*gammazl if (AXISYM .and. is_on_the_axis(ispec) .and. i == 1) then ! d_uz/dr=0 on the axis duz_dxl = 0.d0 endif ! implement anisotropy in 2D sigma_xx = c11*dux_dxl + c13*duz_dzl + c15*(duz_dxl + dux_dzl) ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation if (c12 < 1.e-7 .or. c23 < 1.e-7) call stop_the_code( & 'cannot compute pressure for an anisotropic material if c12 or c23 are zero') sigma_yy = c12*dux_dxl + c23*duz_dzl + c25*(duz_dxl + dux_dzl) sigma_zz = c13*dux_dxl + c33*duz_dzl + c35*(duz_dxl + dux_dzl) endif ! store pressure ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation pressure_element(i,j) = - (sigma_xx + sigma_yy + sigma_zz) / 3.d0 enddo enddo else if (ispec_is_poroelastic(ispec)) then ! poro-elastic element lambdal_unrelaxed_elastic = poroelastcoef(1,1,kmato(ispec)) mul_unrelaxed_elastic = poroelastcoef(2,1,kmato(ispec)) ! get poroelastic parameters of current spectral element call get_poroelastic_material(ispec,phi,tort,mu_s,kappa_s,rho_s,kappa_f,rho_f,eta_f,mu_fr,kappa_fr,rho_bar) ! Biot coefficients for the input phi call get_poroelastic_Biot_coeff(phi,kappa_s,kappa_f,kappa_fr,mu_fr,D_biot,H_biot,C_biot,M_biot) ! where T = G:grad u_s + C div w I ! and T_f = C div u_s I + M div w I ! we are expressing lambdaplus2mu, lambda, and mu for G, C, and M mu_G = mu_fr lambdal_G = H_biot - TWO*mu_fr lambdalplus2mul_G = lambdal_G + TWO*mu_G do j = 1,NGLLZ do i = 1,NGLLX ! derivative along x and along z dux_dxi = ZERO duz_dxi = ZERO dux_dgamma = ZERO duz_dgamma = ZERO dwx_dxi = ZERO dwz_dxi = ZERO dwx_dgamma = ZERO dwz_dgamma = ZERO ! first double loop over GLL points to compute and store gradients ! we can merge the two loops because NGLLX == NGLLZ do k = 1,NGLLX dux_dxi = dux_dxi + displs_poroelastic(1,ibool(k,j,ispec))*hprime_xx(i,k) duz_dxi = duz_dxi + displs_poroelastic(2,ibool(k,j,ispec))*hprime_xx(i,k) dux_dgamma = dux_dgamma + displs_poroelastic(1,ibool(i,k,ispec))*hprime_zz(j,k) duz_dgamma = duz_dgamma + displs_poroelastic(2,ibool(i,k,ispec))*hprime_zz(j,k) dwx_dxi = dwx_dxi + displw_poroelastic(1,ibool(k,j,ispec))*hprime_xx(i,k) dwz_dxi = dwz_dxi + displw_poroelastic(2,ibool(k,j,ispec))*hprime_xx(i,k) dwx_dgamma = dwx_dgamma + displw_poroelastic(1,ibool(i,k,ispec))*hprime_zz(j,k) dwz_dgamma = dwz_dgamma + displw_poroelastic(2,ibool(i,k,ispec))*hprime_zz(j,k) enddo xixl = xix(i,j,ispec) xizl = xiz(i,j,ispec) gammaxl = gammax(i,j,ispec) gammazl = gammaz(i,j,ispec) ! derivatives of displacement dux_dxl = dux_dxi*xixl + dux_dgamma*gammaxl duz_dzl = duz_dxi*xizl + duz_dgamma*gammazl dwx_dxl = dwx_dxi*xixl + dwx_dgamma*gammaxl dwz_dzl = dwz_dxi*xizl + dwz_dgamma*gammazl ! compute diagonal components of the stress tensor (include attenuation if needed) if (ATTENUATION_VISCOELASTIC) then ! attenuation is implemented following the memory variable formulation of ! J. M. Carcione, Seismic modeling in viscoelastic media, Geophysics, ! vol. 58(1), p. 110-120 (1993). More details can be found in ! J. M. Carcione, D. Kosloff and R. Kosloff, Wave propagation simulation in a linear ! viscoelastic medium, Geophysical Journal International, vol. 95, p. 597-611 (1988). ! When implementing viscoelasticity according to the Carcione 1993 paper, attenuation is ! non-causal rather than causal i.e. wave speed up instead of slowing down ! when attenuation is turned on. We fixed that issue (which is not incorrect but non traditional) ! by taking the unrelaxed state (infinite frequency) as a reference instead of the relaxed state (zero frequency) ! and also using equations in Carcione's 2007 book. ! See file doc/old_problem_attenuation_reference_Specfem2D_fixed_by_Xie_Zhinan.pdf ! and doc/how_we_modified_Carcione_1993_to_make_it_causal_and_include_the_missing_1_over_L_factor.pdf ! See also J. M. Carcione, Seismic modeling in viscoelastic media, Geophysics, ! vol. 58(1), p. 110-120 (1993) for two memory-variable mechanisms (page 112). ! and J. M. Carcione, D. Kosloff and R. Kosloff, Wave propagation simulation ! in a linear viscoelastic medium, Geophysical Journal International, ! vol. 95, p. 597-611 (1988) for two memory-variable mechanisms (page 604). ! compute the stress using the unrelaxed Lame parameters (Carcione 2007 page 125) sigma_xx = (lambdal_unrelaxed_elastic + 2.0 * mul_unrelaxed_elastic)*dux_dxl + lambdal_unrelaxed_elastic*duz_dzl ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation ! sigma_yy = ... ! it is not zero because of the plane strain formulation, thus it should be computed here call stop_the_code('pressure calculation not implemented for poroelastic media yet, you should compute sigma_yy here') sigma_zz = (lambdal_unrelaxed_elastic + 2.0 * mul_unrelaxed_elastic)*duz_dzl + lambdal_unrelaxed_elastic*dux_dxl ! add the memory variables using the relaxed parameters (Carcione 2007 page 125) ! beware: there is a bug in Carcione's equation (2c) of his 1993 paper for sigma_zz, we fixed it in the code below e1_sum = 0._CUSTOM_REAL e11_sum = 0._CUSTOM_REAL do i_sls = 1,N_SLS e1_sum = e1_sum + e1(i_sls,i,j,ispec) e11_sum = e11_sum + e11(i_sls,i,j,ispec) enddo sigma_xx = sigma_xx + (lambdal_unrelaxed_elastic + mul_unrelaxed_elastic) * e1_sum & + TWO * mul_unrelaxed_elastic * e11_sum ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation ! sigma_yy = ... ! it is not zero because of the plane strain formulation, thus it should be computed here call stop_the_code('pressure calculation not implemented for poroelastic media yet, you should compute sigma_yy here') sigma_zz = sigma_zz + (lambdal_unrelaxed_elastic + mul_unrelaxed_elastic) * e1_sum & - TWO * mul_unrelaxed_elastic * e11_sum else ! no attenuation sigma_xx = lambdalplus2mul_G*dux_dxl + lambdal_G*duz_dzl + C_biot*(dwx_dxl + dwz_dzl) ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation ! sigma_yy = ... ! it is not zero because of the plane strain formulation, thus it should be computed here !! DK DK we temporarily set it to zero here to avoid a warning by certain compilers about an unassigned variable !! DK DK when computing pressure a few lines below; this should be removed and replaced with a true calculation sigma_yy = 0.d0 call stop_the_code('pressure calculation not implemented for poroelastic media yet, you should compute sigma_yy here') sigma_zz = lambdalplus2mul_G*duz_dzl + lambdal_G*dux_dxl + C_biot*(dwx_dxl + dwz_dzl) ! sigmap = C_biot*(dux_dxl + duz_dzl) + M_biot*(dwx_dxl + dwz_dzl) endif ! store pressure ! sigma_yy is not equal to zero in a 2D medium because of the plane strain formulation pressure_element(i,j) = - (sigma_xx + sigma_yy + sigma_zz) / 3.d0 ! pressure_element2(i,j) = - sigmap enddo enddo ! pressure = - Chi_dot_dot if acoustic element else if (ispec_is_acoustic(ispec)) then ! acoustic element if (USE_TRICK_FOR_BETTER_PRESSURE) then ! use a trick to increase accuracy of pressure seismograms in fluid (acoustic) elements: ! use the second derivative of the source for the source time function instead of the source itself, ! and then record -potential_acoustic() as pressure seismograms instead of -potential_dot_dot_acoustic(); ! this is mathematically equivalent, but numerically significantly more accurate because in the explicit ! Newmark time scheme acceleration is accurate at zeroth order while displacement is accurate at second order, ! thus in fluid elements potential_dot_dot_acoustic() is accurate at zeroth order while potential_acoustic() ! is accurate at second order and thus contains significantly less numerical noise. ! compute pressure on the fluid/porous medium edge do j = 1,NGLLZ do i = 1,NGLLX iglob = ibool(i,j,ispec) ! store pressure pressure_element(i,j) = - potential_acoustic(iglob) enddo enddo else do j = 1,NGLLZ do i = 1,NGLLX iglob = ibool(i,j,ispec) ! store pressure pressure_element(i,j) = - potential_dot_dot_acoustic(iglob) enddo enddo endif endif ! end of test if acoustic or elastic element end subroutine compute_pressure_one_element
geodynamics/specfem2d
src/specfem2D/compute_pressure.f90
FORTRAN
gpl-3.0
29,040
#ifndef MOJO_CONFIG_HPP #define MOJO_CONFIG_HPP #include <string> namespace MOJO { constexpr char majorVersion[] = "0"; constexpr char minorVersion[] = "0"; constexpr char patchVersion[] = "5"; constexpr char version[] = "0.5.0"; } #endif
cband/MOJO
include/MOJOConfig.h
C
gpl-3.0
246
/* Copyright (C) 2008-2015 Teddy Michel This file is part of TEngine. TEngine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TEngine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TEngine. If not, see <http://www.gnu.org/licenses/>. */ /** * \file Game/Entities/IBaseAnimating.hpp * \date 11/04/2009 Création de la classe IBaseAnimating. * \date 13/07/2010 Le nombre de points de vie est désormais géré par cette classe. * \date 14/07/2010 Ajout de la méthode WeaponImpact. * \date 16/07/2010 Ajout de la méthode ProjectileImpact. * \date 18/11/2010 Ajout de la méthode getClassName. * \date 08/12/2010 Plus de méthodes inline, suppression du paramètre name. * \date 01/03/2011 Ajout du paramètre parent au constructeur. * \date 02/03/2011 Création des méthodes isPlayer et isNPC. * \date 07/04/2011 Les entités sont identifiées par un nom à la place d'un nombre. */ #ifndef T_FILE_ENTITIES_IBASEANIMATING_HPP_ #define T_FILE_ENTITIES_IBASEANIMATING_HPP_ /*-------------------------------* * Includes * *-------------------------------*/ #include "Game/Export.hpp" #include "IBrushEntity.hpp" namespace Ted { class IBaseProjectile; /** * \class IBaseAnimating * \ingroup Game * \brief Classe de base des entités animées. ******************************/ class T_GAME_API IBaseAnimating : public IBrushEntity { public: // Constructeur et destructeur explicit IBaseAnimating(const CString& name = CString(), ILocalEntity * parent = nullptr); virtual ~IBaseAnimating() = 0; // Accesseurs virtual CString getClassName() const; float getHealth() const; bool isAlive() const; virtual bool isPlayer() const; virtual bool isNPC() const; // Mutateurs void addHealth(float health); void setHealth(float health = 100.0f); // Méthodes publiques virtual void weaponImpact(float damage, IBaseCharacter * character, IBaseWeapon * weapon); virtual void projectileImpact(float damage, IBaseProjectile * projectile); virtual void frame(unsigned int frameTime); protected: // Donnée protégée float m_health; ///< Points de vie (si négatifs, l'entité est morte, 100 par défaut). }; } // Namespace Ted #endif // T_FILE_ENTITIES_IBASEANIMATING_HPP_
teddy-michel/TEngine
include/Game/Entities/IBaseAnimating.hpp
C++
gpl-3.0
2,717
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using PagedList.Core; namespace Marigold { public class ReservationsController : Controller { private IUnitOfWork unitOfWork; private IReservationsBll _bll; public ReservationsController(IReservationsBll bll, IUnitOfWork uow) { _bll = bll; unitOfWork = uow; } public async Task<IActionResult> Index(int? page) { var pageIndex = !page.HasValue || page <= 0 ? 1 : page.Value; var list = _bll.Reservations(pageIndex - 1, 10); ViewBag.RoomUnitDescription = await _bll.RoomUnitDescription(); return View(list); } public async Task<IActionResult> Create() { return View(await _bll.ReservationInput()); } [HttpPost] public async Task<IActionResult> Create(ReservationInputDto input) { if (!ModelState.IsValid) return View(input); await _bll.Create(input); return Redirect("Index"); } public async Task<IActionResult> Checkout(string id) { var input = await _bll.CheckoutView(id); if (input == null) return new NotFoundResult(); ViewBag.RoomUnitDescription = await _bll.RoomUnitDescription(); return View(input); } [HttpPost] public async Task<IActionResult> Checkout(ReservationInputDto input) { var res = await _bll.Checkout(input); if (!res) return new NotFoundResult(); return RedirectToAction("Index"); } public async Task<IActionResult> Bill(string id) { var output = await _bll.Bill(id); if(output == null) return new NotFoundResult(); ViewBag.Currency = "grams of gold"; return View(output); } } }
catalintoma/Mary-Gold
Controllers/ReservationsController.cs
C#
gpl-3.0
2,215
/* gpio.h: PPM firmware general purpose input/output header. * Copyright (C) 2013 Bradley Worley <geekysuavo@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ensure proper inclusion. */ #ifndef __PPM_GPIO_H__ #define __PPM_GPIO_H__ /* include the gpio definitions. */ #include "gpio-defines.h" /* begin function declarations: */ void gpio_init (void); #endif /* __PPM_GPIO_H__ */
geekysuavo/pyppm
firmware/ppm-1.2/gpio.h
C
gpl-3.0
1,007
<?php /* * 2007-2013 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2013 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ // // IMPORTANT : don't forget to delete the underscore _ in the file name if you want to use it ! // $GLOBALS['debugtoolbar'] = array(); if (file_exists(_PS_MODULE_DIR_.'debugtoolbar/debugtoolbar.php')) require_once(_PS_MODULE_DIR_.'debugtoolbar/debugtoolbar.php'); function developpementErrorHandler($errno, $errstr, $errfile, $errline) { if (!(error_reporting() & $errno)) return; switch($errno) { case E_ERROR: echo '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_WARNING: echo '[PHP Warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_PARSE: echo '[PHP Parse #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_NOTICE: echo '[PHP Notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_CORE_ERROR: echo '[PHP Core #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_CORE_WARNING: echo '[PHP Core warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_COMPILE_ERROR: echo '[PHP Compile #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_COMPILE_WARNING: echo '[PHP Compile warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_ERROR: echo '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_WARNING: echo '[PHP User warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_USER_NOTICE: echo '[PHP User notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_STRICT: echo '[PHP Strict #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; case E_RECOVERABLE_ERROR: echo '[PHP Recoverable error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; break; default: echo '[PHP Unknown error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')'; } die; return true; } function debug($debug, $name = null) { $GLOBALS['debugtoolbar'] = (($name !== null) ? '<b>Debug var :</b> '.$name.'<br />' : '').'<pre>'.print_r($debug, true).'</pre>'; } /** * Converts bytes into human readable file size. * * @param string $bytes * @return string human readable file size (2,87 Мб) * @author Mogilev Arseny */ function FileSizeConvert($bytes) { $bytes = floatval($bytes); $arBytes = array( 0 => array( "UNIT" => "tB", "VALUE" => pow(1024, 4) ), 1 => array( "UNIT" => "gB", "VALUE" => pow(1024, 3) ), 2 => array( "UNIT" => "mB", "VALUE" => pow(1024, 2) ), 3 => array( "UNIT" => "kB", "VALUE" => 1024 ), 4 => array( "UNIT" => "bytes", "VALUE" => 1 ), ); $result = ''; foreach($arBytes as $arItem) { if($bytes >= $arItem["VALUE"]) { $result = $bytes / $arItem["VALUE"]; $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; break; } } return $result; } if (!function_exists('getallheaders')) { function getallheaders() { $headers = ''; foreach ($_SERVER as $name => $value) if (substr($name, 0, 5) == 'HTTP_') $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; return $headers; } } function getUrl() { $url = Tools::getShopDomainSsl(true); $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; $url .= $_SERVER["REQUEST_URI"]; return $url; } function smarty_modifier_debug_print_var ($var, $depth = 0, $length = 40) { $_replace = array("\n" => '<i>\n</i>', "\r" => '<i>\r</i>', "\t" => '<i>\t</i>' ); switch (gettype($var)) { case 'array' : $results = '<b>Array (' . count($var) . ')</b>'; foreach ($var as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b>' . strtr($curr_key, $_replace) . '</b> =&gt; ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'object' : $object_vars = get_object_vars($var); $results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>'; foreach ($object_vars as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b> -&gt;' . strtr($curr_key, $_replace) . '</b> = ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'boolean' : case 'NULL' : case 'resource' : if (true === $var) { $results = 'true'; } elseif (false === $var) { $results = 'false'; } elseif (null === $var) { $results = 'null'; } else { $results = htmlspecialchars((string) $var); } $results = '<i>' . $results . '</i>'; break; case 'integer' : case 'float' : $results = htmlspecialchars((string) $var); break; case 'string' : $results = strtr($var, $_replace); if (Smarty::$_MBSTRING) { if (mb_strlen($var, Smarty::$_CHARSET) > $length) { $results = mb_substr($var, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (isset($var[$length])) { $results = substr($var, 0, $length - 3) . '...'; } } $results = htmlspecialchars('"' . $results . '"'); break; case 'unknown type' : default : $results = strtr((string) $var, $_replace); if (Smarty::$_MBSTRING) { if (mb_strlen($results, Smarty::$_CHARSET) > $length) { $results = mb_substr($results, 0, $length - 3, Smarty::$_CHARSET) . '...'; } } else { if (strlen($results) > $length) { $results = substr($results, 0, $length - 3) . '...'; } } $results = htmlspecialchars($results); } return $results; } abstract class Controller extends ControllerCore { public $_memory = array(); public $_time = array(); private static $_footer = true; public static function disableParentCalls() { self::$_footer = false; } private function displayMemoryColor($n) { $n /= 1048576; if ($n > 3) return '<span style="color:#ff4141">'.round($n, 2).' Mb</span>'; if ($n > 1) return '<span style="color:#ef8400">'.round($n, 2).' Mb</span>'; return '<span style="color:#90bd00">'.round($n, 2).' Mb</span>'; } private function displayPeakMemoryColor($n) { $n /= 1048576; if ($n > 16) return '<span style="color:#ff4141">'.round($n, 1).' Mb</span>'; if ($n > 12) return '<span style="color:#ef8400">'.round($n, 1).' Mb</span>'; return '<span style="color:#90bd00">'.round($n, 1).' Mb</span>'; } private function displaySQLQueries($n) { if ($n > 150) return '<span style="color:#ff4141">'.$n.' queries</span>'; if ($n > 100) return '<span style="color:#ef8400">'.$n.' queries</span>'; return '<span style="color:#90bd00">'.$n.' quer'.($n == 1 ? 'y' : 'ies').'</span>'; } private function displayRowsBrowsed($n) { if ($n > 200) return '<span style="color:#ff4141">'.$n.' rows browsed</span>'; if ($n > 50) return '<span style="color:#ef8400">'.$n.' rows browsed</span>'; return '<span style="color:#90bd00">'.$n.' row'.($n == 1 ? '' : 's').' browsed</span>'; } private function displayLoadTimeColor($n, $pre = false) { $balise = ($pre ? 'pre' : 'span'); if ($n > 1) return '<'.$balise.' style="color:#ff4141">'.round($n, 3).'s</'.$balise.'>'; if ($n > 0.5) return '<'.$balise.' style="color:#ef8400">'.round($n * 1000).'ms</'.$balise.'>'; return '<'.$balise.' style="color:#90bd00">'.round($n * 1000).'ms</'.$balise.'>'; } private function getTimeColor($n) { if ($n > 4) return 'style="color:#ff4141"'; if ($n > 2) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getQueryColor($n) { if ($n > 5) return 'style="color:#ff4141"'; if ($n > 2) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getTableColor($n) { if ($n > 30) return 'style="color:#ff4141"'; if ($n > 20) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } private function getObjectModelColor($n) { if ($n > 50) return 'style="color:#ff4141"'; if ($n > 10) return 'style="color:#ef8400"'; return 'style="color:#90bd00"'; } public function __construct() { parent::__construct(); // error management set_error_handler('developpementErrorHandler'); ini_set('html_errors', 'on'); ini_set('display_errors', 'on'); error_reporting(E_ALL | E_STRICT); if (!self::$_footer) return; $this->_memory['config'] = memory_get_usage(); $this->_mempeak['config'] = memory_get_peak_usage(); $this->_time['config'] = microtime(true); parent::__construct(); $this->_memory['constructor'] = memory_get_usage(); $this->_mempeak['constructor'] = memory_get_peak_usage(); $this->_time['constructor'] = microtime(true); } public function run() { if (!class_exists('DebugToolbar')) return parent::run(); if (!DebugToolbar::isEnable()) return parent::run(); $this->init(); $this->_memory['init'] = memory_get_usage(); $this->_mempeak['init'] = memory_get_peak_usage(); $this->_time['init'] = microtime(true); if ($this->checkAccess()) { $this->_memory['checkAccess'] = memory_get_usage(); $this->_mempeak['checkAccess'] = memory_get_peak_usage(); $this->_time['checkAccess'] = microtime(true); if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) $this->setMedia(); $this->_memory['setMedia'] = memory_get_usage(); $this->_mempeak['setMedia'] = memory_get_peak_usage(); $this->_time['setMedia'] = microtime(true); // postProcess handles ajaxProcess $this->postProcess(); $this->_memory['postProcess'] = memory_get_usage(); $this->_mempeak['postProcess'] = memory_get_peak_usage(); $this->_time['postProcess'] = microtime(true); if (!empty($this->redirect_after)) $this->redirect(); if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) $this->initHeader(); $this->_memory['initHeader'] = memory_get_usage(); $this->_mempeak['initHeader'] = memory_get_peak_usage(); $this->_time['initHeader'] = microtime(true); $this->initContent(); $this->_memory['initContent'] = memory_get_usage(); $this->_mempeak['initContent'] = memory_get_peak_usage(); $this->_time['initContent'] = microtime(true); if (!$this->content_only && ($this->display_footer || (isset($this->className) && $this->className))) $this->initFooter(); $this->_memory['initFooter'] = memory_get_usage(); $this->_mempeak['initFooter'] = memory_get_peak_usage(); $this->_time['initFooter'] = microtime(true); // default behavior for ajax process is to use $_POST[action] or $_GET[action] // then using displayAjax[action] if ($this->ajax) { $action = Tools::getValue('action'); if (!empty($action) && method_exists($this, 'displayAjax'.Tools::toCamelCase($action))) $this->{'displayAjax'.$action}(); elseif (method_exists($this, 'displayAjax')) $this->displayAjax(); } else $this->displayDebug(); } else { $this->initCursedPage(); $this->displayDebug(); } } private function ini_get_display_errors() { $a = 'display_errors'; $b = ini_get($a); switch (strtolower($b)) { case 'on': case 'yes': case 'true': return 'assert.active' !== $a; case 'stdout': case 'stderr': return 'display_errors' === $a; default: return (bool)(int)$b; } } private function sizeofvar($var) { $start_memory = memory_get_usage(); try { $tmp = Tools::unSerialize(serialize($var)); } catch (Exception $e) { $tmp = $this->getVarData($var); } $size = memory_get_usage() - $start_memory; return $size; } private function getVarData($var) { if (is_object($var)) return $var; return (string)$var; } public function displayDebug() { global $start_time; $this->display(); $this->_memory['display'] = memory_get_usage(); $this->_mempeak['display'] = memory_get_peak_usage(); $this->_time['display'] = microtime(true); if (!$this->ini_get_display_errors()) return; $memory_peak_usage = memory_get_peak_usage(); $hr = '<hr style="color:#F5F5F5;margin:2px" />'; $totalSize = 0; foreach (get_included_files() as $file) $totalSize += filesize($file); $totalQueryTime = 0; foreach (Db::getInstance()->queries as $data) $totalQueryTime += $data['time']; $hooktime = Hook::getHookTime(); arsort($hooktime); $totalHookTime = 0; foreach ($hooktime as $time) $totalHookTime += $time; $hookMemoryUsage = Hook::getHookMemoryUsage(); arsort($hookMemoryUsage); $totalHookMemoryUsage = 0; foreach ($hookMemoryUsage as $usage) $totalHookMemoryUsage += $usage; $globalSize = array(); $totalGlobalSize = 0; foreach ($GLOBALS as $key => $value) if ($key != 'GLOBALS') { $totalGlobalSize += ($size = $this->sizeofvar($value)); if ($size > 1024) $globalSize[$key] = round($size / 1024, 1); } arsort($globalSize); $cache = Cache::retrieveAll(); $totalCacheSize = $this->sizeofvar($cache); $output = ''; $output .= '<link href="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/views/assets/css/debugtoolbar.css" rel="stylesheet" type="text/css" media="all">'; $output .= ' <div class="debugtoolbar"> <div class="debugtoolbar-window"> <div class="debugtoolbar-content-area"> '; /* LOAD TIME */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-load-times">'; $output .= ' <table> <tr> <th>Name</th> <th>Running Time (ms)</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Application</td> <td>'.$this->displayLoadTimeColor($this->_time['display'] - $start_time, true).'</td> </tr> '; $last_time = $start_time; foreach ($this->_time as $k => $time) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($k).'</td> <td>'.$this->displayLoadTimeColor($time - $last_time, true).'</td> </tr> '; $last_time = $time; } $output .= ' </table> '; $output .= ' </div>'; /* /LOAD TIME */ /* HOOK PROCESSING */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-hook-processing">'; $output .= ' <table> <tr> <th>Name</th> <th>Running Time (ms) / Memory Usage</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Hook</td> <td><pre>'.$this->displayLoadTimeColor($totalHookTime).' / '.$this->displayMemoryColor($totalHookMemoryUsage).'</pre></td> </tr> '; foreach ($hooktime as $hook => $time) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($hook).'</td> <td><pre>'.$this->displayLoadTimeColor($time).' / '.$this->displayMemoryColor($hookMemoryUsage[$hook]).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /HOOK PROCESSING */ /* MEMORY PEAK USAGE */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-memory-peak-usage">'; $output .= ' <table> <tr> <th>Name</th> <th>Memory Usage (Global)</th> </tr> <tr> <td class="debugtoolbar-table-first">Global Memory</td> <td><pre>'.$this->displayPeakMemoryColor($memory_peak_usage).'</pre></td> </tr> '; foreach ($this->_memory as $k => $memory) { $last_memory = 0; $output .= ' <tr> <td class="debugtoolbar-table-first">'.ucfirst($k).'</td> <td><pre>'.$this->displayMemoryColor($memory - $last_memory).' ('.$this->displayPeakMemoryColor($this->_mempeak[$k]).')</pre></td> </tr> '; $last_memory = $memory; } $output .= ' </table> '; $output .= ' </div>'; /* /MEMORY PEAK USAGE */ /* INCLUDED FILES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-included-files">'; $output .= ' <table> <tr> <th>#</th> <th>File</th> <th>Size</th> </tr> <tr> <td class="debugtoolbar-table-first">Size global files</td> <td><pre>'.$this->displayMemoryColor($totalSize).'</pre></td> <td>-</td> </tr> '; $i = 1; foreach (get_included_files() as $file) { $f = ltrim(str_replace('\\', '/', str_replace(_PS_ROOT_DIR_, '', $file)), '/'); $f = dirname($file).'/<span style="color: #0080b0">'.basename($file).'</span>'; $output .= ' <tr> <td class="debugtoolbar-table-first">'.$i.'</td> <td><pre>'.$f.'</pre></td> <td>'.FileSizeConvert(@filesize($file)).'</td> </tr> '; $i++; } $output .= ' </table> '; $output .= ' </div>'; /* /INCLUDED FILES */ /* SQL QUERIES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-sql-queries">'; $output .= ' <table> <tr> <th>Time</th> <th>Query</th> </tr> '; $array_queries = array(); $queries = Db::getInstance()->queries; uasort($queries, 'prestashop_querytime_sort'); foreach ($queries as $data) { $query_row = array( 'time' => $data['time'], 'query' => $data['query'], 'location' => $data['file'].':<span style="color:#0080b0">'.$data['line'].'</span>', 'filesort' => false, 'rows' => 1, 'group_by' => false ); if (preg_match('/^\s*select\s+/i', $data['query'])) { $explain = Db::getInstance()->executeS('explain '.$data['query']); if (stristr($explain[0]['Extra'], 'filesort')) $query_row['filesort'] = true; foreach ($explain as $row) $query_row['rows'] *= $row['rows']; if (stristr($data['query'], 'group by') && !preg_match('/(avg|count|min|max|group_concat|sum)\s*\(/i', $data['query'])) $query_row['group_by'] = true; } $array_queries[] = $query_row; } foreach ($array_queries as $data) { $filestortGroup = ''; if (preg_match('/^\s*select\s+/i', $data['query'])) { if ($data['filesort']) $filestortGroup .= '<b '.$this->getTimeColor($data['time'] * 1000).'>USING FILESORT</b> - '; $filestortGroup .= $this->displayRowsBrowsed($data['rows']); if ($data['group_by']) $filestortGroup .= ' - <b>Useless GROUP BY need to be removed</b>'; } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Query in : </strong>'.$data['location'].' - '.$filestortGroup.'</td> </tr> <tr> <td class="debugtoolbar-table-first"><span '.$this->getTimeColor($data['time'] * 1000).'>'.round($data['time'] * 1000, 3).' ms</span></td> <td><pre>'.htmlspecialchars($data['query'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /SQL QUERIES */ /* TABLES */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-sql-table">'; $output .= ' <table> <tr> <th>Nb call</th> <th>Table</th> </tr> '; $tables = Db::getInstance()->tables; arsort($tables); foreach ($tables as $table => $nb) { $output .= ' <tr> <td class="debugtoolbar-table-first"><b '.$this->getTableColor($nb).'>'.$nb.'</b></td> <td><pre>'.$table.'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* /TABLES */ /* OBJECTMODEL */ if (isset(ObjectModel::$debug_list)) { $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-objectmodel-instance">'; $output .= ' <table> <tr> <th>Nb call</th> <th>ObjectModel Instance</th> </tr> '; $list = ObjectModel::$debug_list; uasort($list, create_function('$a,$b', 'return (count($a) < count($b)) ? 1 : -1;')); $i = 0; foreach ($list as $class => $info) { echo ''; echo ''; $i++; $output .= ' <tr> <td class="debugtoolbar-table-first"><b '.$this->getObjectModelColor(count($info)).'>'.count($info).'</b></td> <td><a href="#" onclick="$(\'#object_model_'.$i.'\').css(\'display\', $(\'#object_model_'.$i.'\').css(\'display\') == \'none\' ? \'block\' : \'none\'); return false" style="color:#0080b0">'.$class.'</a> <pre id="object_model_'.$i.'" style="display: none">'; foreach ($info as $trace) $output .= ltrim(str_replace(array(_PS_ROOT_DIR_, '\\'), array('', '/'), $trace['file']), '/').' ['.$trace['line'].']<br />'; $output .= '</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; } /* /OBJECTMODEL */ /* GETALLHEADERS */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-getallheader">'; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> '; $getallheaders = getallheaders(); foreach ($getallheaders as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } stream_context_set_default(array('http' => array('method' => 'HEAD'))); $url = getUrl(); if ($get_headers = get_headers($url, 1)) { foreach ($get_headers as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.(is_array($value) ? $value[0] : $value).'</pre></td> </tr> '; } } $output .= ' </table> '; $output .= ' </div>'; /* /GETALLHEADERS */ /* DATA */ $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-getpost-data">'; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> <tr> <td class="debugtoolbar-table-title" colspan="2">Post Data</td> </tr> '; $post = isset($_POST) ? $_POST : array(); if(!count($post)) $output .= '<tr><td colspan="2">No POST Data Found</td></tr>'; else { foreach ($post as $name => $value) { if(!is_array($value)) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } else { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td> '; foreach ($value as $k => $v) { $output .= ' <pre>'.$k.' : '.$v.'</pre> '; } $output .= ' </td> </tr> '; } } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2">Get Data</td> </tr> '; $get = isset($_GET) ? $_GET : array(); if(!count($get)) $output .= '<tr><td colspan="2">No GET Data Found</td></tr>'; else { foreach ($get as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2">Server Data</td> </tr> '; $server = isset($_SERVER) ? $_SERVER : array(); if(!count($server)) $output .= '<tr><td colspan="2">No SERVER Data Found</td></tr>'; else { foreach ($server as $name => $value) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$name.'</td> <td><pre>'.$value.'</pre></td> </tr> '; } } $output .= ' </table> '; $output .= ' </div>'; /* /DATA */ /* DEBUG */ if(count($GLOBALS['debugtoolbar'])) { $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-debug">'; $output .= ' <table> <tr> <th>Debug</th> </tr> '; $output .= ' <tr> <td colspan="2">'.$GLOBALS['debugtoolbar'].'</td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; } /* /DEBUG */ /* PS INFOS */ if (isset($this->context->employee->id)) : $ps_infos = array( 'version' => array( 'php' => phpversion(), 'server' => $_SERVER['SERVER_SOFTWARE'], 'memory_limit' => ini_get('memory_limit'), 'max_execution_time' => ini_get('max_execution_time') ), 'database' => array( 'version' => Db::getInstance()->getVersion(), 'prefix' => _DB_PREFIX_, 'engine' => _MYSQL_ENGINE_, ), 'uname' => function_exists('php_uname') ? php_uname('s').' '.php_uname('v').' '.php_uname('m') : '', 'apache_instaweb' => Tools::apacheModExists('mod_instaweb'), 'shop' => array( 'ps' => _PS_VERSION_, 'url' => Tools::getHttpHost(true).__PS_BASE_URI__, 'theme' => _THEME_NAME_, ), 'mail' => Configuration::get('PS_MAIL_METHOD') == 1, 'smtp' => array( 'server' => Configuration::get('PS_MAIL_SERVER'), 'user' => Configuration::get('PS_MAIL_USER'), 'password' => Configuration::get('PS_MAIL_PASSWD'), 'encryption' => Configuration::get('PS_MAIL_SMTP_ENCRYPTION'), 'port' => Configuration::get('PS_MAIL_SMTP_PORT'), ), 'user_agent' => $_SERVER['HTTP_USER_AGENT'], ); $tests = ConfigurationTest::getDefaultTests(); $tests_op = ConfigurationTest::getDefaultTestsOp(); $params_required_results = ConfigurationTest::check($tests); $params_optional_results = ConfigurationTest::check($tests_op); $tests_errors = array( 'phpversion' => 'Update your PHP version', 'upload' => 'Configure your server to allow file uploads', 'system' => 'Configure your server to allow the creation of directories and files with write permissions.', 'gd' => 'Enable the GD library on your server.', 'mysql_support' => 'Enable the MySQL support on your server.', 'config_dir' => 'Set write permissions for the "config" folder.', 'cache_dir' => 'Set write permissions for the "cache" folder.', 'sitemap' => 'Set write permissions for the "sitemap.xml" file.', 'img_dir' => 'Set write permissions for the "img" folder and subfolders.', 'log_dir' => 'Set write permissions for the "log" folder and subfolders.', 'mails_dir' => 'Set write permissions for the "mails" folder and subfolders.', 'module_dir' => 'Set write permissions for the "modules" folder and subfolders.', 'theme_lang_dir' => 'Set the write permissions for the "themes'._THEME_NAME_.'/lang/" folder and subfolders, recursively.', 'translations_dir' => 'Set write permissions for the "translations" folder and subfolders.', 'customizable_products_dir' => 'Set write permissions for the "upload" folder and subfolders.', 'virtual_products_dir' => 'Set write permissions for the "download" folder and subfolders.', 'fopen' => 'Allow the PHP fopen() function on your server', 'register_globals' => 'Set PHP "register_global" option to "Off"', 'gz' => 'Enable GZIP compression on your server.' ); $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-ps-info">'; $output .= " <script type=\"text/javascript\"> $(document).ready(function() { $.ajax({ type: 'GET', url: '".$this->context->link->getAdminLink('AdminInformation')."', data: { 'action': 'checkFiles', 'ajax': 1 }, dataType: 'json', success: function(json) { var tab = { 'missing': 'Missing files', 'updated': 'Updated files' }; if (json.missing.length || json.updated.length) $('#changedFilesDebugtoolbar').html('<div style=\"color:#ef8400;\">Changed/missing files have been detected.</div>'); else $('#changedFilesDebugtoolbar').html('<div style=\"color:#0080b0;\">No change has been detected in your files</div>'); $.each(tab, function(key, lang) { if (json[key].length) { var html = $('<ul>').attr('id', key+'_files'); $(json[key]).each(function(key, file) { html.append($('<li>').html(file)) }); $('#changedFilesDebugtoolbar') .append($('<h3>').html(lang+' ('+json[key].length+')')) .append(html); } }); } }); }); </script> "; $output .= ' <table> <tr> <th>Name</th> <th>Value</th> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Server Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">Server</td> <td><pre>'.htmlspecialchars($ps_infos['uname'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Logiciel Serveur</td> <td><pre>'.htmlspecialchars($ps_infos['version']['server'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">PHP Version</td> <td><pre>'.htmlspecialchars($ps_infos['version']['php'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Memory Limit</td> <td><pre>'.htmlspecialchars($ps_infos['version']['memory_limit'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Max Execution Time</td> <td><pre>'.htmlspecialchars($ps_infos['version']['max_execution_time'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Database Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Version</td> <td><pre>'.htmlspecialchars($ps_infos['database']['version'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Engine</td> <td><pre>'.htmlspecialchars($ps_infos['database']['engine'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">MySQL Prefix</td> <td><pre>'.htmlspecialchars($ps_infos['database']['prefix'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Store Informations</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">PrestaShop Version</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['ps'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Store Url</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['url'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Themes Use</td> <td><pre>'.htmlspecialchars($ps_infos['shop']['theme'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; if(!empty($ps_infos['mail'])) : $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Email Setting</strong></td> </tr> <tr> <td colspan="2"><pre>You are using the PHP mail function.</pre></td> </tr> '; else : $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Email Setting</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">SMTP Server</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['server'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Cryptage</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['encryption'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Port</td> <td><pre>'.htmlspecialchars($ps_infos['smtp']['port'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Login</td> <td><pre>'.(!empty($ps_infos['smtp']['user']) ? '<span style="color:#90bd00;font-weight:bold;">OK</span>' : '<span style="color:#ff4141;font-weight:bold;">Not defined</span>').'</pre></td> </tr> <tr> <td class="debugtoolbar-table-first">Password</td> <td><pre>'.(!empty($ps_infos['smtp']['password']) ? '<span style="color:#90bd00;font-weight:bold;">OK</span>' : '<span style="color:#ff4141;font-weight:bold;">Not defined</span>').'</pre></td> </tr> '; endif; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Your information</strong></td> </tr> <tr> <td class="debugtoolbar-table-first">Your web browser</td> <td><pre>'.htmlspecialchars($ps_infos['user_agent'], ENT_NOQUOTES, 'utf-8', false).'</pre></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Check your configuration</strong></td> </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-first">Required parameters</td> '; if (!in_array('fail', $params_required_results)) : $output .= ' <td><pre><span style="color:#90bd00;font-weight:bold;">OK</span></pre></td> '; else : $output .= ' <td> <pre><span style="color:#ff4141;font-weight:bold;">Please fix the following error(s)</span></pre> <ul> '; foreach ($params_required_results as $key => $value) if ($value == 'fail') $output .= ' <li>'.$tests_errors[$key].'</li>'; $output .= ' </ul> </td> '; endif; $output .= ' </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-first">Optional parameters</td> '; if (!in_array('fail', $params_optional_results)) : $output .= ' <td><pre><span style="color:#90bd00;font-weight:bold;">OK</span></pre></td> '; else : $output .= ' <td> <pre><span style="color:#ff4141;font-weight:bold;">Please fix the following error(s)</span></pre> <ul> '; foreach ($params_optional_results as $key => $value) if ($value == 'fail') $output .= ' <li>'.$key.'</li>'; $output .= ' </ul> </td> '; endif; $output .= ' </tr> '; $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>List of changed files</strong></td> </tr> '; $output .= ' <tr> <td colspan="2"><div id="changedFilesDebugtoolbar"><img src="../img/admin/ajax-loader.gif" /> Checking files...</div></td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; else : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-ps-info">'; $output .= ' <table> <tr> <td><pre><span style="color:#ff4141;font-weight:bold;">Not display in Front office</span></pre></td> </tr> </table> </div> '; endif; /* /PS INFOS */ /* SMARTY DEBUG */ $this->context->smarty->loadPlugin('Smarty_Internal_Debug'); // Smarty_Internal_Debug::display_debug($this->context->smarty); $SID = new Smarty_Internal_Debug(); $obj = $this->context->smarty; $ptr = $SID::get_debug_vars($obj); if ($obj instanceof Smarty) { $smarty = clone $obj; } else { $smarty = clone $obj->smarty; } $_assigned_vars = $ptr->tpl_vars; ksort($_assigned_vars); $_config_vars = $ptr->config_vars; ksort($_config_vars); $smarty->registered_filters = array(); $smarty->autoload_filters = array(); $smarty->default_modifiers = array(); $smarty->force_compile = false; $smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; $smarty->debugging = false; $smarty->force_compile = false; if ($obj instanceof Smarty_Internal_Template) $template_name = $obj->source->type . ':' . $obj->source->name; if ($obj instanceof Smarty) $template_name = $SID::$template_data; else $template_name = null; $execution_time = microtime(true) - $smarty->start_time; $assigned_vars = $_assigned_vars; $config_vars = $_config_vars; // echo 'assigned_vars<pre>'.print_r($assigned_vars['SCRIPT_NAME'], true).'</pre>';die; $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-smarty-debug">'; $output .= ' <table> <tr> <th colspan="2">Smarty Debug Console - '.((isset($template_name) && count($template_name)) ? $template_name : 'Total Time '.number_format($execution_time, 5, '.', '')).'</th> </tr> '; if (isset($template_name) && count($template_name)) { foreach ($template_name as $template) { $output .= ' <tr> <td class="debugtoolbar-table-first"><font color=brown>'.$template['name'].'</font></td> <td> <span style="font-size: 0.8em;font-style: italic;"> '.number_format($template['compile_time'], 5, '.', '').' '.number_format($template['render_time'], 5, '.', '').' '.number_format($template['cache_time'], 5, '.', '').' </span> </td> </tr> '; } } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><strong>Assigned template variables</strong></td> </tr> '; foreach ($assigned_vars as $key => $vars) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$key.'</td> <td><pre>'.smarty_modifier_debug_print_var($vars).'</pre></td> </tr> '; } $output .= ' <tr> <td class="debugtoolbar-table-title" colspan="2"><trong>Assigned config file variables (outer template scope)</strong></td> </tr> '; foreach ($config_vars as $key => $vars) { $output .= ' <tr> <td class="debugtoolbar-table-first">'.$key.'</td> <td><pre>'.smarty_modifier_debug_print_var($vars).'</pre></td> </tr> '; } $output .= ' </table> '; $output .= ' </div>'; /* SMARTY DEBUG */ /* ADMINER */ if (isset($this->context->employee->id)) : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-adminer">'; $output .= ' <table> <tr> <th>Adminer</th> </tr> '; $output .= ' <tr> <td colspan="2"> <iframe src="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/tools/adminer/display.php?server='._DB_SERVER_.'&username='._DB_USER_.'&db='._DB_NAME_.'" frameborder="0" height="880" width="100%" id="adminerFrame"></iframe> <script type="text/javascript"> $(\'#adminerFrame\').load(function(){ $self = $(this).contents(); $self.find("input[name=\'auth[server]\']").val("'._DB_SERVER_.'"); $self.find("input[name=\'auth[username]\']").val("'._DB_USER_.'"); $self.find("input[name=\'auth[password]\']").val("'._DB_PASSWD_.'"); $self.find("input[name=\'auth[db]\']").val("'._DB_NAME_.'"); }); </script> </td> </tr> '; $output .= ' </table> '; $output .= ' </div>'; else : $output .= ' <div class="debugtoolbar-tab-pane debugtoolbar-table debugtoolbar-adminer">'; $output .= ' <table> <tr> <td><pre><span style="color:#ff4141;font-weight:bold;">Not display in Front office</span></pre></td> </tr> </table> </div> '; endif; /* /ADMINER */ $output .= ' </div> </div> <ul id="debugtoolbar-open-tabs" class="debugtoolbar-tabs"> <!-- LOAD TIME --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-load-times">Time <span class="debugtoolbar-count">'.$this->displayLoadTimeColor($this->_time['display'] - $start_time).'</span></a></li> <!-- /LOAD TIME --> <!-- HOOK PROCESSING --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-hook-processing">Hook <span class="debugtoolbar-count">'.$this->displayLoadTimeColor($totalHookTime).' / '.$this->displayMemoryColor($totalHookMemoryUsage).'</span></a></li> <!-- /HOOK PROCESSING --> <!-- MEMORY PEAK USAGE --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-memory-peak-usage">Memory <span class="debugtoolbar-count">'.$this->displayPeakMemoryColor($memory_peak_usage).'</span></a></li> <!-- /MEMORY PEAK USAGE --> <!-- INCLUDED FILES --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-included-files">Files <span class="debugtoolbar-count">'.sizeof(get_included_files()).'</span></a></li> <!-- /INCLUDED FILES --> <!-- SQL QUERIES --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-sql-queries">Sql <span class="debugtoolbar-count">'.$this->displaySQLQueries(count(Db::getInstance()->queries)).'</span><span class="debugtoolbar-count">'.$this->displayLoadTimeColor($totalQueryTime).'</span></a></li> <!-- /SQL QUERIES --> <!-- TABLE --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-sql-table">Table</a></li> <!-- /TABLE --> <!-- OBJECTMODEL --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-objectmodel-instance">ObjectModel</a></li> <!-- /OBJECTMODEL --> <!-- GETALLHEADERS --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-getallheader">Header</a></li> <!-- /GETALLHEADERS --> <!-- DATA --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-getpost-data">Data</a></li> <!-- /DATA --> <!-- PS INFOS --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-ps-info">Infos</a></li> <!-- /PS INFOS --> <!-- SMARTY DEBUG --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-smarty-debug">Smarty</a></li> <!-- /SMARTY DEBUG --> <!-- ADMINER --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-adminer">Adminer</a></li> <!-- /ADMINER --> '; if(count($GLOBALS['debugtoolbar'])) { $output .= ' <!-- DEBUG --> <li><a class="debugtoolbar-tab" data-debugtoolbar-tab="debugtoolbar-debug">Debug</a></li> <!-- /DEBUG --> '; } $output .= ' <li class="debugtoolbar-tab-right"><a id="debugtoolbar-hide" href="#">&#8614;</a></li> <li class="debugtoolbar-tab-right"><a id="debugtoolbar-close" href="#">&times;</a></li> <li class="debugtoolbar-tab-right"><a id="debugtoolbar-zoom" href="#">&#8645;</a></li> </ul> <ul id="debugtoolbar-closed-tabs" class="debugtoolbar-tabs"> <li><a id="debugtoolbar-show" href="#">&#8612;</a></li> </ul> </div> '; $output .= '<script type="text/javascript" src="'.Tools::getHttpHost(true).__PS_BASE_URI__.'modules/debugtoolbar/views/assets/js/debugtoolbar.js"></script>'; echo $output; } } function prestashop_querytime_sort($a, $b) { if ($a['time'] == $b['time']) return 0; return ($a['time'] > $b['time']) ? -1 : 1; }
Prestaspirit/debugtoolbar
override/classes/controller/Controller.php
PHP
gpl-3.0
48,323
This is V3.3.2 of the Arduino Code Improvements: - Weld time can be set down to 1ms (before minimum was 3ms) - Short Pulse (preheat pulse) percentage can be adjusted down to 0% (0% turns the short pulse off) - on weld times below 3ms the short pulse (preheat pulse) will be automatically disabled - battery voltage only updates about every 15 seconds now - low battery message can be canceled by clicking the rotary encoder - code is now compatible with the newer Adafruit SSD1306 and GFX library versions
KaeptnBalu/Arduino_Spot_Welder_V3
Arduino Code/V3.3.2 Arduino Code/Readme.md
Markdown
gpl-3.0
507
// Simple 3D Model Viewer // Copyright (C) 2012 Ingo Ruhnke <grumbel@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef HEADER_ASSERT_GL_HPP #define HEADER_ASSERT_GL_HPP #include <sstream> #include <stdexcept> #include "opengl.hpp" #include "format.hpp" #define assert_gl(...) assert_gl_1(__FILE__, __LINE__, __VA_ARGS__) template<typename ...Arg> inline void assert_gl_1(const char* file, int line, const std::string& fmt, Arg... arg) { GLenum error = glGetError(); if(error != GL_NO_ERROR) { #ifdef HAVE_OPENGLES2 throw std::runtime_error(format("%s:%d: OpenGLError while '%s': %s", file, line, format(fmt, arg...), error)); #else throw std::runtime_error(format("%s:%d: OpenGLError while '%s': %s", file, line, format(fmt, arg...), gluErrorString(error))); #endif } } #endif /* EOF */
Grumbel/viewer
src/assert_gl.hpp
C++
gpl-3.0
1,656
<?php /** * Template part for displaying page content in page.php. * * @link https://codex.wordpress.org/Template_Hierarchy * * @package lorainccc */ ?> <?php $whattodisplay = 'lccc-events'; $today = getdate(); $currentDay = $today['mday']; $month = $today['mon']; $year = $today['year']; $firsteventdate =''; $nexteventdate =''; $todaysevents = ''; $temp = strLen($currentDay); $twoDay = ''; $nextTwoDay = ''; if ($temp < 2){ $twoDay = '0' . $currentDay; }else{ $twoDay = $currentDay; } $twomonth = ''; $tempmonth = strLen($month); if ($tempmonth < 2){ $twomonth = '0' . $month; }else{ $twomonth = $month; } $nextDay = $currentDay + 1; if ($temp < 2){ $nextTwoDay = '0' . $currentDay; }else{ $nextTwoDay = $currentDay; } $starteventdate = event_meta_box_get_meta('event_start_date'); $starteventtime = event_meta_box_get_meta('event_start_time'); $endeventdate = event_meta_box_get_meta('event_end_date'); $endtime = event_meta_box_get_meta('event_end_time'); $starttimevar=strtotime($starteventtime); $starttime= date("h:i a",$starttimevar); $starteventtimehours = date("G",$starttimevar); $starteventtimeminutes = date("i",$starttimevar); $startdate=strtotime($starteventdate); $eventstartdate=date("Y-m-d",$startdate); $eventstartmonth=date("M",$startdate); $eventstartmonthfull=date("F",$startdate); $eventstartday =date("j",$startdate); $eventstartyear =date("Y",$startdate); $endeventtimevar=strtotime($endtime); $endeventtime = date("h:i a",$endeventtimevar); $endeventtimehours = date("G",$endeventtimevar); $endeventtimeminutes = date("i",$endeventtimevar); $enddate=strtotime($endeventdate); $endeventdate = date("Y-m-d",$enddate); $duration = ''; if($endeventtimehours == 0){ $endeventtimehours =24; } $durationhours = $endeventtimehours - $starteventtimehours; if($durationhours > 0){ if($durationhours == 24){ $duration .= '1 day'; }else{ $duration .= $durationhours.'hrs'; } } $durationminutes = $endeventtimeminutes - $starteventtimeminutes; if($durationminutes > 0){ $duration .= $durationminutes.'mins'; } $location = event_meta_box_get_meta('event_meta_box_event_location'); $cost = event_meta_box_get_meta('event_meta_box_ticket_price_s_'); $bgcolor = event_meta_box_get_meta('event_meta_box_stoccker_bg_color'); $ticketlink = event_meta_box_get_meta('event_meta_box_stocker_ticket_link'); $eventsubheading = event_meta_box_get_meta('event_meta_box_sub_heading'); ?> <article id="post-<?php the_ID(); ?>"> <div class="small-12 medium-12 large-12 columns"> <?php the_title( '<h1 class="entry-title indiv-event">', '</h1>' ); ?> <?php if( $eventsubheading != ''){ ?> <h4 class="event-sub-heading"><?php echo $eventsubheading;?> </h4> <?php } ?> </div> <div class="small-12 medium-2 large-2 columns"> <?php echo '<div class="small-12 medium-12 large-12 columns event-date">'; echo '<div class="small-12 medium-12 large-12 columns calender">'; echo '<p class="stocker-month">'.$eventstartmonth.'</p>'; echo '<p class="stocker-day">'.$eventstartday.'</p>'; echo '</div>'; echo '</div>'; ?> </div> <div class="small-12 medium-10 large-10 columns nopadding"> <header class="entry-header"> <div class="taxonomies"> <?php echo get_the_term_list( $post->ID, 'event_categories','', ' , ' , ''); ?> </div> <p><?php echo 'Date: '.$eventstartmonthfull.' '.$eventstartday.' , '.$eventstartyear; ?></p> <p><?php echo 'Time: '.$starttime; ?></p> <p><?php echo 'Location: '.$location; ?></p> <?php if($cost != ''){ ?> <p><?php echo 'Cost: '.$cost; ?></p> <?php } ?> <?php if($ticketlink != ''){ ?> <a href=" <?php echo $ticketlink; ?>" class="buy-ticket-link">Buy Tickets</a> <?php } ?> </header><!-- .entry-header --> </div> <div class="small-12 medium-12large-12 columns content-container"> <div class="entry-content"> <div class="small-12 medium-12large-12 columns nopadding"> <?php the_content(); ?> </div> <div class="small-12 medium-4 large-4 columns nopadding"> <?php echo '<br /> <br /> <a class="button" href="'.get_post_type_archive_link( 'lccc_events' ).'">Back To All Events </a>';?> </div> <div class="small-12 medium-8 large-8 columns"> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'lorainccc' ), 'after' => '</div>', ) ); ?> </div> </div><!-- .entry-content --> </div> <?php if ( get_edit_post_link() ) : ?> <?php edit_post_link( sprintf( /* translators: %s: Name of current post */ esc_html__( 'Edit %s', 'lorainccc' ), the_title( '<span class="screen-reader-text">"', '"</span>', false ) ), '<span class="edit-link">', '</span>' ); ?> <?php endif; ?> </article><!-- #post-## -->
lorainccc/themes
lorainccc_stocker/template-parts/content-lccc-event.php
PHP
gpl-3.0
5,375
#include <vigir_footstep_planning_default_plugins/world_model/terrain_model.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <vigir_footstep_planning_lib/helper.h> #include <vigir_footstep_planning_lib/math.h> #include <vigir_terrain_classifier/terrain_model.h> namespace vigir_footstep_planning { TerrainModel::TerrainModel(const std::string& name) : TerrainModelPlugin(name) { } bool TerrainModel::initialize(const vigir_generic_params::ParameterSet& params) { if (!TerrainModelPlugin::initialize(params)) return false; // get foot dimensions getFootSize(nh_, foot_size); // subscribe std::string topic; getParam("terrain_model_topic", topic, std::string("terrain_model"), true); terrain_model_sub = nh_.subscribe(topic, 1, &TerrainModel::setTerrainModel, this); return true; } bool TerrainModel::loadParams(const vigir_generic_params::ParameterSet& params) { if (!TerrainModelPlugin::loadParams(params)) return false; params.getParam("foot_contact_support/min_sampling_steps_x", min_sampling_steps_x); params.getParam("foot_contact_support/min_sampling_steps_y", min_sampling_steps_y); params.getParam("foot_contact_support/max_sampling_steps_x", max_sampling_steps_x); params.getParam("foot_contact_support/max_sampling_steps_y", max_sampling_steps_y); params.getParam("foot_contact_support/max_intrusion_z", max_intrusion_z); params.getParam("foot_contact_support/max_ground_clearance", max_ground_clearance); params.getParam("foot_contact_support/minimal_support", minimal_support); return true; } void TerrainModel::reset() { TerrainModelPlugin::reset(); boost::unique_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); if (terrain_model) terrain_model->reset(); } bool TerrainModel::isAccessible(const State& s) const { return s.getGroundContactSupport() >= minimal_support; } bool TerrainModel::isAccessible(const State& next, const State& /*current*/) const { return isAccessible(next); } bool TerrainModel::isTerrainModelAvailable() const { return terrain_model && terrain_model->hasTerrainModel(); } void TerrainModel::setTerrainModel(const vigir_terrain_classifier::TerrainModelMsg::ConstPtr& terrain_model) { boost::unique_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); // update terrain model if (!this->terrain_model) this->terrain_model.reset(new vigir_terrain_classifier::TerrainModel(*terrain_model)); else this->terrain_model->fromMsg(*terrain_model); } double TerrainModel::getResolution() const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getResolution(); } bool TerrainModel::getPointWithNormal(const pcl::PointNormal& p_search, pcl::PointNormal& p_result) const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getPointWithNormal(p_search, p_result); } bool TerrainModel::getHeight(double x, double y, double& height) const { boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); return terrain_model->getHeight(x, y, height); } bool TerrainModel::getFootContactSupport(const geometry_msgs::Pose& p, double &support, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { tf::Pose p_tf; tf::poseMsgToTF(p, p_tf); return getFootContactSupport(p_tf, support, checked_positions); } bool TerrainModel::getFootContactSupport(const tf::Pose& p, double& support, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { if (!getFootContactSupport(p, support, min_sampling_steps_x, min_sampling_steps_y, checked_positions)) return false; // refinement of solution if needed if (support == 0.0) // collision, no refinement { return true; } else if (support < 0.95) { if (!getFootContactSupport(p, support, max_sampling_steps_x, max_sampling_steps_y, checked_positions)) return false; } return true; } bool TerrainModel::getFootContactSupport(const tf::Pose& p, double &support, unsigned int sampling_steps_x, unsigned int sampling_steps_y, pcl::PointCloud<pcl::PointXYZI>::Ptr checked_positions) const { /// TODO: find efficient solution to prevent inconsistency //boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); support = 0.0; unsigned int contacts = 0; unsigned int unknown = 0; unsigned int total = 0; tf::Vector3 orig_pos; orig_pos.setZ(0.0); double foot_size_half_x = 0.5*foot_size.x; double foot_size_half_y = 0.5*foot_size.y; double sampling_step_x = foot_size.x/(double)(sampling_steps_x-1); double sampling_step_y = foot_size.y/(double)(sampling_steps_y-1); for (double y = -foot_size_half_y; y <= foot_size_half_y; y+=sampling_step_y) { orig_pos.setY(y); for (double x = -foot_size_half_x; x <= foot_size_half_x; x+=sampling_step_x) { total++; // determine point in world frame and get height at this point orig_pos.setX(x); const tf::Vector3 &trans_pos = p * orig_pos; double height = 0.0; if (!getHeight(trans_pos.getX(), trans_pos.getY(), height)) { //ROS_WARN_THROTTLE(1.0, "getFootSupportArea: No height data found at %f/%f", p.getOrigin().getX(), p.getOrigin().getY()); unknown++; continue; } // diff heights double diff = trans_pos.getZ()-height; // save evaluated point for visualization if (checked_positions) { pcl::PointXYZI p_checked; p_checked.x = trans_pos.getX(); p_checked.y = trans_pos.getY(); p_checked.z = trans_pos.getZ(); p_checked.intensity = std::abs(diff); checked_positions->push_back(p_checked); //ROS_INFO("%f %f | %f %f | %f", x, y, p.z, height, diff); } // check diff in z if (diff < -max_intrusion_z) // collision -> no support! return true; else if (diff < max_ground_clearance) // ground contact contacts++; } } if (unknown == total) { return false; } else { /// @ TODO: refinement (center of pressure) support = static_cast<double>(contacts)/static_cast<double>(total); return true; } } bool TerrainModel::update3DData(geometry_msgs::Pose& p) const { return terrain_model->update3DData(p); } bool TerrainModel::update3DData(State& s) const { /// TODO: find efficient solution to prevent inconsistency //boost::shared_lock<boost::shared_mutex> lock(terrain_model_shared_mutex); bool result = true; // get z double z = s.getZ(); if (!getHeight(s.getX(), s.getY(), z)) { //ROS_WARN_THROTTLE(1.0, "No height data found at %f/%f", s.getX(), s.getY()); result = false; } else { s.setZ(z); } // get roll and pitch pcl::PointNormal p_n; p_n.x = s.getX(); p_n.y = s.getY(); p_n.z = s.getZ(); if (!getPointWithNormal(p_n, p_n)) { //ROS_WARN_THROTTLE(1.0, "No normal data found at %f/%f", s.getX(), s.getY()); result = false; } else { s.setNormal(p_n.normal_x, p_n.normal_y, p_n.normal_z); } // determine ground contact support double support = 0.0; if (!getFootContactSupport(s.getPose(), support)) { //ROS_WARN_THROTTLE(1.0, "Couldn't determine ground contact support at %f/%f", s.getX(), s.getY()); result = false; } else { s.setGroundContactSupport(support); } return result; } } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(vigir_footstep_planning::TerrainModel, vigir_footstep_planning::TerrainModelPlugin)
team-vigir/vigir_footstep_planning_core
vigir_footstep_planning_default_plugins/src/world_model/terrain_model.cpp
C++
gpl-3.0
7,592
<?php /***************************************************************************\ * SPIP, Système de publication pour l'internet * * * * Copyright © avec tendresse depuis 2001 * * Arnaud Martin, Antoine Pitrou, Philippe Rivière, Emmanuel Saint-James * * * * Ce programme est un logiciel libre distribué sous licence GNU/GPL. * * Pour plus de détails voir le fichier COPYING.txt ou l'aide en ligne. * \***************************************************************************/ if (!defined('_ECRIRE_INC_VERSION')) { return; } include_spip('base/abstract_sql'); function install_etape_2_dist() { $adresse_db = defined('_INSTALL_HOST_DB') ? _INSTALL_HOST_DB : _request('adresse_db'); if (preg_match(',(.*):(.*),', $adresse_db, $r)) { [, $adresse_db, $port] = $r; } else { $port = ''; } $login_db = defined('_INSTALL_USER_DB') ? _INSTALL_USER_DB : _request('login_db'); $pass_db = defined('_INSTALL_PASS_DB') ? _INSTALL_PASS_DB : _request('pass_db'); $server_db = defined('_INSTALL_SERVER_DB') ? _INSTALL_SERVER_DB : _request('server_db'); $name_db = defined('_INSTALL_NAME_DB') ? _INSTALL_NAME_DB : ''; $chmod = _request('chmod'); $link = spip_connect_db($adresse_db, $port, $login_db, $pass_db, $name_db, $server_db); $GLOBALS['connexions'][$server_db] = $link; $GLOBALS['connexions'][$server_db][$GLOBALS['spip_sql_version']] = $GLOBALS['spip_' . $server_db . '_functions_' . $GLOBALS['spip_sql_version']]; echo install_debut_html(); // prenons toutes les dispositions possibles pour que rien ne s'affiche ! /* * /!\ sqlite3/PDO : erreur sur join(', ', $link) * L'objet PDO ne peut pas etre transformee en chaine * Un echo $link ne fonctionne pas non plus * Il faut utiliser par exemple print_r($link) */ //echo "\n<!--\n", join(', ', $link), " $login_db "; $db_connect = 0; // revoirfunction_exists($ferrno) ? $ferrno() : 0; //echo join(', ', $GLOBALS['connexions'][$server_db]); //echo "\n-->\n"; if (($db_connect == '0') && $link) { echo "<div class='success'><b>" . _T('info_connexion_ok') . '</b></div>'; echo info_progression_etape(2, 'etape_', 'install/'); echo info_etape(_T('menu_aide_installation_choix_base') . aider('install2', true)); echo "\n", '<!-- ', sql_version($server_db), ' -->'; [$checked, $res] = install_etape_2_bases($login_db, $server_db); $hidden = (defined('_SPIP_CHMOD') ? '' : ("\n<input type='hidden' name='chmod' value='" . spip_htmlspecialchars($chmod) . "' />")) . predef_ou_cache($adresse_db . ($port ? ':' . $port : ''), $login_db, $pass_db, $server_db); echo install_etape_2_form($hidden, $checked, $res, 3); } else { echo info_progression_etape(1, 'etape_', 'install/', true); echo "<div class='error'>"; echo info_etape(_T('info_connexion_base')); echo '<h3>' . _T('avis_connexion_echec_1') . '</h3>'; echo '<p>' . _T('avis_connexion_echec_2') . '</p>'; echo "<p style='font-size: small;'>", _T('avis_connexion_echec_3'), '</p></div>'; } echo install_fin_html(); } // Liste les bases accessibles, // avec une heuristique pour preselectionner la plus probable function install_etape_2_bases($login_db, $server_db) { $res = install_etape_liste_bases($server_db, $login_db); if ($res) { [$checked, $bases] = $res; return [ $checked, "<label for='choix_db'><b>" . _T('texte_choix_base_2') . '</b><br />' . _T('texte_choix_base_3') . '</label>' . "<ul>\n<li>" . join("</li>\n<li>", $bases) . "</li>\n</ul><p>" . _T('info_ou') . ' ' ]; } $res = '<b>' . _T('avis_lecture_noms_bases_1') . '</b> ' . _T('avis_lecture_noms_bases_2') . '<p>'; $checked = false; if ($login_db) { // Si un login comporte un point, le nom de la base est plus // probablement le login sans le point -- testons pour savoir $test_base = $login_db; $ok = sql_selectdb($test_base, $server_db); $test_base2 = str_replace('.', '_', $test_base); if (sql_selectdb($test_base2, $server_db)) { $test_base = $test_base2; $ok = true; } if ($ok) { $res .= _T('avis_lecture_noms_bases_3') . '<ul>' . '<li><input name="choix_db" value="' . $test_base . "\" type='radio' id='stand' checked='checked' />" . "<label for='stand'>" . $test_base . "</label></li>\n" . '</ul>' . '<p>' . _T('info_ou') . ' '; $checked = true; } } return [$checked, $res]; } function install_etape_2_form($hidden, $checked, $res, $etape) { return generer_form_ecrire('install', ( "\n<input type='hidden' name='etape' value='$etape' />" . $hidden . (defined('_INSTALL_NAME_DB') ? '<h3>' . _T('install_nom_base_hebergeur') . ' <tt>' . _INSTALL_NAME_DB . '</tt>' . '</h3>' : "\n<fieldset><legend>" . _T('texte_choix_base_1') . "</legend>\n" . $res . "\n<input name=\"choix_db\" value=\"new_spip\" type='radio' id='nou'" . ($checked ? '' : " checked='checked'") . " />\n<label for='nou'>" . _T('info_creer_base') . "</label></p>\n<p>" . "\n<input type='text' name='table_new' class='text' value=\"spip\" size='20' /></p></fieldset>\n" ) . ((defined('_INSTALL_TABLE_PREFIX') or $GLOBALS['table_prefix'] != 'spip') ? '<h3>' . _T('install_table_prefix_hebergeur') . ' <tt>' . $GLOBALS['table_prefix'] . '</tt>' . '</h3>' : '<fieldset><legend>' . _T('texte_choix_table_prefix') . "</legend>\n" . "<p><label for='table_prefix'>" . _T('info_table_prefix') . '</label></p><p>' . "\n<input type='text' id='tprefix' name='tprefix' class='text' value='" . 'spip' # valeur par defaut . "' size='20' /></p></fieldset>" ) . bouton_suivant())); }
spip/SPIP
ecrire/install/etape_2.php
PHP
gpl-3.0
5,813
<div class="container"> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_START_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&startservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_STOP_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&stopservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_RESTART_SPOOLING']; ?></h4> <br> <a style="color: white;" href="index.php?commands&restartservice"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> <h4 class="form-signin-heading"><?php echo $lang['ADMIN_COMMANDS_REMOVE_ALL_JOBS']; ?></h4> <br> <a style="color: white;" href="index.php?commands&removealljobs"><button type="button" class="btn btn-success btn-lg"><?php echo $lang['ADMIN_COMMANDS_APPLY']; ?></button></a> <br> <hr> </div>
akshinmustafayev/PrinterSetupSystem
app/views/commands.php
PHP
gpl-3.0
1,265
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.Xml; using System.Xml.Serialization; namespace Fibonatix.CommDoo.Kalixa.Entities.Response { [Serializable()] [XmlRoot("executePaymentActionResponse", Namespace = "http://www.cqrpayments.com/PaymentProcessing")] public class CaptureResponse : Response { [Required] [XmlElement(ElementName = "statusCode")] public string statusCode { get; set; } [XmlArray("actionResults")] [XmlArrayItem(typeof(keyStringValuePair), ElementName = "result")] public dataList actionResults { get; set; } public static CaptureResponse DeserializeFromXmlDocument(XmlDocument doc) { XmlSerializer seri = new XmlSerializer(typeof(CaptureResponse)); var reader = new XmlNodeReader(doc.DocumentElement); CaptureResponse entry = (CaptureResponse)seri.Deserialize(reader); return entry; } public static CaptureResponse DeserializeFromString(string xmlData) { XmlDocument xml = new XmlDocument(); xml.LoadXml(xmlData); return DeserializeFromXmlDocument(xml); } public static CaptureResponse DeserializeFromStringSafe(string xmlData) { CaptureResponse ret = null; try { ret = DeserializeFromString(xmlData); } catch (Exception) { } return ret; } } }
alexeybezverkhiy/fibonatix
PSP/Fibonatix.CommDoo/Kalixa/Entities/Responses/CaptureResponse.cs
C#
gpl-3.0
1,577
/******************************************************************************* * This file is part of RedReader. * * RedReader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RedReader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.quantumbadger.redreader.receivers.announcements; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public final class Payload { private final HashMap<String, String> mStrings = new HashMap<>(); private final HashMap<String, Long> mLongs = new HashMap<>(); private final HashMap<String, Boolean> mBooleans = new HashMap<>(); private static final byte HEADER_EOF = 0; private static final byte HEADER_ENTRY_STRING = 1; private static final byte HEADER_ENTRY_LONG = 2; private static final byte HEADER_ENTRY_BOOLEAN = 3; public void setString(@NonNull final String key, @NonNull final String value) { mStrings.put(key, value); } public void setLong(@NonNull final String key, final long value) { mLongs.put(key, value); } public void setBoolean(@NonNull final String key, final boolean value) { mBooleans.put(key, value); } @Nullable public String getString(@NonNull final String key) { return mStrings.get(key); } @Nullable public Long getLong(@NonNull final String key) { return mLongs.get(key); } @Nullable public Boolean getBoolean(@NonNull final String key) { return mBooleans.get(key); } @NonNull public byte[] toBytes() { final ByteArrayOutputStream result = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(result); try { for(final Map.Entry<String, String> entry : mStrings.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_STRING); dos.writeUTF(entry.getKey()); dos.writeUTF(entry.getValue()); } for(final Map.Entry<String, Long> entry : mLongs.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_LONG); dos.writeUTF(entry.getKey()); dos.writeLong(entry.getValue()); } for(final Map.Entry<String, Boolean> entry : mBooleans.entrySet()) { if(entry.getValue() == null) { continue; } dos.writeByte(HEADER_ENTRY_BOOLEAN); dos.writeUTF(entry.getKey()); dos.writeBoolean(entry.getValue()); } dos.writeByte(HEADER_EOF); dos.flush(); dos.close(); } catch(final IOException e) { throw new RuntimeException(e); } return result.toByteArray(); } @NonNull public static Payload fromBytes(@NonNull final byte[] data) throws IOException { try(DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data))) { final Payload result = new Payload(); while(true) { final byte header = dis.readByte(); switch(header) { case HEADER_EOF: return result; case HEADER_ENTRY_STRING: result.setString(dis.readUTF(), dis.readUTF()); break; case HEADER_ENTRY_LONG: result.setLong(dis.readUTF(), dis.readLong()); break; case HEADER_ENTRY_BOOLEAN: result.setBoolean(dis.readUTF(), dis.readBoolean()); break; default: throw new IOException("Unknown entry header " + header); } } } } }
QuantumBadger/RedReader
src/main/java/org/quantumbadger/redreader/receivers/announcements/Payload.java
Java
gpl-3.0
4,046
// ************************************************************************************************ // // BornAgain: simulate and fit reflection and scattering // //! @file GUI/coregui/utils/ImportDataInfo.h //! @brief Defines ImportDataInfo helper struct //! //! @homepage http://www.bornagainproject.org //! @license GNU General Public License v3 or higher (see COPYING) //! @copyright Forschungszentrum Jülich GmbH 2018 //! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) // // ************************************************************************************************ #ifndef BORNAGAIN_GUI_COREGUI_UTILS_IMPORTDATAINFO_H #define BORNAGAIN_GUI_COREGUI_UTILS_IMPORTDATAINFO_H #include "Device/Unit/IUnitConverter.h" #include <QString> #include <memory> template <class T> class OutputData; //! Carries information about loaded data. class ImportDataInfo { public: ImportDataInfo(); ImportDataInfo(ImportDataInfo&& other); ImportDataInfo(std::unique_ptr<OutputData<double>> data, Axes::Units units); ImportDataInfo(std::unique_ptr<OutputData<double>> data, const QString& units); ~ImportDataInfo(); operator bool() const; std::unique_ptr<OutputData<double>> intensityData() const&; std::unique_ptr<OutputData<double>> intensityData() &&; size_t dataRank() const; QString unitsLabel() const; QString axisLabel(size_t axis_index) const; private: void checkValidity(); std::unique_ptr<OutputData<double>> m_data; Axes::Units m_units; }; #endif // BORNAGAIN_GUI_COREGUI_UTILS_IMPORTDATAINFO_H
gpospelov/BornAgain
GUI/coregui/utils/ImportDataInfo.h
C
gpl-3.0
1,598
.PHONY: default dist install isclean DATAFILES = LICENSE.txt README.rst PYFILES = proxtop default: dist: isclean $(PYFILES) $(DATAFILES) python setup.py sdist ##python setup.py register # only needed once #python setup.py sdist upload # clean up $(RM) MANIFEST install: python setup.py install isclean: # Check that there are no leftover unversioned python files. # If there are, you should clean it up. # (We check this, because the setup.py will include every .py it finds # due to its find_package_module() function.) ! (git status | sed -e '1,/^# Untracked/d;/^#\t.*\.py$$/!d;s/^#\t/Untracked: /' | grep .)
ossobv/proxtop
Makefile
Makefile
gpl-3.0
627
<?php header('Content-Type:text/html; charset=utf-8'); define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PWD', 'yangfan'); define('DB_NAME', 'blog'); $conn = @mysql_connect(DB_HOST, DB_USER, DB_PWD) or die('数据库链接失败:'.mysql_error()); @mysql_select_db(DB_NAME) or die('数据库错误:'.mysql_error()); @mysql_query('SET NAMES UTF8') or die('字符集错误:'.mysql_error()); ?>
shoushou70/blog_1
blog/config.php
PHP
gpl-3.0
431
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SCA.Interface.DatabaseAccess; using SCA.Interface; using System.Data.OleDb; using System.Data; using System.Collections; /* ============================== * * Author : William * Create Date: 2016/10/26 15:40:54 * FileName : MSAccessDatabaseAccess * Description:微软Access数据库处理类 * Version:V1 * =============================== */ namespace SCA.DatabaseAccess { public class MSAccessDatabaseAccess:IDatabaseService { private static Object _locker = new Object(); //并行锁 private OleDbConnection _db = null; private ILogRecorder _logRecorder; //日志处理 private IFileService _fileService; //文件处理 private OleDbCommand _dbCommand = null; //Command命令 protected string connectionString = ""; //数据库连接串 public MSAccessDatabaseAccess(string connString, ILogRecorder logRecorder, IFileService fileService) { connectionString = connString; _logRecorder = logRecorder; _fileService = fileService; } /// <summary> /// 获取数据为连接对象 /// </summary> /// <returns></returns> public OleDbConnection GetInstance() { if (_db == null) { //"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\App1\你的数据库名.mdb; User ID=admin; Password=" return _db = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + connectionString + "; User ID=; Password=");//("Driver= {MicrosoftAccessDriver(*.mdb)};DBQ="+_connectionString+";Uid=;Pwd="); } else { lock (_locker) { return _db; } } } public object GetObjectValue(StringBuilder sql) { return GetObjectValue(sql, null); } public object GetObjectValue(StringBuilder sql, object[] param) { object result=null; OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { //打开连接 conn.Open(); OleDbCommand cmd = new OleDbCommand(sql.ToString(), conn); if (param != null) { cmd.Parameters.AddRange(param); } result = cmd.ExecuteScalar(); } catch (Exception e) { _logRecorder.WriteException(e); } finally { conn.Close(); } return result; } public int ExecuteBySql(StringBuilder sql) { return ExecuteBySql(sql, null); } public int ExecuteBySql(StringBuilder sql, object[] param) { int num = 0; //创建连接 OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { conn.Open(); //创建指令 String strSQL = sql.ToString(); String[] arraySql = strSQL.Split(';'); for (int i = 0; i < arraySql.Length; i++) { OleDbCommand cmd = new OleDbCommand(arraySql[i].ToString(), conn); OleDbTransaction DbTrans = conn.BeginTransaction(); if (param != null) { cmd.Parameters.AddRange(param); } try { Console.WriteLine("tryExecute"); cmd.Transaction = DbTrans; num = cmd.ExecuteNonQuery(); DbTrans.Commit(); } catch (Exception e) { Console.WriteLine("first:" + e.Message); DbTrans.Rollback(); num = -1; this._logRecorder.WriteException(e); Console.Write(_logRecorder.GetType().ToString()); } } //finally //{ // conn.Close(); // conn.Dispose(); //} } catch (Exception e) { Console.WriteLine("Second" + e.Message); _logRecorder.WriteException(e); } finally { conn.Close(); // conn.Dispose(); } return num; } public int BatchExecuteBySql(object[] sqls, object[] param) { throw new NotImplementedException(); } public System.Data.DataTable GetDataTableBySQL(StringBuilder sql) { return GetDataTableBySQL(sql, null); } public System.Data.DataTable GetDataTableBySQL(StringBuilder sql, object[] param) { OleDbConnection conn = (OleDbConnection)this.GetInstance(); try { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = sql.ToString(); cmd.CommandType = CommandType.Text; if (param != null) { cmd.Parameters.AddRange(param); } return DbReader.ReaderToDataTable(cmd.ExecuteReader()); } catch (Exception e) { this._logRecorder.WriteException(e); return null; } finally { conn.Close(); } } public System.Data.DataSet GetDataSetBySQL(StringBuilder sql) { throw new NotImplementedException(); } public System.Data.DataSet GetDataSetBySQL(StringBuilder sql, object[] param) { throw new NotImplementedException(); } public System.Collections.IList GetDataListBySQL<T>(StringBuilder sql) { throw new NotImplementedException(); } public System.Collections.IList GetDataListBySQL<T>(StringBuilder sql, object[] param) { throw new NotImplementedException(); } public System.Data.DataTable GetPageList(string sql, object[] param, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Data.DataTable GetPageList(string sql, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Collections.IList GetPageList<T>(string sql, object[] param, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public System.Collections.IList GetPageList<T>(string sql, string orderField, string orderType, int pageIndex, int pageSize, ref int count) { throw new NotImplementedException(); } public bool BulkInsert(System.Data.DataTable dt) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public void CreateDBFile() { throw new NotImplementedException(); } } }
A1X71/twilight
SCA.WPF/SCA.DatabaseAccess/Utility/MSAccessDatabaseAccess.cs
C#
gpl-3.0
7,896
package regalowl.hyperconomy.command; import regalowl.hyperconomy.HyperConomy; import regalowl.hyperconomy.HyperEconomy; import regalowl.hyperconomy.shop.Shop; import regalowl.hyperconomy.tradeobject.TradeObject; import regalowl.hyperconomy.tradeobject.TradeObjectType; import regalowl.hyperconomy.transaction.PlayerTransaction; import regalowl.hyperconomy.transaction.TransactionResponse; import regalowl.hyperconomy.transaction.TransactionType; public class Sell extends BaseCommand implements HyperCommand { public Sell(HyperConomy hc) { super(hc, true); } @Override public CommandData onCommand(CommandData data) { if (!validate(data)) return data; try { if (args.length == 0) { data.addResponse(L.get("SELL_INVALID")); return data; } HyperEconomy he = hp.getHyperEconomy(); Shop s = dm.getHyperShopManager().getShop(hp); TradeObject ho = he.getTradeObject(args[0], dm.getHyperShopManager().getShop(hp)); if (ho == null) { data.addResponse(L.get("OBJECT_NOT_IN_DATABASE")); return data; } int amount = 1; if (args.length > 1) { if (args[1].equalsIgnoreCase("max")) { if (ho.getType() == TradeObjectType.ITEM) { amount = hp.getInventory().count(ho.getItem()); } else if (ho.getType() == TradeObjectType.EXPERIENCE) { amount = hp.getTotalXpPoints(); } else if (ho.getType() == TradeObjectType.ENCHANTMENT) { amount = 1; } } else { try { amount = Integer.parseInt(args[1]); if (amount > 10000) amount = 10000; } catch (Exception e) { data.addResponse(L.get("SELL_INVALID")); return data; } } } if (amount > 10000) { amount = 10000; } PlayerTransaction pt = new PlayerTransaction(TransactionType.SELL); pt.setObeyShops(true); pt.setHyperObject(ho); pt.setAmount(amount); if (s != null) pt.setTradePartner(s.getOwner()); TransactionResponse response = hp.processTransaction(pt); response.sendMessages(); } catch (Exception e) { hc.gSDL().getErrorWriter().writeError(e); } return data; } }
RegalOwl/HyperConomy
src/main/java/regalowl/hyperconomy/command/Sell.java
Java
gpl-3.0
2,152
from PyQt5 import QtCore import subprocess from pyconrad import * import numpy as np import jpype import time class forward_project_thread(QtCore.QThread): forward_project_finsihed = QtCore.pyqtSignal(str) def init(self, use_cl, ForwardProj, Phantom): self.use_cl = use_cl self.ForwardProj = ForwardProj self.Phantom = Phantom def get_fanogram(self): return self.fanogram def run(self): jpype.attachThreadToJVM() if self.use_cl: self.fanogram = self.ForwardProj.projectRayDrivenCL(self.Phantom.grid) else: self.fanogram = self.ForwardProj.projectRayDriven(self.Phantom) # time.sleep(5) jpype.detachThreadFromJVM() self.forward_project_finsihed.emit('finished')
alPreuhs/InteractiveReconstruction
Threads/forward_projection_thread.py
Python
gpl-3.0
783
// // NaiveToken.h // CppRete // // Created by Cory Slep on 10/30/13. // Copyright (c) 2013 Cory Slep. All rights reserved. // #ifndef __CppRete__NaiveToken__ #define __CppRete__NaiveToken__ #include <list> #include "Namespaces.h" #include "IToken.h" NAMESPACE_RETE_BEGIN class IBetaMemory; NAMESPACE_RETE_END NAMESPACE_TUPLE_BEGIN class IWME; class NaiveToken : public IToken { public: NaiveToken(IWME* pIWME); NaiveToken(IWME* pIWME, NAMESPACE_RETE::IBetaMemory* pParentMemory); NaiveToken(IWME* pIWME, NAMESPACE_RETE::IBetaMemory* pParentMemory, IToken* pParentToken); virtual ~NaiveToken(); // Inherited from IToken virtual const IToken* const GetParentToken() const; virtual bool SetParentToken(IToken* parent); virtual const NAMESPACE_RETE::IBetaMemory* const GetParentMemory() const; virtual void SetParentMemory(NAMESPACE_RETE::IBetaMemory* parent); virtual const IWME* const GetWME() const; virtual long GetNumTokenChildren() const; virtual bool AddTokenChild(IToken* child); virtual bool RemoveTokenChild(IToken* child); // Inherited from ITupleTraversee virtual void TraversedBy(NAMESPACE_ALG::ITupleTraverser* visitor); // Clients use operators instead of the following functions virtual bool Equals(const IToken& rhs) const; protected: std::list<IToken*> m_listChildTokens; NAMESPACE_RETE::IBetaMemory* m_pParentMemory; IToken* m_pParentToken; IWME* m_pIWME; private: // Disallow copying NaiveToken& operator=(const NaiveToken&); NaiveToken(const NaiveToken&); }; NAMESPACE_TUPLE_END #endif /* defined(__CppRete__NaiveToken__) */
cjslep/cpp-rete-prototype
Headers/NaiveToken.h
C
gpl-3.0
1,675
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.web.magma.support; import java.io.File; import javax.validation.constraints.NotNull; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.obiba.magma.DatasourceFactory; import org.obiba.magma.datasource.crypt.DatasourceEncryptionStrategy; import org.obiba.magma.support.BatchDatasourceFactory; import org.obiba.magma.support.IncrementalDatasourceFactory; import org.obiba.magma.support.Initialisables; import org.obiba.opal.core.identifiers.IdentifierGenerator; import org.obiba.opal.core.magma.IdentifiersMappingDatasourceFactory; import org.obiba.opal.core.runtime.OpalRuntime; import org.obiba.opal.core.service.IdentifiersTableService; import org.obiba.opal.core.service.NoSuchIdentifiersMappingException; import org.obiba.opal.web.model.Identifiers; import org.obiba.opal.web.model.Magma; import org.obiba.opal.web.model.Magma.DatasourceFactoryDto; import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractDatasourceFactoryDtoParser implements DatasourceFactoryDtoParser { @Autowired private OpalRuntime opalRuntime; @Autowired private IdentifiersTableService identifiersTableService; @Autowired private IdentifierGenerator participantIdentifier; @Override public DatasourceFactory parse(DatasourceFactoryDto dto, DatasourceEncryptionStrategy encryptionStrategy) { DatasourceFactory factory = internalParse(dto, encryptionStrategy); // apply wrappers factory = applyIdentifiersMapping(dto, factory); factory = applyIncremental(dto, factory); factory = applyBatch(dto, factory); Initialisables.initialise(factory); return factory; } private DatasourceFactory applyIdentifiersMapping(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasIdConfig()) return factory; Identifiers.IdentifiersMappingConfigDto idConfig = dto.getIdConfig(); String idMapping = idConfig.getName(); if(!identifiersTableService.hasIdentifiersMapping(idMapping)) { throw new NoSuchIdentifiersMappingException(idMapping); } return new IdentifiersMappingDatasourceFactory(factory, idMapping, identifiersTableService, idConfig.getAllowIdentifierGeneration() ? participantIdentifier : null, idConfig.getIgnoreUnknownIdentifier()); } private DatasourceFactory applyIncremental(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasIncrementalConfig()) return factory; Magma.DatasourceIncrementalConfigDto incrementalConfig = dto.getIncrementalConfig(); if(incrementalConfig.getIncremental() && incrementalConfig.hasIncrementalDestinationName()) { return new IncrementalDatasourceFactory(factory, incrementalConfig.getIncrementalDestinationName()); } return factory; } private DatasourceFactory applyBatch(DatasourceFactoryDto dto, DatasourceFactory factory) { if(!dto.hasBatchConfig()) return factory; return new BatchDatasourceFactory(factory, dto.getBatchConfig().getLimit()); } @NotNull protected abstract DatasourceFactory internalParse(DatasourceFactoryDto dto, DatasourceEncryptionStrategy encryptionStrategy); @SuppressWarnings("UnusedDeclaration") protected OpalRuntime getOpalRuntime() { return opalRuntime; } protected FileObject resolveFileInFileSystem(String path) throws FileSystemException { return opalRuntime.getFileSystem().getRoot().resolveFile(path); } protected File resolveLocalFile(String path) { try { // note: does not ensure that file exists return opalRuntime.getFileSystem().getLocalFile(resolveFileInFileSystem(path)); } catch(FileSystemException e) { throw new IllegalArgumentException(e); } } }
apruden/opal
opal-core-ws/src/main/java/org/obiba/opal/web/magma/support/AbstractDatasourceFactoryDtoParser.java
Java
gpl-3.0
4,236
#!/usr/bin/env python # encoding: utf-8 # # Copyright 2009 !j Incorporated # # This file is part of Canner. # # Canner is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Canner is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Canner. If not, see <http://www.gnu.org/licenses/>. # """ parse-config.py """ import sys, os, re from canner import taglib def main(filename): lines = open(filename, 'rU') n = 0 ssh_version = None ssh_enable = False for line in lines: n += 1 # hostname m = re.match(r'set hostname ([\w\d.-]+)', line) if m: host = m.group(1) taglib.tag("hostname", host).implied_by(taglib.env_tags.device, line=n) continue # time m = re.match(r'set ntp server( backup\d)? "?([\w\d.-]+)"?', line) if m: server = m.group(2) if not server == '0.0.0.0': taglib.tag("NTP server", server).implied_by(taglib.env_tags.device, line=n) continue # dns m = re.match(r'set domain ([\w\d.-]+)', line) if m: domain = m.group(1) taglib.tag("domain name", domain).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set dns host dns\d ([\w\d.-]+)', line) if m: server = m.group(1) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set xauth ([\w\d.-]+) dns\d ([\w\d.-]+)', line) if m: server = m.group(2) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue m = re.match(r'set l2tp dns\d ([\w\d.-]+)', line) if m: server = m.group(1) taglib.tag("name server", server).implied_by(taglib.env_tags.device, line=n) continue # interfaces m = re.match(r'set interface ([\w\d]+) ip ([\d.]+)/([\d.]+)( secondary)?', line) if m: name, ipaddress, plen, secondary = m.groups() address = ipaddress + "/" + plen ifaddr_tag = taglib.ip_address_tag(address, "interface address") address_tag = taglib.ip_address_tag(address) subnet_tag = taglib.ip_subnet_tag(address) name_tag = taglib.tag("interface", "%s %s" % (taglib.env_tags.device.name, name)) name_tag.implied_by(taglib.env_tags.snapshot, line=n) name_tag.implies(taglib.env_tags.device, line=n) name_tag.implies(ifaddr_tag, line=n) ifaddr_tag.implies(address_tag, line=n) address_tag.implies(subnet_tag, line=n) continue # accounts m = re.match(r'set admin user "?([\w\d.-]+)"?\s+.*', line) if m: account = m.group(1) taglib.tag("user", account).implied_by(taglib.env_tags.device, line=n) continue # services m = re.match(r'set ssh version ([\w\d]+)', line) if m: ssh_version = m.group(1) ssh_version_line = n continue m = re.match(r'set ssh enable', line) if m: ssh_enable = True taglib.tag("service", 'SSH').implied_by(taglib.env_tags.device, n) continue m = re.match(r'set scp enable', line) if m: taglib.tag("service", 'SCP').implied_by(taglib.env_tags.device, n) continue # post parse phase if ssh_enable: if ssh_version: taglib.tag("service", 'SSH' + ssh_version).implied_by(taglib.env_tags.device, ssh_version_line) if __name__ == '__main__': main(taglib.default_filename) taglib.output_tagging_log()
pusateri/canner
taggers/OS--ScreenOS/file--config.netscreen/parse-config.py
Python
gpl-3.0
4,229
# Copyright (C) 2006-2007 Red Hat, Inc. # Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging from gi.repository import GObject import dbus from gi.repository import TelepathyGLib CONNECTION = TelepathyGLib.IFACE_CONNECTION CONNECTION_STATUS_CONNECTED = TelepathyGLib.ConnectionStatus.CONNECTED from sugar3 import profile from jarabe.util.telepathy import connection_watcher CONNECTION_INTERFACE_BUDDY_INFO = 'org.laptop.Telepathy.BuddyInfo' _owner_instance = None class BaseBuddyModel(GObject.GObject): __gtype_name__ = 'SugarBaseBuddyModel' def __init__(self, **kwargs): self._key = None self._nick = None self._color = None self._tags = None self._current_activity = None GObject.GObject.__init__(self, **kwargs) def get_nick(self): return self._nick def set_nick(self, nick): self._nick = nick nick = GObject.Property(type=object, getter=get_nick, setter=set_nick) def get_key(self): return self._key def set_key(self, key): if isinstance(key, bytes): key = key.decode('utf-8') self._key = key key = GObject.Property(type=object, getter=get_key, setter=set_key) def get_color(self): return self._color def set_color(self, color): self._color = color color = GObject.Property(type=object, getter=get_color, setter=set_color) def get_tags(self): return self._tags tags = GObject.Property(type=object, getter=get_tags) def get_current_activity(self): return self._current_activity def set_current_activity(self, current_activity): if self._current_activity != current_activity: self._current_activity = current_activity self.notify('current-activity') current_activity = GObject.Property(type=object, getter=get_current_activity, setter=set_current_activity) def is_owner(self): raise NotImplementedError class OwnerBuddyModel(BaseBuddyModel): __gtype_name__ = 'SugarOwnerBuddyModel' def __init__(self): BaseBuddyModel.__init__(self) self.props.nick = profile.get_nick_name() self.props.color = profile.get_color() self.props.key = profile.get_profile().pubkey self.connect('notify::nick', self.__property_changed_cb) self.connect('notify::color', self.__property_changed_cb) bus = dbus.SessionBus() bus.add_signal_receiver( self.__name_owner_changed_cb, signal_name='NameOwnerChanged', dbus_interface='org.freedesktop.DBus') bus_object = bus.get_object(dbus.BUS_DAEMON_NAME, dbus.BUS_DAEMON_PATH) for service in bus_object.ListNames( dbus_interface=dbus.BUS_DAEMON_IFACE): if service.startswith(CONNECTION + '.'): path = '/%s' % service.replace('.', '/') conn_proxy = bus.get_object(service, path) self._prepare_conn(path, conn_proxy) def _prepare_conn(self, object_path, conn_proxy): self.connection = {} self.object_path = object_path self.conn_proxy = conn_proxy self.conn_ready = False self.connection[CONNECTION] = \ dbus.Interface(self.conn_proxy, CONNECTION) self.connection[CONNECTION].GetInterfaces( reply_handler=self.__conn_get_interfaces_reply_cb, error_handler=self.__error_handler_cb) def __conn_get_interfaces_reply_cb(self, interfaces): for interface in interfaces: self.connection[interface] = dbus.Interface( self.conn_proxy, interface) self.conn_ready = True self.__connection_ready_cb(self.connection) def __connection_ready_cb(self, connection): if not self.conn_ready: return self._sync_properties_on_connection(connection) def __name_owner_changed_cb(self, name, old, new): if name.startswith(CONNECTION + '.') and not old and new: path = '/' + name.replace('.', '/') self.conn_proxy = dbus.Bus().get_object(name, path) self._prepare_conn(path, self.conn_proxy) def __property_changed_cb(self, buddy, pspec): self._sync_properties() def _sync_properties(self): conn_watcher = connection_watcher.get_instance() for connection in conn_watcher.get_connections(): self._sync_properties_on_connection(connection) def _sync_properties_on_connection(self, connection): if CONNECTION_INTERFACE_BUDDY_INFO in connection: properties = {} if self.props.key is not None: properties['key'] = dbus.ByteArray( self.props.key.encode('utf-8')) if self.props.color is not None: properties['color'] = self.props.color.to_string() logging.debug('calling SetProperties with %r', properties) connection[CONNECTION_INTERFACE_BUDDY_INFO].SetProperties( properties, reply_handler=self.__set_properties_cb, error_handler=self.__error_handler_cb) def __set_properties_cb(self): logging.debug('__set_properties_cb') def __error_handler_cb(self, error): raise RuntimeError(error) def is_owner(self): return True def get_owner_instance(): global _owner_instance if _owner_instance is None: _owner_instance = OwnerBuddyModel() return _owner_instance class BuddyModel(BaseBuddyModel): __gtype_name__ = 'SugarBuddyModel' def __init__(self, **kwargs): self._account = None self._contact_id = None self._handle = None BaseBuddyModel.__init__(self, **kwargs) def is_owner(self): return False def get_account(self): return self._account def set_account(self, account): self._account = account account = GObject.Property(type=object, getter=get_account, setter=set_account) def get_contact_id(self): return self._contact_id def set_contact_id(self, contact_id): self._contact_id = contact_id contact_id = GObject.Property(type=object, getter=get_contact_id, setter=set_contact_id) def get_handle(self): return self._handle def set_handle(self, handle): self._handle = handle handle = GObject.Property(type=object, getter=get_handle, setter=set_handle)
sugarlabs/sugar
src/jarabe/model/buddy.py
Python
gpl-3.0
7,314
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 5.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by the Perl program only. The format and even # the name or existence of this file are subject to change without notice. # Don't use it directly. # 'X' below means that this form is discouraged. Consult perluniprops.pod # # This file returns the 96 code points in Unicode Version 5.2.0 that match # any of the following regular expression constructs: # # \p{Block=Tai_Xuan_Jing_Symbols} # \p{Blk=Tai_Xuan_Jing_Symbols} # \p{Is_Block=Tai_Xuan_Jing_Symbols} # \p{Is_Blk=Tai_Xuan_Jing_Symbols} # # X \p{Tai_Xuan_Jing_Symbols} # X \p{Is_Tai_Xuan_Jing_Symbols} # \p{In_Tai_Xuan_Jing_Symbols} # # perluniprops.pod should be consulted for the syntax rules for any of these, # including if adding or subtracting white space, underscore, and hyphen # characters matters or doesn't matter, and other permissible syntactic # variants. Upper/lower case distinctions never matter. # # A colon can be substituted for the equals sign, and anything to the left of # the equals (or colon) can be combined with anything to the right. Thus, # for example, # \p{Is_Blk: Tai_Xuan_Jing_Symbols} # is also valid. # # The format of the lines of this file is: START\tSTOP\twhere START is the # starting code point of the range, in hex; STOP is the ending point, or if # omitted, the range has just one code point. Numbers in comments in # [brackets] indicate how many code points are in the range. return <<'END'; 1D300 1D35F # [96] END
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/perl/5.12.4/unicore/lib/Blk/TaiXuanJ.pl
Perl
gpl-3.0
1,746
/* * Copyright (C) 2014 David Gutiérrez Rubio <davidgutierrezrubio@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gui.DatosEditor.Docencia; import data.MyConstants; import data.profesores.Profesor; import java.awt.Image; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.TransferHandler; /** * * @author David Gutiérrez Rubio <davidgutierrezrubio@gmail.com> */ public class JTreeProfesoresTransferHandler extends TransferHandler { @Override protected Transferable createTransferable(JComponent c) { ProfesorDraggable resul = null; JTree jtree = (JTree) c; Object value = jtree.getSelectionPath().getLastPathComponent(); if (value instanceof Profesor) { resul = new ProfesorDraggable((Profesor) value); } return resul; } @Override public Image getDragImage() { MyConstants mc = new MyConstants(); return mc.PROFESOR_ICON.getImage(); } @Override public int getSourceActions(JComponent c) { return DnDConstants.ACTION_MOVE; } @Override protected void exportDone(JComponent source, Transferable data, int action) { //System.out.println("ExportDone"); // Here you need to decide how to handle the completion of the transfer, // should you remove the item from the list or not... } @Override public boolean canImport(TransferHandler.TransferSupport support) { return (support.getComponent() instanceof JTree) && support.isDataFlavorSupported(TramoDraggable.MY_FLAVOR); } }
joaquinpintos/kairos
src/gui/DatosEditor/Docencia/JTreeProfesoresTransferHandler.java
Java
gpl-3.0
2,284
/* OpenChange Storage Abstraction Layer library OpenChange Project Copyright (C) Wolfgang Sourdeau 2011 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <talloc.h> #include <dlinklist.h> #include "mapiproxy/libmapistore/mapistore.h" #include "mapiproxy/libmapistore/mapistore_private.h" #include "mapiproxy/libmapistore/mapistore_errors.h" #include "mapiproxy/libmapistore/mgmt/mapistore_mgmt.h" #include "mapiproxy/libmapistore/mgmt/gen_ndr/ndr_mapistore_mgmt.h" static int mapistore_subscription_destructor(void *data) { struct mapistore_subscription *subscription = (struct mapistore_subscription *) data; DEBUG(0, ("#### DELETING SUBSCRIPTION ###\n")); if (!data) return -1; DEBUG(0, ("### 1. NotificationFlags = 0x%x\n", subscription->notification_types)); DEBUG(0, ("### 2. handle = 0x%x\n", subscription->handle)); if (subscription->mqueue != -1) { if (mq_unlink(subscription->mqueue_name) == -1) { perror("mq_unlink"); } DEBUG(0, ("%s unlinked\n", subscription->mqueue_name)); talloc_free(subscription->mqueue_name); } return 0; } struct mapistore_subscription *mapistore_new_subscription(TALLOC_CTX *mem_ctx, struct mapistore_context *mstore_ctx, const char *username, uint32_t handle, uint16_t notification_types, void *notification_parameters) { int ret; struct mapistore_connection_info c; struct mapistore_mgmt_notif n; struct mapistore_subscription *new_subscription; struct mapistore_table_subscription_parameters *table_parameters; struct mapistore_object_subscription_parameters *object_parameters; unsigned int prio; struct mq_attr attr; DATA_BLOB data; new_subscription = talloc_zero(mem_ctx, struct mapistore_subscription); new_subscription->handle = handle; new_subscription->notification_types = notification_types; new_subscription->mqueue = -1; new_subscription->mqueue_name = NULL; if (notification_types == fnevTableModified) { table_parameters = notification_parameters; new_subscription->parameters.table_parameters = *table_parameters; } else { object_parameters = notification_parameters; new_subscription->parameters.object_parameters = *object_parameters; /* NewMail POC: open newmail mail queue */ if (notification_types & fnevNewMail || notification_types & fnevObjectCreated) { new_subscription->mqueue_name = talloc_asprintf((TALLOC_CTX *)new_subscription, MAPISTORE_MQUEUE_NEWMAIL_FMT, username); new_subscription->mqueue = mq_open(new_subscription->mqueue_name, O_RDONLY|O_NONBLOCK|O_CREAT, 0777, NULL); if (new_subscription->mqueue == -1) { perror("mq_open"); talloc_free(new_subscription->mqueue_name); return new_subscription; } /* Empty queue since we only want to retrieve new data from now */ ret = mq_getattr(new_subscription->mqueue, &attr); if (ret == -1) { perror("mq_getattr"); } else { data.data = talloc_size(mem_ctx, attr.mq_msgsize); while ((data.length = mq_receive(new_subscription->mqueue, (char *)data.data, attr.mq_msgsize, &prio)) != -1) { dump_data(0, data.data, data.length); talloc_free(data.data); data.data = talloc_size(mem_ctx, attr.mq_msgsize); } talloc_free(data.data); } /* Set destructor on new_subscription as we want to unlink the queue upon release */ talloc_set_destructor((void *)new_subscription, (int (*)(void *))mapistore_subscription_destructor); /* Send notification to tell about newmail */ n.WholeStore = object_parameters->whole_store; n.NotificationFlags = notification_types; if (n.WholeStore == true) { n.FolderID = 0; n.MessageID = 0; n.MAPIStoreURI = NULL; } else { n.FolderID = object_parameters->folder_id; n.MessageID = object_parameters->object_id; /* FIXME */ n.MAPIStoreURI = NULL; } c.username = (char *)username; c.mstore_ctx = mstore_ctx; ret = mapistore_mgmt_interface_register_subscription(&c, &n); DEBUG(0, ("[%s:%d]: registering notification: %d\n", __FUNCTION__, __LINE__, ret)); } } return new_subscription; } _PUBLIC_ void mapistore_push_notification(struct mapistore_context *mstore_ctx, uint8_t object_type, enum mapistore_notification_type event, void *parameters) { struct mapistore_notification *new_notification; struct mapistore_notification_list *new_list; struct mapistore_table_notification_parameters *table_parameters; struct mapistore_object_notification_parameters *object_parameters; if (!mstore_ctx) return; new_list = talloc_zero(mstore_ctx, struct mapistore_notification_list); new_notification = talloc_zero(new_list, struct mapistore_notification); new_list->notification = new_notification; new_notification->object_type = object_type; new_notification->event = event; if (object_type == MAPISTORE_TABLE) { table_parameters = parameters; new_notification->parameters.table_parameters = *table_parameters; } else { object_parameters = parameters; new_notification->parameters.object_parameters = *object_parameters; if (new_notification->parameters.object_parameters.tag_count > 0 && new_notification->parameters.object_parameters.tag_count != 0xffff) { new_notification->parameters.object_parameters.tags = talloc_memdup(new_notification, new_notification->parameters.object_parameters.tags, sizeof(enum MAPITAGS) * new_notification->parameters.object_parameters.tag_count); } } DLIST_ADD_END(mstore_ctx->notifications, new_list, void); } static struct mapistore_notification_list *mapistore_notification_process_mqueue_notif(TALLOC_CTX *mem_ctx, DATA_BLOB data) { struct mapistore_notification_list *nl; struct mapistore_mgmt_command command; struct ndr_pull *ndr_pull = NULL; ndr_pull = ndr_pull_init_blob(&data, mem_ctx); ndr_pull_mapistore_mgmt_command(ndr_pull, NDR_SCALARS|NDR_BUFFERS, &command); /* verbose */ { struct ndr_print *ndr_print; ndr_print = talloc_zero(mem_ctx, struct ndr_print); ndr_print->print = ndr_print_printf_helper; ndr_print->depth = 1; ndr_print_mapistore_mgmt_command(ndr_print, "command", &command); talloc_free(ndr_print); } if (command.type != MAPISTORE_MGMT_NOTIF) { DEBUG(0, ("[%s:%d]: Invalid command type received: 0x%x\n", __FUNCTION__, __LINE__, command.type)); return NULL; } if (command.command.notification.status != MAPISTORE_MGMT_SEND) { DEBUG(0, ("[%s:%d]: Invalid notification status: 0x%x\n", __FUNCTION__, __LINE__, command.command.notification.status)); return NULL; } nl = talloc_zero(mem_ctx, struct mapistore_notification_list); nl->notification = talloc_zero((TALLOC_CTX *)nl, struct mapistore_notification); /* On newmail notification received, trigger 3 notifications: 1. FolderModifiedNotification (0x3010) 2. MessageObjectCreated (0x8004) 3. FolderModification (0x10) */ switch (command.command.notification.NotificationFlags) { case 0x8004: nl->notification->object_type = MAPISTORE_MESSAGE; nl->notification->event = MAPISTORE_OBJECT_CREATED; nl->notification->parameters.object_parameters.folder_id = command.command.notification.FolderID; nl->notification->parameters.object_parameters.object_id = command.command.notification.MessageID; nl->notification->parameters.object_parameters.tag_count = 24; nl->notification->parameters.object_parameters.tags = talloc_array(nl->notification, enum MAPITAGS, nl->notification->parameters.object_parameters.tag_count); nl->notification->parameters.object_parameters.tags[0] = PR_RCVD_REPRESENTING_ENTRYID; nl->notification->parameters.object_parameters.tags[1] = PR_RCVD_REPRESENTING_ADDRTYPE; nl->notification->parameters.object_parameters.tags[2] = PR_RCVD_REPRESENTING_EMAIL_ADDRESS; nl->notification->parameters.object_parameters.tags[3] = PR_RCVD_REPRESENTING_NAME; nl->notification->parameters.object_parameters.tags[4] = PR_RCVD_REPRESENTING_SEARCH_KEY; nl->notification->parameters.object_parameters.tags[5] = PidTagReceivedRepresentingFlags; nl->notification->parameters.object_parameters.tags[6] = 0x67BA0102; nl->notification->parameters.object_parameters.tags[7] = PR_CONTENT_FILTER_SCL; nl->notification->parameters.object_parameters.tags[8] = PR_LAST_MODIFICATION_TIME; nl->notification->parameters.object_parameters.tags[9] = PR_LAST_MODIFIER_ENTRYID; nl->notification->parameters.object_parameters.tags[10] = PR_LAST_MODIFIER_NAME; nl->notification->parameters.object_parameters.tags[11] = PR_MODIFIER_FLAGS; nl->notification->parameters.object_parameters.tags[12] = 0x67BE0102; nl->notification->parameters.object_parameters.tags[13] = PR_LOCAL_COMMIT_TIME; nl->notification->parameters.object_parameters.tags[14] = PR_RECEIVED_BY_SEARCH_KEY; nl->notification->parameters.object_parameters.tags[15] = PR_RECEIVED_BY_ENTRYID; nl->notification->parameters.object_parameters.tags[16] = PR_RECEIVED_BY_ADDRTYPE; nl->notification->parameters.object_parameters.tags[17] = PR_RECEIVED_BY_EMAIL_ADDRESS; nl->notification->parameters.object_parameters.tags[18] = PR_RECEIVED_BY_NAME; nl->notification->parameters.object_parameters.tags[19] = PidTagReceivedByFlags; nl->notification->parameters.object_parameters.tags[20] = 0x67B90102; nl->notification->parameters.object_parameters.tags[21] = PR_MESSAGE_FLAGS; nl->notification->parameters.object_parameters.tags[22] = PR_MESSAGE_SIZE; nl->notification->parameters.object_parameters.tags[23] = PR_INTERNET_ARTICLE_NUMBER; break; case 0x3010: nl->notification->object_type = MAPISTORE_FOLDER; nl->notification->event = MAPISTORE_OBJECT_MODIFIED; nl->notification->parameters.object_parameters.folder_id = command.command.notification.FolderID; nl->notification->parameters.object_parameters.tag_count = 0x5; nl->notification->parameters.object_parameters.tags = talloc_array(nl->notification, enum MAPITAGS, nl->notification->parameters.object_parameters.tag_count); nl->notification->parameters.object_parameters.tags[0] = PR_CONTENT_COUNT; nl->notification->parameters.object_parameters.tags[1] = PR_CONTENT_UNREAD; nl->notification->parameters.object_parameters.tags[2] = PR_MESSAGE_SIZE; nl->notification->parameters.object_parameters.tags[3] = PR_RECIPIENT_ON_NORMAL_MSG_COUNT; nl->notification->parameters.object_parameters.tags[4] = PR_NORMAL_MESSAGE_SIZE; nl->notification->parameters.object_parameters.message_count = command.command.notification.TotalNumberOfMessages; break; default: DEBUG(3, ("Unsupported Notification Type: 0x%x\n", command.command.notification.NotificationFlags)); break; /* TODO: Finir de faire les notifications FIX dcesrv_exchange_emsmdb.c: fill_notification Faire le test allelouia */ } /* HACK: we only support NewMail notifications for now */ return nl; } /** \details Return the list of pending mapistore notifications available on the queue name specified in argument. \param mstore_ctx pointer to the mapistore context \param mqueue_name the name of the queue to open \param nl pointer on pointer to the list of mapistore notifications to return \return MAPISTORE_SUCCESS on success, otherwise MAPISTORE error. */ _PUBLIC_ enum MAPISTATUS mapistore_get_queued_notifications_named(struct mapistore_context *mstore_ctx, const char *mqueue_name, struct mapistore_notification_list **nl) { int ret; mqd_t mqueue; struct mapistore_notification_list *nlist = NULL; struct mapistore_notification_list *el = NULL; unsigned int prio; struct mq_attr attr; DATA_BLOB data; bool found = false; printf("[%s:%d]: queue name = %s\n", __FUNCTION__, __LINE__, ((mqueue_name) ? mqueue_name : NULL)); /* Sanity checks */ MAPISTORE_RETVAL_IF(!mstore_ctx, MAPISTORE_ERR_NOT_INITIALIZED, NULL); MAPISTORE_RETVAL_IF(!nl, MAPISTORE_ERR_INVALID_PARAMETER, NULL); mqueue = mq_open(mqueue_name, O_RDONLY|O_NONBLOCK|O_CREAT, 0777, NULL); if (mqueue == -1) { perror("mq_open"); return MAPISTORE_ERR_NOT_INITIALIZED; } /* Retrieve queue attributes */ ret = mq_getattr(mqueue, &attr); if (ret == -1) { perror("mq_getattr"); /* set proper error message here and remove above */ if (mq_close(mqueue) == -1) { perror("mq_close"); } MAPISTORE_RETVAL_IF(ret == -1, MAPISTORE_ERR_NOT_FOUND, NULL); } data.data = talloc_size((TALLOC_CTX *)mstore_ctx, attr.mq_msgsize); while ((data.length = mq_receive(mqueue, (char *)data.data, attr.mq_msgsize, &prio)) != -1) { printf("* we received a notification on queue %s\n", mqueue_name); if (!nlist) { nlist = talloc_zero((TALLOC_CTX *)mstore_ctx, struct mapistore_notification_list); } el = mapistore_notification_process_mqueue_notif((TALLOC_CTX *)nlist, data); printf("* processing notification returned %p\n", el); if (el) { DLIST_ADD_END(nlist, el, struct mapistore_notification_list); } talloc_free(data.data); found = true; data.data = talloc_size((TALLOC_CTX *)mstore_ctx, attr.mq_msgsize); } talloc_free(data.data); if (found == true) { *nl = nlist; } if (mq_close(mqueue) == -1) { perror("mq_close"); } return (found == false) ? MAPISTORE_ERR_NOT_FOUND : MAPISTORE_SUCCESS; } /** \details Return the list of pending mapistore notifications within the queue pointed by the mapistore subscription structure. \param mstore_ctx pointer to the mapistore context \param s pointer to the mapistore subscription where the mqueue file descriptor is stored \param nl pointer on pointer to the list of mapistore noficiations to return \return MAPISTORE_SUCCESS on success, otherwise MAPISTORE error */ _PUBLIC_ enum MAPISTATUS mapistore_get_queued_notifications(struct mapistore_context *mstore_ctx, struct mapistore_subscription *s, struct mapistore_notification_list **nl) { int ret; struct mapistore_notification_list *nlist = NULL; struct mapistore_notification_list *el = NULL; unsigned int prio; struct mq_attr attr; DATA_BLOB data; bool found = false; DEBUG(0, ("mapistore_get_queued_notifications: queue name = %s\n", s->mqueue_name)); DEBUG(0, ("mapistore_get_queued_notifications: before sanity checks\n")); /* Sanity checks */ MAPISTORE_RETVAL_IF(!mstore_ctx, MAPISTORE_ERR_NOT_INITIALIZED, NULL); MAPISTORE_RETVAL_IF(!s, MAPISTORE_ERR_INVALID_PARAMETER, NULL); MAPISTORE_RETVAL_IF(!nl, MAPISTORE_ERR_INVALID_PARAMETER, NULL); MAPISTORE_RETVAL_IF(s->mqueue == -1, MAPISTORE_ERR_NOT_FOUND, NULL); DEBUG(0, ("mapistore_get_queued_notifications: after sanity checks\n")); /* Retrieve queue attributes */ ret = mq_getattr(s->mqueue, &attr); if (ret == -1) { perror("mq_getattr"); /* set proper error message here and remove above */ MAPISTORE_RETVAL_IF(ret == -1, MAPISTORE_ERR_NOT_FOUND, NULL); } data.data = talloc_size((TALLOC_CTX *)mstore_ctx, attr.mq_msgsize); DEBUG(0, ("###### attr.mq_msgsize = %d\n", attr.mq_msgsize)); while ((data.length = mq_receive(s->mqueue, (char *)data.data, attr.mq_msgsize, &prio)) != -1) { DEBUG(0, ("data.length = %d\n", data.length)); if (!nlist) { nlist = talloc_zero((TALLOC_CTX *)mstore_ctx, struct mapistore_notification_list); } el = mapistore_notification_process_mqueue_notif((TALLOC_CTX *)nlist, data); if (el) { DLIST_ADD_END(nlist, el, struct mapistore_notification_list); } talloc_free(data.data); found = true; data.data = talloc_size((TALLOC_CTX *)mstore_ctx, attr.mq_msgsize); } talloc_free(data.data); if (found == true) { *nl = nlist; } DEBUG(0, ("mapistore_get_queued_notification: found = %s\n", (found == false) ? "MAPISTORE_ERR_NOT_FOUND" : "MAPISTORE_SUCCESS")); return (found == false) ? MAPISTORE_ERR_NOT_FOUND : MAPISTORE_SUCCESS; } static bool notification_matches_subscription(struct mapistore_notification *notification, struct mapistore_subscription *subscription) { bool result; struct mapistore_table_notification_parameters *n_table_parameters; struct mapistore_table_subscription_parameters *s_table_parameters; struct mapistore_object_notification_parameters *n_object_parameters; struct mapistore_object_subscription_parameters *s_object_parameters; result = false; if (notification->object_type == MAPISTORE_TABLE) { if (subscription->notification_types & fnevTableModified) { n_table_parameters = &notification->parameters.table_parameters; if (subscription->handle == n_table_parameters->handle) { s_table_parameters = &subscription->parameters.table_parameters; result = (n_table_parameters->table_type == s_table_parameters->table_type && n_table_parameters->folder_id == s_table_parameters->folder_id); } } } else { if (((subscription->notification_types & fnevObjectCreated) && notification->event == MAPISTORE_OBJECT_CREATED) || ((subscription->notification_types & fnevObjectModified) && notification->event == MAPISTORE_OBJECT_MODIFIED) || ((subscription->notification_types & fnevObjectDeleted) && notification->event == MAPISTORE_OBJECT_DELETED) || ((subscription->notification_types & fnevObjectCopied) && notification->event == MAPISTORE_OBJECT_COPIED) || ((subscription->notification_types & fnevObjectMoved) && notification->event == MAPISTORE_OBJECT_MOVED)) { n_object_parameters = &notification->parameters.object_parameters; s_object_parameters = &subscription->parameters.object_parameters; if (s_object_parameters->whole_store) result = true; else { if (notification->object_type == MAPISTORE_FOLDER) { result = (n_object_parameters->object_id == s_object_parameters->folder_id); } else if (notification->object_type == MAPISTORE_MESSAGE) { result = (n_object_parameters->folder_id == s_object_parameters->folder_id && (s_object_parameters->object_id == 0 || n_object_parameters->object_id == s_object_parameters->object_id)); } else { DEBUG(5, ("[%s] warning: considering notification for unhandled object: %d...\n", __PRETTY_FUNCTION__, notification->object_type)); } } } } return result; } _PUBLIC_ enum mapistore_error mapistore_delete_subscription(struct mapistore_context *mstore_ctx, uint32_t identifier, uint16_t NotificationFlags) { struct mapistore_subscription_list *el; /* Sanity checks */ MAPISTORE_RETVAL_IF(!mstore_ctx, MAPISTORE_ERR_NOT_INITIALIZED, NULL); for (el = mstore_ctx->subscriptions; el; el = el->next) { if ((el->subscription->handle == identifier) && (el->subscription->notification_types == NotificationFlags)) { DEBUG(0, ("*** DELETING SUBSCRIPTION ***\n")); DEBUG(0, ("subscription: handle = 0x%x\n", el->subscription->handle)); DEBUG(0, ("subscription: types = 0x%x\n", el->subscription->notification_types)); DEBUG(0, ("subscription: mqueue = %d\n", el->subscription->mqueue)); DEBUG(0, ("subscription: mqueue name = %s\n", el->subscription->mqueue_name)); DLIST_REMOVE(mstore_ctx->subscriptions, el); talloc_free(el); return MAPISTORE_SUCCESS; } } return MAPISTORE_ERR_NOT_FOUND; } _PUBLIC_ struct mapistore_subscription_list *mapistore_find_matching_subscriptions(struct mapistore_context *mstore_ctx, struct mapistore_notification *notification) { struct mapistore_subscription_list *matching_subscriptions, *new_element, *current_element; if (!mstore_ctx) return NULL; matching_subscriptions = NULL; current_element = mstore_ctx->subscriptions; while (current_element) { if (notification_matches_subscription(notification, current_element->subscription)) { new_element = talloc_memdup(mstore_ctx, current_element, sizeof(struct mapistore_subscription_list)); DLIST_ADD_END(matching_subscriptions, new_element, void); } current_element = current_element->next; } return matching_subscriptions; }
inverse-inc/openchange.old
mapiproxy/libmapistore/mapistore_notification.c
C
gpl-3.0
21,844
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace NeoComp.Networks.Computational.Neural { [Serializable] [DataContract(IsReference = true, Namespace = NeoComp.xmlns, Name = "afLin")] public sealed class LinearActivationFunction : IActivationFunction { #region Constructors public LinearActivationFunction() { Alpha = 1.0; } public LinearActivationFunction(double alpha) { Alpha = alpha; } #endregion #region Properties [DataMember(Name = "a")] public double Alpha { get; set; } #endregion #region Calculate public double Function(double value) { double result = (value * Alpha); if (result < -Alpha) return -Alpha; else if (result > Alpha) return Alpha; return result; } public double Derivate(double value) { //if (value < -Alpha) return -0.000001; //if (value > Alpha) return 0.000001; //if (value < -Alpha || value > Alpha) return 0; return Alpha; } #endregion } }
unbornchikken/Neuroflow
_vault/NFBak/NeoComp02/NeoComp/Neocomp Framework/!OLD/NeoComp/Networks/Computational/Neural/_ActivationFunctions/LinearActivationFunction.cs
C#
gpl-3.0
1,252
module Api module V21 class InterfacesController < V2::InterfacesController include Api::Version21 def index super render :json => @interfaces, :each_serializer => InterfaceSerializer end def show render :json => @interface, :serializer => InterfaceSerializer end end end end
daviddavis/foretello_api_v21
app/controllers/api/v21/interfaces_controller.rb
Ruby
gpl-3.0
346
/* * Copyright 2015 Jeff Simpson. * * This file is part of the Argo MQTT Transport plugin. * * Argo MQTT Transport plugin is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package ws.argo.responder.plugin.repeater.mqtt; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import ws.argo.plugin.probehandler.ProbeHandlerConfigException; import ws.argo.plugin.probehandler.ProbeHandlerPlugin; import ws.argo.plugin.transport.exception.TransportConfigException; import ws.argo.plugin.transport.exception.TransportException; import ws.argo.plugin.transport.sender.Transport; import ws.argo.probe.Probe; import ws.argo.probe.ProbeSender; import ws.argo.probe.ProbeSenderException; import ws.argo.probe.transport.sender.mqtt.MqttSenderTransport; import ws.argo.wireline.probe.ProbeWrapper; import ws.argo.wireline.probe.XMLSerializer; import ws.argo.wireline.response.ResponseWrapper; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import static java.lang.Integer.parseInt; /** * The MqttRepeaterProbeHandlerPlugin does pretty much what it says. It takes probes * that were handled by the Responder via whatever transports it has configured and then * repeats them out onto a MQTT Sender transport that is separately configured as part * of this probe handler plugin. * * <p>This handler should be used in handling discovery domain gateways. However, if * this repeater resends the probe on the same MQTT channel as it received it, it could * cause very odd behavior. It should NOT resend on a channel that would cause a loop * back or other feedback issues. * * Created by jmsimpson on 10/27/15. */ public class MqttRepeaterProbeHandlerPlugin implements ProbeHandlerPlugin { private static final Logger LOGGER = Logger.getLogger(MqttRepeaterProbeHandlerPlugin.class.getName()); // Properties private ProbeSender _sender; /** * The probe handler will simply resend the probe via the sender it setup with it * initialized. It then will return an empty response back to the Responder as * it isn't actually finding any services to return. * * @param probeWrapper the wireline probe payload to repeat * @return the empty ResponseWrapper */ @Override public ResponseWrapper handleProbeEvent(ProbeWrapper probeWrapper) { LOGGER.fine("MqttRepeaterProbeHandlerPlugin handling probe: " + probeWrapper.asXML()); ResponseWrapper response = new ResponseWrapper(probeWrapper.getProbeId()); Probe probe = new Probe(probeWrapper); try { _sender.sendProbe(probe); } catch (ProbeSenderException e) { LOGGER.log(Level.WARNING, "Unable to repeat probe to MQTT Transport.", e); } return response; } /** * Read in the XML configuration file provided. This should contain the data it needs to * make the MQTT connection and setup the probe sender. * * @param xmlConfigFilename the name of the XML config file * @throws ProbeHandlerConfigException if something goes wrong */ @Override public void initializeWithPropertiesFilename(String xmlConfigFilename) throws ProbeHandlerConfigException { Properties properties; try { properties = processPropertiesFile(xmlConfigFilename); initializeProbeSender(properties); } catch (TransportConfigException e) { throw new ProbeHandlerConfigException("Error reading config [" + xmlConfigFilename + "]", e); } catch (SocketException | UnknownHostException e) { throw new ProbeHandlerConfigException("Error initializing MQTT Repeater", e); } } @Override public String pluginName() { return "MQTT Repeater"; } private void initializeProbeSender(Properties properties) throws UnknownHostException, SocketException, TransportConfigException { Transport transport = new MqttSenderTransport(); NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); String macAddr = ni.getHardwareAddress().toString(); String clientId = "MQTT-Repeater-Client-" + macAddr; properties.put("clientId", clientId); transport.initialize(properties, ""); _sender = new ProbeSender(transport); } /** * Digs through the xml file to get the particular configuration items necessary to * run this responder transport. * * @param xmlConfigFilename the name of the xml configuration file * @return an XMLConfiguration object * @throws TransportConfigException if something goes awry */ private Properties processPropertiesFile(String xmlConfigFilename) throws TransportConfigException { Properties props = new Properties(); XMLConfiguration config; try { config = new XMLConfiguration(xmlConfigFilename); } catch (ConfigurationException e) { throw new TransportConfigException(e.getLocalizedMessage(), e); } props.put("mqttTopic", config.getString("mqttTopic")); props.put("qos", config.getString("qos", "0")); props.put("broker", config.getString("broker")); props.put("clientId", config.getString("clientId", "NO CLIENT ID")); if (config.getString("username") != null) props.put("username", config.getString("username")); if (config.getString("password") != null) props.put("password", config.getString("password")); return props; } }
argoPlugins/mqttTransportPlugin
src/main/java/ws/argo/responder/plugin/repeater/mqtt/MqttRepeaterProbeHandlerPlugin.java
Java
gpl-3.0
6,368
<?php /* * This file is part of Totara LMS * * Copyright (C) 2010-2012 Totara Learning Solutions LTD * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Piers Harding <piers@catalyst.net.nz> * @package totara * @subpackage message */ /** * Displays collaborative features for the current user */ require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); require_once($CFG->dirroot.'/totara/reportbuilder/lib.php'); // initialise jquery requirements require_once($CFG->dirroot.'/totara/core/js/lib/setup.php'); require_login(); global $SESSION,$USER; $format = optional_param('format', '',PARAM_TEXT); //export format // default to current user $id = $USER->id; $context = context_system::instance(); $PAGE->set_context($context); $PAGE->set_url('/totara/message/tasks.php'); $PAGE->set_pagelayout('noblocks'); // users can only view their own and their staff's pages // or if they are an admin if (($USER->id != $id && !totara_is_manager($id) && !has_capability('totara/message:viewallmessages',$context))) { print_error('youcannotview', 'totara_message'); } $strheading = get_string('tasks', 'totara_message'); $shortname = 'tasks'; $data = array( 'userid' => $id, ); if (!$report = reportbuilder_get_embedded_report($shortname, $data)) { print_error('error:couldnotgenerateembeddedreport', 'totara_reportbuilder'); } $report->defaultsortcolumn = 'message_values_sent'; $report->defaultsortorder = 3; if ($format!='') { add_to_log(SITEID, 'reportbuilder', 'export report', 'report.php?id='. $report->_id, $report->fullname); $report->export_data($format); die; } add_to_log(SITEID, 'reportbuilder', 'view report', 'report.php?id='. $report->_id, $report->fullname); $report->include_js(); $PAGE->requires->js_init_call('M.totara_message.init'); /// /// Display the page /// $PAGE->navbar->add($strheading); $PAGE->set_title($strheading); $PAGE->set_button($report->edit_button()); $PAGE->set_heading($strheading); $output = $PAGE->get_renderer('totara_reportbuilder'); echo $output->header(); echo $output->heading($strheading, 1); echo html_writer::tag('p', html_writer::link("{$CFG->wwwroot}/my/", "<< " . get_string('mylearning', 'totara_core'))); // display table here $fullname = $report->fullname; $countfiltered = $report->get_filtered_count(); $countall = $report->get_full_count(); // display heading including filtering stats if ($countfiltered == $countall) { echo $output->heading("$countall ".get_string('records', 'totara_reportbuilder')); } else { echo $output->heading("$countfiltered/$countall".get_string("recordsshown", "totara_plan")); } if (empty($report->description)) { $report->description = get_string('task_description', 'totara_message'); } echo $output->print_description($report->description, $report->_id); $report->display_search(); $PAGE->requires->string_for_js('reviewitems', 'block_totara_alerts'); $PAGE->requires->js_init_call('M.totara_message.dismiss_input_toggle'); if ($countfiltered > 0) { echo $output->showhide_button($report->_id, $report->shortname); echo html_writer::start_tag('form', array('id' => 'totara_messages', 'name' => 'totara_messages', 'action' => new moodle_url('/totara/message/action.php'), 'method' => 'post')); $report->display_table(); echo totara_message_action_button('dismiss'); echo totara_message_action_button('accept'); echo totara_message_action_button('reject'); $out = $output->box_start('generalbox', 'totara_message_actions'); $out .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'returnto', 'value' => $FULLME)); $out .= html_writer::start_tag('center'); $tab = new html_table(); $tab->attributes = array('class', 'fullwidth'); $dismisslink = html_writer::empty_tag('input', array('type' => 'submit', 'name' => 'dismiss', 'id' => 'totara-dismiss', 'disabled' => 'true', 'value' => get_string('dismiss', 'totara_message'), 'style' => 'display:none;')). html_writer::tag('noscript', get_string('noscript', 'totara_message')); $tab->data[] = new html_table_row(array(get_string('withselected', 'totara_message'), $dismisslink)); $out .= html_writer::table($tab); $out .= html_writer::end_tag('center'); $out .= $output->box_end(); echo $out; echo html_writer::end_tag('form'); // export button $output->export_select($report->_id); echo totara_message_checkbox_all_none(); } echo $output->footer(); ?>
danielbonetto/twig_MVC
totara/message/tasks.php
PHP
gpl-3.0
5,091
/******************************************************************** * Tasmota App manager * * To use: `import tapp` * *******************************************************************/ #include "be_constobj.h" /******************************************************************** ** Solidified function: init ********************************************************************/ be_local_closure(Tapp_init, /* name */ be_nested_proto( 4, /* nstack */ 1, /* argc */ 0, /* varg */ 0, /* has upvals */ NULL, /* no upvals */ 0, /* has sup protos */ NULL, /* no sub protos */ 1, /* has constants */ ( &(const bvalue[ 2]) { /* constants */ /* K0 */ be_nested_str_literal("tasmota"), /* K1 */ be_nested_str_literal("add_driver"), }), (be_nested_const_str("init", 380752755, 4)), ((bstring*) &be_const_str_input), ( &(const binstruction[ 5]) { /* code */ 0xB8060000, // 0000 GETNGBL R1 K0 0x8C040301, // 0001 GETMET R1 R1 K1 0x5C0C0000, // 0002 MOVE R3 R0 0x7C040400, // 0003 CALL R1 2 0x80000000, // 0004 RET 0 }) ) ); /*******************************************************************/ /******************************************************************** ** Solidified function: autoexec ********************************************************************/ be_local_closure(Tapp_autoexec, /* name */ be_nested_proto( 12, /* nstack */ 1, /* argc */ 0, /* varg */ 0, /* has upvals */ NULL, /* no upvals */ 0, /* has sup protos */ NULL, /* no sub protos */ 1, /* has constants */ ( &(const bvalue[15]) { /* constants */ /* K0 */ be_nested_str_literal("path"), /* K1 */ be_nested_str_literal("string"), /* K2 */ be_nested_str_literal("listdir"), /* K3 */ be_nested_str_literal("/"), /* K4 */ be_nested_str_literal("find"), /* K5 */ be_nested_str_literal(".tapp"), /* K6 */ be_const_int(0), /* K7 */ be_nested_str_literal("tasmota"), /* K8 */ be_nested_str_literal("log"), /* K9 */ be_nested_str_literal("format"), /* K10 */ be_nested_str_literal("TAP: found Tasmota App '%s'"), /* K11 */ be_const_int(2), /* K12 */ be_nested_str_literal("load"), /* K13 */ be_nested_str_literal("#autoexec.be"), /* K14 */ be_nested_str_literal("stop_iteration"), }), (be_nested_const_str("autoexec", -618105405, 8)), ((bstring*) &be_const_str_input), ( &(const binstruction[34]) { /* code */ 0xA4060000, // 0000 IMPORT R1 K0 0xA40A0200, // 0001 IMPORT R2 K1 0x8C0C0302, // 0002 GETMET R3 R1 K2 0x58140003, // 0003 LDCONST R5 K3 0x7C0C0400, // 0004 CALL R3 2 0x60100010, // 0005 GETGBL R4 G16 0x5C140600, // 0006 MOVE R5 R3 0x7C100200, // 0007 CALL R4 1 0xA8020014, // 0008 EXBLK 0 #001E 0x5C140800, // 0009 MOVE R5 R4 0x7C140000, // 000A CALL R5 0 0x8C180504, // 000B GETMET R6 R2 K4 0x5C200A00, // 000C MOVE R8 R5 0x58240005, // 000D LDCONST R9 K5 0x7C180600, // 000E CALL R6 3 0x24180D06, // 000F GT R6 R6 K6 0x781A000B, // 0010 JMPF R6 #001D 0xB81A0E00, // 0011 GETNGBL R6 K7 0x8C180D08, // 0012 GETMET R6 R6 K8 0x8C200509, // 0013 GETMET R8 R2 K9 0x5828000A, // 0014 LDCONST R10 K10 0x5C2C0A00, // 0015 MOVE R11 R5 0x7C200600, // 0016 CALL R8 3 0x5824000B, // 0017 LDCONST R9 K11 0x7C180600, // 0018 CALL R6 3 0xB81A0E00, // 0019 GETNGBL R6 K7 0x8C180D0C, // 001A GETMET R6 R6 K12 0x00200B0D, // 001B ADD R8 R5 K13 0x7C180400, // 001C CALL R6 2 0x7001FFEA, // 001D JMP #0009 0x5810000E, // 001E LDCONST R4 K14 0xAC100200, // 001F CATCH R4 1 0 0xB0080000, // 0020 RAISE 2 R0 R0 0x80000000, // 0021 RET 0 }) ) ); /*******************************************************************/ /******************************************************************** ** Solidified class: Tapp ********************************************************************/ be_local_class(Tapp, 0, NULL, be_nested_map(2, ( (struct bmapnode*) &(const bmapnode[]) { { be_nested_key("autoexec", -618105405, 8, -1), be_const_closure(Tapp_autoexec_closure) }, { be_nested_key("init", 380752755, 4, 0), be_const_closure(Tapp_init_closure) }, })), be_str_literal("Tapp") ); /******************************************************************** ** Solidified function: _anonymous_ ********************************************************************/ be_local_closure(tapp__anonymous_, /* name */ be_nested_proto( 3, /* nstack */ 1, /* argc */ 0, /* varg */ 0, /* has upvals */ NULL, /* no upvals */ 0, /* has sup protos */ NULL, /* no sub protos */ 1, /* has constants */ ( &(const bvalue[ 1]) { /* constants */ /* K0 */ be_const_class(be_class_Tapp), }), (be_nested_const_str("_anonymous_", 1957281476, 11)), ((bstring*) &be_const_str_input), ( &(const binstruction[ 5]) { /* code */ 0x58040000, // 0000 LDCONST R1 K0 0xB4000000, // 0001 CLASS K0 0x5C080200, // 0002 MOVE R2 R1 0x7C080000, // 0003 CALL R2 0 0x80040400, // 0004 RET 1 R2 }) ) ); /*******************************************************************/ /******************************************************************** ** Solidified module: tapp ********************************************************************/ be_local_module(tapp, "tapp", be_nested_map(1, ( (struct bmapnode*) &(const bmapnode[]) { { be_nested_key("init", 380752755, 4, -1), be_const_closure(tapp__anonymous__closure) }, })) ); BE_EXPORT_VARIABLE be_define_const_native_module(tapp); /********************************************************************/
stefanbode/Sonoff-Tasmota
lib/libesp32/Berry/default/be_tapp_lib.c
C
gpl-3.0
6,627
/* -------------------------------------------------------------------------- * feeds list * -------------------------------------------------------------------------- */ #feeds div { margin: 0; padding: 0; font-size: 10px; font-family: sans; } #feeds div.item { padding: 2px 0; border-bottom: 1px dotted grey; } #feeds div.item:hover { background-color: #ddd; } #feeds div.item > span { display: inline-block; vertical-align: middle; } #feeds div.folder { background-color: #eee; } #feeds div.folder > span.icon:first-child { cursor: pointer; border-right: 1px dotted black; } #feeds div.folder > span.info { text-align: center; } #feeds div.item > span.icon { width: 16px; height: 16px; } #feeds div.item > span.fav { background-size: 16px 16px; background-repeat: no-repeat; } #feeds div.item > .info { float: right; } #feeds div.item.unread > .name { font-weight: bold; } #feeds div.item > .purge { cursor: pointer; } #feeds span.ui-icon { border-radius: 16px; } #feeds span.ui-icon-circle-minus { background-color: red; } #feeds span.ui-icon-circle-check { background-color: lime; } #feeds div.item.selected { background-color: #bbb; } #feeds div.item.disabled { background-color: #ffc; } #feeds div.item.root { position: absolute; width: 100%; left: 0; top: 0; background-color: #eee; border-bottom: 1px solid black; } #feeds div.item.root span.icon { border: 0; border-left: 1px solid black; text-align: center; } #feeds div.folder_contents { margin-left: 16px; border-left: 1px dotted grey; } #feeds div.folder_contents:hover { border-left: 1px solid black; } /* -------------------------------------------------------------------------- * items list * -------------------------------------------------------------------------- */ #items div { margin: 0; padding: 0; font-size: 10px; font-family: sans; } #items select { font-size: 10px; font-weight: bold; } #items div.item { padding: 2px 0; border-bottom: 1px dotted grey; } #items div.item:hover { background-color: #ddd; } #items div.item.selected { background-color: #bbb; border: 2px inset black; } #items div.item > span { display: inline-block; vertical-align: middle; } #items div.item > span.icon { width: 16px; height: 16px; background-repeat: no-repeat; text-align: center; } #items div.item > span.ui-icon { border-right: 1px dotted grey; } #items div.item > span.title { width: 70%; height: 12px; overflow: hidden; } #items div.item > span.fav { background-size: 16px 16px; } #items div.item > span.icon.kept, #items div.item > span.icon.read { cursor: pointer; } #items div.item > .info { float: right; } #items div.item.unread .title { font-weight: bold; } #items div.item.kept { background-color: #fdd; } #items div.item.root { position: absolute; width: 98%; left: 0; top: 0; background-color: #eee; border-bottom: 1px solid black; } #items div.item.root span.icon { border: 0; border-right: 1px solid black; text-align: center; } #items div.item.root span.info.icon { border: 0; border-left: 1px solid black; cursor: pointer; } #items div.item.root span.mode { font-weight: bold; font-style: italic; } /* -------------------------------------------------------------------------- * item details, linear view * -------------------------------------------------------------------------- */ #item { font-size: 14px; font-family: sans; } #item hr { border: 0 none; height: 1px; background-color: grey; } #item div { margin: 0; padding: 0; } #item div.item { padding: 2px 0; border-bottom: 1px dotted grey; } #item div.item span, #item span.ui-icon { display: inline-block; vertical-align: middle; } #item div.item > span.icon { width: 16px; height: 16px; background-repeat: no-repeat; text-align: center; } #item div.item > span.ui-icon { border-right: 1px solid black; } #item div.item > span.fav { background-size: 16px 16px; } #item div.item span.icon.kept, #item div.item span.icon.read, #item div.item span.icon.cmt, #item div.item span.icon.edit { cursor: pointer; } #item div.item > .info { float: right; } #item div.item.root { position: absolute; width: 98%; left: 0; top: 0; background-color: #eee; border-bottom: 1px solid black; } #item div.comment span { font-style: italic; } #item .content { display: inline-block; } #item pre.extra_info { color: grey; font-size: small; } #item .edit_content { display: none; } #item .edit_content textarea { width: 100%; height: 15em; } #item div.linear_item { border-bottom: 3px solid black; } #item div.linear_item.kept { background-color: #fdd; } #item div.linear_item.unread > div.root a { font-weight: bold; } #item div.linear_item > div.root { position: relative; } #item div.linear_item.inline_item { float: left; width: 200px; height: 350px; overflow: hidden; font-size: 10px; border: 1px outset silver; } #item div.linear_item.inline_item div.root span.date, #item div.linear_item.inline_item div.root span.ui-icon.edit, #item div.linear_item.inline_item div.comment { display: none; } #item div.linear_item.inline_item div.root { width: 100% !important; } #item div.linear_item.inline_item div.root a { font-size: 12px; font-weight: inherit; } #item div.log_buffer { font-size: 10px; font-family: monospace; } #item div.log_buffer .ui-icon { vertical-align: bottom; } #item div.log_buffer .type_D { background-color: #ccf; } #item div.log_buffer .type_I { background-color: #9f9; } #item div.log_buffer .type_W { background-color: #f96; } #item div.log_buffer .type_E { background-color: #f66; } #item div.log_buffer div:hover { background-color: #eef; border-left: 2px solid black; padding-left: 2px; } #item table.help { margin-left: 1em; border: 1px solid black; border-collapse: collapse; } #item table.help td, #item table.help th { padding: 0.3em; border: 1px solid black; } #item table.help.keyb_shortcuts tr td:first-child { font-weight: bold; } #item a { color: blue; } #item a:hover { box-shadow: 0 0 2px lime; border-radius: 2px; }
acavalin/rrss
public/css/layouts/spartan.css
CSS
gpl-3.0
6,133
package Finance::Bank::SentinelBenefits::Csv401kConverter; $Finance::Bank::SentinelBenefits::Csv401kConverter::VERSION = '1.0'; use Modern::Perl; use DateTime; use DateTime::Format::Flexible; =head1 NAME Finance::Bank::SentinelBenefits::Csv401kConverter - Takes a series of lines in Sentinel Benefits format and writes them out as QIF files, subject to the symbol mappings specified. =head1 VERSION version 1.0 =head1 SYNOPSIS =head1 DESCRIPTION This module takes a CSV file in the format "provided" i.e. copy-pasted from the Sentinel Benefits website. It also takes a description->symbol mapping, and one or two filenames to write out. The first file is a list of the transactions in QIF format. The second file, if provided, is a list of the company matches with the signs reversed, which can be useful if you want to keep unvested company contributions from showing up in your net worth calculations. =cut use Moose; use MooseX::Method::Signatures; use MooseX::StrictConstructor; use Finance::Bank::SentinelBenefits::Csv401kConverter::SymbolMap; use Finance::Bank::SentinelBenefits::Csv401kConverter::LineParser; use Finance::Bank::SentinelBenefits::Csv401kConverter::QifWriter; use Finance::Bank::SentinelBenefits::Csv401kConverter::SideReverser; =head1 Accessors =head2 $p->trade_input() A file handle that supplies the trade data =cut has 'trade_input' => ( is => 'ro', isa => 'FileHandle', required => 1, ); has 'primary_output_file' => ( is => 'ro', isa => 'Str', required => 1, ); has 'symbol_map' => ( is => 'ro', isa => 'Finance::Bank::SentinelBenefits::Csv401kConverter::SymbolMap', required => 1, ); =head2 $p->trade_date() Used if you wish to override the trade date specified in the input file, or if no trade date is available in the files. If no dates are specified here or in the files, an exception will be thrown. =cut has 'trade_date' => ( is => 'ro', isa => 'DateTime', required => 0, ); has 'account' => ( is => 'ro', isa => 'Str', required => 1, ); has 'companymatch_account' => ( is => 'ro', isa => 'Str', required => 0, ); has '_side_reverser' => ( is => 'ro', isa => 'Finance::Bank::SentinelBenefits::Csv401kConverter::SideReverser', required => 0, default => sub { Finance::Bank::SentinelBenefits::Csv401kConverter::SideReverser->new(); } ); method write_output(){ my $parser = Finance::Bank::SentinelBenefits::Csv401kConverter::LineParser->new ( symbol_map => $self->symbol_map() ); my $writer = Finance::Bank::SentinelBenefits::Csv401kConverter::QifWriter->new ( output_file => ">" . $self->primary_output_file(), account => $self->account(), ); my $fh = $self->trade_input(); my @lines; my $date = $self->trade_date(); while(<$fh>){ #this line is a date and there is no override, parse it as such if(9 == length && (not defined $self->trade_date()) ){ $date = DateTime::Format::Flexible->parse_datetime($_); # warn "date is $date"; }else{ my $line = $parser->parse_line($_, $date); if (defined $line) { $writer->output_line($line); push @lines, $line; } } } $writer->close(); if($self->companymatch_account()) { my $cm_writer = Finance::Bank::SentinelBenefits::Csv401kConverter::QifWriter->new ( output_file => ">>" . $self->primary_output_file(), account => $self->companymatch_account(), ); foreach my $line (@lines) { if($line->source() eq 'Match'){ my $cm_line = Finance::Bank::SentinelBenefits::Csv401kConverter::Line->new ( date => $line->date(), symbol => $line->symbol(), memo => $line->memo(), quantity => $line->quantity(), price => $line->price(), total => $line->total(), source => $line->source(), side => $self->_side_reverser->flip($line->side()), ); $cm_writer->output_line($cm_line); } } $cm_writer->close(); } } no Moose; __PACKAGE__->meta->make_immutable; 1; # Copyright 2009-2011 David Solimano # This file is part of Finance::Bank::SentinelBenefits::Csv401kConverter # Finance::Bank::SentinelBenefits::Csv401kConverter is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Finance::Bank::SentinelBenefits::Csv401kConverter is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Finance::Bank::SentinelBenefits::Csv401kConverter. If not, see <http://www.gnu.org/licenses/>.
gitpan/Finance-Bank-SentinelBenefits-Csv401kConverter
lib/Finance/Bank/SentinelBenefits/Csv401kConverter.pm
Perl
gpl-3.0
5,037
<?php //TODO EM_Events is currently static, better we make this non-static so we can loop sets of events, and standardize with other objects. /** * Use this class to query and manipulate sets of events. If dealing with more than one event, you probably want to use this class in some way. * */ class EM_Events extends EM_Object { /** * Returns an array of EM_Events that match the given specs in the argument, or returns a list of future evetnts in future * (see EM_Events::get_default_search() ) for explanation of possible search array values. You can also supply a numeric array * containing the ids of the events you'd like to obtain * * @param array $args * @return EM_Event array() */ public static function get( $args = array(), $count=false ) { global $wpdb; $events_table = EM_EVENTS_TABLE; $locations_table = EM_LOCATIONS_TABLE; //Quick version, we can accept an array of IDs, which is easy to retrieve if( self::array_is_numeric($args) ){ //Array of numbers, assume they are event IDs to retreive //We can just get all the events here and return them $events = array(); foreach($args as $event_id){ $events[$event_id] = em_get_event($event_id); } return apply_filters('em_events_get', $events, $args); } //We assume it's either an empty array or array of search arguments to merge with defaults $args = self::get_default_search($args); $limit = ( $args['limit'] && is_numeric($args['limit'])) ? "LIMIT {$args['limit']}" : ''; $offset = ( $limit != "" && is_numeric($args['offset']) ) ? "OFFSET {$args['offset']}" : ''; $groupby_sql = array(); //Get the default conditions $conditions = self::build_sql_conditions($args); //Put it all together $where = ( count($conditions) > 0 ) ? " WHERE " . implode ( " AND ", $conditions ):''; //Get ordering instructions $EM_Event = new EM_Event(); $EM_Location = new EM_Location(); $orderby = self::build_sql_orderby($args, array_keys(array_merge($EM_Event->fields, $EM_Location->fields)), get_option('dbem_events_default_order')); //Now, build orderby sql $orderby_sql = ( count($orderby) > 0 ) ? 'ORDER BY '. implode(', ', $orderby) : ''; //Create the SQL statement and execute if( !$count && $args['array'] ){ $selectors_array = array(); foreach( array_keys($EM_Event->fields) as $field_selector){ $selectors_array[] = $events_table.'.'.$field_selector; } $selectors = implode(',', $selectors_array); }elseif( EM_MS_GLOBAL ){ $selectors = $events_table.'.post_id, '.$events_table.'.blog_id'; $groupby_sql[] = $events_table.'.post_id, '. $events_table.'.blog_id'; }else{ $selectors = $events_table.'.post_id'; $groupby_sql[] = $events_table.'.post_id'; //prevent duplicates showing in lists } if( $count ){ $selectors = 'SQL_CALC_FOUND_ROWS *'; $limit = 'LIMIT 1'; $offset = 'OFFSET 0'; } //add group_by if needed $groupby_sql = !empty($groupby_sql) && is_array($groupby_sql) ? 'GROUP BY '.implode(',', $groupby_sql):''; $sql = apply_filters('em_events_get_sql'," SELECT $selectors FROM $events_table LEFT JOIN $locations_table ON {$locations_table}.location_id={$events_table}.location_id $where $groupby_sql $orderby_sql $limit $offset ", $args); //If we're only counting results, return the number of results if( $count ){ $wpdb->query($sql); return apply_filters('em_events_get_count', $wpdb->get_var('SELECT FOUND_ROWS()'), $args); } $results = $wpdb->get_results( $sql, ARRAY_A); //If we want results directly in an array, why not have a shortcut here? if( $args['array'] == true ){ return apply_filters('em_events_get_array',$results, $args); } //Make returned results EM_Event objects $results = (is_array($results)) ? $results:array(); $events = array(); if( EM_MS_GLOBAL ){ foreach ( $results as $event ){ $events[] = em_get_event($event['post_id'], $event['blog_id']); } }else{ foreach ( $results as $event ){ $events[] = em_get_event($event['post_id'], 'post_id'); } } return apply_filters('em_events_get', $events, $args); } /** * Returns the number of events on a given date * @param $date * @return int */ public static function count_date($date){ global $wpdb; $table_name = EM_EVENTS_TABLE; $sql = "SELECT COUNT(*) FROM $table_name WHERE (event_start_date like '$date') OR (event_start_date <= '$date' AND event_end_date >= '$date');"; return apply_filters('em_events_count_date', $wpdb->get_var($sql)); } public static function count( $args = array() ){ return apply_filters('em_events_count', self::get($args, true), $args); } /** * Will delete given an array of event_ids or EM_Event objects * @param unknown_type $id_array */ public static function delete( $array ){ global $wpdb; //Detect array type and generate SQL for event IDs $results = array(); if( !empty($array) && @get_class(current($array)) != 'EM_Event' ){ $events = self::get($array); }else{ $events = $array; } $event_ids = array(); foreach ($events as $EM_Event){ $event_ids[] = $EM_Event->event_id; $results[] = $EM_Event->delete(); } //TODO add better error feedback on events delete fails return apply_filters('em_events_delete', in_array(false, $results), $event_ids); } /** * Output a set of matched of events. You can pass on an array of EM_Events as well, in this event you can pass args in second param. * Note that you can pass a 'pagination' boolean attribute to enable pagination, default is enabled (true). * @param array $args * @param array $secondary_args * @return string */ public static function output( $args ){ global $EM_Event; $EM_Event_old = $EM_Event; //When looping, we can replace EM_Event global with the current event in the loop //get page number if passed on by request (still needs pagination enabled to have effect) $page_queryvar = !empty($args['page_queryvar']) ? $args['page_queryvar'] : 'pno'; if( !empty($args['pagination']) && !array_key_exists('page',$args) && !empty($_REQUEST[$page_queryvar]) && is_numeric($_REQUEST[$page_queryvar]) ){ $page = $args['page'] = $_REQUEST[$page_queryvar]; } //Can be either an array for the get search or an array of EM_Event objects if( is_object(current($args)) && get_class((current($args))) == 'EM_Event' ){ $func_args = func_get_args(); $events = $func_args[0]; $args = (!empty($func_args[1]) && is_array($func_args[1])) ? $func_args[1] : array(); $args = apply_filters('em_events_output_args', self::get_default_search($args), $events); $limit = ( !empty($args['limit']) && is_numeric($args['limit']) ) ? $args['limit']:false; $offset = ( !empty($args['offset']) && is_numeric($args['offset']) ) ? $args['offset']:0; $page = ( !empty($args['page']) && is_numeric($args['page']) ) ? $args['page']:1; $events_count = count($events); }else{ //Firstly, let's check for a limit/offset here, because if there is we need to remove it and manually do this $args = apply_filters('em_events_output_args', self::get_default_search($args)); $limit = ( !empty($args['limit']) && is_numeric($args['limit']) ) ? $args['limit']:false; $offset = ( !empty($args['offset']) && is_numeric($args['offset']) ) ? $args['offset']:0; $page = ( !empty($args['page']) && is_numeric($args['page']) ) ? $args['page']:1; $args_count = $args; $args_count['limit'] = false; $args_count['offset'] = false; $args_count['page'] = false; $events_count = self::count($args_count); $events = self::get( $args ); } //What format shall we output this to, or use default $format = ( empty($args['format']) ) ? get_option( 'dbem_event_list_item_format' ) : $args['format'] ; $output = ""; $events = apply_filters('em_events_output_events', $events); if ( $events_count > 0 ) { foreach ( $events as $EM_Event ) { $output .= $EM_Event->output($format); } //Add headers and footers to output if( $format == get_option( 'dbem_event_list_item_format' ) ){ //we're using the default format, so if a custom format header or footer is supplied, we can override it, if not use the default $format_header = empty($args['format_header']) ? get_option('dbem_event_list_item_format_header') : $args['format_header']; $format_footer = empty($args['format_footer']) ? get_option('dbem_event_list_item_format_footer') : $args['format_footer']; }else{ //we're using a custom format, so if a header or footer isn't specifically supplied we assume it's blank $format_header = !empty($args['format_header']) ? $args['format_header'] : '' ; $format_footer = !empty($args['format_footer']) ? $args['format_footer'] : '' ; } $output = $format_header . $output . $format_footer; //Pagination (if needed/requested) if( !empty($args['pagination']) && !empty($limit) && $events_count > $limit ){ $output .= self::get_pagination_links($args, $events_count); } } else { $output = get_option ( 'dbem_no_events_message' ); } //TODO check if reference is ok when restoring object, due to changes in php5 v 4 $EM_Event = $EM_Event_old; $output = apply_filters('em_events_output', $output, $events, $args); return $output; } /** * Generate a grouped list of events by year, month, week or day. * * There is a nuance with this function, long_events won't work unless you add a limit of 0. The reason is because this won't work with pagination, due to the fact * that you need to alter the event total count to reflect each time an event is displayed in a time range. e.g. if an event lasts 2 days and it's daily grouping, * then that event would count as 2 events for pagination purposes. For that you need to count every single event and calculate date range etc. which is too resource * heavy and not scalabale, therefore we've added this limitation. * * @since 5.4.4.2 * @param array $args * @return string */ public static function output_grouped( $args = array() ){ //Reset some args to include pagination for if pagination is requested. $args['limit'] = isset($args['limit']) ? $args['limit'] : get_option('dbem_events_default_limit'); $args['page'] = (!empty($args['page']) && is_numeric($args['page']) )? $args['page'] : 1; $args['page'] = (!empty($args['pagination']) && !empty($_REQUEST['pno']) && is_numeric($_REQUEST['pno']) )? $_REQUEST['pno'] : $args['page']; $args['offset'] = ($args['page']-1) * $args['limit']; $args['orderby'] = 'event_start_date,event_start_time,event_name'; // must override this to display events in right cronology. $args['mode'] = !empty($args['mode']) ? $args['mode'] : get_option('dbem_event_list_groupby'); $args['header_format'] = !empty($args['header_format']) ? $args['header_format'] : get_option('dbem_event_list_groupby_header_format', '<h2>#s</h2>'); //Reset some vars for counting events and displaying set arrays of events $atts = (array) $args; $atts['pagination'] = false; $atts['limit'] = false; $atts['page'] = false; $atts['offset'] = false; //decide what form of dates to show $events_count = self::count($atts); ob_start(); if( $events_count > 0 ){ $EM_Events = self::get($args); switch ( $args['mode'] ){ case 'yearly': //go through the events and put them into a monthly array $format = (!empty($args['date_format'])) ? $args['date_format']:'Y'; $events_dates = array(); foreach($EM_Events as $EM_Event){ /* @var $EM_Event EM_Event */ $year = date('Y',$EM_Event->start); $events_dates[$year][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_year = $year + 1; $year_end = date('Y', $EM_Event->end); while( $next_year <= $year_end ){ $events_dates[$next_year][] = $EM_Event; $next_year = $next_year + 1; } } } foreach ($events_dates as $year => $events){ echo str_replace('#s', date_i18n($format,strtotime($year.'-01-01', current_time('timestamp'))), $args['header_format']); echo self::output($events, $atts); } break; case 'monthly': //go through the events and put them into a monthly array $format = (!empty($args['date_format'])) ? $args['date_format']:'M Y'; $events_dates = array(); foreach($EM_Events as $EM_Event){ $events_dates[date('Y-m-'.'01', $EM_Event->start)][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_month = strtotime("+1 Month", $EM_Event->start); while( $next_month <= $EM_Event->end ){ $events_dates[date('Y-m-'.'01',$next_month)][] = $EM_Event; $next_month = strtotime("+1 Month", $next_month); } } } foreach ($events_dates as $month => $events){ echo str_replace('#s', date_i18n($format, strtotime($month, current_time('timestamp'))), $args['header_format']); echo self::output($events, $atts); } break; case 'weekly': $format = (!empty($args['date_format'])) ? $args['date_format']:get_option('date_format'); $events_dates = array(); foreach($EM_Events as $EM_Event){ $start_of_week = get_option('start_of_week'); $day_of_week = date('w',$EM_Event->start); $day_of_week = date('w',$EM_Event->start); $offset = $day_of_week - $start_of_week; if($offset<0){ $offset += 7; } $offset = $offset * 60*60*24; //days in seconds $start_day = strtotime($EM_Event->start_date); $events_dates[$start_day - $offset][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $next_week = $start_day - $offset + (86400 * 7); while( $next_week <= $EM_Event->end ){ $events_dates[$next_week][] = $EM_Event; $next_week = $next_week + (86400 * 7); } } } foreach ($events_dates as $event_day_ts => $events){ echo str_replace('#s', date_i18n($format,$event_day_ts). get_option('dbem_dates_separator') .date_i18n($format,$event_day_ts+(60*60*24*6)), $args['header_format']); echo self::output($events, $atts); } break; default: //daily //go through the events and put them into a daily array $format = (!empty($args['date_format'])) ? $args['date_format']:get_option('date_format'); $events_dates = array(); foreach($EM_Events as $EM_Event){ $event_start_date = strtotime($EM_Event->start_date); $events_dates[$event_start_date][] = $EM_Event; //if long events requested, add event to other dates too if( empty($args['limit']) && !empty($args['long_events']) && $EM_Event->event_end_date != $EM_Event->event_start_date ) { $tomorrow = $event_start_date + 86400; while( $tomorrow <= $EM_Event->end ){ $events_dates[$tomorrow][] = $EM_Event; $tomorrow = $tomorrow + 86400; } } } foreach ($events_dates as $event_day_ts => $events){ echo str_replace('#s', date_i18n($format,$event_day_ts), $args['header_format']); echo self::output($events, $atts); } break; } //Show the pagination links (unless there's less than $limit events) if( !empty($args['pagination']) && !empty($args['limit']) && $events_count > $args['limit'] ){ echo self::get_pagination_links($args, $events_count, 'search_events_grouped'); } }else{ echo get_option ( 'dbem_no_events_message' ); } return ob_get_clean(); } public static function get_pagination_links($args, $count, $search_action = 'search_events', $default_args = array()){ //get default args if we're in a search, supply to parent since we can't depend on late static binding until WP requires PHP 5.3 or later if( empty($default_args) && (!empty($args['ajax']) || !empty($_REQUEST['action']) && $_REQUEST['action'] == $search_action) ){ $default_args = self::get_default_search(); $default_args['limit'] = get_option('dbem_events_default_limit'); } return parent::get_pagination_links($args, $count, $search_action, $default_args); } /* (non-PHPdoc) * DEPRECATED - this class should just contain static classes, * @see EM_Object::can_manage() */ function can_manage($event_ids = false , $admin_capability = false, $user_to_check = false ){ global $wpdb; if( current_user_can('edit_others_events') ){ return apply_filters('em_events_can_manage', true, $event_ids); } if( EM_Object::array_is_numeric($event_ids) ){ $condition = implode(" OR event_id=", $event_ids); //we try to find any of these events that don't belong to this user $results = $wpdb->get_var("SELECT COUNT(*) FROM ". EM_EVENTS_TABLE ." WHERE event_owner != '". get_current_user_id() ."' event_id=$condition;"); return apply_filters('em_events_can_manage', ($results == 0), $event_ids); } return apply_filters('em_events_can_manage', false, $event_ids); } public static function get_post_search($args = array(), $filter = false, $request = array(), $accepted_args = array()){ //supply $accepted_args to parent argument since we can't depend on late static binding until WP requires PHP 5.3 or later $accepted_args = !empty($accepted_args) ? $accepted_args : array_keys(self::get_default_search()); return apply_filters('em_events_get_post_search', parent::get_post_search($args, $filter, $request, $accepted_args)); } /* Overrides EM_Object method to apply a filter to result * @see wp-content/plugins/events-manager/classes/EM_Object#build_sql_conditions() */ public static function build_sql_conditions( $args = array() ){ self::$context = EM_POST_TYPE_EVENT; global $wpdb; $conditions = parent::build_sql_conditions($args); if( !empty($args['search']) ){ $like_search = array('event_name',EM_EVENTS_TABLE.'.post_content','location_name','location_address','location_town','location_postcode','location_state','location_country','location_region'); $like_search_string = '%'.$wpdb->esc_like($args['search']).'%'; $like_search_strings = array(); foreach( $like_search as $v ) $like_search_strings[] = $like_search_string; $like_search_sql = "(".implode(" LIKE %s OR ", $like_search). " LIKE %s)"; $conditions['search'] = $wpdb->prepare($like_search_sql, $like_search_strings); } $conditions['status'] = "(`event_status` >= 0 )"; //shows pending & published if not defined if( array_key_exists('status',$args) ){ if( is_numeric($args['status']) ){ $conditions['status'] = "(`event_status`={$args['status']})"; //pending or published }elseif( $args['status'] == 'pending' ){ $conditions['status'] = "(`event_status`=0)"; //pending }elseif( $args['status'] == 'publish' ){ $conditions['status'] = "(`event_status`=1)"; //published }elseif( $args['status'] === null || $args['status'] == 'draft' ){ $conditions['status'] = "(`event_status` IS NULL )"; //show draft items }elseif( $args['status'] == 'trash' ){ $conditions['status'] = "(`event_status` = -1 )"; //show trashed items }elseif( $args['status'] == 'all'){ $conditions['status'] = "(`event_status` >= 0 OR `event_status` IS NULL)"; //search all statuses that aren't trashed }elseif( $args['status'] == 'everything'){ unset($conditions['status']); //search all statuses } } //private events if( empty($args['private']) ){ $conditions['private'] = "(`event_private`=0)"; }elseif( !empty($args['private_only']) ){ $conditions['private_only'] = "(`event_private`=1)"; } if( EM_MS_GLOBAL && !empty($args['blog']) ){ if( is_numeric($args['blog']) ){ if( is_main_site($args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id={$args['blog']} OR ".EM_EVENTS_TABLE.".blog_id IS NULL)"; }else{ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id={$args['blog']})"; } }else{ if( !is_array($args['blog']) && preg_match('/^([\-0-9],?)+$/', $args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id IN ({$args['blog']}) )"; }elseif( is_array($args['blog']) && self::array_is_numeric($args['blog']) ){ $conditions['blog'] = "(".EM_EVENTS_TABLE.".blog_id IN (".implode(',',$args['blog']).") )"; } } } if( $args['bookings'] === 'user' && is_user_logged_in()){ //get bookings of user $EM_Person = new EM_Person(get_current_user_id()); $booking_ids = $EM_Person->get_bookings(true); if( count($booking_ids) > 0 ){ $conditions['bookings'] = "(event_id IN (SELECT event_id FROM ".EM_BOOKINGS_TABLE." WHERE booking_id IN (".implode(',',$booking_ids).")))"; }else{ $conditions['bookings'] = "(event_id = 0)"; } } //post search if( !empty($args['post_id'])){ if( is_array($args['post_id']) ){ $conditions['post_id'] = "(".EM_EVENTS_TABLE.".post_id IN (".implode(',',$args['post_id'])."))"; }else{ $conditions['post_id'] = "(".EM_EVENTS_TABLE.".post_id={$args['post_id']})"; } } //events with or without locations if( !empty($args['has_location']) ){ $conditions['has_location'] = '('.EM_EVENTS_TABLE.'.location_id IS NOT NULL AND '.EM_EVENTS_TABLE.'.location_id != 0)'; }elseif( !empty($args['no_location']) ){ $conditions['no_location'] = '('.EM_EVENTS_TABLE.'.location_id IS NULL OR '.EM_EVENTS_TABLE.'.location_id = 0)'; } return apply_filters( 'em_events_build_sql_conditions', $conditions, $args ); } /* Overrides EM_Object method to apply a filter to result * @see wp-content/plugins/events-manager/classes/EM_Object#build_sql_orderby() */ public static function build_sql_orderby( $args, $accepted_fields, $default_order = 'ASC' ){ self::$context = EM_POST_TYPE_EVENT; $accepted_fields[] = 'event_date_modified'; $accepted_fields[] = 'event_date_created'; return apply_filters( 'em_events_build_sql_orderby', parent::build_sql_orderby($args, $accepted_fields, get_option('dbem_events_default_order')), $args, $accepted_fields, $default_order ); } /* * Adds custom Events search defaults * @param array $array_or_defaults may be the array to override defaults * @param array $array * @return array * @uses EM_Object#get_default_search() */ public static function get_default_search( $array_or_defaults = array(), $array = array() ){ self::$context = EM_POST_TYPE_EVENT; $defaults = array( 'orderby' => get_option('dbem_events_default_orderby'), 'order' => get_option('dbem_events_default_order'), 'bookings' => false, //if set to true, only events with bookings enabled are returned 'status' => 1, //approved events only 'town' => false, 'state' => false, 'country' => false, 'region' => false, 'has_location' => false, 'no_location' => false, 'blog' => get_current_blog_id(), 'private' => current_user_can('read_private_events'), 'private_only' => false, 'post_id' => false ); //sort out whether defaults were supplied or just the array of search values if( empty($array) ){ $array = $array_or_defaults; }else{ $defaults = array_merge($defaults, $array_or_defaults); } //specific functionality if( EM_MS_GLOBAL && (!is_admin() || defined('DOING_AJAX')) ){ if( empty($array['blog']) && is_main_site() && get_site_option('dbem_ms_global_events') ){ $array['blog'] = false; } } if( is_admin() && !defined('DOING_AJAX') ){ //figure out default owning permissions $defaults['owner'] = !current_user_can('edit_others_events') ? get_current_user_id() : false; if( !array_key_exists('status', $array) && current_user_can('edit_others_events') ){ $defaults['status'] = false; //by default, admins see pending and live events } } return apply_filters('em_events_get_default_search', parent::get_default_search($defaults,$array), $array, $defaults); } } ?>
dexxtr/osbb-web-manager
www/wp-content/plugins/events-manager/classes/em-events.php
PHP
gpl-3.0
24,240
/* * Children Immunization Registry System (IRS). Copyright (C) 2011 PATH (www.path.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Author: Tran Trung Hieu * Email: htran282@gmail.com */ package org.hil.core.model; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.GrantedAuthority; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; @Entity @Table(name = "system_account") public class SystemAccount extends AbstractEntity implements Serializable, UserDetails { @Column(name = "account_name", length = 50, unique = true) private String accountName; @Column(name = "password", length = 100) private String password; @Column(name = "expired") private Boolean expired = new Boolean(false); @Column(name = "locked") private Boolean locked = new Boolean(false); @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "system_account_role", joinColumns = { @JoinColumn(name = "id_system_account") }, inverseJoinColumns = @JoinColumn(name = "id_system_role")) private Set<SystemRole> roles = new HashSet<SystemRole>(); public Set<SystemRole> getRoles() { return roles; } public void setRoles(Set<SystemRole> roles) { this.roles = roles; } public void addRole(SystemRole role) { getRoles().add(role); } /** * @return the accountName */ public String getAccountName() { return accountName; } /** * @param accountName the accountName to set */ public void setAccountName(String accountName) { this.accountName = accountName; } @Transient public GrantedAuthority[] getAuthorities() { return roles.toArray(new GrantedAuthority[0]); } @Transient public String getUsername() { return getAccountName(); } @Transient public boolean isAccountNonExpired() { return true; } @Transient public boolean isAccountNonLocked() { return true; } @Transient public boolean isCredentialsNonExpired() { return true; } @Transient public boolean isEnabled() { return true; } public Boolean getExpired() { return expired; } public void setExpired(Boolean expired) { this.expired = expired; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public void setPassword(String password) { this.password = password; } @Transient public String getPassword() { return password; } }
htran282/IRS
src/main/java/org/hil/core/model/SystemAccount.java
Java
gpl-3.0
3,183
// Copyright (c) 2005 - 2015 Settlers Freaks (sf-team at siedler25.org) // // This file is part of Return To The Roots. // // Return To The Roots is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Return To The Roots is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Return To The Roots. If not, see <http://www.gnu.org/licenses/>. #ifndef GAMESERVER_H_ #define GAMESERVER_H_ #pragma once #include "FramesInfo.h" #include "GameMessageInterface.h" #include "GameServerInterface.h" #include "GlobalGameSettings.h" #include "Random.h" #include "helpers/Deleter.h" #include "gameTypes/MapInfo.h" #include "gameTypes/ServerType.h" #include "libutil/src/LANDiscoveryService.h" #include "libutil/src/Singleton.h" #include <boost/interprocess/smart_ptr/unique_ptr.hpp> #include <vector> class AIBase; struct CreateServerInfo; class GameMessage; class GameMessage_GameCommand; class GameServerPlayer; namespace AIEvent { class Base; } class GameServer : public Singleton<GameServer, SingletonPolicies::WithLongevity>, public GameMessageInterface, private GameServerInterface { public: BOOST_STATIC_CONSTEXPR unsigned Longevity = 6; GameServer(); ~GameServer() override; /// "Versucht" den Server zu starten (muss ggf. erst um Erlaubnis beim LobbyClient fragen) bool TryToStart(const CreateServerInfo& csi, const std::string& map_path, const MapType map_type); /// Startet den Server, muss vorher TryToStart aufgerufen werden! bool Start(); void Run(); void Stop(); bool StartGame(); bool StartCountdown(); void CancelCountdown(); void SetPaused(bool paused); bool IsPaused() { return framesinfo.isPaused; } void ToggleAINation(unsigned char playerId); void ToggleAITeam(unsigned char playerId); void ToggleAIColor(unsigned char playerId); void TogglePlayerState(unsigned char playerId); void ChangeGlobalGameSettings(const GlobalGameSettings& ggs) override; /// Removes the lua script for the currently loaded map (only valid in config mode) void RemoveLuaScript(); /// Tauscht Spieler(positionen) bei Savegames in dskHostGame void SwapPlayer(const unsigned char player1, const unsigned char player2); void AIChat(const GameMessage& msg) { SendToAll(msg); } std::string GetGameName() const { return config.gamename; } bool HasPwd() const { return !config.password.empty(); } unsigned short GetPort() const { return config.port; } unsigned GetMaxPlayerCount() const override { return config.playercount; } bool IsRunning() const override { return status != SS_STOPPED; } const GlobalGameSettings& GetGGS() const override { return ggs_; } GameServerInterface& GetInterface() { return *this; } private: /// Lässt einen Spieler wechseln (nur zu Debugzwecken) void ChangePlayer(const unsigned char old_id, const unsigned char new_id); void SendToAll(const GameMessage& msg) override; void KickPlayer(unsigned char playerId, unsigned char cause, unsigned short param); void KickPlayer(unsigned playerIdx) override; void ClientWatchDog(); void WaitForClients(); void FillPlayerQueues(); /// Sendet ein NC-Paket ohne Befehle void SendNothingNC(const unsigned& id); unsigned GetFilledSlots() const; /// Notifies listeners (e.g. Lobby) that the game status has changed (e.g player count) void AnnounceStatusChange() override; void OnGameMessage(const GameMessage_Pong& msg) override; void OnGameMessage(const GameMessage_Server_Type& msg) override; void OnGameMessage(const GameMessage_Server_Password& msg) override; void OnGameMessage(const GameMessage_Server_Chat& msg) override; void OnGameMessage(const GameMessage_System_Chat& msg) override; void OnGameMessage(const GameMessage_Player_Name& msg) override; void OnGameMessage(const GameMessage_Player_Set_Nation& msg) override; void OnGameMessage(const GameMessage_Player_Set_Team& msg) override; void OnGameMessage(const GameMessage_Player_Set_Color& msg) override; void OnGameMessage(const GameMessage_Player_Ready& msg) override; void OnGameMessage(const GameMessage_Player_Swap& msg) override; void OnGameMessage(const GameMessage_Map_Checksum& msg) override; void OnGameMessage(const GameMessage_GameCommand& msg) override; void OnGameMessage(const GameMessage_Server_Speed& msg) override; void OnGameMessage(const GameMessage_SendAsyncLog& msg) override; /// Sets the color of this player to the given color, if it is unique, or to the next free one if not /// Sends a notification to all players if the color was changed void CheckAndSetColor(unsigned playerIdx, unsigned newColor) override; /// Handles advancing of GFs, actions of AI and potentially the NWF void ExecuteGameFrame(); void RunGF(bool isNWF); void ExecuteNWF(const unsigned currentTime); void CheckAndKickLaggingPlayer(const unsigned char playerIdx); unsigned char GetLaggingPlayer() const; JoinPlayerInfo& GetJoinPlayer(unsigned playerIdx) override; private: enum ServerState { SS_STOPPED = 0, SS_CREATING_LOBBY, // Creating game lobby (Call Start() next) SS_CONFIG, SS_GAME } status; FramesInfo framesinfo; unsigned currentGF; class ServerConfig { public: ServerConfig(); void Clear(); ServerType servertype; unsigned playercount; std::string gamename; std::string password; unsigned short port; bool ipv6; bool use_upnp; } config; MapInfo mapinfo; Socket serversocket; std::vector<GameServerPlayer> players; GlobalGameSettings ggs_; /// der Spielstartcountdown class CountDown { bool isActive; unsigned remainingSecs; unsigned lasttime; public: CountDown(); /// Starts a countdown at curTime of timeInSec seconds void Start(unsigned timeInSec, unsigned curTime); void Stop(); /// Updates the state and returns true on change. Stops 1s after remainingSecs reached zero bool Update(unsigned curTime); bool IsActive() const { return isActive; } unsigned GetRemainingSecs() const { return remainingSecs; } } countdown; /// Alle KI-Spieler und ihre Daten (NULL, falls ein solcher Spieler nicht existiert) std::vector<AIBase*> ai_players; /// AsyncLogs of two async players int async_player1, async_player2; bool async_player1_done, async_player2_done; std::vector<RandomEntry> async_player1_log, async_player2_log; LANDiscoveryService lanAnnouncer; public: AIBase* GetAIPlayer(unsigned playerID) { return ai_players[playerID]; } unsigned skiptogf; }; /////////////////////////////////////////////////////////////////////////////// // Makros / Defines #define GAMESERVER GameServer::inst() #endif
frin/s25client
src/GameServer.h
C
gpl-3.0
7,585
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ispd.motor.filas; import ispd.motor.filas.servidores.CS_Comunicacao; import ispd.motor.filas.servidores.implementacao.CS_Internet; import ispd.motor.filas.servidores.implementacao.CS_Maquina; import ispd.motor.filas.servidores.CS_Processamento; import ispd.motor.filas.servidores.implementacao.CS_MaquinaCloud; import ispd.motor.filas.servidores.implementacao.CS_VirtualMac; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Possui listas de todos os icones presentes no modelo utilizado para buscas e * para o motor de simulação * * @author denison_usuario */ public class RedeDeFilasCloud extends RedeDeFilas{ /** * Todos os mestres existentes no sistema incluindo o front-node dos * clusters */ private List<CS_Processamento> mestres; /** * Todas as máquinas que não são mestres */ private List<CS_MaquinaCloud> maquinasCloud; /** * Todas as conexões */ private List<CS_Comunicacao> links; /** * Todos icones de internet do modelo */ private List<CS_Internet> internets; /** * Mantem lista dos usuarios da rede de filas */ private List<String> usuarios; /** * Mantem a lista de máquinas virtuais */ private List<CS_VirtualMac> VMs; /** * Armazena listas com a arquitetura de todo o sistema modelado, utilizado * para buscas das métricas e pelo motor de simulação * * @param mestres * @param maquinas * @param vms * @param links * @param internets */ public RedeDeFilasCloud(List<CS_Processamento> mestres, List<CS_MaquinaCloud> maquinas, List<CS_VirtualMac> vms, List<CS_Comunicacao> links, List<CS_Internet> internets) { super(mestres,null,links, internets); this.maquinasCloud = maquinas; this.VMs = vms; } public List<CS_MaquinaCloud> getMaquinasCloud() { return maquinasCloud; } public void setMaquinasCloud(List<CS_MaquinaCloud> maquinasCloud) { this.maquinasCloud = maquinasCloud; } public List<CS_VirtualMac> getVMs() { return VMs; } public void setVMs(List<CS_VirtualMac> VMs) { this.VMs = VMs; } /** * Cria falhas para ocorrer durante a simulação usando a distribuição de Weibull. * A distribuição de Weibull indica o momento que ocorre a falha, * enquanto a uniforme indica o tempo de recuperação do recurso * @param min número mínimo de falhas que ocorrerão * @param max número máximo do falahas que ocorrerão * @param scale parâmetro de escala da distribuição de Weibull * @param shape parâmetro de forma da distribuição de Weibull * @param recMin tempo mínimo para recuperação do recurso que falhou * @param recMax tempo máximo para recuperação do recurso que falhou * @param recuperavel indica se a falha tem recuperação automática */ @Override public void setFalhas(int min, int max, double scale, double shape, double recMin, double recMax, boolean recuperavel) { Random rd = new Random(); int numFalhas = min + rd.nextInt(max - min); List<Double> falhas = new ArrayList<Double>(); for (int i = 0; i < numFalhas; i++) { falhas.add(scale * Math.pow(-Math.log(1 - rd.nextDouble()), 1 / shape)); } Collections.sort(falhas); while(!falhas.isEmpty()){ int next = rd.nextInt(maquinasCloud.size()); System.out.println("Falha "+falhas.get(0)+" no "+maquinasCloud.get(next).getId()); maquinasCloud.get(next).addFalha(falhas.remove(0), recMin, recuperavel); } } }
joaoamr/iSPD
src/ispd/motor/filas/RedeDeFilasCloud.java
Java
gpl-3.0
3,854
package yt.bam.library.modules; import java.util.ArrayList; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import yt.bam.library.*; import yt.bam.library.commands.*; /** * CommandModule * @author FR34KYN01535 * @version 1.1 */ public class CommandModule { public static final Logger logger = Bukkit.getLogger(); public Plugin Plugin; public static TranslationModule TranslationManager; public static ArrayList<String> RootCommands; public static ArrayList<ICommand> Commands; public CommandModule(Plugin plugin,TranslationModule translationManager,String[] rootCommands,ArrayList<ICommand> commands){ Plugin = plugin; TranslationManager = translationManager; RootCommands = new ArrayList<String>(); for(String rootCommand :rootCommands) { RootCommands.add(rootCommand.toLowerCase()); } Commands = commands; } public static boolean onCommand(CommandSender sender, org.bukkit.command.Command root, String commandLabel, String[] args) { if (RootCommands.contains(root.getName().toLowerCase())) { ICommand command=null; if(args.length==0){ command = new CmdHelp(); }else{ for(ICommand cmd : Commands){ String[] cmdargs = cmd.getName(); if(args.length >= cmdargs.length){ int index = 0; boolean found = true; for(String cmdarg : cmdargs){ if(!cmdarg.equals(args[index])){ found =false; } } if(found){ command=cmd; break; } } } } if (command == null) { Helpers.sendMessage(sender, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_UNKNOWN_COMMAND")); return true; } try { Permission permission = command.getPermissions(); if(permission == null || hasPermission(sender,permission)){ if(!command.allowedInConsole() && !(sender instanceof Player)){ Helpers.sendMessage(sender, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_ONLY_CHAT")); }else{ command.execute(sender, commandLabel, args); // Execute } return true; } } catch (Exception e) { sender.sendMessage(commandLabel); logger.info(e.getMessage()); } finally { return true; } } return false; } public static boolean hasPermission(CommandSender player, Permission permission){ if(player.hasPermission(permission)){ return true; }else{ Helpers.sendMessage(player, ChatColor.RED + TranslationManager.getTranslation("COMMAND_MANAGER_NO_PERMISSION")+ " ("+permission.getName()+")"); return false; } } public void onEnable() { } public void onDisable() { // } }
BAMdevelopment/BAMLibrary
src/main/java/yt/bam/library/modules/CommandModule.java
Java
gpl-3.0
3,547
/* * * DATA SCENE * */ // Fait la moyenne des data sommé par le hub function getSensorData() { var result = {}; if (motion.counter != 0) { result.motion = { acceleration : { x : motion.acceleration.x / motion.counter, y : motion.acceleration.y / motion.counter, z : motion.acceleration.z / motion.counter }, rotationRate: { betaDeg : motion.rotationRate.betaDeg / motion.counter, gammaDeg : motion.rotationRate.gammaDeg / motion.counter, alphaDeg : motion.rotationRate.alphaDeg / motion.counter }, interval : motion.interval }; } else { result.motion = previousData.motion; } if (orientation.counter != 0) { result.orientation = { betaDeg : orientation.betaDeg / orientation.counter, gammaDeg : orientation.gammaDeg/ orientation.counter, alphaDeg : orientation.alphaDeg/ orientation.counter }; } else { result.orientation = previousData.orientation; } if (nipple.counter != 0) { result.nipple = { force : nipple.force / nipple.counter, angleRad : nipple.angleRad / nipple.counter }; } else { result.nipple = previousData.nipple; } if(result.motion.interval >= 1000/60) { result.motion.interval = 1000/60; } // Kalman rate init and interval ! kalmanAlpha.setRate(result.motion.rotationRate.alphaDeg); kalmanBeta.setRate(result.motion.rotationRate.betaDeg); kalmanGamma.setRate(result.motion.rotationRate.gammaDeg); kalmanBeta.setDeltat(result.motion.interval/1000); kalmanGamma.setDeltat(result.motion.interval/1000); kalmanAlpha.setDeltat(result.motion.interval/1000); //previousData = result; return result; } // Reset to 0 sensor data function resetSensorData() { motion.counter = 0; motion.acceleration.x = 0; motion.acceleration.y = 0; motion.acceleration.z = 0; motion.rotationRate.betaDeg = 0; motion.rotationRate.gammaDeg = 0; motion.rotationRate.alphaDeg = 0; motion.interval = 0; orientation.counter = 0; orientation.betaDeg = 0; orientation.gammaDeg = 0; orientation.alphaDeg = 0; nipple.counter = 0; nipple.force = 0; nipple.angleRad = 0; }
sandros06/R-3D
apps/base_websocket/public/javascripts/scripts/data_scene.js
JavaScript
gpl-3.0
2,528
<?php ob_start ("ob_gzhandler"); header("Content-type: text/css; charset= UTF-8"); header("Cache-Control: must-revalidate"); $expires_time = 1440; $offset = 60 * $expires_time ; $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT"; header($ExpStr); ?> /*** kunena.forum.css ***/ @charset "utf-8"; /** * @version $Id$ * Kunena Component * @package Kunena * * @Copyright (C) 2008 - 2011 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org * * Based on FireBoard Component * @Copyright (C) 2006 - 2007 Best Of Joomla All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.bestofjoomla.com * **/ /* ------------------------- FONT SIZES FOR BLUE EAGLE PX EM PCT PT 6px .5em 50% 5pt 7px .583em 58.3% 5pt 8px .667em 66.7% 6pt 9px .75em 75% 7pt 10px .833em 83.3% 8pt 11px .917em 91.7% 8pt 12px 1em 100% 9pt (Base size) 13px 1.083em 108.3% 10pt 14px 1.167em 116.7% 11pt 15px 1.25em 125% 11pt 16px 1.333em 133.3% 12pt 17px 1.417em 141.7% 13pt 18px 1.5em 150% 14pt 19px 1.583em 158.3% 14pt 20px 1.667em 166.7% 15pt 21px 1.75em 175% 16pt 22px 1.833em 183.3% 17pt 23px 1.917em 191.7% 17pt 24px 2em 200% 18pt ----------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------- */ /* MAIN STYLES ----------------------------------------------------------------------------------------------- */ #Kunena { padding: 0; margin: 0; line-height: 1.333em; } #Kunena td, #Kunena table, #Kunena th, #Kunena div, #Kunena p, #Kunena span { font-size: 1em; } #Kunena sup { vertical-align: super; } #Kunena sub { vertical-align: sub; } #Kunena ul li { background: none; margin: 0; } #Kunena .clr { clear:both; height:1px; overflow:hidden;} #Kunena .fltlft {float:left;} #Kunena .fltrt {float:right;} #Kunena .kright {text-align:right;} #Kunena .kleft {text-align:left;} #Kunena .kcenter {text-align:center;} #Kunena .nowrap {white-space:nowrap;} #Kunena .divider {margin:0 3px;} #Kunena .hidden {overflow:hidden;} #Kunena a { text-decoration: none; font-weight: normal; } #Kunena a:link, #Kunena a:visited, #Kunena a:active {} #Kunena a:focus {outline: none;} #Kunena a:hover {} #Kunena .overflow { display: table; table-layout:fixed; width: 100%; } #Kunena .kxs { /* 9px */ font-size: .75em; } #Kunena .kms { /* 10px */ font-size: .833em; } #Kunena .ks { /* 11px */ font-size: .917em; } #Kunena .km { /* 12px */ font-size: 1em; } #Kunena .kl { /* 16px */ font-size: 1.333em; } #Kunena .kxl { /* 17px */ font-size: 1.417em; } #Kunena .kxxl { /* 20px */ font-size: 1.667em; } #Kunena input.ksmall { width: 25%; } #Kunena input.kmedium { width: 45%; } #Kunena input.klarge { width: 95%; } #Kunena textarea, #Kunena textarea.kmedium { font-size: 1em; width: 95%; height: 10em; } #Kunena textarea.ksmall { height: 5em; } #Kunena textarea.klarge { height: 20em; } #Kunena .knewchar { font-weight: bold; margin-left: 3px; font-size: .75em; vertical-align:top; white-space:nowrap; } #Kunena table { width :100%; border-collapse:collapse; padding:0; margin:0; } /* Block styling ----------------------------------------------------------------------------------------------- */ #Kunena div.kblock { display: table; table-layout:fixed; width: 100%; border: none; margin: 5px 0 0 0; clear: both; border-bottom:4px solid; } #Kunena .kblock div.kheader { border-bottom:2px solid; padding:0 10px 0 10px; background: #5388B4 !important; } #Kunena .kheader h2, #Kunena .kheader h2 a { font-weight: bold; margin-bottom: 0; padding: 0; } #Kunena div.kblock div.ktitle { text-align: left; display: table-row; width:100%; margin: 0; word-wrap: break-word; overflow: hidden; } #Kunena div.kblock div.ktitle h1, #Kunena div.kblock div.ktitle h2 { border: none; display: block; line-height: 1.9em; font-size:1.333em; text-indent: 0px; padding-top: 2px; margin: 0 10px; padding: 2px 0; width: auto; } #Kunena div.kblock span.ktoggler { float: right; top: 1px; right: -10px; height: 1px; position: relative; } #Kunena .ktoggler a:hover { color:#ff0000; background: url("../../default/images/expand.gif") no-repeat scroll 0 0 transparent; } #Kunena div.kblock span.select-toggle { float: right; top: 5px; right: 13px; height: 1px; position: relative; } #Kunena div.kblock div.kcontainer { display: table-row; } #Kunena div.kblock div.kbody { border-style:solid; border-width:0px 1px; overflow: hidden; word-wrap: break-word; } #Kunena div.kblock label { clear: both; /*display: block;*/ } #Kunena div.kblock div.khelprulescontent, #Kunena div.kblock div.kfheadercontent { vertical-align: top; padding: 15px; /*border: 1px solid;*/ } #Kunena div.kblock div.khelprulesjump { border: 1px solid; } #Kunena div.kblock div.kactions { padding: 5px 10px; line-height: 13px; } #Kunena div.kblock div.kactions a { color: #FFF !important; background-color:transparent !important } #Kunena table.kblock { width: 100%; margin: 5px 0 0 0; clear: both; border-spacing: 0; } #Kunena tr.krow1 td { padding: 4px 8px; } #Kunena tr.krow2 td { padding: 4px 8px; } #Kunena table.kblock .kcol { padding: 4px 8px; } #Kunena .kcol-annid { text-align: center; width: 5%; } #Kunena .kcol-anndate { width: 15%; } #Kunena .kcol-anntitle { width: 50%; } #Kunena .kcol-annpublish { text-align: center; width: 10%; } #Kunena .kcol-annedit { text-align: center; width: 10%; } #Kunena .kcol-anndelete { text-align: center; width: 10%; } #Kunena table.kblocktable .knewchar { font-size: .583em; } #Kunena tr.ksth { font-size: 1em; } #Kunena tr.ksth th{ padding: 3px 5px; text-align: center; } #Kunena td#kpost-buttons { text-align:center; } #Kunena tr.krow1 td.kcc-row1, #Kunena tr.krow2 td.kcc-row1 { background: none; } #Kunena td.kcol-ktopicreplies { text-align: center; width:1%; } #Kunena td.kcol-ktopicreplies strong { display: block; font-size: 2.091em; font-weight: normal; margin: 4px 0; } #Kunena span.kcat-topics, #Kunena span.kcat-replies { text-align:center; font-size: 1em; } #Kunena span.kcat-topics-number, #Kunena span.kcat-replies-number { display:block; font-size: 1.417em; margin:5px 0; } #Kunena .ktopic-latest-post, #Kunena .ktopic-date { font-size: .917em; } #Kunena a.ktopic-title { font-weight: bold; font-size: 1.25em; } #Kunena div.ktopic-title-cover { text-align:left; } #Kunena div.ktopic-details { clear:left; font-size: .977em; } #Kunena .klatest-avatar, #Kunena .ktopic-latest-post-avatar { display: block; height: auto; width: 36px; padding: 1px; margin: 4px 6px 2px 0; border: 1px solid; float: left; } #Kunena img.klist-avatar { height: auto; width: 36px; border: 0px } #Kunena .klatest-post-info { display:block; } #Kunena .kcredits { height: 31px; line-height: 26px; /*font-size: .833em;*/ } #Kunena td.kcredits-kintro { vertical-align: middle; padding: 0 15px; } #Kunena .kfooter { font-size: .833em; } #Kunena .kfooter-time { } #Kunena .kalert { } #Kunena td.kcol-first { border-left: none; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; white-space:nowrap; } #Kunena td.kcol-mid { border-left: 1px solid; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; } #Kunena td.kcol-last { border-left: 1px solid; border-bottom: 1px solid; padding: 4px 8px; vertical-align: middle; } #Kunena td.ktopicmodule { padding: 0; } #Kunena td.ktopicmoderation { width: 1%; vertical-align: middle; } #Kunena td.kcol-ktopiclastpost { font-size: .917em; width: 25%; vertical-align: middle; } /* COLOR ADMINISTRATOR AND MODERATOR ----------------------------------------------------------------------------------------------- */ #Kunena .kwho-admin { } #Kunena .kwho-globalmoderator { } #Kunena .kwho-moderator { } #Kunena .kwho-user { } #Kunena .kwho-guest { } #Kunena .kwho-banned { } #Kunena .kwho-blocked { } /* MENU ----------------------------------------------------------------------------------------------- */ #Kunena #ktop { margin: 0; border-style: solid; border-top-width: 0; border-right-width: 0; border-bottom-width: 3px; border-left-width: 0; vertical-align: bottom; line-height: 0; } #Kunena #ktop span.ktoggler { margin:-16px 0; padding:1px 1px 0; } #Kunena #ktopmenu { margin:0.33em 0; display: inline; } #Kunena #ktab { margin:0 20px 0 0; top: 0; } #Kunena #ktab ul { margin: 0; padding: 0; list-style: none; display: inline-block; } #Kunena #ktab ul ul { margin: -2px 2px; padding: 0; list-style: none; float: left; } #Kunena #ktab li, #Kunena #ktab div.moduletable ul.menu li { display: inline; float: left; margin: 2px 2px 0 0!important; padding: 0; border: 0; } #ktab div.moduletable { background: none; margin-bottom: 0; } #ktab div.moduletable ul.menu, #ktab div.moduletable ul.menu li a, #ktab div.moduletable ul.menu li a span { background-image:none!important; font-size: 1em; line-height: 2em; } #Kunena #ktab a { margin: 0; padding: 0 10px; text-decoration: none; border: 0; display: block; float: left; border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; -webkit-border-radius: 5px 5px 0 0; color: #fff !important; font-size: 1em; line-height: 2.3em; text-indent: 0; } #Kunena #ktab a span { display: block; font-size: 1em; line-height: 2.3em; text-indent: 0; padding: 0; } #Kunena #ktab a:hover, #Kunena #ktab li.Kunena-item-active a { background-position: right bottom; } #Kunena #ktab a:hover span, #Kunena #ktab li.Kunena-item-active a span { background-position: left bottom; font-style: normal; text-decoration: none; } #Kunena select#searchlist { margin-bottom: 10px; float:left; } #Kunena select, #Kunena select:focus, #Kunena select:hover { /* background: none repeat scroll 0 0; */ /*font-size: .917em;*/ border: 1px solid; padding: 0px; } #Kunena td.td-1 { vertical-align:top; } /* Using a Joomla menu module */ #Kunena div.moduletable { margin: 0; padding: 0; border:none; } #Kunena #ktab ul.menu li.active a { /* Do not specify background color: template parameter */ } #Kunena option { background: none repeat scroll 0 0; font-size: .917em; padding: 0px 10px 0px 2px; } #Kunena .button, #Kunena .kbutton { background: none repeat scroll 0 0; font-size: .917em; border: 1px solid; padding: 0px 4px; margin-right: 10px; } #Kunena .kbutton-back { } #Kunena .kbutton-container { margin-top: 20px; text-align:center; } #Kunena .kbutton-container input.kbutton, #Kunena .kbutton-container .kbutton, #Kunena .kbutton-container .kbutton:hover, #Kunena .kbutton-container .kbutton:focus { font-size:1em; font-weight:bold; padding:4px; } #Kunena input.kinput { border: 1px solid; } #Kunena table.klist-bottom td { padding: 0 5px; height: 20px; line-height: 20px; text-align:center; } #Kunena table.klist-bottom td.klist-moderators { text-align:left; } #Kunena .kbutton:hover, #Kunena .kbutton:focus { background: none repeat scroll 0 0; font-size: .917em; border: 1px solid; padding: 0px 4px; } #Kunena .klist-actions { border: 1px solid; margin-top: -1px; } #Kunena .klist-actions td { vertical-align:middle; padding: 0 10px; white-space:nowrap; } #Kunena .klist-actions-bottom { border: 1px solid; margin-bottom: -1px; } #Kunena .klist-actions-info { float: left; font-weight: bold; height: 28px; line-height: 28px; padding-left: 15px; padding-right: 10px; } #Kunena .klist-actions-info a { text-decoration: underline; } #Kunena .klist-pages { border-left: 1px solid; float: right; font-size: 1.333em; font-weight: bold; height: 28px; line-height: 28px; padding-left: 10px; padding-right: 5px; } #Kunena .klist-times { border-left: 1px solid; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 10px; } #Kunena a.klist-pages-link:link, #Kunena a.klist-pages-link:visited { text-decoration: underline; } #Kunena .klist-pages-link { padding: 0pt 5px; } #Kunena .klist-actions-info-all { font-weight: bold; height: 28px; line-height: 28px; padding-left: 15px; padding-right: 10px; width: 100%; } #Kunena .klist-actions-goto { height: 28px; padding: 0px 2px 0px 2px; width: 1%; vertical-align: middle; } #Kunena .klist-actions-forum { border-left: 1px solid; height: 28px; padding: 1px 4px 1px 4px; white-space: nowrap; vertical-align: middle; width: 10%; } #Kunena .klist-pages-all { border-left: 1px solid; font-size: 1.333em; font-weight: bold; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 3px; vertical-align: middle; text-align: right; } #Kunena .klist-times-all { width: 1%; border-left: 1px solid; height: 28px; line-height: 28px; padding-left: 5px; padding-right: 5px; } #Kunena .klist-jump-all { width: 1%; border-left: 1px solid; height: 20px; line-height: 20px; padding-left: 5px; padding-right: 5px; white-space: nowrap; } #Kunena .klist-jump-all form { display: table; } #Kunena .klist-times-all .inputboxusl { /*font-size: .833em;*/ margin: 0pt; padding: 0pt; width: 100px; } #Kunena .klist-jump-all form .inputbox { /*font-size: .833em;*/ margin: 0pt; padding: 0pt; width: 150px; } #Kunena .klist-pages-all table tr td { height: 28px; line-height: 28px; white-space: nowrap; } #Kunena td.klist-jump-all input.kjumpgo { display: none; } #Kunena .klist-top { background: none; border: 1px solid; margin: -1px 0px 0px; width: 100%; } #Kunena .klist-bottom { background:none; border:1px solid; margin:0 0 5px; min-height:2.33em; padding:1px 5px; } #Kunena .klist-moderators { clear: left; } #Kunena .klist-markallcatsread { min-height: 27px; padding: 0px; overflow: hidden; border: 1px solid; } #Kunena .klist-markallcatsread input.kbutton { padding:0; margin: 4px; } #Kunena .klist-categories { border-left: 1px solid; /* height: 28px; line-height: 28px; */ padding: 0 5px 0 10px; white-space: nowrap; margin: 0; } #Kunena div.bannergroup { text-align:center; } /*---------- Pagination ------------- */ #Kunena ul.kpagination{ border:0; margin:0; padding:0 5px 0 0; } #Kunena .kpagination li{ border:0; margin:0; padding:0; font-size: .667em; list-style-type:none; line-height: .667em; display:inline-block; } #Kunena #kflattable ul.kpagination { width: auto; font-size: 1.167em; line-height: 1.167em; } #Kunena .kpagination a { border:solid 1px; } #Kunena .kpagination li.page { margin-right:2px; } #Kunena .kpagination li.more { padding:4px 2px; font-weight:bold; } #Kunena .kpagination .active { border:solid 1px; font-weight:bold; padding:3px 5px; margin: 2px; } #Kunena .kpagination a:link, #Kunena .kpagination a:visited { display:block; padding:3px 5px; margin: 2px; text-decoration:none; } #Kunena #kflattable .kpagination a:link, #Kunena #kflattable .kpagination a:visited { margin: 0; } #Kunena .kpagination a:hover{ border:solid 1px; } /* Inline pagination in topics */ #Kunena div.ktopic-title-cover ul.kpagination { padding-top: 2px; text-align:left; /* display:inline; */ } #Kunena div.ktopic-title-cover ul.kpagination li{ font-size:.833em; } #Kunena div.ktopic-title-cover ul.kpagination li.page { float:left; padding:4px 3px 0 0; } #Kunena div.ktopic-title-cover ul.kpagination a { border:solid 1px; } #Kunena div.ktopic-title-cover ul.kpagination a:hover{ border:solid 1px; } #Kunena #kflattable ul.kpagination li { margin-right: 5px; } #Kunena span.ktopic-posted-time { display: block; float:left; font-size: .917em; } #Kunena span.ktopic-category { float:left; clear:left; font-size: .917em; } #Kunena span.ktopic-views { text-align:center; } #Kunena span.ktopic-views-number { display: block; font-size: 1.455em; margin:5px 0; text-align:center; } #Kunena span.ktopic-by { float:left; } #Kunena span.ktopic-locked { margin-left: 3px; text-align: left; } /* HEADER ----------------------------------------------------------------------------------------------- */ #Kunena td.kprofileboxcnt { text-align:left; width: 95%; vertical-align:middle; padding:5px; } #Kunena td.kprofileboxcnt ul { margin: 5px 0 5px 5px; padding-left: 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-link { margin: 5px 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-link li { height: 10px; line-height: 10px; font-size: .917em; margin-top: 5px; padding-left:10px !important; } #Kunena td.kprofileboxcnt ul li { list-style-type:none; display: block; background: 0 none; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li { padding: 2px; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton { margin: 0; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton:hover { } #Kunena .kpbox { margin: 0!important; padding:0; } #Kunena div#kforum-head { padding: 5px 10px; vertical-align:middle; border-left: 1px solid; border-right: 1px solid; border-bottom: 1px solid; } #Kunena table#kforumsearch input.kbutton { margin: 10px; } #Kunena div#kmoderatorslist div.kbody { border:1px solid; height:25px; line-height:25px; margin:-6px 0 0; padding:5px; } #Kunena div.kmoderatorslist-jump form#jumpto { margin:5px; } #Kunena table.kblock .kcol-search-subject { width: 70%; } #Kunena table.kblock .kcol-search-author { width: 10%; } #Kunena table.kblock .kcol-search-date { width: 20%; } /* SEARCH ----------------------------------------------------------------------------------------------- */ #Kunena fieldset { border:1px solid; padding:15px; margin-bottom: 15px; } #Kunena fieldset legend { font-size: 1.182em; padding-left: 5px; padding-right: 5px; margin: 0 0 0 -5px; font-weight: bold; } #Kunena select#catids option{ padding-left: 5px; } #Kunena label.searchlabel { display:block; margin-bottom: 5px; margin-right: 100px; } #Kunena input#keywords, #Kunena input#username { /*width:250px;*/ margin-right: 10px; } #Kunena select#catids { float:left; margin-bottom: 20px; } #Kunena label#childforums-lbl{ float:left; clear:left; } #Kunena fieldset#search-posts-date select, #Kunena fieldset#search-posts-sort select { margin-right: 10px; } #Kunena fieldset#search-posts-start select { margin-left: 10px; } #Kunena div.ksearchresult-desc { padding: 5px; } #Kunena div#ksearchresult div.resultmsg { padding: 15px 0; clear:left; } #Kunena div#ksearchresult span.kmsgtitle a { font-weight: bold; } #Kunena div#ksearchresult span.kmsgdate { float: left; } #Kunena div#ksearchresult div.kresult-title { border-bottom: 1px solid; overflow:hidden; padding-bottom:5px; } #Kunena div#ksearchresult td.resultmsg { padding: 0 10px 10px; } #Kunena div#ksearchresult div.resultcat { padding: 5px 0 0 0; border-top: 1px dotted; } #Kunena div.kadvsearch td.kcol-first, #Kunena div.kadvsearch td.kcol-mid { width: 50%; vertical-align: top; } /* PROFILEBOX AND LOGINBOX ----------------------------------------------------------------------------------------------- */ #Kunena ul.kprofilebox-link { float:right; } #Kunena ul.kprofilebox-link li { background: url("../../default/images/icons/arrow.png") no-repeat left !important; padding-left: 12px; display: inline; padding-right:10px; } #Kunena .kprofilebox-left { width: 5%; padding: 8px; border-right: 1px solid; vertical-align: middle; } #Kunena .kprofilebox-right { border-left: 1px solid; padding: 8px; } #Kunena .klink-block { padding-top: 5px; } #Kunena div.kpbox { border-bottom: 1px solid; } /* CATEGORY LIST ----------------------------------------------------------------------------------------------- */ #Kunena td.kmycount, #Kunena td.kcol-kcattopics, #Kunena td.kcol-kcatreplies, #Kunena td.kcol-ktopicicon, #Kunena td.kcol-ktopicviews { white-space:nowrap; text-align:center; width: 1%; vertical-align: middle; } .kcol-ktopicicon img { border: 0 none; } #Kunena td.kcol-kcatlastpost { width: 25%; text-align:left; vertical-align: middle; } #Kunena td.kcol-knoposts { width: 25%; text-align:center; vertical-align: middle; } #Kunena td.kcol-category-icon { width: 1%; } #Kunena #kblock4, #Kunena #kblock1, #Kunena .k-bt-cvr1 { margin-top: 5px; } #Kunena table.kblocktable { border-style: solid; border-width: 0px 0px 0px 0px; text-align: left; } #Kunena h1, #Kunena h2 { text-align: left; display: block; width:100%; line-height: 1.5em; font-size:1.333em; padding-top: 2px; min-height: 1.6em; margin-top: 0px; margin-bottom: 0px; font-weight:bold; text-transform: none; } #Kunena h2 a { font-weight: bold; } #Kunena h1 a:hover, #Kunena h2 a:hover { text-decoration: underline; } #Kunena h1 a:link, #Kunena h1 a:active, #Kunena h1 a:visited { } #Kunena h2 span.kright { float: right; margin: 0 10px; } #Kunena h2 span.kheadbtn { margin: 0 !important; } #Kunena h2 span.kheadbtn a { font-size: 11px; line-height: 23px; border: 1px solid; padding-top: 1px; padding-bottom: 3px; padding-left: 3px; padding-right: 3px; } #Kunena h2 span.kheadbtn:hover a { text-decoration: none; border: 1px solid; } #Kunena div.ktitle-desc { margin-top:-3px; padding:0 0 6px; } #Kunena .kcheckbox { float:right; margin-right: -14px; width: 20px; } #Kunena div.kfavorite { background: url("../../default/images/icons/favoritestar.png") no-repeat left top; height: 18px; width: 18px; display: inline-block; margin:-25px 4px 0; float: right; } #Kunena .ktitle, #Kunena a.ktitle { font-weight: bold; display: block; text-decoration: none; float:left; } #Kunena .ktitle a { font-weight: bold; text-decoration: none; } #Kunena div.kthead-title a { font-size: .917em; display: inline-block; float: left; padding-bottom: 0; margin-bottom: 3px; font-weight: bold; } #Kunena div.kthead-desc, #Kunena div.kthead-moderators { clear: left; line-height: 1.2em; } #Kunena div.kthead-moderators { margin-top: 5px; font-size: .833em; } #Kunena div.kthead-desc a { font-weight:bold; } #Kunena div.kthead-desc a:hover { text-decoration:underline; } #Kunena div.kthead-child { clear: left; border-top: 1px dotted; margin-top: 4px; } #Kunena table.kcc-table tr td { border: 0px solid; } #Kunena div.kcc-childcat-title { width: 100%; display: inline-block; vertical-align: top; padding-top: 4px; line-height: 2em; text-transform: uppercase; font-size: .833em; } #Kunena div.kcc-table { display: inline; } #Kunena span.kchildcount { margin-left: 2px; margin-right: 6px; display: inline; font-size: 0.833em; line-height: 17px; } #Kunena div.klatest-subject, #Kunena div.klatest-subject-by { margin-left: 5px; } #Kunena div.kcc-subcat { float: left; display: inline-block; vertical-align: top; padding-top: 2px; } #Kunena div.kcc-subcat a { font-size: .917em; vertical-align: bottom; } /* SHOW CATEGORY ----------------------------------------------------------------------------------------------- */ #Kunena img.stickyicon, #Kunena img.attachicon { float: right; border: 0; margin: 2px; } #Kunena img.catavatar { width: 20px; height: 20px; margin-left: 4px; border: 1px solid; } #Kunena .kcontenttablespacer { border-left: 0px; border-right: 0px; border-bottom: 1px solid; line-height:0.5em; } #Kunena .krow1-stickymsg { } #Kunena .krow2-stickymsg { } /* VIEW PAGE -------------------------------------------------------------------- */ #Kunena div.kmsg-header { border-bottom:2px solid; padding:0; } #Kunena div.kmsg-header h2 { font-size:.917em; padding:3px 0; margin-bottom: 0; } #Kunena div.kmsg-header-top span.kmsgdate-top, #Kunena div.kmsg-header-bottom span.kmsgdate-bottom, #Kunena div.kmsg-header-right span.kmsgdate-right, #Kunena div.kmsg-header-left span.kmsgdate-left { width: 180px; text-align: center; line-height:1.8em; padding-left: 10px; } #Kunena div.kmsg-header-left span.kmsgdate-left { float: none; padding: 0; padding-bottom: 5px; } #Kunena div.kmsg-header-top span.kmsg-title-top, #Kunena div.kmsg-header-bottom span.kmsg-title-bottom, #Kunena div.kmsg-header-left span.kmsg-title-left, #Kunena div.kmsg-header-right span.kmsg-title-right { /*padding-left:15px;*/ margin-left:5px; } #Kunena div.kmsg-header-top span.kmsg-id-top, #Kunena div.kmsg-header-bottom span.kmsg-id-bottom, #Kunena div.kmsg-header-left span.kmsg-id-left, #Kunena div.kmsg-header-right span.kmsg-id-right { float: right; margin:0 10px 0 0; padding: 0 } #Kunena span.kpost-thankyou { float: right; margin-right: 15px; font-size:0.917em; } #Kunena div.kpost-thankyou { margin-top:4px; } #Kunena span.kmsgusertype { font-weight: normal; text-decoration: none; text-decoration: none; font-style: italic; } #Kunena span.kavatar img { border: 1px solid; padding: 1px; margin: 5px; max-width: 100px; max-height: 150px; } #Kunena span.kmsgtitle, #Kunena span.kmsgtitle-new { font-weight: bold; text-decoration: none; background: url("../../default/images/msgtitleicon.gif") no-repeat left center; padding-left: 25px; line-height: 22px; font-size: 1.333em; } #Kunena span.kmsgtitle-new { background: url("../../default/images/msgtitlenew.gif") no-repeat left center; } #Kunena table.kmsg th.kmsg-date { vertical-align: middle !important; } #Kunena th.kmsg-date span.ktopbottom, #Kunena th.kmsg-date span.kheader-right { float: left; margin:2px 25px; } #Kunena span.kmsgdate { font-weight: normal; text-decoration: none; padding-left: 5px; /*font-size: .833em;*/ white-space: nowrap; /*float: left;*/ } #Kunena div.kmsgbody { display: table; table-layout: fixed; width: 100%; padding: 10px 0 0 0; margin-top: 5px; min-height: 180px; } #Kunena div.kmsgbody div.kmsgtext { overflow: auto; word-wrap:break-word; } #Kunena td.kmessage-right div.kmsgbody, #Kunena td.kmessage-left div.kmsgbody, #Kunena td.kmessage-top div.kmsgbody, #Kunena td.kmessage-bottom div.kmsgbody { width: 97%; } #Kunena div.kmsgbody div.kmsgtext { overflow: auto; word-wrap:break-word; } #Kunena div.kmsgbody div.kmsgtext img { max-width:100%; max-height: 800px; } #Kunena div.kmsgbody div.kmsgtext ul > li { list-style-type:disc; } #Kunena div.kmsgattach { overflow: hidden; padding: 8px; margin-top: 8px; background:none; border:1px dotted; display:block; } #Kunena ul.kfile-attach, #Kunena ul.kfile-attach-editing { margin:0 0 8px 0; padding:0; } #Kunena ul.kfile-attach li { list-style-type: none; margin-top: 10px; padding-left: 30px; background:url("../../default/images/icons/attachment.png") no-repeat; height: 32px; line-height: 32px; width: auto; float: left; } #Kunena ul.kfile-attach li span { padding-left: 10px; vertical-align:top; font-size: .833em; } #Kunena ul.kfile-attach-editing li span { vertical-align:top; padding-left: 2px; } #Kunena ul.kfile-attach-editing li { list-style-type: none; margin-top: 10px; line-height: 32px; } #Kunena ul.kfile-attach li a img, #Kunena ul.kfile-attach-editing li a img { max-width: 32px; max-height: 32px; margin-left: 10px; } #Kunena span.kmsgtext-xs { font-size: 0.5em; } #Kunena span.kmsgtext-s { font-size: 0.75em; } #Kunena span.kmsgtext-m { font-size: 1em; } #Kunena span.kmsgtext-l { font-size: 1.25em; } #Kunena span.kmsgtext-xl { font-size: 1.50em; } #Kunena span.kmsgtext-xxl { font-size: 2em; } #Kunena div.kmsgtext pre, #Kunena div.kmsgtext code { border-left: 5px solid; border-right: 1px solid; border-top: 1px solid; border-bottom: 1px solid; font-weight: normal; line-height: 1.5; margin: 3px 0 10px 0; padding: 10px 15px; overflow: auto; width: auto; word-wrap:normal; max-height: 25em; } #Kunena table.kmsg th a { float: right; } #Kunena div.kmessage-editmarkup-cover { padding-top: 5px; text-align: right; border-bottom: 1px dotted; } #Kunena span.kmessage-editmarkup { background: no-repeat left center; height: 16px; border-left: 1px dotted; border-right: 1px dotted; border-top: 1px dotted; padding: 2px 5px 2px 5px; margin-left: 3px; font-size: .75em; } #Kunena span.kmessage-informmarkup { height: 16px; border-left: 1px dotted; border-right: 1px dotted; border-top: 1px dotted; padding: 2px 5px 2px 5px; margin-left: 3px; font-size: .75em; } #Kunena div.kmsgsignature { border-top:1px dotted; font-size: .833em; margin:15px 0; padding:5px 0; text-align:left; } #Kunena div.kmsgsignature img { max-width:100%; max-height: 100px; } #Kunena div.kmessage-buttons-cover { float: right; } #Kunena div.kmessage-buttons-row { text-align: left; height: 15px; line-height: 15px; margin: 3px 0px; line-height: 14px; white-space: nowrap; font-size: .917em; } #Kunena div.kmessage-thankyou{ border-top: 1px dotted; clear: both; } #Kunena .kreply-form { border: 1px solid; padding: 0.5em; } #Kunena .kreply-form .inputbox { border: 1px solid; margin: 2px 0px; } #Kunena div.kmsgtext-article, #Kunena div.kmsgtext-quote, #Kunena div.kmsgtext-hide, #Kunena div.kmsgtext-confidential { display: block; border: 1px dotted; margin: 5px 0pt; padding: 5px; font-style: italic; } #Kunena div.kmsgtext-article { } #Kunena div.kmsgtext-hide { } #Kunena div.kmsgtext-confidential { } #Kunena div.khide { background: url("../../default/images/bullet-tips.gif") no-repeat scroll 5px center; border: 1px dotted; font-size: 1.3em; padding: 10px 10px 10px 25px; } /* AVATAR POSITION ----------------------------------------------------------------------- */ #Kunena div.kmsgtitle { /*border-bottom:1px solid; padding-bottom: 5px;*/ } /* right ----------------------------------------*/ #Kunena td.kprofile-right { width: 170px; min-width: 170px; border-bottom: 1px solid; border-left: 1px solid; vertical-align:top; } #Kunena td.kmessage-right { width: 100%; overflow: hidden; padding: 10px 10px 0px 10px; vertical-align: top; } #Kunena td.kbuttonbar-right { vertical-align:bottom; width: 100%; height: 1em; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } /* left ----------------------------------------*/ #Kunena td.kprofile-left { vertical-align: top; width: 170px; min-width: 170px; border-bottom: 1px solid; border-right: 1px solid; } #Kunena td.kmessage-left { overflow: hidden; width: 100%; padding: 10px 10px 0px 10px; vertical-align: top !important; } #Kunena td.kbuttonbar-left { vertical-align:bottom; width: 100%; height: 1em; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } #Kunena .kunapproved td { } #Kunena .kdeleted td { } #Kunena div.kprofile { text-align: center; padding: 5px; } /* User info on posts ----------------------------------------*/ /* Left and right layouts */ #Kunena ul.kpost-profile li { padding: 0px; } #Kunena ul.kpost-profile { margin:8px 0; padding: 0; text-align:center; line-height: 1.5em; } #Kunena ul.kpost-profile li { list-style-type: none; display:block; padding-bottom: 1px; text-align:center !important; } #Kunena ul.kpost-profile li.kpost-username {font-size: 1.333em;} #Kunena ul.kpost-profile li.kpost-usertype {} #Kunena ul.kpost-profile li.kpost-avatar{} #Kunena ul.kpost-profile li.kpost-userrank{} #Kunena ul.kpost-profile li.kpost-userrank-img {} #Kunena ul.kpost-profile li.kpost-userrank-img img{vertical-align: text-top;} #Kunena ul.kpost-profile li.kpost-online-img{} #Kunena ul.kpost-profile li.kpost-online-img img {vertical-align: text-top;} #Kunena ul.kpost-profile li.kpost-karma {} #Kunena li.kpost-karma span.kmsgkarma { } #Kunena span.kkarma-minus { background: url("../../default/media/iconsets/profile/default/default.png") no-repeat 0px -294px; height: 14px; width: 14px; display: inline-block; margin: -2px 0; } #Kunena span.kkarma-plus { background: url("../../default/media/iconsets/profile/default/default.png") no-repeat 0px -313px; height: 14px; width: 14px; display: inline-block; margin: -2px 0; } #Kunena li.kpost-userposts{ margin : 0px; } #Kunena ul.kpost-profile li.kpost-smallicons{ margin: 0px auto; width: 90%; } #Kunena ul.kpost-profile li.kpost-personal{ text-align: center; font-style:italic; } #Kunena span.kpost-online-status-yes { display:inline-block; background: url("../../default/images/icons/online.gif") no-repeat; height: 15px; width: 74px; vertical-align: text-top; } #Kunena span.kpost-online-status-no { display:inline-block; background: url("../../default/images/icons/offline.gif") no-repeat; height: 15px; width: 74px; vertical-align: text-top; } #Kunena li.kpost-online-status-top-yes { display:block; float: left; padding-right:5px; background: url("../../default/images/icons/online.gif") no-repeat; height: 15px; width: 74px; } #Kunena li.kpost-online-status-top-no { display:block; float: left; padding-right:5px; background: url("../../default/images/icons/offline.gif") no-repeat; height: 15px; width: 74px; } /* Top and bottom layouts */ #Kunena ul#kpost-profiletop { margin:0; padding: 0; } #Kunena ul#kpost-profiletop li { list-style-type: none; display:block; padding: 0; } #Kunena ul#kpost-profiletop li.kpost-avatar{ float:left; clear:left; margin-right: 5px; } #Kunena ul#kpost-profiletop li.kpost-userrank{ padding-right: 5px; } #Kunena ul#kpost-profiletop li.kpost-smallicons{ float:right; width: auto; padding-top: 5px; } #Kunena ul#kpost-profiletop li.kpost-personal{ text-align: center; font-style:italic; float:right; width: 40%; padding-top: 5px; } /* top ----------------------------------------*/ #Kunena ul#kpost-profiletop li.kpost-userrank-img { display: block; } #Kunena td.kprofile-top { vertical-align: top; border-bottom: 1px solid; padding: 5px; } #Kunena td.kmessage-top { width: 100%; padding: 10px 10px 0px 10px; } #Kunena td.kbuttonbar-top { width: 100%; margin: 3px; border-bottom: 1px solid; padding: 3px 10px; } #Kunena div.ktopbottom-avatar { float: left; } #Kunena div.kprofile-mid { padding: 0px 5px; display: inline; text-align: left; vertical-align: middle; float:left; } #Kunena div.kprofile-right { display: inline; vertical-align: middle; float:right; width: 15%; text-align:right; } #Kunena div.kpersonal { padding: 0px 20px; display: inline; text-align: left; vertical-align: middle; float:left; } /* bottom ----------------------------------------*/ #Kunena td.kprofile-bottom { vertical-align: bottom; border-bottom: 1px solid; border-top: 1px solid; padding: 5px; } #Kunena td.kmessage-bottom { width: 100%; overflow: hidden; padding: 10px 10px 0px 10px; } #Kunena td.kbuttonbar-bottom { width: 100%; margin: 3px; padding: 3px 10px; } /* Stats on main page */ #Kunena ul#kstatslistleft, #Kunena ul#kstatslistright { margin: 0; padding: 0; } #Kunena ul#kstatslistleft li, #Kunena ul#kstatslistright li { list-style-type:none; display:block; margin-left: 0; padding: 1px 0px 1px 0; background: none; line-height: 1.333em; } #Kunena ul#kstatslistright li strong a { font-weight:bold; } /* POST PAGE -------------------------------------------------------------------- */ #Kunena #kpost-message .postinput { width: 94%; border: 1px solid; padding: 3px 5px; } #Kunena #kpost-message .postinput:hover, #Kunena #kpost-message .postinput:focus { width: 94%; border: 1px solid; padding: 3px 5px; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons table { width: 95%; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons td { border: 1px solid; width: 99%; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td.kposthint { border: 1px solid; padding: 2px 5px; } #Kunena table#kpostmessage .kposthint .kinputbox { border: 0px solid; width: 99%; } #Kunena .kpostbuttonset { width: 95%; margin: 2px; border: 1px solid; } #Kunena tr.krow1 .kpostbuttons { border: 1px solid; } #Kunena table#kpostmessage .ktxtarea { overflow: auto; /* IMPORTANT: height must be set in px */ height: 200px; border: 1px solid; } #Kunena table.kreview-table td.author { width: 15%; text-align: center; } #Kunena td.kcaptcha { text-align: left; vertical-align:middle; height: 35px; } #Kunena div#khistory td.kauthor, #Kunena div#ksearchresult td.kresultauthor { text-align:center; } #Kunena div#khistory td.khistorymsg { text-align:left; padding: 10px; } #Kunena div#khistory span.khistory-msgdate { float:left; padding-left: 10px; } #Kunena div#khistory tr.ksth a { float:right; padding-right: 10px; } /* ---- Post Previews ---- */ #Kunena textarea#kbbcode-message { width: 95%; float: left; } #Kunena #kbbcode-preview { /* IMPORTANT: do not set height - controlled by js */ border: 1px solid; overflow: scroll; } #Kunena div.kbbcode-preview-bottom { /* IMPORTANT: do not set height - controlled by js */ float:left; clear:left; width: 95%; margin-top: 10px; } #Kunena div.kbbcode-preview-right { /* IMPORTANT: do not set height - controlled by js */ float:right; width: 48%; margin-right: 10px; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td, #Kunena #kpostmessage tr.krow2 .kpostbuttonset td { border-bottom: 1px solid; } #Kunena #kpost-message td.kcol-first { width: 15%; text-align: right; vertical-align: middle; } #Kunena #kpost-result div { border: 1px solid; font-size: 1em; } #Kunena #kpost-buttons { padding: 4px; } #Kunena #kpost-buttons .kbutton { padding: 4px; font-weight: bold; font-size: 1em; } #Kunena div#kcolor-palette, #Kunena div#link, #Kunena div#image, #Kunena div#video { border-bottom: 1px solid; margin-bottom: 5px; padding-bottom: 5px; } /* FORUM ICON BUTTONS ----------------------------------------------------------------------------------------------- */ #Kunena .kicon-button { text-transform: uppercase; /* We need to use fixed font size: button does not grow */ font-size: 11px; text-decoration: none; cursor: pointer; line-height: 145%; display: inline-block; background-image: url("../../default/media/iconsets/buttons/default/default.png") !important; background-repeat: repeat-x; border: none; margin:0 5px; } /* #Kunena a.kicon-button:hover { background-position: 0 -480px !important; } */ #Kunena .kicon-button span { background-image: inherit; background-repeat: no-repeat; display: inline-block; margin:0 -5px; } #Kunena .kicon-button span span { height: 18px; display: inline-block; margin: 0; padding: 0 7px 0 20px; background-repeat: no-repeat; } #Kunena a.kicon-button span span:hover { text-decoration: underline; } /* Need the hover states to fix Beez in Joomla 1.6 */ #Kunena .kbuttonuser, #Kunena .kbuttonuser:hover { background-position: 0 -360px; } #Kunena .kbuttononline-yes, #Kunena .kbuttonmod, #Kunena .kbuttononline-yes:hover, #Kunena .kbuttonmod:hover{ background-position: 0 -200px; } #Kunena .kbuttononline-no, #Kunena .kbuttongen, #Kunena .kbuttoncomm, #Kunena .kbuttononline-no:hover, #Kunena .kbuttongen:hover, #Kunena .kbuttoncomm:hover { background-position: 0 -480px; } #Kunena .kbuttononline-yes span span, #Kunena .kbuttonmod span span, #Kunena .kbuttononline-yes span span:hover, #Kunena .kbuttonmod span span:hover{ background-position: right -220px; } #Kunena .kbuttonuser span span, #Kunena .kbuttonuser span span:hover { background-position: right -380px; } #Kunena .kbuttononline-no span span, #Kunena .kbuttongen span span, #Kunena .kbuttoncomm span span, #Kunena .kbuttononline-no span span:hover, #Kunena .kbuttongen span span:hover, #Kunena .kbuttoncomm span span:hover { background-position: right -500px; } #Kunena .kbuttononline-yes span span, #Kunena .kbuttononline-no span span { padding: 0 7px; height: 15px; } #Kunena .kbuttononline-yes span.online-yes {background-position: 0 0px;} #Kunena .kbuttononline-no span.online-no {background-position: 0 -400px;} #Kunena .kbuttoncomm span.reply {background-position: 0 -460px;} #Kunena .kbuttoncomm span.quote {background-position: 0 -440px;} #Kunena .kbuttoncomm span.newtopic {background-position: 0 -420px;} #Kunena .kbuttonuser span.layout-flat {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-flat span {padding: 0 7px;} #Kunena .kbuttonuser span.layout-threaded {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-threaded span {padding: 0 7px;} #Kunena .kbuttonuser span.layout-indented {background-position: 0 -240px} #Kunena .kbuttonuser span.layout-indented span {padding: 0 7px;} #Kunena .kbuttonuser span.thankyou {background-position: 0 -340px;} #Kunena .kbuttonuser span.favorite {background-position: 0 -260px;} #Kunena .kbuttonuser span.subscribe {background-position: 0 -320px;} #Kunena .kbuttonuser span.markread {background-position: 0 -300px;} #Kunena .kbuttonuser span.report {background-position: 0 -320px;} #Kunena .kbuttonmod span.merge {background-position: 0 -100px;} #Kunena .kbuttonmod span.edit {background-position: 0 -60px;} #Kunena .kbuttonmod span.delete {background-position: 0 -40px;} #Kunena .kbuttonmod span.permdelete {background-position: 0 -40px;} #Kunena .kbuttonmod span.undelete {background-position: 0 -20px;} #Kunena .kbuttonmod span.move {background-position: 0 -140px;} #Kunena .kbuttonmod span.sticky {background-position: 0 -180px;} #Kunena .kbuttonmod span.lock {background-position: 0 -80px;} #Kunena .kbuttonmod span.split {background-position: 0 -160px;} #Kunena .kbuttonmod span.approve {background-position: 0 -180px;} #Kunena .kbuttonmod span.moderate {background-position: 0 -120px;} /* Goto Up/down buttons */ #Kunena a.kbuttongoto { } #Kunena a.kbuttongoto span.top { background: url("../../default/images/icons/top_arrow.gif") no-repeat left top; height: 18px; width: 18px; display: block; } #Kunena a.kbuttongoto span.bottom { background: url("../../default/images/icons/bottom_arrow.gif") no-repeat left top; height: 18px; width: 18px; display: block; } #Kunena div#kreport-container { /*border:1px solid;*/ height:1%; overflow:auto; padding:10px 10px 30px; } #Kunena form.kform-report, #Kunena form.kform-report label, #Kunena form.kform-report input, #Kunena form.kform-report textarea { float:left; clear:both; } #Kunena form.kform-report label { margin-top: 15px; } #Kunena form.kform-report input, #Kunena form.kform-report textarea { border:1px solid; } #Kunena div.kreportstatus { text-align:center; margin: 30px 0; } /* BBCODE BUTTONS -------------------------------------------------------------------- */ #Kunena img.kbbcode { cursor: pointer; margin-top: 4px; margin-right: 1px; padding: 0px; } #Kunena img.kbbcode:hover { cursor: pointer; margin-top: 4px; margin-right: 1px; padding: 0px; } #Kunena .kbbcode-colortable { cursor: pointer; width: 100%; margin-left: auto; margin-right: auto; } #Kunena div#kbbcode-size-options { margin:2px 0 0; } #Kunena div#kbbcode-size-options span { vertical-align: middle; display: inline-block; line-height: 24px; } #Kunena div#kbbcode-size-options span:hover { cursor: pointer; padding: 0px; } #Kunena table.kpostbuttonset tr td.kpostbuttons select.kslcbox { position: relative; bottom: 5px; } #Kunena #kbbcode-toolbar { list-style-position:inside; list-style-type:none; height:18px; margin:2px 0 2px; padding:0; position:relative; } #Kunena #kbbcode-toolbar li { float:left; list-style-image:none !important; list-style-type:none !important; margin:0; padding:0; } #Kunena #kbbcode-toolbar li a { background-repeat: no-repeat; display:block; height:18px; width:18px; margin-right: 2px; } #Kunena #kbbcode-toolbar li a:hover { cursor: pointer; padding: 0px; } #Kunena #kbbcode-toolbar li span { display:none; } #Kunena ul#kbbcode-toolbar li a#kbbcode-separator1, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator2, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator3, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator4, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator5, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator6, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator7, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator8 { background-position:-400px 0; width: 8px; cursor: default; } #Kunena ul#kbbcode-toolbar li a#kbbcode-bold-button {background-position:0 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-italic-button {background-position:-18px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-underline-button {background-position:-36px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-strike-button {background-position:-54px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-sub-button {background-position:-72px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-sup-button {background-position:-90px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-size-button {background-position:-108px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-color-button {background-position:-126px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-spoiler-button {background-position:-144px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-hide-button {background-position:-162px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-ulist-button {background-position:-180px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-olist-button {background-position:-198px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-list-button {background-position:-216px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-left-button {background-position:-234px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-center-button {background-position:-252px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-right-button {background-position:-270px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-quote-button {background-position:-288px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-code-button {background-position:-306px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-image-button {background-position:-324px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-link-button {background-position:-342px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-table-button {background-position:0 -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-module-button {background-position:-18px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-ebay-button {background-position:-360px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-video-button {background-position:-378px 0;} #Kunena ul#kbbcode-toolbar li a#kbbcode-map-button {background-position:-72px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-attach-button {background-position:-36px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-gallery-button {background-position:-54px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-poll-button {background-position:-90px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-previewbottom-button {background-position:-252px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-previewright-button {background-position:-270px -18px;} #Kunena ul#kbbcode-toolbar li a#kbbcode-help-button {background-position:-396px -18px;} #Kunena .kspoiler { cursor:pointer; } #Kunena .kattachment .hasTip { display: inline; } #Kunena .kattachment .kbutton { /* font-size: 1em; */ } #Kunena #kattachments { line-height:18px; } #Kunena #kattachments a { background-repeat: no-repeat; display:inline-block; height:18px; width:18px; margin-right: 2px; } #Kunena #kattachments a { background-position:-216px -18px; } /* Define default image if not set in admin config */ #Kunena #kbbcode-toolbar li a, #Kunena #kattachments a { background-image:url("../../default/media/iconsets/editor/default/default.png"); } /* Multi file upload for bbcode editor -------------------------------------------------------------------- */ #kfilename {} #Kunena .kfile-input-textbox {/* float: left; */ display: inline-block; } #kupload {} #Kunena .kfile-hide { position: relative; width: 100px; height: 23px; overflow: hidden; } #Kunena .kfile-input-button, #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { top: 0px; background: none; font-size: .833em !important; border: 1px solid; padding: 3px 6px; cursor:pointer; } #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background: none; border: 1px solid; } #Kunena .kattachment-remove, #Kunena .kattachment-insert { background: none; font-size: .917em !important; border: 1px solid; padding: 3px 6px; } #Kunena .kattachment-remove:hover, #Kunena .kattachment-insert:hover { font-size:0.917em !important; padding: 3px 6px; } #Kunena .kattachment-insert { margin-left: 20px; } #Kunena .kfile-input { font-size: 23px; position: absolute; right: 0px; top: -10px; /* CSS3 standard */ opacity: 0; /* For IE */ filter:alpha(opacity=0); } #Kunena #kbbcode-filelist { padding: 0; list-style: none; margin: 0; } #Kunena #kbbcode-filelist .file-invalid { cursor: pointer; padding-left: 48px; line-height: 24px; margin-bottom: 1px; } #Kunena #kbbcode-filelist .file-invalid span { padding: 1px; } #Kunena #kbbcode-filelist .file { line-height: 2em; padding-left: 22px; } #Kunena #kbbcode-filelist .file span, #Kunena #kbbcode-filelist .file a { padding: 0 4px; } #Kunena #kbbcode-filelist .file .file-size { } #Kunena #kbbcode-filelist .file .file-error { } #Kunena #kbbcode-filelist .file .file-progress { width: 125px; height: 12px; vertical-align: middle; } /* POLLS -------------------------------------------------------------------- */ label.kpoll-title-lbl { display:inline-block; margin: 10px 15px 10px 5px; } label.kpoll-term-lbl { display:inline-block; margin: 10px 15px 10px 30px; } #kpoll-text-help { font-weight: bold; padding: 0px 10px; margin: 3px; } #kpoll-text-help p { padding: 5px 10px; } #kpoll-form-vote fieldset { border: 0 none; margin:0; padding:0; } #kpoll-form-vote legend { text-indent: -9999px; } #kpoll-form-vote ul { margin:0 0 0 20px; padding: 0; } #kpoll-form-vote ul li { list-style-type:none; line-height: 30px; list-style: none !important; } #kpoll-btns { margin: 5px 0 20px 20px; } #Kunena div.kpolldesc td.kpoll-option { text-align: left; width: 60%; padding: 3px 8px; } #Kunena div.kpolldesc td.kpoll-bar { text-align: left; width: 20%; } #Kunena div.kpolldesc td.kpoll-number, #Kunena div.kpolldesc td.kpoll-percent { text-align: center; width: 10%; } #Kunena #kpoll-button-vote { margin: 20px 20px 20px 30px; } /* PATHWAY ----------------------------------------------------------------------------------------------- */ #Kunena .kforum-pathway { padding: 5px; line-height: 18px; margin: -5px 0 0; border-left: 1px solid; border-right: 1px solid; } #Kunena .kforum-pathway-bottom { padding: 3px; line-height: 18px; margin: -1px 0 5px 0; border: 1px solid; } #Kunena .kforum-pathway-bottom img { vertical-align:text-bottom; } #Kunena .path-element-first { font-weight: normal; height: 18px; line-height: 18px; background: url("../../default/images/pathway_start.gif") no-repeat left center; display: inline; padding: 1px 3px 1px 22px; } #Kunena .path-element-first a:link, #Kunena .path-element-first a:visited { font-weight: normal; text-decoration: none; background: none; } #Kunena .path-element-last, #Kunena .path-element-last a:link { font-weight: bold; text-decoration: none; text-indent: 5px; display: inline; } #Kunena .kforum-pathway .path-element, #Kunena .kforum-pathway-bottom .path-element { background: url("../../default/images/icons/arrow.png") no-repeat left center; padding-left: 12px; display: inline; font-weight: normal; height: 18px; line-height: 18px; padding-right: 3px; } #Kunena .kforum-pathway .path-element-last, #Kunena .kforum-pathway-bottom .path-element-last { height: 18px; line-height: 18px; background: url("../../default/images/pathway_finallink.gif") no-repeat left center; padding: 1px 5px 1px 37px; } #Kunena .path-element-users { display: inline; margin-top: 21px; } /* FORUM HEADER DESCRIPTION -------------------------------------------------------------------- */ #Kunena .kforum-headerdesc { padding: 3px; line-height: 18px; margin: -1px 0 0 0; border: 1px solid; } #Kunena .kforum-headerdesc td{ padding: 8px; } /* HELP, RULES, UPLOAD AVATAR, ANNOUNCEMENT -------------------------------------------------------------------- */ #Kunena div.kannouncement h2 { table-layout:fixed; word-wrap:break-word; } #Kunena div#kannouncement .kanndesc { padding: 5px 10px; } #Kunena img.calendar { margin: 5px 0 -5px 5px; } #Kunena td.kuadesc, #Kunena td.kcreditsdesc { vertical-align: top; padding: 15px; /*border: 1px solid;*/ } #Kunena td.kcreditsdesc div.kfooter { text-align:center; } #Kunena .kcredits-intro { margin:5px; padding:15px 30px; text-align:left; border: 1px solid; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kteam { margin: 0; padding: 0; } #Kunena .kteammember { list-style-type:circle; margin:0 10px; padding:0; text-align:left; background: transparent none; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kcredits-more { padding: 10px 20px; margin: 15px; border: 1px solid; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kcredits-language { padding: 10px 20px; border: 1px solid; margin: 15px; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; } #Kunena .kstatsicon { background: url("../../default/images/icons/stats.png") no-repeat center top; width: 32px; height: 32px; } #Kunena div#searchuser_tbody div.search-user { padding:5px 10px; float: left; } #Kunena div#searchuser_tbody div.userlist-jump { float: right; } #Kunena tr.userlist th { padding: 3px; text-align: center; } #Kunena tr.userlist th a { color: #FFF !important; } #Kunena div#userlist_tbody td, #Kunena table#kuserlist_bottom th { padding: 4px 8px; } #Kunena div#userlist-tbody td { text-align: center; } #Kunena table#kuserlist-bottom div { text-align: center; padding: 3px; } /* STATISTICS PAGE ------------------------------------------------------------------- */ #Kunena tr.ksth th.kname { width: 50%; text-align: left; } #Kunena tr.ksth th.kbar { width: 40%; } #Kunena tr.ksth th.knr { width: 10%; } #Kunena div.kwhoisonline td.kcol-first, #Kunena div.kgenstats td.kcol-first, #Kunena div.kfrontstats td.kcol-first { width: 1%; } #Kunena div.kgenstats th { text-align: left !important; } #Kunena div.kedituser td.kcol-first, #Kunena div.keditavatar td.kcol-first, #Kunena div.keditprofile td.kcol-first, #Kunena div.keditsettings td.kcol-first { width: 120px; } #Kunena div.klogin div.kbody, #Kunena div.kinfomessage div.kbody { padding: 15px; text-align: center; } /* WHO IS ONLINE ------------------------------------------------------------------- */ #Kunena .kwhoicon { background: url("../../default/images/icons/who_is_online.png") no-repeat center top; width: 32px; height: 32px; } #Kunena khidden-ktitle {} #Kunena kwho-total {} #Kunena .kwholegend { border-top: 1px dotted; width: 100%; margin-top: 5px; padding-top: 5px; } #Kunena .kwhoonline { border-bottom: 1px dotted; width: 100%; padding-bottom: 5px; } #Kunena #kwhoispage td.td-3 { text-align:left; } /* MODERATOR PAGE -------------------------------------------------------------------- */ #Kunena div#kmod-container { /*border: 1px solid;*/ margin: 0; padding: 10px 10px 30px 10px; overflow:hidden; height: 1%; clear:left; } #Kunena div#kmod-container div { padding: 5px 0; } #Kunena div#kmod-leftcol { width: 47%; float:left; clear:left; } #Kunena div#kmod-rightcol { width: 47%; float:right; } #Kunena div.kmoderate-message { border:1px solid; padding:5px !important; margin:5px 0; display:inline-block; width:98%; } #Kunena div.kmoderate-message h4 { margin:0; padding:0; } #Kunena div.kmoderate-message div.kmessage-avatar { float:left; padding:5px 5px 0 0; } #Kunena div.kmoderate-message div.kmessage-msgtext { margin-left: 42px; } #Kunena td.krowmoderation input.kbutton { margin: 0 0 0 5px;; } #Kunena table#kaddban td.kcol-first { width: 35%; } #Kunena table#kaddban td.kcol-mid textarea { width: 100%; height: 50px; } #Kunena table#kaddban td.kcol-mid input { width: 100%; } #Kunena table#kforumsearch th { padding: 0px; } #Kunena td.krowmoderation { text-align: right; } #Kunena div.banhistory th.kid { width:2%; } #Kunena div.banhistory th.kbanfrom { width:14%; } #Kunena div.banhistory th.kbanstart, #Kunena div.banhistory th.kbanexpire, #Kunena div.banhistory th.kbancreate { width:20%; } #Kunena div.banhistory th.kbanmodify { width:24%; } /* PROFILE -------------------------------------------------------------------- */ #Kunena .kicon-profile { background-repeat: no-repeat; width: 16px; height: 16px; display: inline-block; vertical-align: text-top; margin-right: 3px; background-image: url("../../default/media/iconsets/profile/default/default.png"); } #Kunena span.kicon-profile-website, #Kunena span.kicon-profile-pm { vertical-align: top; margin-top: 3px; } #Kunena .kicon-profile-aim { background-position: 0 0; } #Kunena .kicon-profile-bebo { background-position: 0 -21px; } #Kunena .kicon-profile-birthdate { background-position: 0 -42px; } #Kunena .kicon-profile-blogspot { background-position: 0 -63px; } #Kunena .kicon-profile-delicious { background-position: 0 -84px; } #Kunena .kicon-profile-digg { background-position: 0 -105px; } #Kunena .kicon-profile-email { background-position: 0 -126px; } #Kunena .kicon-profile-facebook { background-position: 0 -147px; } #Kunena .kicon-profile-gender-female { background-position: 0 -168px; } #Kunena .kicon-profile-flickr { background-position: 0 -189px; } #Kunena .kicon-profile-friendfeed { background-position: 0 -210px; } #Kunena .kicon-profile-gender-unknown { background-position: 0 -231px; } #Kunena .kicon-profile-gtalk { background-position: 0 -252px; } #Kunena .kicon-profile-icq { background-position: 0 -273px; } #Kunena .kicon-profile-karmaminus { background-position: 0 -294px; } #Kunena .kicon-profile-karmaplus { background-position: 0 -313px; } #Kunena .kicon-profile-linkedin { background-position: 0 -332px; } #Kunena .kicon-profile-location { background-position: 0 -353px; } #Kunena .kicon-profile-gender-male { background-position: 0 -374px; } #Kunena .kicon-profile-msn { background-position: 0 -395px; } #Kunena .kicon-profile-myspace { background-position: 0 -416px; } #Kunena .kicon-profile-pm { background-position: 0 -437px; } #Kunena .kicon-profile-remind { background-position: 0 -458px; } #Kunena .kicon-profile-skype { background-position: 0 -479px; } #Kunena .kicon-profile-twitter { background-position: 0 -500px; } #Kunena .kicon-profile-website { background-position: 0 -521px; } #Kunena .kicon-profile-yim { background-position: 0 -542px; } #Kunena .kicon-profile-aim-off { background-position: 0 -563px; } #Kunena .kicon-profile-bebo-off { background-position: 0 -584px; } #Kunena .kicon-profile-birthday-off { background-position: 0 -605px; } #Kunena .kicon-profile-blogspot-off { background-position: 0 -626px; } #Kunena .kicon-profile-delicious-off { background-position: 0 -647px; } #Kunena .kicon-profile-digg-off { background-position: 0 -668px; } #Kunena .kicon-profile-facebook-off { background-position: 0 -689px; } #Kunena .kicon-profile-flickr-off { background-position: 0 -710px; } #Kunena .kicon-profile-friendfeed-off { background-position: 0 -731px; } #Kunena .kicon-profile-gender-off { background-position: 0 -752px; } #Kunena .kicon-profile-gtalk-off { background-position: 0 -773px; } #Kunena .kicon-profile-icq-off { background-position: 0 -794px; } #Kunena .kicon-profile-linkedin-off { background-position: 0 -815px; } #Kunena .kicon-profile-msn-off { background-position: 0 -836px; } #Kunena .kicon-profile-myspace-off { background-position: 0 -857px; } #Kunena .kicon-profile-pm-off { background-position: 0 -878px; } #Kunena .kicon-profile-remind-off { background-position: 0 -899px; } #Kunena .kicon-profile-skype-off { background-position: 0 -920px; } #Kunena .kicon-profile-twitter-off { background-position: 0 -941px; } #Kunena .kicon-profile-website-off { background-position: 0 -962px; } #Kunena .kicon-profile-yim-off { background-position: 0 -983px; } #Kunena div#kprofile-leftcol { width: 200px; font-size: 1em; float:left; /*margin-right: 10px;*/} #Kunena div.kavatar-lg { width: 200px; height: 200px; border: 1px solid; display: table-cell; vertical-align:middle; text-align:center; } #Kunena div.kavatar-lg img { } #Kunena div#kprofile-stats { margin-top: 15px;} #Kunena div#kprofile-stats ul { margin: 0 0 0 3px; padding: 0;} #Kunena div#kprofile-stats ul li { list-style-type: none; padding-top: 5px; clear:both; font-size:.917em ;} #Kunena div#kprofile-stats ul li span.konline-status-yes { display:block; background: url("../../default/images/icons/online.gif") no-repeat; height: 16px; width: 70px; } #Kunena div#kprofile-stats ul li span.konline-status-no { display:block; background: url("../../default/images/icons/offline.gif") no-repeat; height: 16px; width: 70px; } div#kprofile-stats ul li span.krankname { display:block; margin-right: 5px; font-weight:bold; float:left; } div#kprofile-stats ul li span.krank-admin { display:block; background: url("../../default/images/ranks/rankadmin.gif") no-repeat; height: 16px; width: 70px; margin-right: 5px; float:right; margin-top: 0; } #Kunena div#kprofile-rightcol { /*display:inline-block; float:left; margin-left:10px; width:75%;*/ } #Kunena table#kprofile td.kcol-left { padding: 10px 10px 30px; vertical-align: top; } #Kunena table#kprofile td.kcol-right { border-left: 0; padding: 10px 10px 30px; vertical-align: top; } #Kunena div#kprofile-rightcoltop {width: 100%;} #Kunena div.kprofile-rightcol1 { width: 45%; } #Kunena div.kprofile-rightcol1 ul {margin: 0;padding: 0;} #Kunena div.kprofile-rightcol1 ul li, #Kunena div.kprofile-rightcol2 ul li { list-style-type: none !important; background: 0 none; padding-bottom: 8px; padding-left: 0; } #Kunena div#kprofile-stats ul li { list-style-type: none !important; background: 0 none; padding-left: 0; } #Kunena li.bd a { margin-left: 10px; } #Kunena div.kiconrow { width: 121px; padding-right: 10px; padding-bottom: 5px; float:left; } #Kunena div.kiconrow span, #Kunena div.kiconprofile span { background-repeat: no-repeat; display:block; float:left; margin: 0 5px 5px 0; border: 0 none; } #Kunena div.kiconprofile span.birthday { background-image: none; border: 0 none; } #Kunena div.clrline { clear:both; border-top: 1px solid; margin: 15px 0 20px 0; line-height: 10px; } #Kunena div#kprofile-rightcolbot { } #Kunena div.kprofile-rightcol1 h4 { margin:10px 0 0 0; padding: 0; font-size: 1em; font-weight:bold;} #Kunena div.kprofile-rightcol1 p { margin:0; padding: 0;} #Kunena div.kprofile-rightcol2 { float:right; width: 45%; margin-left: 10px;} #Kunena div.kprofile-rightcol2 ul {margin: 0;padding: 0;} #Kunena div.kprofile-rightcol2 ul li {list-style-type: none !important; padding-bottom: 8px;} #Kunena div.kprofile-rightcol2 ul li span.email { float:left; display:block; background: url("../../default/images/icons/email.png") no-repeat; height: 16px; width: 16px; margin-right: 5px; } #Kunena div.kprofile-rightcol2 ul li span.website { float:left; margin-right: 5px; } #Kunena dd.kprofile-modtools h4 { margin-bottom: 5px; margin-left: 5px; } #Kunena dd.kprofile-modtools ul li span { margin-right: 15px; } #Kunena dd.kprofile-modtools ul li { padding-bottom: 5px; } #Kunena li.usertype { font-weight:bold; } #Kunena li.kprofile-rank { } #Kunena li.kprofile-rank img { } /* Tabs ----------------------------------*/ #Kunena #kprofile-tabs { width: 100%; margin-top: 0px; } #Kunena dl.tabs { float: left; margin: 10px 0 -1px 0; z-index: 50; } #Kunena dl.tabs dt { float: left; padding: 4px 10px; border-left: 1px solid; border-right: 1px solid; border-top: 1px solid; margin-left: 3px; } #Kunena dl.tabs dt.open { border-bottom: 1px solid; z-index: 100; } #Kunena div.current { clear: both; border: 1px solid; padding: 10px 10px; overflow: hidden; } #Kunena div.current dd { padding: 0; margin: 0; } #Kunena dt.kprofile-modbtn { } #Kunena dd.kprofile-modtools ul { margin:0; padding:0; margin-left: 5px; } #Kunena dd.kprofile-modtools ul li { list-style-type:none; } #Kunena dd.kprofile-modtools .kcheckbox { float:left; clear:left; } #Kunena dd.kprofile-modtools label { float:left; clear:right; margin: 3px 10px 10px 5px; } #Kunena input.kbutton { margin: 10px 0 0 5px; } #Kunena form#jumpto { margin: 5px; } #Kunena form#jumpto input.kbutton { margin: 0px;} #Kunena table.klist-top td.klist-markallcatsread input.kbutton { vertical-align:middle; margin: 5px;} /* SLIDERS ----------------------------------------------------------------------------------------------- */ #Kunena span#kprofilebox-status { font-weight:bold; display:block; height: 14px; width: 15px; } #Kunena #kprofilebox-toggle { display:block; height: 15px; width: 15px; margin-right: 1px; margin-top: -14px; border: 1px solid; } #Kunena a.close { display:block; background: url("../../default/images/shrink.gif") no-repeat; height: 15px; width: 15px; } #Kunena a.open { display:block; background: url("../../default/images/expand.gif") no-repeat; height: 15px; width: 15px; } /* FOOTER ----------------------------------------------------------------------------------------------- */ #Kunena .kcredits { text-align: center; } #Kunena .kfooter { text-align: center; } #Kunena img.rsslink { float:right; margin-top: 10px; margin-right: 3px; } /* Mootools Autocompleter CSS classes ----------------------------------------------------------------------------------------------- */ /* DO NOT ADD #Kunena into these rules! */ ul.autocompleter-choices { position: absolute; margin: 0; padding: 0; list-style: none; border: 1px solid; text-align: left; z-index: 50; } ul.autocompleter-choices li { position: relative; margin: -2px 0 0 0; padding: 0.2em 1.5em 0.2em 1em; display: block; float: none !important; cursor: pointer; font-weight: normal; white-space: nowrap; font-size: 1em; line-height: 1.5em; } ul.autocompleter-choices li.kautocompleter-selected { } ul.autocompleter-choices span.kautocompleter-queried { display: inline; float: none; font-weight: bold; margin: 0; padding: 0; } ul.autocompleter-choices li.kautocompleter-selected span.kautocompleter-queried { } /* for form-validation ------------------------------------------------------ */ #Kunena #kpost-message .invalid { border: 1px solid !important; } /* SHOW ICONS ----------------------------------------------------------------------------------------------- */ #Kunena span.kicon { background: none; border: 0; margin: 0; padding: 0; display: inline-block; } #Kunena span.ktopicattach { background: url("../../default/images/icons/attachment.png") no-repeat left center; margin: 2px; width: 32px; height: 32px; float:right; } #Kunena span.kfavoritestar { background: url("../../default/images/icons/favoritestar.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.kfavoritestar-grey { background: url("../../default/images/icons/favoritestar-grey.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.ktopiclocked, #Kunena span.kforumlocked { background: url("../../default/images/icons/lock_sm.png") no-repeat left center; width: 16px; height: 16px; } #Kunena span.ktopicsticky { background: url("../../default/images/icons/tsticky.png") no-repeat left center; width: 27px; height: 44px; float:right; margin-right: -5px; } #Kunena span.kforumbottom { background: url("../../default/images/icons/bottom_arrow.gif") no-repeat left center; width: 18px; height: 15px; } #Kunena span.kforumtop { background: url("../../default/images/icons/top_arrow.gif") no-repeat left center; width: 18px; height: 15px; } #Kunena span.krss { background: url("../../default/images/icons/rss.png") no-repeat left center; width: 24px; height: 24px; margin: 5px 5px 0 -29px; } #Kunena span.kpdf { background: url("../../default/images/icons/pdf.png") no-repeat left center; width: 24px; height: 24px; margin: 5px 33px 0 -29px; } #Kunena div.krss-block { float: right; } #Kunena span.kforummoderated { background: url("../../default/images/icons/tmoder.gif") no-repeat left center; width: 16px; height: 16px; } #Kunena span.kreadforum, #Kunena span.knotloginforum { background: url("../../default/images/icons/folder_nonew.png") no-repeat left center; width: 32px; height: 32px; } #Kunena span.kunreadforum { background: url("../../default/images/icons/folder.png") no-repeat left center; width: 32px; height: 32px; } #Kunena span.kreadforum-sm, #Kunena span.knotloginforum-sm { background: url("../../default/images/icons/folder_nonew_sm.png") no-repeat left center; width: 12px; height: 12px; margin-right: 3px; vertical-align: middle; } #Kunena span.kunreadforum-sm { background: url("../../default/images/icons/folder_sm.png") no-repeat left center; width: 12px; height: 12px; margin-right: 3px; vertical-align: middle; } .kgooglemap { width: 100%; display:block; height:480px; overflow:hidden; position:relative; } .kgooglemap img { max-width:none !important; } /* Fix for Atomic Template */ #ktab .joomla-nav { background-color: transparent; border: 0 none; } /* Threaded view ----------------------------------------------------------------------------------------------- */ #Kunena .ktree { width: 15px; height: 27px; margin: -9px 0; display: inline-block; background: url("../../default/images/treenodes.png") no-repeat left center; } #Kunena .ktree-crossedge { background-position: -45px 0; } #Kunena .ktree-lastedge { background-position: -75px 0; } #Kunena .ktree-root { background-position: -15px 0; } #Kunena .ktree-single { background-position: 0 0; } #Kunena .ktree-leaf { background-position: -90px 0; } #Kunena .ktree-node { background-position: -60px 0; } #Kunena .ktree-edge { background-position: -30px 0; } #Kunena .ktree-gap { background-position: -105px 0; } #Kunena .ktree-empty { background: none; } /*** kunena.default.css ***/ @charset "utf-8"; /** * @version $Id$ * Kunena Component * @package Kunena * * @Copyright (C) 2008 - 2011 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org * * Based on FireBoard Component * @Copyright (C) 2006 - 2007 Best Of Joomla All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.bestofjoomla.com * **/ /* ------------------------- COLOR PALETTE FOR BLUE EAGLE Dark blue color: #5388B4 RGB: 83/136/180 Medium blue color: #609FBF RGB: 96/159/191 Light grey color: #F2F1EE RGB: 242/241/238 Medium grey color: #999999 RGB: 153/153/153 Dark grey color: #737373 RGB: 115/115/115 Border grey color: #BFC3C6 RGB: 191/195/198 Yellow highlight: #FFFFCC RGB: 255/255/204 Grey text color: #999999 RGB: 153/153/153 Red hover color: #FF0000 RGB: 255/0/0 Forum highlight/dark colors Green forum highlight: #d2f8db RGB: 210/248/219 Green forum dark: #bfe5c7 RGB: 191/229/199 Orange forum highlight: #ffeb8c RGB: 255/235/140 Orange forum dark: #ffd475 RGB: 255/212/117 Blue forum highlight: #c3f0ff RGB: 195/240/255 Blue forum dark: #b1e3ff RGB: 177/227/255 Grey forum highlight: #e5e5e5 RGB: 229/229/229 Grey forum dark: #d5d5d5 RGB: 213/213/213 Pink forum highlight: #ffddff RGB: 255/221/255 Pink forum dark: #ffd0ff RGB: 255/208/255 ----------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------- */ /* MAIN STYLES ----------------------------------------------------------------------------------------------- */ #Kunena td, #Kunena table, #Kunena th, #Kunena div, #Kunena p, #Kunena span { font-family: Arial, Helvetica, sans-serif; } #Kunena ul li { background: none; } #Kunena .divider {color:#999999;} #Kunena a:link, #Kunena a:visited, #Kunena a:active, #Kunena a:focus { color: #5388B4 !important; background-color:transparent !important;} #Kunena a:hover { color: #FF0000 !important; background-color:transparent !important; } #Kunena .knewchar { color: #009900; font-family: Arial, Helvetica, sans-serif; } /* Block styling ----------------------------------------------------------------------------------------------- */ #Kunena div.kblock { border-bottom-color:#BFC3C6; background-color: #FFFFFF; } #Kunena .kblock div.kheader { border-bottom-color:#D9D9D9; color: #FFFFFF; } #Kunena .kheader h2, #Kunena .kheader h2 a { color: #fff !important; } #Kunena div.kblock div.ktitle { background-color: #5388B4; color: #FFFFFF; } #Kunena div.kblock div.ktitle h1, #Kunena div.kblock div.ktitle h2 { color: #FFFFFF; } #Kunena div.kblock div.kbody { border-color:#BFC3C6; } #Kunena div.kblock div.khelprulescontent, #Kunena div.kblock div.kfheadercontent { background-color: #FFFFFF; color: #000000; } #Kunena div.kblock div.khelprulesjump { border-color: #BFC3C6; background-color: #FFFFFF; color: #000000; } #Kunena div.kblock div.kactions { background-color: #737373; color:#FFFFFF ; } #Kunena div.kblock div.kactions a { color:#FFFFFF !important; } #Kunena tr.krow1 td { background-color: #F2F1EE; } #Kunena tr.krow2 td { background-color: #FFFFFF; } #Kunena tr.ksth { background-color: #737373; color: #fff; font-family: Arial, Helvetica, sans-serif; } #Kunena td.kcol-ktopicreplies { color: #999999; } #Kunena td.kcol-ktopicreplies strong { color: #999999; } #Kunena span.kcat-topics, #Kunena span.kcat-replies { color:#999999; } #Kunena span.kcat-topics-number, #Kunena span.kcat-replies-number { color: #999999; } #Kunena .klatest-avatar, #Kunena .ktopic-latest-post-avatar { border-color: #BFC3C6; } #Kunena .kfooter-time { color: #999999; } #Kunena .kalert { color: #FF0000; } #Kunena td.kcol-first { border-bottom-color: #BFC3C6; } #Kunena td.kcol-mid { border-left-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena td.kcol-last { border-left-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena td.ktopicmodule { border-bottom-color: #BFC3C6; } /* COLOR ADMINISTRATOR AND MODERATOR ----------------------------------------------------------------------------------------------- */ #Kunena .kwho-admin, #Kunena a.kwho-admin { color: #FF0000 !important; } #Kunena .kwho-globalmoderator, #Kunena a.kwho-globalmoderator { color: #800000 !important; } #Kunena .kwho-moderator, #Kunena a.kwho-moderator { color: #0000FF !important; } #Kunena .kwho-user, #Kunena a.kwho-user { color: #5388B4 !important; } #Kunena .kwho-guest, #Kunena a.kwho-guest { color: #666666 !important; } #Kunena .kwho-banned , #Kunena a.kwho-banned { color: #A39D49 !important; } #Kunena .kwho-blocked, #Kunena a.kwho-blocked { color: #ff0000 !important; } /* MENU ----------------------------------------------------------------------------------------------- */ #Kunena #ktop { background-color: transparent; color: #000000; } #ktab div.moduletable ul.menu, #ktab div.moduletable ul.menu li a, #ktab div.moduletable ul.menu li a span { background-image:none!important; } #Kunena #ktab a { background-color: #737373; } #Kunena #ktab a span { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena #ktab a:hover span, #Kunena #ktab li.Kunena-item-active a span { color: #FFFFFF; } #Kunena select, #Kunena select:focus, #Kunena select:hover { border-color: #999999; color: #000000; } /* Using a Joomla menu module */ #Kunena option { background-color: #FFFFFF; color: #000000; } #Kunena .button, #Kunena .kbutton { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kbutton-back { color: #000000; } #Kunena input.kinput { border-color: #999999; } #Kunena .kbutton:hover, #Kunena .kbutton:focus { background-color: #609FBF; border-color: #5388B4; color: #FFFFFF; } #Kunena .klist-actions { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena .klist-actions-bottom { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena .klist-actions-info a { color: #009933; } #Kunena .klist-pages { border-left-color: #BFC3C6; color: #666666; font-family: Arial, Helvetica, sans-serif; } #Kunena .klist-times { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-actions-info-all { color: #999999; } #Kunena .klist-actions-forum { border-left-color: #BFC3C6; } #Kunena .klist-pages-all { border-left-color: #BFC3C6; color: #666666; font-family: Arial, Helvetica, sans-serif; } #Kunena .klist-times-all { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-jump-all { border-left-color: #BFC3C6; color: #666666; } #Kunena .klist-top { background-color: #FFFFFF; border-color: #BFC3C6; } #Kunena .klist-bottom { background-color:#FFFFFF; border-color:#BFC3C6; } #Kunena .klist-markallcatsread { border-color: #BFC3C6; background-color: #FFFFFF; } #Kunena .klist-categories { border-left-color: #BFC3C6; color: #666666; } /*---------- Pagination ------------- */ #Kunena .kpagination a { border-color:#5388B4; background-color: #ffffff !important; } #Kunena .kpagination .active { border-color:#5388B4; background-color:#5388B4; color:#FFFFFF; } #Kunena .kpagination a:link, #Kunena .kpagination a:visited { color:#5388B4; } #Kunena .kpagination a:hover{ border-color:#5388B4; color: #ffffff; background-color: #609FBF; } #Kunena div.ktopic-title-cover ul.kpagination li.page { color:#999; } #Kunena div.ktopic-title-cover ul.kpagination a { border-color:#bcbcbc; background-color: #ffffff; } #Kunena div.ktopic-title-cover ul.kpagination a:hover{ border-color:#5388B4; color: #ffffff; background-color: #609FBF; } #Kunena span.ktopic-views { color:#999999; } #Kunena span.ktopic-views-number { color: #999999; } /* HEADER ----------------------------------------------------------------------------------------------- */ #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton { background-color: #fff; } #Kunena td.kprofileboxcnt ul.kprofilebox-welcome li input.kbutton:hover { background-color: #609FBF; } #Kunena div#kforum-head { border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-bottom-color: #BFC3C6; } #Kunena div#kmoderatorslist div.kbody { border-color:#CCCCCC; background-color: #FFFFFF; } /* SEARCH ----------------------------------------------------------------------------------------------- */ #Kunena fieldset { background-color: #fff; border-color:#CCCCCC; } #Kunena div#ksearchresult div.kresult-title { border-bottom-color: #DDDDDD; } #Kunena div#ksearchresult div.resultcat { border-top-color: #BFC3C6; } /* PROFILEBOX AND LOGINBOX ----------------------------------------------------------------------------------------------- */ #Kunena .kprofilebox-left { border-right-color: #BFC3C6; background-color: #EEEEEE; } #Kunena .kprofilebox-right { border-left-color: #BFC3C6; } #Kunena div.kpbox { border-bottom-color: #BFC3C6; } /* CATEGORY LIST ----------------------------------------------------------------------------------------------- */ #Kunena table.kblocktable { border-color: #BFC3C6; } #Kunena h1, #Kunena h2 { color: #FFFFFF; } #Kunena h2 a { color: #FFFFFF !important; } #Kunena h1 a:link, #Kunena h1 a:active, #Kunena h1 a:visited { color: #FFFFFF; } #Kunena h2 span.kheadbtn a { border-color: #FFF; background-color: #609FBF; } #Kunena h2 span.kheadbtn:hover a { border-color: #FFF; } #Kunena .ktitle, #Kunena a.ktitle { color: #FFFFFF; } #Kunena .ktitle a { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena div.kthead-title a { font-family: Lucida Grande, Lucida, Arial, Helvetica, sans-serif; } #Kunena div.kthead-moderators { color: #666; } #Kunena div.kthead-child { border-top-color: #DDD5BF; } #Kunena table.kcc-table tr td { border-color: #FFFFFF; } #Kunena div.kcc-childcat-title { color: #666666; } #Kunena span.kchildcount { color: #999999; } /* SHOW CATEGORY ----------------------------------------------------------------------------------------------- */ #Kunena img.catavatar { border-color: #BFC3C6; } #Kunena .kcontenttablespacer { border-bottom-color: #BFC3C6; } #Kunena .krow1-stickymsg { background-color: #FFFFCC; } #Kunena .krow2-stickymsg { background-color: #FFFFCC; } /* VIEW PAGE -------------------------------------------------------------------- */ #Kunena div.kmsg-header { border-bottom-color:#D9D9D9; background-color: #5388B4; color: #FFFFFF; } #Kunena div.kmsg-header h2 { background-color: #737373; } #Kunena .kpost-profile span.kavatar img, #Kunena .kprofilebox .kavatar { border-color: #BFC3C6; } #Kunena span.kmsgdate { font-family: Arial, Helvetica, sans-serif; color: #FFFFFF; } #Kunena div.kmsgattach { background-color:#F8F7EF; border-color:#BFC3C6; } #Kunena div.kmsgtext pre, #Kunena div.kmsgtext code { border-left-color: #F4A94F; border-right-color: #BFC3C6; border-top-color: #BFC3C6; border-bottom-color: #BFC3C6; font-family: "Courier News", Courier, monospace; } #Kunena table.kmsg th a { color: #FFFFFF; } #Kunena div.kmessage-editmarkup-cover { border-bottom-color: #BFC3C6; } #Kunena span.kmessage-editmarkup { background-color: #F2F1EE no-repeat left center; border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; color: #666666; } #Kunena span.kmessage-informmarkup { background-color: #F2F1EE; border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; color: #666666; } #Kunena div.kmsgsignature { border-top-color:#BFC3C6; color:#999999; } #Kunena div.kmessage-thankyou{ border-top-color: #BFC3C6; } #Kunena .kreply-form { border-color: #BFC3C6; } #Kunena .kreply-form .inputbox { border-color: #999999; background-color: #FFFFFF; color: #000000; } #Kunena div.kmsgtext-article, #Kunena div.kmsgtext-quote, #Kunena div.kmsgtext-hide, #Kunena div.kmsgtext-confidential { border-color: #BFC3C6; font-family: Arial, Helvetica, sans-serif; background-color: #F2F1EE; } #Kunena div.kmsgtext-article { background-color: #FFFFFF; } #Kunena div.kmsgtext-hide { background-color: #FFFFCC; } #Kunena div.kmsgtext-confidential { background-color: #FAE0F8; } #Kunena div.khide { background-color: #F2F1EE; border-color: #F2CAB7; } #Kunena .kmsgtitle { color: #fff ; } #Kunena div.kmsg-header-top span.kmsg-id-top a, #Kunena div.kmsg-header-bottom span.kmsg-id-bottom a, #Kunena div.kmsg-header-left span.kmsg-id-left a, #Kunena div.kmsg-header-right span.kmsg-id-right a { color: #fff !important; } /* AVATAR POSITION ----------------------------------------------------------------------- */ /* right ----------------------------------------*/ #Kunena td.kprofile-right { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-left-color: #DDDDDD; } #Kunena td.kbuttonbar-right { border-bottom-color: #BFC3C6; } /* left ----------------------------------------*/ #Kunena td.kprofile-left { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-right-color: #DDDDDD; } #Kunena td.kbuttonbar-left { border-bottom-color: #BFC3C6; } #Kunena .kunapproved td { background-color: #DDDDDD !important; } #Kunena .kdeleted td { background-color: #CCCCCC !important; } /* User info on posts ----------------------------------------*/ #Kunena td.kprofile-top { background-color: #EFF0F4; border-bottom-color: #DDDDDD; } #Kunena td.kbuttonbar-top { border-bottom-color: #BFC3C6; } /* bottom ----------------------------------------*/ #Kunena td.kprofile-bottom { background-color: #EFF0F4; border-bottom-color: #BFC3C6; border-top-color: #DDDDDD; } /* POST PAGE -------------------------------------------------------------------- */ #Kunena #kpost-message .postinput { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpost-message .postinput:hover, #Kunena #kpost-message .postinput:focus { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpostmessage tr.krow2 td.kcol-ktopicicons td { background-color: #FFFFFF; color: #000000; border-color: #BFC3C6; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td.kposthint { background-color: #FFFFCC; border-color: #DDD5BF; } #Kunena table#kpostmessage .kposthint .kinputbox { background-color: #FFFFCC; border-color: #FFFFCC; } #Kunena .kpostbuttonset { border-color: #BFC3C6 } #Kunena tr.krow1 .kpostbuttons { border-color: #BFC3C6; } #Kunena table#kpostmessage .ktxtarea { border-color: #BFC3C6; } #Kunena div#khistory tr.ksth a { color: #ffffff; } /* ---- Post Previews ---- */ #Kunena #kbbcode-preview { border-color: #BFC3C6; background-color: #F2F1EE; } #Kunena #kpostmessage tr.krow1 .kpostbuttonset td, #Kunena #kpostmessage tr.krow2 .kpostbuttonset td { border-bottom-color: #BFC3C6; } #Kunena #kpost-result div { border-color: #999; } #Kunena div#kcolor-palette, #Kunena div#link, #Kunena div#image, #Kunena div#video { border-bottom-color: #BFC3C6; } /* FORUM ICON BUTTONS ----------------------------------------------------------------------------------------------- */ #Kunena .kicon-button { color: #FFF; } #Kunena .kicon-button span span { color: #ffffff; } #Kunena form.kform-report input, #Kunena form.kform-report textarea { border-color:#BFC3C6; } /* BBCODE BUTTONS -------------------------------------------------------------------- */ #Kunena img.kbbcode:hover { background-color: #e4e4e4; } #Kunena div#kbbcode-size-options span:hover { background-color: #e4e4e4; } #Kunena #kbbcode-toolbar li a:hover { background-color: #e4e4e4; } #Kunena ul#kbbcode-toolbar li a#kbbcode-separator1, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator2, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator3, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator4, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator5, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator6, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator7, #Kunena ul#kbbcode-toolbar li a#kbbcode-separator8 { background-color: #eeeeee; } #Kunena .kattachment .kbutton { color: #000000; } /* Multi file upload for bbcode editor -------------------------------------------------------------------- */ #Kunena .kfile-input-button, #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kfile-input-button:hover, #Kunena .kfile-input-button:focus { background-color: #609FBF; border-color: #5388B4; color: #FFFFFF; } #Kunena .kattachment-remove, #Kunena .kattachment-insert { background-color: #F2F1EE; border-color: #999999; color: #000000; } #Kunena .kattachment-remove:hover, #Kunena .kattachment-insert:hover { color: #FFFFFF; } #Kunena #kbbcode-filelist .file-invalid { color: #514721; } #Kunena #kbbcode-filelist .file-invalid span { background-color: #fff6bf; } #Kunena #kbbcode-filelist .file .file-size { color: #666; } #Kunena #kbbcode-filelist .file .file-error { color: #8a1f11; } /* POLLS -------------------------------------------------------------------- */ #kpoll-text-help { background-color: #ff8f4f; } #kpoll-form-vote fieldset { background-color:#FFFFFF; } /* PATHWAY ----------------------------------------------------------------------------------------------- */ #Kunena .kforum-pathway { border-left-color: #BFC3C6; border-right-color: #BFC3C6; color: #000000; background-color: #F2F1EE; } #Kunena .kforum-pathway-bottom { border-color: #BFC3C6; color: #000000; background-color: #F2F1EE; } /* FORUM HEADER DESCRIPTION -------------------------------------------------------------------- */ #Kunena .kforum-headerdesc { border-color: #BFC3C6; color: #000000; background-color: #FFF; } /* HELP, RULES, UPLOAD AVATAR, ANNOUNCEMENT -------------------------------------------------------------------- */ #Kunena td.kuadesc, #Kunena td.kcreditsdesc { /*border-color: #BFC3C6;*/ background-color: #FFFFFF; color: #000000; } #Kunena .kcredits-intro { border-color: #BFC3C6; } #Kunena .kcredits-more { background-color: #F2F1EE; border-color: #BFC3C6; } #Kunena .kcredits-language { border-color: #BFC3C6; } #Kunena tr.userlist th a { color: #FFFFFF; } /* WHO IS ONLINE ------------------------------------------------------------------- */ #Kunena .kwholegend { border-top-color: #CCCCCC; } #Kunena .kwhoonline { border-bottom-color: #CCCCCC; } /* MODERATOR PAGE -------------------------------------------------------------------- */ #Kunena div#kmod-container { /*border-color: #BFC3C6;*/ } #Kunena div.kmoderate-message { border-color:#CCCCCC; } } /* PROFILE -------------------------------------------------------------------- */ #Kunena div.kavatar-lg { background-color: #FFF; border-color: #999999; } #Kunena div#kprofile-stats ul li span.konline-status-yes { color: #fff; } #Kunena div#kprofile-stats ul li span.konline-status-no { color:#fff; } #Kunena div.clrline { border-top-color: #BFC3C6; } #Kunena div.kprofile-rightcol1 h4 { color: #333333;} /* Tabs ----------------------------------*/ #Kunena dl.tabs dt { border-left-color: #BFC3C6; border-right-color: #BFC3C6; border-top-color: #BFC3C6; background-color: #f0f0f0; color: #666; } #Kunena dl.tabs dt.open { background-color: #F9F9F9; border-bottom-color: #F9F9F9; color: #000; } #Kunena div.current { border-color: #BFC3C6; } #Kunena dt.kprofile-modbtn { background-color:#999999 !important; color: #FFF !important; } /* SLIDERS ----------------------------------------------------------------------------------------------- */ #Kunena span#kprofilebox-status { color: #fff; background-color: #5388B4; } #Kunena #kprofilebox-toggle { border-color: #fff; } /* Mootools Autocompleter CSS classes ----------------------------------------------------------------------------------------------- */ /* DO NOT ADD #Kunena into these rules! */ ul.autocompleter-choices { border-color: #7c7c7c; border-left-color: #c3c3c3; border-right-color: #c3c3c3; border-bottom-color: #ddd; background-color: #fff; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; background-color: #fff; } ul.autocompleter-choices li.kautocompleter-selected { background-color: #444; color: #fff; } ul.autocompleter-choices li.kautocompleter-selected span.kautocompleter-queried { color: #9FCFFF; } /* CSS suffix support for category specific styling (Leave this section at the bottom) ----------------------------------------------------------------------------------------------- */ /* -red category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-red { color: #000000; background-color: #FFDDDD; } #Kunena tr.krow1-red td { background-color: #FFDDDD; } #Kunena tr.krow2-red td { background-color: #FFCFCF; } /* -green category suffix ----------------------------------------------------- */ #Kunena .kforum-headerdesc-green { background-color: #d2f8db; } #Kunena tr.krow1-green td { background-color: #d2f8db; } #Kunena tr.krow2-green td { background-color: #bfe5c7; } /* -yellow category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-yellow { color: #000000; background-color: #FFFFCC; } #Kunena tr.krow1-yellow td { background-color: #FFFFCC; } #Kunena tr.krow2-yellow td { background-color: #FFFFAA; } /* -blue category suffix ------------------------------------------------------- */ #Kunena .kforum-headerdesc-blue { color: #000000; background-color: #c3f0ff; } #Kunena tr.krow1-blue td { background-color: #c3f0ff; } #Kunena tr.krow2-blue td { background-color: #b1e3ff; } /* -grey category suffix ------------------------------------------------------ */ #Kunena .kforum-headerdesc-grey { color: #000000; background-color: #e5e5e5; } #Kunena tr.krow1-grey td { background-color: #e5e5e5; } #Kunena tr.krow2-grey td { background-color: #d5d5d5; } /* -pink category suffix ---------------------------------------------------- */ #Kunena .kforum-headerdesc-pink { color: #000000; background-color: #ffddff; } #Kunena tr.krow1-pink td { background-color: #ffddff; } #Kunena tr.krow2-pink td { background-color: #ffd0ff; } /* for form-validation ------------------------------------------------------ */ #Kunena #kpost-message .invalid { border-color: red !important; background-color: #FFDDDD !important; } /* SHOW ICONS ----------------------------------------------------------------------------------------------- */ .kgooglemap { background-color:#E5E3DF; }
crosslink/huai
components/com_kunena/template/example/css/css-ad511544f6303b617227b4948cdd904d.php
PHP
gpl-3.0
93,030
const merge = require("merge"); function fakeOne(modelName, overrides) { const model = require("../models/" + modelName); const fakeData = require("../fakers/" + modelName); instance = new model(merge.recursive(true, fakeData(), overrides)); return instance.save(); } module.exports = (modelName, count, overrides) => new Promise((resolve, reject) => { if (!overrides) { overrides = {}; } if (!count) { return resolve(fakeOne(modelName, overrides)); } const instances = []; for (let i = 0; i < count; i++) { instances[i] = fakeOne(modelName, overrides); } Promise.all(instances) .then(x => resolve(x)) .catch(e => reject(e)); });
BlackChaosNL/dragontide
lib/fake.js
JavaScript
gpl-3.0
660
var searchData= [ ['flash_2ec',['flash.c',['../flash_8c.html',1,'']]], ['flash_2eh',['flash.h',['../flash_8h.html',1,'']]], ['flash_5fcommon_5ff234_2ec',['flash_common_f234.c',['../flash__common__f234_8c.html',1,'']]], ['flash_5fcommon_5ff234_2ed',['flash_common_f234.d',['../flash__common__f234_8d.html',1,'']]], ['flash_5fcommon_5ff234_2eh',['flash_common_f234.h',['../flash__common__f234_8h.html',1,'']]], ['flash_5fcommon_5ff24_2ec',['flash_common_f24.c',['../flash__common__f24_8c.html',1,'']]], ['flash_5fcommon_5ff24_2ed',['flash_common_f24.d',['../flash__common__f24_8d.html',1,'']]], ['flash_5fcommon_5ff24_2eh',['flash_common_f24.h',['../flash__common__f24_8h.html',1,'']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32f2/html/search/files_4.js
JavaScript
gpl-3.0
703
// Copyright 2016 Mustafa Serdar Sanli // // This file is part of HexArtisan. // // HexArtisan is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // HexArtisan is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with HexArtisan. If not, see <http://www.gnu.org/licenses/>. #include <string> #include "unicode/umachine.h" #include "unicode/uchar.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "Endianness.hpp" #include "Unicode.hpp" using namespace std; // TODO FIXME u_isgraph ignores spaces. // Checks whether the give code point belongs to one of the following char // categories: // * Me. U_ENCLOSING_MARK, // * Mn. U_NON_SPACING_MARK // * Mc. U_COMBINING_SPACING_MARK // // See runtime/tools/unicode.vim from vim repo. bool IsComposingCodePoint(char32_t code_point) { UCharCategory category = static_cast<UCharCategory>( u_getIntPropertyValue(code_point, UCHAR_GENERAL_CATEGORY)); return (category == U_ENCLOSING_MARK || category == U_NON_SPACING_MARK || category == U_COMBINING_SPACING_MARK); } bool IsControlCodePoint(char32_t code_point) { UCharCategory category = static_cast<UCharCategory>( u_getIntPropertyValue(code_point, UCHAR_GENERAL_CATEGORY)); return category == U_CONTROL_CHAR; } int GetCodePointWidth(char32_t code_point) { if (IsComposingCodePoint(code_point)) return 0; UEastAsianWidth width = static_cast<UEastAsianWidth>( u_getIntPropertyValue(code_point, UCHAR_EAST_ASIAN_WIDTH)); // TODO some of the enum values are not well defined. // Need some tests for these. if (width == U_EA_FULLWIDTH || width == U_EA_WIDE) return 2; return 1; } void AppendCodePointAsUtf8(std::string &s, char32_t code_point) { UnicodeString((UChar32)code_point).toUTF8String(s); }
mserdarsanli/HexArtisan
src/Unicode.cpp
C++
gpl-3.0
2,209
/* This file is part of Integrator * (C) 2010 George Kettleborough * This is free software. See COPYING file for license. * 2010 Computer science final year project */ /* the Lazard-Rioboo-Trager algorithm for calculating the logarithmic part of * a rational function integral */ #ifndef H_LRT #define H_LRT #include "polynomial.h" #include "coef_array.h" #include "tree.h" void IntRationalLogPart(CoefArray *Qi, CoefArray *Si, Coefficient A, Coefficient D, char var, char newvar, int trace); void IntRationalLogPartI(node_type *root, char var, char newvar); #endif /* H_LRT */
georgek/integrator
src/lrt.h
C
gpl-3.0
662
function init() setName("Roughness") setDesc("Sets up roughness") end function apply() math.randomseed(os.time()) addNode("perlin_noise.lua", -70, 0) addNode("blend.lua", 50, 0) setParameter(0, 0, math.random(-1000, 1000)) setParameter(0, 1, math.random(4, 6)) setParameter(0, 2, math.random(5, 7)) setParameter(0, 5, 16) setParameter(1, 0, 1) addConnection(0, 0, 1, 1) end
Ledgamedev/Tilemancer
Presets/roughness.lua
Lua
gpl-3.0
418
// // // LiveFlight Connect // // UsbNotification.cs // Source: http://stackoverflow.com/questions/16245706/check-for-device-change-add-remove-events // // Licensed under GPL-V3. // https://github.com/LiveFlightApp/Connect-Windows/blob/master/LICENSE // using System; using System.Runtime.InteropServices; namespace LiveFlight { public static class UsbNotification { public const int DbtDevicearrival = 0x8000; // system detected a new device public const int DbtDeviceremovecomplete = 0x8004; // device is gone public const int WmDevicechange = 0x0219; // device change event private const int DbtDevtypDeviceinterface = 5; private static readonly Guid GuidDevinterfaceUSBDevice = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // USB devices private static IntPtr notificationHandle; /// <summary> /// Registers a window to receive notifications when USB devices are plugged or unplugged. /// </summary> /// <param name="windowHandle">Handle to the window receiving notifications.</param> public static void RegisterUsbDeviceNotification(IntPtr windowHandle) { DevBroadcastDeviceinterface dbi = new DevBroadcastDeviceinterface { DeviceType = DbtDevtypDeviceinterface, Reserved = 0, ClassGuid = GuidDevinterfaceUSBDevice, Name = 0 }; dbi.Size = Marshal.SizeOf(dbi); IntPtr buffer = Marshal.AllocHGlobal(dbi.Size); Marshal.StructureToPtr(dbi, buffer, true); notificationHandle = RegisterDeviceNotification(windowHandle, buffer, 0); } /// <summary> /// Unregisters the window for USB device notifications /// </summary> public static void UnregisterUsbDeviceNotification() { UnregisterDeviceNotification(notificationHandle); } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr RegisterDeviceNotification(IntPtr recipient, IntPtr notificationFilter, int flags); [DllImport("user32.dll")] private static extern bool UnregisterDeviceNotification(IntPtr handle); [StructLayout(LayoutKind.Sequential)] private struct DevBroadcastDeviceinterface { internal int Size; internal int DeviceType; internal int Reserved; internal Guid ClassGuid; internal short Name; } } }
LiveFlightApp/Connect-Windows
LiveFlight-Connect/UsbNotification.cs
C#
gpl-3.0
2,599
/*This file is part of Packet Sniffer * Copyright (C) 2009,2010 Daniel Myers dan<at>moird.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /// This is the class that sets the adapter into Promisucus Listen mode. /// Promisucus mode basically is that any Internet Traffic the Program recieves /// it processes. Unfotunately probably due to windows limitations this only /// includes traffic that is specifically being sent to the adapter being listened /// with and it's IP address, so it will NOT pick up other traffic on the network using System; using System.Net; using System.Net.Sockets; using System.Threading; namespace PacketSniffer { public class Listen { #region Fields private const int p_PacketBufferSize = 65536; // this is the Maximum size that a packet will ever be private byte[] p_PacketBuffer = new byte[p_PacketBufferSize]; //Packet Buffer private string p_HostIP; #endregion //Fields private PacketRecieveEvent p_PRE; private Socket ListenSocket; #region HostIP /// <summary> /// Set the Adapter that we are Listening On /// </summary> public string HostIP { set { p_HostIP = value; } } #endregion //HostIP public Listen(PacketRecieveEvent PRE) { p_PRE = PRE; } public void RunReciever() { ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); try { // Setup the Socket ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0)); ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1); ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]); while (true) //Infinite Loop keeps the Socket in Listen { ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None, new AsyncCallback(CallReceive), this); while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read { Thread.Sleep(1); } } } catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method catch (Exception e) {new ErrorHandle(e);} finally //Shutdown the Socket when finished { if (ListenSocket != null) { ListenSocket.Shutdown(SocketShutdown.Both); ListenSocket.Close(); } } } protected virtual void CallReceive(IAsyncResult ar) { new PacketHandler(p_PRE, ref p_PacketBuffer); } } }
moird/PacketSniffer
PacketSniffer/Listen.cs
C#
gpl-3.0
3,625
package ocpp.cs._2012._06; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für ReadingContext. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * <p> * <pre> * &lt;simpleType name="ReadingContext"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="Interruption.Begin"/&gt; * &lt;enumeration value="Interruption.End"/&gt; * &lt;enumeration value="Sample.Clock"/&gt; * &lt;enumeration value="Sample.Periodic"/&gt; * &lt;enumeration value="Transaction.Begin"/&gt; * &lt;enumeration value="Transaction.End"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "ReadingContext") @XmlEnum public enum ReadingContext { @XmlEnumValue("Interruption.Begin") INTERRUPTION_BEGIN("Interruption.Begin"), @XmlEnumValue("Interruption.End") INTERRUPTION_END("Interruption.End"), @XmlEnumValue("Sample.Clock") SAMPLE_CLOCK("Sample.Clock"), @XmlEnumValue("Sample.Periodic") SAMPLE_PERIODIC("Sample.Periodic"), @XmlEnumValue("Transaction.Begin") TRANSACTION_BEGIN("Transaction.Begin"), @XmlEnumValue("Transaction.End") TRANSACTION_END("Transaction.End"); private final String value; ReadingContext(String v) { value = v; } public String value() { return value; } public static ReadingContext fromValue(String v) { for (ReadingContext c: ReadingContext.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
dtag-dev-sec/emobility
dist/src/centralsystem/target/generated-sources/ocpp/cs/_2012/_06/ReadingContext.java
Java
gpl-3.0
1,773
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle( "PackageManager" )] [assembly: AssemblyDescription( "" )] [assembly: AssemblyConfiguration( "" )] [assembly: AssemblyCompany( "Microsoft" )] [assembly: AssemblyProduct( "PackageManager" )] [assembly: AssemblyCopyright( "Copyright © Microsoft 2011" )] [assembly: AssemblyTrademark( "" )] [assembly: AssemblyCulture( "" )] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible( false )] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "3358174b-eb3b-4242-aa5d-b54afc2f9487" )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion( "1.0.0.0" )] [assembly: AssemblyFileVersion( "1.0.0.0" )]
bretambrose/CCGOnlinePublic
CCGOnline/CCGOnline/PackageManager/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,446
/******************************************************************************* Copyright (c) 2010 Matt Williams This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *******************************************************************************/ #ifndef __PolyVox_TestMaterial_H__ #define __PolyVox_TestMaterial_H__ #include <QObject> class TestMaterial: public QObject { Q_OBJECT private slots: void testCompile(); }; #endif
Zidit/Fort_up
polyvox/tests/testmaterial.h
C
gpl-3.0
1,226
#!/bin/bash while test 1=1 do ./webservice.sh >log.txt 2>error_log.txt echo "Restarting.. `date`" done
LUMII-AILab/Webservices
production.sh
Shell
gpl-3.0
107
#include "ThePEG/Config/Constants.h" namespace Herwig { using namespace ThePEG; /** \ingroup Utilities * This is a namespace which provides the loop functions * from NPB297 (1988) 221-243 which are used to * calculate Higgs production with an additional jet * and the real correction to \f$h^0\to gg\f$. */ namespace HiggsLoopFunctions { /** * Epsilon parameter */ const Complex epsi = Complex(0.,-1.e-20); /** * The \f$W_1(s)\f$ function of NPB297 (1988) 221-243. * @param s The invariant * @param mf2 The fermion mass squared */ Complex W1(Energy2 s,Energy2 mf2) { double root = sqrt(abs(1.-4.*mf2/s)); if(s<ZERO) return 2.*root*asinh(0.5*sqrt(-s/mf2)); else if(s<4.*mf2) return 2.*root*asin(0.5*sqrt( s/mf2)); else return root*(2.*acosh(0.5*sqrt(s/mf2)) -Constants::pi*Complex(0.,1.)); } /** * The \f$W_2(s)\f$ function of NPB297 (1988) 221-243. * @param s The invariant * @param mf2 The fermion mass squared */ Complex W2(Energy2 s,Energy2 mf2) { double root=0.5*sqrt(abs(s)/mf2); if(s<ZERO) return 4.*sqr(asinh(root)); else if(s<4.*mf2) return -4.*sqr(asin(root)); else return 4.*sqr(acosh(root))-sqr(Constants::pi) -4.*Constants::pi*acosh(root)*Complex(0.,1.); } /** * The \f$I_3(s,t,u,v)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param v The \f$v\f$ invariant * @param mf2 The fermion mass squared */ Complex I3(Energy2 s, Energy2 t, Energy2 u, Energy2 v, Energy2 mf2) { double ratio=(4.*mf2*t/(u*s)),root(sqrt(1+ratio)); if(v==ZERO) return 0.; Complex y=0.5*(1.+sqrt(1.-4.*(mf2+epsi*MeV*MeV)/v)); Complex xp=0.5*(1.+root),xm=0.5*(1.-root); Complex output = Math::Li2(xm/(xm-y))-Math::Li2(xp/(xp-y))+ Math::Li2(xm/(y-xp))-Math::Li2(xp/(y-xm))+ log(-xm/xp)*log(1.-epsi-v/mf2*xp*xm); return output*2./root; } /** * The \f$W_3(s,t,u,v)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param v The \f$u\f$ invariant * @param mf2 The fermion mass squared. */ Complex W3(Energy2 s, Energy2 t, Energy2 u, Energy2 v, Energy2 mf2) { return I3(s,t,u,v,mf2)-I3(s,t,u,s,mf2)-I3(s,t,u,u,mf2); } /** * The \f$b_2(s,t,u)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param mf2 The fermion mass squared. */ Complex b2(Energy2 s, Energy2 t, Energy2 u, Energy2 mf2) { Energy2 mh2(s+u+t); complex<Energy2> output=s*(u-s)/(s+u)+2.*u*t*(u+2.*s)/sqr(s+u)*(W1(t,mf2)-W1(mh2,mf2)) +(mf2-0.25*s)*(0.5*(W2(s,mf2)+W2(mh2,mf2))-W2(t,mf2)+W3(s,t,u,mh2,mf2)) +sqr(s)*(2.*mf2/sqr(s+u)-0.5/(s+u))*(W2(t,mf2)-W2(mh2,mf2)) +0.5*u*t/s*(W2(mh2,mf2)-2.*W2(t,mf2)) +0.125*(s-12.*mf2-4.*u*t/s)*W3(t,s,u,mh2,mf2); return output*mf2/sqr(mh2); } /** * The \f$b_2(s,t,u)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param mf2 The fermion mass squared. */ Complex b4(Energy2 s, Energy2 t, Energy2 u, Energy2 mf2) { Energy2 mh2(s+t+u); return mf2/mh2*(-2./3.+(mf2/mh2-0.25)*(W2(t,mf2)-W2(mh2,mf2)+W3(s,t,u,mh2,mf2))); } /** * The \f$A_1(m_h^2)\f$ function of NPB297 (1988) 221-243. * @param mh2 The Higgs mass squared * @param mf2 The fermion mass squared. */ Complex A1(Energy2 mh2, Energy2 mf2) { return mf2/mh2*(4.-W2(mh2,mf2)*(1.-4.*mf2/mh2)); } /** * The \f$A_2(s,t,u)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param mf2 The fermion mass squared. */ Complex A2(Energy2 s, Energy2 t, Energy2 u, Energy2 mf2) { return b2(s,t,u,mf2)+b2(s,u,t,mf2); } /** * The \f$A_4(s,t,u)\f$ function of NPB297 (1988) 221-243. * @param s The \f$s\f$ invariant * @param t The \f$t\f$ invariant * @param u The \f$u\f$ invariant * @param mf2 The fermion mass squared. */ Complex A4(Energy2 s, Energy2 t, Energy2 u, Energy2 mf2) { return b4(s,t,u,mf2)+b4(u,s,t,mf2)+b4(t,u,s,mf2); } } }
hep-mirrors/herwig
Utilities/HiggsLoopFunctions.h
C
gpl-3.0
4,615
Imports System.Data.SqlClient Imports System.Data Imports System.Text Imports System.Collections.Specialized Imports System.IO Imports System.Drawing Public Class ClassManager Private cmdb As SqlCommandBuilder Private cmd As SqlCommand Public ds As New DataSet() Public da As New SqlDataAdapter() Public batchSQLitem As New StringCollection Public batchSQLLista As New List(Of CbatchSQLIitem) Public batchReturnAutoNumericInt As Boolean = False Public batchAutoNumericInt As Integer = 0 Public IDAutoFirstParent As Integer = 0 Public schemaName As String = "" Public Function CreateInsertSql(ByVal pTableName As String, ByVal pFields As String, ByVal pValues As String) As String Dim SQL As New StringBuilder Try SQL.AppendLine("INSERT INTO " & IIf(schemaName <> "", schemaName, "dbo" & "." & pTableName)) SQL.Append(String.Format(" ({0})", pFields)) SQL.AppendLine(String.Format(" VALUES ({0}) ", pValues)) Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function 'insertar Public Function Insert(ByVal sTableName As String, ByVal sFields As String, ByVal sValues As String) As Boolean Dim i As Integer Dim sql As String Dim bOk As Boolean Try sql = CreateInsertSql(sTableName, sFields, sValues) If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() cmd = New SqlCommand(sql, conex) i = cmd.ExecuteNonQuery() If i > 0 Then bOk = True Else bOk = False End If conex.Close() Return bOk Catch ex As Exception Throw bOk = False Return bOk Finally End Try End Function Public Function CreateDeleteSql(ByVal pTableName As String, ByVal pWHERE As String) As String Dim SQL As New StringBuilder Try SQL.AppendLine("DELETE FROM " & IIf(schemaName <> "", schemaName, "dbo" & "." & pTableName)) SQL.AppendLine(String.Format("WHERE {0} ", pWHERE)) Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function Public Function CreateFunctionSql(ByVal pFunctionName As String, ByVal pParametros As String) As String Dim SQL As New StringBuilder Try SQL.AppendLine("SELECT " & IIf(schemaName <> "", schemaName, "dbo" & "." & pFunctionName)) SQL.AppendLine(String.Format("( {0} )", pParametros)) Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function 'eliminar Public Function Delete(sTablaName As String, sCondicion As String) As Boolean Dim i As Integer Dim sql As String Dim bOk As Boolean Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() 'Dim sql As String = "Delete From " & sTablaName & sCondicion sql = CreateDeleteSql(sTablaName, sCondicion) cmd = New SqlCommand(sql, conex) i = cmd.ExecuteNonQuery() If i > 0 Then bOk = True Else bOk = False End If conex.Close() Return bOk Catch ex As Exception Throw bOk = False Return bOk Finally End Try Return bOk End Function Public Function CreateUpdateSql(ByVal pTableName As String, ByVal pSetValues As String, ByVal pWHERE As String) As String Dim SQL As New StringBuilder Try SQL.AppendLine("UPDATE " & IIf(schemaName <> "", schemaName, "dbo" & "." & pTableName)) SQL.AppendLine(String.Format("SET {0}", pSetValues)) SQL.AppendLine(String.Format("WHERE {0} ", pWHERE)) Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function Public Function Update(sTableName As String, sSetValues As String, sWhere As String) As Boolean Dim i As Integer Dim sql As String Dim bOk As Boolean Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() 'Dim sql As String = "Update " & sTablaName & " set " & sFieldNames & sCondicion sql = CreateUpdateSql(sTableName, sSetValues, sWhere) cmd = New SqlCommand(sql, conex) i = cmd.ExecuteNonQuery() If i > 0 Then bOk = True Else bOk = False End If conex.Close() Return bOk Catch ex As Exception Throw bOk = False Return bOk Finally End Try End Function Public Function ExecSPwithImage(sNameStoreProc As String, sParameters As String, MyImage As Image) As Boolean Dim sql As String Dim bOk As Boolean Dim i As Integer Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() ' sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) If Not (MyImage Is Nothing) Then Dim ImageBytes(0) As Byte Using mStream As New MemoryStream() MyImage.Save(mStream, MyImage.RawFormat) ImageBytes = mStream.ToArray() End Using sParameters = sParameters & ",@MyNewImage" sql = CreateStoreProcSql(sNameStoreProc, sParameters) cmd = New SqlCommand(sql, conex) With cmd.Parameters.Add("@MyNewImage", SqlDbType.Image) .Value = ImageBytes .Size = ImageBytes.Length End With Else sql = CreateStoreProcSql(sNameStoreProc, sParameters) cmd = New SqlCommand(sql, conex) End If i = cmd.ExecuteNonQuery() conex.Close() bOk = True Catch ex As Exception Throw bOk = False Finally End Try Return bOk End Function Public Function ExecAplicaRecibo(sNameStoreProc As String, tblPagos As DataTable, sUsuario As String, dTipoCambio As Double, bflgFlotante As Boolean) As Boolean Dim bOk As Boolean Dim i As Integer Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) cmd = New SqlCommand() cmd.Connection = conex cmd.CommandText = sNameStoreProc cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Pagos", tblPagos).SqlDbType = SqlDbType.Structured cmd.Parameters.AddWithValue("@Usuario", sUsuario) cmd.Parameters.AddWithValue("@TipoCambio", dTipoCambio) cmd.Parameters.AddWithValue("@flgFlotante", bflgFlotante) i = cmd.ExecuteNonQuery() conex.Close() bOk = True Catch ex As Exception Throw bOk = False Finally End Try Return bOk End Function Public Function ExecSP(sNameStoreProc As String, sParameters As String) As Boolean Dim sql As String Dim bOk As Boolean Dim i As Integer Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() ' sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) sql = CreateStoreProcSql(sNameStoreProc, sParameters) cmd = New SqlCommand(sql, conex) i = cmd.ExecuteNonQuery() conex.Close() bOk = True Catch ex As Exception Throw bOk = False Finally End Try Return bOk End Function Public Function ExecSPgetData(sNameStoreProc As String, sParameters As String) As DataTable Dim sql As String Dim dt As New DataTable Dim reader As SqlDataReader Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() 'sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) sql = CreateStoreProcSql(sNameStoreProc, sParameters) cmd = New SqlCommand(sql, conex) reader = cmd.ExecuteReader() dt.Load(reader) conex.Close() Return dt Catch ex As Exception Throw dt = New DataTable Return dt Finally End Try End Function Public Function ExecFunction(sFunctionName As String, sParameters As String) As DataTable Dim sql As String Dim dt As New DataTable Dim reader As SqlDataReader Try If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() 'sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) sql = CreateFunctionSql(sFunctionName, sParameters) cmd = New SqlCommand(sql, conex) reader = cmd.ExecuteReader() dt.Load(reader) conex.Close() Return dt Catch ex As Exception Throw dt = New DataTable Return dt Finally End Try End Function Public Function ExecFunctionWithinTransacction(conex As SqlConnection, tran As SqlTransaction, sFunctionName As String, sParameters As String) As DataTable Dim sql As String Dim dt As New DataTable Dim reader As SqlDataReader Try 'sNameStoreProc = IIf(schemaName <> "", schemaName, "dbo" & "." & sNameStoreProc) sql = CreateFunctionSql(sFunctionName, sParameters) cmd = New SqlCommand(sql, conex, tran) reader = cmd.ExecuteReader() dt.Load(reader) Return dt Catch ex As Exception Throw dt = New DataTable Return dt Finally End Try End Function Public Function CreateSelectSql(ByVal pTableName As String, ByVal pFields As String, ByVal pWHERE As String, ByVal pOrderBy As String) As String Dim SQL As New StringBuilder Try pTableName = IIf(schemaName <> "", schemaName, "dbo" & "." & pTableName) SQL.AppendLine(String.Format("SELECT {0} FROM {1} ", pFields, pTableName)) If pWHERE.Length > 0 Then SQL.AppendLine(String.Format("WHERE {0} ", pWHERE)) End If If pOrderBy.Length > 0 Then SQL.AppendLine(String.Format("ORDER BY {0} ", pOrderBy)) End If Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function Public Function CreateStoreProcSql(ByVal pStoreName As String, ByVal pParameters As String) As String Dim SQL As New StringBuilder Try If pStoreName.Length > 0 Then pStoreName = IIf(schemaName <> "", schemaName, "dbo" & "." & pStoreName) SQL.AppendLine(String.Format(" Exec {0}", pStoreName)) End If If pParameters.Length > 0 Then SQL.AppendLine(String.Format("{0}", pParameters)) End If Catch ex As Exception Throw SQL = New StringBuilder Finally End Try Return SQL.ToString End Function Public Sub GetData(sTableName As String, sFields As String, sWHERE As String, sOrderBy As String) Dim sql As String Try sTableName = IIf(schemaName <> "", schemaName, "dbo" & "." & sTableName) sql = CreateSelectSql(sTableName, sFields, sWHERE, sOrderBy) ds.Clear() da = New SqlDataAdapter(sql, conex) cmdb = New SqlCommandBuilder(da) da.Fill(ds, sTableName) Catch ex As Exception Throw Finally End Try End Sub Public Function GetDataTable(sTableName As String, sFields As String, sWHERE As String, sOrderBy As String) As DataTable Dim sql As String Dim dt As DataTable Dim da As SqlDataAdapter Dim dts As DataSet Try ''sTableName = IIf(schemaName <> "", schemaName, "dbo" & "." & sTableName) sql = CreateSelectSql(sTableName, sFields, sWHERE, sOrderBy) da = New SqlDataAdapter(sql, conex) dts = New DataSet() da.Fill(dts, sTableName) dt = New DataTable() dt = dts.Tables(sTableName) Return dt Catch ex As Exception Throw dt = New DataTable Return dt Finally End Try End Function Public Function GetDescrFromTable(sTableName As String, sFieldDescr As String, sWHERE As String, sOrderBy As String) As String Dim sql As String Dim dt As DataTable Dim da As SqlDataAdapter Dim dts As DataSet Dim strDescr As String = "" Try ''sTableName = IIf(schemaName <> "", schemaName, "dbo" & "." & sTableName) sql = CreateSelectSql(sTableName, sFieldDescr, sWHERE, sOrderBy) da = New SqlDataAdapter(sql, conex) dts = New DataSet() da.Fill(dts, sTableName) dt = New DataTable() dt = dts.Tables(sTableName) If dt.Rows.Count > 0 Then strDescr = dt.Rows(0)(sFieldDescr).ToString() End If Return strDescr Catch ex As Exception Throw strDescr = "" Return sFieldDescr Finally End Try End Function Public Function ExistsInTable(sTableName As String, sFieldDescr As String, sWHERE As String, sOrderBy As String) As Boolean Dim sql As String Dim dt As DataTable Dim da As SqlDataAdapter Dim dts As DataSet Dim strDescr As String = "" Dim lbResult As Boolean = False Try sql = CreateSelectSql(sTableName, sFieldDescr, sWHERE, sOrderBy) da = New SqlDataAdapter(sql, conex) dts = New DataSet() da.Fill(dts, sTableName) dt = New DataTable() dt = dts.Tables(sTableName) If dt.Rows.Count > 0 Then lbResult = True End If Return lbResult Catch ex As Exception Throw lbResult = False Return lbResult Finally End Try End Function Public Sub ClearsqlCollation() batchSQLitem.Clear() End Sub Public Function ExecCmdWithTransaction() As Boolean Dim bOk As Boolean Dim i As Integer Dim index As Integer Dim dt As DataTable Dim dtItemsSqlParentID As New DataTable Dim iAutoNumeric As Integer 'Dim iAutoNumericAnterior As Integer bOk = False Dim tran As SqlTransaction If conex.State = ConnectionState.Open Then conex.Close() End If conex.Open() tran = conex.BeginTransaction Try dtItemsSqlParentID.Columns.Add("ID", GetType(Integer)) dtItemsSqlParentID.Columns.Add("EsParent", GetType(Boolean)) dtItemsSqlParentID.Columns.Add("UsaParent", GetType(Boolean)) dtItemsSqlParentID.Columns.Add("IDAuto", GetType(Integer)) dtItemsSqlParentID.Columns.Add("IDParent", GetType(Integer)) dtItemsSqlParentID.Columns.Add("ProcesoPadre", GetType(String)) dtItemsSqlParentID.Columns.Add("ProcesoHijo", GetType(String)) ' LLeno la tabla con los padres e hijos index = 0 For Each item As CbatchSQLIitem In batchSQLLista dtItemsSqlParentID.Rows.Add(index, item.EsParentID, item.UsaParentID, 0, 0, item.sProcesoPadre, item.sProcesoHijo) index = index + 1 Next batchAutoNumericInt = 0 index = 0 For Each item As CbatchSQLIitem In batchSQLLista If item.UsaAutoNumericInteger And item.UsaParentID Then Dim theRow As DataRow() = dtItemsSqlParentID.Select("ID=" & (index).ToString()) If theRow.Count > 0 Then If Not CBool(theRow(0)("EsParent")) And CBool(theRow(0)("UsaParent")) Then Dim theRow3 As DataRow() = dtItemsSqlParentID.Select("ID=" & (index - 1).ToString()) If theRow3.Count > 0 Then iAutoNumeric = CInt(theRow3(0)("IDAuto")) theRow(0)("IDParent") = iAutoNumeric ' si usa autonumeric y aun asi devuelve valor cero el parent If iAutoNumeric = 0 Then Dim theRow4 As DataRow() = dtItemsSqlParentID.Select("ID=" & (index - 1).ToString()) If theRow4.Count > 0 Then iAutoNumeric = CInt(theRow4(0)("IDParent")) theRow(0)("IDParent") = iAutoNumeric End If End If End If End If If CBool(theRow(0)("EsParent")) And CBool(theRow(0)("UsaParent")) Then iAutoNumeric = CInt(theRow(0)("IDParent")) theRow(0)("IDParent") = iAutoNumeric End If item.sql = item.sql.Replace("@@Identity", iAutoNumeric.ToString()) End If End If cmd = New SqlCommand(item.sql, conex, tran) i = cmd.ExecuteNonQuery() If item.gRetornaIDNumerico = True Then dt = ExecFunctionWithinTransacction(conex, tran, "getAutoIDInt", "") If item.EsParentID Then batchAutoNumericInt = dt.Rows(0).Item(0) End If ' actualizo el IDAuto del parent Dim myRow() As Data.DataRow myRow = dtItemsSqlParentID.Select("ID=" & index.ToString() & " and ProcesoHijo = '" & item.sProcesoHijo & "'") ' si es la raiz de todo If myRow(0)("Esparent") And myRow(0)("UsaParent") = False Then myRow(0)("IDAuto") = batchAutoNumericInt myRow(0)("IDParent") = batchAutoNumericInt IDAutoFirstParent = batchAutoNumericInt ' actualizo el ID padre en toda la gerarquia Dim myRow2() As Data.DataRow myRow2 = dtItemsSqlParentID.Select("ProcesoPadre = '" & item.sProcesoHijo & "'") For j = 0 To myRow2.Count - 1 myRow2(j)("IDParent") = batchAutoNumericInt Next Else myRow(0)("IDAuto") = batchAutoNumericInt End If End If index = index + 1 Next bOk = True Catch ex As Exception bOk = False tran.Rollback() conex.Close() Throw Return bOk End Try tran.Commit() conex.Close() Return bOk End Function End Class
Solutions4U-NI/CDTSA
Facturacion/Clases/ClassManager.vb
Visual Basic
gpl-3.0
20,558
/* * Copyright (C) 2018 Stuart Howarth <showarth@marxoft.co.uk> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "categories.h" #include "clipboardurlmodel.h" #include "decaptchapluginmanager.h" #include "definitions.h" #include "downloadrequestmodel.h" #include "logger.h" #include "mainwindow.h" #include "pluginsettings.h" #include "recaptchapluginmanager.h" #include "request.h" #include "servicepluginmanager.h" #include "settings.h" #include "transfermodel.h" #include "urlcheckmodel.h" #include "urlretrievalmodel.h" #include <QApplication> #include <QNetworkAccessManager> Q_DECL_EXPORT int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName("QDL-Client"); app.setApplicationVersion(VERSION_NUMBER); app.setWindowIcon(QIcon::fromTheme("qdl2-client")); const QStringList args = app.arguments(); const int verbosity = args.indexOf("-v") + 1; if ((verbosity > 1) && (verbosity < args.size())) { Logger::setVerbosity(qMax(1, args.at(verbosity).toInt())); } else { Logger::setFileName(Settings::loggerFileName()); Logger::setVerbosity(Settings::loggerVerbosity()); } QNetworkAccessManager manager; Request::setNetworkAccessManager(&manager); QScopedPointer<Categories> categories(Categories::instance()); QScopedPointer<ClipboardUrlModel> clipboard(ClipboardUrlModel::instance()); QScopedPointer<DecaptchaPluginManager> decaptchaManager(DecaptchaPluginManager::instance()); QScopedPointer<DownloadRequestModel> requester(DownloadRequestModel::instance()); QScopedPointer<PluginSettings> pluginSettings(PluginSettings::instance()); QScopedPointer<RecaptchaPluginManager> recaptchaManager(RecaptchaPluginManager::instance()); QScopedPointer<ServicePluginManager> serviceManager(ServicePluginManager::instance()); QScopedPointer<Settings> settings(Settings::instance()); QScopedPointer<TransferModel> transfers(TransferModel::instance()); QScopedPointer<UrlCheckModel> checker(UrlCheckModel::instance()); QScopedPointer<UrlRetrievalModel> retriever(UrlRetrievalModel::instance()); clipboard.data()->setEnabled(Settings::clipboardMonitorEnabled()); clipboard.data()->restore(); transfers.data()->setAutoReloadEnabled(Settings::autoReloadEnabled()); MainWindow window; window.show(); QObject::connect(settings.data(), SIGNAL(clipboardMonitorEnabledChanged(bool)), clipboard.data(), SLOT(setEnabled(bool))); QObject::connect(settings.data(), SIGNAL(autoReloadEnabledChanged(bool)), transfers.data(), SLOT(setAutoReloadEnabled(bool))); return app.exec(); }
marxoft/qdl2
client/src/desktop/main.cpp
C++
gpl-3.0
3,225
/** AirCasting - Share your Air! Copyright (C) 2011-2012 HabitatMap, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You can contact the authors by email at <info@habitatmap.org> */ package pl.llp.aircasting.screens.sessionRecord; import pl.llp.aircasting.Intents; import pl.llp.aircasting.R; import pl.llp.aircasting.screens.common.helpers.SettingsHelper; import pl.llp.aircasting.screens.common.ToastHelper; import pl.llp.aircasting.screens.common.sessionState.CurrentSessionManager; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.inject.Inject; import pl.llp.aircasting.screens.common.base.DialogActivity; import roboguice.inject.InjectView; public class ContributeActivity extends DialogActivity { @Inject CurrentSessionManager currentSessionManager; @Inject Context context; @Inject SettingsHelper settingsHelper; @InjectView(R.id.yes) Button yes; @InjectView(R.id.no) Button no; @Override protected void onResume() { super.onResume(); if (!settingsHelper.hasCredentials()) { ToastHelper.show(context, R.string.account_reminder, Toast.LENGTH_LONG); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.contribute); initDialogToolbar("Contribute Session"); if(!getIntent().hasExtra(Intents.SESSION_ID)) { throw new RuntimeException("Should have arrived here with a session id"); } final long sessionId = getIntent().getLongExtra(Intents.SESSION_ID, 0); yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentSessionManager.finishSession(sessionId, true); finish(); } }); no.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentSessionManager.finishSession(sessionId, false); finish(); } }); } @Override public void onBackPressed() { currentSessionManager.continueSession(); finish(); } }
HabitatMap/AirCastingAndroidClient
src/main/java/pl/llp/aircasting/screens/sessionRecord/ContributeActivity.java
Java
gpl-3.0
2,765
/* * Copyright (C) 2017 zsel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.neology.lastdays; import com.neology.data.model.Frame; import com.neology.data.model.LoginData; import io.reactivex.Observable; import io.reactivex.Single; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; /** * * @author obsidiam */ public interface LastDaysService { @FormUrlEncoded @POST("/api/login") Single<LoginData> postCredential(@Field("username")String userName, @Field("password") String password, @Field("expires") String expires); @GET("/api/token") Call<ResponseBody> postToken(@Header("Authorization") String token); @FormUrlEncoded @POST("/api/register") Single<LoginData> postRegisterUser(@Field("username") String userName, @Field("password")String password, @Field("email") String email); @PUT("/api/todo") Single<TodoResult> postTodo(@Header("Authorization") String token, @Body TodoTicket t); @GET("/api/todo") Observable<Frame> getTodoList(@Header("Authorization") String token); }
Obsidiam/amelia
src/main/java/com/neology/lastdays/LastDaysService.java
Java
gpl-3.0
1,866
/* <genericpacket.cpp> Copyright(C) 2014 Jan Simon Bunten Simon Kadel Martin Sven Oehler Arne Sven Stühlmeyer This File is part of the WhisperLibrary WhisperLibrary is free software : you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WhisperLibrary is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <genericpacket.hpp> namespace whisper_library { vector<bool> GenericPacket::packet() const { return m_content; } void GenericPacket::setPacket(vector<bool> packet) { m_content = packet; } }
UndeadKernel/whisper-library
whisperLibrary/src/genericpacket.cpp
C++
gpl-3.0
1,011
""" DFO-GN ==================== A derivative-free solver for least squares minimisation with bound constraints. This version has resampling (not part of main package). This file is a modified version of DFOGN which allows resampling and restarts, to better cope with noisy problems. Lindon Roberts, 2017 Call structure is: x, f, nf, exit_flag, exit_str = dfogn(objfun, x0, lower, upper, maxfun, init_tr_radius, rhoend=1e-8) Required inputs: objfun Objective function, callable as: residual_vector = objfun(x) x0 Initial starting point, NumPy ndarray Optional inputs: lower, upper Lower and upper bound constraints (lower <= x <= upper), must be NumPy ndarrays of same size as x0 (default +/-1e20) maxfun Maximum number of allowable function evalutions (default 1000) init_tr_radius Initial trust region radius (default 0.1*max(1, ||x0||_infty) rhoend Termination condition on trust region radius (default 1e-8) Outputs: x Estimate of minimiser f Value of least squares objective at x (f = ||objfun(x)||^2) nf Number of objective evaluations used to find x exit_flag Integer flag indicating termination criterion (see list below imports) exit_str String with more detailed termination message This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. The development of this software was sponsored by NAG Ltd. (http://www.nag.co.uk) and the EPSRC Centre For Doctoral Training in Industrially Focused Mathematical Modelling (EP/L015803/1) at the University of Oxford. Please contact NAG for alternative licensing. Copyright 2017, Lindon Roberts """ # Ensure compatibility with Python 2 from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import scipy.linalg as sp_linalg from math import sqrt import logging from .util import * from .trust_region import * from .alternative_move import * ####################### # Exit codes EXIT_SUCCESS = 0 # successful finish (rho=rhoend or sufficient objective reduction) EXIT_INPUT_ERROR = 1 # error, bad inputs EXIT_MAXFUN_WARNING = 2 # warning, reached max function evals EXIT_TR_INCREASE_ERROR = 3 # error, trust region step increased model value EXIT_LINALG_ERROR = 4 # error, linalg error (singular matrix encountered) EXIT_ALTMOV_MEMORY_ERROR = 5 # error, stpsav issue in ALTMOV # Errors for which we can do a restart (not including rho=rhoend in EXIT_SUCCESS) DO_RESTART_ERRORS = [EXIT_TR_INCREASE_ERROR, EXIT_LINALG_ERROR, EXIT_ALTMOV_MEMORY_ERROR] ####################### ####################### # Sampling scenarios SCEN_PRELIM = 1 # during prelim SCEN_GROWING_NEW_DIRECTION = 2 # adding new direction while growing SCEN_TR_STEP = 3 # sampling xk+sk from successful trust region step SCEN_GEOM_UPDATE = 4 # calling altmov for geometry fixing SCEN_RHOEND_REACHED = 5 # reached rhoend in unsuccessful TR step ####################### class Model: def __init__(self, n, m, npt, x0, xl, xu): assert npt==n+1, "Require strictly linear model" # Problem sizes self.n = n self.m = m self.npt = npt self.npt_so_far = 0 # how many points have we added so far (for growing initial set) # Actual model info # Here, the model for each residual is centred around xbase # m(x) = model_const_term + gqv*(x-xbase) self.kbase = 0 # index of base point self.xbase = x0 # base point self.xl = xl # lower bounds (absolute terms) self.xu = xu # upper bounds (absolute terms) self.sl = xl - x0 # lower bounds (adjusted for xbase), should be -ve (actually < -rhobeg) self.su = xu - x0 # upper bounds (adjusted for xbase), should be +ve (actually > rhobeg) self.xpt = np.zeros((npt, n)) # interpolation points self.fval_v = np.zeros((npt, m)) # residual vectors at each xpt(+xbase) self.fval = np.zeros((npt, )) # total sum of squares at each xpt(+xbase) self.model_const_term_v = np.zeros((m,)) # constant term of each mini-model self.gqv = np.zeros((n, m)) # interpolated gradients for each mini-model self.kopt = None # index of current best x self.fbeg = None # initial sum of squares at x0 self.xsave = None # possible final return value (abs coords) self.fsave = None # sum of squares for final return value self.lu = None # LU decomp of interp matrix self.piv = None # pivots for LU decomposition of interp matrix self.lu_current = False # whether current LU factorisation of interp matrix is up-to-date or not self.EXACT_CONST_TERM = True # use exact c=r(xopt) for interpolation (improve conditioning) # Affects mini-model interpolation / interpolation matrix, but also geometry updating self.nsamples = np.zeros((npt,), dtype=np.int) # how many samples we have averaged to get fval_v, where fval = sumsq(avg fval_v) def x_within_bounds(self, k=None, x=None): # Get x value for k-th point or x vector (in absolute terms, force within bounds) if k is not None: return np.minimum(np.maximum(self.xl, self.xbase + self.xpt[k, :]), self.xu) elif x is not None: return np.minimum(np.maximum(self.xl, self.xbase + x), self.xu) else: return None def xopt(self): # Current best x (relative to xbase) return self.xpt[self.kopt, :].copy() def fval_v_opt(self): return self.fval_v[self.kopt,:] def fval_opt(self): return self.fval[self.kopt] def update_point(self, knew, xnew, v_err, f): if knew >= self.npt_so_far and self.npt_so_far < self.npt: # when still growing, need to append in correct order assert knew == self.npt_so_far, "Updating new index too far along (%g when should be %g)" % (knew, self.npt_so_far) self.npt_so_far += 1 # Add point xnew with objective vector v_err (full objective f) at the knew-th index self.xpt[knew,:] = xnew self.fval_v[knew, :] = v_err self.fval[knew] = f self.nsamples[knew] = 1 # Update XOPT, GOPT and KOPT if the new calculated F is less than FOPT. if f < self.fval_opt(): self.kopt = knew self.lu_current = False return def add_point_resample(self, knew, v_err_new): # We have resampled point knew and got a new fval_v = v_err_new # Update our estimates of fval_v assert knew < self.npt_to_use(), "Invalid knew" t = float(self.nsamples[knew]) / float(self.nsamples[knew] + 1) self.fval_v[knew, :] = t * self.fval_v[knew, :] + (1 - t) * v_err_new self.fval[knew] = sumsq(self.fval_v[knew, :]) self.nsamples[knew] += 1 if self.fval[knew] < self.fval_opt(): self.kopt = knew return def npt_to_use(self): # Number of points to use when building interpolation system return min(self.npt_so_far, self.npt) # depends on whether we have a full set yet (or not) def gqv_at_xopt(self): return self.gqv def shift_base(self, xbase_shift): for m1 in range(self.m): self.model_const_term_v[m1] += np.dot(self.gqv[:, m1], xbase_shift) # The main updates for k in range(self.npt): self.xpt[k, :] = self.xpt[k, :] - xbase_shift self.xbase += xbase_shift self.sl = self.sl - xbase_shift self.su = self.su - xbase_shift self.lu_current = False self.factorise_LU() return def interpolate_mini_models(self): # Build interpolation matrix and factorise (in self.lu, self.piv) self.factorise_LU() try: if self.EXACT_CONST_TERM: idx_to_use = [k for k in range(self.npt) if k != self.kopt] for m1 in range(self.m): rhs = np.zeros((self.n,)) for i in range(self.n): k = idx_to_use[i] rhs[i] = self.fval_v[k, m1] - self.fval_v[self.kopt, m1] - \ np.dot(self.gqv[:, m1], self.xpt[k, :] - self.xopt()) soln = sp_linalg.lu_solve((self.lu, self.piv), rhs) self.gqv[:, m1] += soln # whole solution is gradient # shift constant term back self.model_const_term_v = self.fval_v[self.kopt, :] - np.dot(self.gqv.T, self.xopt()) return True # flag ok else: model_values_v = np.zeros((self.npt, self.m)) for k in range(self.npt): model_values_v[k, :] = self.predicted_values(self.xpt[k, :], d_based_at_xopt=False, with_const_term=True) # Sometimes when things get too close to a solution, we can get NaNs in model_values - flag error & quit if np.any(np.isnan(model_values_v)): self.gqv = None return False # flag error for m1 in range(self.m): rhs = self.fval_v[:, m1] - model_values_v[:, m1] soln = sp_linalg.lu_solve((self.lu, self.piv), rhs) self.model_const_term_v[m1] += soln[0] self.gqv[:, m1] += soln[1:] # first term is constant, rest is gradient term return True # flag ok except np.linalg.LinAlgError: self.gqv = None return False # flag error except ValueError: # happens when LU decomposition has Inf or NaN self.gqv = None return False # flag error def factorise_LU(self): if not self.lu_current: Wmat = self.build_interp_matrix() self.lu, self.piv = sp_linalg.lu_factor(Wmat) # LU has L and U parts, piv indicates row swaps for pivoting self.lu_current = True return def solve_LU(self, rhs): # If lu_current, use that, otherwise revert to generic solver if self.lu_current: if self.EXACT_CONST_TERM: return sp_linalg.lu_solve((self.lu, self.piv), rhs) # only get gradient (no const term) else: return sp_linalg.lu_solve((self.lu, self.piv), rhs)[1:] # only return gradient (1st term is constant) else: logging.warning("model.solve_LU not using factorisation") Wmat = self.build_interp_matrix() if self.EXACT_CONST_TERM: return np.linalg.solve(Wmat, rhs) # only get gradient (no const term) else: return np.linalg.solve(Wmat, rhs)[1:] # only return gradient (1st term is constant) def get_final_results(self): # Called when about to exit BOBYQB # Return x and fval for optimal point (either from xsave+fsave or kopt) if self.fsave is None or self.fval_opt() <= self.fsave: # optimal has changed since xsave+fsave were last set x = self.x_within_bounds(k=self.kopt) f = self.fval_opt() else: x = self.xsave f = self.fsave return x, f def build_full_model(self): # Build full least squares objective model from mini-models # Centred around xopt = xpt[kopt, :] v_temp = self.fval_v_opt() # m-vector gqv_xopt = self.gqv_at_xopt() # J^T (transpose of Jacobian) at xopt, rather than xbase # Use the gradient at xopt to formulate \sum_i (2*f_i \nabla f_i) = 2 J^t m(x_opt) gopt = np.dot(gqv_xopt, v_temp) # n-vector (gqv = J^T) # Gauss-Newton part of Hessian hq = to_upper_triangular_vector(np.dot(gqv_xopt, gqv_xopt.T)) # Apply scaling based on convention for objective - this code uses sumsq(r_i) not 0.5*sumsq(r_i) gopt = 2.0 * gopt hq = 2.0 * hq return gopt, hq def build_interp_matrix(self): if self.EXACT_CONST_TERM: Wmat = np.zeros((self.n, self.n)) idx_to_use = [k for k in range(self.npt) if k != self.kopt] for i in range(self.n): Wmat[i,:] = self.xpt[idx_to_use[i], :] - self.xopt() else: Wmat = np.zeros((self.n + 1, self.n + 1)) Wmat[:, 0] = 1.0 Wmat[:, 1:] = self.xpt # size npt * n return Wmat def predicted_values(self, d, d_based_at_xopt=True, with_const_term=False): if d_based_at_xopt: Jd = np.dot(self.gqv.T, d + self.xopt()) # J^T * d (where Jacobian J = self.gqv^T) else: # d based at xbase Jd = np.dot(self.gqv.T, d) # J^T * d (where Jacobian J = self.gqv^T) return Jd + (self.model_const_term_v if with_const_term else 0.0) def square_distances_to_xopt(self): sq_distances = np.zeros((self.npt,)) for k in range(self.npt): sq_distances[k] = sumsq(self.xpt[k, :] - self.xopt()) return sq_distances def min_objective_value(self, abs_tol=1.0e-12, rel_tol=1.0e-20): # Set a minimum value so that if the full objective falls below it, we immediately finish if self.fbeg is not None: return max(abs_tol, rel_tol * self.fbeg) else: return abs_tol def sample_objective(m, objfun, x, nf, nx, maxfun, min_obj_value, nsamples=1): # Sample from objective function several times, keeping track of maxfun and min_obj_value throughout if m is None: # Don't initialise v_err_list yet v_err_list = None else: v_err_list = np.zeros((nsamples, m)) f_list = np.zeros((nsamples,)) exit_flag = None exit_str = None nsamples_run = 0 for i in range(nsamples): if nf >= maxfun: exit_flag = EXIT_MAXFUN_WARNING exit_str = "Objective has been called MAXFUN times" break # quit nf += 1 this_v_err, f_list[i] = eval_least_squares_objective_v2(objfun, x, eval_num=nf, pt_num=nx+1, full_x_thresh=6) if m is None: m = len(this_v_err) v_err_list = np.zeros((nsamples, m)) v_err_list[i, :] = this_v_err nsamples_run += 1 if f_list[i] <= min_obj_value: # Force model.get_final_results() to return this new point if it's better than xopt, then quit exit_flag = EXIT_SUCCESS exit_str = "Objective is sufficiently small" break # quit return v_err_list, f_list, nf, nx+1, nsamples_run, exit_flag, exit_str def build_initial_set(objfun, x0, xl, xu, rhobeg, maxfun, nsamples, nf_so_far, nx_so_far, ndirs_initial, nruns_so_far, m=None, random_initial_directions=False): n = np.size(x0) npt = n + 1 if m is not None: # Initialise model (sets x0 as base point and xpt = zeros, so xpt[0,:] = x0) model = Model(n, m, npt, x0, xl, xu) model.kopt = 0 minval = model.min_objective_value() else: # If we don't yet have m, wait until we have done a function evaluation before initialising model model = None minval = -1.0 assert 1 <= ndirs_initial < np.size(x0)+1, "build_inital_set: must have 1 <= ndirs_initial < n+1" nx = nx_so_far nf = nf_so_far # For calling nsamples: delta = rhobeg rho = rhobeg current_iter = 0 # Evaluate at initial point (also gets us m in the first run through) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_PRELIM) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(m, objfun, x0, nf, nx, maxfun, minval, nsamples=nsamples_to_use) # If we have just learned m, initialise model (sets x0 as base point and xpt = zeros, so xpt[0,:] = x0) if model is None: # Now we know m = v_err_list.shape[1] model = Model(n, v_err_list.shape[1], npt, x0, xl, xu) model.kopt = 0 f0 = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if model.fsave is None or fmin < model.fsave: model.xsave = x0 model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results (increments model.npt_so_far) model.update_point(0, model.xpt[0, :], v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(0, v_err_list[i, :]) # add new info # Add results of objective evaluation at x0 model.fbeg = f0 model.xsave = x0.copy() model.fsave = f0 # Build initial sample set either using random orthogonal directions, or coordinate directions if random_initial_directions: # Get ndirs_initial random orthogonal directions A = np.random.randn(n, ndirs_initial) # Standard Gaussian n*ndirs_initial Q = np.linalg.qr(A)[0] # Q is n*ndirs_initial with orthonormal columns # Now add the random directions for ndirns in range(ndirs_initial): dirn = Q[:, ndirns] # Scale direction to ensure the new point lies within initial trust region, satisfies constraints scale_factor = rhobeg / np.linalg.norm(dirn) for j in range(n): if dirn[j] < 0.0: scale_factor = min(scale_factor, model.sl[j] / dirn[j]) elif dirn[j] > 0.0: scale_factor = min(scale_factor, model.su[j] / dirn[j]) model.xpt[1 + ndirns, :] = scale_factor * dirn else: at_upper_boundary = (model.su < 0.01 * rhobeg) # su = xu - x0, should be +ve, actually > rhobeg for k in range(ndirs_initial): step_size = (rhobeg if not at_upper_boundary[k] else -rhobeg) model.xpt[k+1, k] = step_size # Evaluate objective at each point in the initial sample set for k in range(1, ndirs_initial): x = model.x_within_bounds(k=k) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_PRELIM) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if model.fsave is None or fmin < model.fsave: model.xsave = x model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results (increments model.npt_so_far) model.update_point(k, model.xpt[k, :], v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(k, v_err_list[i, :]) # add new info return_to_new_tr_iteration = True # return and continue exit_flag = None exit_str = None return model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str def get_new_orthogonal_directions(model, adelt, num_steps=1): # Step from xopt along a random direction orthogonal to other yt (or multiple mutually orthogonal steps) for i in range(20): # allow several tries, in case we choosing a point in the subspace of (yt-xk) [very unlucky] A = np.random.randn(model.n, num_steps) # (modified) Gram-Schmidt to orthogonalise for k in range(min(model.npt_so_far, model.npt)): if k == model.kopt: continue yk = model.xpt[k,:] - model.xopt() for j in range(num_steps): A[:,j] = A[:,j] - (np.dot(A[:,j], yk) / np.dot(yk, yk)) * yk # continue if every column sufficiently large all_cols_ok = True for j in range(num_steps): if np.linalg.norm(A[:,j]) < 1e-8: all_cols_ok = False if all_cols_ok: break # Scale appropriately so within bounds and ||d|| <= adelt Q = np.linalg.qr(A)[0] # Q is n*ndirs with orthonormal columns for j in range(num_steps): scale_factor = adelt / np.linalg.norm(Q[:,j]) for i in range(model.n): if Q[i,j] < 0.0: scale_factor = min(scale_factor, (model.sl[i] - model.xopt()[i]) / Q[i,j]) elif Q[i,j] > 0.0: scale_factor = min(scale_factor, (model.su[i] - model.xopt()[i]) / Q[i,j]) Q[:,j] = Q[:,j] * scale_factor # Finished! return Q def altmov_wrapper(model, knew, adelt): model.factorise_LU() # First need to get knew-th column of H matrix if model.EXACT_CONST_TERM: if knew == model.kopt: ek = -np.ones((model.n, )) # matrix based on (y-xk), so different geom structure for kopt else: ek = np.zeros((model.n, )) if knew < model.kopt: ek[knew] = 1.0 else: ek[knew - 1] = 1.0 H_knew = model.solve_LU(ek) else: ek = np.zeros((model.n + 1,)) ek[knew] = 1.0 H_knew = model.solve_LU(ek) xnew, xalt, cauchy, abs_denom = altmov(model.xpt, model.sl, model.su, model.kopt, model.xopt(), knew, adelt, H_knew) # abs_denom is Lagrange_knew evaluated at xnew return xnew, xalt, cauchy, abs_denom def choose_knew(model, delta, xnew, skip_kopt=True): # in model, uses: n, npt, xpt, kopt/xopt, build_interp_matrix() # model unchanged by this method # Criteria is to maximise: max(1, ||yt-xk||^4/Delta^4) * abs(Lagrange_t(xnew)) # skip_kopt determines whether to check t=kopt as a possible candidate or not model.factorise_LU() # Prep for linear solves delsq = delta ** 2 scaden = -1.0 knew = None # may knew never be set here? try: for k in range(model.npt): if skip_kopt and k == model.kopt: continue # next k in this inner loop if model.EXACT_CONST_TERM: if k == model.kopt: ek = -np.ones((model.n,)) # matrix based on (y-xk), so different geom structure for kopt else: ek = np.zeros((model.n, )) if k < model.kopt: ek[k] = 1.0 else: ek[k-1] = 1.0 Hk = model.solve_LU(ek) else: ek = np.zeros((model.n + 1,)) ek[k] = 1.0 Hk = model.solve_LU(ek) # k-th column of H, except 1st entry (i.e. Lagrange polynomial gradient) lagrange_k_at_d = 1.0 + np.dot(xnew-model.xpt[k, :], Hk) distsq = sumsq(model.xpt[k, :] - model.xopt()) temp = max(1.0, (distsq / delsq) ** 2) if temp * abs(lagrange_k_at_d) > scaden: scaden = temp * abs(lagrange_k_at_d) knew = k linalg_error = False except np.linalg.LinAlgError: linalg_error = True return knew, linalg_error def trust_region_subproblem_least_squares(model, delta): # in model, uses: n, npt, xpt, kopt/xopt, sl, su, build_full_model() # model unchanged by this method # Build model for full least squares objectives gopt, hq = model.build_full_model() # Call original BOBYQA trsbox function d, gnew, crvmin = trsbox(model.xopt(), gopt, hq, model.sl, model.su, delta) return d, gopt, hq, gnew, crvmin def done_with_current_rho(model, current_iter, last_successful_iter, rho, diffs, xnew, gnew, hq, crvmin): # in model, uses: n, sl, su # model unchanged by this method if current_iter <= last_successful_iter + 2: return False errbig = max(diffs) frhosq = 0.125 * rho ** 2 if crvmin > 0.0 and errbig > frhosq * crvmin: return False bdtol = errbig / rho for j in range(model.n): bdtest = bdtol if xnew[j] == model.sl[j]: bdtest = gnew[j] if xnew[j] == model.su[j]: bdtest = -gnew[j] if bdtest < bdtol: curv = get_hessian_element(model.n, hq, j, j) # curv = Hessian(j, j) bdtest += 0.5 * curv * rho if bdtest < bdtol: return False return True def reduce_rho(old_rho, rhoend): ratio = old_rho/rhoend if ratio <= 16.0: new_rho = rhoend elif ratio <= 250.0: new_rho = sqrt(ratio)*rhoend else: new_rho = 0.1*old_rho delta = max(0.5*old_rho, new_rho) return delta, new_rho def check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=True): # [Fortran label 650] # If any xpt more than distsq away from xopt, fix geometry knew_tmp, distsq_tmp = get_vector_max(all_square_distances(model.xpt, model.xopt())) if distsq_tmp > distsq: # fix geometry and quit knew = knew_tmp distsq = distsq_tmp dist = sqrt(distsq) if update_delta: # optional delta = max(min(0.1 * delta, 0.5 * dist), 1.5 * rho) # use 0.5*dist, within range [0.1*delta, 1.5*rho] adelt = max(min(0.1 * dist, delta), rho) if adelt ** 2 <= rounding_error_const * sumsq(model.xopt()): model.shift_base(model.xopt()) model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str \ = fix_geometry(model, objfun, knew, delta, adelt, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, nruns_so_far) return model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str else: # Do nothing, just quit # return_to_new_tr_iteration = None when didn't fix geometry return model, delta, nf, nx, last_successful_iter, diffs, None, None, None def fix_geometry(model, objfun, knew, delta, adelt, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, nruns_so_far): # in model, uses: n, npt, xpt, sl, su, kopt/xopt, build_interp_metrix, and others # model is changed by this function: gqv from interp_mini_models, and others try: xnew, xalt, cauchy, denom = altmov_wrapper(model, knew, adelt) except np.linalg.LinAlgError: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix encountered in ALTMOV" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str if xnew is None: # issue with stpsav occurred, quit DFOGN exit_flag = EXIT_ALTMOV_MEMORY_ERROR exit_str = "Error in ALTMOV - stpsav undefined" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str if denom < cauchy and cauchy > 0.0: xnew = xalt.copy() d = xnew - model.xopt() # [Fortran label 360] x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GEOM_UPDATE) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str # Otherwise, add new results model.update_point(knew, xnew, v_err_list[0, :], f_list[0]) # increments model.npt_so_far, if still growing for i in range(1, nsamples_run): model.add_point_resample(knew, v_err_list[i, :]) # add new info # Estimate actual reduction to add to diffs vector f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Use the quadratic model to predict the change in F due to the step D, # and set DIFF to the error of this prediction. gopt, hq = model.build_full_model() if gopt is None: # Use this to indicate linalg error if f < model.fval_opt(): # Force model.get_final_results() to return this new point if it's better than xopt, then quit model.xsave = x model.fsave = f exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix encountered in FIX_GEOMETRY (full model interpolation step)" return_to_new_tr_iteration = False # return and quit return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str pred_reduction = - calculate_model_value(gopt, hq, d) actual_reduction = model.fval_opt() - f diffs = [abs(pred_reduction - actual_reduction), diffs[0], diffs[1]] if dnorm > rho: last_successful_iter = current_iter exit_flag = None exit_str = None return_to_new_tr_iteration = True # return and start new trust region iteration (label 60) return model, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, exit_flag, exit_str def dfogn_main(objfun, x0, xl, xu, rhobeg, rhoend, maxfun, nsamples, m=None, delta_scale_for_new_dirns_when_growing=1.0, use_random_initial_directions=False, ndirs_initial=None, num_geom_steps_when_growing=1, nf_so_far=0, nx_so_far=0, nruns_so_far=0): exit_flag = None exit_str = None # One variable in BOBYQB depends on which code form we are using if zhang_code_structure: rounding_error_const = 0.1 # Zhang code else: rounding_error_const = 1.0e-3 # BOBYQA ########################################################### # Set up initial interpolation set ########################################################### # It shouldn't ever happen, but make sure ndirs_initial is not None if ndirs_initial is None: ndirs_initial = np.size(x0) model, nf, nx, return_to_new_tr_iteration, exit_flag, exit_str = \ build_initial_set(objfun, x0, xl, xu, rhobeg, maxfun, nsamples, nf_so_far, nx_so_far, ndirs_initial, nruns_so_far, m=m, random_initial_directions=use_random_initial_directions) if not return_to_new_tr_iteration: x, f = model.get_final_results() return x, f, nf, nx, exit_flag, exit_str, model.m ########################################################### # Set other variables before begin iterations ########################################################### finished_main_loop = False (rho, delta) = (rhobeg, rhobeg) diffs = [0.0, 0.0, 0.0] # (diffa, diffb, diffc) in Fortran code, used in done_with_current_rho() ########################################################### # Start of main loop [Fortran label 60] ########################################################### current_iter = -1 last_successful_iter = 0 while not finished_main_loop: current_iter += 1 logging.debug("Iter %g (last successful %g) with delta = %g and rho = %g" % ( current_iter, last_successful_iter, delta, rho)) # Interpolate each mini-model interp_ok = model.interpolate_mini_models() if not interp_ok: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix in mini-model interpolation (main loop)" finished_main_loop = True break # quit # Solve trust region subproblem to get tentative step d # Model for full least squares objective is given by (gopt, hq) d, gopt, hq, gnew, crvmin = trust_region_subproblem_least_squares(model, delta) logging.debug("Trust region step is d = " + str(d)) xnew = model.xopt() + d dsq = sumsq(d) dnorm = min(delta, sqrt(dsq)) if dnorm < 0.5 * rho and model.npt_so_far < model.n + 1: # Failed TR step during initial phase - add a point and see if that helps logging.debug("Failed trust region step during growing phase - adding new directions") dnew_matrix = get_new_orthogonal_directions(model, delta_scale_for_new_dirns_when_growing * delta, num_steps=num_geom_steps_when_growing) break_main_loop = False # the internal breaks only quit this inner loop! for j in range(num_geom_steps_when_growing): xnew = model.xopt() + dnew_matrix[:, j] logging.debug("Growing: compulsory geometry improving step xnew = %s" % str(xnew)) x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GROWING_NEW_DIRECTION) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin break_main_loop = True break # quit inner loop over j, then quit main iteration if model.npt_so_far < model.npt: # still growing kmin = model.npt_so_far logging.debug("Updating point kmin=%g, since still growing" % kmin) else: # full set kmin, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding kmin (in main loop)" break_main_loop = True break # quit inner loop over j, then quit main iteration logging.debug("Updating point kmin=%g, chosen in usual way" % kmin) # Otherwise, add new results, incrementing model.npt_so_far (if still growing) model.update_point(kmin, xnew, v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(kmin, v_err_list[i, :]) # add new info # Finished adding new directions - restart main trust region iteration (if no errors encountered) if break_main_loop: finished_main_loop = True break # quit else: finished_main_loop = False continue # next trust region step elif dnorm < 0.5 * rho: ################### # Start failed TR step ################### logging.debug("Failed trust region step (main phase)") if not done_with_current_rho(model, current_iter, last_successful_iter, rho, diffs, xnew, gnew, hq, crvmin): # [Fortran label 650] distsq = (10.0 * rho) ** 2 model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, geom_exit_flag, geom_exit_str = \ check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=True) if return_to_new_tr_iteration is not None: # i.e. if we did actually fix geometry if return_to_new_tr_iteration: finished_main_loop = False continue # next trust region step else: # quit exit_flag = geom_exit_flag exit_str = geom_exit_str finished_main_loop = True break # quit # If we didn't fix geometry, reduce rho as below # otherwise, if we are done with current rho, reduce rho as below # Reduce rho and continue [Fortran label 680] if rho > rhoend: delta, rho = reduce_rho(rho, rhoend) logging.info("New rho = %g after %i function evaluations" % (rho, nf)) logging.debug("Best so far: f = %.15g at x = " % (model.fval_opt()) + str(model.xbase + model.xopt())) last_successful_iter = current_iter finished_main_loop = False continue # next trust region step else: # Cannot reduce rho, so check xnew and quit x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_RHOEND_REACHED) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break # quit # Force model.get_final_results() to return this new point if it's better than xopt, then quit model.xsave = x model.fsave = np.min(f_list[:nsamples_run]) exit_flag = EXIT_SUCCESS exit_str = "rho has reached rhoend" finished_main_loop = True break # quit ################### # End failed TR step ################### else: ################### # Start successful TR step ################### logging.debug("Successful trust region step") # Severe cancellation is likely to occur if XOPT is too far from XBASE. [Fortran label 90] if dsq <= rounding_error_const * sumsq(model.xopt()): model.shift_base(model.xopt()) # includes a re-factorisation of the interpolation matrix xnew = xnew - model.xopt() # Set KNEW to the index of the next interpolation point to be deleted to make room for a trust # region step. Again RESCUE may be called if rounding errors have damaged # the chosen denominator, which is the reason for attempting to select # KNEW before calculating the next value of the objective function. knew, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding knew (in main loop)" finished_main_loop = True break # quit # Calculate the value of the objective function at XBASE+XNEW, unless # the limit on the number of calculations of F has been reached. # [Fortran label 360, with ntrits > 0] x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_TR_STEP) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Estimate f in order to compute 'actual reduction' f = sumsq(np.mean(v_err_list[:nsamples_run, :], axis=0)) # estimate actual objective value # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break # quit # Use the quadratic model to predict the change in F due to the step D, # and set DIFF to the error of this prediction. pred_reduction = - calculate_model_value(gopt, hq, d) actual_reduction = model.fval_opt() - f diffs = [abs(pred_reduction - actual_reduction), diffs[0], diffs[1]] if dnorm > rho: last_successful_iter = current_iter if pred_reduction < 0.0: exit_flag = EXIT_TR_INCREASE_ERROR exit_str = "Trust region step gave model increase" finished_main_loop = True break # quit # Pick the next value of DELTA after a trust region step. # Update trust region radius ratio = actual_reduction / pred_reduction if ratio <= 0.1: delta = min(0.5 * delta, dnorm) elif ratio <= 0.7: delta = max(0.5 * delta, dnorm) else: # (ratio > 0.7) Different updates depending on which code version we're using if zhang_code_structure: delta = min(max(2.0 * delta, 4.0 * dnorm), 1.0e10) # DFBOLS code version elif bbqtr: delta = max(0.5 * delta, 2.0 * dnorm) # BOBYQA version else: delta = max(delta, 2.0 * dnorm) # Zhang paper version if delta <= 1.5 * rho: # cap trust region radius at rho delta = rho logging.debug("New delta = %g (rho = %g) from ratio %g" % (delta, rho, ratio)) # Recalculate KNEW and DENOM if the new F is less than FOPT. if actual_reduction > 0.0: # f < model.fval_opt() knew, linalg_error = choose_knew(model, delta, xnew, skip_kopt=False) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding knew (in main loop, second time)" finished_main_loop = True break # quit # Updating... logging.debug("Updating with knew = %i" % knew) model.update_point(knew, xnew, v_err_list[0, :], f_list[0]) # increments model.npt_so_far, if still growing for i in range(1, nsamples_run): model.add_point_resample(knew, v_err_list[i, :]) # add new info # When growing and don't yet have a full set of directions, we always need a geometry improving step if model.npt_so_far <= model.n + 1: # even after npt function evaluations, still one direction short dnew_matrix = get_new_orthogonal_directions(model, delta_scale_for_new_dirns_when_growing * delta, num_steps=num_geom_steps_when_growing) # breaks below only stop num_geom_steps_when_growing loop, check if need to quit main loop too break_main_loop = False for j in range(num_geom_steps_when_growing): xnew = model.xopt() + dnew_matrix[:, j] logging.debug("Growing: compulsory geometry improving step xnew = %s" % str(xnew)) x = model.x_within_bounds(x=xnew) nsamples_to_use = nsamples(delta, rho, current_iter, nruns_so_far, SCEN_GROWING_NEW_DIRECTION) v_err_list, f_list, nf, nx, nsamples_run, exit_flag, exit_str = \ sample_objective(model.m, objfun, x, nf, nx, maxfun, model.min_objective_value(), nsamples=nsamples_to_use) # Handle exit conditions (f < min obj value or maxfun reached) if exit_flag is not None: # then exit_str is also set if nsamples_run > 0: fmin = np.min(f_list[:nsamples_run]) if fmin < model.fsave: model.xsave = x model.fsave = fmin finished_main_loop = True break_main_loop = True break # quit if model.npt_so_far < model.npt: # still growing kmin = model.npt_so_far logging.debug("Updating point kmin=%g, since still growing" % kmin) else: # full set kmin, linalg_error = choose_knew(model, delta, xnew, skip_kopt=True) if linalg_error: exit_flag = EXIT_LINALG_ERROR exit_str = "Singular matrix when finding kmin (in main loop)" finished_main_loop = True break_main_loop = True break # quit logging.debug("Updating point kmin=%g, chosen in usual way" % kmin) # Otherwise, add new results, incrementing model.npt_so_far (if still growing) model.update_point(kmin, xnew, v_err_list[0, :], f_list[0]) for i in range(1, nsamples_run): model.add_point_resample(kmin, v_err_list[i, :]) # add new info # Finished adding new directions - restart main trust region iteration (if no errors encountered) if break_main_loop: finished_main_loop = True break # quit # If a trust region step has provided a sufficient decrease in F, then # branch for another trust region calculation. if ratio >= 0.1: finished_main_loop = False continue # next trust region step # Alternatively, find out if the interpolation points are close enough # to the best point so far. # [Fortran label 650] distsq = max((2.0 * delta) ** 2, (10.0 * rho) ** 2) model, delta, nf, nx, last_successful_iter, diffs, return_to_new_tr_iteration, geom_exit_flag, geom_exit_str = \ check_and_fix_geometry(model, objfun, distsq, delta, rho, dnorm, diffs, nf, nx, current_iter, last_successful_iter, maxfun, nsamples, rounding_error_const, nruns_so_far, update_delta=False) # don't update delta when ntrits > 0 if return_to_new_tr_iteration is not None: # i.e. if we did actually fix geometry if return_to_new_tr_iteration: finished_main_loop = False continue # next trust region step else: # quit exit_flag = geom_exit_flag exit_str = geom_exit_str finished_main_loop = True break # quit # If we didn't fix geometry, reduce rho [Fortran label 680] if ratio > 0.0: finished_main_loop = False continue # next trust region step if max(delta, dnorm) > rho: finished_main_loop = False continue # next trust region step # Reduce rho and continue [Fortran label 680] if rho > rhoend: delta, rho = reduce_rho(rho, rhoend) logging.info("New rho = %g after %i function evaluations" % (rho, nf)) logging.debug("Best so far: f = %.15g at x = " % (model.fval_opt()) + str(model.xbase + model.xopt())) last_successful_iter = current_iter finished_main_loop = False continue # next trust region step else: # Cannot reduce rho further exit_flag = EXIT_SUCCESS exit_str = "rho has reached rhoend" finished_main_loop = True break # quit ################### # End successful TR step ################### ############################# # End this iteration of main loop - take next TR step ############################# ########################################################### # End of main loop [Fortran label 720] ########################################################### x, f = model.get_final_results() logging.debug("At return from DFOGN, number of function evals = %i" % nf) logging.debug("Smallest objective value = %.15g at x = " % f + str(x)) return x, f, nf, nx, exit_flag, exit_str, model.m def dfogn_resampling(objfun, x0, lower=None, upper=None, maxfun=1000, nsamples=None, init_tr_radius=None, rhoend=1e-8, delta_scale_for_new_dirns_when_growing=1.0, use_random_initial_directions=False, ndirs_initial='n', num_geom_steps_when_growing=1, use_restarts=True, max_unsuccessful_restarts=10): # If bounds not provided, set to something large xl = (lower if lower is not None else -1.0e20 * np.ones(x0.shape)) xu = (upper if upper is not None else 1.0e20 * np.ones(x0.shape)) # Set default value of rhobeg to something sensible rhobeg = (init_tr_radius if init_tr_radius is not None else 0.1 * max(np.max(np.abs(x0)), 1.0)) # Set default number of samples to be 1 for every evaluation if nsamples is None: nsamples_to_use = lambda delta, rho, iter, nruns_so_far, scenario : 1 else: nsamples_to_use = nsamples n = np.size(x0) assert (rhobeg > 0.0), "rhobeg must be strictly positive" assert (rhoend > 0.0), "rhoend must be strictly positive" assert (rhoend < rhobeg), "rhoend must be less than rhobeg" assert (maxfun > 0), "maxfun must be strictly positive" assert (np.shape(x0) == (n,)), "x0 must be a vector" assert (np.shape(x0) == np.shape(xl)), "xl must have same shape as x0" assert (np.shape(x0) == np.shape(x0)), "xu must have same shape as x0" assert (np.all(xu-xl >= 2.0*rhobeg)), "gap between xl and xu must be at least 2*rhobeg" if maxfun <= n+1: logging.warning("Warning (maxfun <= n+1): Are you sure your budget is large enough?") # Parse string arguments: number of geometry steps to take at each growing iteration of main TR loop n_extra_steps_to_use = None if type(num_geom_steps_when_growing) == int: n_extra_steps_to_use = num_geom_steps_when_growing elif type(num_geom_steps_when_growing) == str: if num_geom_steps_when_growing == 'tenthn': n_extra_steps_to_use = int(x0.size // 10) elif num_geom_steps_when_growing == 'fifthn': n_extra_steps_to_use = int(x0.size // 5) elif num_geom_steps_when_growing == 'qtrn': n_extra_steps_to_use = int(x0.size // 4) assert n_extra_steps_to_use is not None, "Unknown num_geom_steps_when_growing: " + str( num_geom_steps_when_growing) n_extra_steps_to_use = max(n_extra_steps_to_use, 1) # floor at 1 # Parse string arguments: number of initial directions to add before beginning main TR loop ndirs_initial_val = None if type(ndirs_initial) == int: ndirs_initial_val = ndirs_initial elif type(ndirs_initial) == str: if ndirs_initial == 'tenthn': ndirs_initial_val = int(n // 10) elif ndirs_initial == 'fifthn': ndirs_initial_val = int(n // 5) elif ndirs_initial == 'qtrn': ndirs_initial_val = int(n // 4) elif ndirs_initial == 'halfn': ndirs_initial_val = int(n // 2) elif ndirs_initial == 'n': ndirs_initial_val = n elif ndirs_initial == '2n': ndirs_initial_val = 2 * n elif ndirs_initial == 'nsq': ndirs_initial_val = (n + 1) * (n + 2) // 2 - 1 assert ndirs_initial_val is not None, "Unknown ndirs_initial: " + str(ndirs_initial) assert ndirs_initial_val == n, "Must have n initial directions (build_interp_matrix assumes this)" ndirs_initial_val = max(ndirs_initial_val, 1) # floor at 1 # Enforce lower bounds on x0 (ideally with gap of at least rhobeg) idx = (xl < x0) & (x0 <= xl+rhobeg) x0[idx] = xl[idx] + rhobeg idx = (x0 <= xl) x0[idx] = xl[idx] # Enforce upper bounds on x0 (ideally with gap of at least rhobeg) idx = (xu-rhobeg <= x0) & (x0 < xu) x0[idx] = xu[idx] - rhobeg idx = (x0 >= xu) x0[idx] = xu[idx] # First run x, f, nf, nx, exit_flag, exit_str, m = \ dfogn_main(objfun, x0, xl, xu, rhobeg, rhoend, maxfun, nsamples_to_use, m=None, delta_scale_for_new_dirns_when_growing=delta_scale_for_new_dirns_when_growing, use_random_initial_directions=use_random_initial_directions, ndirs_initial=ndirs_initial_val, num_geom_steps_when_growing=n_extra_steps_to_use, nf_so_far=0, nx_so_far=0, nruns_so_far=0) # Now do repeats nruns_so_far = 1 reduction_last_run = True # did the last run give us a reduction? rhobeg_to_use = rhobeg rhoend_to_use = rhoend last_successful_run = 1 while use_restarts and nf < maxfun and nruns_so_far - last_successful_run < max_unsuccessful_restarts and \ ((exit_flag == EXIT_SUCCESS and 'rho' in exit_str) or exit_flag in DO_RESTART_ERRORS): if reduction_last_run: rhobeg_to_use = max(0.1 * max(np.max(np.abs(x)), 1.0), 10 * rhoend_to_use) rhoend_to_use = 1.0 * rhoend_to_use else: # Reduce initial TR radius when things have been going badly rhobeg_to_use = max(0.5 * rhobeg_to_use, 10 * rhoend_to_use) logging.info( "Restarting from finish point (f = %g) after %g function evals; new rhobeg = %g and rhoend = %g" % ( f, nf, rhobeg_to_use, rhoend_to_use)) x2, f2, nf, nx, exit_flag, exit_str, m_tmp = \ dfogn_main(objfun, x, xl, xu, rhobeg_to_use, rhoend_to_use, maxfun, nsamples_to_use, m=m, delta_scale_for_new_dirns_when_growing=delta_scale_for_new_dirns_when_growing, use_random_initial_directions=use_random_initial_directions, ndirs_initial=ndirs_initial_val, num_geom_steps_when_growing=n_extra_steps_to_use, nf_so_far=nf, nx_so_far=nx, nruns_so_far=nruns_so_far) nruns_so_far += 1 if f2 < f or np.isnan(f): logging.info("Successful run with new f = %s compared to old f = %s" % (f2, f)) last_successful_run = nruns_so_far x = x2 f = f2 reduction_last_run = True else: logging.info("Unsuccessful run with new f = %s compared to old f = %s" % (f2, f)) reduction_last_run = False logging.info("Finished after a total of %g runs" % nruns_so_far) # Clean up exit_str to have better information: if exit_flag == EXIT_SUCCESS: exit_str = "Success: " + exit_str elif exit_flag == EXIT_MAXFUN_WARNING: exit_str = "Warning: " + exit_str elif exit_flag == EXIT_INPUT_ERROR: exit_str = "Input error: " + exit_str elif exit_flag == EXIT_TR_INCREASE_ERROR: exit_str = "Trust region subproblem error: " + exit_str elif exit_flag == EXIT_LINALG_ERROR: exit_str = "Linear algebra error: " + exit_str elif exit_flag == EXIT_ALTMOV_MEMORY_ERROR: exit_str = "ALTMOV memory error: " + exit_str else: exit_str = "Unknown exit flag " + str(exit_flag) + " with message " + exit_str return x, f, nf, exit_flag, exit_str
numericalalgorithmsgroup/dfogn
dfogn/dfogn_resampling.py
Python
gpl-3.0
58,645
/** * test.c * * * driver test source code * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char *argv[]) { int globalvarfd = 0; fd_set fds; struct timeval tv; int input = 0; globalvarfd = open("/dev/globalvar0", O_RDONLY); if (globalvarfd < 0) { perror("open globalvar0 failed\n"); return -1; } do { FD_ZERO(&fds); FD_SET(globalvarfd, &fds); tv.tv_sec = 5; tv.tv_usec = 0; select(globalvarfd + 1, &fds, NULL, NULL, &tv); if (!FD_ISSET(globalvarfd, &fds)) { printf("no input data in 5 seconds\n"); continue; } read(globalvarfd, &input, sizeof(int)); printf("read:%d\n", input); } while (input != 0xFF); return 0; }
w01230/test
driver/test1/test.c
C
gpl-3.0
789
package algorithms func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { head := &ListNode{} l3 := head for l1 != nil && l2 != nil { if l1.Val < l2.Val { l3.Next = l1 l1 = l1.Next } else { l3.Next = l2 l2 = l2.Next } l3 = l3.Next } if l1 == nil { l3.Next = l2 } if l2 == nil { l3.Next = l1 } return head.Next }
BedivereZero/LeeCode
algorithms/0021-merge-two-sorted-lists.go
GO
gpl-3.0
350
<HTML> <HEAD> <meta charset="UTF-8"> <title>PhraseTag.VNP - koalanlp</title> <link rel="stylesheet" href="../../../style.css"> </HEAD> <BODY> <a href="../../index.html">koalanlp</a>&nbsp;/&nbsp;<a href="../index.html">kr.bydelta.koala</a>&nbsp;/&nbsp;<a href="index.html">PhraseTag</a>&nbsp;/&nbsp;<a href="./-v-n-p.html">VNP</a><br/> <br/> <h1>VNP</h1> <a name="kr.bydelta.koala.PhraseTag.VNP"></a> <code><span class="identifier">VNP</span></code> <a href="https://github.com/koalanlp/koalanlp/blob/master/core/src/main/kotlin/kr/bydelta/koala/types.kt#L358">(source)</a> <p>구문구조 표지자: 긍정지정사구</p> <p>무엇이 무엇이라고 지정하는 단어(이다) 또는 이 역할을 하는 구</p> </BODY> </HTML>
nearbydelta/KoreanAnalyzer
docs/api/koalanlp/kr.bydelta.koala/-phrase-tag/-v-n-p.html
HTML
gpl-3.0
732
package PCA_testcases; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; import org.apache.commons.io.FileUtils; import org.junit.Assert; public class CompareFiles { public static void compare(String one, String two) { compare(one, two, true); } public static void compare(String one, String two, boolean ignoreFirstField)//only use this on small files! (I want it to print the whole thing if it is incorrect) { String first = null; String second = null; try { first = read(one); second = read(two); } catch (IOException e) {e.printStackTrace();} if(ignoreFirstField && first.split("\t").length>1) { first=first.substring(first.indexOf("\t"), first.length()); second=second.substring(second.indexOf("\t"), second.length()); } //remove anything over 5 decimals.. (there are rounding error that I do not care about...) String regex = "(.[0-9]{5})[0-9]*([E\t\n])"; String replace = "$1$2"; first = first.replaceAll(regex, replace); second = second.replaceAll(regex, replace); // first = first.trim(); // second = second.trim(); // System.out.println(first); // System.out.println("\n"); // System.out.println(second); Assert.assertEquals(first,second); } public static String read(String path) throws IOException { BufferedReader reader = null; if(path.endsWith(".gz")) reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(path)))); else reader = new BufferedReader(new FileReader(new File(path))); String file = ""; String line = null; while((line=reader.readLine())!=null) file+=line+"\n"; reader.close(); return file; } }
Sipkovandam/PCrotation
Sipko/src/main/java/PCA_testcases/CompareFiles.java
Java
gpl-3.0
1,891
<?php /** %%%copyright%%% * * FusionTicket - ticket reservation system * Copyright (C) 2007-2013 FusionTicket Solution Limited . All rights reserved. * * Original Design: * phpMyTicket - ticket reservation system * Copyright (C) 2004-2005 Anna Putrino, Stanislav Chachkov. All rights reserved. * * This file is part of FusionTicket. * * This file may be distributed and/or modified under the terms of the * "GNU General Public License" version 3 as published by the Free * Software Foundation and appearing in the file LICENSE included in * the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. * * Any links or references to Fusion Ticket must be left in under our licensing agreement. * * By USING this file you are agreeing to the above terms of use. REMOVING this licence does NOT * remove your obligation to the terms of use. * * The "GNU General Public License" (GPL) is available at * http://www.gnu.org/copyleft/gpl.html. * * Contact help@fusionticket.com if any conditions of this licencing isn't * clear to you. */ if (!defined('ft_check')) {die('System intrusion ');} require_once(INC."classes/redundantdatachecker.php"); require_once(INC."classes".DS."class.model.php"); //require_once(INC."classes".DS."model.organizer.php"); class install_execute { static function precheck($Install, $configpath = false) { global $_SHOP; $tempdir = is($_SESSION['SHOP']['tmp_dir'],ROOT."includes/temp"); RemoveDir($tempdir,false); $install_mode=$_SESSION['radio']; OpenDatabase(); if (!ShopDB::$link) { array_push($Install->Errors,"Can not connect to the database."); return true; } if($install_mode == 'NORMAL'){ $Table_Names = ShopDB::TableList(''); for ($i=0;$i<count($Table_Names);$i++){ ShopDB::query("drop table `{$Table_Names[$i]}`"); } } global $tbls; require_once(ROOT."includes/install/data_db.php"); if ($errors = ShopDB::DatabaseUpgrade($tbls, true)){ foreach ($errors as $data) { if ($data['error']) { $Install->Errors[] = "<pre>".$data['changes']. $data['error']."</pre>"; } } if ($Install->Errors) return true; } if (ShopDB::Tableexists('SPoint')){ $Install->Warnings[] = "<pre>Migrated Spoint table</pre>"; self::MigrateSpoint(); } if (ShopDB::Tableexists('Control')){ $Install->Warnings[] = "<pre>Migrated Control table</pre>"; self::MigrateControl(); } if (ShopDB::Tableexists('Organizer')){ $Install->Warnings[] = "<pre>Removed Organizer table</pre>"; self::renameTables(array('Organizer')); } if (ShopDB::Tableexists('ShopConfig')){ $Install->Warnings[] = "<pre>Removed ShopConfig table</pre>"; self::MigrateShopConfig(); } self::renameTables(array('Color','Payment_log','sessions','Sessions')); if ($install_mode == 'NORMAL'){ // import contens of mysqldump to db if ($error = file_to_db(ROOT."includes/install/base_sql.sql")){ array_push($Install->Errors,$error); return true; } if ($_SESSION['db_demos']==1 and $error = file_to_db(ROOT."includes/install/demo_sql.sql")){ array_push($Install->Errors,$error); return true; } $_SESSION['admin_realname'] = is($_SESSION['admin_realname'],''); $query = "update Admin set admin_login='{$_SESSION['admin_login']}', admin_realname='{$_SESSION['admin_realname']}', admin_password=md5('{$_SESSION['admin_password']}'), admin_status='admin' where admin_id = 1"; if (!shopDB::query($query)){ array_push($Install->Errors,"Admin user can not be created! \n".ShopDB::error()); return true; } } self::recalcStats($Install); self::moveOrderNotes($Install); Orphans::clearZeros('Category', array('category_pm_id','category_event_id','category_pmp_id')); Orphans::clearZeros('Event', array('event_group_id','event_main_id')); Orphans::clearZeros('Order', array('order_owner_id', 'order_admin_id')); Orphans::clearZeros('PlaceMapPart', array('pmp_pm_id','pmp_ort_id','pmp_event_id')); Orphans::clearZeros('Seat', array('seat_category_id','seat_zone_id' ,'seat_user_id' , 'seat_order_id' ,'seat_pmp_id' ,'seat_discount_id')); shopDB::query("UPDATE Template set template_status='new'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='forgot_passwd'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='Signup_email'"); shopDB::query("UPDATE Template set template_type='systm' where template_type='email' and template_name='email_res'"); shopDB::query("UPDATE `Order` set order_payment_status='cancelled' where order_payment_status='canceled'"); shopDB::query("UPDATE `Order` set order_payment_status='paid' where order_payment_status='payed'"); shopDB::query("UPDATE `User` set user_status=1 where user_status=0"); if ((install_execute::CreateConfig($configpath)===false) or !file_exists($configpath)){ array_push($Install->Errors,"Configuration file is not saved correctly check the folder permissions!"); return true; } install_execute::fillConfigDB(); if (getophandata()!=='none') { array_push($Install->Warnings,'After the update the installer found some problems with your database.<br>'. 'To use with the new version we suggest fixing the database or create an new database.'); return true ; } return false; } static function postcheck($Install) { if (is($_POST['fixdatabase'],0)==2) { self::renameTables(array('Category','Discount','Event','Event_group', 'PlaceMap2','PlaceMapPart','PlaceMapZone','Seat','Order')); array_push($Install->Warnings,"The next tables are renamed: Category, Discount, Event, Event_group, PlaceMap2, PlaceMapPart, PlaceMapZone,Seat, Order. You can copy the data back yourself."); } return false; } static function fillConfigDB() { $config = config::load(); $config->_fill($_SESSION['CONFIG']); $config->Save(); } static function fillConfig($array, $suffix, $eq=' = ',$isarray=false){ $arr_type = array('langs_names','valutas','event_group_type_enum','event_type_enum'); $config =($isarray!==2)?'':array(); foreach ($array as $key =>$value) { if (is_int($key)){ $key= ''; if ($isarray===1) { $key = "[]"; } } else { if ($isarray===1) { $key = "['$key']"; } if ($isarray===2) { $key = "'$key'"; } } if (is_array($value)) { $x = (!$isarray and !in_array($key,$arr_type ))?2:(($isarray)?$isarray:1); if ($x==1) { $config .= self::fillConfig($value, $suffix .$key, $eq, $x); } else { $config .= "{$suffix}{$key} {$eq} array("; $item = self::fillConfig($value, '', '=>', $x); $config .= implode(", " ,$item ); $config .= ");\n"; } continue; } elseif(is_null($value)) { $value = 'null'; } elseif(is_bool($value)) { $value = ($value)?'True':'False'; } elseif(is_string($value)) { $value = _esc($value); } If ($isarray==2) { if (strlen(trim("{$suffix}{$key}"))==0) { $config[] = "{$value}"; } else $config[] = "{$suffix}{$key} {$eq} {$value}"; } elseif (strlen(trim("{$suffix}{$key}"))==0) { $config .= "{$value}"; } else $config .= "{$suffix}{$key} {$eq} {$value};\n"; } return $config; } static function CreateConfig(&$configpath) { $storetmp = !empty($configpath); $config = "<?php\n"; $config .= "/**\n"; $config .= " * %%%copyright%%%\n"; $config .= file_get_contents (ROOT."licence.txt")."\n"; $config .= " */\n\n"; $config .= "// Create on: ".date('r')."\n\n"; $config .= "// The following settings are automatically filled by the installation procedure:\n\n"; // $config .= "global \$_SHOP;\n\n"; $config .= "define(\"CURRENT_VERSION\",\"".INSTALL_VERSION."\");\n\n"; unset($_SESSION['SHOP']['install_dir']); if (is($_SESSION['fixed_url'],false)) { $_SESSION['SHOP']['root'] = BASE_URL."/"; if (!isset($_SESSION['SHOP']['root_secured']) or empty($_SESSION['SHOP']['root_secured'])) { $_SESSION['SHOP']['root_secured'] = $_SESSION['SHOP']['root']; } } else { unset ($_SESSION['SHOP']['root']); unset ($_SESSION['SHOP']['root_secured']); if (!$storetmp) {unset ($_SESSION['SHOP']['tmp_dir']); } } if (!is_null($_SESSION['SHOP']['tmp_dir'])) {unset ($_SESSION['SHOP']['tmp_dir']); } if (!isset($_SESSION['SHOP']['secure_id'])) { if (!isset($_SESSION['BASE_URL'])) { $_SESSION['BASE_URL'] = BASE_URL; } $_SESSION['SHOP']['secure_id'] = sha1(AUTH_REALM. $_SESSION['BASE_URL'] . uniqid()); } ksort($_SESSION['SHOP']); $config .= self::fillConfig($_SESSION['SHOP'],'$_SHOP->'); $config .= "\n?>"; $configpath = ($configpath)?$configpath:(ROOT."includes".DS."config".DS."init_config.php"); return file_put_contents($configpath, $config); } static function display($Install) { global $_SHOP, $orphancheck; OpenDatabase(); if(isset($_GET['fix'])){ Orphans::dofix($_GET['fix']); } $data = Orphans::getlist($keys,true,"&do=fix&inst_mode=post&inst_pg={$Install->return_pg}"); $space = (count($keys)*60 < 780 -200)?1:0; Install_Form_Open ($Install->return_pg,'', 'Database Orphan check'); echo "<table cellpadding=\"1\" cellspacing=\"2\" width='100%'> <tr><td> The list below gives you a view of the orphans in your database. Look at our website for instructions how to fix this or contact us on the forum or IRC. To be safe, we suggest creating a new database and importing the common information. This can be done by the installer. </td></tr> <tr> <td height='6px'></td> </tr> <tr> <td> <input type=\"radio\" name=\"fixdatabase\" value=\"1\" id='fixdatabase1' checked /><label for='fixdatabase1'> Fix tables manual </label> <input type=\"radio\" name=\"fixdatabase\" value=\"2\" id='fixdatabase2' /><label for='fixdatabase2'> Recreate tables </label> </td> </tr> </table>"; echo "<div style='overflow: auto; height: 250px; width:100%; border: 1'>"; echo "<table cellpadding=\"1\" cellspacing=\"2\" width='100%'>"; print " <tr class='admin_list_header'> <th width=130 align='left'> Tablename </th> <th width=50 align='right'> ID </th>"; foreach ($keys as $key) { print "<th width=60 align='center'> {$key}&nbsp;</th>"; } if ($space) { print "<th align='center'>&nbsp;</th>"; } print "</tr>"; $alt =0; foreach ($data as $row) { print "<tr class='admin_list_row_$alt'> <td class='admin_list_item'>{$row['_table']}</td> <td class='admin_list_item' align='right'>{$row['_id']}</td>\n"; foreach ($keys as $key) { print "<td align='center'>".((isset($row[$key]))?$row[$key]:'&nbsp;')."</td>\n"; } if ($space) { print "<th align='center'>&nbsp;</th>"; } print "</tr>"; $alt = ($alt + 1) % 2; } echo "</table></div>\n"; Install_Form_Buttons (); Install_Form_Close (); } static function checkadmin($name) { $query="select Count(*) as count from Admin where admin_login= "._esc($name); if(!$res=ShopDB::query_one_row($query)){ user_error(shopDB::error()); } else return ($res["count"]>0); } static function MigrateSpoint() { $query = "select * from SPoint"; $res = ShopDB::Query($query); while ($row = ShopDB::fetch_assoc($res)){ If (self::checkAdmin($row['login'])) $row['login'] = "pos~{$row['login']}"; $query = "INSERT INTO `Admin` SET ". "admin_login = '{$row['login']}', admin_password = '{$row['password']}', admin_user_id = '{$row['user_id']}', admin_status = 'pos'"; ShopDB::query($query); } $sql = "RENAME TABLE `SPoint` TO `old_spoint`"; // The MySQL way. ShopDB::query($sql); } static function MigrateShopConfig() { $query = "select * from ShopConfig"; $res = ShopDB::Query($query); $row = ShopDB::fetch_assoc($res); foreach($row as $key => $value) { $_SESSION['CONFIG'][$key] = $value; } $sql = "RENAME TABLE `ShopConfig` TO `old_shopconfig`"; // The MySQL way. ShopDB::query($sql); } static function MigrateControl(){ $query = "select * from `Control`"; $res = ShopDB::Query($query); while ($row = ShopDB::fetch_assoc($res)){ If (self::checkAdmin($row['control_login'])) $row['control_login'] = "tt~{$row['control_login']}"; $query = "INSERT INTO `Admin` SET ". "admin_login = '{$row['control_login']}', admin_password = '{$row['control_password']}', control_event_ids = '{$row['control_event_ids']}', admin_status = 'control'"; ShopDB::query($query); } $sql = "RENAME TABLE `Control` TO `old_control`"; // The MySQL way. ShopDB::query($sql); } static function renameTables($array) { if (is_array($array)) { foreach($array as $table) { $no = ''; if (ShopDB::Tableexists($table)) { while (ShopDB::TableExists("old{$no}_{$table}")) { $no = (int)$no +1; } $sql = "RENAME TABLE `{$table}` TO `old{$no}_{$table}`"; // The MySQL way. ShopDB::query($sql); } } } } static function recalcStats($Install) { if (ShopDB::TableExists ('Event_stat')) { ShopDB::Query("update Event set event_free = (select count(*) from `Seat` where seat_event_id = event_id and seat_status IN ('res','free','trash') and seat_user_id IS NULL and seat_order_id IS NULL ), event_total = (select count(*) from `Seat` where seat_event_id = event_id)"); ShopDB::Query("update Category set category_free = (select count(*) from `Seat` where seat_category_id = category_id and seat_status in ('res', 'free','trash') and seat_user_id IS NULL and seat_order_id IS NULL)"); array_push($Install->Warnings,"We moved the statistics information back to there main table this gives us a more stable system."); self::renameTables(array('Category_stat','Event_stat')); } } /** * install_execute::moveOrderNotes() * * Move order notes to new order_notes table * * @return void */ static function moveOrderNotes($Install){ $rec = is(ShopDB::query_one_row("SELECT COUNT(*) FROM `Order` WHERE order_note IS NOT NULL"),array(0)); if(isset($rec[0]) && $rec[0] >0 ){ $query = "INSERT INTO `order_note` (`onote_order_id`,`onote_subject`,`onote_note`) SELECT order_id,'Old Note',order_note FROM `Order` WHERE order_note IS NOT NULL"; if(ShopDB::query($query)){ $query = "UPDATE `Order` SET order_note = NULL WHERE order_note IS NULL"; ShopDB::query($query); } array_push($Install->Warnings,"Moved the Order Note to there new location!"); } } } ?>
fusionticket/FTS_RC1
includes/install/install_execute.php
PHP
gpl-3.0
16,737
CREATE TABLE "oeig_monthly_report_january_2013_pending_investigations_as_of_december_31_2012_" ( "january_2013" text, "number" real );
talos/docker4data
data/socrata/data.illinois.gov/oeig_monthly_report_january_2013_pending_investigations_as_of_december_31_2012_/schema.sql
SQL
gpl-3.0
137
<?php namespace simvc\lib\request; abstract class DecoratorRequest extends ProcessRequest{ protected $request; public function __construct( ProcessRequest $request ){ $this -> request = $request; } } ?>
yiyide266/simvc
simvc/lib/request/DecoratorRequest.class.php
PHP
gpl-3.0
212
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Tue Oct 20 10:34:57 CEST 2015 --> <title>Uses of Class ch.ethz.inspire.emod.model.PumpAccumulatorTest</title> <meta name="date" content="2015-10-20"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class ch.ethz.inspire.emod.model.PumpAccumulatorTest"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/model/PumpAccumulatorTest.html" title="class in ch.ethz.inspire.emod.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/class-use/PumpAccumulatorTest.html" target="_top">Frames</a></li> <li><a href="PumpAccumulatorTest.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class ch.ethz.inspire.emod.model.PumpAccumulatorTest" class="title">Uses of Class<br>ch.ethz.inspire.emod.model.PumpAccumulatorTest</h2> </div> <div class="classUseContainer">No usage of ch.ethz.inspire.emod.model.PumpAccumulatorTest</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/model/PumpAccumulatorTest.html" title="class in ch.ethz.inspire.emod.model">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/class-use/PumpAccumulatorTest.html" target="_top">Frames</a></li> <li><a href="PumpAccumulatorTest.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
sizuest/EMod
ch.ethz.inspire.emod/doc/ch/ethz/inspire/emod/model/class-use/PumpAccumulatorTest.html
HTML
gpl-3.0
4,297
package de.deepamehta.storage.neo4j; import de.deepamehta.core.storage.spi.DeepaMehtaTransaction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; /** * Adapts a Neo4j transaction to a DeepaMehta transaction. */ class Neo4jTransactionAdapter implements DeepaMehtaTransaction { // ---------------------------------------------------------------------------------------------- Instance Variables private Transaction tx; // ---------------------------------------------------------------------------------------------------- Constructors Neo4jTransactionAdapter(GraphDatabaseService neo4j) { tx = neo4j.beginTx(); } // -------------------------------------------------------------------------------------------------- Public Methods @Override public void success() { tx.success(); } @Override public void failure() { tx.failure(); } @Override public void finish() { tx.finish(); } }
ascherer/deepamehta
modules/dm4-storage-neo4j/src/main/java/de/deepamehta/storage/neo4j/Neo4jTransactionAdapter.java
Java
gpl-3.0
1,023
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class W3Effect_PoisonCritical : W3CriticalDOTEffect { public W3Effect_PoisonCritical(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3Effect_PoisonCritical(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/W3Effect_PoisonCritical.cs
C#
gpl-3.0
691
# arvinall.github.io ALL's poetry, prose and rhythmic prose, collection [download the android webapp](https://github.com/arvinall/arvinall.github.io/releases/download/v1.0.0/ALLRhythmicProse.apk)
arvinall/arvinall.github.io
README.md
Markdown
gpl-3.0
197
#page-local-report_users-index .col-md-9 { clear:both; }
lernlink/iomad-ll
local/report_users/styles.css
CSS
gpl-3.0
61
/** * This file is part of libtools * * libtools is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * libtools is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with libtools. If not, see <http:www.gnu.org/licenses/>. */ #ifndef _TOOLS_S_RB_TREE_PRIVATE_H_ # define _TOOLS_S_RB_TREE_PRIVATE_H_ # include "tree/s_rb_tree.h" /** * @brief Color for a specific node */ enum _e_color { _e_red, _e_black, _e_d_black }; /** * @brief The binary search tree structure * @param data: user data stored * @param color: the color associate to the node * @param parent: parent node * @param left: left child * @param right: right child */ struct s_rb_tree { void *data; enum _e_color color; struct s_rb_tree *parent; struct s_rb_tree *left; struct s_rb_tree *right; }; /** * @brief A convenience macro to get the data in an element. */ # define m_rb_tree_get_data(tree) ((tree) ? (tree)->data : NULL) /** * @brief A convenience macro to get the data in an element. */ # define m_rb_tree_get_color(tree) ((tree) ? (tree)->color : _e_black) /** * @brief A convenience macro to get the left element of a node. */ # define m_rb_tree_get_left(tree) ((tree) ? (tree)->left : NULL) /** * @brief A convenience macro to get the right element of a node. */ # define m_rb_tree_get_right(tree) ((tree) ? (tree)->right : NULL) /** * @brief A convenience macro to get the parent node of a node */ # define m_rb_tree_get_parent(tree) ((tree) ? (tree)->parent : NULL) /** * @brief A convenience macro to get the grand parent node of a node */ # define m_rb_tree_get_grand_parent(tree) \ m_rb_tree_get_parent(m_rb_tree_get_parent(tree)) /** * @brief A convenience macro to get sibling node of a node */ # define m_rb_tree_get_sibling(tree) \ (m_rb_tree_get_left(m_rb_tree_get_parent(tree)) == tree ? \ m_rb_tree_get_right(m_rb_tree_get_parent(tree)) : \ m_rb_tree_get_left(m_rb_tree_get_parent(tree))) /** * @brief A convenience macro to get the position of the node according to its * parent (ie get 1 is node is the left one) */ # define m_rb_tree_is_left(parent, node) \ ((parent) ? (parent)->left == node : 0) /** * @brief A convenience macro to get the position of the node according to its * parent (ie get 1 is node is the right one) */ # define m_rb_tree_is_right(parent, node) \ ((parent) ? (parent)->right == node : 0) # define m_rb_tree_is_black(node) \ ((node)->color == _e_black || (node)->color == _e_d_black) /** * @brief A convenience macro to change the data of a specific node */ # define m_rb_tree_set_data(tree, value) { \ do { \ if (tree) { \ (tree)->data = value; \ } \ } while (0); \ } /** * @brief A convenience macro to change the color of a specific node */ # define m_rb_tree_set_color(tree, col) { \ do { \ if (tree) { \ (tree)->color = col; \ } \ } while (0); \ } /** * @brief A convenience macro to get the parent node of a node */ # define m_rb_tree_set_parent(tree, node) { \ do { \ if (tree) { \ (tree)->parent = (node); \ } \ } while (0); \ } /** * @brief A convenience macro to change the left of a specific node */ # define m_rb_tree_set_left(tree, node) { \ do { \ if (tree) { \ (tree)->left = node; \ } \ } while (0); \ } /** * @brief A convenience macro to change the right of a specific node */ # define m_rb_tree_set_right(tree, node) { \ do { \ if (tree) { \ (tree)->right = node; \ } \ } while (0); \ } /** * @brief A convenience macro to switch data from dst to src */ # define m_rb_tree_switch_data(dst, src, destroy) { \ do { \ if (destroy) { \ destroy(m_rb_tree_get_data(dst)); \ } \ m_rb_tree_set_data(dst, m_rb_tree_get_data(src)); \ } while (0); \ } /** * @brief Get the uncle of a specific node * @param tree[in] : node to browse * @return a valid pointer on success, NULL on error or not found */ struct s_rb_tree *_s_rb_tree_get_uncle(struct s_rb_tree *tree); /** * @brief Perform a right rotate operation on node * @param node[in] : node to rotate * @return return the new root */ void _s_rb_tree_right_rotate(struct s_rb_tree *a); /** * @brief Perform a left rotate operation on node * @param node[in] : node to rotate * @return the new root of that rotation */ void _s_rb_tree_left_rotate(struct s_rb_tree *a); #endif /* !_TOOLS_S_RB_TREE_PRIVATE_H_ */
lecseb/tools
src/tree/s_rb_tree-private.h
C
gpl-3.0
4,778
// // DecisionTreeQuestion.h // ios-galaxyzoo // // Created by Murray Cumming on 04/05/2015. // Copyright (c) 2015 Murray Cumming. All rights reserved. // #import "DecisionTreeQuestionAnswer.h" #import "DecisionTreeQuestionCheckbox.h" #import <Foundation/Foundation.h> @interface DecisionTreeQuestion : NSObject @property (nonatomic, copy) NSString *questionId; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *text; @property (nonatomic, copy) NSString *help; @property (nonatomic, copy) NSArray *answers; //of DecisionTreeAnswer @property (nonatomic, copy) NSArray *checkboxes; //of DecisionTreeCheckbox - (instancetype)init NS_DESIGNATED_INITIALIZER; - (instancetype)initWithDetails:(NSString *)questionId title:(NSString *)title text:(NSString *)text help:(NSString *)help answers:(NSArray *)answers checkboxes:(NSArray *)checkboxes; - (DecisionTreeQuestionAnswer*) answerForId:(NSString *)answerId; - (DecisionTreeQuestionCheckbox*) checkboxForId:(NSString *)answerId; @end
murraycu/ios-galaxyzoo
ios-galaxyzoo/DecisionTree/DecisionTreeQuestion.h
C
gpl-3.0
1,145
/* * _____ _ _ _____ _ * | __ \| | | | / ____| | | * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| * | | * |_| * PlotSquared plot management system for Minecraft * Copyright (C) 2021 IntellectualSites * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.plotsquared.core.plot.flag.implementations; import com.plotsquared.core.configuration.caption.TranslatableCaption; import com.plotsquared.core.plot.flag.types.BooleanFlag; import org.checkerframework.checker.nullness.qual.NonNull; public class HangingPlaceFlag extends BooleanFlag<HangingPlaceFlag> { public static final HangingPlaceFlag HANGING_PLACE_TRUE = new HangingPlaceFlag(true); public static final HangingPlaceFlag HANGING_PLACE_FALSE = new HangingPlaceFlag(false); private HangingPlaceFlag(boolean value) { super(value, TranslatableCaption.miniMessage("flags.flag_description_hanging_place")); } @Override protected HangingPlaceFlag flagOf(@NonNull Boolean value) { return value ? HANGING_PLACE_TRUE : HANGING_PLACE_FALSE; } }
IntellectualCrafters/PlotSquared
Core/src/main/java/com/plotsquared/core/plot/flag/implementations/HangingPlaceFlag.java
Java
gpl-3.0
2,113
<?php if (!defined('IDIR')) { die; } /*======================================================================*\ || #################################################################### || || # vBulletin - Licence Number VBF98A5CB5 || # ---------------------------------------------------------------- # || || # All PHP code in this file is ©2000-2006 Jelsoft Enterprises Ltd. # || || # This file may not be redistributed in whole or significant part. # || || # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # || || # http://www.vbulletin.com | http://www.vbulletin.com/license.html # || || #################################################################### || \*======================================================================*/ /** * deluxeportal_007 Import Post module * * @package ImpEx.deluxeportal * @version $Revision: 1.5 $ * @author Jerry Hutchings <jerry.hutchings@vbulletin.com> * @checkedout $Name: $ * @date $Date: 2006/04/03 02:57:11 $ * @copyright http://www.vbulletin.com/license.html * */ class deluxeportal_007 extends deluxeportal_000 { var $_version = '0.0.1'; var $_dependent = '006'; var $_modulestring = 'Import Post'; function deluxeportal_007() { // Constructor } function init(&$sessionobject, &$displayobject, &$Db_target, &$Db_source) { if ($this->check_order($sessionobject,$this->_dependent)) { if ($this->_restart) { if ($this->restart($sessionobject, $displayobject, $Db_target, $Db_source,'clear_imported_posts')) { $displayobject->display_now('<h4>Imported posts have been cleared</h4>'); $this->_restart = true; } else { $sessionobject->add_error('fatal', $this->_modulestring, get_class($this) . '::restart failed , clear_imported_posts','Check database permissions'); } } // Start up the table $displayobject->update_basic('title','Import Post'); $displayobject->update_html($displayobject->do_form_header('index',substr(get_class($this) , -3))); $displayobject->update_html($displayobject->make_hidden_code(substr(get_class($this) , -3),'WORKING')); $displayobject->update_html($displayobject->make_hidden_code('import_post','working')); $displayobject->update_html($displayobject->make_table_header($this->_modulestring)); // Ask some questions $displayobject->update_html($displayobject->make_input_code('Posts to import per cycle (must be greater than 1)','postperpage',500)); // End the table $displayobject->update_html($displayobject->do_form_footer('Continue','Reset')); // Reset/Setup counters for this $sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_done', '0'); $sessionobject->add_session_var(substr(get_class($this) , -3) . '_objects_failed', '0'); $sessionobject->add_session_var('poststartat','0'); $sessionobject->add_session_var('postdone','0'); } else { // Dependant has not been run $displayobject->update_html($displayobject->do_form_header('index','')); $displayobject->update_html($displayobject->make_description('<p>This module is dependent on <i><b>' . $sessionobject->get_module_title($this->_dependent) . '</b></i> cannot run until that is complete.')); $displayobject->update_html($displayobject->do_form_footer('Continue','')); $sessionobject->set_session_var(substr(get_class($this) , -3),'FALSE'); $sessionobject->set_session_var('module','000'); } } function resume(&$sessionobject, &$displayobject, &$Db_target, &$Db_source) { // Set up working variables. $displayobject->update_basic('displaymodules','FALSE'); $target_database_type = $sessionobject->get_session_var('targetdatabasetype'); $target_table_prefix = $sessionobject->get_session_var('targettableprefix'); $source_database_type = $sessionobject->get_session_var('sourcedatabasetype'); $source_table_prefix = $sessionobject->get_session_var('sourcetableprefix'); // Per page vars $post_start_at = $sessionobject->get_session_var('poststartat'); $post_per_page = $sessionobject->get_session_var('postperpage'); $class_num = substr(get_class($this) , -3); // Start the timing if(!$sessionobject->get_session_var($class_num . '_start')) { $sessionobject->timing($class_num ,'start' ,$sessionobject->get_session_var('autosubmit')); } // Get an array of post details $post_array = $this->get_deluxeportal_post_details($Db_source, $source_database_type, $source_table_prefix, $post_start_at, $post_per_page); $user_ids_array = $this->get_user_ids($Db_target, $target_database_type, $target_table_prefix, $do_int_val = false); $thread_ids_array = $this->get_threads_ids($Db_target, $target_database_type, $target_table_prefix); // Display count and pass time $displayobject->display_now('<h4>Importing ' . count($post_array) . ' posts</h4><p><b>From</b> : ' . $post_start_at . ' :: <b>To</b> : ' . ($post_start_at + count($post_array)) . '</p>'); $post_object = new ImpExData($Db_target, $sessionobject, 'post'); foreach ($post_array as $post_id => $post_details) { $try = (phpversion() < '5' ? $post_object : clone($post_object)); // Mandatory $try->set_value('mandatory', 'threadid', $thread_ids_array["$post_details[threadid]"]); $try->set_value('mandatory', 'userid', $user_ids_array["$post_details[userid]"]); $try->set_value('mandatory', 'importthreadid', $post_details['threadid']); // Non Mandatory #$try->set_value('nonmandatory', 'parentid', $post_details['parentid']); $try->set_value('nonmandatory', 'username', $post_details['username']); $try->set_value('nonmandatory', 'title', $post_details['subject']); $try->set_value('nonmandatory', 'dateline', $post_details['postdate']); $try->set_value('nonmandatory', 'pagetext', $this->html_2_bb($this->deluxeportal_html($post_details['message']))); $try->set_value('nonmandatory', 'allowsmilie', $post_details['smilies']); $try->set_value('nonmandatory', 'showsignature', $post_details['showsignature']); $try->set_value('nonmandatory', 'ipaddress', $post_details['ip']); $try->set_value('nonmandatory', 'iconid', $post_details['iconid']); $try->set_value('nonmandatory', 'visible', '1'); #$try->set_value('nonmandatory', 'attach', $post_details['attach']); $try->set_value('nonmandatory', 'importpostid', $post_details['postid']); // Check if post object is valid if($try->is_valid()) { if($try->import_post($Db_target, $target_database_type, $target_table_prefix)) { $displayobject->display_now('<br /><span class="isucc"><b>' . $try->how_complete() . '%</b></span> :: post from -> ' . $post_details['username']); $sessionobject->add_session_var($class_num . '_objects_done',intval($sessionobject->get_session_var($class_num . '_objects_done')) + 1 ); } else { $sessionobject->set_session_var($class_num . '_objects_failed',$sessionobject->get_session_var($class_num. '_objects_failed') + 1 ); $sessionobject->add_error('warning', $this->_modulestring, get_class($this) . '::import_custom_profile_pic failed.', 'Check database permissions and database table'); $displayobject->display_now("<br />Found avatar post and <b>DID NOT</b> imported to the {$target_database_type} database"); } } else { $displayobject->display_now("<br />Invalid post object, skipping." . $try->_failedon); } unset($try); }// End foreach // Check for page end if (count($post_array) == 0 OR count($post_array) < $post_per_page) { $sessionobject->timing($class_num,'stop', $sessionobject->get_session_var('autosubmit')); $sessionobject->remove_session_var($class_num . '_start'); $displayobject->display_now('Updateing parent ids to allow for a threaded view....'); if ($this->update_post_parent_ids($Db_target, $target_database_type, $target_table_prefix)) { $displayobject->display_now('Done !'); } else { $displayobject->display_now('Error updating parent ids'); } $displayobject->update_html($displayobject->module_finished($this->_modulestring, $sessionobject->return_stats($class_num, '_time_taken'), $sessionobject->return_stats($class_num, '_objects_done'), $sessionobject->return_stats($class_num, '_objects_failed') )); $sessionobject->set_session_var($class_num ,'FINISHED'); $sessionobject->set_session_var('import_post','done'); $sessionobject->set_session_var('module','000'); $sessionobject->set_session_var('autosubmit','0'); $displayobject->update_html($displayobject->print_redirect('index.php','1')); } $sessionobject->set_session_var('poststartat',$post_start_at+$post_per_page); $displayobject->update_html($displayobject->print_redirect('index.php')); }// End resume }//End Class # Autogenerated on : September 11, 2004, 2:50 pm # By ImpEx-generator 1.0. /*======================================================================*\ || #################################################################### || # Downloaded: 03:45, Mon Nov 13th 2006 || # CVS: $RCSfile: 007.php,v $ - $Revision: 1.5 $ || #################################################################### \*======================================================================*/ ?>
chrisplough/otmfaq
otmfaq.com/htdocs/forums/impex/systems/deluxeportal/007.php
PHP
gpl-3.0
9,316
/* * Copyright (C) 2012, 2013 Paul Grégoire * * This file is part of AIWar. * * AIWar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AIWar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AIWar. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MININGSHIP_HPP #define MININGSHIP_HPP #include <ostream> #include "item.hpp" #include "movable.hpp" #include "living.hpp" #include "playable.hpp" #include "memory.hpp" namespace aiwar { namespace core { class Mineral; class Base; class MiningShip : virtual public Item, public Movable, public Living, public Playable, public Memory { public: MiningShip(GameManager& gm, Key k, double xpos, double ypos, Team team, PlayFunction& pf); ~MiningShip(); void update(unsigned int tick); unsigned int extract(Mineral *m); unsigned int mineralStorage() const; unsigned int pushMineral(Base *base, unsigned int mineralPoints); // helper function only called by a base item unsigned int _release(unsigned int mineralPoint); std::string _dump() const; private: /** * \brief Initialize the MiningShip * * Reset _hasExtracted */ void _preUpdate(unsigned int tick); void _setMineralStorage(int n); unsigned int _mineralStorage; ///< Number of mineral units stored bool _hasExtracted; }; } // namespace aiwar::core } // namespace aiwar std::ostream& operator<< (std::ostream& os, const aiwar::core::MiningShip& t); #endif /* MININGSHIP_HPP */
merovingien/AIWar
miningship.hpp
C++
gpl-3.0
2,149
<img src="<?php echo get_bloginfo('wpurl');?>/wp-content/plugins/native-apps-builder/img/logo.png" /> <style type="text/css"> <?php require_once("login.css"); ?> </style> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#registerform").bind("submit",function(e){ //e.preventDefault(); //e.stopPropagation(); if(!jQuery("#terms").prop("checked")){ return false; } return true; }); }); </script> <?php if(isset($msg)){ echo "<div style='border:1px dashed red; padding:15px;color:red;font-size:16px;margin:6px;'><span><strong>".$msg."</strong></span></div>"; } ?> <div class="metabox-holder"> <div class="postbox"> <h3>Login your AppsBuilder account</h3> <form method="POST" action="" id="loginform"> <table class="form-table"> <tr><th scope="row"><strong>Username :</strong></th><td> <input name="username" type="text" value="" size="45"/></td></tr> <tr><th scope="row"><strong>Password :</strong></th><td> <input name="password" type="password" size="45"/></td></tr> <tr><th scope="row"></th><td><input name="page" type="hidden" value="login" /><input class="button-primary" type="submit" value="login"/></td></tr> </table> </form> </div> </div> <h3>.. OR ..</h3> <div class="metabox-holder"> <div class="postbox"> <h3>Not registered yet? Fill the fields below and sign in now!</h3> <form method="POST" action="" id="registerform"> <table class="form-table" > <tr><th scope="row"><strong>Username :</strong></th><td> <input name="username" type="text" value="" size="45"/></td></tr> <tr><th scope="row"><strong>Password :</strong></th><td> <input name="password" type="password" size="45"/></td></tr> <tr><th scope="row"><strong>Email :</strong></th><td> <input name="email" type="text" value="" size="45"/></td></tr> <tr><th scope="row"></th><td><input id="terms" type="checkbox" name="terms"><a href="http://www.apps-builder.com/pag/terms"> I have read and agreed the following terms and conditions</a></td></tr> <input name="page" type="hidden" value="register"/> <tr><th scope="row"></th><td><input type="submit" value="REGISTER NOW" class="button-primary"/></td></tr> </table> </form> </div> </div> <?php include_once('footer.php'); ?>
wp-plugins/native-apps-builder
login/login.php
PHP
gpl-3.0
2,266
/* Group C TCAS Project https://github.com/ericloewe/TCAS Sistemas Aviónicos Integrados 2016/2017 Instituto Superior Técnico Copyright 2017 Simão Marto 75326 Eric Loewenthal 75848 João Martins 76964 This software is licensed under the terms of the GNU General Public License version 3. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. TCAS_sim: The actual TCAS work happens here */ #pragma once #include <unistd.h> #include <vector> #include <thread> #include <string.h> #include "TCAS_defs.h" #include "AC_sim.h" #include "TCAS_comms.h" #include "Radar.h" class TCAS_sim { public: const static int NumOfTargets = MAX_TARGETS; //Maximum??? private: AC_sim own_State_sim; TCAS_state own_TCAS_State; broadcast_socket* socket_ptr; std::vector<AC_state> targetStates; std::vector<TCAS_state> target_TCAS_States; //Used to communicate with the socket void UpdateOwnState(); void UpdateTargetStates(); //Function to have its own thread, and its thread handler void sim_thread_fn(); std::thread sim_thread; //Performs the decisions characterstic of a TCAS system bool resolve(int which_target); void Actual_TCAS(); const double min_safe_distance = 600; //m const double min_return_distance = 1000; //m const double Resolution_Time = 30; //s const double Advisory_Time = 40; //s bool continueLoop = true; bool analyse_collision_danger(const int which_target, double &time_to_approach); //returns weather this aircraft will be or is within min_safe_distance of our aircraft public: TCAS_sim(AC_sim new_State_sim, broadcast_socket* new_socket_ptr); TCAS_state get_own_TCAS_State(); std::vector<AC_state> get_targetStates(); AC_sim getAC_sim(); }; double internal_product(double A[3], double B[3]); void printState (AC_state state);
ericloewe/TCAS
TCAS_sim.h
C
gpl-3.0
2,479
DEVICE = attiny85 # I don't promise it will work with anything else F_CPU = 16500000 FLASH=./micronucleus # If you don't use micronucleus # FLASH=avrdude -c usbasp -p$(DEVICE) #OPTFLAGS = -Os OPTFLAGS = -O3 -flto -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -finline-limit=3 -fno-inline-small-functions -ffunction-sections -fdata-sections -ffreestanding -Wl,--relax -mcall-prologues -fno-tree-scev-cprop -fno-split-wide-types INCLUDES = -Iv-usb/libs-device -I. -Iv-usb/usbdrv -DDEBUG_LEVEL=0 CFLAGS = $(OPTFLAGS) -Wall $(INCLUDES) -mmcu=$(DEVICE) -DF_CPU=$(F_CPU) OBJECTS = main.o light_ws2812.o v-usb/usbdrv/usbdrv.o v-usb/usbdrv/oddebug.o v-usb/libs-device/osccal.o v-usb/usbdrv/usbdrvasm.o COMPILE= avr-gcc $(CFLAGS) .S.o: $(COMPILE) -x assembler-with-cpp -c $< -o $@ .c.o: $(COMPILE) -c $< -o $@ flash: hex $(FLASH) main.hex main.elf: $(OBJECTS) $(COMPILE) $(OBJECTS) -o $@ main.hex: main.elf avr-objcopy -j .text -j .data -O ihex main.elf main.hex avr-size main.hex hex: main.hex clean: rm -f main.hex main.elf $(OBJECTS)
bjonnh/pomodocube
Makefile
Makefile
gpl-3.0
1,067
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GWpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GWpy. If not, see <http://www.gnu.org/licenses/>. """Basic utilities for reading/writing LIGO_LW-format XML files. All specific unified input/output for class objects should be placed in an 'io' subdirectory of the containing directory for that class. """ import os import os.path from contextlib import contextmanager from functools import wraps from importlib import import_module import numpy try: from ligo.lw.ligolw import ( ElementError as LigolwElementError, LIGOLWContentHandler, ) except ImportError: # no ligo.lw LigolwElementError = None LIGOLWContentHandler = None from .utils import (file_list, FILE_LIKE) from ..utils.decorators import deprecated_function __author__ = 'Duncan Macleod <duncan.macleod@ligo.org>' # XML elements XML_SIGNATURE = b'<?xml' LIGOLW_SIGNATURE = b'<!doctype ligo_lw' LIGOLW_ELEMENT = b'<ligo_lw>' # -- hack around around TypeError from LIGOTimeGPS(numpy.int32(...)) ---------- def _ligotimegps(s, ns=0): """Catch TypeError and cast `s` and `ns` to `int` """ from lal import LIGOTimeGPS try: return LIGOTimeGPS(s, ns) except TypeError: return LIGOTimeGPS(int(s), int(ns)) @contextmanager def patch_ligotimegps(module="ligo.lw.lsctables"): """Context manager to on-the-fly patch LIGOTimeGPS to accept all int types """ module = import_module(module) orig = module.LIGOTimeGPS module.LIGOTimeGPS = _ligotimegps try: yield finally: module.LIGOTimeGPS = orig # -- content handling --------------------------------------------------------- def strip_ilwdchar(_ContentHandler): """Wrap a LIGO_LW content handler to swap ilwdchar for int on-the-fly when reading a document This is adapted from :func:`ligo.skymap.utils.ilwd`, copyright Leo Singer (GPL-3.0-or-later). """ from ligo.lw.lsctables import TableByName from ligo.lw.table import (Column, TableStream) from ligo.lw.types import (FromPyType, ToPyType) class IlwdMapContentHandler(_ContentHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._idconverter = {} @wraps(_ContentHandler.startColumn) def startColumn(self, parent, attrs): result = super().startColumn(parent, attrs) # if an old ID type, convert type definition to an int if result.Type == "ilwd:char": old_type = ToPyType[result.Type] def converter(old): return int(old_type(old)) self._idconverter[(id(parent), result.Name)] = converter result.Type = FromPyType[int] try: validcolumns = TableByName[parent.Name].validcolumns except KeyError: # parent.Name not in TableByName return result if result.Name not in validcolumns: stripped_column_to_valid_column = { Column.ColumnName(name): name for name in validcolumns } if result.Name in stripped_column_to_valid_column: result.setAttribute( 'Name', stripped_column_to_valid_column[result.Name], ) return result @wraps(_ContentHandler.startStream) def startStream(self, parent, attrs): result = super().startStream(parent, attrs) if isinstance(result, TableStream): loadcolumns = set(parent.columnnames) if parent.loadcolumns is not None: loadcolumns &= set(parent.loadcolumns) pid = id(parent) result._tokenizer.set_types([ self._idconverter.pop((pid, colname), pytype) if colname in loadcolumns else None for pytype, colname in zip( parent.columnpytypes, parent.columnnames, ) ]) return result return IlwdMapContentHandler def _wrap_content_handler(contenthandler): from ligo.lw.lsctables import use_in @strip_ilwdchar @use_in class ContentHandler(contenthandler): pass return ContentHandler def default_content_handler(): """Return a standard content handler to read LIGO_LW documents This handler knows how to parse LSCTables, and automatically converts old-style ilwdchar ID types to `int`. Returns ------- contenthandler : subclass of `ligo.lw.ligolw.LIGOLWContentHandler` """ from ligo.lw.ligolw import LIGOLWContentHandler return _wrap_content_handler(LIGOLWContentHandler) def get_partial_contenthandler(element): """Build a `PartialLIGOLWContentHandler` to read only this element Parameters ---------- element : `type`, subclass of :class:`~ligo.lw.ligolw.Element` the element class to be read Returns ------- contenthandler : `type` a subclass of `~ligo.lw.ligolw.PartialLIGOLWContentHandler` to read only the given `element` """ from ligo.lw.ligolw import PartialLIGOLWContentHandler from ligo.lw.table import Table if issubclass(element, Table): def _element_filter(name, attrs): return element.CheckProperties(name, attrs) else: def _element_filter(name, _): return name == element.tagName return build_content_handler(PartialLIGOLWContentHandler, _element_filter) def get_filtering_contenthandler(element): """Build a `FilteringLIGOLWContentHandler` to exclude this element Parameters ---------- element : `type`, subclass of :class:`~ligo.lw.ligolw.Element` the element to exclude (and its children) Returns ------- contenthandler : `type` a subclass of `~ligo.lw.ligolw.FilteringLIGOLWContentHandler` to exclude an element and its children """ from ligo.lw.ligolw import FilteringLIGOLWContentHandler from ligo.lw.table import Table if issubclass(element, Table): def _element_filter(name, attrs): return ~element.CheckProperties(name, attrs) else: def _element_filter(name, _): # pylint: disable=unused-argument return name != element.tagName return build_content_handler( FilteringLIGOLWContentHandler, _element_filter, ) def build_content_handler(parent, filter_func): """Build a `~xml.sax.handler.ContentHandler` with a given filter Parameters ---------- parent : `type`, subclass of `xml.sax.handler.ContentHandler` a class of contenthandler to use filter_func : `callable` the filter function to pass to the content handler creation Returns ------- contenthandler : subclass of ``parent`` a new content handler that applies the filter function and the default parsing extras from :func:`_wrap_content_handler`. """ class ContentHandler(parent): # pylint: disable=too-few-public-methods def __init__(self, document): super().__init__(document, filter_func) return _wrap_content_handler(ContentHandler) # -- reading ------------------------------------------------------------------ def read_ligolw(source, contenthandler=None, **kwargs): """Read one or more LIGO_LW format files Parameters ---------- source : `str`, `file` the open file or file path to read contenthandler : `~xml.sax.handler.ContentHandler`, optional content handler used to parse document verbose : `bool`, optional be verbose when reading files, default: `False` Returns ------- xmldoc : :class:`~ligo.lw.ligolw.Document` the document object as parsed from the file(s) """ from ligo.lw.ligolw import Document from ligo.lw import types from ligo.lw.utils import (load_url, ligolw_add) # mock ToPyType to link to numpy dtypes topytype = types.ToPyType.copy() for key in types.ToPyType: if key in types.ToNumPyType: types.ToPyType[key] = numpy.dtype(types.ToNumPyType[key]).type # set contenthandler if contenthandler is None: contenthandler = default_content_handler() # read one or more files into a single Document source = file_list(source) try: if len(source) == 1: return load_url( source[0], contenthandler=contenthandler, **kwargs ) return ligolw_add.ligolw_add( Document(), source, contenthandler=contenthandler, **kwargs ) finally: # replace ToPyType types.ToPyType = topytype # -- reading ------------------------------------------------------------------ def read_table( source, tablename=None, columns=None, contenthandler=None, **kwargs, ): """Read a :class:`~ligo.lw.table.Table` from one or more LIGO_LW files Parameters ---------- source : `Document`, `file`, `str`, `CacheEntry`, `list` object representing one or more files. One of - a LIGO_LW :class:`~ligo.lw.ligolw.Document` - an open `file` - a `str` pointing to a file path on disk - a formatted :class:`~lal.utils.CacheEntry` representing one file - a `list` of `str` file paths or :class:`~lal.utils.CacheEntry` tablename : `str` name of the table to read. columns : `list`, optional list of column name strings to read, default all. contenthandler : `~xml.sax.handler.ContentHandler`, optional SAX content handler for parsing LIGO_LW documents. **kwargs other keyword arguments are passed to `~gwpy.io.ligolw.read_ligolw` Returns ------- table : :class:`~ligo.lw.table.Table` `Table` of data """ from ligo.lw.ligolw import Document from ligo.lw import (table, lsctables) # get content handler to read only this table (if given) if tablename is not None: tableclass = lsctables.TableByName[ table.Table.TableName(tablename) ] if contenthandler is None: contenthandler = get_partial_contenthandler(tableclass) # overwrite loading column names to get just what was asked for _oldcols = tableclass.loadcolumns if columns is not None: tableclass.loadcolumns = columns # read document if isinstance(source, Document): xmldoc = source else: if contenthandler is None: contenthandler = default_content_handler() try: xmldoc = read_ligolw( source, contenthandler=contenthandler, **kwargs) finally: # reinstate original set of loading column names if tablename is not None: tableclass.loadcolumns = _oldcols # now find the right table if tablename is None: tables = list_tables(xmldoc) if not tables: raise ValueError("No tables found in LIGO_LW document(s)") if len(tables) > 1: raise ValueError( "Multiple tables found in LIGO_LW document(s), please specify " "the table to read via the ``tablename=`` keyword argument. " "The following tables were found: " "'{}'".format("', '".join(tables)), ) tableclass = lsctables.TableByName[table.Table.TableName(tables[0])] # extract table return tableclass.get_table(xmldoc) # -- writing ------------------------------------------------------------------ def open_xmldoc(fobj, contenthandler=None, **kwargs): """Try and open an existing LIGO_LW-format file, or create a new Document Parameters ---------- fobj : `str`, `file` file path or open file object to read contenthandler : `~xml.sax.handler.ContentHandler`, optional the content handler with which to parse the document, if not given a default handler will be created using :func:`default_content_handler`. **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_fileobj` as appropriate Returns -------- xmldoc : :class:`~ligo.lw.ligolw.Document` either the `Document` as parsed from an existing file, or a new, empty `Document` """ from ligo.lw.ligolw import Document from ligo.lw.utils import load_fileobj if contenthandler is None: contenthandler = default_content_handler() # read from an existing Path/filename if not isinstance(fobj, FILE_LIKE): try: with open(fobj, "rb") as fobj2: return open_xmldoc( fobj2, contenthandler=contenthandler, **kwargs, ) except (OSError, IOError): # or just create a new Document return Document() return load_fileobj( fobj, contenthandler=contenthandler, **kwargs, ) def get_ligolw_element(xmldoc): """Find an existing <LIGO_LW> element in this XML Document """ from ligo.lw.ligolw import (LIGO_LW, WalkChildren) if isinstance(xmldoc, LIGO_LW): return xmldoc for elem in WalkChildren(xmldoc): if isinstance(elem, LIGO_LW): return elem raise ValueError("Cannot find LIGO_LW element in XML Document") def write_tables_to_document(xmldoc, tables, overwrite=False): """Write the given LIGO_LW table into a :class:`Document` Parameters ---------- xmldoc : :class:`~ligo.lw.ligolw.Document` the document to write into tables : `list` of :class:`~ligo.lw.table.Table` the set of tables to write overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows """ from ligo.lw.ligolw import LIGO_LW from ligo.lw import lsctables # find or create LIGO_LW tag try: llw = get_ligolw_element(xmldoc) except ValueError: llw = LIGO_LW() xmldoc.appendChild(llw) for table in tables: try: # append new data to existing table old = lsctables.TableByName[ table.TableName(table.Name)].get_table(xmldoc) except ValueError: # or create a new table llw.appendChild(table) else: if overwrite: llw.removeChild(old) old.unlink() llw.appendChild(table) else: old.extend(table) return xmldoc def write_tables( target, tables, append=False, overwrite=False, contenthandler=None, **kwargs, ): """Write an LIGO_LW table to file Parameters ---------- target : `str`, `file`, :class:`~ligo.lw.ligolw.Document` the file or document to write into tables : `list`, `tuple` of :class:`~ligo.lw.table.Table` the tables to write append : `bool`, optional, default: `False` if `True`, append to an existing file/table, otherwise `overwrite` overwrite : `bool`, optional, default: `False` if `True`, delete an existing instance of the table type, otherwise append new rows contenthandler : `~xml.sax.handler.ContentHandler`, optional the content handler with which to parse the document, if not given a default handler will be created using :func:`default_content_handler`. **kwargs other keyword arguments to pass to :func:`~ligo.lw.utils.load_fileobj` as appropriate """ from ligo.lw.ligolw import Document, LIGO_LW from ligo.lw import utils as ligolw_utils # allow writing directly to XML if isinstance(target, (Document, LIGO_LW)): xmldoc = target # open existing document, if possible elif append: if contenthandler is None: contenthandler = default_content_handler() xmldoc = open_xmldoc( target, contenthandler=contenthandler, ) # fail on existing document and not overwriting elif ( not overwrite and isinstance(target, (str, os.PathLike)) and os.path.exists(target) ): raise IOError(f"File exists: {target}") else: # or create a new document xmldoc = Document() # convert table to format write_tables_to_document(xmldoc, tables, overwrite=overwrite) # find writer function and target filename if isinstance(target, FILE_LIKE): writer = ligolw_utils.write_fileobj name = target.name else: writer = ligolw_utils.write_filename name = target = str(target) # handle gzip compression kwargs if name.endswith('.gz'): kwargs.setdefault('compress', 'gz') # write XML writer(xmldoc, target, **kwargs) # -- utilities ---------------------------------------------------------------- def iter_tables(source): """Iterate over all tables in the given document(s) Parameters ---------- source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one or more open files, file paths, or LIGO_LW `Document`s Yields ------ ligo.lw.table.Table a table structure from the document(s) """ from ligo.lw.ligolw import (Element, Stream, WalkChildren) # get LIGO_LW object if not isinstance(source, Element): filt = get_filtering_contenthandler(Stream) source = read_ligolw(source, contenthandler=filt) llw = get_ligolw_element(source) # yield tables for elem in WalkChildren(llw): if elem.tagName == "Table": yield elem def list_tables(source): """List the names of all tables in this file(s) Parameters ---------- source : `file`, `str`, :class:`~ligo.lw.ligolw.Document`, `list` one or more open files, file paths, or LIGO_LW `Document`s Examples -------- >>> from gwpy.io.ligolw import list_tables >>> print(list_tables('H1-LDAS_STRAIN-968654552-10.xml.gz')) ['process', 'process_params', 'sngl_burst', 'search_summary', 'segment_definer', 'segment_summary', 'segment'] """ # noqa: E501 return [tbl.TableName(tbl.Name) for tbl in iter_tables(source)] def to_table_type(val, cls, colname): """Cast a value to the correct type for inclusion in a LIGO_LW table This method returns the input unmodified if a type mapping for ``colname`` isn't found. Parameters ---------- val : `object` The input object to convert, of any type cls : `type`, subclass of :class:`~ligo.lw.table.Table` the table class to map against colname : `str` The name of the mapping column Returns ------- obj : `object` The input ``val`` cast to the correct type Examples -------- >>> from gwpy.io.ligolw import to_table_type as to_ligolw_type >>> from ligo.lw.lsctables import SnglBurstTable >>> x = to_ligolw_type(1.0, SnglBurstTable, 'central_freq')) >>> print(type(x), x) <class 'numpy.float32'> 1.0 """ from ligo.lw.types import ( ToNumPyType as numpytypes, ToPyType as pytypes, ) # if nothing to do... if val is None or colname not in cls.validcolumns: return val llwtype = cls.validcolumns[colname] # map to numpy or python types try: return numpy.sctypeDict[numpytypes[llwtype]](val) except KeyError: return pytypes[llwtype](val) # -- identify ----------------------------------------------------------------- def is_ligolw(origin, filepath, fileobj, *args, **kwargs): """Identify a file object as LIGO_LW-format XML """ # pylint: disable=unused-argument if fileobj is not None: loc = fileobj.tell() fileobj.seek(0) try: line1 = fileobj.readline().lower() line2 = fileobj.readline().lower() try: return ( line1.startswith(XML_SIGNATURE) and line2.startswith((LIGOLW_SIGNATURE, LIGOLW_ELEMENT)) ) except TypeError: # bytes vs str return ( line1.startswith(XML_SIGNATURE.decode('utf-8')) and line2.startswith(( LIGOLW_SIGNATURE.decode('utf-8'), LIGOLW_ELEMENT.decode('utf-8'), )) ) finally: fileobj.seek(loc) try: from ligo.lw.ligolw import Element except ImportError: return return len(args) > 0 and isinstance(args[0], Element) @deprecated_function def is_xml(origin, filepath, fileobj, *args, **kwargs): # pragma: no cover """Identify a file object as XML (any format) """ # pylint: disable=unused-argument if fileobj is not None: loc = fileobj.tell() fileobj.seek(0) try: sig = fileobj.read(5).lower() return sig == XML_SIGNATURE finally: fileobj.seek(loc) elif filepath is not None: return filepath.endswith(('.xml', '.xml.gz'))
gwpy/gwpy
gwpy/io/ligolw.py
Python
gpl-3.0
22,098
/*************************************************************************** * nc_cor_cluster_cmb_lens_limber.h * * Wed June 11 17:19:50 2014 * Copyright 2014 Mariana Penna Lima * <pennalima@gmail.com> ****************************************************************************/ /* * nc_cor_cluster_cmb_lens_limber.h * Copyright (C) 2014 Mariana Penna Lima <pennalima@gmail.com> * * numcosmo is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * numcosmo is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _NC_COR_CLUSTER_CMB_LENS_LIMBER_H_ #define _NC_COR_CLUSTER_CMB_LENS_LIMBER_H_ #include <glib.h> #include <glib-object.h> #include <numcosmo/build_cfg.h> #include <numcosmo/nc_distance.h> //#include <numcosmo/lss/nc_matter_var.h> #include <numcosmo/lss/nc_growth_func.h> //#include <numcosmo/lss/nc_mass_function.h> #include <numcosmo/lss/nc_halo_density_profile.h> #include <numcosmo/lss/nc_halo_bias_func.h> #include <numcosmo/lss/nc_cluster_abundance.h> #include <numcosmo/math/ncm_spline_cubic_notaknot.h> #include <numcosmo/math/ncm_spline2d.h> G_BEGIN_DECLS #define NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER (nc_cor_cluster_cmb_lens_limber_get_type ()) #define NC_COR_CLUSTER_CMB_LENS_LIMBER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER, NcCorClusterCmbLensLimber)) #define NC_COR_CLUSTER_CMB_LENS_LIMBER_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER, NcCorClusterCmbLensLimberClass)) #define NC_IS_COR_CLUSTER_CMB_LENS_LIMBER(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER)) #define NC_IS_COR_CLUSTER_CMB_LENS_LIMBER_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER)) #define NC_COR_CLUSTER_CMB_LENS_LIMBER_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NC_TYPE_COR_CLUSTER_CMB_LENS_LIMBER, NcCorClusterCmbLensLimberClass)) typedef struct _NcCorClusterCmbLensLimberClass NcCorClusterCmbLensLimberClass; typedef struct _NcCorClusterCmbLensLimber NcCorClusterCmbLensLimber; struct _NcCorClusterCmbLensLimberClass { /*< private >*/ GObjectClass parent_class; }; struct _NcCorClusterCmbLensLimber { /*< private >*/ GObject parent_instance; NcmSpline *oneh_int_mass_spline; }; GType nc_cor_cluster_cmb_lens_limber_get_type (void) G_GNUC_CONST; NcCorClusterCmbLensLimber *nc_cor_cluster_cmb_lens_limber_new (void); gdouble nc_cor_cluster_cmb_lens_limber_oneh_int_mass (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcClusterMass *clusterm, NcHICosmo *cosmo, NcHaloDensityProfile *dp, gdouble k, gdouble z, gdouble *lnM_obs, gdouble *lnM_obs_params); gdouble nc_cor_cluster_cmb_lens_limber_oneh_term (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcHICosmo *cosmo, NcDistance *dist, NcHaloDensityProfile *dp, gint l, gdouble *lnM_obs, gdouble *lnM_obs_params, gdouble *z_obs, gdouble *z_obs_params); gdouble nc_cor_cluster_cmb_lens_limber_twoh_int_mass1 (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcClusterMass *clusterm, NcHICosmo *cosmo, gdouble z); gdouble nc_cor_cluster_cmb_lens_limber_twoh_int_mm (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcHICosmo *cosmo, NcHaloDensityProfile *dp, gdouble k, gdouble z); gdouble nc_cor_cluster_cmb_lens_limber_twoh_int_mass2 (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcClusterMass *clusterm, NcHICosmo *cosmo, NcHaloDensityProfile *dp, gdouble k, gdouble z); gdouble nc_cor_cluster_cmb_lens_limber_twoh_term (NcCorClusterCmbLensLimber *cccll, NcClusterAbundance *cad, NcHICosmo *cosmo, NcDistance *dist, NcHaloDensityProfile *dp, gint l, gdouble *z_obs, gdouble *z_obs_params); G_END_DECLS #endif /* _NC_COR_CLUSTER_CMB_LENS_LIMBER_H_ */
NumCosmo/NumCosmo
numcosmo/lss/nc_cor_cluster_cmb_lens_limber.h
C
gpl-3.0
4,310
using System.Collections.Generic; using ECCentral.BizEntity.IM; using ECCentral.Service.IM.IDataAccess; using ECCentral.Service.Utility; using ECCentral.Service.Utility.DataAccess; namespace ECCentral.Service.IM.SqlDataAccess { [VersionExport(typeof(IAccessoryDA))] public class AccessoryDA : IAccessoryDA { public AccessoryInfo GetBySysNo(int sysNo) { DataCommand dc = DataCommandManager.GetDataCommand("GetBySysNo"); dc.SetParameterValue("@SysNo", sysNo); return dc.ExecuteEntity<AccessoryInfo>(); } public AccessoryInfo Insert(AccessoryInfo accessoryInfo) { DataCommand dc = DataCommandManager.GetDataCommand("Insert"); dc.SetParameterValue("@SysNo", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryName", accessoryInfo.AccessoryName.Content); dc.ExecuteNonQuery(); accessoryInfo.SysNo = (int)dc.GetParameterValue("@SysNo"); return accessoryInfo; } public AccessoryInfo Update(AccessoryInfo accessoryInfo) { DataCommand dc = DataCommandManager.GetDataCommand("Update"); dc.SetParameterValue("@SysNo", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryID", accessoryInfo.SysNo); dc.SetParameterValue("@AccessoryName", accessoryInfo.AccessoryName.Content); dc.ExecuteNonQuery(); return accessoryInfo; } public IList<AccessoryInfo> GetList(string accessoryName) { DataCommand dc = DataCommandManager.GetDataCommand("GetListByAccessoryName"); dc.SetParameterValue("@AccessoryName", accessoryName); return dc.ExecuteEntityList<AccessoryInfo>(); } public IList<AccessoryInfo> GetAll() { DataCommand dc = DataCommandManager.GetDataCommand("GetAll"); return dc.ExecuteEntityList<AccessoryInfo>(); } public IList<AccessoryInfo> GetListByID(string accessoryID) { DataCommand dc = DataCommandManager.GetDataCommand("GetListByID"); dc.SetParameterValue("@AccessoriesID", accessoryID); return dc.ExecuteEntityList<AccessoryInfo>(); } } }
ZeroOne71/ql
02_ECCentral/03_Service/02_IM/ECCentral.Service.IM.SqlDataAccess/AccessoryDA.cs
C#
gpl-3.0
2,285
// -*- C++ -*- /*! * @file SFMLJoystickToVelocityComp.cpp * @brief Standalone component * @date $Date$ * * $Id$ */ #include <rtm/Manager.h> #include <iostream> #include <string> #include <stdlib.h> #include "SFMLJoystickToVelocity.h" void MyModuleInit(RTC::Manager* manager) { SFMLJoystickToVelocityInit(manager); RTC::RtcBase* comp; // Create a component comp = manager->createComponent("SFMLJoystickToVelocity"); if (comp==NULL) { std::cerr << "Component create failed." << std::endl; abort(); } // Example // The following procedure is examples how handle RT-Components. // These should not be in this function. // Get the component's object reference // RTC::RTObject_var rtobj; // rtobj = RTC::RTObject::_narrow(manager->getPOA()->servant_to_reference(comp)); // Get the port list of the component // PortServiceList* portlist; // portlist = rtobj->get_ports(); // getting port profiles // std::cout << "Number of Ports: "; // std::cout << portlist->length() << std::endl << std::endl; // for (CORBA::ULong i(0), n(portlist->length()); i < n; ++i) // { // PortService_ptr port; // port = (*portlist)[i]; // std::cout << "Port" << i << " (name): "; // std::cout << port->get_port_profile()->name << std::endl; // // RTC::PortInterfaceProfileList iflist; // iflist = port->get_port_profile()->interfaces; // std::cout << "---interfaces---" << std::endl; // for (CORBA::ULong i(0), n(iflist.length()); i < n; ++i) // { // std::cout << "I/F name: "; // std::cout << iflist[i].instance_name << std::endl; // std::cout << "I/F type: "; // std::cout << iflist[i].type_name << std::endl; // const char* pol; // pol = iflist[i].polarity == 0 ? "PROVIDED" : "REQUIRED"; // std::cout << "Polarity: " << pol << std::endl; // } // std::cout << "---properties---" << std::endl; // NVUtil::dump(port->get_port_profile()->properties); // std::cout << "----------------" << std::endl << std::endl; // } return; } int main (int argc, char** argv) { RTC::Manager* manager; manager = RTC::Manager::init(argc, argv); // Initialize manager manager->init(argc, argv); // Set module initialization proceduer // This procedure will be invoked in activateManager() function. manager->setModuleInitProc(MyModuleInit); // Activate manager and register to naming service manager->activateManager(); // run the manager in blocking mode // runManager(false) is the default. manager->runManager(); // If you want to run the manager in non-blocking mode, do like this // manager->runManager(true); return 0; }
sugarsweetrobotics/SFMLJoystickToVelocity
src/SFMLJoystickToVelocityComp.cpp
C++
gpl-3.0
2,659
#include "player.h" #include "constants.h" #include "macros.h" #include "neslib.h" extern unsigned char blue_door_state; #pragma zpsym("blue_door_state") extern unsigned char yellow_door_state; #pragma zpsym("yellow_door_state") extern unsigned char i; #pragma zpsym("i") extern unsigned char a; #pragma zpsym("a") extern unsigned char b; #pragma zpsym("b") extern unsigned char d; #pragma zpsym("d") extern unsigned char e; #pragma zpsym("e") extern unsigned char f; #pragma zpsym("f") extern unsigned char g; #pragma zpsym("g") extern unsigned char h; #pragma zpsym("h") extern unsigned char teleport_state; #pragma zpsym("teleport_state") extern unsigned char teleport_timer; #pragma zpsym("teleport_timer") extern unsigned char sec; #pragma zpsym("sec") extern unsigned char player_trigger[2]; #pragma zpsym("player_trigger") extern unsigned char player_last_trigger[2]; #pragma zpsym("player_last_trigger") extern unsigned char player_shooting_last_state[2]; #pragma zpsym("player_shooting_last_state") extern unsigned char blue_worrior_ai; #pragma zpsym("blue_worrior_ai") extern unsigned char j; #pragma zpsym("j") extern unsigned char frame_cnt; #pragma zpsym("frame_cnt") extern unsigned char k; #pragma zpsym("k") extern unsigned char player_shot_loop[2]; #pragma zpsym("player_shot_loop") extern unsigned char score0[7]; extern unsigned char score1[7]; extern unsigned char score2[7]; extern const unsigned char pixel_box_x[11]; extern const unsigned char pixel_box_y[7]; extern unsigned char stamp_x[8]; // Stamp X position #pragma zpsym("stamp_x") extern unsigned char stamp_y[8]; // Stamp Y position #pragma zpsym("stamp_y") extern unsigned char stamp_type[8]; // Stamp type #pragma zpsym("stamp_type") extern unsigned char stamp_state[8]; // Stamp state #pragma zpsym("stamp_state") extern unsigned char stamp_last_state[8]; // Stamp last state #pragma zpsym("stamp_last_state") extern unsigned char stamp_frame[8]; // Stamp frame #pragma zpsym("stamp_frame") extern unsigned char stamp_delay[8]; // Stamp delay #pragma zpsym("stamp_delay") extern unsigned char stamp_timer[8]; // Stamp timer #pragma zpsym("stamp_timer") extern unsigned char stamp_pad[8]; // Stamp pad #pragma zpsym("stamp_pad") extern unsigned char stamp_shooting[8]; // Stamp shooting #pragma zpsym("stamp_shooting") extern unsigned char stamp_move_delay[8]; // Stamp move delay #pragma zpsym("stamp_move_delay") extern unsigned char laser_x[8]; // Laser X position #pragma zpsym("laser_x") extern unsigned char laser_y[8]; // Laser Y position #pragma zpsym("laser_y") extern unsigned char laser_type[8]; // Laser type #pragma zpsym("laser_type") extern unsigned char laser_shooting[8]; // Laser shooting #pragma zpsym("laser_shooting") extern unsigned char laser_direction[8]; // Laser direction #pragma zpsym("laser_direction") extern unsigned char laser_offset_x[8]; // Laser X offset #pragma zpsym("laser_offset_x") extern unsigned char laser_offset_y[8]; // Laser Y offset #pragma zpsym("laser_offset_y") extern void get_current_box(void); extern void get_current_laser_box(void); extern void add_points(unsigned char player); /** * player_blue_ready() - Ready the blue player */ void player_blue_ready(void) { stamp_timer[1]=3; // Player is in the box. stamp_x[1]=PIXEL_BOX_X(0); stamp_y[1]=PIXEL_BOX_Y(6)-1; // 6 is the special spawn box. stamp_type[1]=STAMP_TYPE_BLUE_WORRIOR; stamp_state[1]=stamp_last_state[1]=1; // Facing right Idle stamp_frame[1]=0; stamp_delay[1]=0; blue_door_state=OPEN; } /** * player_yellow_ready() - Ready the blue player */ void player_yellow_ready(void) { stamp_timer[0]=6; stamp_x[0]=PIXEL_BOX_X(9); stamp_y[0]=PIXEL_BOX_Y(6)-1; // 6 is the special spawn box. stamp_type[0]=STAMP_TYPE_YELLOW_WORRIOR; stamp_state[0]=stamp_last_state[0]=3; // Facing left Idle stamp_frame[0]=0; stamp_delay[0]=0; yellow_door_state=OPEN; } /** * player_handle_idle() */ void player_handle_idle(void) { // Change to idle state if pad is idle. switch(stamp_last_state[i]) { case STATE_PLAYER_RIGHT: stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_RIGHT_IDLE_SHOOTING:STATE_PLAYER_RIGHT_IDLE); break; case STATE_PLAYER_LEFT: stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_LEFT_IDLE_SHOOTING:STATE_PLAYER_LEFT_IDLE); break; case STATE_PLAYER_UP: stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_UP_IDLE_SHOOTING:STATE_PLAYER_UP_IDLE); break; case STATE_PLAYER_DOWN: stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_DOWN_IDLE_SHOOTING:STATE_PLAYER_DOWN_IDLE); break; } } /** * player_in_field() * Handle when player is on the playfield */ void player_in_field(void) { if (frame_cnt==0) set_rand(stamp_x[0]); if (stamp_state[i]==STATE_DEAD) { goto no_move; } else if (stamp_state[i]>STATE_PLAYER_DOWN_IDLE_SHOOTING || stamp_state[i]==STATE_DYING) { player_shot(); } else if ((stamp_x[i]==PIXEL_BOX_X(a)) && (stamp_y[i]==PIXEL_BOX_Y(b))) { // We are aligned. if (PLAYER_PAD_LEFT(i) && stamp_last_state[i] != STATE_PLAYER_RIGHT && stamp_x[i]==PIXEL_BOX_X(0) && stamp_y[i]==PIXEL_BOX_Y(2) && teleport_state == OPEN) { stamp_x[i]=PIXEL_BOX_X(9); teleport_state=CLOSED; teleport_timer=2; } else if (PLAYER_PAD_RIGHT(i) && stamp_last_state[i] != STATE_PLAYER_LEFT && stamp_x[i]==PIXEL_BOX_X(9) && stamp_y[i]==PIXEL_BOX_Y(2) && teleport_state == OPEN) { stamp_x[i]=PIXEL_BOX_X(0); teleport_state=CLOSED; teleport_timer=2; } else if (PLAYER_PAD_RIGHT(i) && (stamp_last_state[i] != STATE_PLAYER_RIGHT || stamp_last_state[i] != STATE_PLAYER_RIGHT_IDLE) && !BOX_WALL_RIGHT(d)) stamp_state[i]=stamp_last_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_RIGHT_SHOOTING:STATE_PLAYER_RIGHT); else if (PLAYER_PAD_LEFT(i) && (stamp_last_state[i] != STATE_PLAYER_LEFT || stamp_last_state[i] != STATE_PLAYER_LEFT_IDLE) && !BOX_WALL_LEFT(d)) stamp_state[i]=stamp_last_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_LEFT_SHOOTING:STATE_PLAYER_LEFT); else if (PLAYER_PAD_UP(i) && (stamp_last_state[i] != STATE_PLAYER_UP || stamp_last_state[i] != STATE_PLAYER_UP_IDLE) && !BOX_WALL_UP(d)) stamp_state[i]=stamp_last_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_UP_SHOOTING:STATE_PLAYER_UP); else if (PLAYER_PAD_DOWN(i) && (stamp_last_state[i] != STATE_PLAYER_DOWN || stamp_last_state[i] != STATE_PLAYER_DOWN_IDLE) && !BOX_WALL_DOWN(d)) stamp_state[i]=stamp_last_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_DOWN_SHOOTING:STATE_PLAYER_DOWN); else if (PLAYER_PAD_IDLE(i)) player_handle_idle(); if (stamp_last_state[i]==STATE_PLAYER_LEFT && stamp_x[i]==PIXEL_BOX_X(0) && stamp_y[i]==PIXEL_BOX_Y(2) && teleport_state == OPEN) stamp_state[i]=STATE_PLAYER_LEFT; else if (stamp_last_state[i]==STATE_PLAYER_RIGHT && stamp_x[i]==PIXEL_BOX_X(9) && stamp_y[i]==PIXEL_BOX_Y(2) && teleport_state == OPEN) stamp_state[i]=STATE_PLAYER_RIGHT; else if ((stamp_last_state[i]==STATE_PLAYER_RIGHT || stamp_last_state[i]==STATE_PLAYER_RIGHT_IDLE) && BOX_WALL_RIGHT(d)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_RIGHT_IDLE_SHOOTING:STATE_PLAYER_RIGHT_IDLE); else if ((stamp_last_state[i]==STATE_PLAYER_LEFT || stamp_last_state[i]==STATE_PLAYER_LEFT_IDLE) && BOX_WALL_LEFT(d)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_LEFT_IDLE_SHOOTING:STATE_PLAYER_LEFT_IDLE); else if ((stamp_last_state[i]==STATE_PLAYER_UP || stamp_last_state[i]==STATE_PLAYER_UP_IDLE) && BOX_WALL_UP(d)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_UP_IDLE_SHOOTING:STATE_PLAYER_UP_IDLE); else if ((stamp_last_state[i]==STATE_PLAYER_DOWN || stamp_last_state[i]==STATE_PLAYER_DOWN_IDLE) && BOX_WALL_DOWN(d)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_DOWN_IDLE_SHOOTING:STATE_PLAYER_DOWN_IDLE); } else { // We are not aligned. if (PLAYER_PAD_IDLE(i)) player_handle_idle(); else if (PLAYER_PAD_RIGHT(i) && (stamp_last_state[i]==STATE_PLAYER_LEFT)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_RIGHT_SHOOTING:STATE_PLAYER_RIGHT); else if (PLAYER_PAD_LEFT(i) && (stamp_last_state[i]==STATE_PLAYER_RIGHT)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_LEFT_SHOOTING:STATE_PLAYER_LEFT); else if (PLAYER_PAD_UP(i) && (stamp_last_state[i]==STATE_PLAYER_DOWN)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_UP_SHOOTING:STATE_PLAYER_UP); else if (PLAYER_PAD_DOWN(i) && (stamp_last_state[i]==STATE_PLAYER_UP)) stamp_state[i]=(stamp_shooting[i]==1?STATE_PLAYER_DOWN_SHOOTING:STATE_PLAYER_DOWN); else { if (stamp_shooting[i]==1 && stamp_last_state[i]==STATE_PLAYER_LEFT) stamp_state[i]=STATE_PLAYER_LEFT_SHOOTING; else if (stamp_shooting[i]==1 && stamp_last_state[i]==STATE_PLAYER_RIGHT) stamp_state[i]=STATE_PLAYER_RIGHT_SHOOTING; else if (stamp_shooting[i]==1 && stamp_last_state[i]==STATE_PLAYER_DOWN) stamp_state[i]=STATE_PLAYER_DOWN_SHOOTING; else if (stamp_shooting[i]==1 && stamp_last_state[i]==STATE_PLAYER_UP) stamp_state[i]=STATE_PLAYER_UP_SHOOTING; else stamp_state[i]=stamp_last_state[i]; } } // Apply player movement. AI player moves at half speed. if (stamp_move_delay[i]==0) { switch(stamp_state[i]) { case STATE_PLAYER_RIGHT: stamp_x[i]+=(blue_worrior_ai==1&&i==1)?1:2; break; case STATE_PLAYER_LEFT: stamp_x[i]-=(blue_worrior_ai==1&&i==1)?1:2; break; case STATE_PLAYER_UP: stamp_y[i]-=(blue_worrior_ai==1&&i==1)?1:2; break; case STATE_PLAYER_DOWN: stamp_y[i]+=(blue_worrior_ai==1&&i==1)?1:2; break; } } // And set last state, if we aren't idle. if (!PLAYER_PAD_IDLE(i) && stamp_shooting[i]==0) stamp_last_state[i]=stamp_state[i]; // Convert trigger press to shooting state. if (player_trigger[i]==player_last_trigger[i]) { // Debounce } else { if (player_last_trigger[i]==0 && player_trigger[i]==1) { stamp_shooting[i]=1; stamp_frame[i]=0; player_laser_fire(i); } } // Finally handle AI trigger. Naive and somewhat random, for now. if (rand8()>0xc0) if (blue_worrior_ai==1 && rand8()<0x08 && i==1 && laser_shooting[i]==0) { stamp_shooting[1]=1; stamp_frame[1]=0; player_laser_fire(1); } // Stop shooting animation if we're done. if (stamp_shooting[i]==1 && stamp_frame[i]==3) stamp_shooting[i]=0; // Handle shooting. if (laser_shooting[i]==1) { get_current_laser_box(); if (laser_direction[i]==STATE_PLAYER_RIGHT_SHOOTING || laser_direction[i]==STATE_PLAYER_RIGHT || laser_direction[i]==STATE_PLAYER_RIGHT_IDLE || laser_direction[i]==STATE_PLAYER_RIGHT_IDLE_SHOOTING) { if (BOX_WALL_RIGHT(h) && laser_x[i]==PIXEL_BOX_X(e)) player_laser_stop(i); else laser_x[i]+=frame_cnt&0x01?0:8; } else if (laser_direction[i]==STATE_PLAYER_LEFT_SHOOTING || laser_direction[i]==STATE_PLAYER_LEFT || laser_direction[i]==STATE_PLAYER_LEFT_IDLE || laser_direction[i]==STATE_PLAYER_LEFT_IDLE_SHOOTING) { if (BOX_WALL_LEFT(h) && laser_x[i]==PIXEL_BOX_X(e)) player_laser_stop(i); else laser_x[i]-=frame_cnt&0x01?0:8; } else if (laser_direction[i]==STATE_PLAYER_DOWN_SHOOTING || laser_direction[i]==STATE_PLAYER_DOWN || laser_direction[i]==STATE_PLAYER_DOWN_IDLE || laser_direction[i]==STATE_PLAYER_DOWN_IDLE_SHOOTING) { if (BOX_WALL_DOWN(h) && laser_y[i]==PIXEL_BOX_Y(f)) player_laser_stop(i); else laser_y[i]+=frame_cnt&0x01?0:8; } else if (laser_direction[i]==STATE_PLAYER_UP_SHOOTING || laser_direction[i]==STATE_PLAYER_UP || laser_direction[i]==STATE_PLAYER_UP_IDLE || laser_direction[i]==STATE_PLAYER_UP_IDLE_SHOOTING) { if (BOX_WALL_UP(h) && laser_y[i]==PIXEL_BOX_Y(f)) player_laser_stop(i); else laser_y[i]-=frame_cnt&0x01?0:8; } if (BOX_PIXEL_X(stamp_x[0])==BOX_PIXEL_X(laser_x[1]) && BOX_PIXEL_Y(stamp_y[0])==BOX_PIXEL_Y(laser_y[1]) && stamp_state[0]<STATE_PLAYER_RIGHT_SHOT) { player_die(0); player_laser_stop(i); } else if (BOX_PIXEL_X(stamp_x[1])==BOX_PIXEL_X(laser_x[0]) && BOX_PIXEL_Y(stamp_y[1])==BOX_PIXEL_Y(laser_y[0]) && stamp_state[1]<STATE_PLAYER_RIGHT_SHOT) { player_die(1); player_laser_stop(i); } if (stamp_state[i]==STATE_DYING && stamp_frame[i]==3) { stamp_state[i]=STATE_DEAD; stamp_frame[i]=0; stamp_shooting[i]=0; } } no_move: return; } /** * player_shot() * Player has been shot by something. */ void player_shot(void) { // Handle dying animation. if (stamp_state[i]!=STATE_DYING && player_shot_loop[i]>0 && stamp_frame[i]==3) { player_shot_loop[i]--; } else if (stamp_state[i]!=STATE_DYING && stamp_state[i]>STATE_PLAYER_DOWN_IDLE_SHOOTING && player_shot_loop[i]==0) { stamp_state[i]=STATE_DYING; stamp_frame[i]=0; } } /** * player_in_box() * Handle when player is in box. */ void player_in_box(void) { if (stamp_timer[i]>0) { if (stamp_pad[i] != 0) { stamp_timer[i]=0; } else { stamp_y[i]=PIXEL_BOX_Y(6)-1; // 6 is the Y for the box. if (sec==0) // 0 means approximately 1 second elapsed. stamp_timer[i]--; // Decrement timer } } else { stamp_y[i]=PIXEL_BOX_Y(5); // Pop out of box. if (i==0) { stamp_state[i]=stamp_last_state[i]=STATE_PLAYER_LEFT_IDLE; yellow_door_state=CLOSED; } else { if (i==1 && blue_worrior_ai==0) stamp_state[i]=stamp_last_state[i]=STATE_PLAYER_RIGHT_IDLE; else stamp_pad[1]=PAD_UP; blue_door_state=CLOSED; } } } /** * player_move_all() */ void player_move_all(void) { for (i=0;i<2;i++) { get_current_box(); if (blue_worrior_ai==1 && i==1) player_blue_move_ai(); else stamp_pad[i]=pad_poll(i); player_trigger[i]=(PLAYER_PAD_A(i)?1:0); if (stamp_y[i]==PIXEL_BOX_Y(6)-1) { player_in_box(); } else { player_in_field(); } player_last_trigger[i]=player_trigger[i]; } } /** * player_laser_fire() */ void player_laser_fire(unsigned char player) { // Position laser in player box. laser_shooting[player]=1; laser_direction[player]=stamp_state[i]; laser_x[player]=PIXEL_BOX_X(a); laser_y[player]=PIXEL_BOX_Y(b); switch(laser_direction[player]) { case STATE_PLAYER_LEFT: case STATE_PLAYER_LEFT_IDLE: case STATE_PLAYER_LEFT_SHOOTING: case STATE_PLAYER_LEFT_IDLE_SHOOTING: case STATE_PLAYER_RIGHT: case STATE_PLAYER_RIGHT_IDLE: case STATE_PLAYER_RIGHT_SHOOTING: case STATE_PLAYER_RIGHT_IDLE_SHOOTING: laser_offset_x[i]=LASER_X_OFFSET_H; laser_offset_y[i]=LASER_Y_OFFSET_H; laser_type[player]=86; break; case STATE_PLAYER_DOWN: case STATE_PLAYER_DOWN_IDLE: case STATE_PLAYER_DOWN_SHOOTING: case STATE_PLAYER_DOWN_IDLE_SHOOTING: case STATE_PLAYER_UP: case STATE_PLAYER_UP_IDLE: case STATE_PLAYER_UP_SHOOTING: case STATE_PLAYER_UP_IDLE_SHOOTING: laser_offset_x[i]=LASER_X_OFFSET_V; laser_offset_y[i]=LASER_Y_OFFSET_V; laser_type[player]=93; break; } } /** * player_laser_stop() */ void player_laser_stop(unsigned char player) { laser_x[player]=0xff; laser_y[player]=0xff; laser_type[player]=92; laser_shooting[player]=0; laser_direction[player]=0; laser_offset_x[player]=0; laser_offset_y[player]=0; } /** * player_change_ai_direction() * Change the direction of the blue player * TODO: if it isn't useful soon, remove it. */ void player_change_ai_direction() { switch(rand8()&0x03) { case 0: stamp_pad[i]=PAD_RIGHT; break; case 1: stamp_pad[i]=PAD_LEFT; break; case 2: stamp_pad[i]=PAD_DOWN; break; case 3: stamp_pad[i]=PAD_UP; break; } } /** * Move blue worrior AI if needed. */ void player_blue_move_ai(void) { pick_monster_rand: if (k==0) k=rand8()&0x07; // We don't want the blue worrior to chase the yellow player or himself. if (k<2) goto pick_monster_rand; else if (k>7) goto pick_monster_rand; /* if (stamp_state[k]==STATE_DEAD) */ /* goto pick_monster_rand; */ // get enemy's target box e=BOX_PIXEL_X(stamp_x[k]); f=BOX_PIXEL_Y(stamp_y[k]); if (a==e && b>f) stamp_pad[i]=PAD_UP; else if (a<e && b>f) stamp_pad[i]=PAD_UP|PAD_RIGHT; else if (a<e && b==f) stamp_pad[i]=PAD_RIGHT; else if (a>e && b<f) stamp_pad[i]=PAD_DOWN|PAD_RIGHT; else if (a==e && b<f) stamp_pad[i]=PAD_DOWN; else if (a>e && b>f) stamp_pad[i]=PAD_DOWN|PAD_LEFT; else if (a>e && b==f) stamp_pad[i]=PAD_LEFT; else if (a>e&& b<f) stamp_pad[i]=PAD_UP|PAD_LEFT; } /** * player_die(player) * Player was killed by player or monster, player=player shot. */ void player_die(unsigned char player) { unsigned char new_state; memfill(&score0,1,sizeof(score0)); switch(stamp_state[player]) { case STATE_PLAYER_RIGHT: case STATE_PLAYER_RIGHT_SHOOTING: new_state=STATE_PLAYER_RIGHT_SHOT; break; case STATE_PLAYER_RIGHT_IDLE: case STATE_PLAYER_RIGHT_IDLE_SHOOTING: new_state=STATE_PLAYER_RIGHT_IDLE_SHOT; break; case STATE_PLAYER_LEFT: case STATE_PLAYER_LEFT_SHOOTING: new_state=STATE_PLAYER_LEFT_SHOT; break; case STATE_PLAYER_LEFT_IDLE: case STATE_PLAYER_LEFT_IDLE_SHOOTING: new_state=STATE_PLAYER_LEFT_IDLE_SHOT; break; case STATE_PLAYER_UP: case STATE_PLAYER_UP_SHOOTING: new_state=STATE_PLAYER_UP_SHOT; break; case STATE_PLAYER_UP_IDLE: case STATE_PLAYER_UP_IDLE_SHOOTING: new_state=STATE_PLAYER_UP_IDLE_SHOT; break; case STATE_PLAYER_DOWN: case STATE_PLAYER_DOWN_SHOOTING: new_state=STATE_PLAYER_DOWN_SHOT; break; case STATE_PLAYER_DOWN_IDLE: case STATE_PLAYER_DOWN_IDLE_SHOOTING: new_state=STATE_PLAYER_DOWN_IDLE_SHOT; break; } stamp_state[player]=new_state; stamp_frame[player]=0; player_shot_loop[player]=8; if (i<2) // Only deal with score if player shoots player. { score0[3]=2; // 1000 points. add_points(i); } if (player==1 && blue_worrior_ai==1) k=0; // Go tell AI to chase another player, if applicable. }
tschak909/wow
player.c
C
gpl-3.0
18,467
################################################################################# # Copyright 2014 See AUTHORS file. # # Licensed under the GNU General Public License Version 3.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.gnu.org/licenses/gpl-3.0.txt # # 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. ################################################################################# bl_info = { "name": "LibGDX G3D Exporter", "author": "Danilo Costa Viana", "blender": (2,6,9), "version": (0,1,0), "location": "File > Import-Export", "description": "Export scene to G3D (LibGDX) format", "category": "Import-Export" } import bpy from io_scene_g3d.export_g3d import G3DExporter class Mesh(object): def __init__(self, s): self.s = s def __repr__(self): return '<Mesh(%s)>' % self.s def menu_func(self, context): self.layout.operator(G3DExporter.bl_idname, text="LibGDX G3D text format (.g3dj)") def register(): bpy.utils.register_module(__name__) bpy.types.INFO_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_export.remove(menu_func) if __name__ == "__main__": register()
blackears/libgdx_blender_g3d_exporter
io_scene_g3d/__init__.py
Python
gpl-3.0
1,616
# # Copyright 2017 Russell Smiley # # This file is part of timetools. # # timetools is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # timetools is distributed in the hope that it will be useful # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with timetools. If not, see <http://www.gnu.org/licenses/>. # import numpy import unittest import timetools.signalProcessing.tolerance as spt import timetools.synchronization.intervals as si class TestIntervals (unittest.TestCase): def testCalculateLogIntervalScale1 (self): minValue = 10 maxValue = 120 numberPoints = 11 result = si.generateLogIntervalScale(minValue, maxValue, numberPoints) self.assertTrue(len(result) == numberPoints, 'Result does not have correct length') minValueTolerance = spt.ToleranceValue(minValue, 0.1, spt.ToleranceUnit['percent']) maxValueTolerance = spt.ToleranceValue(maxValue, 0.1, spt.ToleranceUnit['percent']) self.assertTrue((minValueTolerance.isWithinTolerance(result[0]) and maxValueTolerance.isWithinTolerance(result[-1])), 'Incorrect endpoints') # A logarithmic sequence will be evenly spaced in the logarithmic domain logIntervals = numpy.diff(numpy.log10(result)) intervalTolerance = spt.ToleranceValue(numpy.mean(logIntervals), 0.1, spt.ToleranceUnit['percent']) self.assertTrue(numpy.all(intervalTolerance.isWithinTolerance(logIntervals)), 'Intervals are not logarithmic') def testGenerateMonotonicLogScale1 (self): minValue = 10 maxValue = 25 numberPoints = 12 expectedSequence = numpy.array([10, 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 25]) thisArray = si.generateLogIntervalScale(minValue, maxValue, numberPoints) thisIntegerArray = numpy.floor(thisArray) monotonicIntervals = si.generateMonotonicLogScale(thisIntegerArray) self.assertTrue(isinstance(monotonicIntervals[0], numpy.intp), '') self.assertTrue(len(monotonicIntervals) == len(expectedSequence), 'Incorrect length of monotonic sequence') self.assertTrue(numpy.all(monotonicIntervals == expectedSequence), 'Monotonicity failed') if __name__ == "__main__": unittest.main()
blueskyjunkie/timeTools
timetools/synchronization/tests/testIntervals.py
Python
gpl-3.0
2,719
#include <bits/stdc++.h> using namespace std; const int maxn = 25; const int maxs = 4099; int n, bcnt[maxs], n1, n2; int a[maxn]; char cht[maxs]; map<int, int> val; int main() { bcnt[0] = 0; for (int i = 1; i < maxs; ++i) bcnt[i] = bcnt[i >> 1] + (i & 1); while (scanf("%d", &n) == 1) { val.clear(); for (int i = 0; i < n; ++i) { a[i] = 0; scanf("%s", cht); for (char *c = cht; *c; ++c) { int x = *c - 'A'; a[i] ^= (1 << x); } } n1 = n >> 1; n2 = n - n1; for (int S = 0; S < (1 << n1); ++S) { int xsum = 0; for (int i = 0; i < n1; ++i) { if (S & (1 << i)) xsum ^= a[i]; } if (!val.count(xsum)) val[xsum] = S; else if (bcnt[S] > bcnt[val[xsum]]) val[xsum] = S; } int best = 0, ans = 0; for (int T = 0; T < (1 << n); T += (1 << n1)) { int xsum = 0; for (int i = n1; i < n; ++i) { if (T & (1 << i)) xsum ^= a[i]; } if (!val.count(xsum)) continue; int S = val[xsum]; int cur = bcnt[S] + bcnt[T >> n1]; if (cur > best) { best = cur; ans = S ^ T; } } printf("%d\n", best); bool flag = false; for (int i = 0; i < n; ++i) { if (ans & (1 << i)) { if (flag) putchar(' '); printf("%d", i + 1); flag = true; } } putchar('\n'); } return 0; }
Chrogeek/chrogeek-noi
LA 2965 Jurassic Remains/la2965.cpp
C++
gpl-3.0
1,257
<?php /** * This file is part of Mbiz_RobotsTxt for Magento. * * @license All rights reserved. * @author Léo Peltier <l.peltier@monsieurbiz.com> * @category Mbiz * @package Mbiz_RobotsTxt * @copyright Copyright (c) 2013 Monsieur Biz (http://monsieurbiz.com/) */ class Mbiz_RobotsTxt_Model_RobotsTxt extends Mage_Core_Model_Config_Data { /** * @return string robots.txt file path. */ protected function getRobotsTxtPath() { return Mage::getBaseDir('base') . '/robots.txt'; } /** * Rewrite robots.txt when the configuration is saved. */ protected function _beforeSave() { parent::_beforeSave(); $contents = $this->getValue(); $ret = file_put_contents($this->getRobotsTxtPath(), $contents); if ($ret === false) { throw new Exception('Failed to write robots.txt.'); } return $this; } /** * Load the value directly from the robots.txt file. * * If the file does not exist, discard what is in the magento config and * load an empty string. */ protected function _afterLoad() { parent::_afterLoad(); $path = $this->getRobotsTxtPath(); if(file_exists($path)) { $this->setValue(file_get_contents($path)); } else { $this->setValue(''); } } }
monsieurbiz/Mbiz_RobotsTxt
app/code/community/Mbiz/RobotsTxt/Model/RobotsTxt.php
PHP
gpl-3.0
1,375