code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This file is part of SableCC. *
* See the file "LICENSE" for copyright information and the *
* terms and conditions for copying, distribution and *
* modification of SableCC. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package org.sablecc.sablecc;
import java.util.*;
import org.sablecc.sablecc.analysis.*;
import org.sablecc.sablecc.node.*;
@SuppressWarnings({"rawtypes","unchecked"})
public class AlternativeElementTypes extends DepthFirstAdapter
{
private Map altElemTypes = new TypedHashMap(StringCast.instance,
StringCast.instance);
private ResolveIds ids;
private String currentAlt;
public AlternativeElementTypes(ResolveIds ids)
{
this.ids = ids;
}
public Map getMapOfAltElemType()
{
return altElemTypes;
}
@Override
public void caseAAst(AAst node)
{}
@Override
public void caseAProd(final AProd production)
{
Object []temp = production.getAlts().toArray();
for(int i = 0; i<temp.length; i++)
{
((PAlt)temp[i]).apply(this);
}
}
@Override
public void caseAAlt(AAlt node)
{
currentAlt = (String)ids.names.get(node);
Object []temp = node.getElems().toArray();
for(int i = 0; i<temp.length; i++)
{
((PElem)temp[i]).apply(this);
}
}
@Override
public void inAElem(AElem node)
{
String elemType = (String)ids.elemTypes.get(node);
if(node.getElemName() != null)
{
altElemTypes.put(currentAlt+"."+node.getElemName().getText(), elemType );
}
else
{
altElemTypes.put(currentAlt+"."+node.getId().getText(), elemType );
}
}
}
| renatocf/MAC0434-PROJECT | external/sablecc-3.7/src/org/sablecc/sablecc/AlternativeElementTypes.java | Java | gpl-3.0 | 1,765 |
#include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> modulus(std::vector<int> a);
void multiplication(std::vector<int> a, std::vector<int> b) {
std::vector<int> c;
c.resize(a.size() + b.size() - 1);
for (int x = 0; x < b.size(); x++) {
for (int y = 0; y < a.size(); y++) {
c[x + y] += a[y] * b[x];
}
}
for (int x = 0; x < c.size(); x++) {
c[x] %= 2;
}
std::cout << std::endl << "\n\tIloczyn przed modulacja: \t\t";
for (int x = 0; x < c.size(); x++) {
std::cout << "" << c[x] << "";
}
c = modulus(c);
std::cout << std::endl << "\tIloczyn po modulacji: \t\t";
for (int x = 0; x < c.size(); x++) {
std::cout << "" << c[x] << "";
}
std::cout << std::endl << std::endl;
} | Tomashnikov/GF_Multiplication | GF_Multiplication/GF_Multiplication/multiplication.cpp | C++ | gpl-3.0 | 730 |
/*
* Copyright 2012 Justin Driggers <jtxdriggers@gmail.com>
*
* This file is part of Ventriloid.
*
* Ventriloid 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.
*
* Ventriloid 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 Ventriloid. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jtxdriggers.android.ventriloid;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ServerAdapter extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "ventriloiddata";
public static final int DATABASE_VERSION = 3;
public static final String TABLE_SERVERS = "Servers";
public static final String KEY_ID = "ID";
public static final String KEY_USERNAME = "Username";
public static final String KEY_PHONETIC = "Phonetic";
public static final String KEY_SERVERNAME = "Servername";
public static final String KEY_HOSTNAME = "Hostname";
public static final String KEY_PORT = "Port";
public static final String KEY_PASSWORD = "Password";
public static final String CREATE_SERVERS_TABLE = "CREATE TABLE " + TABLE_SERVERS + "("
+ KEY_ID + " INTEGER PRIMARY KEY, " + KEY_USERNAME + " TEXT NOT NULL, "
+ KEY_PHONETIC + " TEXT NOT NULL, " + KEY_SERVERNAME + " TEXT NOT NULL, "
+ KEY_HOSTNAME + " TEXT NOT NULL, " + KEY_PORT + " INTEGER NOT NULL, "
+ KEY_PASSWORD + " TEXT NOT NULL);";
public ServerAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SERVERS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 3) {
db.execSQL("ALTER TABLE " + TABLE_SERVERS + " RENAME TO ServersTemp;");
db.execSQL(CREATE_SERVERS_TABLE);
db.execSQL("INSERT INTO " + TABLE_SERVERS + "("
+ KEY_ID + ", " + KEY_USERNAME + ", "
+ KEY_PHONETIC + ", " + KEY_SERVERNAME + ", "
+ KEY_HOSTNAME + ", " + KEY_PORT + ", "
+ KEY_PASSWORD + ") "
+ "SELECT _id, username, phonetic, "
+ "servername, hostname, portnumber, password "
+ "FROM ServersTemp;");
db.execSQL("DROP TABLE IF EXISTS ServersTemp;");
}
}
public void addServer(Server server) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, server.getUsername());
values.put(KEY_PHONETIC, server.getPhonetic());
values.put(KEY_SERVERNAME, server.getServername());
values.put(KEY_HOSTNAME, server.getHostname());
values.put(KEY_PORT, server.getPort());
values.put(KEY_PASSWORD, server.getPassword());
db.insert(TABLE_SERVERS, null, values);
db.close();
}
public Server getServer(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(true, TABLE_SERVERS, new String[] { KEY_ID, KEY_USERNAME,
KEY_PHONETIC, KEY_SERVERNAME, KEY_HOSTNAME, KEY_PORT, KEY_PASSWORD }, KEY_ID + "=" + id,
null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Server server = new Server(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3),
cursor.getString(4), Integer.parseInt(cursor.getString(5)), cursor.getString(6));
cursor.close();
db.close();
return server;
}
public ArrayList<Server> getAllServers() {
ArrayList<Server> serverList = new ArrayList<Server>();
String selectQuery = "SELECT * FROM " + TABLE_SERVERS;
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Server server = new Server();
server.setId(Integer.parseInt(cursor.getString(0)));
server.setUsername(cursor.getString(1));
server.setPhonetic(cursor.getString(2));
server.setServername(cursor.getString(3));
server.setHostname(cursor.getString(4));
server.setPort(Integer.parseInt(cursor.getString(5)));
server.setPassword(cursor.getString(6));
serverList.add(server);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return serverList;
}
public ArrayList<String> getAllServersAsStrings() {
ArrayList<String> serverList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_SERVERS;
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Server server = new Server();
server.setUsername(cursor.getString(1));
server.setServername(cursor.getString(3));
server.setHostname(cursor.getString(4));
server.setPort(Integer.parseInt(cursor.getString(5)));
serverList.add(server.getServername());
} while (cursor.moveToNext());
}
cursor.close();
db.close();
if (serverList.size() < 1)
serverList.add("No servers added");
return serverList;
}
public int getServersCount() {
String countQuery = "SELECT * FROM " + TABLE_SERVERS;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public void updateServer(Server server) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, server.getUsername());
values.put(KEY_PHONETIC, server.getPhonetic());
values.put(KEY_SERVERNAME, server.getServername());
values.put(KEY_HOSTNAME, server.getHostname());
values.put(KEY_PORT, server.getPort());
values.put(KEY_PASSWORD, server.getPassword());
values.put(KEY_ID, server.getId());
db.update(TABLE_SERVERS, values, KEY_ID + " = " + server.getId(), null);
db.close();
}
public void deleteServer(Server server) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_SERVERS, KEY_ID + " = ?",
new String[] { String.valueOf(server.getId()) });
db.close();
}
public void clearServers() {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_SERVERS, null, null);
db.close();
}
}
| justindriggers/Ventriloid | com.jtxdriggers.android.ventriloid/src/com/jtxdriggers/android/ventriloid/ServerAdapter.java | Java | gpl-3.0 | 7,275 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="lb_LU">
<context>
<name>QObject</name>
<message>
<location filename="../main/main.cpp" line="+87"/>
<source>LTR</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| annejan/qtpass | localization/localization_lb_LU.ts | TypeScript | gpl-3.0 | 312 |
<?php
/**
* WooCommerce Account Functions
*
* Functions for account specific things.
*
* @author WooThemes
* @category Core
* @package WooCommerce/Functions
* @version 2.6.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Returns the url to the lost password endpoint url.
*
* @access public
* @param string $default_url
* @return string
*/
function wc_lostpassword_url( $default_url = '' ) {
$wc_password_reset_url = wc_get_page_permalink( 'myaccount' );
if ( false !== $wc_password_reset_url ) {
return wc_get_endpoint_url( 'lost-password', '', $wc_password_reset_url );
} else {
return $default_url;
}
}
add_filter( 'lostpassword_url', 'wc_lostpassword_url', 10, 1 );
/**
* Get the link to the edit account details page.
*
* @return string
*/
function wc_customer_edit_account_url() {
$edit_account_url = wc_get_endpoint_url( 'edit-account', '', wc_get_page_permalink( 'myaccount' ) );
return apply_filters( 'woocommerce_customer_edit_account_url', $edit_account_url );
}
/**
* Get the edit address slug translation.
*
* @param string $id Address ID.
* @param bool $flip Flip the array to make it possible to retrieve the values from both sides.
*
* @return string Address slug i18n.
*/
function wc_edit_address_i18n( $id, $flip = false ) {
$slugs = apply_filters( 'woocommerce_edit_address_slugs', array(
'billing' => sanitize_title( _x( 'billing', 'edit-address-slug', 'woocommerce' ) ),
'shipping' => sanitize_title( _x( 'shipping', 'edit-address-slug', 'woocommerce' ) )
) );
if ( $flip ) {
$slugs = array_flip( $slugs );
}
if ( ! isset( $slugs[ $id ] ) ) {
return $id;
}
return $slugs[ $id ];
}
/**
* Get My Account menu items.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_menu_items() {
return apply_filters( 'woocommerce_account_menu_items', array(
'dashboard' => __( 'Dashboard', 'woocommerce' ),
'orders' => __( 'Orders', 'woocommerce' ),
'downloads' => __( 'Downloads', 'woocommerce' ),
'edit-address' => __( 'Addresses', 'woocommerce' ),
'payment-methods' => __( 'Payment Methods', 'woocommerce' ),
'edit-account' => __( 'Account Details', 'woocommerce' ),
'customer-logout' => __( 'Logout', 'woocommerce' ),
) );
}
/**
* Get account menu item classes.
*
* @since 2.6.0
* @param string $endpoint
* @return string
*/
function wc_get_account_menu_item_classes( $endpoint ) {
global $wp;
$classes = array(
'woocommerce-MyAccount-navigation-link',
'woocommerce-MyAccount-navigation-link--' . $endpoint,
);
// Set current item class.
$current = isset( $wp->query_vars[ $endpoint ] );
if ( 'dashboard' === $endpoint && ( isset( $wp->query_vars['page'] ) || empty( $wp->query_vars ) ) ) {
$current = true; // Dashboard is not an endpoint, so needs a custom check.
}
if ( $current ) {
$classes[] = 'is-active';
}
$classes = apply_filters( 'woocommerce_account_menu_item_classes', $classes, $endpoint );
return implode( ' ', array_map( 'sanitize_html_class', $classes ) );
}
/**
* Get account endpoint URL.
*
* @since 2.6.0
* @param string $endpoint
* @return string
*/
function wc_get_account_endpoint_url( $endpoint ) {
if ( 'dashboard' === $endpoint ) {
return wc_get_page_permalink( 'myaccount' );
}
return wc_get_endpoint_url( $endpoint );
}
/**
* Get My Account > Orders columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_orders_columns() {
$columns = apply_filters( 'woocommerce_account_orders_columns', array(
'order-number' => __( 'Order', 'woocommerce' ),
'order-date' => __( 'Date', 'woocommerce' ),
'order-status' => __( 'Status', 'woocommerce' ),
'order-total' => __( 'Total', 'woocommerce' ),
'order-actions' => ' ',
) );
// Deprecated filter since 2.6.0.
return apply_filters( 'woocommerce_my_account_my_orders_columns', $columns );
}
/**
* Get My Account > Downloads columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_downloads_columns() {
return apply_filters( 'woocommerce_account_downloads_columns', array(
'download-file' => __( 'File', 'woocommerce' ),
'download-remaining' => __( 'Remaining', 'woocommerce' ),
'download-expires' => __( 'Expires', 'woocommerce' ),
'download-actions' => ' ',
) );
}
/**
* Get My Account > Payment methods columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_payment_methods_columns() {
return apply_filters( 'woocommerce_account_payment_methods_columns', array(
'method' => __( 'Method', 'woocommerce' ),
'expires' => __( 'Expires', 'woocommerce' ),
'actions' => ' ',
) );
}
/**
* Get My Account > Payment methods types
*
* @since 2.6.0
* @return array
*/
function wc_get_account_payment_methods_types() {
return apply_filters( 'woocommerce_payment_methods_types', array(
'cc' => __( 'Credit Card', 'woocommerce' ),
'echeck' => __( 'eCheck', 'woocommerce' ),
) );
}
/**
* Returns an array of a user's saved payments list for output on the account tab.
*
* @since 2.6
* @param array $list List of payment methods passed from wc_get_customer_saved_methods_list()
* @param int $customer_id The customer to fetch payment methods for
* @return array Filtered list of customers payment methods
*/
function wc_get_account_saved_payment_methods_list( $list, $customer_id ) {
$payment_tokens = WC_Payment_Tokens::get_customer_tokens( $customer_id );
foreach ( $payment_tokens as $payment_token ) {
$delete_url = wc_get_endpoint_url( 'delete-payment-method', $payment_token->get_id() );
$delete_url = wp_nonce_url( $delete_url, 'delete-payment-method-' . $payment_token->get_id() );
$set_default_url = wc_get_endpoint_url( 'set-default-payment-method', $payment_token->get_id() );
$set_default_url = wp_nonce_url( $set_default_url, 'set-default-payment-method-' . $payment_token->get_id() );
$type = strtolower( $payment_token->get_type() );
$list[ $type ][] = array(
'method' => array(
'gateway' => $payment_token->get_gateway_id(),
),
'expires' => esc_html__( 'N/A', 'woocommerce' ),
'is_default' => $payment_token->is_default(),
'actions' => array(
'delete' => array(
'url' => $delete_url,
'name' => esc_html__( 'Delete', 'woocommerce' ),
),
),
);
$key = key( array_slice( $list[ $type ], -1, 1, true ) );
if ( ! $payment_token->is_default() ) {
$list[ $type ][$key]['actions']['default'] = array(
'url' => $set_default_url,
'name' => esc_html__( 'Make Default', 'woocommerce' ),
);
}
$list[ $type ][ $key ] = apply_filters( 'woocommerce_payment_methods_list_item', $list[ $type ][ $key ], $payment_token );
}
return $list;
}
add_filter( 'woocommerce_saved_payment_methods_list', 'wc_get_account_saved_payment_methods_list', 10, 2 );
/**
* Controls the output for credit cards on the my account page.
*
* @since 2.6
* @param array $item Individual list item from woocommerce_saved_payment_methods_list
* @param WC_Payment_Token $payment_token The payment token associated with this method entry
* @return array Filtered item
*/
function wc_get_account_saved_payment_methods_list_item_cc( $item, $payment_token ) {
if ( 'cc' !== strtolower( $payment_token->get_type() ) ) {
return $item;
}
$card_type = $payment_token->get_card_type();
$item['method']['last4'] = $payment_token->get_last4();
$item['method']['brand'] = ( ! empty( $card_type ) ? ucfirst( $card_type ) : esc_html__( 'Credit Card', 'woocommerce' ) );
$item['expires'] = $payment_token->get_expiry_month() . '/' . substr( $payment_token->get_expiry_year(), -2 );
return $item;
}
add_filter( 'woocommerce_payment_methods_list_item', 'wc_get_account_saved_payment_methods_list_item_cc', 10, 2 );
/**
* Controls the output for eChecks on the my account page.
*
* @since 2.6
* @param array $item Individual list item from woocommerce_saved_payment_methods_list
* @param WC_Payment_Token $payment_token The payment token associated with this method entry
* @return array Filtered item
*/
function wc_get_account_saved_payment_methods_list_item_echeck( $item, $payment_token ) {
if ( 'echeck' !== strtolower( $payment_token->get_type() ) ) {
return $item;
}
$item['method']['last4'] = $payment_token->get_last4();
$item['method']['brand'] = esc_html__( 'eCheck', 'woocommerce' );
return $item;
}
add_filter( 'woocommerce_payment_methods_list_item', 'wc_get_account_saved_payment_methods_list_item_echeck', 10, 2 );
| SteveHoneyNZ/woocommerce | includes/wc-account-functions.php | PHP | gpl-3.0 | 8,677 |
<!-- Give the category a name. -->
<p>
{!! Form::label('title','Title:') !!}
{!! Form::text('title', old('title'), ['class' => 'form-control']) !!}
</p>
<!-- Give a good description. -->
<p>
{!! Form::label('description', 'Description:') !!}
{!! Form::textarea('description', old('description'), ['class' => 'form-control']) !!}
</p>
<!-- Provide the slug. A slug is what the browser will read for SEO. -->
<p>
{!! Form::label('slug','Slug:') !!}
{!! Form::text('slug', old('slug'), ['class' => 'form-control']) !!}
</p>
<!-- Submit the form -->
<p>
{!! Form::submit($submitButtonText, ['class' => 'btn btn-success']) !!}
</p>
| pchater/flommerce.dev | resources/views/categories/form.blade.php | PHP | gpl-3.0 | 627 |
/*
* Copyright (C) 2017 GedMarc
*
* 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.jwebmp.core.base.servlets;
import com.google.inject.Singleton;
import com.guicedee.guicedinjection.json.StaticStrings;
import com.guicedee.guicedinjection.GuiceContext;
import com.guicedee.guicedservlets.GuicedServletKeys;
import com.guicedee.logger.LogFactory;
import jakarta.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The base Servlet for the JWebSwing environment. Constructs each page on call
*
* @author GedMarc
* @version 1.1
* @since 2012/10/09
*/
@Singleton
public class JWebMPServlet
extends JWDefaultServlet
{
/**
* The logger for the swing Servlet
*/
private static final Logger log = LogFactory.getInstance()
.getLogger("JWebSwingServlet");
/**
* Constructs a new JWebSwing Servlet that is not session aware
*/
public JWebMPServlet()
{
//Nothing Needed
}
/**
* When to perform any commands
*/
@Override
public void perform()
{
HttpServletResponse response = GuiceContext.get(GuicedServletKeys.getHttpServletResponseKey());
sendPage(response);
}
/**
* Sends the page out
*
* @param response
* The response object
*/
private void sendPage(HttpServletResponse response)
{
response.setContentType(StaticStrings.HTML_HEADER_DEFAULT_CONTENT_TYPE);
writeOutput(getPageHTML(), StaticStrings.HTML_HEADER_DEFAULT_CONTENT_TYPE, StaticStrings.UTF_CHARSET);
}
/**
* Destroys this object and all references to it
*/
@Override
public void destroy()
{
try
{
JWebMPServlet.log.log(Level.INFO, "Destroying Servlet JWebMP Servlet and all Static Objects");
GuiceContext.destroy();
}
catch (Exception t)
{
JWebMPServlet.log.log(Level.SEVERE, "Unable to destroy", t);
}
super.destroy();
}
}
| GedMarc/JWebSwing | src/main/java/com/jwebmp/core/base/servlets/JWebMPServlet.java | Java | gpl-3.0 | 2,483 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.iescomercio.tema5.cuentas_bancarias;
/**
*
* @author VESPERTINO
*/
public class CuentaAhorro extends CuentaCorriente {
private double interes;
public CuentaAhorro(Titular t, Numero_de_Cuenta nc, double saldo, double interes){
super(t, nc, saldo);
this.interes = interes;
}
public CuentaAhorro(Titular t, Numero_de_Cuenta nc, double interes){
this(t, nc, 15.3, interes);
}
public CuentaAhorro(Titular t, Numero_de_Cuenta nc){
this(t, nc, 15.3, 2.5);
}
public double getInteres(){
return interes;
}
public void calcularInteres(){
ingresar(getSaldo() * (interes / 100));
}
}
| sagasta95/DAW1 | src/com/iescomercio/tema5/cuentas_bancarias/CuentaAhorro.java | Java | gpl-3.0 | 921 |
#pragma once
#include "GLTexture.hpp"
namespace mls {
template<GLenum textureType>
class GLTextureHandle {
GLuint64 m_nHandle = 0u;
public:
explicit GLTextureHandle(GLuint64 handle = 0u) : m_nHandle(handle) {
}
explicit GLTextureHandle(const GLTextureBase<textureType>& texture):
m_nHandle(glGetTextureHandleNV(texture.glId())) {
}
explicit operator bool() const {
return m_nHandle != 0u;
}
explicit operator GLuint64() const {
return m_nHandle;
}
bool isResident() const {
assert(m_nHandle);
return glIsTextureHandleResidentNV(m_nHandle);
}
void makeResident() const {
assert(m_nHandle);
return glMakeTextureHandleResidentNV(m_nHandle);
}
void makeNonResident() const {
assert(m_nHandle);
return glMakeTextureHandleNonResidentNV(m_nHandle);
}
};
template<GLenum textureType>
class GLImageHandle {
GLuint64 m_nHandle = 0u;
public:
explicit GLImageHandle(GLuint64 handle = 0u) : m_nHandle(handle) {
}
explicit GLImageHandle(const GLTextureBase<textureType>& texture,
GLint level,
GLint layer,
GLenum format):
m_nHandle(glGetImageHandleNV(texture.glId(), level, GL_FALSE, layer, format)) {
}
explicit GLImageHandle(const GLTextureBase<textureType>& texture,
GLint level,
GLenum format):
m_nHandle(glGetImageHandleNV(texture.glId(), level, GL_TRUE, 0, format)) {
}
explicit operator bool() const {
return m_nHandle != 0u;
}
explicit operator GLuint64() const {
return m_nHandle;
}
void makeResident(GLenum access) const {
glMakeImageHandleResidentNV(m_nHandle, access);
}
bool isResident() const {
return glIsImageHandleResidentNV(m_nHandle);
}
void makeNonResident() const {
glMakeImageHandleNonResidentNV(m_nHandle);
}
};
using GLTexture2DHandle = GLTextureHandle<GL_TEXTURE_2D>;
using GLTexture3DHandle = GLTextureHandle<GL_TEXTURE_3D>;
using GLTextureCubeMapHandle = GLTextureHandle<GL_TEXTURE_CUBE_MAP>;
using GLTexture2DArrayHandle = GLTextureHandle<GL_TEXTURE_2D_ARRAY>;
using GLTextureCubeMapArrayHandle = GLTextureHandle<GL_TEXTURE_CUBE_MAP_ARRAY>;
using GLImage2DHandle = GLImageHandle<GL_TEXTURE_2D>;
using GLImage3DHandle = GLImageHandle<GL_TEXTURE_3D>;
using GLImageCubeMapHandle = GLImageHandle<GL_TEXTURE_CUBE_MAP>;
using GLImage2DArrayHandle = GLImageHandle<GL_TEXTURE_2D_ARRAY>;
using GLImageCubeMapArrayHandle = GLImageHandle<GL_TEXTURE_CUBE_MAP_ARRAY>;
}
| Celeborn2BeAlive/melisandre | melisandre/src/melisandre/opengl/utils/GLBindlessTexture.hpp | C++ | gpl-3.0 | 2,692 |
using System;
using System.Collections.Generic;
using System.Linq;
using ColossalFramework;
namespace CWS_MrSlurpExtensions
{
public class DistrictInfo
{
public int DistrictID { get; set; }
public String DistrictName { get; set; }
public DistrictServiceData Population { get; set; }
public int TotalBuildingCount { get; set; }
public int TotalVehicleCount { get; set; }
public int WeeklyTouristVisits { get; set; }
public int AverageLandValue { get; set; }
public Double Pollution { get; set; }
public DistrictDoubleServiceData Jobs { get; set; }
public DistrictDoubleServiceData Households { get; set; }
public Dictionary<string, DistrictServiceData> Privates { get; set; }
public DistrictServiceData Happiness { get; set; }
public DistrictServiceData Crime { get; set; }
public DistrictServiceData Health { get; set; }
public Dictionary<string, DistrictServiceData> Productions { get; set; }
public Dictionary<string, DistrictServiceData> Consumptions { get; set; }
public Dictionary<string, DistrictServiceData> Educated { get; set; }
public DistrictServiceData BirthDeath { get; set; }
public Dictionary<string, DistrictServiceData> Students { get; set; }
public Dictionary<string, DistrictServiceData> Graduations { get; set; }
public Dictionary<string, DistrictServiceData> ImportExport { get; set; }
public VehiclesInfo Vehicles { get; set; }
public PolicyInfo[] Policies { get; set; }
#region servica data structure classes
// simple city service data with only name and current value field (most of services)
public class ServiceData
{
public string Name { get; set; }
public int Current { get; set; }
}
// add a second field for city serices that provide the availability value (households/jobs)
public class DoubleServiceData : ServiceData
{
public int Available { get; set; }
}
public class DistrictServiceData
{
public int TotalCurrent
{
get { return Categories.Sum(x=> x.Current); }
set {}
}
public List<ServiceData> Categories { get; set; }
}
public class DistrictDoubleServiceData
{
public int TotalCurrent
{
get { return Categories.Sum(x => x.Current); }
set { }
}
// allow to use a global game value (total power/water production)
// or automatic sum
private int? totalAvailable;
public int TotalAvailable
{
get
{
if (totalAvailable.HasValue)
return totalAvailable.Value;
else
return Categories.Sum(x => (x.Available != 0) ? x.Available : x.Current);
}
set { totalAvailable = value; }
}
public List<DoubleServiceData> Categories { get; set; }
}
#endregion
public class DistrictServiceDataCollection : Dictionary<string, DistrictServiceData>{}
public static IEnumerable<int> GetDistricts()
{
var districtManager = Singleton<DistrictManager>.instance;
return districtManager.GetDistrictIds();
}
public static DistrictInfo GetDistrictInfo(int districtID)
{
var districtManager = Singleton<DistrictManager>.instance;
var district = GetDistrict(districtID);
if (!district.IsValid()) { return null; }
String districtName = String.Empty;
if (districtID == 0)
{
// The district with ID 0 is always the global district.
// It receives an auto-generated name by default, but the game always displays the city name instead.
districtName = "City";
}
else
{
districtName = districtManager.GetDistrictName(districtID);
}
var pollution = Math.Round((district.m_groundData.m_finalPollution / (Double) byte.MaxValue), 2);
#region data model familly to game service/zone type list & dictionary
//
// warning these strings match object field names in game models and should not be changed
// see specified class to understand
// in DistrictPrivateData
List<string> ServiceZoneTypes = new List<string> { "Residential", "Commercial", "Industrial", "Office", "Player" };
List<string> NoPlayerZoneTypes = new List<string> { "Residential", "Commercial", "Industrial", "Office" };
List<string> JobServiceZoneTypes = new List<string> { "Commercial", "Industrial", "Office", "Player" };
List<string> ImportExportTypes = new List<string> { "Agricultural", "Forestry", "Goods", "Oil", "Ore" };
// in DistrictProductionData
Dictionary<string, string> ProductionsTypes = new Dictionary<string, string> {
{"Electricity", "ElectricityCapacity"},
{"Water","WaterCapacity"},
{"Sewage", "SewageCapacity"},
{"GarbageA", "GarbageCapacity"} ,
{"GarbageC", "GarbageAmount"} ,
{"Incineration", "IncinerationCapacity"},
{"Cremate", "CremateCapacity"},
{"DeadA", "DeadAmount"},
{"DeadC", "DeadCapacity"},
{"Heal", "HealCapacity"},
{"LowEducation", "Education1Capacity"},
{"MediumEducation", "Education2Capacity"},
{"HighEducation", "Education3Capacity"},
};
// in DistrictConsumptionData
// NOTE : consumptions are stored in each kind of service, cool we can create consumption distributions pie
Dictionary<string, string> ConsumptionsTypes = new Dictionary<string, string> {
{"Dead", "DeadCount"},
{"Sick", "SickCount"},
{"Electricity","ElectricityConsumption"},
{"Water","WaterConsumption"},
{"Sewage","SewageAccumulation"},
{"Garbage","GarbageAccumulation"},
{"Income", "IncomeAccumulation"},
{"WaterPollution", "WaterPollution"},
{"Building", "BuildingCount"},
{"GarbagePiles", "GarbagePiles"},
{"ImportAmount", "ImportAmount"},
};
Dictionary<string, string> PrivateDataTypes = new Dictionary<string, string> {
{"Abandoned","AbandonedCount"},
{"BuildingArea","BuildingArea"},
//{"BuildingCount","BuildingCount"}, same data as in DistrictConsumptionData
{"Burned","BurnedCount"},
{"EmptyCount","EmptyCount"},
//{"Happiness","Happiness"}, do in diffferent way to be easyly able to display hapiness by type
//{"CrimeRate","CrimeRate"},
//{"Health","Health"},
/* to re add if a day I understand usage
{"Level","Level"},
{"Level1","Level1"},
{"Level2","Level2"},
{"Level3","Level3"},
{"Level4","Level4"},
{"Level5","Level5"},*/
};
// in DistrictEducationData
Dictionary<string, string> EducatedLevels = new Dictionary<string, string> {
{"No","educated0"},
{"Low","educated1"},
{"Medium","educated2"},
{"High","educated3"}
};
Dictionary<string, string> EducatedDataTypes = new Dictionary<string, string> {
{"Total", "Count"},
{"EligibleWorkers", "EligibleWorkers"},
{"Homeless", "Homeless"},
{"Unemployed","Unemployed"},
};
// in DistrictAgeData
Dictionary<string, string> GraduationTypes = new Dictionary<string, string>
{
{"LowEducation","education1"},
{"MediumEducation","education2"},
{"HighEducation","education3"},
};
Dictionary<string, string> StudentTypes = new Dictionary<string, string>
{
{"LowStudent","student1"},
{"MediumStudent","student2"},
{"HighStudent","student3"},
};
Dictionary<string, string> BirthDeathTypes = new Dictionary<string, string>
{
{"Births","birth"},
{"Deaths","death"}
};
Dictionary<string, string> PopulationType = new Dictionary<string,string>{
{"Childs","child"},
{"Teens","teen"},
{"Youngs","young"},
{"Adults","adult"},
{"Seniors","senior"},
};
#endregion
var model = new DistrictInfo
{
DistrictID = districtID,
DistrictName = districtName,
#region service data generation
Population = new DistrictServiceData{
Categories = new List<ServiceData>(PopulationType.Keys.Select(x => district.GetAgeServiceData(PopulationType[x], x))),
},
Happiness = new DistrictServiceData{
Categories = new List<ServiceData>(NoPlayerZoneTypes.Select(y => district.GetPrivateServiceData(y, "Happiness")) )
},
Crime = new DistrictServiceData{
Categories = new List<ServiceData>(NoPlayerZoneTypes.Select(y => district.GetPrivateServiceData(y, "CrimeRate")))
},
Health = new DistrictServiceData{
Categories = new List<ServiceData>(NoPlayerZoneTypes.Select(y => district.GetPrivateServiceData(y, "Health")))
},
// warning double lambda, but pretty magical effect
Privates = new Dictionary<string, DistrictServiceData>(
PrivateDataTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData>(ServiceZoneTypes.Select(y => district.GetPrivateServiceData(y, PrivateDataTypes[x]))) }
)
),
Households = new DistrictDoubleServiceData{Categories = new List<DoubleServiceData>{district.GetCountAndAliveServiceData("residential"),},},
Jobs = new DistrictDoubleServiceData{Categories = new List<DoubleServiceData>(JobServiceZoneTypes.Select(x => district.GetCountAndAliveServiceData(x)))},
ImportExport = new Dictionary<string, DistrictServiceData>{
{"Import", new DistrictServiceData{Categories = new List<ServiceData>(ImportExportTypes.Select(x => district.GetImportExportServiceData("import", x)))}},
{"Export", new DistrictServiceData{Categories = new List<ServiceData>(ImportExportTypes.Select(x => district.GetImportExportServiceData("export", x)))}},
},
Productions = new Dictionary<string,DistrictServiceData>(
ProductionsTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData> { district.GetProductionServiceData(x, ProductionsTypes[x]) } }
)
),
// warning double lambda, but pretty magical effect
Consumptions = new Dictionary<string,DistrictServiceData>(
ConsumptionsTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData>(ServiceZoneTypes.Select(y => district.GetConsumptionServiceData(y, ConsumptionsTypes[x]))) }
)
),
// warning double lambda, but pretty magical effect
Educated = new Dictionary<string, DistrictServiceData>(
EducatedDataTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData>(EducatedLevels.Keys.Select(y => district.GetEducatedServiceData(EducatedLevels[y], EducatedDataTypes[x], y))) }
)
),
BirthDeath = new DistrictServiceData{
Categories = new List<ServiceData>(BirthDeathTypes.Keys.Select(x => district.GetAgeServiceData(BirthDeathTypes[x], x))),
},
Graduations = new Dictionary<string, DistrictServiceData>(
GraduationTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData> { district.GetAgeServiceData(GraduationTypes[x]) } }
)
),
Students= new Dictionary<string, DistrictServiceData>(
StudentTypes.Keys.ToDictionary(x => x,
x => new DistrictServiceData { Categories = new List<ServiceData> { district.GetAgeServiceData(StudentTypes[x]) } }
)
),
#endregion
AverageLandValue = district.GetLandValue(),
Pollution = pollution,
WeeklyTouristVisits = (int)district.m_tourist1Data.m_averageCount + (int)district.m_tourist2Data.m_averageCount + (int)district.m_tourist3Data.m_averageCount,
Policies = GetPolicies().ToArray(),
};
if (districtID != 0)
{
CityInfoRequestHandler.LogMessages("Building vehicles for", districtID.ToString());
model.Vehicles = new VehiclesInfo(districtID);
}
else
{
CityInfoRequestHandler.LogMessages("Building vehicles for city");
model.Vehicles = new VehiclesInfo();
}
return model;
}
private static District GetDistrict(int? districtID = null)
{
if (districtID == null) { districtID = 0; }
var districtManager = Singleton<DistrictManager>.instance;
var district = districtManager.m_districts.m_buffer[districtID.Value];
return district;
}
private static IEnumerable<PolicyInfo> GetPolicies()
{
var policies = EnumHelper.GetValues<DistrictPolicies.Policies>();
var districtManager = Singleton<DistrictManager>.instance;
foreach (var policy in policies)
{
String policyName = Enum.GetName(typeof(DistrictPolicies.Policies), policy);
Boolean isEnabled = districtManager.IsCityPolicySet(DistrictPolicies.Policies.AlligatorBan);
yield return new PolicyInfo
{
Name = policyName,
Enabled = isEnabled
};
}
}
}
} | MrSlurp/CityWebServerExtension | CWS_MrSlurpExtensions/Models/DistrictInfo.cs | C# | gpl-3.0 | 15,313 |
package com.abm.mainet.common.jbpm.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.validation.ObjectError;
import com.abm.mainet.common.jbpm.util.ResponseType;
public class ActionResponse {
private ResponseType response;
private List<ObjectError> errorList;
private String error;
private Map<String, String> responseData;
private List<? extends Object> dataList;
private WorkflowRequest document;
//private ComplaintAcknowledgementModel complaintAcknowledgementModel;
private Date actionDate;
/**
* Constructor
*/
public ActionResponse() {
this.responseData = new HashMap<String, String>();
this.dataList = new ArrayList<Object>();
this.errorList = new ArrayList<ObjectError>();
}
/**
* Constructor with Arguements
*
* @param response
*/
public ActionResponse(ResponseType response) {
this.response = response;
this.responseData = new HashMap<String, String>();
this.errorList = new ArrayList<ObjectError>();
}
public Map<String, String> getResponseData() {
return responseData;
}
public void setResponseData(Map<String, String> responseData) {
this.responseData = responseData;
}
public void addResponseData(String key, String data) {
responseData.put(key, data);
}
public String getResponseData(String key) {
return responseData.get(key);
}
public ResponseType getResponse() {
return response;
}
public void setResponse(ResponseType response) {
this.response = response;
}
public List<ObjectError> getErrorList() {
return errorList;
}
public void setErrorList(List<ObjectError> errorList) {
this.errorList = errorList;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public List<? extends Object> getDataList() {
return dataList;
}
public void setDataList(List<? extends Object> dataList) {
this.dataList = dataList;
}
public WorkflowRequest getDocument() {
return document;
}
public void setDocument(WorkflowRequest document) {
this.document = document;
}
/*public ComplaintAcknowledgementModel getComplaintAcknowledgementModel() {
return complaintAcknowledgementModel;
}
public void setComplaintAcknowledgementModel(
ComplaintAcknowledgementModel complaintAcknowledgementModel) {
this.complaintAcknowledgementModel = complaintAcknowledgementModel;
}*/
public Date getActionDate() {
return actionDate;
}
public void setActionDate(Date actionDate) {
this.actionDate = actionDate;
}
}
| abmindiarepomanager/ABMOpenMainet | Mainet1.0/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/jbpm/domain/ActionResponse.java | Java | gpl-3.0 | 2,602 |
package andriell.cxor;
public class Constants {
public static final String CHARSET = "UTF-8";
public static final int MAX_SIZE = 1048576;
}
| andriell/cXor | src/main/java/andriell/cxor/Constants.java | Java | gpl-3.0 | 149 |
const router = require('express').Router({ mergeParams: true });
const HttpStatus = require('http-status-codes');
const path = '/status';
function health(_, res) {
res.status(HttpStatus.OK);
res.send('ok');
}
function ready(_, res) {
res.send('ok');
}
router.get('/health', health);
router.get('/ready', ready);
module.exports = {
router,
path,
};
| omarcinp/cronos | src/api/routes/status.js | JavaScript | gpl-3.0 | 363 |
package sk.upjs.doctororganizer.Entities;
import java.math.BigInteger;
public class Patient {
private Long id;
private String name;
private String surname;
private String adress;
private String date_of_birth;
private BigInteger id_number;
private String insured_at;
private String phone_number;
private String email;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public BigInteger getId_number() {
return id_number;
}
public void setId_number(BigInteger id_number) {
this.id_number = id_number;
}
public String getInsured_at() {
return insured_at;
}
public void setInsured_at(String insured_at) {
this.insured_at = insured_at;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Patient{" + "id=" + id + ", name=" + name + ", surname=" + surname + ", adress=" + adress + ", date_of_birth=" + date_of_birth + ", id_number=" + id_number + ", insured_at=" + insured_at + ", phone_number=" + phone_number + ", email=" + email + ", password=" + password + '}';
}
}
| mohnanskygabriel/DoctorOrganizer | DoctorOrganizer/src/main/java/sk/upjs/doctororganizer/Entities/Patient.java | Java | gpl-3.0 | 2,365 |
#region Copyright
/////////////////////////////////////////////////////////////////////////////
// Altaxo: a data processing and data plotting program
// Copyright (C) 2014 Dr. Dirk Lellinger
//
// 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 2 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
/////////////////////////////////////////////////////////////////////////////
#endregion Copyright
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Altaxo.Calc.Fourier;
namespace Altaxo.Worksheet.Commands.Analysis
{
/// <summary>
/// User options for 2D Fourier transformations.
/// </summary>
public class RealFourierTransformation2DOptions
:
Main.SuspendableDocumentLeafNodeWithEventArgs,
ICloneable
{
// Input options
protected double _rowIncrementValue;
protected bool _isUserDefinedRowIncrementValue;
protected double _columnIncrementValue;
protected bool _isUserDefinedColumnIncrementValue;
protected double? _replacementValueForNaNMatrixElements;
protected double? _replacementValueForInfiniteMatrixElements;
protected int? _dataPretreatmentCorrectionOrder;
protected Altaxo.Calc.Fourier.Windows.IWindows2D? _fourierWindow;
// Output options
protected RealFourierTransformationOutputKind _kindOfOutputResult = RealFourierTransformationOutputKind.Amplitude;
protected bool _centerResult;
protected double _resultFractionOfRows = 1;
protected double _resultFractionOfColumns = 1;
protected bool _outputFrequencyHeaderColumns = true;
protected string _frequencyRowHeaderColumnName = string.Empty;
protected string _frequencyColumnHeaderColumnName = string.Empty;
protected bool _outputPeriodHeaderColumns = false;
protected string _periodRowHeaderColumnName = string.Empty;
protected string _periodColumnHeaderColumnName = string.Empty;
// Helper members - not serialized
[NonSerialized]
protected string? _rowIncrementMessage;
[NonSerialized]
protected string? _columnIncrementMessage;
public object Clone()
{
return MemberwiseClone();
}
#region Serialization
#region Version 0
/// <summary>
/// 2014-07-08 initial version.
/// </summary>
[Altaxo.Serialization.Xml.XmlSerializationSurrogateFor(typeof(RealFourierTransformation2DOptions), 0)]
private class XmlSerializationSurrogate0 : Altaxo.Serialization.Xml.IXmlSerializationSurrogate
{
public virtual void Serialize(object obj, Altaxo.Serialization.Xml.IXmlSerializationInfo info)
{
var s = (RealFourierTransformation2DOptions)obj;
info.AddValue("RowIncrementValue", s._rowIncrementValue);
info.AddValue("ColumnIncrementValue", s._columnIncrementValue);
info.AddValue("ReplacementValueForNaNMatrixElements", s._replacementValueForNaNMatrixElements);
info.AddValue("ReplacementValueForInfiniteMatrixElements", s._replacementValueForInfiniteMatrixElements);
info.AddValue("DataPretreatmentCorrectionOrder", s._dataPretreatmentCorrectionOrder);
info.AddValueOrNull("FourierWindow", s._fourierWindow);
info.AddEnum("KindOfOutputResult", s._kindOfOutputResult);
info.AddValue("CenterResult", s._centerResult);
info.AddValue("ResultFractionOfRows", s._resultFractionOfRows);
info.AddValue("ResultFractionOfColumns", s._resultFractionOfColumns);
info.AddValue("OutputFrequencyHeaderColumns", s._outputFrequencyHeaderColumns);
info.AddValue("FrequencyRowHeaderColumnName", s._frequencyRowHeaderColumnName);
info.AddValue("FrequencyColumnHeaderColumnName", s._frequencyColumnHeaderColumnName);
info.AddValue("OutputPeriodHeaderColumns", s._outputPeriodHeaderColumns);
info.AddValue("PeriodRowHeaderColumnName", s._periodRowHeaderColumnName);
info.AddValue("PeriodColumnHeaderColumnName", s._periodColumnHeaderColumnName);
}
protected virtual RealFourierTransformation2DOptions SDeserialize(object? o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object? parent)
{
var s = (RealFourierTransformation2DOptions?)o ?? new RealFourierTransformation2DOptions();
s._rowIncrementValue = info.GetDouble("RowIncrementValue");
s._columnIncrementValue = info.GetDouble("ColumnIncrementValue");
s._replacementValueForNaNMatrixElements = info.GetNullableDouble("ReplacementValueForNaNMatrixElements");
s._replacementValueForInfiniteMatrixElements = info.GetNullableDouble("ReplacementValueForInfiniteMatrixElements");
s._dataPretreatmentCorrectionOrder = info.GetNullableInt32("DataPretreatmentCorrectionOrder");
s._fourierWindow = (Altaxo.Calc.Fourier.Windows.IWindows2D?)info.GetValueOrNull("FourierWindow", s);
s._kindOfOutputResult = (RealFourierTransformationOutputKind)info.GetEnum("KindOfOutputResult", typeof(RealFourierTransformationOutputKind));
s._centerResult = info.GetBoolean("CenterResult");
s._resultFractionOfRows = info.GetDouble("ResultFractionOfRows");
s._resultFractionOfColumns = info.GetDouble("ResultFractionOfColumns");
s._outputFrequencyHeaderColumns = info.GetBoolean("OutputFrequencyHeaderColumns");
s._frequencyRowHeaderColumnName = info.GetString("FrequencyRowHeaderColumnName");
s._frequencyColumnHeaderColumnName = info.GetString("FrequencyColumnHeaderColumnName");
s._outputPeriodHeaderColumns = info.GetBoolean("OutputPeriodHeaderColumns");
s._periodRowHeaderColumnName = info.GetString("PeriodRowHeaderColumnName");
s._periodColumnHeaderColumnName = info.GetString("PeriodColumnHeaderColumnName");
return s;
}
public object Deserialize(object? o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object? parent)
{
var s = SDeserialize(o, info, parent);
return s;
}
}
#endregion Version 0
#region Version 1
/// <summary>
/// 2015-05-19 Added IsUserDefinedRowIncrementValue and IsUserDefinedColumnIncrementValue
/// </summary>
[Altaxo.Serialization.Xml.XmlSerializationSurrogateFor(typeof(RealFourierTransformation2DOptions), 1)]
private class XmlSerializationSurrogate1 : Altaxo.Serialization.Xml.IXmlSerializationSurrogate
{
public virtual void Serialize(object obj, Altaxo.Serialization.Xml.IXmlSerializationInfo info)
{
var s = (RealFourierTransformation2DOptions)obj;
info.AddValue("IsUserDefinedRowIncrementValue", s._isUserDefinedRowIncrementValue);
info.AddValue("RowIncrementValue", s._rowIncrementValue);
info.AddValue("IsUserDefinedColumnIncrementValue", s._isUserDefinedColumnIncrementValue);
info.AddValue("ColumnIncrementValue", s._columnIncrementValue);
info.AddValue("ReplacementValueForNaNMatrixElements", s._replacementValueForNaNMatrixElements);
info.AddValue("ReplacementValueForInfiniteMatrixElements", s._replacementValueForInfiniteMatrixElements);
info.AddValue("DataPretreatmentCorrectionOrder", s._dataPretreatmentCorrectionOrder);
info.AddValueOrNull("FourierWindow", s._fourierWindow);
info.AddEnum("KindOfOutputResult", s._kindOfOutputResult);
info.AddValue("CenterResult", s._centerResult);
info.AddValue("ResultFractionOfRows", s._resultFractionOfRows);
info.AddValue("ResultFractionOfColumns", s._resultFractionOfColumns);
info.AddValue("OutputFrequencyHeaderColumns", s._outputFrequencyHeaderColumns);
info.AddValue("FrequencyRowHeaderColumnName", s._frequencyRowHeaderColumnName);
info.AddValue("FrequencyColumnHeaderColumnName", s._frequencyColumnHeaderColumnName);
info.AddValue("OutputPeriodHeaderColumns", s._outputPeriodHeaderColumns);
info.AddValue("PeriodRowHeaderColumnName", s._periodRowHeaderColumnName);
info.AddValue("PeriodColumnHeaderColumnName", s._periodColumnHeaderColumnName);
}
protected virtual RealFourierTransformation2DOptions SDeserialize(object? o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object? parent)
{
var s = (o is null ? new RealFourierTransformation2DOptions() : (RealFourierTransformation2DOptions)o);
s._isUserDefinedRowIncrementValue = info.GetBoolean("IsUserDefinedRowIncrementValue");
s._rowIncrementValue = info.GetDouble("RowIncrementValue");
s._isUserDefinedColumnIncrementValue = info.GetBoolean("IsUserDefinedColumnIncrementValue");
s._columnIncrementValue = info.GetDouble("ColumnIncrementValue");
s._replacementValueForNaNMatrixElements = info.GetNullableDouble("ReplacementValueForNaNMatrixElements");
s._replacementValueForInfiniteMatrixElements = info.GetNullableDouble("ReplacementValueForInfiniteMatrixElements");
s._dataPretreatmentCorrectionOrder = info.GetNullableInt32("DataPretreatmentCorrectionOrder");
s._fourierWindow = (Altaxo.Calc.Fourier.Windows.IWindows2D?)info.GetValueOrNull("FourierWindow", s);
s._kindOfOutputResult = (RealFourierTransformationOutputKind)info.GetEnum("KindOfOutputResult", typeof(RealFourierTransformationOutputKind));
s._centerResult = info.GetBoolean("CenterResult");
s._resultFractionOfRows = info.GetDouble("ResultFractionOfRows");
s._resultFractionOfColumns = info.GetDouble("ResultFractionOfColumns");
s._outputFrequencyHeaderColumns = info.GetBoolean("OutputFrequencyHeaderColumns");
s._frequencyRowHeaderColumnName = info.GetString("FrequencyRowHeaderColumnName");
s._frequencyColumnHeaderColumnName = info.GetString("FrequencyColumnHeaderColumnName");
s._outputPeriodHeaderColumns = info.GetBoolean("OutputPeriodHeaderColumns");
s._periodRowHeaderColumnName = info.GetString("PeriodRowHeaderColumnName");
s._periodColumnHeaderColumnName = info.GetString("PeriodColumnHeaderColumnName");
return s;
}
public object Deserialize(object? o, Altaxo.Serialization.Xml.IXmlDeserializationInfo info, object? parent)
{
var s = SDeserialize(o, info, parent);
return s;
}
}
#endregion Version 1
#endregion Serialization
public bool IsUserDefinedRowIncrementValue { get { return _isUserDefinedRowIncrementValue; } set { _isUserDefinedRowIncrementValue = value; } }
public bool IsUserDefinedColumnIncrementValue { get { return _isUserDefinedColumnIncrementValue; } set { _isUserDefinedColumnIncrementValue = value; } }
public double RowIncrementValue { get { return _rowIncrementValue; } set { SetMemberAndRaiseSelfChanged(ref _rowIncrementValue, value); } }
public double ColumnIncrementValue { get { return _columnIncrementValue; } set { SetMemberAndRaiseSelfChanged(ref _columnIncrementValue, value); } }
public double? ReplacementValueForNaNMatrixElements { get { return _replacementValueForNaNMatrixElements; } set { SetMemberAndRaiseSelfChanged(ref _replacementValueForNaNMatrixElements, value); } }
public double? ReplacementValueForInfiniteMatrixElements { get { return _replacementValueForInfiniteMatrixElements; } set { SetMemberAndRaiseSelfChanged(ref _replacementValueForInfiniteMatrixElements, value); } }
public int? DataPretreatmentCorrectionOrder { get { return _dataPretreatmentCorrectionOrder; } set { SetMemberAndRaiseSelfChanged(ref _dataPretreatmentCorrectionOrder, value); } }
public Altaxo.Calc.Fourier.Windows.IWindows2D? FourierWindow
{
get { return _fourierWindow; }
set
{
if (!object.ReferenceEquals(_fourierWindow, value))
{
_fourierWindow = value;
EhSelfChanged(EventArgs.Empty);
}
}
}
public Altaxo.Calc.Fourier.RealFourierTransformationOutputKind OutputKind { get { return _kindOfOutputResult; } set { SetMemberEnumAndRaiseSelfChanged(ref _kindOfOutputResult, value); } }
public bool CenterResult { get { return _centerResult; } set { SetMemberAndRaiseSelfChanged(ref _centerResult, value); } }
public double ResultingFractionOfRowsUsed
{
get { return _resultFractionOfRows; }
set
{
if (!(value >= 0 && (value <= 1)))
throw new ArgumentOutOfRangeException("Value has to be in the range between 0 and 1");
SetMemberAndRaiseSelfChanged(ref _resultFractionOfRows, value);
}
}
public double ResultingFractionOfColumnsUsed
{
get { return _resultFractionOfColumns; }
set
{
if (!(value >= 0 && (value <= 1)))
throw new ArgumentOutOfRangeException("Value has to be in the range between 0 and 1");
SetMemberAndRaiseSelfChanged(ref _resultFractionOfColumns, value);
}
}
public bool OutputFrequencyHeaderColumns { get { return _outputFrequencyHeaderColumns; } set { SetMemberAndRaiseSelfChanged(ref _outputFrequencyHeaderColumns, value); } }
public string FrequencyRowHeaderColumnName { get { return _frequencyRowHeaderColumnName; } set { SetMemberAndRaiseSelfChanged(ref _frequencyRowHeaderColumnName, value); } }
public string FrequencyColumnHeaderColumnName { get { return _frequencyColumnHeaderColumnName; } set { SetMemberAndRaiseSelfChanged(ref _frequencyColumnHeaderColumnName, value); } }
public bool OutputPeriodHeaderColumns { get { return _outputPeriodHeaderColumns; } set { SetMemberAndRaiseSelfChanged(ref _outputPeriodHeaderColumns, value); } }
public string PeriodRowHeaderColumnName { get { return _periodRowHeaderColumnName; } set { SetMemberAndRaiseSelfChanged(ref _periodRowHeaderColumnName, value); } }
public string PeriodColumnHeaderColumnName { get { return _periodColumnHeaderColumnName; } set { SetMemberAndRaiseSelfChanged(ref _periodColumnHeaderColumnName, value); } }
public string? RowIncrementMessage { get { return _rowIncrementMessage; } set { SetMemberAndRaiseSelfChanged(ref _rowIncrementMessage, value); } }
public string? ColumnIncrementMessage { get { return _columnIncrementMessage; } set { SetMemberAndRaiseSelfChanged(ref _columnIncrementMessage, value); } }
}
}
| Altaxo/Altaxo | Altaxo/Base/Worksheet/Commands/Analysis/RealFourierTransformation2DOptions.cs | C# | gpl-3.0 | 14,821 |
import pytest
import nengo
def pytest_funcarg__Simulator(request):
"""the Simulator class being tested.
Please use this, and not nengo.Simulator directly,
unless the test is reference simulator specific.
"""
return nengo.Simulator
def pytest_generate_tests(metafunc):
if "nl" in metafunc.funcargnames:
metafunc.parametrize("nl", [nengo.LIF, nengo.LIFRate, nengo.Direct])
if "nl_nodirect" in metafunc.funcargnames:
metafunc.parametrize("nl_nodirect", [nengo.LIF, nengo.LIFRate])
def pytest_addoption(parser):
parser.addoption('--benchmarks', action='store_true', default=False,
help='Also run benchmarking tests')
parser.addoption('--noexamples', action='store_false', default=True,
help='Do not run examples')
parser.addoption(
'--optional', action='store_true', default=False,
help='Also run optional tests that may use optional packages')
def pytest_runtest_setup(item):
for mark, option, message in [
('benchmark', 'benchmarks', "benchmarks not requested"),
('example', 'noexamples', "examples not requested"),
('optional', 'optional', "optional tests not requested")]:
if getattr(item.obj, mark, None) and not item.config.getvalue(option):
pytest.skip(message)
| ZeitgeberH/nengo | nengo/tests/conftest.py | Python | gpl-3.0 | 1,348 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import socket
import sys
from argparse import ArgumentParser
from setproctitle import setproctitle
from amavisvt.config import Configuration
BUFFER_SIZE = 4096
class AmavisVTClient(object):
def __init__(self, socket_path):
self.config = Configuration()
self.socket_path = socket_path or self.config.socket_path
def execute(self, command, *arguments):
logger.debug("Executing command '%s' with args: %s", command, arguments)
translate = {
'ping': 'PING',
'scan': 'CONTSCAN',
'report': 'REPORT',
}
sock = None
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.socket_path)
# send absolute paths to amavisvtd
absolute_args = [os.path.abspath(p) for p in arguments]
s = "%s %s" % (translate.get(command, command.upper()), ' '.join(absolute_args))
payload = s.strip() + "\n"
sock.sendall(payload.encode('utf-8'))
data = sock.recv(BUFFER_SIZE)
return data.decode('utf-8')
finally:
if sock:
sock.close()
if __name__ == "__main__": # pragma: no cover
setproctitle("amavisvtd")
parser = ArgumentParser()
parser.add_argument('-v', '--verbose', action='count', help='Increase verbosity', default=2)
parser.add_argument('-d', '--debug', action='store_true', default=False, help='Send verbose log messages to stdout too')
parser.add_argument('-s', '--socket', help='Socket path')
parser.add_argument('command', choices=('ping', 'scan', 'report'))
parser.add_argument('command_args', nargs='*')
args = parser.parse_args()
logging.basicConfig(
level=logging.FATAL - (10 * args.verbose),
format='%(asctime)s %(levelname)-7s [%(threadName)s] %(message)s',
)
logger = logging.getLogger()
if not args.debug:
for h in logger.handlers:
h.setLevel(logging.ERROR)
if not args.command.lower() in ('ping', 'scan', 'report'):
print("Invalid command: %s" % args.command)
sys.exit(1)
error = False
try:
client = AmavisVTClient(args.socket)
response = client.execute(args.command, *tuple(args.command_args))
error = response.startswith('ERROR:')
print(response)
except Exception as ex:
error = True
logger.exception("Command '%s' failed", args.command)
print(ex)
finally:
sys.exit(int(error))
| ercpe/amavisvt | amavisvt/amavisvtc.py | Python | gpl-3.0 | 2,613 |
'use strict';
const express = require('express');
const service = express();
var os = require('os');
var networkInterfaces = os.networkInterfaces();
module.exports = service;
module.exports.networkInterfaces = networkInterfaces;
| orhaneee/SlackBotHeroku | server/service.js | JavaScript | gpl-3.0 | 232 |
<?php
/**
* The template for displaying search results pages
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
*
* @package ibreatheart
*/
get_header(); ?>
<section id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'ibreatheart' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'template-parts/content', 'search' );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</section><!-- #primary -->
<?php
get_sidebar();
get_footer();
| BracketMonks/hackathon-frontend | wordpress-project/ibreatheart-underscores/search.php | PHP | gpl-3.0 | 1,111 |
package bio.singa.simulation.model.modules;
import bio.singa.simulation.entities.ChemicalEntity;
import bio.singa.features.model.Evidence;
import bio.singa.features.model.Feature;
import bio.singa.simulation.model.modules.concentration.ModuleState;
import bio.singa.simulation.model.simulation.Simulation;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* @author cl
*/
public interface UpdateModule extends Runnable {
String getIdentifier();
ModuleState getState();
void setSimulation(Simulation simulation);
Set<ChemicalEntity> getReferencedChemicalEntities();
Set<Class<? extends Feature>> getRequiredFeatures();
void checkFeatures();
void setFeature(Feature<?> feature);
Collection<Feature<?>> getFeatures();
List<Evidence> getEvidence();
void initialize();
void reset();
void onReset();
void onCompletion();
}
| cleberecht/singa | singa-simulation/src/main/java/bio/singa/simulation/model/modules/UpdateModule.java | Java | gpl-3.0 | 906 |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
class Main{
public static class Agency {
String name;
int A, B;
public Agency(String s) {
StringTokenizer st=new StringTokenizer(s,":");
this.name=st.nextToken();
st=new StringTokenizer(st.nextToken(),",");
this.A=Integer.parseInt(st.nextToken());
this.B=Integer.parseInt(st.nextToken());
}
}
public static class Result implements Comparable<Result> {
Agency a;
int cost;
public int compareTo(Result r) {
return (this.cost!=r.cost) ? this.cost-r.cost : this.a.name.compareTo(r.a.name);
}
}
public static void main (String [] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int testCaseCount=Integer.parseInt(br.readLine());
for (int testCase=1;testCase<=testCaseCount;testCase++) {
StringTokenizer st=new StringTokenizer(br.readLine());
int N=Integer.parseInt(st.nextToken());
int M=Integer.parseInt(st.nextToken());
int L=Integer.parseInt(st.nextToken());
Agency [] agencies=new Agency [L];
for (int l=0;l<L;l++) agencies[l]=new Agency(br.readLine());
Result [] results=new Result[L];
for (int l=0;l<L;l++) {
Agency agency=agencies[l];
results[l]=new Result();
results[l].a=agency;
int curr=N;
int cost=0;
while (curr>M) {
if (curr/2>=M) {
int c1=agency.B;
int c2=(curr-curr/2)*agency.A;
curr/=2;
if (c1<c2) cost+=c1;
else cost+=c2;
} else {
cost+=(curr-M)*agency.A;
curr=M;
}
}
results[l].cost=cost;
}
Arrays.sort(results);
StringBuilder sb=new StringBuilder();
sb.append("Case ");
sb.append(testCase);
sb.append('\n');
for (Result r: results) {
sb.append(r.a.name);
sb.append(' ');
sb.append(r.cost);
sb.append('\n');
}
System.out.print(sb.toString());
}
}
} | PuzzlesLab/UVA | King/10670 Work Reduction.java | Java | gpl-3.0 | 1,957 |
/*
* 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/>.
*/
/*
* CleanUpHandler.java
* Copyright (C) 2009 University of Waikato, Hamilton, New Zealand
*/
package adams.core;
/**
* Interface for classes that support cleaning up of memory.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface CleanUpHandler {
/**
* Cleans up data structures, frees up memory.
*/
public void cleanUp();
}
| waikato-datamining/adams-base | adams-core/src/main/java/adams/core/CleanUpHandler.java | Java | gpl-3.0 | 1,068 |
/*
Copyright (C) 2012 Andrew Cotter
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/>.
*/
/**
\file svm_optimizer_classification_unbiased_perceptron.cpp
\brief SVM::Optimizer::Unbiased::Perceptron implementation
*/
#include "svm_optimizer_classification_unbiased_perceptron.hpp"
namespace SVM {
namespace Optimizer {
namespace Classification {
namespace Unbiased {
//============================================================================
// Perceptron methods
//============================================================================
Perceptron::~Perceptron() {
}
unsigned int const Perceptron::TrainingSize() const {
return m_pKernel->TrainingSize();
}
unsigned int const Perceptron::ValidationSize() const {
return( m_pKernel->Size() - m_pKernel->TrainingSize() );
}
void Perceptron::GetAlphas( double* const begin, double* const end ) const {
unsigned int const trainingSize = m_pKernel->TrainingSize();
if ( end != begin + trainingSize )
throw std::runtime_error( "Perceptron::GetAlphas parameter array has incorrect length" );
double const scale = 1 / std::sqrt( m_normSquared );
for ( unsigned int ii = 0; ii < trainingSize; ++ii )
begin[ ii ] = m_alphas[ ii ] * scale;
}
double const Perceptron::NormSquared() const {
return 1;
}
void Perceptron::GetValidationResponses( double* const begin, double* const end ) const {
unsigned int const trainingSize = m_pKernel->TrainingSize();
unsigned int const totalSize = m_pKernel->Size();
BOOST_ASSERT( trainingSize <= totalSize );
if ( trainingSize >= totalSize )
throw std::runtime_error( "Perceptron::GetValidationResponses requires a validation set" );
if ( end != begin + totalSize - trainingSize )
throw std::runtime_error( "Perceptron::GetValidationResponses parameter array has incorrect length" );
{ double const scale = 1 / std::sqrt( m_normSquared );
double* pDestination = begin;
double* pDestinationEnd = end;
double const* pResponse = m_responses.get() + trainingSize;
double const* pLabel = m_pKernel->Labels() + trainingSize;
for ( ; pDestination != pDestinationEnd; ++pDestination, ++pResponse, ++pLabel ) {
double const response = *pResponse * scale;
*pDestination = ( ( *pLabel > 0 ) ? response : -response );
}
}
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SparseVector< float > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SparseVector< double > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SpanVector< float > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SpanVector< double > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, DenseVector< float > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, DenseVector< double > const& otherVector ) const {
return EvaluateHelper( otherVector );
}
void Perceptron::Iterate( Random::Generator::LaggedFibonacci4<>& generator ) {
unsigned int const trainingSize = m_pKernel->TrainingSize();
double const scaledMargin = m_margin * std::sqrt( m_normSquared );
FindKappa();
if ( m_kappa < scaledMargin ) {
unsigned int index = m_index;
double kappa = scaledMargin;
{ double const* pAlpha = m_alphas.get();
double const* pAlphaEnd = pAlpha + trainingSize;
double const* pResponse = m_responses.get();
double const* pLabel = m_pKernel->Labels();
for ( ; pAlpha != pAlphaEnd; ++pAlpha, ++pResponse, ++pLabel ) {
if ( *pAlpha != 0 ) {
double const response = ( ( *pLabel > 0 ) ? *pResponse : -*pResponse );
if ( UNLIKELY( response <= kappa ) ) {
index = ( pAlpha - m_alphas.get() );
kappa = response;
}
}
}
}
if ( m_pKernel->Labels()[ index ] > 0 ) {
m_normSquared += 2 * m_responses[ index ] + m_normsSquared[ index ];
m_pKernel->SetAlpha( m_alphas.get(), m_responses.get(), index, m_alphas[ index ] + 1 );
}
else {
m_normSquared += -2 * m_responses[ index ] + m_normsSquared[ index ];
m_pKernel->SetAlpha( m_alphas.get(), m_responses.get(), index, m_alphas[ index ] - 1 );
}
m_index = trainingSize;
m_kappa = std::numeric_limits< double >::quiet_NaN();
}
}
void Perceptron::Recalculate() {
unsigned int const trainingSize = m_pKernel->TrainingSize();
m_pKernel->RecalculateResponses( m_alphas.get(), m_responses.get() );
{ double accumulator = 0;
double const* pAlpha = m_alphas.get();
double const* pAlphaEnd = pAlpha + trainingSize;
double const* pResponse = m_responses.get();
for ( ; pAlpha != pAlphaEnd; ++pAlpha, ++pResponse )
accumulator += *pAlpha * *pResponse;
BOOST_ASSERT( accumulator >= 0 );
m_normSquared = accumulator;
}
m_index = trainingSize;
m_kappa = std::numeric_limits< double >::quiet_NaN();
}
void Perceptron::FindKappa() const {
if ( boost::math::isnan( m_kappa ) ) {
unsigned int const trainingSize = m_pKernel->TrainingSize();
m_index = trainingSize;
m_kappa = std::numeric_limits< double >::infinity();
double const* pResponse = m_responses.get();
double const* pResponseEnd = pResponse + trainingSize;
double const* pLabel = m_pKernel->Labels();
for ( ; pResponse != pResponseEnd; ++pResponse, ++pLabel ) {
double const response = ( ( *pLabel > 0 ) ? *pResponse : -*pResponse );
if ( UNLIKELY( response < m_kappa ) ) {
m_index = ( pResponse - m_responses.get() );
m_kappa = response;
}
}
}
BOOST_ASSERT( m_index < m_pKernel->TrainingSize() );
BOOST_ASSERT( ! boost::math::isnan( m_kappa ) );
}
} // namespace Unbiased
} // namespace Classification
} // namespace Optimizer
} // namespace SVM
| maliq/issvm | svm_optimizer_classification_unbiased_perceptron.cpp | C++ | gpl-3.0 | 6,718 |
<?php
/**
* Normatividad Torreón - ReglamentoArchivoMunicipal
*
* Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.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 NormatividadTorreon
*/
namespace ReglamentosVigentes;
/**
* Clase ReglamentoArchivoMunicipal
*/
class ReglamentoArchivoMunicipal extends \Base\PublicacionSchemaArticle {
/**
* Constructor
*/
public function __construct() {
// Ejecutar constructor en el padre
parent::__construct();
// Título, autor y fecha
$this->nombre = 'Reglamento del Archivo Municipal de Torreón';
//~ $this->autor = '';
$this->fecha = '2013-01-01T00:00';
// El nombre del archivo a crear
$this->archivo = 'reglamento-archivo-municipal';
// La descripción y claves dan información a los buscadores y redes sociales
$this->descripcion = 'El presente reglamento tiene por objeto la guarda, preservación, conservación preventiva, restauración, conducción, depuración y aprovechamiento institucional y social del patrimonio archivístico municipal.';
$this->claves = 'Reglamento, Vigente, Archivo, Municipal';
// Ruta al archivo markdown con el contenido
$this->contenido_archivo_markdown = 'lib/ReglamentosVigentes/ReglamentoArchivoMunicipal.md';
} // constructor
} // Clase ReglamentoArchivoMunicipal
?>
| normatividadtorreon/normatividadtorreon.github.io | lib/ReglamentosVigentes/ReglamentoArchivoMunicipal.php | PHP | gpl-3.0 | 2,138 |
/*************************
Coppermine Photo Gallery
************************
Copyright (c) 2003-2016 Coppermine Dev Team
v1.0 originally written by Gregory DEMAR
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.
********************************************
Coppermine version: 1.6.01
$HeadURL$
$Revision$
**********************************************/
/*
* Date prototype extensions. Doesn't depend on any
* other code. Doesn't overwrite existing methods.
*
* Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
* isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
* setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
*
* Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
*
* Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
* I've added my name to these methods so you know who to blame if they are broken!
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* An Array of day names starting with Sunday.
*
* @example dayNames[0]
* @result 'Sunday'
*
* @name dayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
/**
* An Array of abbreviated day names starting with Sun.
*
* @example abbrDayNames[0]
* @result 'Sun'
*
* @name abbrDayNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
/**
* An Array of month names starting with Janurary.
*
* @example monthNames[0]
* @result 'January'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/**
* An Array of abbreviated month names starting with Jan.
*
* @example abbrMonthNames[0]
* @result 'Jan'
*
* @name monthNames
* @type Array
* @cat Plugins/Methods/Date
*/
Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/**
* The first day of the week for this locale.
*
* @name firstDayOfWeek
* @type Number
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.firstDayOfWeek = 1;
/**
* The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.format = 'dd/mm/yyyy';
//Date.format = 'mm/dd/yyyy';
//Date.format = 'yyyy-mm-dd';
//Date.format = 'dd mmm yy';
/**
* The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
* only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
*
* @name format
* @type String
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fullYearStart = '20';
(function() {
/**
* Adds a given method under the given name
* to the Date prototype if it doesn't
* currently exist.
*
* @private
*/
function add(name, method) {
if( !Date.prototype[name] ) {
Date.prototype[name] = method;
}
};
/**
* Checks if the year is a leap year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.isLeapYear();
* @result true
*
* @name isLeapYear
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isLeapYear", function() {
var y = this.getFullYear();
return (y%4==0 && y%100!=0) || y%400==0;
});
/**
* Checks if the day is a weekend day (Sat or Sun).
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekend();
* @result false
*
* @name isWeekend
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekend", function() {
return this.getDay()==0 || this.getDay()==6;
});
/**
* Check if the day is a day of the week (Mon-Fri)
*
* @example var dtm = new Date("01/12/2008");
* dtm.isWeekDay();
* @result false
*
* @name isWeekDay
* @type Boolean
* @cat Plugins/Methods/Date
*/
add("isWeekDay", function() {
return !this.isWeekend();
});
/**
* Gets the number of days in the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDaysInMonth();
* @result 31
*
* @name getDaysInMonth
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDaysInMonth", function() {
return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
});
/**
* Gets the name of the day.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName();
* @result 'Saturday'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayName(true);
* @result 'Sat'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getDayName", function(abbreviated) {
return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
});
/**
* Gets the name of the month.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName();
* @result 'Janurary'
*
* @example var dtm = new Date("01/12/2008");
* dtm.getMonthName(true);
* @result 'Jan'
*
* @param abbreviated Boolean When set to true the name will be abbreviated.
* @name getDayName
* @type String
* @cat Plugins/Methods/Date
*/
add("getMonthName", function(abbreviated) {
return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
});
/**
* Get the number of the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getDayOfYear();
* @result 11
*
* @name getDayOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getDayOfYear", function() {
var tmpdtm = new Date("1/1/" + this.getFullYear());
return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
});
/**
* Get the number of the week of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.getWeekOfYear();
* @result 2
*
* @name getWeekOfYear
* @type Number
* @cat Plugins/Methods/Date
*/
add("getWeekOfYear", function() {
return Math.ceil(this.getDayOfYear() / 7);
});
/**
* Set the day of the year.
*
* @example var dtm = new Date("01/12/2008");
* dtm.setDayOfYear(1);
* dtm.toString();
* @result 'Tue Jan 01 2008 00:00:00'
*
* @name setDayOfYear
* @type Date
* @cat Plugins/Methods/Date
*/
add("setDayOfYear", function(day) {
this.setMonth(0);
this.setDate(day);
return this;
});
/**
* Add a number of years to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addYears(1);
* dtm.toString();
* @result 'Mon Jan 12 2009 00:00:00'
*
* @name addYears
* @type Date
* @cat Plugins/Methods/Date
*/
add("addYears", function(num) {
this.setFullYear(this.getFullYear() + num);
return this;
});
/**
* Add a number of months to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMonths(1);
* dtm.toString();
* @result 'Tue Feb 12 2008 00:00:00'
*
* @name addMonths
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMonths", function(num) {
var tmpdtm = this.getDate();
this.setMonth(this.getMonth() + num);
if (tmpdtm > this.getDate())
this.addDays(-this.getDate());
return this;
});
/**
* Add a number of days to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addDays(1);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addDays
* @type Date
* @cat Plugins/Methods/Date
*/
add("addDays", function(num) {
this.setDate(this.getDate() + num);
return this;
});
/**
* Add a number of hours to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addHours(24);
* dtm.toString();
* @result 'Sun Jan 13 2008 00:00:00'
*
* @name addHours
* @type Date
* @cat Plugins/Methods/Date
*/
add("addHours", function(num) {
this.setHours(this.getHours() + num);
return this;
});
/**
* Add a number of minutes to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addMinutes(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 01:00:00'
*
* @name addMinutes
* @type Date
* @cat Plugins/Methods/Date
*/
add("addMinutes", function(num) {
this.setMinutes(this.getMinutes() + num);
return this;
});
/**
* Add a number of seconds to the date object.
*
* @example var dtm = new Date("01/12/2008");
* dtm.addSeconds(60);
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name addSeconds
* @type Date
* @cat Plugins/Methods/Date
*/
add("addSeconds", function(num) {
this.setSeconds(this.getSeconds() + num);
return this;
});
/**
* Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
*
* @example var dtm = new Date();
* dtm.zeroTime();
* dtm.toString();
* @result 'Sat Jan 12 2008 00:01:00'
*
* @name zeroTime
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("zeroTime", function() {
this.setMilliseconds(0);
this.setSeconds(0);
this.setMinutes(0);
this.setHours(0);
return this;
});
/**
* Returns a string representation of the date object according to Date.format.
* (Date.toString may be used in other places so I purposefully didn't overwrite it)
*
* @example var dtm = new Date("01/12/2008");
* dtm.asString();
* @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
*
* @name asString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
add("asString", function() {
var r = Date.format;
return r
.split('yyyy').join(this.getFullYear())
.split('yy').join((this.getFullYear() + '').substring(2))
.split('mmm').join(this.getMonthName(true))
.split('mm').join(_zeroPad(this.getMonth()+1))
.split('dd').join(_zeroPad(this.getDate()));
});
/**
* Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
* (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
*
* @example var dtm = Date.fromString("12/01/2008");
* dtm.toString();
* @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
*
* @name fromString
* @type Date
* @cat Plugins/Methods/Date
* @author Kelvin Luck
*/
Date.fromString = function(s)
{
var f = Date.format;
var d = new Date('01/01/1977');
var iY = f.indexOf('yyyy');
if (iY > -1) {
d.setFullYear(Number(s.substr(iY, 4)));
} else {
// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
}
var iM = f.indexOf('mmm');
if (iM > -1) {
var mStr = s.substr(iM, 3);
for (var i=0; i<Date.abbrMonthNames.length; i++) {
if (Date.abbrMonthNames[i] == mStr) break;
}
d.setMonth(i);
} else {
d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
}
d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
if (isNaN(d.getTime())) {
return false;
}
return d;
};
// utility method
var _zeroPad = function(num) {
var s = '0'+num;
return s.substring(s.length-2)
//return ('0'+num).substring(-2); // doesn't work on IE :(
};
})(); | CatBerg-TestOrg/coppermine | js/date.js | JavaScript | gpl-3.0 | 13,375 |
from biot import *
# display_wires(N_wires=6, r_wires=r_wires)
display_quiver()
display_particles(mode_name="boris_exact", colormap="Blues")
# display_particles(mode_name="RK4_exact", colormap="Reds")
print("Finished display")
mlab.show()
| StanczakDominik/PythonBiotSavart | plot.py | Python | gpl-3.0 | 240 |
# This should hold main initialization logic
puts "hello world" | benweissmann/rise | src/src/main.rb | Ruby | gpl-3.0 | 63 |
package info.jlibrarian.stringutils; /* Original source code (c) 2013 C. Ivan Cooper. Licensed under GPLv3, see file COPYING for terms. */
import java.util.Comparator;
/**
* Represents a comparable wildcard string, also contains static functions for comparing wildcard strings.
*
* A wildcard string is any String. If the wildcard string includes an asterisk '*', then for the purpose
* of comparison, only the characters before the asterisk need match the other wildcard string.
*
* if any wildcards are used, this comparison is symmetric and reflexive, but it is NOT transitive -
* e.g. a=b and b=c but maybe not a=c
*
* for example, these pairs of wildcard strings are all considered "equal"
* foobar foobar
* foo* foobar
* foobar foo*
* * foobar
* foobar foobar*
*
* @author C. Ivan Cooper (ivan@4levity.net)
*
*/
public class WildcardString implements Comparable<WildcardString>,Comparator<String> {
private final String string;
/**
* Compares two strings with a simple wildcard rule (see WildcardString)
*
* @param a
* @param b
* @return comparison result or 0 if equal
*/
static public int compareWildcardString(String a,String b) {
if(a==null && b==null)
return 0;
//else
if(a==null)
return -1;
//else
if(b==null)
return 1;
int wca=a.indexOf("*");
int wcb=b.indexOf("*");
if(wcb>=0) {
b = b.substring(0,wcb); // remove * and trailing chars
if(a.length()>wcb)
a = a.substring(0,wcb);
}
if(wca>=0) {
a = a.substring(0,wca); // remove * and trailing chars
if(b.length()>wca)
b = b.substring(0,wca);
}
return a.compareToIgnoreCase(b);
//return a.compareTo(b);
}
static public String generalizeWildcard(String s) {
if (s==null)
return "*";
int ix=s.length()-1;
if(ix<=1)
return "*";
while(ix>0 && s.charAt(ix)=='*')
ix--; // skip any * fields starting from the end
return s.substring(0, ix)+"*";
}
public WildcardString(String s) {
if(s==null)
string="*";
else
string=s;
}
public WildcardString() {
string="*";
}
/**
* note: violates transitivity of equality
* @param arg0
* @param arg1
* @return
*/
public int compare(String arg0, String arg1) {
return compareWildcardString(arg0,arg1);
}
/**
* note: violates transitivity of equality
* @param arg0
* @return
*/
public int compareTo(WildcardString arg0) {
if(arg0==null)
throw new NullPointerException("cannot compare WildcardString to null");
return compareWildcardString(string,arg0.toString());
}
@Override
public String toString() {
return string;
}
/**
* note: violates transitivity of equality
* @param obj
* @return
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final WildcardString other = (WildcardString) obj;
return (0==compareTo(other));
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + (this.string != null ? this.string.hashCode() : 0);
return hash;
}
}
| 4levity/Conan | src/main/java/info/jlibrarian/stringutils/WildcardString.java | Java | gpl-3.0 | 3,562 |
<?php
/**
* acm : Algae Culture Management (https://github.com/singularfactory/ACM)
* Copyright 2012, Singular Factory <info@singularfactory.com>
*
* This file is part of ACM
*
* ACM 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.
*
* ACM 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 ACM. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2012, Singular Factory <info@singularfactory.com>
* @package ACM.Frontend
* @since 1.0
* @link https://github.com/singularfactory/ACM
* @license GPLv3 License (http://www.gnu.org/licenses/gpl.txt)
*/
?>
<?php use_helper('BarCode'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="title" content="Algae culture management | Banco Español de Algas" />
<meta name="description" content="Algae culture management of Banco Español de Algas" />
<meta name="keywords" content="bea, banco, español, algas, marine, biotechnology, spanish, banl, algae" />
<meta name="language" content="en" />
<meta name="robots" content="index, follow" />
<title>Algae culture management | Banco Español de Algas</title>
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" media="screen" href="/css/labels.css" />
</head>
<body>
<?php foreach ($strains as $strain):?>
<table width="100%">
<tr>
<th width="25%" style="text-align:right;">BEA Number</th>
<td style="text-align:left;"><?php echo $strain->getFullCode();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Genus</th>
<td style="text-align:left;"><?php echo $strain->getGenus();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Species</th>
<td style="text-align:left;"><?php echo $strain->getSpecies();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Class</th>
<td style="text-align:left;"><?php echo $strain->getTaxonomicClass();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Public</th>
<td style="text-align:left;"><?php echo $strain->getIsPublic();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Internal Code</th>
<td style="text-align:left;"><?php echo $strain->getInternalCode();?></td>
</tr>
<tr>
<th width="25%" style="text-align:right;">Remarks</th>
<td style="text-align:left;"><?php echo $strain->getRemarks();?></td>
</tr>
</table>
<hr/>
<?php endforeach; ?>
</body>
</html>
| singularfactory/ACM | apps/frontend/modules/report/templates/_maintenance_pdf.php | PHP | gpl-3.0 | 3,157 |
package TFC.Handlers.Client;
import org.lwjgl.opengl.GL11;
import TFC.*;
import TFC.Core.TFC_Core;
import TFC.Core.TFC_Settings;
import TFC.Core.TFC_Time;
import TFC.Core.Player.PlayerInfo;
import TFC.Core.Player.PlayerManagerTFC;
import TFC.Items.*;
import TFC.TileEntities.TileEntityWoodConstruct;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.entity.*;
import net.minecraft.client.gui.inventory.*;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.block.*;
import net.minecraft.block.material.*;
import net.minecraft.crash.*;
import net.minecraft.creativetab.*;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.*;
import net.minecraft.entity.effect.*;
import net.minecraft.entity.item.*;
import net.minecraft.entity.monster.*;
import net.minecraft.entity.player.*;
import net.minecraft.entity.projectile.*;
import net.minecraft.inventory.*;
import net.minecraft.item.*;
import net.minecraft.nbt.*;
import net.minecraft.network.*;
import net.minecraft.network.packet.*;
import net.minecraft.pathfinding.*;
import net.minecraft.potion.*;
import net.minecraft.server.*;
import net.minecraft.stats.*;
import net.minecraft.tileentity.*;
import net.minecraft.util.*;
import net.minecraft.village.*;
import net.minecraft.world.*;
import net.minecraft.world.biome.*;
import net.minecraft.world.chunk.*;
import net.minecraft.world.gen.feature.*;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.event.ForgeSubscribe;
public class PlankHighlightHandler{
@ForgeSubscribe
public void DrawBlockHighlightEvent(DrawBlockHighlightEvent evt)
{
World world = evt.player.worldObj;
double var8 = evt.player.lastTickPosX + (evt.player.posX - evt.player.lastTickPosX) * (double)evt.partialTicks;
double var10 = evt.player.lastTickPosY + (evt.player.posY - evt.player.lastTickPosY) * (double)evt.partialTicks;
double var12 = evt.player.lastTickPosZ + (evt.player.posZ - evt.player.lastTickPosZ) * (double)evt.partialTicks;
if(evt.currentItem != null && evt.currentItem.getItem() instanceof ItemPlank)
{
//Setup GL for the depthbox
//GL11.glEnable(GL11.GL_BLEND);
//GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glColor3f(1,1,1);
//GL11.glDisable(GL11.GL_CULL_FACE);
//GL11.glDepthMask(false);
//ForgeHooksClient.bindTexture("/bioxx/woodoverlay.png", ModLoader.getMinecraftInstance().renderEngine.getTexture("/bioxx/woodoverlay.png"));
// double blockMinX = evt.target.blockX;
// double blockMinY = evt.target.blockY;
// double blockMinZ = evt.target.blockZ;
// double blockMaxX = evt.target.blockX+1;
// double blockMaxY = evt.target.blockY+1;
// double blockMaxZ = evt.target.blockZ+1;
// drawFaceUV(AxisAlignedBB.getAABBPool().addOrModifyAABBInPool(
// blockMinX,
// blockMinY,
// blockMinZ,
// blockMaxX,
// blockMaxY,
// blockMaxZ
// ).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12), evt.target.sideHit);
GL11.glDisable(GL11.GL_TEXTURE_2D);
boolean isConstruct = world.getBlockId(evt.target.blockX, evt.target.blockY, evt.target.blockZ) == TFCBlocks.WoodConstruct.blockID;
float div = 1f / TileEntityWoodConstruct.PlankDetailLevel;
//Get the hit location in local box coords
double hitX = Math.round((evt.target.hitVec.xCoord - evt.target.blockX)*100)/100.0d;
double hitY = Math.round((evt.target.hitVec.yCoord - evt.target.blockY)*100)/100.0d;
double hitZ = Math.round((evt.target.hitVec.zCoord - evt.target.blockZ)*100)/100.0d;
//get the targeted sub block coords
double subX = (double)((int)((hitX)*8))/8;
double subY = (double)((int)((hitY)*8))/8;
double subZ = (double)((int)((hitZ)*8))/8;
//create the box size
double minX = evt.target.blockX + subX;
double minY = evt.target.blockY + subY;
double minZ = evt.target.blockZ + subZ;
double maxX = minX + 0.125;
double maxY = minY + 0.125;
double maxZ = minZ + 0.125;
if(isConstruct && hitY != 0 && hitY != 1 && hitZ != 0 && hitZ != 1 && hitX != 0 && hitX != 1)
{
if(evt.target.sideHit == 0)
{
minY = evt.target.blockY;
maxY = evt.target.blockY + 1;
}
else if(evt.target.sideHit == 1)
{
minY = evt.target.blockY;
maxY = evt.target.blockY + 1;
}
else if(evt.target.sideHit == 2)
{
minZ = evt.target.blockZ;
maxZ = evt.target.blockZ+1;
}
else if(evt.target.sideHit == 3)
{
minZ = evt.target.blockZ;
maxZ = evt.target.blockZ+1;
}
else if(evt.target.sideHit == 4)
{
minX = evt.target.blockX;
maxX = evt.target.blockX+1;
}
else if(evt.target.sideHit == 5)
{
minX = evt.target.blockX;
maxX = evt.target.blockX+1;
}
}
else
{
if(evt.target.sideHit == 0)
{
maxY = minY;
minY = minY - 1;
}
else if(evt.target.sideHit == 1)
{
maxY = minY + 1;
}
else if(evt.target.sideHit == 2)
{
maxZ = minZ;
minZ = minZ - 1;
}
else if(evt.target.sideHit == 3)
{
maxZ = minZ + 1;
}
else if(evt.target.sideHit == 4)
{
maxX = minX;
minX = minX - 1;
}
else if(evt.target.sideHit == 5)
{
maxX = minX + 1;
}
}
//Setup GL for the depthbox
GL11.glEnable(GL11.GL_BLEND);
//Setup the GL stuff for the outline
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.4F);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glDepthMask(false);
//Draw the mini Box
drawBox(AxisAlignedBB.getAABBPool().getAABB(minX,minY,minZ,maxX,maxY,maxZ).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
GL11.glDepthMask(true);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_BLEND);
}
}
void drawFaceUV(AxisAlignedBB par1AxisAlignedBB, int side)
{
Tessellator var2 = Tessellator.instance;
var2.setColorRGBA_F(1, 1, 1, 1);
//Top
var2.startDrawing(GL11.GL_QUADS);
if(side == 0)
{
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 0, 1);
}
else if(side == 1)
{
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 0, 1);
}
else if(side == 2)
{
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1);
}
else if(side == 3)
{
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 0, 1);
}
else if(side == 4 )
{
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1);
}
else if( side == 5)
{
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1);
var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1);
}
var2.draw();
}
void drawFace(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
//Top
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
}
void drawBox(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
//Top
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
//Bottom
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.draw();
//-x
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.draw();
//+x
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
//-z
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
//+z
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.draw();
}
void drawOutlinedBoundingBox(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
var2.startDrawing(3);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
var2.startDrawing(3);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.draw();
var2.startDrawing(GL11.GL_LINES);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
}
}
| Timeslice42/TFCraft | TFC_Shared/src/TFC/Handlers/Client/PlankHighlightHandler.java | Java | gpl-3.0 | 14,157 |
<?php
global $_MODULE;
$_MODULE = array();
$_MODULE['<{blocksearch}prestashop>blocksearch-top_13348442cc6a27032d2b4aa28b75a5d3'] = 'Cerca';
$_MODULE['<{blocksearch}prestashop>blocksearch_31a0c03d7fbd1dc61d3b8e02760e703b'] = 'Blocco ricerca rapida';
$_MODULE['<{blocksearch}prestashop>blocksearch_99e20473c0bf3c22d7420eff03ce66c3'] = 'Aggiunge un blocco con un campo di ricerca rapida';
$_MODULE['<{blocksearch}prestashop>blocksearch_13348442cc6a27032d2b4aa28b75a5d3'] = 'Cerca';
$_MODULE['<{blocksearch}prestashop>blocksearch_52d578d063d6101bbdae388ece037e60'] = 'Inserisci il nome di un prodotto';
$_MODULE['<{blocksearch}prestashop>blocksearch_34d1f91fb2e514b8576fab1a75a89a6b'] = 'Vai';
| desarrollosimagos/puroextremo.com.ve | modules/blocksearch_mod/translations/it.php | PHP | gpl-3.0 | 691 |
package com.bahram.relationshippoints.logistical.Lifecycle;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
/**
* Created by bahram on 23.05.2015.
*/
public abstract class SupportFragmentLifecycle extends Fragment implements LifecycleDataHandling
{
/**
* Called to retrieve per-instance state from an activity before being killed
* so that the state can be restored in {@link #onCreate} or
* {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method
* will be passed to both).
* <p/>
* <p>This method is called before an activity may be killed so that when it
* comes back some time in the future it can restore its state. For example,
* if activity B is launched in front of activity A, and at some point activity
* A is killed to reclaim resources, activity A will have a chance to save the
* current state of its user interface via this method so that when the user
* returns to activity A, the state of the user interface can be restored
* via {@link #onCreate} or {@link #onRestoreInstanceState}.
* <p/>
* <p>Do not confuse this method with activity lifecycle callbacks such as
* {@link #onPause}, which is always called when an activity is being placed
* in the background or on its way to destruction, or {@link #onStop} which
* is called before destruction. One example of when {@link #onPause} and
* {@link #onStop} is called and not this method is when a user navigates back
* from activity B to activity A: there is no need to call {@link #onSaveInstanceState}
* on B because that particular instance will never be restored, so the
* system avoids calling it. An example when {@link #onPause} is called and
* not {@link #onSaveInstanceState} is when activity B is launched in front of activity A:
* the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't
* killed during the lifetime of B since the state of the user interface of
* A will stay intact.
* <p/>
* <p>The default implementation takes care of most of the UI per-instance
* state for you by calling {@link View#onSaveInstanceState()} on each
* view in the hierarchy that has an id, and by saving the id of the currently
* focused view (all of which is restored by the default implementation of
* {@link #onRestoreInstanceState}). If you override this method to save additional
* information not captured by each individual view, you will likely want to
* call through to the default implementation, otherwise be prepared to save
* all of the state of each view yourself.
* <p/>
* <p>If called, this method will occur before {@link #onStop}. There are
* no guarantees about whether it will occur before or after {@link #onPause}.
*
* @param outState Bundle in which to place your saved state.
* @see #onCreate
* @see #onRestoreInstanceState
* @see #onPause
*/
@Override
public void onSaveInstanceState(Bundle outState)
{
saveNecessaryData(outState);
storeStateGUI(outState);
super.onSaveInstanceState(outState);
}
}
| Mithrandir21/RelationshipPoints | app/src/main/java/com/bahram/relationshippoints/logistical/Lifecycle/SupportFragmentLifecycle.java | Java | gpl-3.0 | 3,247 |
<?php
/**
*
* UEA Style report
*
* This is the report suggested from the team using WebPA at UEA, UK
*
*
* @copyright 2007 Loughborough University
* @license http://www.gnu.org/licenses/gpl.txt
* @version 0.0.0.1
* @since 8 Aug 2008
*
*/
require_once("../../../includes/inc_global.php");
require_once(DOC__ROOT . 'includes/classes/class_assessment.php');
require_once(DOC__ROOT . 'includes/classes/class_algorithm_factory.php');
require_once(DOC__ROOT . 'includes/functions/lib_array_functions.php');
if (!check_user($_user, APP__USER_TYPE_TUTOR)){
header('Location:'. APP__WWW .'/logout.php?msg=denied');
exit;
}
// --------------------------------------------------------------------------------
// Process GET/POST
$assessment_id = fetch_GET('a');
$type = fetch_GET('t', 'view');
$tab = fetch_GET('tab');
$year = fetch_GET('y', date('Y'));
$marking_date = fetch_GET('md');
// --------------------------------------------------------------------------------
$assessment = new Assessment($DB);
if (!$assessment->load($assessment_id)) {
$assessment = null;
echo(gettext('Error: The requested assessment could not be loaded.'));
exit;
} else {
// ----------------------------------------
// Get the marking parameters used for the marksheet this report will display
$marking_params = $assessment->get_marking_params($marking_date);
if (!$marking_params) {
echo(gettext('Error: The requested marksheet could not be loaded.'));
exit;
}
// ----------------------------------------
// Get the appropriate algorithm and calculate the grades
$algorithm = AlgorithmFactory::get_algorithm($marking_params['algorithm']);
if (!$algorithm) {
echo(gettext('Error: The requested algorithm could not be loaded.'));
exit;
} else {
$algorithm->set_assessment($assessment);
$algorithm->set_marking_params($marking_params);
$algorithm->calculate();
$group_members = $algorithm->get_group_members();
$member_names = array();
for ($i =0; $i<count($group_members); $i++){
$array_key = array_keys($group_members);
$temp = $group_members[$array_key[$i]];
for ($j=0; $j<count($temp);$j++){
array_push($member_names, $CIS->get_user($temp[$j]));
}
}
}// /if-else(is algorithm)
}// /if-else(is assessment)
// ----------------------------------------
// Get the questions used in this assessment
$form = new Form($DB);
$form_xml =& $assessment->get_form_xml();
$form->load_from_xml($form_xml);
$question_count = (int) $form->get_question_count();
// Create the actual array (question_ids are 0-based)
if ($question_count>0) {
$questions = range(0, $question_count-1);
} else {
$questions = array();
}
//get the information in the format required
$score_array = null;
//get the information in the format required
//get an array of the group names
$group_names = $algorithm->get_group_names();
if ($assessment) {
foreach ($group_members as $group_id => $g_members) {
$g_member_count = count($group_members[$group_id]);
foreach ($questions as $question_id) {
$q_index = $question_id+1;
$question = $form->get_question($question_id);
$q_text = "Q{$q_index} : {$question['text']['_data']}";
foreach ($g_members as $i => $member_id) {
$individ = $CIS->get_user($member_id);
$mark_recipient = "{$individ['lastname']}, {$individ['forename']}";
foreach ($g_members as $j => $target_member_id) {
$individ = $CIS->get_user($target_member_id);
$marker = "{$individ['lastname']}, {$individ['forename']}";
if ($assessment->assessment_type == '0') {
if ($member_id == $target_member_id) {
$score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = 'n/a';
} else {
$score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = $algorithm->get_member_response($group_id, $target_member_id, $question_id,$member_id );
}
} else {
$score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = $algorithm->get_member_response($group_id, $target_member_id, $question_id, $member_id);
}
if (is_null($score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker])) {
$score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = '-';
}
}
}
}
}
}
/*
* --------------------------------------------------------------------------------
* If report type is HTML view
* --------------------------------------------------------------------------------
*/
if ($type == 'view') {
// Begin Page
$page_title = ($assessment) ? "{$assessment->name}" : gettext('report');
$UI->page_title = APP__NAME . ' ' . $page_title;
$UI->head();
?>
<style type="text/css">
<!--
#side_bar { display: none; }
#main { margin: 0px; }
table.grid th { padding: 8px; }
table.grid td { padding: 8px; text-align: center; }
table.grid td.important { background-color: #eec; }
-->
</style>
<?php
$UI->body();
$UI->content_start();
?>
<div class="content_box">
<h1 style="font-size: 150%;"><?php echo gettext('Student Responses');?></h1>
<table class="grid" cellpadding="2" cellspacing="1">
<tr>
<td>
<?php
//get an array of the group names
$group_names = $algorithm->get_group_names();
$teams = array_keys($score_array);
foreach ($teams as $i=> $team) {
echo "<h2>{$team}</h2>";
$team_members = array_keys($score_array[$team]);
foreach ($team_members as $team_member) {
echo "<h3>".gettext("Results for:")." {$team_member}</h3>";
$questions = array_keys($score_array[$team][$team_member]);
//print_r($questions);
echo "<table class='grid' cellpadding='2' cellspacing='1' style='font-size: 0.8em'>";
$q_count = 0;
foreach ($questions as $question) {
$markers = array_keys($score_array[$team][$team_member][$question]);
$markers_row = '';
$scores_row = '';
foreach ($markers as $marker) {
$markers_row = $markers_row ."<th>{$marker}</th>";
$score = $score_array[$team][$team_member][$question][$marker];
$scores_row = $scores_row . "<td>{$score}</td>";
}
if ($q_count == 0) {
echo "<tr><th> </th>";
echo $markers_row;
}
echo "</tr><tr><th>{$question}</th>";
echo $scores_row;
$q_count++;
}
echo "</tr></table><br/><br/>";
}
}
?>
</td>
</tr>
</table>
</div>
<?php
$UI->content_end(false, false, false);
}
/*
* --------------------------------------------------------------------------------
* If report type is download RTF (Rich Text Files)
* --------------------------------------------------------------------------------
*/
if ($type == 'download-rtf') {
header("Content-Disposition: attachment; filename=uea.rtf");
header("Content-Type: text/enriched\n");
$group_names = $algorithm->get_group_names();
$teams = array_keys($score_array);
foreach ($teams as $i=> $team) {
echo "\n{$team}\n";
$team_members = array_keys($score_array[$team]);
foreach ($team_members as $team_member) {
echo "\n".gettext("Results for:")." {$team_member}\n";
$questions = array_keys($score_array[$team][$team_member]);
$q_count = 0;
foreach ($questions as $question) {
$markers = array_keys($score_array[$team][$team_member][$question]);
$markers_row = '';
$scores_row = '';
foreach ($markers as $marker) {
$markers_row = $markers_row ."{$marker}\t";
$score = $score_array[$team][$team_member][$question][$marker];
$scores_row = $scores_row . "{$score}\t";
}
if ($q_count == 0) {
echo "\n\t";
echo $markers_row ."\t";
}
echo "\n{$question}\t";
echo $scores_row . "\n";
$q_count++;
}
echo "\n";
}
}
}
if ($type == 'download-csv') {
header("Content-Disposition: attachment; filename=\"uea_report_style.csv\"");
header('Content-Type: text/csv');
$group_names = $algorithm->get_group_names();
$teams = array_keys($score_array);
foreach ($teams as $i=> $team) {
echo "\n{$team}\n";
$team_members = array_keys($score_array[$team]);
foreach ($team_members as $team_member) {
echo "\n\"".gettext("Results for:")." {$team_member}\"";
$questions = array_keys($score_array[$team][$team_member]);
$q_count = 0;
foreach ($questions as $question) {
$markers = array_keys($score_array[$team][$team_member][$question]);
$markers_row = '';
$scores_row = '';
foreach ($markers as $marker) {
$markers_row .= APP__SEPARATION."\"{$marker}\"";
$score = $score_array[$team][$team_member][$question][$marker];
$scores_row = $scores_row . "\"{$score}\"".APP__SEPARATION;
}
if ($q_count == 0) {
echo "\n";
echo $markers_row;
}
echo "\n\"{$question}\"".APP__SEPARATION;
echo $scores_row;
$q_count++;
}
echo "\n";
}
}
}
?> | ICTO/WebPA-Source | tutors/assessments/reports/report_uea.php | PHP | gpl-3.0 | 9,239 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Drawing;
using System.IO;
using FeedReader;
using FeedReader.Xml.Interfaces;
namespace FeedReader.Xml
{
internal class FeedRdfImageXmlParser : IFeedTypeImageXmlParser
{
private Image _feedImage;
private string _feedImagePath = string.Empty;
public Image GetParsedImage()
{
return _feedImage;
}
public string GetImagePath()
{
return _feedImagePath;
}
public bool TryParseFeedImageUrl(XDocument xmlFeed, string cacheFolder, string feedTitle)
{
bool returnValue = false;
_feedImage = null;
_feedImagePath = string.Empty;
//1. Try
string url = FeedXmlParser.ParseString(xmlFeed.Descendants("channel").Elements("image").Attributes("resource"), "channel/image/attribute[resource]");
returnValue = DownloadAndCheckFeedImageValid(cacheFolder, url, feedTitle);
if (returnValue) return true;
LogEvents.InvokeOnDebug(new FeedArgs("No feed image could be parsed"));
return false;
}
public bool TryParseFeedItemImageUrl(XDocument xmlFeed, string cacheFolder, string feedTitle, string feedItemTitle, int itemNumber)
{
XElement item = xmlFeed.Descendants("item").ElementAt(itemNumber);
bool returnValue = false;
_feedImage = null;
_feedImagePath = string.Empty;
if (item != null)
{
//1. Try
string url = FeedXmlParser.ParseString(item.Element("item"), "about", "item[" + itemNumber + "]/attribute[about]");
if (Path.GetExtension(url) == ".gif" || Path.GetExtension(url) == ".bmp" ||
Path.GetExtension(url) == ".jpg" || Path.GetExtension(url) == ".png" ||
Path.GetExtension(url) == ".jpeg")
{
returnValue = DownloadAndCheckFeedItemImageValid(cacheFolder, url, feedTitle, feedItemTitle);
if (returnValue) return true;
}
//Last Try
LogEvents.InvokeOnDebug(new FeedArgs("Try to get feed item image out of description field..."));
string description = FeedXmlParser.ParseString(item.Element("description"), "item[" + itemNumber + "]/description");
url = Utils.GetImageOutOfDescription(Utils.ReplaceHTMLSpecialChars(description));
returnValue = DownloadAndCheckFeedItemImageValid(cacheFolder, url, feedTitle, feedItemTitle);
if (returnValue) return true;
}
LogEvents.InvokeOnDebug(new FeedArgs("No feed item image could be parsed"));
return false;
}
public bool DownloadAndCheckFeedImageValid(string cacheFolder, string url, string feedTitle)
{
if (Utils.IsValidUrl(ref url))
{
LogEvents.InvokeOnDebug(new FeedArgs("Parsed feed image \"" + url + "\" successfull. Downloading image/Load image from cache..."));
if (string.IsNullOrEmpty(cacheFolder))
{
if (Utils.LoadFeedImage(url, feedTitle, out _feedImage)) return true;
}
else
{
if (Utils.LoadFeedImage(url, feedTitle, cacheFolder, out _feedImage, out _feedImagePath)) return true;
}
}
return false;
}
public bool DownloadAndCheckFeedItemImageValid(string cacheFolder, string url, string feedTitle, string feedItemTitle)
{
if (Utils.IsValidUrl(ref url))
{
LogEvents.InvokeOnDebug(new FeedArgs("Parsed feed item image \"" + url + "\" successfull. Downloading image/Load image from cache..."));
if (string.IsNullOrEmpty(cacheFolder))
{
if (Utils.LoadFeedItemImage(url, feedTitle, feedItemTitle, out _feedImage)) return true;
}
else
{
if (Utils.LoadFeedItemImage(url, feedTitle, feedItemTitle, cacheFolder, out _feedImage, out _feedImagePath)) return true;
}
}
return false;
}
public bool TryParseFeedImageUrl(XDocument xmlFeed, string feedTitle)
{
return TryParseFeedImageUrl(xmlFeed, string.Empty, feedTitle);
}
public bool TryParseFeedItemImageUrl(XDocument xmlFeed, string feedTitle, string feedItemTitle, int itemNumber)
{
return TryParseFeedItemImageUrl(xmlFeed, string.Empty, feedTitle, feedItemTitle, itemNumber);
}
}
}
| hasenbolle/InfoService | InfoService/InfoService/Feeds/FeedReader/Xml/FeedRdfImageXmlParser.cs | C# | gpl-3.0 | 4,835 |
<?php
/**
* New Offer email
*
* @since 0.1.0
* @package public/includes/emails
* @author AngellEYE <andrew@angelleye.com>
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?>
<?php do_action( 'woocommerce_email_header', $email_heading ); ?>
<?php printf( '<p><strong>' . __('New offer submitted on', 'offers-for-woocommerce') . ' %s.</strong><br />' . __('To manage this offer please use the following link:', 'offers-for-woocommerce') . '</p> %s', get_bloginfo( 'name' ), '<a style="background:#EFEFEF; color:#161616; padding:8px 15px; margin:10px; border:1px solid #CCCCCC; text-decoration:none; " href="'. admin_url( 'post.php?post='. $offer_args['offer_id'] .'&action=edit' ) .'"><span style="border-bottom:1px dotted #666; ">' . __( 'Manage Offer', 'offers-for-woocommerce') . '</span></a>' ); ?>
<h2><?php echo __( 'Offer ID:', 'offers-for-woocommerce') . ' ' . $offer_args['offer_id']; ?> (<?php printf( '<time datetime="%s">%s</time>', date_i18n( 'c', time() ), date_i18n( wc_date_format(), time() ) ); ?>)</h2>
<table cellspacing="0" cellpadding="6" style="width: 100%; border: 1px solid #eee;" border="1" bordercolor="#eee">
<thead>
<tr>
<th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Product', 'woocommerce' ); ?></th>
<th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Quantity', 'woocommerce' ); ?></th>
<th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Price', 'woocommerce' ); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo stripslashes($offer_args['product_title_formatted']); ?></td>
<td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo number_format( $offer_args['product_qty'], 0 ); ?></td>
<td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo get_woocommerce_currency_symbol() . ' ' . number_format( $offer_args['product_price_per'], 2 ); ?></td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row" colspan="2" style="text-align:left; border: 1px solid #eee; border-top-width: 4px; "><?php _e( 'Subtotal', 'woocommerce' ); ?></th>
<td style="text-align:left; border: 1px solid #eee; border-top-width: 4px; "><?php echo get_woocommerce_currency_symbol() . ' ' . number_format( $offer_args['product_total'], 2 ); ?></td>
</tr>
</tfoot>
</table>
<h4><?php echo __('Offer Contact Details:', 'offers-for-woocommerce'); ?></h4>
<?php echo (isset($offer_args['offer_name']) && $offer_args['offer_name'] != '') ? '<strong>' . __('Name:', 'offers-for-woocommerce') . ' </strong>'.stripslashes($offer_args['offer_name']) : ''; ?>
<?php echo (isset($offer_args['offer_company_name']) && $offer_args['offer_company_name'] != '') ? '<br /><strong>' . __('Company Name:', 'offers-for-woocommerce') . ' </strong>'.stripslashes($offer_args['offer_company_name']) : ''; ?>
<?php echo (isset($offer_args['offer_email']) && $offer_args['offer_email'] != '') ? '<br /><strong>' . __('Email:', 'offers-for-woocommerce') . ' </strong>'.stripslashes($offer_args['offer_email']) : ''; ?>
<?php echo (isset($offer_args['offer_phone']) && $offer_args['offer_phone'] != '') ? '<br /><strong>' . __('Phone:', 'offers-for-woocommerce') . ' </strong>'.stripslashes($offer_args['offer_phone']) : ''; ?>
<?php if(isset($offer_args['offer_notes']) && $offer_args['offer_notes'] != '') { echo '<h4>'. __( 'Offer Notes:', 'offers-for-woocommerce' ) .'</h4>'. stripslashes($offer_args['offer_notes']); } ?>
<?php do_action( 'woocommerce_email_footer' ); ?> | wp-plugins/offers-for-woocommerce | public/includes/emails/woocommerce-new-offer.php | PHP | gpl-3.0 | 3,810 |
using System.Diagnostics;
using System.Security.Claims;
using System.Security.Principal;
namespace DotnetSpider.Portal.Common
{
/// <summary>
/// Extension methods for <see cref="System.Security.Principal.IPrincipal"/> and <see cref="System.Security.Principal.IIdentity"/> .
/// </summary>
public static class PrincipalExtensions
{
/// <summary>
/// Gets the name.
/// </summary>
/// <param name="principal">The principal.</param>
/// <returns></returns>
[DebuggerStepThrough]
public static string GetDisplayName(this ClaimsPrincipal principal)
{
var name = principal.Identity.Name;
if (!string.IsNullOrWhiteSpace(name)) return name;
var sub = principal.FindFirst("sub");
if (sub != null) return sub.Value;
return string.Empty;
}
/// <summary>
/// Determines whether this instance is authenticated.
/// </summary>
/// <param name="principal">The principal.</param>
/// <returns>
/// <c>true</c> if the specified principal is authenticated; otherwise, <c>false</c>.
/// </returns>
[DebuggerStepThrough]
public static bool IsAuthenticated(this IPrincipal principal)
{
return principal != null && principal.Identity != null && principal.Identity.IsAuthenticated;
}
}
} | zlzforever/DotnetSpider | src/DotnetSpider.Portal/Common/PrincipalExtensions.cs | C# | gpl-3.0 | 1,235 |
<p class="quote"><?php echo $quote->quoteText; ?></p>
<p class="author">-<?php echo $quote->quoteAuthor; ?></p> | Hammercake/pi-kiosk-alarm | modules/quote/view.php | PHP | gpl-3.0 | 111 |
#!/usr/bin/env python3
#
# Copyright (C) 2016 Canonical, Ltd.
# Author: Scott Sweeny <scott.sweeny@canonical.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; version 3.
#
# 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 os
class Rule:
def __init__(self, path):
# Make sure path ends in a separator to make things easier
self.path = os.path.join(path, '')
def get_file_list(self):
'''Return a list of files in the snap'''
file_list = []
for root, dirs, files in os.walk(self.path):
for f in files:
file_list.append(os.path.relpath(os.path.join(root, f),
self.path))
return file_list
def get_dir_list(self):
'''Return a list of directories in the snap'''
dir_list = []
for root, dirs, files in os.walk(self.path):
for d in dirs:
dir_list.append(os.path.relpath(os.path.join(root, d),
self.path))
return dir_list
def scan(self):
'''Override this method to implement your rule checking logic'''
pass
| ssweeny/snaplint | snaplint/_rule.py | Python | gpl-3.0 | 1,643 |
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Security;
namespace System.Threading
{
[ComVisibleAttribute(false)]
[DebuggerDisplayAttribute("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")]
public class Barrier : IDisposable
{
public int ParticipantsRemaining
{
get { throw new NotImplementedException(); }
}
public int ParticipantCount
{
get { throw new NotImplementedException(); }
}
public long CurrentPhaseNumber
{
get { throw new NotImplementedException(); }
}
public Barrier(int participantCount)
{
throw new NotImplementedException();
}
public Barrier(int participantCount, Action<Barrier> postPhaseAction)
{
throw new NotImplementedException();
}
public long AddParticipant()
{
throw new NotImplementedException();
}
public long AddParticipants(int participantCount)
{
throw new NotImplementedException();
}
public void RemoveParticipant()
{
throw new NotImplementedException();
}
public void RemoveParticipants(int participantCount)
{
throw new NotImplementedException();
}
public void SignalAndWait()
{
throw new NotImplementedException();
}
public void SignalAndWait(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public bool SignalAndWait(TimeSpan timeout)
{
throw new NotImplementedException();
}
public bool SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public bool SignalAndWait(int millisecondsTimeout)
{
throw new NotImplementedException();
}
public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
protected virtual void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
| zebraxxl/CIL2Java | StdLibs/System/System/Threading/Barrier.cs | C# | gpl-3.0 | 2,746 |
// Copyright (c) Clickberry, Inc. All rights reserved.
// Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See License.txt in the project root for license information.
define("datacontext", ["jquery"], function($) {
return function(resourceUri) {
if (!resourceUri) {
throw Error("Invalid resource uri.");
}
function getUri(uri, id) {
return id ? uri + "/" + id : uri;
}
this.post = function(requestData) {
return $.Deferred(function(deferred) {
$.ajax({
type: 'POST',
url: getUri(resourceUri),
data: requestData,
error: function(responseData) {
deferred.reject(responseData);
},
success: function(responseData) {
deferred.resolve(responseData);
}
});
}).promise();
};
this.get = function(id) {
return $.Deferred(function(deferred) {
$.ajax({
url: getUri(resourceUri, id),
dataType: 'json',
error: function(responseData) {
deferred.reject(responseData);
},
success: function(responseData) {
deferred.resolve(responseData);
}
});
}).promise();
};
this.put = function(id, requestData) {
return $.Deferred(function(deferred) {
$.ajax({
type: 'POST',
url: getUri(resourceUri, id),
data: requestData,
headers: { 'X-HTTP-Method-Override': "PUT" },
error: function(responseData) {
deferred.reject(responseData);
},
success: function(responseData) {
deferred.resolve(responseData);
}
});
}).promise();
};
this.remove = function(id, requestData) {
return $.Deferred(function(deferred) {
$.ajax({
type: 'POST',
url: getUri(resourceUri, id),
data: requestData,
headers: { 'X-HTTP-Method-Override': "DELETE" },
error: function(responseData) {
deferred.reject(responseData);
},
success: function(responseData) {
deferred.resolve(responseData);
}
});
}).promise();
};
};
}); | clickberry/video-portal | Source/FrontEnd/Portal.Web/Cdn/js/spa/datacontext.js | JavaScript | gpl-3.0 | 2,802 |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2012-2015 Marco Craveiro <marco.craveiro@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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include <string>
#include <ostream>
#include <stdexcept>
#include "masd.dogen.extraction/io/editors_io.hpp"
namespace masd::dogen::extraction {
std::ostream& operator<<(std::ostream& s, const editors& v) {
s << "{ " << "\"__type__\": " << "\"editors\", " << "\"value\": ";
std::string attr;
switch (v) {
case editors::invalid:
attr = "\"invalid\"";
break;
case editors::emacs:
attr = "\"emacs\"";
break;
case editors::vi:
attr = "\"vi\"";
break;
case editors::vim:
attr = "\"vim\"";
break;
case editors::ex:
attr = "\"ex\"";
break;
default:
throw std::invalid_argument("Invalid value for editors");
}
s << attr << " }";
return s;
}
}
| DomainDrivenConsulting/dogen | projects/masd.dogen.extraction/src/io/editors_io.cpp | C++ | gpl-3.0 | 1,654 |
<?php
/**
* Kunena Component
* @package Kunena.Template.Crypsis
* @subpackage Layout.User
*
* @copyright (C) 2008 - 2015 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined('_JEXEC') or die;
?>
<h2>
<?php echo JText::_('COM_KUNENA_USER_PROFILE'); ?> <?php echo $this->escape($this->profile->getName()); ?>
<?php echo $this->profile->getLink(
'<i class="glyphicon glyphicon-arrow-left"></i> ' . JText::_('COM_KUNENA_BACK'),
JText::_('COM_KUNENA_BACK'), 'nofollow', '', 'btn pull-right'
); ?>
</h2>
<form action="<?php echo KunenaRoute::_('index.php?option=com_kunena&view=user'); ?>" method="post" enctype="multipart/form-data" name="kuserform" class="form-validate" id="kuserform">
<input type="hidden" name="task" value="save" />
<input type="hidden" name="userid" value="<?php echo (int) $this->user->id; ?>" />
<?php echo JHtml::_('form.token'); ?>
<div class="tabs">
<ul id="KunenaUserEdit" class="nav nav-tabs">
<li class="active">
<a href="#home" data-toggle="tab">
<?php echo JText::_('COM_KUNENA_PROFILE_EDIT_USER'); ?>
</a>
</li>
<li>
<a href="#editprofile" data-toggle="tab">
<?php echo JText::_('COM_KUNENA_PROFILE_EDIT_PROFILE'); ?>
</a>
</li>
<li>
<a href="#editavatar" data-toggle="tab">
<?php echo JText::_('COM_KUNENA_PROFILE_EDIT_AVATAR'); ?>
</a>
</li>
<li>
<a href="#editsettings" data-toggle="tab">
<?php echo JText::_('COM_KUNENA_PROFILE_EDIT_SETTINGS'); ?>
</a>
</li>
</ul>
<div id="KunenaUserEdit" class="tab-content">
<div class="tab-pane fade in active" id="home">
<?php echo $this->subRequest('User/Edit/User'); ?>
</div>
<div class="tab-pane fade" id="editprofile">
<?php echo $this->subRequest('User/Edit/Profile'); ?>
</div>
<div class="tab-pane fade" id="editavatar">
<?php echo $this->subRequest('User/Edit/Avatar'); ?>
</div>
<div class="tab-pane fade" id="editsettings">
<?php echo $this->subRequest('User/Edit/Settings'); ?>
</div>
<br />
<div class="center">
<button class="btn btn-primary validate" type="submit">
<?php echo JText::_('COM_KUNENA_SAVE'); ?>
</button>
<input type="button" name="cancel" class="btn"
value="<?php echo (' ' . JText::_('COM_KUNENA_CANCEL') . ' '); ?>"
onclick="window.history.back();"
title="<?php echo (JText::_('COM_KUNENA_EDITOR_HELPLINE_CANCEL')); ?>" />
</div>
</div>
</div>
</form>
| OSTraining/Kunena-Forum | components/com_kunena/site/template/crypsisb3/layouts/user/edit/default.php | PHP | gpl-3.0 | 2,560 |
#pragma once
/* This file is part of Imagine.
Imagine 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.
Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */
#include <type_traits>
#include <imagine/io/IO.hh>
#include <imagine/io/PosixFileIO.hh>
using FileIO = PosixFileIO;
#ifdef __ANDROID__
#include <imagine/io/AAssetIO.hh>
using AssetIO = AAssetIO;
#else
using AssetIO = FileIO;
#endif
namespace FileUtils
{
AssetIO openAppAsset(const char *name, IO::AccessHint access, const char *appName);
ssize_t writeToPath(const char *path, void *data, size_t size, std::error_code *ecOut = nullptr);
ssize_t writeToPath(const char *path, IO &io, std::error_code *ecOut = nullptr);
ssize_t readFromPath(const char *path, void *data, size_t size);
}
| DarkCaster/emu-ex-plus-alpha | imagine/include/imagine/io/FileIO.hh | C++ | gpl-3.0 | 1,248 |
ModX Revolution 2.5.0 = 539f52dd202abe6bff3cf711e1c09993
MODX Revolution 2.2.8 = 93c2ffd8a497f42474f7b4a3e49503ca
| gohdan/DFC | known_files/hashes/core/lexicon/de/filters.inc.php | PHP | gpl-3.0 | 114 |
/*
* Copyright (C) 2016 Daniel Saukel
*
* 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 io.github.dre2n.factionscosmetics.listener;
import io.github.dre2n.factionscosmetics.FactionsCosmetics;
import io.github.dre2n.factionsone.api.event.FactionsReloadEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
/**
* @author Daniel Saukel
*/
public class FactionsListener implements Listener {
protected static FactionsCosmetics plugin = FactionsCosmetics.getInstance();
@EventHandler
public void onReload(FactionsReloadEvent event) {
plugin.loadFCConfig(plugin.getFCConfig().getFile());
}
}
| DRE2N/FactionsCosmetics | src/main/java/io/github/dre2n/factionscosmetics/listener/FactionsListener.java | Java | gpl-3.0 | 1,254 |
#include <iostream>
#include <Eigen/Dense>
#include "gtest/gtest.h"
#include "observability.h"
TEST(ObservabilityTest, Simple)
{
Eigen::MatrixXd A(2, 2);
Eigen::MatrixXd C(2, 2);
A << 1, 1, 4, -2;
C << 1, 0, 0, 1;
Eigen::MatrixXd O = control::observability_matrix(A, C);
Eigen::MatrixXd O_expected(4, 2);
O_expected << 1, 0,
0, 1,
1, 1,
4, -2; // From Matlab.
EXPECT_EQ(O, O_expected) << "Observability matrix differs: " << O_expected
<< std::endl << O << std::endl;
}
| hazelnusse/libcontrol | source/tests/test_observability.cc | C++ | gpl-3.0 | 541 |
package org.halvors.nuclearphysics.common.event.handler;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.item.ItemExpireEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.halvors.nuclearphysics.common.ConfigurationManager.General;
import org.halvors.nuclearphysics.common.effect.explosion.AntimatterExplosion;
import org.halvors.nuclearphysics.common.init.ModItems;
@EventBusSubscriber
public class ItemEventHandler {
@SubscribeEvent
public static void onItemExpireEvent(final ItemExpireEvent event) {
if (General.enableAntimatterPower) {
final EntityItem entityItem = event.getEntityItem();
if (entityItem != null) {
final ItemStack itemStack = entityItem.getEntityItem();
if (itemStack.getItem() == ModItems.itemAntimatterCell) {
final AntimatterExplosion explosion = new AntimatterExplosion(entityItem.getEntityWorld(), entityItem, entityItem.getPosition(), 4, itemStack.getMetadata());
explosion.explode();
}
}
}
}
}
| halvors/Nuclear-Physics | src/main/java/org/halvors/nuclearphysics/common/event/handler/ItemEventHandler.java | Java | gpl-3.0 | 1,244 |
package com.jeewd.web_store.security;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class User implements UserDetails {
private static final long serialVersionUID = -3849758589040177326L;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private boolean enabled;
private String username;
private String password;
private Collection<GrantedAuthority> authorities;
public User(String username, String password,
Collection<GrantedAuthority> authorities) {
this.enabled = true;
this.accountNonExpired = true;
this.credentialsNonExpired = true;
this.accountNonLocked = true;
this.username = username;
this.password = password;
this.authorities = authorities;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setAuthorities(Collection<GrantedAuthority> authorities) {
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
| slavidlancer/JavaEEWebDevelopment | 11_CourseProject_Java_Web_Development/CourseProjectWebStore/src/main/java/com/jeewd/web_store/security/User.java | Java | gpl-3.0 | 2,377 |
# -*- coding: utf-8 -*-
import numpy as np
import config
from feature.feature_multi import FeatureMulti
from similarity.similarity_base import SimiliarityBase
class SimilarityStyle(SimiliarityBase):
def calculate(self, image1, image2):
# 获取特征
multi_feature_extractor = FeatureMulti()
luminance_sample_p, mu_p, sigma_p = multi_feature_extractor.extract(image1)
luminance_sample_s, mu_s, sigma_s = multi_feature_extractor.extract(image2)
# 实际相似度计算
return self.__class__.calculate_inner(luminance_sample_p, luminance_sample_s, mu_p, mu_s, sigma_p, sigma_s)
@classmethod
def calculate_inner(cls, luminance_sample_p, luminance_sample_s, mu_p, mu_s, sigma_p, sigma_s):
# 参数
lambda_l = config.style_ranking['lambda_l']
lambda_c = config.style_ranking['lambda_c']
epsilon = config.style_ranking['epsilon']
# 求亮度之间的欧式距离
de = np.power(np.linalg.norm(luminance_sample_p - luminance_sample_s, 2), 2)
# 求色彩之间的距离
mu = np.matrix(np.abs(mu_p - mu_s) + epsilon).T
sigma = np.matrix((sigma_p + sigma_s) / 2)
dh_1 = np.power(np.linalg.norm(sigma_s.dot(sigma_p), 1), 1 / 4) / (np.power(np.linalg.norm(sigma, 1), 1 / 2))
dh_2 = (-1 / 8) * mu.T * np.linalg.inv(sigma) * mu
dh = 1 - dh_1 * np.exp(dh_2)
ans = np.exp(-de / lambda_l) * np.exp(-np.power(dh, 2) / lambda_c)
# 因为ans是一个 1x1 Matrix,所以必须弄成一个值
return np.max(ans)
| jinyu121/ACACTS | similarity/similarity_style.py | Python | gpl-3.0 | 1,581 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2018, SCISYS UK Limited
*
* 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.sldeditor.test.unit.tool.batchupdatefont;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import com.sldeditor.common.LoadSLDInterface;
import com.sldeditor.common.SLDDataInterface;
import com.sldeditor.common.SLDEditorInterface;
import com.sldeditor.common.data.SLDUtils;
import com.sldeditor.test.unit.datasource.impl.DummyInternalSLDFile3;
import com.sldeditor.tool.batchupdatefont.BatchUpdateFontPanel;
import java.awt.GraphicsEnvironment;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.styling.Font;
import org.geotools.styling.NamedLayer;
import org.geotools.styling.StyleFactoryImpl;
import org.geotools.styling.StyledLayerDescriptor;
import org.geotools.styling.TextSymbolizer;
import org.junit.jupiter.api.Test;
import org.opengis.filter.FilterFactory;
/**
* The unit test for BatchUpdateFontData.
*
* <p>{@link com.sldeditor.tool.batchupdatefont.BatchUpdateFontPanel}
*
* @author Robert Ward (SCISYS)
*/
class BatchUpdateFontPanelTest {
class TestBatchUpdateFontPanel extends BatchUpdateFontPanel {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new test batch update font panel.
*
* @param application the application
*/
public TestBatchUpdateFontPanel(SLDEditorInterface application) {
super(application);
}
public void testApplyData() {
applyData();
}
/** Save data. */
public void testSaveData() {
saveData();
}
/**
* Sets the selected option to update font, used for testing.
*
* @param font the new update font
*/
public void setUpdateFont(Font font) {
super.setUpdateFont(font);
}
/**
* Sets the selected option to update font size, used for testing.
*
* @param font the new update font size
*/
public void setUpdateFontSize(Font font) {
super.setUpdateFontSize(font);
}
}
class TestSLDEditorInterface implements SLDEditorInterface {
public SLDDataInterface savedSldData = null;
public Class<?> savedParent = null;
public Class<?> savedPanelClass = null;
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#getAppPanel()
*/
@Override
public JPanel getAppPanel() {
return null;
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#updateWindowTitle(boolean)
*/
@Override
public void updateWindowTitle(boolean dataEditedFlag) {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#chooseNewSLD()
*/
@Override
public void chooseNewSLD() {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#exitApplication()
*/
@Override
public void exitApplication() {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#saveFile(java.net.URL)
*/
@Override
public void saveFile(URL url) {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#saveSLDData(com.sldeditor.common.
* SLDDataInterface)
*/
@Override
public void saveSLDData(SLDDataInterface sldData) {
savedSldData = sldData;
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#getLoadSLDInterface()
*/
@Override
public LoadSLDInterface getLoadSLDInterface() {
return null;
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#openFile(java.net.URL)
*/
@Override
public void openFile(URL selectedURL) {}
/*
* (non-Javadoc)
*
* @see com.sldeditor.common.SLDEditorInterface#refreshPanel(java.lang.Class,
* java.lang.Class)
*/
@Override
public void refreshPanel(Class<?> parent, Class<?> panelClass) {
savedParent = parent;
savedPanelClass = panelClass;
}
}
/**
* Test method for {@link
* com.sldeditor.tool.batchupdatefont.BatchUpdateFontPanel#populate(java.util.List)}.
*/
@Test
void testPopulateUpdateFontSize() {
TestSLDEditorInterface app = new TestSLDEditorInterface();
TestBatchUpdateFontPanel testObj = new TestBatchUpdateFontPanel(app);
List<SLDDataInterface> sldDataList = new ArrayList<SLDDataInterface>();
DummyInternalSLDFile3 dummy = new DummyInternalSLDFile3();
sldDataList.add(dummy.getSLDData());
Double originalFontSize = getFontSize(dummy.getSLDData());
testObj.populate(sldDataList);
testObj.testSaveData();
assertNull(app.savedParent);
Double expectedFontSizeIncrease = 24.0;
StyleFactoryImpl styleFactory = (StyleFactoryImpl) CommonFactoryFinder.getStyleFactory();
FilterFactory ff = CommonFactoryFinder.getFilterFactory();
String originalFontname = "Serif";
String originalFontStyle = "normal";
String originalFontWeight = "normal";
Font expectedFont =
styleFactory.createFont(
ff.literal(originalFontname),
ff.literal(originalFontStyle),
ff.literal(originalFontWeight),
ff.literal(expectedFontSizeIncrease));
testObj.setUpdateFontSize(expectedFont);
testObj.testApplyData();
testObj.testSaveData();
Double actualFontSize = getFontSize(app.savedSldData);
Double expectedFontSize = originalFontSize + expectedFontSizeIncrease;
assertEquals(actualFontSize.doubleValue(), expectedFontSize.doubleValue());
}
/**
* Test method for {@link
* com.sldeditor.tool.batchupdatefont.BatchUpdateFontPanel#populate(java.util.List)}.
*/
@Test
void testPopulateUpdateFontData() {
TestSLDEditorInterface app = new TestSLDEditorInterface();
TestBatchUpdateFontPanel testObj = new TestBatchUpdateFontPanel(app);
List<SLDDataInterface> sldDataList = new ArrayList<SLDDataInterface>();
DummyInternalSLDFile3 dummy = new DummyInternalSLDFile3();
sldDataList.add(dummy.getSLDData());
testObj.populate(sldDataList);
testObj.testSaveData();
assertNull(app.savedParent);
Double expectedFontSizeIncrease = 24.0;
StyleFactoryImpl styleFactory = (StyleFactoryImpl) CommonFactoryFinder.getStyleFactory();
FilterFactory ff = CommonFactoryFinder.getFilterFactory();
String[] families =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
String originalFontname = families[0];
String originalFontStyle = "normal";
String originalFontWeight = "normal";
Font expectedFont =
styleFactory.createFont(
ff.literal(originalFontname),
ff.literal(originalFontStyle),
ff.literal(originalFontWeight),
ff.literal(expectedFontSizeIncrease));
testObj.setUpdateFont(expectedFont);
testObj.testApplyData();
testObj.testSaveData();
assertEquals(originalFontname, getFontName(app.savedSldData));
}
private Double getFontSize(SLDDataInterface sldData) {
StyledLayerDescriptor sld = SLDUtils.createSLDFromString(sldData);
NamedLayer namedLayer = (NamedLayer) sld.layers().get(0);
TextSymbolizer text =
(TextSymbolizer)
namedLayer
.styles()
.get(0)
.featureTypeStyles()
.get(0)
.rules()
.get(0)
.symbolizers()
.get(2);
return Double.valueOf(text.getFont().getSize().toString());
}
private String getFontName(SLDDataInterface sldData) {
StyledLayerDescriptor sld = SLDUtils.createSLDFromString(sldData);
NamedLayer namedLayer = (NamedLayer) sld.layers().get(0);
TextSymbolizer text =
(TextSymbolizer)
namedLayer
.styles()
.get(0)
.featureTypeStyles()
.get(0)
.rules()
.get(0)
.symbolizers()
.get(2);
return text.getFont().getFamily().get(0).toString();
}
}
| robward-scisys/sldeditor | modules/application/src/test/java/com/sldeditor/test/unit/tool/batchupdatefont/BatchUpdateFontPanelTest.java | Java | gpl-3.0 | 10,111 |
// *****************************************************************************
// randpool.cpp Tao3D project
// *****************************************************************************
//
// File description:
//
//
//
//
//
//
//
//
// *****************************************************************************
// This software is licensed under the GNU General Public License v3
// (C) 2019, Christophe de Dinechin <christophe@dinechin.org>
// (C) 2011, Jérôme Forissier <jerome@taodyne.com>
// *****************************************************************************
// This file is part of Tao3D
//
// Tao3D is free software: you can r 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.
//
// Tao3D 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 Tao3D, in a file named COPYING.
// If not, see <https://www.gnu.org/licenses/>.
// *****************************************************************************
// randpool.cpp - written and placed in the public domain by Wei Dai
// RandomPool used to follow the design of randpool in PGP 2.6.x,
// but as of version 5.5 it has been redesigned to reduce the risk
// of reusing random numbers after state rollback (which may occur
// when running in a virtual machine like VMware).
#include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "randpool.h"
#include "aes.h"
#include "sha.h"
#include "hrtimer.h"
#include <time.h>
NAMESPACE_BEGIN(CryptoPP)
RandomPool::RandomPool()
: m_pCipher(new AES::Encryption), m_keySet(false)
{
memset(m_key, 0, m_key.SizeInBytes());
memset(m_seed, 0, m_seed.SizeInBytes());
}
void RandomPool::IncorporateEntropy(const byte *input, size_t length)
{
SHA256 hash;
hash.Update(m_key, 32);
hash.Update(input, length);
hash.Final(m_key);
m_keySet = false;
}
void RandomPool::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword size)
{
if (size > 0)
{
if (!m_keySet)
m_pCipher->SetKey(m_key, 32);
Timer timer;
TimerWord tw = timer.GetCurrentTimerValue();
CRYPTOPP_COMPILE_ASSERT(sizeof(tw) <= 16);
*(TimerWord *)m_seed.data() += tw;
time_t t = time(NULL);
CRYPTOPP_COMPILE_ASSERT(sizeof(t) <= 8);
*(time_t *)(m_seed.data()+8) += t;
do
{
m_pCipher->ProcessBlock(m_seed);
size_t len = UnsignedMin(16, size);
target.ChannelPut(channel, m_seed, len);
size -= len;
} while (size > 0);
}
}
NAMESPACE_END
#endif
| c3d/tao-3D | libcryptopp/cryptopp/randpool.cpp | C++ | gpl-3.0 | 2,879 |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2010,2012 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <limits>
#include <Eigen/Eigenvalues>
template<typename MatrixType> void eigensolver(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
/* this test covers the following files:
EigenSolver.h
*/
Index rows = m.rows();
Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType;
typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex;
MatrixType a = MatrixType::Random(rows,cols);
MatrixType a1 = MatrixType::Random(rows,cols);
MatrixType symmA = a.adjoint() * a + a1.adjoint() * a1;
EigenSolver<MatrixType> ei0(symmA);
VERIFY_IS_EQUAL(ei0.info(), Success);
VERIFY_IS_APPROX(symmA * ei0.pseudoEigenvectors(), ei0.pseudoEigenvectors() * ei0.pseudoEigenvalueMatrix());
VERIFY_IS_APPROX((symmA.template cast<Complex>()) * (ei0.pseudoEigenvectors().template cast<Complex>()),
(ei0.pseudoEigenvectors().template cast<Complex>()) * (ei0.eigenvalues().asDiagonal()));
EigenSolver<MatrixType> ei1(a);
VERIFY_IS_EQUAL(ei1.info(), Success);
VERIFY_IS_APPROX(a * ei1.pseudoEigenvectors(), ei1.pseudoEigenvectors() * ei1.pseudoEigenvalueMatrix());
VERIFY_IS_APPROX(a.template cast<Complex>() * ei1.eigenvectors(),
ei1.eigenvectors() * ei1.eigenvalues().asDiagonal());
VERIFY_IS_APPROX(ei1.eigenvectors().colwise().norm(), RealVectorType::Ones(rows).transpose());
VERIFY_IS_APPROX(a.eigenvalues(), ei1.eigenvalues());
EigenSolver<MatrixType> ei2;
ei2.setMaxIterations(RealSchur<MatrixType>::m_maxIterationsPerRow * rows).compute(a);
VERIFY_IS_EQUAL(ei2.info(), Success);
VERIFY_IS_EQUAL(ei2.eigenvectors(), ei1.eigenvectors());
VERIFY_IS_EQUAL(ei2.eigenvalues(), ei1.eigenvalues());
if (rows > 2) {
ei2.setMaxIterations(1).compute(a);
VERIFY_IS_EQUAL(ei2.info(), NoConvergence);
VERIFY_IS_EQUAL(ei2.getMaxIterations(), 1);
}
EigenSolver<MatrixType> eiNoEivecs(a, false);
VERIFY_IS_EQUAL(eiNoEivecs.info(), Success);
VERIFY_IS_APPROX(ei1.eigenvalues(), eiNoEivecs.eigenvalues());
VERIFY_IS_APPROX(ei1.pseudoEigenvalueMatrix(), eiNoEivecs.pseudoEigenvalueMatrix());
MatrixType id = MatrixType::Identity(rows, cols);
VERIFY_IS_APPROX(id.operatorNorm(), RealScalar(1));
if (rows > 2)
{
// Test matrix with NaN
a(0,0) = std::numeric_limits<typename MatrixType::RealScalar>::quiet_NaN();
EigenSolver<MatrixType> eiNaN(a);
VERIFY_IS_EQUAL(eiNaN.info(), NoConvergence);
}
}
template<typename MatrixType> void eigensolver_verify_assert(const MatrixType& m)
{
EigenSolver<MatrixType> eig;
VERIFY_RAISES_ASSERT(eig.eigenvectors());
VERIFY_RAISES_ASSERT(eig.pseudoEigenvectors());
VERIFY_RAISES_ASSERT(eig.pseudoEigenvalueMatrix());
VERIFY_RAISES_ASSERT(eig.eigenvalues());
MatrixType a = MatrixType::Random(m.rows(),m.cols());
eig.compute(a, false);
VERIFY_RAISES_ASSERT(eig.eigenvectors());
VERIFY_RAISES_ASSERT(eig.pseudoEigenvectors());
}
void test_eigensolver_generic()
{
int s;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( eigensolver(Matrix4f()) );
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
CALL_SUBTEST_2( eigensolver(MatrixXd(s,s)) );
// some trivial but implementation-wise tricky cases
CALL_SUBTEST_2( eigensolver(MatrixXd(1,1)) );
CALL_SUBTEST_2( eigensolver(MatrixXd(2,2)) );
CALL_SUBTEST_3( eigensolver(Matrix<double,1,1>()) );
CALL_SUBTEST_4( eigensolver(Matrix2d()) );
}
CALL_SUBTEST_1( eigensolver_verify_assert(Matrix4f()) );
s = internal::random<int>(1,EIGEN_TEST_MAX_SIZE/4);
CALL_SUBTEST_2( eigensolver_verify_assert(MatrixXd(s,s)) );
CALL_SUBTEST_3( eigensolver_verify_assert(Matrix<double,1,1>()) );
CALL_SUBTEST_4( eigensolver_verify_assert(Matrix2d()) );
// Test problem size constructors
CALL_SUBTEST_5(EigenSolver<MatrixXf>(s));
// regression test for bug 410
CALL_SUBTEST_2(
{
MatrixXd A(1,1);
A(0,0) = std::sqrt(-1.);
Eigen::EigenSolver<MatrixXd> solver(A);
MatrixXd V(1, 1);
V(0,0) = solver.eigenvectors()(0,0).real();
}
);
EIGEN_UNUSED_VARIABLE(s)
}
| anders-dc/cppfem | eigen/test/eigensolver_generic.cpp | C++ | gpl-3.0 | 4,745 |
#!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Galaxy Harvester 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
import dbSession
import pymysql
import cgi
from http import cookies
import ghShared
import ghLists
import dbShared
#
form = cgi.FieldStorage()
C = cookies.SimpleCookie()
errorstr = ''
try:
C.load(os.environ['HTTP_COOKIE'])
except KeyError:
errorstr = 'no cookies\n'
if errorstr == '':
try:
currentUser = C['userID'].value
except KeyError:
currentUser = ''
try:
sid = C['gh_sid'].value
except KeyError:
sid = form.getfirst('gh_sid', '')
else:
currentUser = ''
sid = form.getfirst('gh_sid', '')
# Get a session
logged_state = 0
sess = dbSession.getSession(sid)
if (sess != ''):
logged_state = 1
currentUser = sess
groupType = form.getfirst('groupType', '')
profession = form.getfirst('profession', '')
craftingTab = form.getfirst('craftingTab', '')
resType = form.getfirst('resType', '')
resSecondary = form.getfirst('resSecondary', '')
resGroup = form.getfirst('resGroup', '')
selectSchematic = form.getfirst('selectSchematic', '')
listFormat = form.getfirst('listFormat', 'list')
galaxy = form.getfirst('galaxy', '')
# escape input to prevent sql injection
groupType = dbShared.dbInsertSafe(groupType)
profession = dbShared.dbInsertSafe(profession)
craftingTab = dbShared.dbInsertSafe(craftingTab)
resType = dbShared.dbInsertSafe(resType)
resSecondary = dbShared.dbInsertSafe(resSecondary)
resGroup = dbShared.dbInsertSafe(resGroup)
selectSchematic = dbShared.dbInsertSafe(selectSchematic)
listFormat = dbShared.dbInsertSafe(listFormat)
# groupType determines the filtering method for narrowing down schematic list
filterStr = ''
joinStr = ''
if (groupType == 'prof'):
if (profession.isdigit()):
filterStr = ' WHERE tSkillGroup.profID = ' + str(profession)
elif (groupType == 'tab'):
if (craftingTab.isdigit()):
filterStr = ' WHERE tSchematic.craftingTab = ' + str(craftingTab)
elif (groupType == 'res'):
if (resGroup != '' and resGroup != None):
if resSecondary == '1':
joinStr = ' INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="' + resGroup + '") rtg ON ingredientObject = rtg.resourceType'
else:
filterStr = ' WHERE ingredientObject = "' + resGroup + '"'
else:
if resSecondary == '1':
filterStr = ' WHERE ingredientObject IN (SELECT tResourceTypeGroup.resourceGroup FROM tResourceTypeGroup INNER JOIN tResourceGroup ON tResourceTypeGroup.resourceGroup=tResourceGroup.resourceGroup WHERE resourceType="' + resType + '" AND groupLevel=(SELECT Max(rg.groupLevel) FROM tResourceTypeGroup rtg INNER JOIN tResourceGroup rg ON rtg.resourceGroup = rg.resourceGroup WHERE rtg.resourceType="' + resType + '") GROUP BY tResourceTypeGroup.resourceGroup)'
joinStr = ' INNER JOIN (SELECT tResourceTypeGroup.resourceGroup FROM tResourceTypeGroup INNER JOIN tResourceGroup ON tResourceTypeGroup.resourceGroup=tResourceGroup.resourceGroup WHERE resourceType="' + resType + '" AND groupLevel=(SELECT Max(rg.groupLevel) FROM tResourceTypeGroup rtg INNER JOIN tResourceGroup rg ON rtg.resourceGroup = rg.resourceGroup WHERE rtg.resourceType="' + resType + '") GROUP BY tResourceTypeGroup.resourceGroup) rtgg ON ingredientObject = rtgg.resourceGroup'
else:
filterStr = ' WHERE ingredientObject = "' + resType + '"'
elif (groupType == 'favorite'):
filterStr = ' WHERE tFavorites.userID = "' + currentUser + '" AND favType = 4'
joinStr = ' INNER JOIN tFavorites ON tSchematic.schematicID = tFavorites.favGroup'
conn = dbShared.ghConn()
# Some schematics are custom entered per galaxy but those with galaxyID 0 are for all
if galaxy.isdigit():
baseProfs = '0, 1337'
checkCursor = conn.cursor()
if (checkCursor):
checkCursor.execute('SELECT galaxyNGE FROM tGalaxy WHERE galaxyID={0};'.format(str(galaxy)))
checkRow = checkCursor.fetchone()
if (checkRow != None) and (checkRow[0] > 0):
baseProfs = '-1, 1337'
checkCursor.close()
filterStr = filterStr + ' AND tSchematic.galaxy IN ({1}, {0}) AND tSchematic.schematicID NOT IN (SELECT schematicID FROM tSchematicOverrides WHERE galaxyID={0})'.format(galaxy, baseProfs)
# We output an unordered list or a bunch of select element options depending on listFormat
currentGroup = ''
currentIngredient = ''
print('Content-type: text/html\n')
if listFormat != 'option':
print(' <ul class="schematics">')
cursor = conn.cursor()
if (cursor):
if (groupType == 'tab' or groupType == 'favorite'):
sqlStr1 = 'SELECT schematicID, tSchematic.craftingTab, typeName, schematicName FROM tSchematic INNER JOIN tObjectType ON tSchematic.objectType = tObjectType.objectType' + joinStr + filterStr + ' ORDER BY craftingTab, typeName, schematicName'
elif (groupType == 'res'):
sqlStr1 = 'SELECT DISTINCT tSchematic.schematicID, tSchematic.craftingTab, typeName, schematicName, ingredientObject, res.resName FROM tSchematic INNER JOIN tObjectType ON tSchematic.objectType = tObjectType.objectType INNER JOIN tSchematicIngredients ON tSchematic.schematicID = tSchematicIngredients.schematicID' + joinStr + ' LEFT JOIN (SELECT resourceGroup AS resID, groupName AS resName FROM tResourceGroup UNION ALL SELECT resourceType, resourceTypeName FROM tResourceType) res ON ingredientObject = res.resID' + filterStr + ' ORDER BY res.resName, craftingTab, typeName, schematicName'
else:
sqlStr1 = 'SELECT schematicID, profName, skillGroupName, schematicName FROM tSchematic INNER JOIN tSkillGroup ON tSchematic.skillGroup = tSkillGroup.skillGroup LEFT JOIN tProfession ON tSkillGroup.profID = tProfession.profID' + joinStr + filterStr
if listFormat == 'option':
sqlStr1 += ' ORDER BY schematicName'
else:
sqlStr1 += ' ORDER BY profName, skillGroupName, schematicName'
cursor.execute(sqlStr1)
row = cursor.fetchone()
if (row == None):
print(' <li><h3>No Schematics Found</h3></li>')
while (row != None):
if listFormat == 'option':
print('<option value="' + row[0] + '">' + row[3] + '</option>')
else:
if (groupType == 'res'):
if (currentIngredient != row[5]):
print(' </ul>')
print(' <div style="margin-top:14px;"><a class="bigLink" href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + str(row[4]) + '">' + str(row[5]) + '</a></div>')
print(' <ul class="schematics">')
currentIngredient = row[5]
currentGroup = ''
if (currentGroup != row[2]):
print(' <li><h3>' + row[2] + '</h3></li>')
currentGroup = row[2]
if row[0] == selectSchematic:
print(' <li class="listSelected"><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[0] + '">' + row[3] + '</a></li>')
else:
print(' <li><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[0] + '">' + row[3] + '</a></li>')
row = cursor.fetchone()
cursor.close()
conn.close()
if listFormat != 'option':
print(' </ul>')
| pwillworth/galaxyharvester | html/getSchematicList.py | Python | gpl-3.0 | 7,494 |
#include "mounter.h"
#include "manager.h"
#include <iostream>
#include <QStringList>
#include <QDir>
#include <QDebug>
#include <QQueue>
class MounterItem
{
public:
MounterItem( const QString & f , const QString & m )
{ file = f ; mount_point = m; }
QString file;
QString mount_point;
};
class MounterPrivate
{
public:
QProcess *process;
QString command;
QQueue<MounterItem> queue;
};
Mounter::Mounter(QObject *parent) :
QObject(parent)
{
p = new MounterPrivate;
p->process = new QProcess( this );
p->command = "mount";
connect( p->process , SIGNAL(finished(int,QProcess::ExitStatus)) , SLOT(finished(int,QProcess::ExitStatus)) , Qt::QueuedConnection );
}
void Mounter::mount( const QString & file , const QString & mount_point )
{
p->queue.enqueue( MounterItem( file , mount_point ) );
if( p->queue.count() == 1 )
mount_prev( file , mount_point );
Manager::increase();
}
void Mounter::mount_prev( const QString & file , const QString & mount_point )
{
QDir dir( mount_point );
dir.mkpath( mount_point );
QStringList arguments;
arguments << "-o";
arguments << "loop";
arguments << file;
arguments << mount_point;
p->process->start( p->command , arguments );
}
void Mounter::finished( int exit_code , QProcess::ExitStatus state )
{
p->queue.dequeue();
if( !p->queue.isEmpty() )
{
const MounterItem & item = p->queue.dequeue();
mount_prev( item.file , item.mount_point );
}
if( state == QProcess::CrashExit )
{
qDebug() << "The mount process has unexpectedly finished.";
Manager::decrease();
return;
}
if( exit_code == 0 )
{
Manager::decrease();
return;
}
if( exit_code & 1 ) qDebug() << "Incorrect invocation or permissions.";
if( exit_code & 2 ) qDebug() << "System error (out of memory, cannot fork, no more loop devices).";
if( exit_code & 4 ) qDebug() << "Internal mount bug.";
if( exit_code & 8 ) qDebug() << "User interrupt.";
if( exit_code & 16 ) qDebug() << "Problems writing or locking /etc/mtab .";
if( exit_code & 32 ) qDebug() << "Mount failure.";
if( exit_code & 64 ) qDebug() << "Some mount succeeded.";
Manager::decrease();
}
Mounter::~Mounter()
{
delete p;
}
| realbardia/silicon | SPlugins/RootMount/Binary/mounter.cpp | C++ | gpl-3.0 | 2,378 |
/*---------------------------------------------------------------------------*\
* interactive networked Virtual Reality system (inVRs) *
* *
* Copyright (C) 2005-2009 by the Johannes Kepler University, Linz *
* *
* www.inVRs.org *
* *
* contact: canthes@inVRs.org, rlander@inVRs.org *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
\*---------------------------------------------------------------------------*/
#include "AllInOneTranslationModel.h"
#include <inVRs/SystemCore/ArgumentVector.h>
#include <inVRs/SystemCore/DebugOutput.h>
AllInOneTranslationModel::AllInOneTranslationModel(unsigned upDownIdx, unsigned speedIdx, float forBackSpeed, float upDownSpeed)
{
this->upDownIdx = upDownIdx;
this->speedIdx = speedIdx;
this->upDownSpeed = upDownSpeed;
this->forBackSpeed = forBackSpeed;
}
void AllInOneTranslationModel::getTranslation(ControllerInterface* controller, const gmtl::Quatf& rotationChange, gmtl::Vec3f& result, float dt)
{
gmtl::Vec3f temp;
gmtl::Vec3f frontBackDir = gmtl::Vec3f(0, 0, 1);
gmtl::Vec3f upDownDir = gmtl::Vec3f(0, 1, 0);
result = gmtl::Vec3f(0, 0, 0);
if(controller->getNumberOfAxes() <= (int)speedIdx) return;
result += frontBackDir*controller->getAxisValue(speedIdx)*forBackSpeed;
if(controller->getNumberOfAxes() <= (int)upDownIdx) return;
result += upDownDir*controller->getAxisValue(upDownIdx)*upDownSpeed;
}
AllInOneTranslationModelFactory::~AllInOneTranslationModelFactory()
{
}
TranslationModel* AllInOneTranslationModelFactory::create(
std::string className, ArgumentVector* args)
{
if (className != "AllInOneTranslationModel")
{
return NULL;
}
unsigned upDownIdx = 0;
unsigned speedIdx = 1;
float upDownSpeed = 1;
float forBackSpeed = 1;
if (args && args->keyExists("upDownIdx"))
args->get("upDownIdx", upDownIdx);
else
printd(WARNING,
"AllInOneTranslationModelFactory::create(): WARNING: missing attribute upDownIdx, assuming default!\n");
if (args && args->keyExists("speedIdx"))
args->get("speedIdx", speedIdx);
else
printd(WARNING,
"AllInOneTranslationModelFactory::create(): WARNING: missing attribute speedIdx, assuming default!\n");
if (args && args->keyExists("upDownSpeed"))
args->get("upDownSpeed", upDownSpeed);
else
printd(WARNING,
"AllInOneTranslationModelFactory::create(): WARNING: missing attribute upDownSpeed, assuming default!\n");
if (args && args->keyExists("forBackSpeed"))
args->get("forBackSpeed", forBackSpeed);
else
printd(WARNING,
"AllInOneTranslationModelFactory::create(): WARNING: missing attribute forBackSpeed, assuming default!\n");
return new AllInOneTranslationModel(upDownIdx, speedIdx, forBackSpeed,
upDownSpeed);
}
| jzarl/inVRs | src/inVRs/Modules/Navigation/AllInOneTranslationModel.cpp | C++ | gpl-3.0 | 4,248 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
"""
@file outTemp.py
@brief ModuleDescription
@date $Date$
"""
import sys
import time
sys.path.append(".")
# Import RTM module
import RTC
import OpenRTM_aist
# Import Service implementation class
# <rtc-template block="service_impl">
# </rtc-template>
# Import Service stub modules
# <rtc-template block="consumer_import">
# </rtc-template>
# This module's spesification
# <rtc-template block="module_spec">
outtemp_spec = ["implementation_id", "outTemp",
"type_name", "outTemp",
"description", "ModuleDescription",
"version", "1.0.0",
"vendor", "VenderName",
"category", "Category",
"activity_type", "STATIC",
"max_instance", "1",
"language", "Python",
"lang_type", "SCRIPT",
""]
# </rtc-template>
##
# @class outTemp
# @brief ModuleDescription
#
# get original temperature and output by celius.
#
#
class outTemp(OpenRTM_aist.DataFlowComponentBase):
##
# @brief constructor
# @param manager Maneger Object
#
def __init__(self, manager):
OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
origin_Temp_arg = [None] * ((len(RTC._d_TimedDouble) - 4) / 2)
self._d_origin_Temp = RTC.TimedDouble(*origin_Temp_arg)
"""
"""
self._origin_TempIn = OpenRTM_aist.InPort("origin_Temp", self._d_origin_Temp,OpenRTM_aist.RingBuffer(1))
# initialize of configuration-data.
# <rtc-template block="init_conf_param">
# </rtc-template>
##
#
# The initialize action (on CREATED->ALIVE transition)
# formaer rtc_init_entry()
#
# @return RTC::ReturnCode_t
#
#
def onInitialize(self):
# Bind variables and configuration variabl
print "onInitialize"
print
# Set InPort buffers
self.addInPort("origin_Temp",self._origin_TempIn)
# Set OutPort buffers
# Set service provider to Ports
# Set service consumers to Ports
# Set CORBA Service Ports
return RTC.RTC_OK
# ##
# #
# # The finalize action (on ALIVE->END transition)
# # formaer rtc_exiting_entry()
# #
# # @return RTC::ReturnCode_t
#
# #
#def onFinalize(self):
#
# return RTC.RTC_OK
# ##
# #
# # The startup action when ExecutionContext startup
# # former rtc_starting_entry()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onStartup(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The shutdown action when ExecutionContext stop
# # former rtc_stopping_entry()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onShutdown(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The activated action (Active state entry action)
# # former rtc_active_entry()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onActivated(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The deactivated action (Active state exit action)
# # former rtc_active_exit()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onDeactivated(self, ec_id):
#
# return RTC.RTC_OK
##
#
# The execution action that is invoked periodically
# former rtc_active_do()
#
# @param ec_id target ExecutionContext Id
#
# @return RTC::ReturnCode_t
#
#
def onExecute(self, ec_id):
self._origin_TempIn.read()
# if(self._origin_TempIn.isNew()):
self._d_origin_Temp = self._origin_TempIn.read()
temp = self._d_origin_Temp.data
#print "Temp: %4.2lf" % self._d_origin_Temp.data
#print self._d_origin_Temp.data
print temp
#else:
# print "no new data"
time.sleep(5)
return RTC.RTC_OK
# ##
# #
# # The aborting action when main logic error occurred.
# # former rtc_aborting_entry()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onAborting(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The error action in ERROR state
# # former rtc_error_do()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onError(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The reset action that is invoked resetting
# # This is same but different the former rtc_init_entry()
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onReset(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The state update action that is invoked after onExecute() action
# # no corresponding operation exists in OpenRTm-aist-0.2.0
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onStateUpdate(self, ec_id):
#
# return RTC.RTC_OK
# ##
# #
# # The action that is invoked when execution context's rate is changed
# # no corresponding operation exists in OpenRTm-aist-0.2.0
# #
# # @param ec_id target ExecutionContext Id
# #
# # @return RTC::ReturnCode_t
# #
# #
#def onRateChanged(self, ec_id):
#
# return RTC.RTC_OK
def outTempInit(manager):
profile = OpenRTM_aist.Properties(defaults_str=outtemp_spec)
manager.registerFactory(profile,
outTemp,
OpenRTM_aist.Delete)
def MyModuleInit(manager):
outTempInit(manager)
# Create a component
comp = manager.createComponent("outTemp")
def main():
mgr = OpenRTM_aist.Manager.init(sys.argv)
mgr.setModuleInitProc(MyModuleInit)
mgr.activateManager()
mgr.runManager()
if __name__ == "__main__":
main()
| max-koara/OutTemp | outTemp.py | Python | gpl-3.0 | 5,559 |
# Paperwork - Using OCR to grep dead trees the easy way
# Copyright (C) 2014 Jerome Flesch
#
# Paperwork 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.
#
# Paperwork 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 Paperwork. If not, see <http://www.gnu.org/licenses/>.
import os
import logging
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gtk
from paperwork.backend.labels import Label
from paperwork.frontend.util import load_uifile
from paperwork.frontend.util.actions import SimpleAction
logger = logging.getLogger(__name__)
DROPPER_BITS = (
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377"
"\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\0\0\0\377"
"\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377"
"\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377"
"\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\0\0\0\377\0\0\0\377\0"
"\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377"
"\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\377\377\377\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0"
"\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\0\0\0\377\0\0"
"\0\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377"
"\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377\377\377"
"\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377\377"
"\0\0\0\377\377\377\377\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377"
"\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\377\377"
"\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0"
"\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377"
"\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377"
"\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\0\0"
"\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0"
"\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
)
DROPPER_WIDTH = 17
DROPPER_HEIGHT = 17
DROPPER_X_HOT = 2
DROPPER_Y_HOT = 16
class PickColorAction(SimpleAction):
"""
Hack taken from libgtk3/gtk/deprecated/gtkcolorsel.c
"""
def __init__(self, label_editor):
super(PickColorAction, self).__init__("Pick color")
self.__editor = label_editor
self.__dropper_grab_widget = None
self.__grab_time = None
self.__has_grab = False
self.__pointer_device = None
def do(self):
self._get_screen_color()
def _make_picker_cursor(self, display):
# XXX(Jflesch) ... do not work
try:
return Gdk.Cursor.new_from_name(display, "color-picker")
except TypeError:
pass
try:
# happens when new_from_name returns NULL at C level
pixbuf = GdkPixbuf.Pixbuf.new_from_data(
DROPPER_BITS, GdkPixbuf.Colorspace.RGB, True, 8,
DROPPER_WIDTH, DROPPER_HEIGHT,
DROPPER_WIDTH * 4
)
cursor = Gdk.Cursor.new_from_pixbuf(display, pixbuf,
DROPPER_X_HOT, DROPPER_Y_HOT)
return cursor
except TypeError:
pass
return None
def _get_screen_color(self):
time = Gtk.get_current_event_time()
screen = self.__editor._pick_button.get_screen()
display = self.__editor._pick_button.get_display()
# XXX(JFlesch): Assumption: mouse is used
pointer_device = Gtk.get_current_event_device()
if not self.__dropper_grab_widget:
self.__dropper_grab_widget = Gtk.Window.new(Gtk.WindowType.POPUP)
self.__dropper_grab_widget.set_screen(screen)
self.__dropper_grab_widget.resize(1, 1)
self.__dropper_grab_widget.move(-100, -100)
self.__dropper_grab_widget.show()
self.__dropper_grab_widget.add_events(
Gdk.EventMask.BUTTON_RELEASE_MASK
)
toplevel = self.__editor._pick_button.get_toplevel()
if isinstance(toplevel, Gtk.Window):
if toplevel.has_group():
toplevel.get_group().add_window(self.__dropper_grab_widget)
window = self.__dropper_grab_widget.get_window()
picker_cursor = self._make_picker_cursor(display)
if (pointer_device.grab(
window,
Gdk.GrabOwnership.APPLICATION, False,
Gdk.EventMask.BUTTON_RELEASE_MASK,
picker_cursor, time) != Gdk.GrabStatus.SUCCESS):
logger.warning("Pointer device grab failed !")
return
Gtk.device_grab_add(self.__dropper_grab_widget, pointer_device, True)
self.__grab_time = time
self.__pointer_device = pointer_device
self.__has_grab = True
self.__dropper_grab_widget.connect("button-release-event",
self._on_mouse_release)
def _grab_color_at_pointer(self, screen, device, x, y):
root_window = screen.get_root_window()
pixbuf = Gdk.pixbuf_get_from_window(root_window, x, y, 1, 1)
# XXX(Jflesch): bad shortcut here ...
pixels = pixbuf.get_pixels()
rgb = (
float(ord(pixels[0]) * 0x101) / 65535,
float(ord(pixels[1]) * 0x101) / 65535,
float(ord(pixels[2]) * 0x101) / 65535,
)
logger.info("Picked color: %s" % str(rgb))
return rgb
def _on_mouse_release(self, invisible_widget, event):
if not self.__has_grab:
return
try:
color = self._grab_color_at_pointer(
event.get_screen(), event.get_device(),
event.x_root, event.y_root
)
self.__editor._color_chooser.set_rgba(
Gdk.RGBA(
red=color[0],
green=color[1],
blue=color[2],
alpha=1.0
)
)
finally:
self.__pointer_device.ungrab(self.__grab_time)
Gtk.device_grab_remove(self.__dropper_grab_widget,
self.__pointer_device)
self.__has_grab = False
self.__pointer_device = None
class LabelEditor(object):
"""
Dialog to create / edit labels
"""
def __init__(self, label_to_edit=None):
if label_to_edit is None:
label_to_edit = Label()
self.label = label_to_edit
self.__ok_button = None
def edit(self, main_window):
"""
Open the edit dialog, and update the label according to user changes
"""
widget_tree = load_uifile(
os.path.join("labeleditor", "labeleditor.glade"))
dialog = widget_tree.get_object("dialogLabelEditor")
dialog.set_transient_for(main_window)
self.__ok_button = widget_tree.get_object("buttonOk")
self._pick_button = widget_tree.get_object("buttonPickColor")
PickColorAction(self).connect([self._pick_button])
self._color_chooser = widget_tree.get_object("labelColorChooser")
self._color_chooser.set_rgba(self.label.color)
name_entry = widget_tree.get_object("entryLabelName")
name_entry.connect("changed", self.__on_label_entry_changed)
name_entry.set_text(self.label.name)
response = dialog.run()
if (response == Gtk.ResponseType.OK
and name_entry.get_text().strip() == ""):
response = Gtk.ResponseType.CANCEL
if (response == Gtk.ResponseType.OK):
logger.info("Label validated")
self.label.name = unicode(name_entry.get_text(), encoding='utf-8')
self.label.color = self._color_chooser.get_rgba()
else:
logger.info("Label editing cancelled")
dialog.destroy()
logger.info("Label after editing: %s" % self.label)
return (response == Gtk.ResponseType.OK)
def __on_label_entry_changed(self, label_entry):
txt = unicode(label_entry.get_text(), encoding='utf-8').strip()
ok_enabled = True
ok_enabled = ok_enabled and txt != u""
ok_enabled = ok_enabled and u"," not in txt
self.__ok_button.set_sensitive(ok_enabled)
| kschwank/paperwork | src/paperwork/frontend/labeleditor/__init__.py | Python | gpl-3.0 | 10,471 |
package com.cloudera.cmf.service;
import com.cloudera.cmf.command.ConfirmCommandInfo;
import com.cloudera.cmf.command.ServiceCommandHandler;
import com.cloudera.cmf.command.SvcCmdArgs;
import com.cloudera.cmf.model.DbCommand;
import com.cloudera.cmf.model.DbRole;
import com.cloudera.cmf.model.DbService;
import com.cloudera.cmf.model.TypedDbBase;
import com.cloudera.cmf.persist.CmfEntityManager;
import com.cloudera.server.web.common.I18n;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@Deprecated
public abstract class AbstractServiceCommand<A extends SvcCmdArgs> extends AbstractCommandHandler<DbService, A>
implements ServiceCommandHandler<A>
{
protected AbstractServiceCommand(ServiceDataProvider sdp)
{
super(sdp);
}
public final DbCommand execute(DbService service, A arg, DbCommand parent)
{
Set roles = Collections.emptySet();
if (arg != null) {
roles = arg.targetRoles;
}
if ((isExclusive()) &&
(hasActiveCommands(service, roles, parent))) {
return CommandUtils.createFailedCommand(getName(), service, "There is already a pending command on this service.", parent);
}
DbCommand cmd = DbCommand.of(service, getName());
cmd.setParent(parent);
CmfEntityManager.currentCmfEntityManager().persistCommand(cmd);
executeImpl(cmd, service, roles, arg);
return cmd;
}
protected abstract void executeImpl(DbCommand paramDbCommand, DbService paramDbService, Set<DbRole> paramSet, A paramA);
public boolean isApplicableToAllRoleInstances()
{
return false;
}
public ConfirmCommandInfo getConfirmCommandInfo(DbService target, A args)
{
String msg;
String msg;
if (args.targetRoles.isEmpty())
msg = I18n.t("message.service.commandConfirm", new String[] { getDisplayName(), target.getDisplayName() });
else {
msg = I18n.t("message.roleInstances.commandConfirm", new String[] { getDisplayName() });
}
return ConfirmCommandInfo.create(msg, getConfirmCommandWarning(target, args));
}
protected String getConfirmCommandWarning(DbService target, A args)
{
return null;
}
public List<? extends TypedDbBase> getContext(CmfEntityManager em, DbCommand cmd)
{
return ImmutableList.of(cmd.getService());
}
} | Mapleroid/cm-server | server-5.11.0.src/com/cloudera/cmf/service/AbstractServiceCommand.java | Java | gpl-3.0 | 2,398 |
package HHCP;
import causalgraph.Edge;
import org.jgrapht.graph.ClassBasedEdgeFactory;
import org.jgrapht.graph.DefaultDirectedWeightedGraph;
import java.util.*;
/**
* Created by ignasi on 21/08/17.
*/
public class JustificationGraph {
private DefaultDirectedWeightedGraph<String, Edge> graph;
public BitSet relevants = new BitSet();
public JustificationGraph(Problem p){
graph = createStringGraph();
for(VAction va : p.getVaList()){
if(va.isObservation){
feedObservations(va);
}else if(va.isNondeterministic){
feedNonDetActions(va);
}else{
feedActions(va);
}
}
}
private void feedActions(VAction a) {
for(VEffect e : a.getEffects()){
for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){
graph.addVertex(String.valueOf(to));
BitSet origins = (BitSet) e.getCondition().clone();
origins.or(a.getPreconditions());
for(int from = origins.nextSetBit(0);from>=0;from = origins.nextSetBit(from+1)){
if(from == to) continue;
graph.addVertex(String.valueOf(from));
Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName());
graph.addEdge(String.valueOf(from), String.valueOf(to), edge);
graph.setEdgeWeight(edge, a.cost * -1);
}
}
}
}
private void feedObservations(VAction a) {
for(VEffect e : a.getEffects()){
for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){
graph.addVertex(String.valueOf(to));
for(int from = a.getPreconditions().nextSetBit(0);from>=0;from = a.getPreconditions().nextSetBit(from+1)){
if(from == to) continue;
graph.addVertex(String.valueOf(from));
Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName());
graph.addEdge(String.valueOf(from), String.valueOf(to), edge);
graph.setEdgeWeight(edge, a.cost * -1);
}
}
}
}
private void feedNonDetActions(VAction a){
for(VEffect e : a.getEffects()){
for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){
graph.addVertex(String.valueOf(to));
for(int from = a.getPreconditions().nextSetBit(0);from>=0;from = a.getPreconditions().nextSetBit(from+1)){
if(from == to) continue;
graph.addVertex(String.valueOf(from));
Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName());
graph.addEdge(String.valueOf(from), String.valueOf(to), edge);
graph.setEdgeWeight(edge, a.cost * -1);
}
}
}
}
private DefaultDirectedWeightedGraph<String, Edge> createStringGraph(){
DefaultDirectedWeightedGraph<String, Edge> g = new DefaultDirectedWeightedGraph<String, Edge>(
new ClassBasedEdgeFactory<String, Edge>(Edge.class));
return g;
}
public Set<Edge> getIncomingEdgesOf(String goal) {
Set<Edge> hS = graph.incomingEdgesOf(goal);
return hS;
}
public double getEdgeWeight(Edge e) {
return graph.getEdgeWeight(e)*-1;
}
public void setRelevantLiterals(Problem p, HashSet<String> relevantList){
for(String lit : relevantList){
relevants.set(p.getPredicate(lit));
}
}
public BitSet getReachableLiterals(BitSet goalState, BitSet initial){
BitSet next = new BitSet();
BitSet current = (BitSet) initial.clone();
HashSet<String> visited = new HashSet<String>();
boolean reached = false;
while(!reached || !contained(current, goalState)){
if(current.equals(next)){
reached = true;
}
for(int i = current.nextSetBit(0); i>=0; i=current.nextSetBit(i+1)){
if(!graph.containsVertex(String.valueOf(i))) continue;
Set<Edge> edges = graph.outgoingEdgesOf(String.valueOf(i));
for(Edge e : edges){
if(!visited.contains(e.getTarget())) {
visited.add(e.getTarget());
next.set(Integer.parseInt(e.getTarget()));
}
}
}
current.or(next);
}
return current;
}
private boolean contained(BitSet current, BitSet goalState) {
BitSet aux = new BitSet();
aux.or(goalState);
aux.and(current);
if(goalState.equals(aux)) return true;
return false;
}
}
| ignasiet/Translator | src/HHCP/JustificationGraph.java | Java | gpl-3.0 | 4,984 |
package database;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Singleton class for connecting to the database through JDBC.
*
* @author Maks (original)
* @author Brett Commandeur (modified by)
* @reference https://github.com/MaksJS/jdbc-singleton/blob/master/JDBC.java on March 1, 2015
**/
public class JDBC {
private static Connection connection = null;
private static String username = null;
private static String password = null;
private static Boolean connectingFromLab = null;
private final static String REMOTE_URL = "jdbc:oracle:thin:@localhost:1525:CRS"; // Work from Home
private final static String LAB_URL = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; // Lab Machines
private final static String DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final int LOGIN_TIMEOUT = 3;
/**
* Method that loads the specified driver
*
* @return void
**/
private static void loadDriver() {
try {
Class drvClass = Class.forName(DRIVER);
DriverManager.registerDriver((Driver)drvClass.newInstance());
}
catch (Exception e) {
errorHandler("Failed to load the driver " + DRIVER, e);
}
}
/**
* Method that loads the connection into the right property
*
* @return void
**/
private static void loadConnection() {
if (username == null || password == null || connectingFromLab == null) {
errorHandler("Please configure username, password, connecting from lab", null);
} else {
String url = (connectingFromLab) ? LAB_URL : REMOTE_URL;
DriverManager.setLoginTimeout(LOGIN_TIMEOUT);
try {
connection = DriverManager.getConnection(url, username, password);
}
catch (SQLException e) {
errorHandler("Failed to connect to the database " + url, e);
}
}
}
/**
* Method that shows the errors thrown by the singleton
*
* @param {String} Message
* @option {Exception} e
* @return void
**/
private static void errorHandler(String message, Exception e) {
System.out.println(message);
if (e != null) System.out.println(e.getMessage());
}
/**
* Method that sets the user and password for the connection
*
* @param newUser
* @param newPassword
* @return void
*/
public static void configure(String newUsername, String newPassword, boolean isConnectingFromLab) {
username = newUsername;
password = newPassword;
connectingFromLab = isConnectingFromLab;
}
/***
* Method that checks whether db info has been set.
*
* @return Whether the necessary db info is configured.
*/
public static boolean isConfigured() {
return (username != null
&& password != null
&& connectingFromLab != null);
}
/**
* Static method that returns the instance for the singleton
*
* @return {Connection} connection
**/
public static Connection connect() {
if (connection == null) {
loadDriver();
loadConnection();
}
return connection;
}
/**
* Static method that closes the connection to the database
*
* @return true on success.
**/
public static boolean closeConnection() {
if (connection == null) {
errorHandler("No connection found", null);
}
else {
try {
connection.close();
connection = null;
return true;
}
catch (SQLException e) {
errorHandler("Failed to close the connection", e);
}
}
return false;
}
/**
* Method to execute a given SQL update on the connection
*
* @param sql
* @return void
**/
public static boolean hasConnection() {
boolean valid = false;
if (connection != null) {
valid = true;
}
return valid;
}
} | C391-Project/RadiologyApp | src/database/JDBC.java | Java | gpl-3.0 | 4,195 |
#ifndef FO_BASE_BUFFER_HPP_
#define FO_BASE_BUFFER_HPP_
#include <stdint.h>
#include <cstdlib>
#include "Common.hpp"
namespace fonline {
class Buffer {
public:
FONLINE_COMMON_API Buffer();
FONLINE_COMMON_API Buffer(size_t alen);
FONLINE_COMMON_API ~Buffer();
FONLINE_COMMON_API void Reset();
FONLINE_COMMON_API void Write(const void* buf, size_t alen);
FONLINE_COMMON_API void Read(void *buf, size_t alen);
// XXX[1.8.2012 alex]: new names
FONLINE_COMMON_API bool IsError();
FONLINE_COMMON_API bool NeedProcess();
FONLINE_COMMON_API void EnsureCapacity(size_t capacity);
FONLINE_COMMON_API void EnsureWriteCapacity(size_t dataSize);
template<class T> Buffer& operator<<(const T& value) {
// XXX[1.8.2012 alex]: endianness?
Write(&value, sizeof(value));
return *this;
}
template<class T> Buffer& operator>>(T& value) {
// XXX[1.8.2012 alex]: endianness?
Read(&value, sizeof(value));
return *this;
}
bool error;
char* data;
size_t capacity;
size_t writePosition;
size_t readPosition;
};
}; // namespace fonline
#endif // FO_BASE_BUFFER_HPP_
| alexknvl/fonline | src/FOnlineCommon/buffer.hpp | C++ | gpl-3.0 | 1,163 |
@extends('layouts.app')
@section('title')
Account Settings - Barmate POS
@stop
@section('custom-css')
@stop
@section('content')
<div class="row paper">
<div class="paper-header">
<h2><i class="fa fa-gear"></i> Account Settings</h2>
</div>
@if ( Session::has('error') )
<div class="paper-notify error">
<i class="fa fa-exclamation-triangle"></i> {{ Session::get('error') }}
</div>
@elseif ( Session::has('success') )
<div class="paper-notify success">
<i class="fa fa-check"></i> {{ Session::get('success') }}
</div>
@endif
<div class="paper-body">
{!! Form::open(['url'=>'app/account', 'method'=>'POST']) !!}
<!-- GENERAL INFORMATIONS -->
<div class="col-md-4">
<label>First name</label>
<input type="text" class="form-control" name="firstname" value="{{ $user->firstname }}">
</div>
<div class="col-md-4">
<label>Last name</label>
<input type="text" class="form-control" name="lastname" value="{{ $user->lastname }}">
</div>
<div class="col-md-4">
<label>Role</label>
<input type="text" class="form-control" disabled value="{{ $roleDescription }}">
</div>
<!-- EMAIL -->
<div class="col-md-12">
<label>Email</label>
<input type="text" class="form-control" name="email" value="{{ $user->email }}">
</div>
<!-- PASSWORD -->
<div class="col-md-4">
<label>Current password</label>
<input type="password" class="form-control" disabled value="password">
</div>
<div class="col-md-4">
<label>New password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="col-md-4">
<label>Repeat new password</label>
<input type="password" name="repeat_password" class="form-control">
</div>
<!-- NOTES -->
<div class="col-md-12">
<label>About me</label>
<textarea class="form-control" name="notes">{{ $user->notes }}</textarea>
<br>
<input type="submit" class="btn btn-primary pull-right" value="Save settings">
</div>
<!-- TRICKY PATCH TO ALLOW PADDING BOTTOM -->
</form>
</div>
</div>
@stop
@section('custom-js')
@stop | Saluki/Barmate | resources/views/account/main.blade.php | PHP | gpl-3.0 | 2,925 |
package com.hhd.breath.app.main.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hhd.breath.app.BaseActivity;
import com.hhd.breath.app.R;
import com.hhd.breath.app.utils.ShareUtils;
public class ModifyNameActivity extends BaseActivity {
private TextView mTextTop ;
private RelativeLayout mLayoutBackRe ;
private RelativeLayout mLayoutRight ;
private EditText mEditName ;
private InputMethodManager imm ;
private String userName ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_name);
userName = getIntent().getExtras().getString("userName") ;
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
initView();
initEvent();
}
@Override
protected void initView() {
mTextTop = (TextView)findViewById(R.id.topText) ;
mLayoutBackRe = (RelativeLayout)findViewById(R.id.back_re) ;
mLayoutRight = (RelativeLayout)findViewById(R.id.layout_right) ;
mEditName = (EditText)findViewById(R.id.edit_username) ;
mLayoutRight.setVisibility(View.VISIBLE);
}
public static void actionActivity(Activity mActivity , String userName){
Bundle mBundle = new Bundle() ;
mBundle.putString("userName",userName);
Intent mIntent = new Intent() ;
mIntent.setClass(mActivity,ModifyNameActivity.class) ;
mIntent.putExtras(mBundle) ;
mActivity.startActivity(mIntent);
}
@Override
protected void initEvent() {
mTextTop.setText("修改用户名");
mEditName.setText(userName);
mLayoutBackRe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (imm.isActive()) {
imm.hideSoftInputFromWindow(mEditName.getWindowToken(), 0); //强制隐藏键盘
}
ModifyNameActivity.this.finish();
}
});
mLayoutRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (imm.isActive()) {
imm.hideSoftInputFromWindow(mEditName.getWindowToken(), 0); //强制隐藏键盘
}
ShareUtils.setUserName(ModifyNameActivity.this,mEditName.getText().toString().trim());
ModifyNameActivity.this.finish();
}
});
}
}
| weibingithub/BreathApp | app/src/main/java/com/hhd/breath/app/main/ui/ModifyNameActivity.java | Java | gpl-3.0 | 2,791 |
""" SicPy
"""
# __version__ = '0.1'
# __author__ = 'disrupts'
# __license__ = 'GPLv3'
# Cryptobox should only be used to implement ciphers
#from sicpy.cryptobox import Cryptobox
# Ciphers are imported directly with sicpy
# not requiring an aditional import
from sicpy.ciphers.caesar import Caesar
from sicpy.ciphers.vigenere import Vigenere
from sicpy.ciphers.railfence import RailFence
# Alphabet can be used to build alphabets easily
# >>> myalpha = Alphabet('ABSDE')
from sicpy.alphabet import Alphabet
# LATIN is imported by cryptobox.py
| disrupts/SicPy | sicpy/__init__.py | Python | gpl-3.0 | 557 |
<?php
/**
* Membership Settings meta box
*
* @package LifterLMS/Admin/PostTypes/MetaBoxes/Classes
*
* @since 1.0.0
* @version 5.9.0
*/
defined( 'ABSPATH' ) || exit;
/**
* Membership Settings meta box class
*
* @since 1.0.0
* @since 3.30.3 Fixed spelling errors; removed duplicate array keys.
* @since 3.35.0 Verify nonces and sanitize `$_POST` data.
* @since 3.36.0 Allow some fields to store values with quotes.
* @since 3.36.3 In the `save() method Added logic to correctly sanitize fields of type
* 'multi' (array) and 'shortcode' (preventing quotes encode).
* Also align the method return type to the parent `save()` method.
*/
class LLMS_Meta_Box_Membership extends LLMS_Admin_Metabox {
/**
* This function allows extending classes to configure required class properties
* $this->id, $this->title, and $this->screens should be configured in this function.
*
* @return void
* @since 3.0.0
*/
public function configure() {
$this->id = 'lifterlms-membership';
$this->title = __( 'Membership Settings', 'lifterlms' );
$this->screens = array(
'llms_membership',
);
$this->priority = 'high';
}
/**
* Get array of data to pass to the auto enrollment courses table.
*
* @since 3.0.0
* @since 3.30.0 Removed sorting by title.
* @since 3.30.3 Fixed spelling errors.
*
* @param obj $membership instance of LLMS_Membership for the current post.
* @return array
*/
private function get_content_table( $membership ) {
$data = array();
$data[] = array(
'',
'<br>' . __( 'No automatic enrollment courses found. Add a course below.', 'lifterlms' ) . '<br><br>',
'',
);
foreach ( $membership->get_auto_enroll_courses() as $course_id ) {
$course = new LLMS_Course( $course_id );
$title = $course->get( 'title' );
$data[] = array(
'<span class="llms-drag-handle" style="color:#999;"><i class="fa fa-ellipsis-v" aria-hidden="true" style="margin-right:2px;"></i><i class="fa fa-ellipsis-v" aria-hidden="true"></i></span>',
'<a href="' . get_edit_post_link( $course->get( 'id' ) ) . '">' . $title . ' (ID#' . $course_id . ')</a>',
'<a class="llms-button-danger small" data-id="' . $course_id . '" href="#llms-course-remove" style="float:right;">' . __( 'Remove course', 'lifterlms' ) . '</a>
<a class="llms-button-secondary small" data-id="' . $course_id . '" href="#llms-course-bulk-enroll" style="float:right;">' . __( 'Enroll All Members', 'lifterlms' ) . '</a>',
);
}
return apply_filters( 'llms_membership_get_content_table_data', $data, $membership );
}
/**
* This function is where extending classes can configure all the fields within the metabox.
* The function must return an array which can be consumed by the "output" function.
*
* @since 3.0.0
* @since 3.30.0 Removed empty field settings. Modified settings to accommodate sortable auto-enrollment table.
* @since 3.30.3 Removed duplicate array keys.
* @since 3.36.0 Allow some fields to store values with quotes.
*
* @return array
*/
public function get_fields() {
global $post;
$membership = new LLMS_Membership( $this->post );
$redirect_options = array();
$redirect_page_id = $membership->get( 'redirect_page_id' );
if ( $redirect_page_id ) {
$redirect_options[] = array(
'key' => $redirect_page_id,
'title' => get_the_title( $redirect_page_id ) . '(ID#' . $redirect_page_id . ')',
);
}
$sales_page_content_type = 'none';
if ( $post && 'auto-draft' !== $post->post_status && $post->post_excerpt ) {
$sales_page_content_type = 'content';
}
return array(
array(
'title' => __( 'Sales Page', 'lifterlms' ),
'fields' => array(
array(
'allow_null' => false,
'class' => 'llms-select2',
'desc' => __( 'Customize the content displayed to visitors and students who are not enrolled in the membership.', 'lifterlms' ),
'desc_class' => 'd-3of4 t-3of4 m-1of2',
'default' => $sales_page_content_type,
'id' => $this->prefix . 'sales_page_content_type',
'is_controller' => true,
'label' => __( 'Sales Page Content', 'lifterlms' ),
'type' => 'select',
'value' => llms_get_sales_page_types(),
),
array(
'controller' => '#' . $this->prefix . 'sales_page_content_type',
'controller_value' => 'content',
'desc' => __( 'This content will only be shown to visitors who are not enrolled in this membership.', 'lifterlms' ),
'id' => '',
'label' => __( 'Sales Page Custom Content', 'lifterlms' ),
'type' => 'post-excerpt',
),
array(
'controller' => '#' . $this->prefix . 'sales_page_content_type',
'controller_value' => 'page',
'data_attributes' => array(
'post-type' => 'page',
'placeholder' => __( 'Select a page', 'lifterlms' ),
),
'class' => 'llms-select2-post',
'id' => $this->prefix . 'sales_page_content_page_id',
'type' => 'select',
'label' => __( 'Select a Page', 'lifterlms' ),
'value' => $membership->get( 'sales_page_content_page_id' ) ? llms_make_select2_post_array( array( $membership->get( 'sales_page_content_page_id' ) ) ) : array(),
),
array(
'controller' => '#' . $this->prefix . 'sales_page_content_type',
'controller_value' => 'url',
'type' => 'text',
'label' => __( 'Sales Page Redirect URL', 'lifterlms' ),
'id' => $this->prefix . 'sales_page_content_url',
'class' => 'input-full',
'value' => '',
'desc_class' => 'd-all',
'group' => 'top',
),
),
),
array(
'title' => __( 'Restrictions', 'lifterlms' ),
'fields' => array(
array(
'allow_null' => false,
'class' => '',
'desc' => __( 'When a non-member attempts to access content restricted to this membership', 'lifterlms' ),
'id' => $this->prefix . 'restriction_redirect_type',
'is_controller' => true,
'type' => 'select',
'label' => __( 'Restricted Access Redirect', 'lifterlms' ),
'value' => array(
array(
'key' => 'none',
'title' => __( 'Stay on page', 'lifterlms' ),
),
array(
'key' => 'membership',
'title' => __( 'Redirect to this membership page', 'lifterlms' ),
),
array(
'key' => 'page',
'title' => __( 'Redirect to a WordPress page', 'lifterlms' ),
),
array(
'key' => 'custom',
'title' => __( 'Redirect to a Custom URL', 'lifterlms' ),
),
),
),
array(
'class' => 'llms-select2-post',
'controller' => '#' . $this->prefix . 'restriction_redirect_type',
'controller_value' => 'page',
'data_attributes' => array(
'post-type' => 'page',
),
'id' => $this->prefix . 'redirect_page_id',
'label' => __( 'Select a WordPress Page', 'lifterlms' ),
'type' => 'select',
'value' => $redirect_options,
),
array(
'class' => '',
'controller' => '#' . $this->prefix . 'restriction_redirect_type',
'controller_value' => 'custom',
'id' => $this->prefix . 'redirect_custom_url',
'label' => __( 'Enter a Custom URL', 'lifterlms' ),
'type' => 'text',
'value' => 'test',
),
array(
'class' => '',
'controls' => '#' . $this->prefix . 'restriction_notice',
'default' => 'yes',
'desc' => __( 'Check this box to output a message after redirecting. If no redirect is selected this message will replace the normal content that would be displayed.', 'lifterlms' ),
'desc_class' => 'd-3of4 t-3of4 m-1of2',
'id' => $this->prefix . 'restriction_add_notice',
'label' => __( 'Display a Message', 'lifterlms' ),
'type' => 'checkbox',
'value' => 'yes',
),
array(
'class' => 'full-width',
'desc' => sprintf( __( 'Shortcodes like %s can be used in this message', 'lifterlms' ), '[lifterlms_membership_link id="' . $this->post->ID . '"]' ),
'default' => sprintf( __( 'You must belong to the %s membership to access this content.', 'lifterlms' ), '[lifterlms_membership_link id="' . $this->post->ID . '"]' ),
'id' => $this->prefix . 'restriction_notice',
'label' => __( 'Restricted Content Notice', 'lifterlms' ),
'type' => 'text',
'sanitize' => 'shortcode',
),
),
),
array(
'title' => __( 'Auto Enrollment', 'lifterlms' ),
'fields' => array(
array(
'label' => __( 'Automatic Enrollment', 'lifterlms' ),
'desc' => sprintf( __( 'When a student joins this membership they will be automatically enrolled in these courses. Click %1$shere%2$s for more information.', 'lifterlms' ), '<a href="https://lifterlms.com/docs/membership-auto-enrollment/" target="_blank">', '</a>' ),
'id' => $this->prefix . 'content_table',
'titles' => array( '', __( 'Course Name', 'lifterlms' ), '' ),
'type' => 'table',
'table_data' => $this->get_content_table( $membership ),
),
array(
'class' => 'llms-select2-post',
'data_attributes' => array(
'placeholder' => __( 'Select course(s)', 'lifterlms' ),
'post-type' => 'course',
'no-view-button' => true,
),
'id' => $this->prefix . 'auto_enroll',
'label' => __( 'Add Course(s)', 'lifterlms' ),
'type' => 'select',
'value' => array(),
),
),
),
);
}
/**
* Save field data.
*
* @since 3.0.0
* @since 3.30.0 Autoenroll courses saved via AJAX and removed from this method.
* @since 3.35.0 Verify nonces and sanitize `$_POST` data.
* @since 3.36.3 Added logic to correctly sanitize fields of type 'multi' (array)
* and 'shortcode' (preventing quotes encode).
* Also align the return type to the parent `save()` method.
* @since 5.9.0 Stop using deprecated `FILTER_SANITIZE_STRING`.
*
* @see LLMS_Admin_Metabox::save_actions()
*
* @param int $post_id WP_Post ID of the post being saved.
* @return int `-1` When no user or user is missing required capabilities or when there's no or invalid nonce.
* `0` during inline saves or ajax requests or when no fields are found for the metabox.
* `1` if fields were found. This doesn't mean there weren't errors during saving.
*/
public function save( $post_id ) {
if ( ! llms_verify_nonce( 'lifterlms_meta_nonce', 'lifterlms_save_data' ) ) {
return -1;
}
// Return early during quick saves and ajax requests.
if ( isset( $_POST['action'] ) && 'inline-save' === $_POST['action'] ) {
return 0;
} elseif ( llms_is_ajax() ) {
return 0;
}
$membership = new LLMS_Membership( $post_id );
if ( ! isset( $_POST[ $this->prefix . 'restriction_add_notice' ] ) ) {
$_POST[ $this->prefix . 'restriction_add_notice' ] = 'no';
}
// Get all defined fields.
$fields = $this->get_fields();
// save all the fields.
$save_fields = array(
$this->prefix . 'restriction_redirect_type',
$this->prefix . 'redirect_page_id',
$this->prefix . 'redirect_custom_url',
$this->prefix . 'restriction_add_notice',
$this->prefix . 'restriction_notice',
$this->prefix . 'sales_page_content_page_id',
$this->prefix . 'sales_page_content_type',
$this->prefix . 'sales_page_content_url',
);
if ( ! is_array( $fields ) ) {
return 0;
}
$to_return = 0;
// Loop through the fields.
foreach ( $fields as $group => $data ) {
// Find the fields in each tab.
if ( isset( $data['fields'] ) && is_array( $data['fields'] ) ) {
// loop through the fields.
foreach ( $data['fields'] as $field ) {
// don't save things that don't have an ID or that are not listed in $save_fields.
if ( isset( $field['id'] ) && in_array( $field['id'], $save_fields, true ) ) {
if ( isset( $field['sanitize'] ) && 'shortcode' === $field['sanitize'] ) {
$val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'], array( FILTER_FLAG_NO_ENCODE_QUOTES ) );
} elseif ( isset( $field['multi'] ) && $field['multi'] ) {
$val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'], array( FILTER_REQUIRE_ARRAY ) );
} else {
$val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'] );
}
$membership->set( substr( $field['id'], strlen( $this->prefix ) ), $val );
$to_return = 1;
}
}
}
}
return $to_return;
}
}
| gocodebox/lifterlms | includes/admin/post-types/meta-boxes/class.llms.meta.box.membership.php | PHP | gpl-3.0 | 13,071 |
package ru.mos.polls.quests.model.quest;
import android.content.Context;
import com.google.gson.annotations.SerializedName;
import ru.mos.polls.quests.model.QuestFamilyElement;
import ru.mos.polls.quests.vm.QuestsFragmentVM;
public class OtherQuest extends BackQuest {
public static final String TYPE = "other";
private static final String LINK_URL = "link_url";
@SerializedName("link_url")
private String linkUrl;
public OtherQuest(long innerId, QuestFamilyElement questFamilyElement) {
super(innerId, questFamilyElement);
linkUrl = questFamilyElement.getLinkUrl();
}
@Override
public void onClick(Context context, QuestsFragmentVM.Listener listener) {
listener.onNews(getTitle(), linkUrl, Integer.valueOf(getId()));
}
}
| active-citizen/android.java | app/src/main/java/ru/mos/polls/quests/model/quest/OtherQuest.java | Java | gpl-3.0 | 788 |
<?php
/**
* This runs all of the tests associated with HUGnetLib.
*
* PHP Version 5
*
* <pre>
* HUGnetLib is a library of HUGnet code
* Copyright (C) 2014 Hunt Utilities Group, LLC
*
* 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.
* </pre>
*
* @category Libraries
* @package HUGnetLibTest
* @subpackage SuiteBase
* @author Scott Price <prices@hugllc.com>
* @copyright 2014 Hunt Utilities Group, LLC
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://dev.hugllc.com/index.php/Project:HUGnetLib
*/
/** This is the HUGnet namespace */
namespace HUGnet\devices\inputTable;
/** This is a required class */
require_once CODE_BASE.'devices/inputTable/DriverVirtual.php';
/** This is a required class */
require_once CODE_BASE.'system/System.php';
/** This is a required class */
require_once TEST_CONFIG_BASE.'stubs/DummyTable.php';
/** This is our base class */
require_once dirname(__FILE__)."/drivers/DriverTestBase.php";
/** This is our interface */
require_once CODE_BASE."devices/inputTable/DriverInterface.php";
/**
* Test class for HUGnetDB.
* Generated by PHPUnit on 2007-12-13 at 10:28:11.
*
* @category Libraries
* @package HUGnetLibTest
* @subpackage SuiteBase
* @author Scott Price <prices@hugllc.com>
* @copyright 2014 Hunt Utilities Group, LLC
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version Release: 0.14.3
* @link http://dev.hugllc.com/index.php/Project:HUGnetLib
*/
class DriverVirtualTest extends drivers\DriverTestBase
{
/** This is the class we are testing */
protected $class = "DriverVirtualTestClass";
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @access protected
*
* @return null
*/
protected function setUp()
{
$sensor = new \HUGnet\DummyBase("Sensor");
$sensor->resetMock(array());
$this->o = DriverVirtual::factory(
"DriverVirtualTestClass", $sensor
);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @access protected
*
* @return null
*/
protected function tearDown()
{
unset($this->o);
}
/**
* data provider for testDeviceID
*
* @return array
*/
public static function dataPresent()
{
return array(
array(
"ThisIsABadName",
false,
),
array(
"unitType",
true,
),
array(
"storageType",
true,
),
array(
"testParam",
true,
),
);
}
/**
* test the set routine when an extra class exists
*
* @param string $name The name of the variable to test.
* @param array $expect The expected return
*
* @return null
*
* @dataProvider dataPresent
*/
public function testPresent($name, $expect)
{
$this->assertSame($expect, $this->o->present($name, 1));
}
/**
* data provider for testDeviceID
*
* @return array
*/
public static function dataGet()
{
return array(
array(
"ThisIsABadName",
array(),
null,
),
array(
"storageType",
array(),
\HUGnet\devices\datachan\Driver::TYPE_RAW,
),
array(
"testParam",
array(),
"12345",
),
array(
"unitType",
array(),
'asdf',
),
);
}
/**
* test the set routine when an extra class exists
*
* @param string $name The name of the variable to test.
* @param array $mock The mocks to use
* @param array $expect The expected return
*
* @return null
*
* @dataProvider dataGet
*/
public function testGet($name, $mock, $expect)
{
$this->assertSame($expect, $this->o->get($name, 1));
}
/**
* Data provider for testGetReading
*
* testGetReading($sensor, $A, $deltaT, $data, $prev, $expect)
*
* @return array
*/
public static function dataGetReading()
{
return array(
array(
array(
"Sensor" => array(
"get" => array(
"location" => "asdf",
),
),
),
256210,
1,
array(),
array(),
array(
array(
"value" => null,
"decimals" => 2,
"units" => "unknown",
"maxDecimals" => 2,
"storageUnit" => "unknown",
"unitType" => "asdf",
"dataType" => "raw",
"label" => "asdf",
"index" => 0,
"epChannel" => false,
"port" => null,
"raw" => null,
),
),
),
);
}
/**
* Generic function for testing sensor routines
*
* This is called by using parent::sensorTest()
*
* @param array $sensor The sensor data array
* @param mixed $A Data for the sensor to work on
* @param float $deltaT The time differenct
* @param array $data The data array being built
* @param array $prev The previous record
* @param mixed $expect The return data to expect
* @param int $channel The channel to test
*
* @return null
*
* @dataProvider dataGetReading()
*/
public function testGetReading(
$sensor, $A, $deltaT, $data, $prev, $expect, $channel = 0
) {
$sen = new \HUGnet\DummyBase("Sensor");
$sen->resetMock($sensor);
$chan = 0;
$ret = $this->o->decodeData($A, $chan, $deltaT, $data, $prev);
$this->assertEquals($expect, $ret, 0.00001);
}
/**
* Data provider for testEncodeData
*
* @return array
*/
public static function dataEncodeDataPoint()
{
return array(
array( // #0
array(
"Sensor" => array(
"id" => 1,
"get" => array(
"sensor" => 2,
"extra" => array(),
),
),
),
"",
1,
array(),
array(),
14.314713,
0,
),
);
}
/**
* data provider for testChannels
*
* @return array
*/
public static function dataChannels()
{
return array(
array(
array(
),
"",
array(
array(
'decimals' => 2,
'units' => 'unknown',
'maxDecimals' => 2,
'storageUnit' => 'unknown',
'unitType' => 'asdf',
'dataType' => 'raw',
'label' => '',
'index' => 0,
'epChannel' => false,
'port' => null,
),
),
),
);
}
}
/** This is the HUGnet namespace */
namespace HUGnet\devices\inputTable\drivers;
/**
* Base driver class for devices.
*
* This class deals with loading the drivers and figuring out what driver needs
* to be loaded.
*
* @category Libraries
* @package HUGnetLib
* @subpackage Devices
* @author Scott Price <prices@hugllc.com>
* @copyright 2014 Hunt Utilities Group, LLC
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version Release: 0.14.3
* @link http://dev.hugllc.com/index.php/Project:HUGnetLib
* @since 0.9.7
*/
class DriverVirtualTestClass extends \HUGnet\devices\inputTable\DriverVirtual
implements \HUGnet\devices\inputTable\DriverInterface
{
/**
* This is where the data for the driver is stored. This array must be
* put into all derivative classes, even if it is empty.
*/
protected $params = array(
"longName" => "Unknown Sensor",
"shortName" => "Unknown",
"unitType" => "asdf", /* This is for test value only */
"testParam" => "12345", /* This is for test value only */
"extraDefault" => array(2,3,5,7,11),
"extraText" => array("a","b","c","d","e"),
"extraDesc" => array("A","B","C","D","E"),
"extraValues" => array(5, 5, 5, 5, 5),
);
/**
* Gets the extra values
*
* @param int $index The extra index to use
*
* @return The extra value (or default if empty)
*/
public function getExtra($index)
{
return parent::getExtra($index);
}
/**
* Changes a raw reading into a output value
*
* @param int $A Output of the A to D converter
* @param float $deltaT The time delta in seconds between this record
* @param array &$data The data from the other sensors that were crunched
* @param mixed $prev The previous value for this sensor
*
* @return mixed The value in whatever the units are in the sensor
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getReading(
$A, $deltaT = 0, &$data = array(), $prev = null
) {
return null;
}
}
?>
| hugllc/HUGnetLib | test/suite/devices/inputTable/DriverVirtualTest.php | PHP | gpl-3.0 | 10,696 |
<?php
/**
* Display the upload transaction file screen
*
* @author Fabrice Douteaud <admin@clearbudget.net>
* @package snippets
* @access public
*/
/***********************************************************************
Copyright (C) 2008 Fabrice Douteaud (admin@clearbudget.net)
This file is part of ClearBudget.
ClearBudget 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.
ClearBudget 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 ClearBudget. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
//prevent direct access
if(!defined('ENGINEON')) die('Direct access forbidden');
?>
<h2><img src="style/icons/table_add.png"/> <?php echo $keys->pageTitle_UploadQif; ?></h2>
<form id="QIFUploadForm" enctype="multipart/form-data" action="" method="POST">
<div id="qifUploadError" style="display: none" class="error"><blockquote><?php echo $keys->error_UploadQif; ?>: <span id="qifUploadErrorText"></span></blockquote></div>
<table class="tableReport">
<tr>
<td colspan="3">
<span id="qifUploadLoading" style="display:none;"><?php echo $keys->text_pageUploadQifLoading; ?></span>
<span id="qifUploadResultCount" style="display:none; color: #3A7;"></span>
</td>
</tr>
<tr>
<td style="width: 350px">
<input name="MAX_FILE_SIZE" value="300000" type="hidden" />
<input name="action" id="action" value="uploadQifSubmit" type="hidden" />
<input name="datafile" id="fileToUpload" type="file" size="60"/>
</td>
<td style="width: 300px">
<?php echo $keys->text_dateFormat; ?>: <input type="radio" name="QIFLocaleType" id="QIFLocaleType" value="us" checked>MM/DD/YYYY <input type="radio" name="QIFLocaleType" id="QIFLocaleType" value="eu">DD/MM/YYYY
</td>
<td style="width: 150px">
<span class="jqUploader" id="jqUploader">
<button class="button" id="buttonUpload" onclick="return ajaxFileUpload();"><?php echo $keys->text_SendButton;?></button>
</span>
</td>
</td>
</tr>
<!--
<tr>
<td colspan="3"><small><?php echo $keys->text_qifFile; ?></small></td>
</tr>
-->
</table>
</form>
<div id="importDetails"></div>
<br/> | thunderace/clearbudget | snippets/uploadQif.php | PHP | gpl-3.0 | 2,711 |
<?php
namespace common\modules\prj\models;
use Yii;
/**
* This is the model class for table "{{%prj_burden_cost_base}}".
*
* @property string $prj_burden_cost_base_id
* @property string $cost_base
* @property string $description
* @property string $cost_base_type
* @property string $effective_from
* @property string $effective_to
* @property integer $priority
* @property integer $created_by
* @property string $creation_date
* @property integer $last_update_by
* @property string $last_update_date
* @property integer $company_id
*/
class PrjBurdenCostBase extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%prj_burden_cost_base}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['cost_base', 'created_by', 'last_update_by'], 'required'],
[['effective_from', 'effective_to', 'creation_date', 'last_update_date'], 'safe'],
[['priority', 'created_by', 'last_update_by', 'company_id'], 'integer'],
[['cost_base', 'cost_base_type'], 'string', 'max' => 25],
[['description'], 'string', 'max' => 255],
[['cost_base'], 'unique'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'prj_burden_cost_base_id' => Yii::t('app', 'Prj Burden Cost Base ID'),
'cost_base' => Yii::t('app', 'Cost Base'),
'description' => Yii::t('app', 'Description'),
'cost_base_type' => Yii::t('app', 'Cost Base Type'),
'effective_from' => Yii::t('app', 'Effective From'),
'effective_to' => Yii::t('app', 'Effective To'),
'priority' => Yii::t('app', 'Priority'),
'created_by' => Yii::t('app', 'Created By'),
'creation_date' => Yii::t('app', 'Creation Date'),
'last_update_by' => Yii::t('app', 'Last Update By'),
'last_update_date' => Yii::t('app', 'Last Update Date'),
'company_id' => Yii::t('app', 'Company ID'),
];
}
}
| zeddarn/yinoerp | _protected/common/modules/prj/models/PrjBurdenCostBase.php | PHP | gpl-3.0 | 2,128 |
<span class="fright">
<?php if($this->phpsession->get('menu_type') == FRONT_END_MENU):?>
<a class="button back" href="/dashboard/menu/<?php echo isset($lang) && $lang != '' ? $lang :$this->phpsession->get('current_menus_lang'); ?>"><em> </em>Quay lại trang Menu</a>
<?php endif;?>
<?php if($this->phpsession->get('menu_type') == BACK_END_MENU):?>
<a class="button back" href="/dashboard/menu-admin/<?php echo isset($lang) && $lang != '' ? $lang :$this->phpsession->get('current_menus_lang'); ?>" ><em> </em>Quay lại trang Menu</a>
<?php endif;?>
</span> | dzung2t/noithatgo | ci_app/modules/menus/views/admin/back-menu-nav.php | PHP | gpl-3.0 | 591 |
var express = require('express');
var router = express.Router();
var seminar = require('../controllers/seminar.controllers');
router.get('/', function(req, res) {
res.json({status: false, message: 'None API Implemented'});
});
router.get('/user/:id', function(req, res) {
seminar.get(req, res);
});
// router.get('/seminar/:id', function(req, res) {
// seminar.getById(req, res);
// });
router.get('/all', function(req, res) {
seminar.getAll(req, res);
});
router.post('/register', function(req, res) {
seminar.register(req, res);
});
router.delete('/delete', function(req, res) {
seminar.delete(req, res);
});
router.post('/attend', function(req, res) {
seminar.attend(req, res);
});
module.exports = router;
| Rajamuda/ittoday-2017 | api/routes/seminar.routes.js | JavaScript | gpl-3.0 | 733 |
#include "InputModels/SimpleGaussianModel.h"
#include "Keyboard.h"
#include "Polygon.h"
#include "math.h"
#include <cctype>
#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
using namespace std;
SimpleGaussianModel::SimpleGaussianModel(double xscale, double yscale, double corr) {
ysigma = xscale*0.5;
xsigma = yscale*0.5;
fixed_length = true;
SetCorrelation(corr);
}
void SimpleGaussianModel::SetCorrelation(double corr) {
if(corr < 0) corr = 0;
if(corr > 1) corr = 1;
correlation = corr;
correlation_complement = sqrt(1.0-correlation*correlation);
}
InputVector SimpleGaussianModel::RandomVector(const char* word, Keyboard& k) {
//it's wasteful to remake this every time but I had trouble making it a global member
boost::normal_distribution<> nd(0.0, 1.0);
boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > normal(generator, nd);
InputVector sigma;
double lastx = normal(), lasty = normal();
for(unsigned int i = 0; i < strlen(word); i++) {
Polygon p = k.GetKey(tolower(word[i]));
const double t = p.TopExtreme();
const double b = p.BottomExtreme();
const double r = p.RightExtreme();
const double l = p.LeftExtreme();
if(i > 0) {
lastx = lastx*correlation + normal()*correlation_complement;
lasty = lasty*correlation + normal()*correlation_complement;
}
const double x = lastx*xsigma*(r-l) + 0.5*(r+l);
const double y = lasty*ysigma*(t-b) + 0.5*(t+b);
sigma.AddPoint(x, y, double(i));
}
return sigma;
}
InputVector SimpleGaussianModel::PerfectVector(const char* word, Keyboard& k) {
const double tmp_xsigma = xsigma; xsigma = 0;
const double tmp_ysigma = ysigma; ysigma = 0;
InputVector sigma = RandomVector(word, k);
xsigma = tmp_xsigma;
ysigma = tmp_ysigma;
return sigma;
}
double SimpleGaussianModel::MarginalProbability( InputVector& sigma, const char* word, Keyboard& k) {
if(sigma.Length() != strlen(word)) {
return 0;
}
double probability = 1;
for(unsigned int i = 0; i < sigma.Length(); i++) {
const Polygon p = k.GetKey(word[i]);
const double r = p.RightExtreme();
const double l = p.LeftExtreme();
const double x = sigma.X(i);
const double xmu = 0.5*(r+l);
if(xsigma > 0) {
const double xsd = xsigma*(r-l);
probability *= (0.3989422804/xsd)*exp(-0.5*(pow((x-xmu)/xsd,2)));
}
else {
if(xmu != x) {
probability = 0;
break;
}
}
const double t = p.TopExtreme();
const double b = p.BottomExtreme();
const double y = sigma.Y(i);
const double ymu = 0.5*(t+b);
if(ysigma > 0) {
const double ysd = ysigma*(t-b);
probability *= (0.3989422804/ysd)*exp(-0.5*(pow((y-ymu)/ysd,2)));
}
else {
if(ymu != y) {
probability = 0;
break;
}
}
}
return probability;
}
double SimpleGaussianModel::Distance( InputVector& sigma, const char* word, Keyboard& k) {
if(sigma.Length() != strlen(word)) {
return 1;
}
double probability = 1;
if(xsigma > 0 && ysigma > 0) {
for(unsigned int i = 0; i < sigma.Length(); i++) {
const Polygon p = k.GetKey(word[i]);
if(xsigma > 0) {
const double r = p.RightExtreme();
const double l = p.LeftExtreme();
const double xsd = xsigma*(r-l);
probability *= 0.3989422804/xsd;
}
if(ysigma > 0) {
const double t = p.TopExtreme();
const double b = p.BottomExtreme();
const double ysd = ysigma*(t-b);
probability *= 0.3989422804/ysd;
}
}
}
return (probability - MarginalProbability(sigma, word, k))/probability;
}
double SimpleGaussianModel::VectorDistance(InputVector& vector1, InputVector& vector2) {
double d2 = 0;
for(unsigned int i = 0; i < vector1.Length(); i++) {
d2 += pow( vector1.X(i) - vector2.X(i), 2) + pow( vector1.Y(i) - vector2.Y(i), 2);
}
return sqrt(d2);
}
| sangaline/dodona | core/src/InputModels/SimpleGaussianModel.cpp | C++ | gpl-3.0 | 4,337 |
#!/usr/bin/env node
// Special Pythagorean triplet
var SUM = 1000;
var triplet = get_pythagorean_triplet_by_sum(SUM);
console.log(triplet[0] * triplet[1] * triplet[2]);
function get_pythagorean_triplet_by_sum(s) {
var s2 = Math.floor(SUM / 2);
var mlimit = Math.ceil(Math.sqrt(s2)) - 1;
for (var m = 2; m <= mlimit; m++) {
if (s2 % m == 0) {
var sm = Math.floor(s2 / m);
while (sm % 2 == 0) {
sm = Math.floor(sm / 2);
}
var k = m + 1;
if (m % 2 == 1) {
k = m + 2;
}
while (k < 2 * m && k <= sm) {
if (sm % k == 0 && gcd(k, m) == 1) {
var d = Math.floor(s2 / (k * m));
var n = k - m;
var a = d * (m * m - n * n);
var b = 2 * d * m * n;
var c = d * (m * m + n * n);
return [a, b, c];
}
k += 2;
}
}
}
return [0, 0, 0];
}
function gcd(int1, int2) {
if (int1 > int2) {
var tmp = int1;
int1 = int2;
int2 = tmp;
}
while (int1) {
var tmp = int1;
int1 = int2 % int1;
int2 = tmp;
}
return int2;
}
| iansealy/projecteuler | optimal/9.js | JavaScript | gpl-3.0 | 1,296 |
#include "Reseaux/RequetePartie/RequetePartie.hpp"
RequetePartie::RequetePartie(int tailleRequete, int numeroRequete)
: Requete(tailleRequete, 0)
{
numeroRequete = numeroRequete << 3;
data[0] = numeroRequete;
} | Aredhele/FreakyMonsters | client/src/Reseaux/RequetePartie/RequetePartie.cpp | C++ | gpl-3.0 | 215 |
<?php
use Phinx\Migration\AbstractMigration;
class NullableInvitationFrom extends AbstractMigration
{
/**
* Migrate Up.
*/
public function up()
{
$this->execute("ALTER TABLE invitations MODIFY sent_by INT(10) UNSIGNED DEFAULT NULL COMMENT 'The player who sent the invitation'");
}
/**
* Migrate Down.
*/
public function down()
{
}
}
| allejo/bzion | migrations/20160212221926_nullable_invitation_from.php | PHP | gpl-3.0 | 396 |
import ChatMessage from "phasecore/messagetypes/chatmessage";
interface DeepHistoryNewer {
discID: number;
messages: ChatMessage[];
newestID: number;
}
export default DeepHistoryNewer;
| popstarfreas/PhaseClient | app/node_modules/phasecore/messagetypes/deephistorynewer.ts | TypeScript | gpl-3.0 | 199 |
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<h1><?php echo L('sensor_LIST'); ?></h1>
</div>
</div>
<div class="row">
<?php if($this->session()->getUserLevel() == 3) : ?>
<div class="col-md-4 text-left">
<a href="javascript:void(0)" id="sensors_rescan" class="btn btn-primary">
<span class="fa fa-refresh btn-icon"></span><span class=""> <?php echo L('sensor_REFRESH_LIST');
?></span></a>
</div>
<?php endif; ?>
</div>
<?php if(isset($this->view->content->list )) : ?>
<br/>
<table class="table table-responsive table-condensed" id="sensor_list_table">
<thead>
<tr>
<th>ID</th>
<th><?php echo L('sensor_VALUE_NAME'); ?></th>
<th><?php echo L('sensor_VALUE_SI_NOTATION'); ?></th>
<th title="<?php echo L('sensor_VALUE_SI_NAME'); ?>"><?php echo L('sensor_VALUE_SI_NSHORT'); ?></th>
<th title="<?php echo L('sensor_VALUE_MIN_RANGE'); ?>"><?php echo L('sensor_VALUE_MIN'); ?></th>
<th title="<?php echo L('sensor_VALUE_MAX_RANGE'); ?>"><?php echo L('sensor_VALUE_MAX'); ?></th>
<th><?php echo L('sensor_VALUE_ERROR'); ?></th>
<th><span class="fa fa-tv"></span></th>
</tr>
</thead>
<tbody>
<?php
$cnt = 0;
foreach($this->view->content->list as $sensor_id => $item) :
$sensor_name = (string) preg_replace('/\-.*/i', '', $sensor_id);
$i = 0;
foreach($item->{'Values'} as $sensor_val_id => &$data) :
if (strlen($sensor_name) == 0)
{
continue;
}
$key = '' . $sensor_id . '#' . (int)$sensor_val_id;
?>
<tr class="row-sensor" data-sensor-id="<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?>">
<td>
<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?>
</td>
<td class="sensor-setup-valname">
<?php echo htmlspecialchars($data->value_name, ENT_QUOTES, 'UTF-8'); ?>
</td>
<td>
<?php echo htmlspecialchars($data->si_notation, ENT_QUOTES, 'UTF-8'); ?>
</td>
<td>
<?php echo htmlspecialchars($data->si_name, ENT_QUOTES, 'UTF-8'); ?>
</td>
<td>
<?php echo htmlspecialchars($data->{'Range'}->{'Min'}, ENT_QUOTES, 'UTF-8'); ?>
</td>
<td>
<?php echo htmlspecialchars($data->{'Range'}->{'Max'}, ENT_QUOTES, 'UTF-8'); ?>
</td>
<td>
<?php echo isset($data->error) ? htmlspecialchars($data->error, ENT_QUOTES, 'UTF-8') : '-'; ?>
</td>
<td>
<span class="glyphicon glyphicon-eye-open sensor-icon-btn" style="cursor:pointer;"></span> <span class="sensor-value"></span>
</td>
</tr>
<?php $i++; $cnt++; endforeach;
endforeach; ?>
</tbody>
<tfoot style="display: none;">
<tr>
<td colspan="8" id="sensors_msgs">
<?php if (!$cnt) : ?>
<div class="alert alert-info" role="alert">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo L('setup_MSG_NO_AVAILABLE_SENSORS'); ?>
</div>
<?php endif; ?>
</td>
</tr>
</tfoot>
</table>
<?php endif; ?>
</div>
| scratchduino/sdlab-frontend | app/views/sensors/view.all.tpl.php | PHP | gpl-3.0 | 2,954 |
# Copyright 2014-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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.
#
# Abydos 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 Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.tests.distance.test_distance_ncd_bwtrle.
This module contains unit tests for abydos.distance.NCDbwtrle
"""
import unittest
from abydos.distance import NCDbwtrle
class NCDbwtrleTestCases(unittest.TestCase):
"""Test compression distance functions.
abydos.distance.NCDbwtrle
"""
cmp = NCDbwtrle()
def test_ncd_bwtrle_dist(self):
"""Test abydos.distance.NCDbwtrle.dist."""
self.assertEqual(self.cmp.dist('', ''), 0)
self.assertGreater(self.cmp.dist('a', ''), 0)
self.assertGreater(self.cmp.dist('abcdefg', 'fg'), 0)
self.assertAlmostEqual(self.cmp.dist('abc', 'abc'), 0)
self.assertAlmostEqual(self.cmp.dist('abc', 'def'), 0.75)
self.assertAlmostEqual(
self.cmp.dist('banana', 'banane'), 0.57142857142
)
self.assertAlmostEqual(self.cmp.dist('bananas', 'bananen'), 0.5)
def test_ncd_bwtrle_sim(self):
"""Test abydos.distance.NCDbwtrle.sim."""
self.assertEqual(self.cmp.sim('', ''), 1)
self.assertLess(self.cmp.sim('a', ''), 1)
self.assertLess(self.cmp.sim('abcdefg', 'fg'), 1)
self.assertAlmostEqual(self.cmp.sim('abc', 'abc'), 1)
self.assertAlmostEqual(self.cmp.sim('abc', 'def'), 0.25)
self.assertAlmostEqual(self.cmp.sim('banana', 'banane'), 0.42857142857)
self.assertAlmostEqual(self.cmp.sim('bananas', 'bananen'), 0.5)
if __name__ == '__main__':
unittest.main()
| chrislit/abydos | tests/distance/test_distance_ncd_bwtrle.py | Python | gpl-3.0 | 2,159 |
# -*- coding: utf-8 -*-
# This file is part of BBFlux (BackBox XFCE -> FluxBox Menu Automatic Update Daemon).
#
# Copyright(c) 2010-2011 Simone Margaritelli
# evilsocket@gmail.com - evilsocket@backbox.org
# http://www.evilsocket.net
# http://www.backbox.org
#
# This file may be licensed under the terms of of the
# GNU General Public License Version 2 (the ``GPL'').
#
# Software distributed under the License is distributed
# on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
# express or implied. See the GPL for the specific language
# governing rights and limitations.
#
# You should have received a copy of the GPL along with this
# program. If not, go to http://www.gnu.org/licenses/gpl.html
# or write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import fnmatch
class IconParser:
__instance = None
def __init__(self):
self.cache = {}
def __findIcon( self, path, pattern ):
for root, dirnames, filenames in os.walk( path ):
for filename in fnmatch.filter( filenames, pattern ):
return os.path.join(root, filename)
return None
def getIconByName( self, name ):
name = name.replace( '.png', '' )
if name is None or name == '':
return None
if name[0] == '/':
return name
elif self.cache.has_key(name):
return self.cache[name]
else:
if os.path.exists( '/usr/share/pixmaps/' + name + '.png' ):
self.cache[name] = '/usr/share/pixmaps/' + name + '.png'
return '/usr/share/pixmaps/' + name + '.png'
elif os.path.exists( '/usr/share/pixmaps/' + name + '.xpm' ):
self.cache[name] = '/usr/share/pixmaps/' + name + '.xpm'
return '/usr/share/pixmaps/' + name + '.xpm'
else:
icon = self.__findIcon( '/usr/share/icons', name + '.png' )
if icon is not None:
self.cache[name] = icon
else:
icon = self.__findIcon( '/usr/share/icons', name + '.xpm' )
if icon is not None:
self.cache[name] = icon
return icon
@classmethod
def getInstance(cls):
if cls.__instance is None:
cls.__instance = IconParser()
return cls.__instance | evilsocket/BBFlux | parsers/IconParser.py | Python | gpl-3.0 | 2,214 |
// Events
document.onkeypress = function (e) {
e = e || window.event;
var key = e.key;
return keymap[key]();
};
// Mouse events
document.onmousemove = function (e) {
e = e || window.event;
lfo.frequency.value = e.clientX;
main_osc.frequency.value = e.clientY / 10;
changeBackgroundColor(lfo_amp.gain.value/3.125, e.clientY, e.clientX);
};
// Color events
var changeBackgroundColor = function(red, green, blue) {
document.body.style.backgroundColor = "rgb(" + red + "," + green + "," + blue + ")";
}; | ruckert/web_audio_experiments | synth007/events.js | JavaScript | gpl-3.0 | 534 |
import { Menu } from 'electron'
import menuActions from './actions'
import deviceItems from './devices'
import folderItems from './folders'
import { getDevicesWithConnections } from '../reducers/devices'
import { getFoldersWithStatus } from '../reducers/folders'
import { name, version } from '../../../package.json'
export default function buildMenu({
st,
state,
state: {
connected,
config,
},
}){
const devices = getDevicesWithConnections(state)
const folders = getFoldersWithStatus(state)
let menu = null
const actions = menuActions(st)
const sharedItems = [
{ label: `${name} ${version}`, enabled: false },
{ label: 'Restart Syncthing', click: actions.restart, accelerator: 'CommandOrControl+R' },
{ label: 'Quit Syncthing', click: actions.quit, accelerator: 'CommandOrControl+Q' },
]
if(connected && config.isSuccess){
menu = Menu.buildFromTemplate([
...folderItems(folders),
{ type: 'separator' },
...deviceItems(devices),
{ type: 'separator' },
{ label: 'Open...', click: actions.editConfig, accelerator: 'CommandOrControl+,' },
{ type: 'separator' },
...sharedItems,
])
}else{
menu = Menu.buildFromTemplate([
{ label: config.isFailed ? 'No config available' : 'Connection error', enabled: false },
...sharedItems,
])
}
return menu
}
| JodusNodus/syncthing-tray | app/main/menu/index.js | JavaScript | gpl-3.0 | 1,367 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test thorns.waves module.
"""
from __future__ import division, absolute_import, print_function
__author__ = "Marek Rudnicki"
import numpy as np
from numpy.testing import assert_equal
import thorns.waves as wv
def test_electrical_pulse_charge():
durations = [1, 1, 1]
amplitudes = [-1, 2, -1]
fs = 100
pulse = wv.electrical_pulse(
fs=fs,
amplitudes=amplitudes,
durations=durations,
charge=1
)
charge = np.sum(np.abs(pulse))/fs
assert_equal(charge, 1)
def test_electrical_amplitudes_2():
durations = [1, 0.5]
amplitudes = wv.electrical_amplitudes(
durations=durations,
polarity=1,
)
assert_equal(amplitudes, [0.5, -1])
def test_electrical_amplitudes_3():
durations = [0.5, 1, 0.5]
ratio = 0.3
polarity = 1
amplitudes = wv.electrical_amplitudes(
durations=durations,
polarity=polarity,
ratio=ratio
)
assert_equal(amplitudes, [0.3, -0.5, 0.7])
| timtammittee/thorns | tests/test_waves.py | Python | gpl-3.0 | 1,056 |
# -*- coding: utf-8 -*-
# Copyright (C) 2005 Osmo Salomaa
#
# 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 gaupol
from gi.repository import Gtk
class _TestPositionTransformDialog(gaupol.TestCase):
def run_dialog(self):
self.dialog.run()
self.dialog.destroy()
def test__on_response(self):
self.dialog.response(Gtk.ResponseType.OK)
class TestFrameTransformDialog(_TestPositionTransformDialog):
def setup_method(self, method):
self.application = self.new_application()
self.dialog = gaupol.FrameTransformDialog(
self.application.window, self.application)
self.dialog.show()
class TestTimeTransformDialog(_TestPositionTransformDialog):
def setup_method(self, method):
self.application = self.new_application()
self.dialog = gaupol.TimeTransformDialog(
self.application.window, self.application)
self.dialog.show()
| otsaloma/gaupol | gaupol/dialogs/test/test_position_transform.py | Python | gpl-3.0 | 1,527 |
package com.kinztech.os.network.codec.game.decode;
import com.kinztech.os.game.node.entity.player.Player;
import com.kinztech.os.network.protocol.PacketDefinition;
import com.kinztech.os.utilities.RSBuffer;
/**
* Created by Allen Kinzalow on 5/25/2015.
*/
public interface DecodedPacket {
void decode(Player player, RSBuffer in, PacketDefinition definition, int size);
}
| kinztechcom/OSRS-Server | src/com/kinztech/os/network/codec/game/decode/DecodedPacket.java | Java | gpl-3.0 | 382 |
import odoo.tests
@odoo.tests.common.at_install(False)
@odoo.tests.common.post_install(True)
class TestUi(odoo.tests.HttpCase):
def test_admin(self):
self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets", login="admin")
def test_demo(self):
self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets", login="demo")
def test_public(self):
self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets")
| ChawalitK/odoo | addons/website_event_sale/tests/test_ui.py | Python | gpl-3.0 | 731 |
<?php
$lang["config_address"] = "Company Address";
$lang["config_address_required"] = "Company address is a required field";
$lang["config_backup_button"] = "Backup";
$lang["config_backup_database"] = "Backup Database";
$lang["config_barcode_company"] = "Company Name";
$lang["config_barcode_configuration"] = "Barcode Configuration";
$lang["config_barcode_content"] = "Barcode Content";
$lang["config_barcode_first_row"] = "Row 1";
$lang["config_barcode_font"] = "Font";
$lang["config_barcode_height"] = "Height (px)";
$lang["config_barcode_id"] = "Item Id/Name";
$lang["config_barcode_info"] = "Barcode Configuration Information";
$lang["config_barcode_layout"] = "Barcode Layout";
$lang["config_barcode_name"] = "Name";
$lang["config_barcode_number"] = "UPC/EAN/ISBN";
$lang["config_barcode_number_in_row"] = "Number in row";
$lang["config_barcode_page_cellspacing"] = "Display page cellspacing";
$lang["config_barcode_page_width"] = "Display page width";
$lang["config_barcode_price"] = "Price";
$lang["config_barcode_quality"] = "Quality (1-100)";
$lang["config_barcode_second_row"] = "Row 2";
$lang["config_barcode_third_row"] = "Row 3";
$lang["config_barcode_type"] = "Barcode Type";
$lang["config_barcode_width"] = "Width (px)";
$lang["config_barcode_generate_if_empty"] = "Generate if empty";
$lang["config_initial_capital"] = "Initial Capital";
$lang["config_invoice_prefix"] = "Invoice Prefix";
$lang["config_company"] = "Company Name";
$lang["config_company_logo"] = "Company Logo";
$lang["config_company_required"] = "Company name is a required field";
$lang["config_company_website_url"] = "Company website is not a valid URL (http://...)";
$lang["config_currency_side"] = "Right side";
$lang["config_currency_symbol"] = "Currency Symbol";
$lang["config_custom1"] = "Custom Field 1";
$lang["config_custom10"] = "Custom Field 10";
$lang["config_custom2"] = "Custom Field 2";
$lang["config_custom3"] = "Custom Field 3";
$lang["config_custom4"] = "Custom Field 4";
$lang["config_custom5"] = "Custom Field 5";
$lang["config_custom6"] = "Custom Field 6";
$lang["config_custom7"] = "Custom Field 7";
$lang["config_custom8"] = "Custom Field 8";
$lang["config_custom9"] = "Custom Field 9";
$lang["config_decimal_point"] = "Decimal Point";
$lang["config_default_barcode_font_size_number"] = "The default barcode font size must be a number";
$lang["config_default_barcode_font_size_required"] = "The default barcode font size is a required field";
$lang["config_default_barcode_height_number"] = "The default barcode height must be a number";
$lang["config_default_barcode_height_required"] = "The default barcode height is a required field";
$lang["config_default_barcode_num_in_row_number"] = "The default barcode num in row must be a number";
$lang["config_default_barcode_num_in_row_required"] = "The default barcode num in row is a required field";
$lang["config_default_barcode_page_cellspacing_number"] = "The default barcode page cellspacing must be a number";
$lang["config_default_barcode_page_cellspacing_required"] = "The default barcode page cellspacing is a required field";
$lang["config_default_barcode_page_width_number"] = "The default barcode page width must be a number";
$lang["config_default_barcode_page_width_required"] = "The default barcode page width is a required field";
$lang["config_default_barcode_quality_number"] = "The default barcode quality must be a number";
$lang["config_default_barcode_quality_required"] = "The default barcode quality is a required field";
$lang["config_default_barcode_width_number"] = "The default barcode width must be a number";
$lang["config_default_barcode_width_required"] = "The default barcode width is a required field";
$lang["config_default_sales_discount"] = "Default Sales Discount %";
$lang["config_default_sales_discount_number"] = "The default sales discount must be a number";
$lang["config_default_sales_discount_required"] = "The default sales discount is a required field";
$lang["config_default_tax_rate"] = "Default Tax Rate %";
$lang["config_default_tax_rate_1"] = "Tax 1 Rate";
$lang["config_default_tax_rate_2"] = "Tax 2 Rate";
$lang["config_default_tax_rate_number"] = "The default tax rate must be a number";
$lang["config_default_tax_rate_required"] = "The default tax rate is a required field";
$lang["config_fax"] = "Fax";
$lang["config_general_configuration"] = "General Configuration";
$lang["config_info"] = "Store Configuration Information";
$lang["config_invoice_default_comments"] = "Default Invoice Comments";
$lang["config_invoice_email_message"] = "Invoice Email Template";
$lang["config_invoice_printer"] = "Invoice Printer";
$lang["config_jsprintsetup_required"] = "Warning! This disabled functionality will only work if you have the FireFox jsPrintSetup addon installed. Save anyway?";
$lang["config_language"] = "Language";
$lang["config_lines_per_page"] = "Lines Per Page";
$lang["config_lines_per_page_number"] = "";
$lang["config_lines_per_page_required"] = "The lines per page is a required field";
$lang["config_location_configuration"] = "Stock Locations";
$lang["config_location_info"] = "Location Configuration Information";
$lang["config_logout"] = "Don't you want to make a backup before logging out? Click [OK] to backup, [Cancel] to logout";
$lang["config_number_format"] = "Number Format";
$lang["config_phone"] = "Company Phone";
$lang["config_phone_required"] = "Company phone is a required field";
$lang["config_print_bottom_margin"] = "Margin Bottom";
$lang["config_print_bottom_margin_number"] = "The default bottom margin must be a number";
$lang["config_print_bottom_margin_required"] = "The default bottom margin is a required field";
$lang["config_print_footer"] = "Print Browser Footer";
$lang["config_print_header"] = "Print Browser Header";
$lang["config_print_left_margin"] = "Margin Left";
$lang["config_print_left_margin_number"] = "The default left margin must be a number";
$lang["config_print_left_margin_required"] = "The default left margin is a required field";
$lang["config_print_right_margin"] = "Margin Right";
$lang["config_print_right_margin_number"] = "The default right margin must be a number";
$lang["config_print_right_margin_required"] = "The default right margin is a required field";
$lang["config_print_silently"] = "Show Print Dialog";
$lang["config_print_top_margin"] = "Margin Top";
$lang["config_print_top_margin_number"] = "The default top margin must be a number";
$lang["config_print_top_margin_required"] = "The default top margin is a required field";
$lang["config_receipt_configuration"] = "Print Settings";
$lang["config_receipt_info"] = "Receipt Configuration Information";
$lang["config_receipt_printer"] = "Ticket Printer";
$lang["config_receipt_show_taxes"] = "Show Taxes";
$lang["config_receiving_calculate_average_price"] = "Calc avg. Price (Receiving)";
$lang["config_recv_invoice_format"] = "Receivings Invoice Format";
$lang["config_return_policy_required"] = "Return policy is a required field";
$lang["config_sales_invoice_format"] = "Sales Invoice Format";
$lang["config_saved_successfully"] = "Configuration saved successfully";
$lang["config_saved_unsuccessfully"] = "Configuration saved unsuccessfully";
$lang["config_show_total_discount"] = "Show total discount";
$lang["config_stock_location"] = "Stock location";
$lang["config_stock_location_duplicate"] = "Please use an unique location name";
$lang["config_stock_location_invalid_chars"] = "The stock location name can not contain '_'";
$lang["config_stock_location_required"] = "Stock location number is a required field";
$lang["config_tax_included"] = "Tax Included";
$lang["config_thousands_separator"] = "Thousands Separator";
$lang["config_timezone"] = "Timezone";
$lang["config_use_invoice_template"] = "Use invoice template";
$lang["config_website"] = "Website";
$lang["config_locale_configuration"] = "Localisation Configuration";
$lang["config_locale_info"] = "Localisation Configuration Information";
$lang["config_datetimeformat"] = "Date and Time format";
| fwahyudi17/ofiskita | pos/application/language/en/config_lang.php | PHP | gpl-3.0 | 8,009 |
/******************************************************************************
* The MIT License
*
* Copyright (c) 2011 LeafLabs, LLC.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*****************************************************************************/
/**
* @file board.cpp for STM32 Nucleo-F103RB
* @original author Grégoire Passault <g.passault@gmail.com>
* @brief Nucleo board file
* edited and tested by Matthias Diro, Release Date: 27.01.2015
* there are some solderings neccessary for complete compatibility
* consider the Nucleo User manual for:
* OSC clock: clock must be driven either from "MCO from ST-Link" or Oscillator from external PF0/PD0/PH0. Soldering is neccessary if board number is MB1136 C-01, see -> 5.7 OSC clock
* USART: If PA2/PA3 needed, solder bridges must be changed. see -> 5.8 USART communication
*/
//#include <board/board.h> // For this board's header file
//#include <wirish_types.h> // For stm32_pin_info and its contents
// (these go into PIN_MAP).
//#include "boards_private.h" // For PMAP_ROW(), which makes
// PIN_MAP easier to read.
#include <board/board.h>
#include <libmaple/gpio.h>
#include <libmaple/timer.h>
/* Roger Clark. Added next to includes for changes to Serial */
#include <libmaple/usart.h>
#include <HardwareSerial.h>
#include <wirish_debug.h>
#include <wirish_types.h>
// boardInit(): NUCLEO rely on some remapping
void boardInit(void) {
afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY); // relase PC3 and PC5 on nucleo
afio_remap(AFIO_REMAP_USART3_PARTIAL); // remap Serial2(USART3)PB10/PB11
// to PC10/PC11 -> don't forget to insert into gpio.h:
// AFIO_REMAP_USART3_PARTIAL = AFIO_MAPR_USART3_REMAP_PARTIAL
afio_remap(AFIO_REMAP_TIM2_FULL); // better PWM compatibility
afio_remap(AFIO_REMAP_TIM3_PARTIAL);// better PWM compatibility
}
/*
namespace wirish {
namespace priv {
static stm32f1_rcc_pll_data pll_data = {RCC_PLLMUL_9};
rcc_clk w_board_pll_in_clk = RCC_CLK_HSI;
rcc_pll_cfg w_board_pll_cfg = {RCC_PLLSRC_HSI_DIV_2, &pll_data};
}
}
*/
// Pin map: this lets the basic I/O functions (digitalWrite(),
// analogRead(), pwmWrite()) translate from pin numbers to STM32
// peripherals.
//
// PMAP_ROW() lets us specify a row (really a struct stm32_pin_info)
// in the pin map. Its arguments are:
//
// - GPIO device for the pin (&gpioa, etc.)
// - GPIO bit for the pin (0 through 15)
// - Timer device, or NULL if none
// - Timer channel (1 to 4, for PWM), or 0 if none
// - ADC device, or NULL if none
// - ADC channel, or ADCx if none
// gpioX, PINbit, TIMER/NULL, timerch/0, &adc1/NULL, adcsub/0
// gpioX, TIMER/NULL, &adc1/NULL, PINbit, timerch/0, adcsub/0
// 0 1 2 3 4 5
// 0 3 1 4 2 5
// 0 1 3 4 2 5
// 0 1 2 4 2 5
extern const stm32_pin_info PIN_MAP[BOARD_NR_GPIO_PINS] = {
/* Arduino-like header, right connectors */
{&gpioa, NULL, &adc1, 3, 0, 3}, /* D0/PA3 */
{&gpioa, NULL, &adc1, 2, 0, 2}, /* D1/PA2 */
{&gpioa, &timer1, NULL, 10, 3, ADCx}, /* D2/PA10 */
{&gpiob, &timer2, NULL, 3, 2, ADCx}, /* D3/PB3 */
{&gpiob, &timer3, NULL, 5, 2, ADCx}, /* D4/PB5 */
{&gpiob, &timer3, NULL, 4, 1, ADCx}, /* D5/PB4 */
{&gpiob, &timer2, NULL, 10, 3, ADCx}, /* D6/PB10 */
{&gpioa, &timer1, NULL, 8, 1, ADCx}, /* D7/PA8 */
{&gpioa, &timer1, NULL, 9, 2, ADCx}, /* D8/PA9 */
{&gpioc, NULL, NULL, 7, 0, ADCx}, /* D9/PC7 */
{&gpiob, &timer4, NULL, 6, 1, ADCx}, /* D10/PB6 */
{&gpioa, NULL, &adc1, 7, 0, 7}, /* D11/PA7 */
{&gpioa, NULL, &adc1, 6, 0, 6}, /* D12/PA6 */
{&gpioa, NULL, NULL, 5, 0, ADCx}, /* D13/PA5 LED - no &adc12_IN5 !*/
{&gpiob, &timer4, NULL, 9, 4, ADCx}, /* D14/PB9 */
{&gpiob, &timer4, NULL, 8, 3, ADCx}, /* D15/PB8 */
{&gpioa, NULL, &adc1, 0, 0, 0}, /* D16/A0/PA0 */
{&gpioa, NULL, &adc1, 1, 0, 1}, /* D17/A1/PA1 */
{&gpioa, NULL, &adc1, 4, 0, 4}, /* D18/A2/PA4 */
{&gpiob, &timer3, &adc1, 0, 3, 8}, /* D19/A3/PB0 */
{&gpioc, NULL, &adc1, 1, 0, 11}, /* D20/A4/PC1 */
{&gpioc, NULL, &adc1, 0, 0, 10}, /* D21/A5/PC0 */
{&gpioc, NULL, NULL, 10, 0, ADCx}, /* D22/PC10 */
{&gpioc, NULL, NULL, 12, 0, ADCx}, /* D23/PC12 */
{&gpiob, &timer4, NULL, 7, 2, ADCx}, /* D24/PB7 */
{&gpioc, NULL, NULL, 13, 0, ADCx}, /* D25/PC13 USER BLUE BUTTON */
{&gpioc, NULL, NULL, 14, 0, ADCx}, /* D26/PC14 */
{&gpioc, NULL, NULL, 15, 0, ADCx}, /* D27/PC15 */
{&gpioc, NULL, &adc1, 2, 0, 12}, /* D28/PC2 */
{&gpioc, NULL, &adc1, 3, 0, 13}, /* D29/PC3 */
{&gpioc, NULL, NULL, 11, 0, ADCx}, /* D30/PC11 */
{&gpiod, NULL, NULL, 2, 0, ADCx}, /* D31/PD2 */
{&gpioc, NULL, NULL, 9, 0, ADCx}, /* D32/PC9 */
{&gpioc, NULL, NULL, 8, 0, ADCx}, /* D33/PC8 */
{&gpioc, NULL, NULL, 6, 0, ADCx}, /* D34/PC6 */
{&gpioc, NULL, &adc1, 5, 0, 15}, /* D35/PC5 */
{&gpioa, NULL, NULL, 12, 0, ADCx}, /* D36/PA12 */
{&gpioa, &timer1, NULL, 11, 4, ADCx}, /* D37/PA11 */
{&gpiob, NULL, NULL, 12, 0, ADCx}, /* D38/PB12 */
{&gpiob, &timer2, NULL, 11, 4, ADCx}, /* D39/PB11 PWM-not working?*/
{&gpiob, NULL, NULL, 2, 0, ADCx}, /* D40/PB2 BOOT1 !!*/
{&gpiob, &timer3, &adc1, 1, 4, 9}, /* D41/PB1 */
{&gpiob, NULL, NULL, 15, 0, ADCx}, /* D42/PB15 */
{&gpiob, NULL, NULL, 14, 0, ADCx}, /* D43/PB14 */
{&gpiob, NULL, NULL, 13, 0, ADCx}, /* D44/PB13 */
{&gpioc, NULL, &adc1, 4, 0, 14}, /* D45/PC4 */
// PMAP_ROW(&gpioa, 13, NULL, 0, NULL, ADCx), /* D41/PA13 do not use*/
// PMAP_ROW(&gpioa, 14, NULL, 0, NULL, ADCx), /* D42/PA14 do not use*/
// PMAP_ROW(&gpioa, 15, &timer2, 1, NULL, ADCx), /* D43/PA15 do not use*/
};
// Array of pins you can use for pwmWrite(). Keep it in Flash because
// it doesn't change, and so we don't waste RAM.
extern const uint8 boardPWMPins[] __FLASH__ = {
2,3,5,6,7,8,10,14,15,19,24,37,39,41
};
// Array of pins you can use for analogRead().
extern const uint8 boardADCPins[] __FLASH__ = {
0,1,11,12,16,17,18,19,20,21,28,29,35,41,45
};
// Array of pins that the board uses for something special. Other than
// the button and the LED, it's usually best to leave these pins alone
// unless you know what you're doing.
/* remappings Infos
*************************************
Bit 12 TIM4_REMAP: TIM4 remapping
This bit is set and cleared by software. It controls the mapping of TIM4 channels 1 to 4 onto
the GPIO ports.
0: No remap (TIM4_CH1/PB6, TIM4_CH2/PB7, TIM4_CH3/PB8, TIM4_CH4/PB9)
1: Full remap (TIM4_CH1/PD12, TIM4_CH2/
*************************************
Bits 11:10 TIM3_REMAP[1:0]: TIM3 remapping
These bits are set and cleared by software. They control the mapping of TIM3 channels 1 to
4 on the GPIO ports.
00: No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1)
01: Not used
10: Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1)
11: Full remap (CH1/PC6, CH2/PC7, CH3/PC8, CH4/PC9)
Note: TIM3_ETR on PE0 is not re-mapped.
*************************************
Bits 9:8 TIM2_REMAP[1:0]: TIM2 remapping
These bits are set and cleared by software. They control the mapping of TIM2 channels 1 to
4 and external trigger (ETR) on the GPIO ports.
00: No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3)
01: Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3)
10: Partial remap (CH1/ETR/PA0, CH2/PA1, CH3/PB10, CH4/PB11)
11: Full remap (CH1/ETR/PA15, CH2/PB3, CH3/PB10, CH4/PB11)
*************************************
Bits 7:6 TIM1_REMAP[1:0]: TIM1 remapping
These bits are set and cleared by software. They control the mapping of TIM1 channels 1 to
4, 1N to 3N, external trigger (ETR) and Break input (BKIN) on the GPIO ports.
00: No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12,
CH1N/PB13, CH2N/PB14, CH3N/PB15)
01: Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6,
CH1N/PA7, CH2N/PB0, CH3N/PB1)
10: not used
11: Full remap (ETR/PE7, CH1/PE9, CH2/PE11, CH3/PE13, CH4/PE14, BKIN/PE15,
CH1N/PE8, CH2N/PE10, CH3N/PE12)
*************************************
Bits 5:4 USART3_REMAP[1:0]: USART3 remapping
These bits are set and cleared by software. They control the mapping of USART3 CTS,
RTS,CK,TX and RX alternate functions on the GPIO ports.
00: No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14)
01: Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14)
10: not used
11: Full remap (TX/PD8, RX/PD9, CK/PD10, CTS/PD11, RTS/PD12)
*************************************
Bit 3 USART2_REMAP: USART2 remapping
This bit is set and cleared by software. It controls the mapping of USART2 CTS, RTS,CK,TX
and RX alternate functions on the GPIO ports.
0: No remap (CTS/PA0, RTS/PA1, TX/PA2, RX/PA3, CK/PA4)
1: Remap (CTS/PD3, RTS/PD4, TX/PD5, RX/PD6, CK/PD7)
*************************************
Bit 2 USART1_REMAP: USART1 remapping
This bit is set and cleared by software. It controls the mapping of USART1 TX and RX
alternate functions on the GPIO ports.
0: No remap (TX/PA9, RX/PA10)
1: Remap (TX/PB6, RX/PB7)
*************************************
Bit 1 I2C1_REMAP: I2C1 remapping
This bit is set and cleared by software. It controls the mapping of I2C1 SCL and SDA
alternate functions on the GPIO ports.
0: No remap (SCL/PB6, SDA/PB7)
1: Remap (SCL/PB8, SDA/PB9)
*************************************
Bit 0 SPI1_REMAP: SPI1 remapping
This bit is set and cleared by software. It controls the mapping of SPI1 NSS, SCK, MISO,
MOSI alternate functions on the GPIO ports.
0: No remap (NSS/PA4, SCK/PA5, MISO/PA6, MOSI/PA7)
1: Remap (NSS/PA15, SCK/PB3, MISO/PB4, MOSI/PB5)
*/
/*
* Roger Clark
*
* 2015/05/28
*
* Moved definitions for Hardware Serial devices from HardwareSerial.cpp so that each board can define which Arduino "Serial" instance
* Maps to which hardware serial port on the microprocessor
*/
#ifdef SERIAL_USB
DEFINE_HWSERIAL(Serial1, 1);
DEFINE_HWSERIAL(Serial2, 2);
DEFINE_HWSERIAL(Serial3, 3);
#else
DEFINE_HWSERIAL(Serial, 3);// Use HW Serial 2 as "Serial"
DEFINE_HWSERIAL(Serial1, 2);
DEFINE_HWSERIAL(Serial2, 1);
#endif | AtDinesh/Arduino_progs | Arduino_STM32/STM32F1/variants/nucleo_f103rb/board.cpp | C++ | gpl-3.0 | 11,487 |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
exports.__esModule = true;
var communication_1 = require("../../bibliotheque/communication");
var TypeMessageChat;
(function (TypeMessageChat) {
TypeMessageChat[TypeMessageChat["COM"] = 0] = "COM";
TypeMessageChat[TypeMessageChat["TRANSIT"] = 1] = "TRANSIT";
TypeMessageChat[TypeMessageChat["AR"] = 2] = "AR";
TypeMessageChat[TypeMessageChat["ERREUR_CONNEXION"] = 3] = "ERREUR_CONNEXION";
TypeMessageChat[TypeMessageChat["ERREUR_EMET"] = 4] = "ERREUR_EMET";
TypeMessageChat[TypeMessageChat["ERREUR_DEST"] = 5] = "ERREUR_DEST";
TypeMessageChat[TypeMessageChat["ERREUR_TYPE"] = 6] = "ERREUR_TYPE";
TypeMessageChat[TypeMessageChat["INTERDICTION"] = 7] = "INTERDICTION";
})(TypeMessageChat = exports.TypeMessageChat || (exports.TypeMessageChat = {}));
var MessageChat = (function (_super) {
__extends(MessageChat, _super);
function MessageChat() {
return _super !== null && _super.apply(this, arguments) || this;
}
MessageChat.prototype.net = function () {
var msg = this.enJSON();
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
return JSON.stringify({
type: TypeMessageChat[msg.type],
date: (new Date(msg.date)).toLocaleString("fr-FR", options),
de: msg.emetteur,
à: msg.destinataire,
contenu: msg.contenu
});
};
return MessageChat;
}(communication_1.Message));
exports.MessageChat = MessageChat;
function creerMessageErreurConnexion(emetteur, messageErreur) {
return new MessageChat({
"emetteur": emetteur,
"destinataire": emetteur,
"type": TypeMessageChat.ERREUR_CONNEXION,
"contenu": messageErreur,
"date": new Date()
});
}
exports.creerMessageErreurConnexion = creerMessageErreurConnexion;
function creerMessageCommunication(emetteur, destinataire, texte) {
return new MessageChat({
"emetteur": emetteur,
"destinataire": destinataire,
"type": TypeMessageChat.COM,
"contenu": texte,
"date": new Date()
});
}
exports.creerMessageCommunication = creerMessageCommunication;
function creerMessageRetourErreur(original, codeErreur, messageErreur) {
return new MessageChat({
"emetteur": original.enJSON().emetteur,
"destinataire": original.enJSON().destinataire,
"type": codeErreur,
"contenu": messageErreur,
"date": original.enJSON().date
});
}
exports.creerMessageRetourErreur = creerMessageRetourErreur;
function creerMessageTransit(msg) {
return new MessageChat({
"emetteur": msg.enJSON().emetteur,
"destinataire": msg.enJSON().destinataire,
"type": TypeMessageChat.TRANSIT,
"contenu": msg.enJSON().contenu,
"date": msg.enJSON().date
});
}
exports.creerMessageTransit = creerMessageTransit;
function creerMessageAR(msg) {
return new MessageChat({
"emetteur": msg.enJSON().emetteur,
"destinataire": msg.enJSON().destinataire,
"type": TypeMessageChat.AR,
"contenu": msg.enJSON().contenu,
"date": msg.enJSON().date
});
}
exports.creerMessageAR = creerMessageAR;
var SommetChat = (function (_super) {
__extends(SommetChat, _super);
function SommetChat() {
return _super !== null && _super.apply(this, arguments) || this;
}
SommetChat.prototype.net = function () {
var msg = this.enJSON();
return JSON.stringify({
nom: msg.pseudo + "(" + msg.id + ")"
});
};
return SommetChat;
}(communication_1.Sommet));
exports.SommetChat = SommetChat;
function fabriqueSommetChat(s) {
return new SommetChat(s);
}
exports.fabriqueSommetChat = fabriqueSommetChat;
function creerAnneauChat(noms) {
var assembleur = new communication_1.AssemblageReseauEnAnneau(noms.length);
noms.forEach(function (nom, i, tab) {
var s = new SommetChat({ id: "id-" + i, pseudo: tab[i] });
assembleur.ajouterSommet(s);
});
return assembleur.assembler();
}
exports.creerAnneauChat = creerAnneauChat;
//# sourceMappingURL=chat.js.map | hgrall/merite | src/communication/v0/typeScript/build/tchat/commun/chat.js | JavaScript | gpl-3.0 | 4,687 |
'use strict';
var CONFIGURATOR = {
'releaseDate': 1456739663000, // 2016.02.29 - new Date().getTime() or "date +%s"000
'firmwareVersionEmbedded': [3, 8, 8], // version of firmware that ships with the app, dont forget to also update initialize_configuration_objects switch !
'firmwareVersionLive': 0, // version number in single uint16 [8bit major][4bit][4bit] fetched from mcu
'activeProfile': 0, // currently active profile on tx module (each profile can correspond to different BIND_DATA)
'defaultProfile': 0, // current default profile setting on tx module
'connectingToRX': false, // indicates if TX is trying to connect to RX
'readOnly': false // indicates if data can be saved to eeprom
};
var STRUCT_PATTERN,
TX_CONFIG,
RX_CONFIG,
BIND_DATA;
// live PPM data
var PPM = {
ppmAge: 0,
channels: Array(16)
};
var RX_SPECIAL_PINS = [];
var NUMBER_OF_OUTPUTS_ON_RX = 0;
var RX_FAILSAFE_VALUES = [];
// pin_map "helper" object (related to pin/port map of specific units)
var PIN_MAP = {
0x20: 'PPM',
0x21: 'RSSI',
0x22: 'SDA',
0x23: 'SCL',
0x24: 'RXD',
0x25: 'TXD',
0x26: 'ANALOG',
0x27: 'Packet loss - Beeper', // LBEEP
0x28: 'Spektrum satellite', // spektrum satellite output
0x29: 'SBUS',
0x2A: 'SUMD',
0x2B: 'Link Loss Indication'
};
// 0 = default 433
// 1 = RFMXX_868
// 2 = RFMXX_915
var frequencyLimits = {
min: null,
max: null,
minBeacon: null,
maxBeacon: null
};
function initializeFrequencyLimits(rfmType) {
switch (rfmType) {
case 0:
frequencyLimits.min = 413000000;
frequencyLimits.max = 463000000;
frequencyLimits.minBeacon = 413000000;
frequencyLimits.maxBeacon = 463000000;
break;
case 1:
frequencyLimits.min = 848000000;
frequencyLimits.max = 888000000;
frequencyLimits.minBeacon = 413000000;
frequencyLimits.maxBeacon = 888000000;
break;
case 2:
frequencyLimits.min = 895000000;
frequencyLimits.max = 935000000;
frequencyLimits.minBeacon = 413000000;
frequencyLimits.maxBeacon = 935000000;
break;
default:
frequencyLimits.min = 0;
frequencyLimits.max = 0;
frequencyLimits.minBeacon = 0;
frequencyLimits.maxBeacon = 0;
}
}
function initialize_configuration_objects(version) {
switch (version >> 4) {
case 0x38:
case 0x37:
CONFIGURATOR.readOnly = false;
var TX = [
{'name': 'rfm_type', 'type': 'u8'},
{'name': 'max_frequency', 'type': 'u32'},
{'name': 'flags', 'type': 'u32'},
{'name': 'chmap', 'type': 'array', 'of': 'u8', 'length': 16}
];
var BIND = [
{'name': 'version', 'type': 'u8'},
{'name': 'serial_baudrate', 'type': 'u32'},
{'name': 'rf_frequency', 'type': 'u32'},
{'name': 'rf_magic', 'type': 'u32'},
{'name': 'rf_power', 'type': 'u8'},
{'name': 'rf_channel_spacing', 'type': 'u8'},
{'name': 'hopchannel', 'type': 'array', 'of': 'u8', 'length': 24},
{'name': 'modem_params', 'type': 'u8'},
{'name': 'flags', 'type': 'u8'}
];
var RX = [
{'name': 'rx_type', 'type': 'u8'},
{'name': 'pinMapping', 'type': 'array', 'of': 'u8', 'length': 13},
{'name': 'flags', 'type': 'u8'},
{'name': 'RSSIpwm', 'type': 'u8'},
{'name': 'beacon_frequency', 'type': 'u32'},
{'name': 'beacon_deadtime', 'type': 'u8'},
{'name': 'beacon_interval', 'type': 'u8'},
{'name': 'minsync', 'type': 'u16'},
{'name': 'failsafe_delay', 'type': 'u8'},
{'name': 'ppmStopDelay', 'type': 'u8'},
{'name': 'pwmStopDelay', 'type': 'u8'}
];
break;
case 0x36:
CONFIGURATOR.readOnly = true;
var TX = [
{'name': 'rfm_type', 'type': 'u8'},
{'name': 'max_frequency', 'type': 'u32'},
{'name': 'flags', 'type': 'u32'}
];
var BIND = [
{'name': 'version', 'type': 'u8'},
{'name': 'serial_baudrate', 'type': 'u32'},
{'name': 'rf_frequency', 'type': 'u32'},
{'name': 'rf_magic', 'type': 'u32'},
{'name': 'rf_power', 'type': 'u8'},
{'name': 'rf_channel_spacing', 'type': 'u8'},
{'name': 'hopchannel', 'type': 'array', 'of': 'u8', 'length': 24},
{'name': 'modem_params', 'type': 'u8'},
{'name': 'flags', 'type': 'u8'}
];
var RX = [
{'name': 'rx_type', 'type': 'u8'},
{'name': 'pinMapping', 'type': 'array', 'of': 'u8', 'length': 13},
{'name': 'flags', 'type': 'u8'},
{'name': 'RSSIpwm', 'type': 'u8'},
{'name': 'beacon_frequency', 'type': 'u32'},
{'name': 'beacon_deadtime', 'type': 'u8'},
{'name': 'beacon_interval', 'type': 'u8'},
{'name': 'minsync', 'type': 'u16'},
{'name': 'failsafe_delay', 'type': 'u8'},
{'name': 'ppmStopDelay', 'type': 'u8'},
{'name': 'pwmStopDelay', 'type': 'u8'}
];
break;
default:
return false;
}
STRUCT_PATTERN = {'TX_CONFIG': TX, 'RX_CONFIG': RX, 'BIND_DATA': BIND};
if (CONFIGURATOR.readOnly) {
GUI.log(chrome.i18n.getMessage('running_in_compatibility_mode'));
}
return true;
}
function read_firmware_version(num) {
var data = {'str': undefined, 'first': 0, 'second': 0, 'third': 0};
data.first = num >> 8;
data.str = data.first + '.';
data.second = ((num >> 4) & 0x0f);
data.str += data.second + '.';
data.third = num & 0x0f;
data.str += data.third;
return data;
}
| remspoor/openLRSng-configurator | js/data_storage.js | JavaScript | gpl-3.0 | 6,310 |
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'msf/core/payload/transport_config'
require 'msf/core/handler/reverse_http'
require 'msf/core/payload/windows/x64/meterpreter_loader'
require 'msf/base/sessions/meterpreter_x64_win'
require 'msf/base/sessions/meterpreter_options'
require 'rex/payloads/meterpreter/config'
module Metasploit4
CachedSize = 1107014
include Msf::Payload::TransportConfig
include Msf::Payload::Windows
include Msf::Payload::Single
include Msf::Payload::Windows::MeterpreterLoader_x64
include Msf::Sessions::MeterpreterOptions
def initialize(info = {})
super(merge_info(info,
'Name' => 'Windows Meterpreter Shell, Reverse HTTP Inline (x64)',
'Description' => 'Connect back to attacker and spawn a Meterpreter shell',
'Author' => [ 'OJ Reeves' ],
'License' => MSF_LICENSE,
'Platform' => 'win',
'Arch' => ARCH_X64,
'Handler' => Msf::Handler::ReverseHttp,
'Session' => Msf::Sessions::Meterpreter_x64_Win
))
register_options([
OptString.new('EXTENSIONS', [false, "Comma-separate list of extensions to load"]),
], self.class)
end
def generate
stage_meterpreter(true) + generate_config
end
def generate_config(opts={})
opts[:uuid] ||= generate_payload_uuid
opts[:stageless] = true
# create the configuration block
config_opts = {
arch: opts[:uuid].arch,
exitfunk: datastore['EXITFUNC'],
expiration: datastore['SessionExpirationTimeout'].to_i,
uuid: opts[:uuid],
transports: [transport_config_reverse_http(opts)],
extensions: (datastore['EXTENSIONS'] || '').split(',')
}
# create the configuration instance based off the parameters
config = Rex::Payloads::Meterpreter::Config.new(config_opts)
# return the binary version of it
config.to_b
end
end
| cSploit/android.MSF | modules/payloads/singles/windows/x64/meterpreter_reverse_http.rb | Ruby | gpl-3.0 | 2,014 |
/* jshint node: true */
module.exports = function(grunt) {
"use strict";
var theme = grunt.option( 'theme', 'blue' );
var out = 'blue';
var lessFiles = [
'base',
'autocomplete_tagging',
'embed_item',
'iphone',
'masthead',
'library',
'trackster',
'circster',
'jstree'
];
var _ = grunt.util._;
var fmt = _.sprintf;
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
// Create sprite images and .less files
sprite : {
options: {
algorithm: 'binary-tree'
},
'history-buttons': {
src: '../images/history-buttons/*.png',
destImg: fmt( '%s/sprite-history-buttons.png', out ),
destCSS: fmt( '%s/sprite-history-buttons.less', out )
},
'history-states': {
src: '../images/history-states/*.png',
destImg: fmt( '%s/sprite-history-states.png', out ),
destCSS: fmt( '%s/sprite-history-states.less', out )
},
'fugue': {
src: '../images/fugue/*.png',
destImg: fmt( '%s/sprite-fugue.png', out ),
destCSS: fmt( '%s/sprite-fugue.less', out )
}
},
// Compile less files
less: {
options: {
compress: true,
paths: [ out ]
},
dist: {
files: _.reduce( lessFiles, function( d, s ) {
d[ fmt( '%s/%s.css', out, s ) ] = [ fmt( 'src/less/%s.less', s ) ]; return d;
}, {} )
}
},
// remove tmp files
clean: {
clean : [ fmt('%s/tmp-site-config.less', out) ]
}
});
// Write theme variable for less
grunt.registerTask('less-site-config', 'Write site configuration for less', function() {
grunt.file.write( fmt('%s/tmp-site-config.less', out), fmt( "@theme-name: %s;", theme ) );
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-spritesmith');
grunt.loadNpmTasks('grunt-contrib-clean');
// Default task.
grunt.registerTask('default', ['sprite', 'less-site-config', 'less', 'clean']);
};
| mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/static/style/Gruntfile.js | JavaScript | gpl-3.0 | 2,103 |
package pl.llp.aircasting.screens.common.base;
import android.app.ProgressDialog;
/**
* Created by IntelliJ IDEA.
* User: obrok
* Date: 1/16/12
* Time: 12:03 PM
*/
public interface ActivityWithProgress {
public static final int SPINNER_DIALOG = 6355;
public ProgressDialog showProgressDialog(int progressStyle, SimpleProgressTask task);
public void hideProgressDialog();
}
| HabitatMap/AirCastingAndroidClient | src/main/java/pl/llp/aircasting/screens/common/base/ActivityWithProgress.java | Java | gpl-3.0 | 394 |
/**
* This file is part of MythTV Android Frontend
*
* MythTV Android Frontend 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.
*
* MythTV Android Frontend 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 MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>.
*
* This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/>
*/
package org.mythtv.client.ui.preferences;
import org.mythtv.R;
import org.mythtv.client.ui.AbstractMythtvFragmentActivity;
import org.mythtv.client.ui.preferences.LocationProfile.LocationType;
import org.mythtv.db.preferences.PlaybackProfileConstants;
import org.mythtv.db.preferences.PlaybackProfileDaoHelper;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
* @author Daniel Frey
*
*/
public class PlaybackProfileEditor extends AbstractMythtvFragmentActivity {
private static final String TAG = PlaybackProfileEditor.class.getSimpleName();
private PlaybackProfileDaoHelper mPlaybackProfileDaoHelper = PlaybackProfileDaoHelper.getInstance();
private PlaybackProfile profile;
@Override
public void onCreate( Bundle savedInstanceState ) {
Log.v( TAG, "onCreate : enter" );
super.onCreate( savedInstanceState );
setContentView( this.getLayoutInflater().inflate( R.layout.preference_playback_profile_editor, null ) );
setupSaveButtonEvent( R.id.btnPreferencePlaybackProfileSave );
setupCancelButtonEvent( R.id.btnPreferencePlaybackProfileCancel );
int id = getIntent().getIntExtra( PlaybackProfileConstants._ID, -1 );
profile = mPlaybackProfileDaoHelper.findOne( this, (long) id );
if( null == profile ) {
profile = new PlaybackProfile();
profile.setId( id );
profile.setType( LocationType.valueOf( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_TYPE ) ) );
profile.setName( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_NAME ) );
profile.setWidth( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_WIDTH, -1 ) );
profile.setHeight( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_HEIGHT, -1 ) );
profile.setVideoBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_BITRATE, -1 ) );
profile.setAudioBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_AUDIO_BITRATE, -1 ) );
profile.setAudioSampleRate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SAMPLE_RATE, -1 ) );
profile.setSelected( 0 != getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SELECTED, 0 ) );
}
setUiFromPlaybackProfile();
Log.v( TAG, "onCreate : exit" );
}
// internal helpers
private void setUiFromPlaybackProfile() {
Log.v( TAG, "setUiFromPlaybackProfile : enter" );
setName( profile.getName() );
setWidth( "" + profile.getWidth() );
setHeight( "" + profile.getHeight() );
setVideoBitrate( "" + profile.getVideoBitrate() );
setAudioBitrate( "" + profile.getAudioBitrate() );
setSampleRate( "" + profile.getAudioSampleRate() );
Log.v( TAG, "setUiFromPlaybackProfile : exit" );
}
private final String getName() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_name );
}
private final void setName( String name ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_name, name );
}
private final String getWidth() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_width );
}
private final void setWidth( String width ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_width, width );
}
private final String getHeight() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_height );
}
private final void setHeight( String height ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_height, height );
}
private final String getVideoBitrate() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate );
}
private final void setVideoBitrate( String videoBitrate ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate, videoBitrate );
}
private final String getAudioBitrate() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate );
}
private final void setAudioBitrate( String audioBitrate ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate, audioBitrate );
}
private final String getSampleRate() {
return getTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate );
}
private final void setSampleRate( String sampleRate ) {
setTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate, sampleRate );
}
private final String getTextBoxText( int textBoxViewId ) {
final EditText text = (EditText) findViewById( textBoxViewId );
return text.getText().toString();
}
private final void setTextBoxText( int textBoxViewId, String text ) {
final EditText textBox = (EditText) findViewById( textBoxViewId );
textBox.setText( text );
}
private final void setupSaveButtonEvent( int buttonViewId ) {
Log.v( TAG, "setupSaveButtonEvent : enter" );
final Button button = (Button) this.findViewById( buttonViewId );
button.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Log.v( TAG, "setupSaveButtonEvent.onClick : enter" );
saveAndExit();
Log.v( TAG, "setupSaveButtonEvent.onClick : exit" );
}
});
Log.v( TAG, "setupSaveButtonEvent : exit" );
}
private final void setupCancelButtonEvent( int buttonViewId ) {
Log.v( TAG, "setupCancelButtonEvent : enter" );
final Button button = (Button) this.findViewById( buttonViewId );
button.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Log.v( TAG, "setupCancelButtonEvent.onClick : enter" );
finish();
Log.v( TAG, "setupCancelButtonEvent.onClick : exit" );
}
});
Log.v( TAG, "setupCancelButtonEvent : enter" );
}
private void saveAndExit() {
Log.v( TAG, "saveAndExit : enter" );
if( save() ) {
Log.v( TAG, "saveAndExit : save completed successfully" );
finish();
}
Log.v( TAG, "saveAndExit : exit" );
}
private boolean save() {
Log.v( TAG, "save : enter" );
boolean retVal = false;
if( null == profile ) {
Log.v( TAG, "save : creating new Playback Profile" );
profile = new PlaybackProfile();
}
profile.setName( getName() );
profile.setWidth( Integer.parseInt( getWidth() ) );
profile.setHeight( Integer.parseInt( getHeight() ) );
profile.setVideoBitrate( Integer.parseInt( getVideoBitrate() ) );
profile.setAudioBitrate( Integer.parseInt( getAudioBitrate() ) );
profile.setAudioSampleRate( Integer.parseInt( getSampleRate() ) );
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder.setTitle( R.string.preference_edit_error_dialog_title );
builder.setNeutralButton( R.string.btn_ok, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int which ) { }
});
if( "".equals( profile.getName().trim() ) ) {
Log.v( TAG, "save : name contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_name_error_invalid );
builder.show();
} else if( profile.getWidth() < 1 ) {
Log.v( TAG, "save : width contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_width_error_invalid );
builder.show();
} else if( profile.getHeight() < 1 ) {
Log.v( TAG, "save : height contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_height_error_invalid );
builder.show();
} else if( profile.getVideoBitrate() < 1 ) {
Log.v( TAG, "save : video bitrate contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_video_bitrate_error_invalid );
builder.show();
} else if( profile.getAudioBitrate() < 1 ) {
Log.v( TAG, "save : audio bitrate contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_audio_bitrate_error_invalid );
builder.show();
} else if( profile.getAudioSampleRate() < 1 ) {
Log.v( TAG, "save : sample rate contains errors" );
builder.setMessage( R.string.preference_playback_profile_text_view_sample_rate_error_invalid );
builder.show();
} else {
Log.v( TAG, "save : proceeding to save" );
if( profile.getId() != -1 ) {
Log.v( TAG, "save : updating existing playback profile" );
retVal = mPlaybackProfileDaoHelper.save( this, profile );
}
}
Log.v( TAG, "save : exit" );
return retVal;
}
}
| MythTV-Clients/MythTV-Android-Frontend | src/org/mythtv/client/ui/preferences/PlaybackProfileEditor.java | Java | gpl-3.0 | 9,195 |
/*
* Son of Mars
*
* Copyright (c) 2015-2016, Team Son of Mars
*
* 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 "Hud.h"
#include <cassert>
#include <stdlib.h>
#include "local/config.h"
Hud::Hud(game::EventManager& events, game::ResourceManager& resources,game::WindowGeometry& geometry)
: m_geometry(geometry)
, m_timeElapsed(0.0f)
, m_font(nullptr)
, m_characterMaxHealth(0)
, m_characterHealth(0)
, m_characterGold(0)
, m_characterDamage(0)
, m_characterArmor(0)
, m_characterRegenValue(0)
, m_characterRegenRate(0)
, m_display(false)
{
m_font=resources.getFont("GRECOromanLubedWrestling.ttf");
assert(m_font!=nullptr);
// Register event
events.registerHandler<CharacterStatsEvent>(&Hud::onCharacterStatsEvent, this);
}
Hud::~Hud()
{
}
void Hud::update(const float dt)
{
}
void Hud::render(sf::RenderWindow& window)
{
if(m_display==true)
{
sf::RectangleShape baseHud;
baseHud.setFillColor(sf::Color(0,0,0,128));
baseHud.setPosition(sf::Vector2f(0.0f,0.0f));
baseHud.setSize({m_geometry.getXFromRight(0),m_geometry.getYRatio(0.05f,0.0f)});
sf::Text strHealth;
//Set the characteristics of strHealth
strHealth.setFont(*m_font);
strHealth.setCharacterSize(25);
strHealth.setColor(sf::Color::Red);
strHealth.setPosition(0.0f,0.0f);
strHealth.setString("Health: "+std::to_string(m_characterHealth)+"/"+std::to_string(m_characterMaxHealth)+" (A)");
sf::Text strGold;
//Set the characteristics of strGold
strGold.setFont(*m_font);
strGold.setCharacterSize(25);
strGold.setColor(sf::Color::Green);
strGold.setPosition(250.0f,0.0f);
strGold.setString("Sesterces: "+std::to_string(m_characterGold));
sf::Text strDamage;
//Set the characteristics of strDamage
strDamage.setFont(*m_font);
strDamage.setCharacterSize(25);
strDamage.setColor(sf::Color::Blue);
strDamage.setPosition(400.0f,0.0f);
strDamage.setString("Damages: "+std::to_string(m_characterDamage)+" (E)");
sf::Text strArmor;
//Set the characteristics of strDamage
strArmor.setFont(*m_font);
strArmor.setCharacterSize(25);
strArmor.setColor(sf::Color::White);
strArmor.setPosition(600.0f,0.0f);
strArmor.setString("Armor: "+std::to_string(m_characterArmor));
sf::Text strRegen;
//Set the characteristics of strRegen
strRegen.setFont(*m_font);
strRegen.setCharacterSize(25);
strRegen.setColor(sf::Color::Cyan);
strRegen.setPosition(720.0f,0.0f);
strRegen.setString("Regeneration: "+std::to_string(m_characterRegenValue)+" over "+std::to_string(m_characterRegenRate)+" seconds (R)");
window.draw(baseHud);
window.draw(strHealth);
window.draw(strGold);
window.draw(strDamage);
window.draw(strArmor);
window.draw(strRegen);
}
}
game::EventStatus Hud::onCharacterStatsEvent(game::EventType type, game::Event *event)
{
auto statsEvent = static_cast<CharacterStatsEvent *>(event);
m_characterHealth = statsEvent->characterHealth;
m_characterMaxHealth = statsEvent->characterMaxHealth;
m_characterGold = statsEvent->characterGold;
m_characterDamage = statsEvent->characterDamage;
m_characterArmor = statsEvent->characterArmor;
m_characterRegenValue = statsEvent->characterRegenValue;
m_characterRegenRate = statsEvent->characterRegenRate;
return game::EventStatus::KEEP;
}
void Hud::switchDisplay()
{
if(m_display==true)
{
m_display=false;
}
else
{
m_display=true;
}
}
| DeadPixelsSociety/SonOfMars | src/local/Hud.cc | C++ | gpl-3.0 | 4,307 |
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: docker_container
short_description: manage docker containers
description:
- Manage the life cycle of docker containers.
- Supports check mode. Run with C(--check) and C(--diff) to view config difference and list of actions to be taken.
version_added: "2.1"
notes:
- For most config changes, the container needs to be recreated, i.e. the existing container has to be destroyed and
a new one created. This can cause unexpected data loss and downtime. You can use the I(comparisons) option to
prevent this.
- If the module needs to recreate the container, it will only use the options provided to the module to create the
new container (except I(image)). Therefore, always specify *all* options relevant to the container.
- When I(restart) is set to C(true), the module will only restart the container if no config changes are detected.
Please note that several options have default values; if the container to be restarted uses different values for
these options, it will be recreated instead. The options with default values which can cause this are I(auto_remove),
I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty). This behavior
can be changed by setting I(container_default_behavior) to C(no_defaults), which will be the default value from
Ansible 2.14 on.
options:
auto_remove:
description:
- Enable auto-removal of the container on daemon side when the container's process exits.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
version_added: "2.4"
blkio_weight:
description:
- Block IO (relative weight), between 10 and 1000.
type: int
capabilities:
description:
- List of capabilities to add to the container.
type: list
elements: str
cap_drop:
description:
- List of capabilities to drop from the container.
type: list
elements: str
version_added: "2.7"
cleanup:
description:
- Use with I(detach=false) to remove the container after successful execution.
type: bool
default: no
version_added: "2.2"
command:
description:
- Command to execute when the container starts. A command may be either a string or a list.
- Prior to version 2.4, strings were split on commas.
type: raw
comparisons:
description:
- Allows to specify how properties of existing containers are compared with
module options to decide whether the container should be recreated / updated
or not.
- Only options which correspond to the state of a container as handled by the
Docker daemon can be specified, as well as C(networks).
- Must be a dictionary specifying for an option one of the keys C(strict), C(ignore)
and C(allow_more_present).
- If C(strict) is specified, values are tested for equality, and changes always
result in updating or restarting. If C(ignore) is specified, changes are ignored.
- C(allow_more_present) is allowed only for lists, sets and dicts. If it is
specified for lists or sets, the container will only be updated or restarted if
the module option contains a value which is not present in the container's
options. If the option is specified for a dict, the container will only be updated
or restarted if the module option contains a key which isn't present in the
container's option, or if the value of a key present differs.
- The wildcard option C(*) can be used to set one of the default values C(strict)
or C(ignore) to *all* comparisons which are not explicitly set to other values.
- See the examples for details.
type: dict
version_added: "2.8"
container_default_behavior:
description:
- Various module options used to have default values. This causes problems with
containers which use different values for these options.
- The default value is C(compatibility), which will ensure that the default values
are used when the values are not explicitly specified by the user.
- From Ansible 2.14 on, the default value will switch to C(no_defaults). To avoid
deprecation warnings, please set I(container_default_behavior) to an explicit
value.
- This affects the I(auto_remove), I(detach), I(init), I(interactive), I(memory),
I(paused), I(privileged), I(read_only) and I(tty) options.
type: str
choices:
- compatibility
- no_defaults
version_added: "2.10"
cpu_period:
description:
- Limit CPU CFS (Completely Fair Scheduler) period.
- See I(cpus) for an easier to use alternative.
type: int
cpu_quota:
description:
- Limit CPU CFS (Completely Fair Scheduler) quota.
- See I(cpus) for an easier to use alternative.
type: int
cpus:
description:
- Specify how much of the available CPU resources a container can use.
- A value of C(1.5) means that at most one and a half CPU (core) will be used.
type: float
version_added: '2.10'
cpuset_cpus:
description:
- CPUs in which to allow execution C(1,3) or C(1-3).
type: str
cpuset_mems:
description:
- Memory nodes (MEMs) in which to allow execution C(0-3) or C(0,1).
type: str
cpu_shares:
description:
- CPU shares (relative weight).
type: int
detach:
description:
- Enable detached mode to leave the container running in background.
- If disabled, the task will reflect the status of the container run (failed if the command failed).
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(yes).
type: bool
devices:
description:
- List of host device bindings to add to the container.
- "Each binding is a mapping expressed in the format C(<path_on_host>:<path_in_container>:<cgroup_permissions>)."
type: list
elements: str
device_read_bps:
description:
- "List of device path and read rate (bytes per second) from device."
type: list
elements: dict
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit in format C(<number>[<unit>])."
- "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- "Omitting the unit defaults to bytes."
type: str
required: yes
version_added: "2.8"
device_write_bps:
description:
- "List of device and write rate (bytes per second) to device."
type: list
elements: dict
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit in format C(<number>[<unit>])."
- "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- "Omitting the unit defaults to bytes."
type: str
required: yes
version_added: "2.8"
device_read_iops:
description:
- "List of device and read rate (IO per second) from device."
type: list
elements: dict
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit."
- "Must be a positive integer."
type: int
required: yes
version_added: "2.8"
device_write_iops:
description:
- "List of device and write rate (IO per second) to device."
type: list
elements: dict
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit."
- "Must be a positive integer."
type: int
required: yes
version_added: "2.8"
dns_opts:
description:
- List of DNS options.
type: list
elements: str
dns_servers:
description:
- List of custom DNS servers.
type: list
elements: str
dns_search_domains:
description:
- List of custom DNS search domains.
type: list
elements: str
domainname:
description:
- Container domainname.
type: str
version_added: "2.5"
env:
description:
- Dictionary of key,value pairs.
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. C("true")) in order to avoid data loss.
type: dict
env_file:
description:
- Path to a file, present on the target, containing environment variables I(FOO=BAR).
- If variable also present in I(env), then the I(env) value will override.
type: path
version_added: "2.2"
entrypoint:
description:
- Command that overwrites the default C(ENTRYPOINT) of the image.
type: list
elements: str
etc_hosts:
description:
- Dict of host-to-IP mappings, where each host name is a key in the dictionary.
Each host name will be added to the container's C(/etc/hosts) file.
type: dict
exposed_ports:
description:
- List of additional container ports which informs Docker that the container
listens on the specified network ports at runtime.
- If the port is already exposed using C(EXPOSE) in a Dockerfile, it does not
need to be exposed again.
type: list
elements: str
aliases:
- exposed
- expose
force_kill:
description:
- Use the kill command when stopping a running container.
type: bool
default: no
aliases:
- forcekill
groups:
description:
- List of additional group names and/or IDs that the container process will run as.
type: list
elements: str
healthcheck:
description:
- Configure a check that is run to determine whether or not containers for this service are "healthy".
- "See the docs for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck)
for details on how healthchecks work."
- "I(interval), I(timeout) and I(start_period) are specified as durations. They accept duration as a string in a format
that look like: C(5h34m56s), C(1m30s) etc. The supported units are C(us), C(ms), C(s), C(m) and C(h)."
type: dict
suboptions:
test:
description:
- Command to run to check health.
- Must be either a string or a list. If it is a list, the first item must be one of C(NONE), C(CMD) or C(CMD-SHELL).
type: raw
interval:
description:
- Time between running the check.
- The default used by the Docker daemon is C(30s).
type: str
timeout:
description:
- Maximum time to allow one check to run.
- The default used by the Docker daemon is C(30s).
type: str
retries:
description:
- Consecutive number of failures needed to report unhealthy.
- The default used by the Docker daemon is C(3).
type: int
start_period:
description:
- Start period for the container to initialize before starting health-retries countdown.
- The default used by the Docker daemon is C(0s).
type: str
version_added: "2.8"
hostname:
description:
- The container's hostname.
type: str
ignore_image:
description:
- When I(state) is C(present) or C(started), the module compares the configuration of an existing
container to requested configuration. The evaluation includes the image version. If the image
version in the registry does not match the container, the container will be recreated. You can
stop this behavior by setting I(ignore_image) to C(True).
- "*Warning:* This option is ignored if C(image: ignore) or C(*: ignore) is specified in the
I(comparisons) option."
type: bool
default: no
version_added: "2.2"
image:
description:
- Repository path and tag used to create the container. If an image is not found or pull is true, the image
will be pulled from the registry. If no tag is included, C(latest) will be used.
- Can also be an image ID. If this is the case, the image is assumed to be available locally.
The I(pull) option is ignored for this case.
type: str
init:
description:
- Run an init inside the container that forwards signals and reaps processes.
- This option requires Docker API >= 1.25.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
version_added: "2.6"
interactive:
description:
- Keep stdin open after a container is launched, even if not attached.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
ipc_mode:
description:
- Set the IPC mode for the container.
- Can be one of C(container:<name|id>) to reuse another container's IPC namespace or C(host) to use
the host's IPC namespace within the container.
type: str
keep_volumes:
description:
- Retain volumes associated with a removed container.
type: bool
default: yes
kill_signal:
description:
- Override default signal used to kill a running container.
type: str
kernel_memory:
description:
- "Kernel memory limit in format C(<number>[<unit>]). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte). Minimum is C(4M)."
- Omitting the unit defaults to bytes.
type: str
labels:
description:
- Dictionary of key value pairs.
type: dict
links:
description:
- List of name aliases for linked containers in the format C(container_name:alias).
- Setting this will force container to be restarted.
type: list
elements: str
log_driver:
description:
- Specify the logging driver. Docker uses C(json-file) by default.
- See L(here,https://docs.docker.com/config/containers/logging/configure/) for possible choices.
type: str
log_options:
description:
- Dictionary of options specific to the chosen I(log_driver).
- See U(https://docs.docker.com/engine/admin/logging/overview/) for details.
type: dict
aliases:
- log_opt
mac_address:
description:
- Container MAC address (e.g. 92:d0:c6:0a:29:33).
type: str
memory:
description:
- "Memory limit in format C(<number>[<unit>]). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C("0").
type: str
memory_reservation:
description:
- "Memory soft limit in format C(<number>[<unit>]). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
type: str
memory_swap:
description:
- "Total memory limit (memory + swap) in format C(<number>[<unit>]).
Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B),
C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
type: str
memory_swappiness:
description:
- Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
- If not set, the value will be remain the same if container exists and will be inherited
from the host machine if it is (re-)created.
type: int
mounts:
version_added: "2.9"
type: list
elements: dict
description:
- Specification for mounts to be added to the container. More powerful alternative to I(volumes).
suboptions:
target:
description:
- Path inside the container.
type: str
required: true
source:
description:
- Mount source (e.g. a volume name or a host path).
type: str
type:
description:
- The mount type.
- Note that C(npipe) is only supported by Docker for Windows.
type: str
choices:
- bind
- npipe
- tmpfs
- volume
default: volume
read_only:
description:
- Whether the mount should be read-only.
type: bool
consistency:
description:
- The consistency requirement for the mount.
type: str
choices:
- cached
- consistent
- default
- delegated
propagation:
description:
- Propagation mode. Only valid for the C(bind) type.
type: str
choices:
- private
- rprivate
- shared
- rshared
- slave
- rslave
no_copy:
description:
- False if the volume should be populated with the data from the target. Only valid for the C(volume) type.
- The default value is C(false).
type: bool
labels:
description:
- User-defined name and labels for the volume. Only valid for the C(volume) type.
type: dict
volume_driver:
description:
- Specify the volume driver. Only valid for the C(volume) type.
- See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details.
type: str
volume_options:
description:
- Dictionary of options specific to the chosen volume_driver. See
L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details.
type: dict
tmpfs_size:
description:
- "The size for the tmpfs mount in bytes in format <number>[<unit>]."
- "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- "Omitting the unit defaults to bytes."
type: str
tmpfs_mode:
description:
- The permission mode for the tmpfs mount.
type: str
name:
description:
- Assign a name to a new container or match an existing container.
- When identifying an existing container name may be a name or a long or short container ID.
type: str
required: yes
network_mode:
description:
- Connect the container to a network. Choices are C(bridge), C(host), C(none), C(container:<name|id>), C(<network_name>) or C(default).
- "*Note* that from Ansible 2.14 on, if I(networks_cli_compatible) is C(true) and I(networks) contains at least one network,
the default value for I(network_mode) will be the name of the first network in the I(networks) list. You can prevent this
by explicitly specifying a value for I(network_mode), like the default value C(default) which will be used by Docker if
I(network_mode) is not specified."
type: str
userns_mode:
description:
- Set the user namespace mode for the container. Currently, the only valid value are C(host) and the empty string.
type: str
version_added: "2.5"
networks:
description:
- List of networks the container belongs to.
- For examples of the data structure and usage see EXAMPLES below.
- To remove a container from one or more networks, use the I(purge_networks) option.
- Note that as opposed to C(docker run ...), M(docker_container) does not remove the default
network if I(networks) is specified. You need to explicitly use I(purge_networks) to enforce
the removal of the default network (and all other networks not explicitly mentioned in I(networks)).
Alternatively, use the I(networks_cli_compatible) option, which will be enabled by default from Ansible 2.12 on.
type: list
elements: dict
suboptions:
name:
description:
- The network's name.
type: str
required: yes
ipv4_address:
description:
- The container's IPv4 address in this network.
type: str
ipv6_address:
description:
- The container's IPv6 address in this network.
type: str
links:
description:
- A list of containers to link to.
type: list
elements: str
aliases:
description:
- List of aliases for this container in this network. These names
can be used in the network to reach this container.
type: list
elements: str
version_added: "2.2"
networks_cli_compatible:
description:
- "When networks are provided to the module via the I(networks) option, the module
behaves differently than C(docker run --network): C(docker run --network other)
will create a container with network C(other) attached, but the default network
not attached. This module with I(networks: {name: other}) will create a container
with both C(default) and C(other) attached. If I(purge_networks) is set to C(yes),
the C(default) network will be removed afterwards."
- "If I(networks_cli_compatible) is set to C(yes), this module will behave as
C(docker run --network) and will *not* add the default network if I(networks) is
specified. If I(networks) is not specified, the default network will be attached."
- "*Note* that docker CLI also sets I(network_mode) to the name of the first network
added if C(--network) is specified. For more compatibility with docker CLI, you
explicitly have to set I(network_mode) to the name of the first network you're
adding. This behavior will change for Ansible 2.14: then I(network_mode) will
automatically be set to the first network name in I(networks) if I(network_mode)
is not specified, I(networks) has at least one entry and I(networks_cli_compatible)
is C(true)."
- Current value is C(no). A new default of C(yes) will be set in Ansible 2.12.
type: bool
version_added: "2.8"
oom_killer:
description:
- Whether or not to disable OOM Killer for the container.
type: bool
oom_score_adj:
description:
- An integer value containing the score given to the container in order to tune
OOM killer preferences.
type: int
version_added: "2.2"
output_logs:
description:
- If set to true, output of the container command will be printed.
- Only effective when I(log_driver) is set to C(json-file) or C(journald).
type: bool
default: no
version_added: "2.7"
paused:
description:
- Use with the started state to pause running processes inside the container.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
pid_mode:
description:
- Set the PID namespace mode for the container.
- Note that Docker SDK for Python < 2.0 only supports C(host). Newer versions of the
Docker SDK for Python (docker) allow all values supported by the Docker daemon.
type: str
pids_limit:
description:
- Set PIDs limit for the container. It accepts an integer value.
- Set C(-1) for unlimited PIDs.
type: int
version_added: "2.8"
privileged:
description:
- Give extended privileges to the container.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
published_ports:
description:
- List of ports to publish from the container to the host.
- "Use docker CLI syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000), where 8000 is a
container port, 9000 is a host port, and 0.0.0.0 is a host interface."
- Port ranges can be used for source and destination ports. If two ranges with
different lengths are specified, the shorter range will be used.
- "Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are *not* allowed. This
is different from the C(docker) command line utility. Use the L(dig lookup,../lookup/dig.html)
to resolve hostnames."
- A value of C(all) will publish all exposed container ports to random host ports, ignoring
any other mappings.
- If I(networks) parameter is provided, will inspect each network to see if there exists
a bridge network with optional parameter C(com.docker.network.bridge.host_binding_ipv4).
If such a network is found, then published ports where no host IP address is specified
will be bound to the host IP pointed to by C(com.docker.network.bridge.host_binding_ipv4).
Note that the first bridge network with a C(com.docker.network.bridge.host_binding_ipv4)
value encountered in the list of I(networks) is the one that will be used.
type: list
elements: str
aliases:
- ports
pull:
description:
- If true, always pull the latest version of an image. Otherwise, will only pull an image
when missing.
- "*Note:* images are only pulled when specified by name. If the image is specified
as a image ID (hash), it cannot be pulled."
type: bool
default: no
purge_networks:
description:
- Remove the container from ALL networks not included in I(networks) parameter.
- Any default networks such as C(bridge), if not found in I(networks), will be removed as well.
type: bool
default: no
version_added: "2.2"
read_only:
description:
- Mount the container's root file system as read-only.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
recreate:
description:
- Use with present and started states to force the re-creation of an existing container.
type: bool
default: no
restart:
description:
- Use with started state to force a matching container to be stopped and restarted.
type: bool
default: no
restart_policy:
description:
- Container restart policy.
- Place quotes around C(no) option.
type: str
choices:
- 'no'
- 'on-failure'
- 'always'
- 'unless-stopped'
restart_retries:
description:
- Use with restart policy to control maximum number of restart attempts.
type: int
runtime:
description:
- Runtime to use for the container.
type: str
version_added: "2.8"
shm_size:
description:
- "Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses C(64M).
type: str
security_opts:
description:
- List of security options in the form of C("label:user:User").
type: list
elements: str
state:
description:
- 'C(absent) - A container matching the specified name will be stopped and removed. Use I(force_kill) to kill the container
rather than stopping it. Use I(keep_volumes) to retain volumes associated with the removed container.'
- 'C(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no
container matches the name, a container will be created. If a container matches the name but the provided configuration
does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created
with the requested config.'
- 'C(started) - Asserts that the container is first C(present), and then if the container is not running moves it to a running
state. Use I(restart) to force a matching container to be stopped and restarted.'
- 'C(stopped) - Asserts that the container is first C(present), and then if the container is running moves it to a stopped
state.'
- To control what will be taken into account when comparing configuration, see the I(comparisons) option. To avoid that the
image version will be taken into account, you can also use the I(ignore_image) option.
- Use the I(recreate) option to always force re-creation of a matching container, even if it is running.
- If the container should be killed instead of stopped in case it needs to be stopped for recreation, or because I(state) is
C(stopped), please use the I(force_kill) option. Use I(keep_volumes) to retain volumes associated with a removed container.
- Use I(keep_volumes) to retain volumes associated with a removed container.
type: str
default: started
choices:
- absent
- present
- stopped
- started
stop_signal:
description:
- Override default signal used to stop the container.
type: str
stop_timeout:
description:
- Number of seconds to wait for the container to stop before sending C(SIGKILL).
When the container is created by this module, its C(StopTimeout) configuration
will be set to this value.
- When the container is stopped, will be used as a timeout for stopping the
container. In case the container has a custom C(StopTimeout) configuration,
the behavior depends on the version of the docker daemon. New versions of
the docker daemon will always use the container's configured C(StopTimeout)
value if it has been configured.
type: int
trust_image_content:
description:
- If C(yes), skip image verification.
- The option has never been used by the module. It will be removed in Ansible 2.14.
type: bool
default: no
tmpfs:
description:
- Mount a tmpfs directory.
type: list
elements: str
version_added: 2.4
tty:
description:
- Allocate a pseudo-TTY.
- If I(container_default_behavior) is set to C(compatiblity) (the default value), this
option has a default of C(no).
type: bool
ulimits:
description:
- "List of ulimit options. A ulimit is specified as C(nofile:262144:262144)."
type: list
elements: str
sysctls:
description:
- Dictionary of key,value pairs.
type: dict
version_added: 2.4
user:
description:
- Sets the username or UID used and optionally the groupname or GID for the specified command.
- "Can be of the forms C(user), C(user:group), C(uid), C(uid:gid), C(user:gid) or C(uid:group)."
type: str
uts:
description:
- Set the UTS namespace mode for the container.
type: str
volumes:
description:
- List of volumes to mount within the container.
- "Use docker CLI-style syntax: C(/host:/container[:mode])"
- "Mount modes can be a comma-separated list of various modes such as C(ro), C(rw), C(consistent),
C(delegated), C(cached), C(rprivate), C(private), C(rshared), C(shared), C(rslave), C(slave), and
C(nocopy). Note that the docker daemon might not support all modes and combinations of such modes."
- SELinux hosts can additionally use C(z) or C(Z) to use a shared or private label for the volume.
- "Note that Ansible 2.7 and earlier only supported one mode, which had to be one of C(ro), C(rw),
C(z), and C(Z)."
type: list
elements: str
volume_driver:
description:
- The container volume driver.
type: str
volumes_from:
description:
- List of container names or IDs to get volumes from.
type: list
elements: str
working_dir:
description:
- Path to the working directory.
type: str
version_added: "2.4"
extends_documentation_fragment:
- docker
- docker.docker_py_1_documentation
author:
- "Cove Schneider (@cove)"
- "Joshua Conner (@joshuaconner)"
- "Pavel Antonov (@softzilla)"
- "Thomas Steinbach (@ThomasSteinbach)"
- "Philippe Jandot (@zfil)"
- "Daan Oosterveld (@dusdanig)"
- "Chris Houseknecht (@chouseknecht)"
- "Kassian Sun (@kassiansun)"
- "Felix Fontein (@felixfontein)"
requirements:
- "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)"
- "Docker API >= 1.20"
'''
EXAMPLES = '''
- name: Create a data container
docker_container:
name: mydata
image: busybox
volumes:
- /data
- name: Re-create a redis container
docker_container:
name: myredis
image: redis
command: redis-server --appendonly yes
state: present
recreate: yes
exposed_ports:
- 6379
volumes_from:
- mydata
- name: Restart a container
docker_container:
name: myapplication
image: someuser/appimage
state: started
restart: yes
links:
- "myredis:aliasedredis"
devices:
- "/dev/sda:/dev/xvda:rwm"
ports:
- "8080:9000"
- "127.0.0.1:8081:9001/udp"
env:
SECRET_KEY: "ssssh"
# Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted
BOOLEAN_KEY: "yes"
- name: Container present
docker_container:
name: mycontainer
state: present
image: ubuntu:14.04
command: sleep infinity
- name: Stop a container
docker_container:
name: mycontainer
state: stopped
- name: Start 4 load-balanced containers
docker_container:
name: "container{{ item }}"
recreate: yes
image: someuser/anotherappimage
command: sleep 1d
with_sequence: count=4
- name: remove container
docker_container:
name: ohno
state: absent
- name: Syslogging output
docker_container:
name: myservice
image: busybox
log_driver: syslog
log_options:
syslog-address: tcp://my-syslog-server:514
syslog-facility: daemon
# NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for
# older docker installs, use "syslog-tag" instead
tag: myservice
- name: Create db container and connect to network
docker_container:
name: db_test
image: "postgres:latest"
networks:
- name: "{{ docker_network_name }}"
- name: Start container, connect to network and link
docker_container:
name: sleeper
image: ubuntu:14.04
networks:
- name: TestingNet
ipv4_address: "172.1.1.100"
aliases:
- sleepyzz
links:
- db_test:db
- name: TestingNet2
- name: Start a container with a command
docker_container:
name: sleepy
image: ubuntu:14.04
command: ["sleep", "infinity"]
- name: Add container to networks
docker_container:
name: sleepy
networks:
- name: TestingNet
ipv4_address: 172.1.1.18
links:
- sleeper
- name: TestingNet2
ipv4_address: 172.1.10.20
- name: Update network with aliases
docker_container:
name: sleepy
networks:
- name: TestingNet
aliases:
- sleepyz
- zzzz
- name: Remove container from one network
docker_container:
name: sleepy
networks:
- name: TestingNet2
purge_networks: yes
- name: Remove container from all networks
docker_container:
name: sleepy
purge_networks: yes
- name: Start a container and use an env file
docker_container:
name: agent
image: jenkinsci/ssh-slave
env_file: /var/tmp/jenkins/agent.env
- name: Create a container with limited capabilities
docker_container:
name: sleepy
image: ubuntu:16.04
command: sleep infinity
capabilities:
- sys_time
cap_drop:
- all
- name: Finer container restart/update control
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
volumes:
- /tmp:/tmp
comparisons:
image: ignore # don't restart containers with older versions of the image
env: strict # we want precisely this environment
volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there
- name: Finer container restart/update control II
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
comparisons:
'*': ignore # by default, ignore *all* options (including image)
env: strict # except for environment variables; there, we want to be strict
- name: Start container with healthstatus
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# Check if nginx server is healthy by curl'ing the server.
# If this fails or timeouts, the healthcheck fails.
test: ["CMD", "curl", "--fail", "http://nginx.host.com"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 30s
- name: Remove healthcheck from container
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# The "NONE" check needs to be specified
test: ["NONE"]
- name: start container with block device read limit
docker_container:
name: test
image: ubuntu:18.04
state: started
device_read_bps:
# Limit read rate for /dev/sda to 20 mebibytes per second
- path: /dev/sda
rate: 20M
device_read_iops:
# Limit read rate for /dev/sdb to 300 IO per second
- path: /dev/sdb
rate: 300
'''
RETURN = '''
container:
description:
- Facts representing the current state of the container. Matches the docker inspection output.
- Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts
are also accessible directly as C(docker_container). Note that the returned fact will be removed in Ansible 2.12.
- Before 2.3 this was C(ansible_docker_container) but was renamed in 2.3 to C(docker_container) due to
conflicts with the connection plugin.
- Empty if I(state) is C(absent)
- If I(detached) is C(false), will include C(Output) attribute containing any output from container run.
returned: always
type: dict
sample: '{
"AppArmorProfile": "",
"Args": [],
"Config": {
"AttachStderr": false,
"AttachStdin": false,
"AttachStdout": false,
"Cmd": [
"/usr/bin/supervisord"
],
"Domainname": "",
"Entrypoint": null,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"ExposedPorts": {
"443/tcp": {},
"80/tcp": {}
},
"Hostname": "8e47bf643eb9",
"Image": "lnmp_nginx:v1",
"Labels": {},
"OnBuild": null,
"OpenStdin": false,
"StdinOnce": false,
"Tty": false,
"User": "",
"Volumes": {
"/tmp/lnmp/nginx-sites/logs/": {}
},
...
}'
'''
import os
import re
import shlex
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.common.text.formatters import human_to_bytes
from ansible.module_utils.docker.common import (
AnsibleDockerClient,
DifferenceTracker,
DockerBaseClass,
compare_generic,
is_image_name_id,
sanitize_result,
clean_dict_booleans_for_docker_api,
omit_none_from_dict,
parse_healthcheck,
DOCKER_COMMON_ARGS,
RequestException,
)
from ansible.module_utils.six import string_types
try:
from docker import utils
from ansible.module_utils.docker.common import docker_version
if LooseVersion(docker_version) >= LooseVersion('1.10.0'):
from docker.types import Ulimit, LogConfig
from docker import types as docker_types
else:
from docker.utils.types import Ulimit, LogConfig
from docker.errors import DockerException, APIError, NotFound
except Exception:
# missing Docker SDK for Python handled in ansible.module_utils.docker.common
pass
REQUIRES_CONVERSION_TO_BYTES = [
'kernel_memory',
'memory',
'memory_reservation',
'memory_swap',
'shm_size'
]
def is_volume_permissions(mode):
for part in mode.split(','):
if part not in ('rw', 'ro', 'z', 'Z', 'consistent', 'delegated', 'cached', 'rprivate', 'private', 'rshared', 'shared', 'rslave', 'slave', 'nocopy'):
return False
return True
def parse_port_range(range_or_port, client):
'''
Parses a string containing either a single port or a range of ports.
Returns a list of integers for each port in the list.
'''
if '-' in range_or_port:
try:
start, end = [int(port) for port in range_or_port.split('-')]
except Exception:
client.fail('Invalid port range: "{0}"'.format(range_or_port))
if end < start:
client.fail('Invalid port range: "{0}"'.format(range_or_port))
return list(range(start, end + 1))
else:
try:
return [int(range_or_port)]
except Exception:
client.fail('Invalid port: "{0}"'.format(range_or_port))
def split_colon_ipv6(text, client):
'''
Split string by ':', while keeping IPv6 addresses in square brackets in one component.
'''
if '[' not in text:
return text.split(':')
start = 0
result = []
while start < len(text):
i = text.find('[', start)
if i < 0:
result.extend(text[start:].split(':'))
break
j = text.find(']', i)
if j < 0:
client.fail('Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(text, i + 1))
result.extend(text[start:i].split(':'))
k = text.find(':', j)
if k < 0:
result[-1] += text[i:]
start = len(text)
else:
result[-1] += text[i:k]
if k == len(text):
result.append('')
break
start = k + 1
return result
class TaskParameters(DockerBaseClass):
'''
Access and parse module parameters
'''
def __init__(self, client):
super(TaskParameters, self).__init__()
self.client = client
self.auto_remove = None
self.blkio_weight = None
self.capabilities = None
self.cap_drop = None
self.cleanup = None
self.command = None
self.cpu_period = None
self.cpu_quota = None
self.cpus = None
self.cpuset_cpus = None
self.cpuset_mems = None
self.cpu_shares = None
self.detach = None
self.debug = None
self.devices = None
self.device_read_bps = None
self.device_write_bps = None
self.device_read_iops = None
self.device_write_iops = None
self.dns_servers = None
self.dns_opts = None
self.dns_search_domains = None
self.domainname = None
self.env = None
self.env_file = None
self.entrypoint = None
self.etc_hosts = None
self.exposed_ports = None
self.force_kill = None
self.groups = None
self.healthcheck = None
self.hostname = None
self.ignore_image = None
self.image = None
self.init = None
self.interactive = None
self.ipc_mode = None
self.keep_volumes = None
self.kernel_memory = None
self.kill_signal = None
self.labels = None
self.links = None
self.log_driver = None
self.output_logs = None
self.log_options = None
self.mac_address = None
self.memory = None
self.memory_reservation = None
self.memory_swap = None
self.memory_swappiness = None
self.mounts = None
self.name = None
self.network_mode = None
self.userns_mode = None
self.networks = None
self.networks_cli_compatible = None
self.oom_killer = None
self.oom_score_adj = None
self.paused = None
self.pid_mode = None
self.pids_limit = None
self.privileged = None
self.purge_networks = None
self.pull = None
self.read_only = None
self.recreate = None
self.restart = None
self.restart_retries = None
self.restart_policy = None
self.runtime = None
self.shm_size = None
self.security_opts = None
self.state = None
self.stop_signal = None
self.stop_timeout = None
self.tmpfs = None
self.trust_image_content = None
self.tty = None
self.user = None
self.uts = None
self.volumes = None
self.volume_binds = dict()
self.volumes_from = None
self.volume_driver = None
self.working_dir = None
for key, value in client.module.params.items():
setattr(self, key, value)
self.comparisons = client.comparisons
# If state is 'absent', parameters do not have to be parsed or interpreted.
# Only the container's name is needed.
if self.state == 'absent':
return
if self.cpus is not None:
self.cpus = int(round(self.cpus * 1E9))
if self.groups:
# In case integers are passed as groups, we need to convert them to
# strings as docker internally treats them as strings.
self.groups = [str(g) for g in self.groups]
for param_name in REQUIRES_CONVERSION_TO_BYTES:
if client.module.params.get(param_name):
try:
setattr(self, param_name, human_to_bytes(client.module.params.get(param_name)))
except ValueError as exc:
self.fail("Failed to convert %s to bytes: %s" % (param_name, exc))
self.publish_all_ports = False
self.published_ports = self._parse_publish_ports()
if self.published_ports in ('all', 'ALL'):
self.publish_all_ports = True
self.published_ports = None
self.ports = self._parse_exposed_ports(self.published_ports)
self.log("expose ports:")
self.log(self.ports, pretty_print=True)
self.links = self._parse_links(self.links)
if self.volumes:
self.volumes = self._expand_host_paths()
self.tmpfs = self._parse_tmpfs()
self.env = self._get_environment()
self.ulimits = self._parse_ulimits()
self.sysctls = self._parse_sysctls()
self.log_config = self._parse_log_config()
try:
self.healthcheck, self.disable_healthcheck = parse_healthcheck(self.healthcheck)
except ValueError as e:
self.fail(str(e))
self.exp_links = None
self.volume_binds = self._get_volume_binds(self.volumes)
self.pid_mode = self._replace_container_names(self.pid_mode)
self.ipc_mode = self._replace_container_names(self.ipc_mode)
self.network_mode = self._replace_container_names(self.network_mode)
self.log("volumes:")
self.log(self.volumes, pretty_print=True)
self.log("volume binds:")
self.log(self.volume_binds, pretty_print=True)
if self.networks:
for network in self.networks:
network['id'] = self._get_network_id(network['name'])
if not network['id']:
self.fail("Parameter error: network named %s could not be found. Does it exist?" % network['name'])
if network.get('links'):
network['links'] = self._parse_links(network['links'])
if self.mac_address:
# Ensure the MAC address uses colons instead of hyphens for later comparison
self.mac_address = self.mac_address.replace('-', ':')
if self.entrypoint:
# convert from list to str.
self.entrypoint = ' '.join([str(x) for x in self.entrypoint])
if self.command:
# convert from list to str
if isinstance(self.command, list):
self.command = ' '.join([str(x) for x in self.command])
self.mounts_opt, self.expected_mounts = self._process_mounts()
self._check_mount_target_collisions()
for param_name in ["device_read_bps", "device_write_bps"]:
if client.module.params.get(param_name):
self._process_rate_bps(option=param_name)
for param_name in ["device_read_iops", "device_write_iops"]:
if client.module.params.get(param_name):
self._process_rate_iops(option=param_name)
def fail(self, msg):
self.client.fail(msg)
@property
def update_parameters(self):
'''
Returns parameters used to update a container
'''
update_parameters = dict(
blkio_weight='blkio_weight',
cpu_period='cpu_period',
cpu_quota='cpu_quota',
cpu_shares='cpu_shares',
cpuset_cpus='cpuset_cpus',
cpuset_mems='cpuset_mems',
mem_limit='memory',
mem_reservation='memory_reservation',
memswap_limit='memory_swap',
kernel_memory='kernel_memory',
)
result = dict()
for key, value in update_parameters.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
result[key] = getattr(self, value)
return result
@property
def create_parameters(self):
'''
Returns parameters used to create a container
'''
create_params = dict(
command='command',
domainname='domainname',
hostname='hostname',
user='user',
detach='detach',
stdin_open='interactive',
tty='tty',
ports='ports',
environment='env',
name='name',
entrypoint='entrypoint',
mac_address='mac_address',
labels='labels',
stop_signal='stop_signal',
working_dir='working_dir',
stop_timeout='stop_timeout',
healthcheck='healthcheck',
)
if self.client.docker_py_version < LooseVersion('3.0'):
# cpu_shares and volume_driver moved to create_host_config in > 3
create_params['cpu_shares'] = 'cpu_shares'
create_params['volume_driver'] = 'volume_driver'
result = dict(
host_config=self._host_config(),
volumes=self._get_mounts(),
)
for key, value in create_params.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
result[key] = getattr(self, value)
if self.networks_cli_compatible and self.networks:
network = self.networks[0]
params = dict()
for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'):
if network.get(para):
params[para] = network[para]
network_config = dict()
network_config[network['name']] = self.client.create_endpoint_config(**params)
result['networking_config'] = self.client.create_networking_config(network_config)
return result
def _expand_host_paths(self):
new_vols = []
for vol in self.volumes:
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if re.match(r'[.~]', host):
host = os.path.abspath(os.path.expanduser(host))
new_vols.append("%s:%s:%s" % (host, container, mode))
continue
elif len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]):
host = os.path.abspath(os.path.expanduser(parts[0]))
new_vols.append("%s:%s:rw" % (host, parts[1]))
continue
new_vols.append(vol)
return new_vols
def _get_mounts(self):
'''
Return a list of container mounts.
:return:
'''
result = []
if self.volumes:
for vol in self.volumes:
if ':' in vol:
if len(vol.split(':')) == 3:
dummy, container, dummy = vol.split(':')
result.append(container)
continue
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
result.append(parts[1])
continue
result.append(vol)
self.log("mounts:")
self.log(result, pretty_print=True)
return result
def _host_config(self):
'''
Returns parameters used to create a HostConfig object
'''
host_config_params = dict(
port_bindings='published_ports',
publish_all_ports='publish_all_ports',
links='links',
privileged='privileged',
dns='dns_servers',
dns_opt='dns_opts',
dns_search='dns_search_domains',
binds='volume_binds',
volumes_from='volumes_from',
network_mode='network_mode',
userns_mode='userns_mode',
cap_add='capabilities',
cap_drop='cap_drop',
extra_hosts='etc_hosts',
read_only='read_only',
ipc_mode='ipc_mode',
security_opt='security_opts',
ulimits='ulimits',
sysctls='sysctls',
log_config='log_config',
mem_limit='memory',
memswap_limit='memory_swap',
mem_swappiness='memory_swappiness',
oom_score_adj='oom_score_adj',
oom_kill_disable='oom_killer',
shm_size='shm_size',
group_add='groups',
devices='devices',
pid_mode='pid_mode',
tmpfs='tmpfs',
init='init',
uts_mode='uts',
runtime='runtime',
auto_remove='auto_remove',
device_read_bps='device_read_bps',
device_write_bps='device_write_bps',
device_read_iops='device_read_iops',
device_write_iops='device_write_iops',
pids_limit='pids_limit',
mounts='mounts',
nano_cpus='cpus',
)
if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'):
# blkio_weight can always be updated, but can only be set on creation
# when Docker SDK for Python and Docker API are new enough
host_config_params['blkio_weight'] = 'blkio_weight'
if self.client.docker_py_version >= LooseVersion('3.0'):
# cpu_shares and volume_driver moved to create_host_config in > 3
host_config_params['cpu_shares'] = 'cpu_shares'
host_config_params['volume_driver'] = 'volume_driver'
params = dict()
for key, value in host_config_params.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
params[key] = getattr(self, value)
if self.restart_policy:
params['restart_policy'] = dict(Name=self.restart_policy,
MaximumRetryCount=self.restart_retries)
if 'mounts' in params:
params['mounts'] = self.mounts_opt
return self.client.create_host_config(**params)
@property
def default_host_ip(self):
ip = '0.0.0.0'
if not self.networks:
return ip
for net in self.networks:
if net.get('name'):
try:
network = self.client.inspect_network(net['name'])
if network.get('Driver') == 'bridge' and \
network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'):
ip = network['Options']['com.docker.network.bridge.host_binding_ipv4']
break
except NotFound as nfe:
self.client.fail(
"Cannot inspect the network '{0}' to determine the default IP: {1}".format(net['name'], nfe),
exception=traceback.format_exc()
)
return ip
def _parse_publish_ports(self):
'''
Parse ports from docker CLI syntax
'''
if self.published_ports is None:
return None
if 'all' in self.published_ports:
return 'all'
default_ip = self.default_host_ip
binds = {}
for port in self.published_ports:
parts = split_colon_ipv6(str(port), self.client)
container_port = parts[-1]
protocol = ''
if '/' in container_port:
container_port, protocol = parts[-1].split('/')
container_ports = parse_port_range(container_port, self.client)
p_len = len(parts)
if p_len == 1:
port_binds = len(container_ports) * [(default_ip,)]
elif p_len == 2:
port_binds = [(default_ip, port) for port in parse_port_range(parts[0], self.client)]
elif p_len == 3:
# We only allow IPv4 and IPv6 addresses for the bind address
ipaddr = parts[0]
if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr):
self.fail(('Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. '
'Use the dig lookup to resolve hostnames. (Found hostname: {0})').format(ipaddr))
if re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr):
ipaddr = ipaddr[1:-1]
if parts[1]:
port_binds = [(ipaddr, port) for port in parse_port_range(parts[1], self.client)]
else:
port_binds = len(container_ports) * [(ipaddr,)]
for bind, container_port in zip(port_binds, container_ports):
idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port
if idx in binds:
old_bind = binds[idx]
if isinstance(old_bind, list):
old_bind.append(bind)
else:
binds[idx] = [old_bind, bind]
else:
binds[idx] = bind
return binds
def _get_volume_binds(self, volumes):
'''
Extract host bindings, if any, from list of volume mapping strings.
:return: dictionary of bind mappings
'''
result = dict()
if volumes:
for vol in volumes:
host = None
if ':' in vol:
parts = vol.split(':')
if len(parts) == 3:
host, container, mode = parts
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
elif len(parts) == 2:
if not is_volume_permissions(parts[1]):
host, container, mode = (vol.split(':') + ['rw'])
if host is not None:
result[host] = dict(
bind=container,
mode=mode
)
return result
def _parse_exposed_ports(self, published_ports):
'''
Parse exposed ports from docker CLI-style ports syntax.
'''
exposed = []
if self.exposed_ports:
for port in self.exposed_ports:
port = str(port).strip()
protocol = 'tcp'
match = re.search(r'(/.+$)', port)
if match:
protocol = match.group(1).replace('/', '')
port = re.sub(r'/.+$', '', port)
exposed.append((port, protocol))
if published_ports:
# Any published port should also be exposed
for publish_port in published_ports:
match = False
if isinstance(publish_port, string_types) and '/' in publish_port:
port, protocol = publish_port.split('/')
port = int(port)
else:
protocol = 'tcp'
port = int(publish_port)
for exposed_port in exposed:
if exposed_port[1] != protocol:
continue
if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]:
start_port, end_port = exposed_port[0].split('-')
if int(start_port) <= port <= int(end_port):
match = True
elif exposed_port[0] == port:
match = True
if not match:
exposed.append((port, protocol))
return exposed
@staticmethod
def _parse_links(links):
'''
Turn links into a dictionary
'''
if links is None:
return None
result = []
for link in links:
parsed_link = link.split(':', 1)
if len(parsed_link) == 2:
result.append((parsed_link[0], parsed_link[1]))
else:
result.append((parsed_link[0], parsed_link[0]))
return result
def _parse_ulimits(self):
'''
Turn ulimits into an array of Ulimit objects
'''
if self.ulimits is None:
return None
results = []
for limit in self.ulimits:
limits = dict()
pieces = limit.split(':')
if len(pieces) >= 2:
limits['name'] = pieces[0]
limits['soft'] = int(pieces[1])
limits['hard'] = int(pieces[1])
if len(pieces) == 3:
limits['hard'] = int(pieces[2])
try:
results.append(Ulimit(**limits))
except ValueError as exc:
self.fail("Error parsing ulimits value %s - %s" % (limit, exc))
return results
def _parse_sysctls(self):
'''
Turn sysctls into an hash of Sysctl objects
'''
return self.sysctls
def _parse_log_config(self):
'''
Create a LogConfig object
'''
if self.log_driver is None:
return None
options = dict(
Type=self.log_driver,
Config=dict()
)
if self.log_options is not None:
options['Config'] = dict()
for k, v in self.log_options.items():
if not isinstance(v, string_types):
self.client.module.warn(
"Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. "
"If this is not correct, or you want to avoid such warnings, please quote the value." % (k, str(v))
)
v = str(v)
self.log_options[k] = v
options['Config'][k] = v
try:
return LogConfig(**options)
except ValueError as exc:
self.fail('Error parsing logging options - %s' % (exc))
def _parse_tmpfs(self):
'''
Turn tmpfs into a hash of Tmpfs objects
'''
result = dict()
if self.tmpfs is None:
return result
for tmpfs_spec in self.tmpfs:
split_spec = tmpfs_spec.split(":", 1)
if len(split_spec) > 1:
result[split_spec[0]] = split_spec[1]
else:
result[split_spec[0]] = ""
return result
def _get_environment(self):
"""
If environment file is combined with explicit environment variables, the explicit environment variables
take precedence.
"""
final_env = {}
if self.env_file:
parsed_env_file = utils.parse_env_file(self.env_file)
for name, value in parsed_env_file.items():
final_env[name] = str(value)
if self.env:
for name, value in self.env.items():
if not isinstance(value, string_types):
self.fail("Non-string value found for env option. Ambiguous env options must be "
"wrapped in quotes to avoid them being interpreted. Key: %s" % (name, ))
final_env[name] = str(value)
return final_env
def _get_network_id(self, network_name):
network_id = None
try:
for network in self.client.networks(names=[network_name]):
if network['Name'] == network_name:
network_id = network['Id']
break
except Exception as exc:
self.fail("Error getting network id for %s - %s" % (network_name, str(exc)))
return network_id
def _process_mounts(self):
if self.mounts is None:
return None, None
mounts_list = []
mounts_expected = []
for mount in self.mounts:
target = mount['target']
datatype = mount['type']
mount_dict = dict(mount)
# Sanity checks (so we don't wait for docker-py to barf on input)
if mount_dict.get('source') is None and datatype != 'tmpfs':
self.client.fail('source must be specified for mount "{0}" of type "{1}"'.format(target, datatype))
mount_option_types = dict(
volume_driver='volume',
volume_options='volume',
propagation='bind',
no_copy='volume',
labels='volume',
tmpfs_size='tmpfs',
tmpfs_mode='tmpfs',
)
for option, req_datatype in mount_option_types.items():
if mount_dict.get(option) is not None and datatype != req_datatype:
self.client.fail('{0} cannot be specified for mount "{1}" of type "{2}" (needs type "{3}")'.format(option, target, datatype, req_datatype))
# Handle volume_driver and volume_options
volume_driver = mount_dict.pop('volume_driver')
volume_options = mount_dict.pop('volume_options')
if volume_driver:
if volume_options:
volume_options = clean_dict_booleans_for_docker_api(volume_options)
mount_dict['driver_config'] = docker_types.DriverConfig(name=volume_driver, options=volume_options)
if mount_dict['labels']:
mount_dict['labels'] = clean_dict_booleans_for_docker_api(mount_dict['labels'])
if mount_dict.get('tmpfs_size') is not None:
try:
mount_dict['tmpfs_size'] = human_to_bytes(mount_dict['tmpfs_size'])
except ValueError as exc:
self.fail('Failed to convert tmpfs_size of mount "{0}" to bytes: {1}'.format(target, exc))
if mount_dict.get('tmpfs_mode') is not None:
try:
mount_dict['tmpfs_mode'] = int(mount_dict['tmpfs_mode'], 8)
except Exception as dummy:
self.client.fail('tmp_fs mode of mount "{0}" is not an octal string!'.format(target))
# Fill expected mount dict
mount_expected = dict(mount)
mount_expected['tmpfs_size'] = mount_dict['tmpfs_size']
mount_expected['tmpfs_mode'] = mount_dict['tmpfs_mode']
# Add result to lists
mounts_list.append(docker_types.Mount(**mount_dict))
mounts_expected.append(omit_none_from_dict(mount_expected))
return mounts_list, mounts_expected
def _process_rate_bps(self, option):
"""
Format device_read_bps and device_write_bps option
"""
devices_list = []
for v in getattr(self, option):
device_dict = dict((x.title(), y) for x, y in v.items())
device_dict['Rate'] = human_to_bytes(device_dict['Rate'])
devices_list.append(device_dict)
setattr(self, option, devices_list)
def _process_rate_iops(self, option):
"""
Format device_read_iops and device_write_iops option
"""
devices_list = []
for v in getattr(self, option):
device_dict = dict((x.title(), y) for x, y in v.items())
devices_list.append(device_dict)
setattr(self, option, devices_list)
def _replace_container_names(self, mode):
"""
Parse IPC and PID modes. If they contain a container name, replace
with the container's ID.
"""
if mode is None or not mode.startswith('container:'):
return mode
container_name = mode[len('container:'):]
# Try to inspect container to see whether this is an ID or a
# name (and in the latter case, retrieve it's ID)
container = self.client.get_container(container_name)
if container is None:
# If we can't find the container, issue a warning and continue with
# what the user specified.
self.client.module.warn('Cannot find a container with name or ID "{0}"'.format(container_name))
return mode
return 'container:{0}'.format(container['Id'])
def _check_mount_target_collisions(self):
last = dict()
def f(t, name):
if t in last:
if name == last[t]:
self.client.fail('The mount point "{0}" appears twice in the {1} option'.format(t, name))
else:
self.client.fail('The mount point "{0}" appears both in the {1} and {2} option'.format(t, name, last[t]))
last[t] = name
if self.expected_mounts:
for t in [m['target'] for m in self.expected_mounts]:
f(t, 'mounts')
if self.volumes:
for v in self.volumes:
vs = v.split(':')
f(vs[0 if len(vs) == 1 else 1], 'volumes')
class Container(DockerBaseClass):
def __init__(self, container, parameters):
super(Container, self).__init__()
self.raw = container
self.Id = None
self.container = container
if container:
self.Id = container['Id']
self.Image = container['Image']
self.log(self.container, pretty_print=True)
self.parameters = parameters
self.parameters.expected_links = None
self.parameters.expected_ports = None
self.parameters.expected_exposed = None
self.parameters.expected_volumes = None
self.parameters.expected_ulimits = None
self.parameters.expected_sysctls = None
self.parameters.expected_etc_hosts = None
self.parameters.expected_env = None
self.parameters_map = dict()
self.parameters_map['expected_links'] = 'links'
self.parameters_map['expected_ports'] = 'expected_ports'
self.parameters_map['expected_exposed'] = 'exposed_ports'
self.parameters_map['expected_volumes'] = 'volumes'
self.parameters_map['expected_ulimits'] = 'ulimits'
self.parameters_map['expected_sysctls'] = 'sysctls'
self.parameters_map['expected_etc_hosts'] = 'etc_hosts'
self.parameters_map['expected_env'] = 'env'
self.parameters_map['expected_entrypoint'] = 'entrypoint'
self.parameters_map['expected_binds'] = 'volumes'
self.parameters_map['expected_cmd'] = 'command'
self.parameters_map['expected_devices'] = 'devices'
self.parameters_map['expected_healthcheck'] = 'healthcheck'
self.parameters_map['expected_mounts'] = 'mounts'
def fail(self, msg):
self.parameters.client.fail(msg)
@property
def exists(self):
return True if self.container else False
@property
def running(self):
if self.container and self.container.get('State'):
if self.container['State'].get('Running') and not self.container['State'].get('Ghost', False):
return True
return False
@property
def paused(self):
if self.container and self.container.get('State'):
return self.container['State'].get('Paused', False)
return False
def _compare(self, a, b, compare):
'''
Compare values a and b as described in compare.
'''
return compare_generic(a, b, compare['comparison'], compare['type'])
def _decode_mounts(self, mounts):
if not mounts:
return mounts
result = []
empty_dict = dict()
for mount in mounts:
res = dict()
res['type'] = mount.get('Type')
res['source'] = mount.get('Source')
res['target'] = mount.get('Target')
res['read_only'] = mount.get('ReadOnly', False) # golang's omitempty for bool returns None for False
res['consistency'] = mount.get('Consistency')
res['propagation'] = mount.get('BindOptions', empty_dict).get('Propagation')
res['no_copy'] = mount.get('VolumeOptions', empty_dict).get('NoCopy', False)
res['labels'] = mount.get('VolumeOptions', empty_dict).get('Labels', empty_dict)
res['volume_driver'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Name')
res['volume_options'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Options', empty_dict)
res['tmpfs_size'] = mount.get('TmpfsOptions', empty_dict).get('SizeBytes')
res['tmpfs_mode'] = mount.get('TmpfsOptions', empty_dict).get('Mode')
result.append(res)
return result
def has_different_configuration(self, image):
'''
Diff parameters vs existing container config. Returns tuple: (True | False, List of differences)
'''
self.log('Starting has_different_configuration')
self.parameters.expected_entrypoint = self._get_expected_entrypoint()
self.parameters.expected_links = self._get_expected_links()
self.parameters.expected_ports = self._get_expected_ports()
self.parameters.expected_exposed = self._get_expected_exposed(image)
self.parameters.expected_volumes = self._get_expected_volumes(image)
self.parameters.expected_binds = self._get_expected_binds(image)
self.parameters.expected_ulimits = self._get_expected_ulimits(self.parameters.ulimits)
self.parameters.expected_sysctls = self._get_expected_sysctls(self.parameters.sysctls)
self.parameters.expected_etc_hosts = self._convert_simple_dict_to_list('etc_hosts')
self.parameters.expected_env = self._get_expected_env(image)
self.parameters.expected_cmd = self._get_expected_cmd()
self.parameters.expected_devices = self._get_expected_devices()
self.parameters.expected_healthcheck = self._get_expected_healthcheck()
if not self.container.get('HostConfig'):
self.fail("has_config_diff: Error parsing container properties. HostConfig missing.")
if not self.container.get('Config'):
self.fail("has_config_diff: Error parsing container properties. Config missing.")
if not self.container.get('NetworkSettings'):
self.fail("has_config_diff: Error parsing container properties. NetworkSettings missing.")
host_config = self.container['HostConfig']
log_config = host_config.get('LogConfig', dict())
restart_policy = host_config.get('RestartPolicy', dict())
config = self.container['Config']
network = self.container['NetworkSettings']
# The previous version of the docker module ignored the detach state by
# assuming if the container was running, it must have been detached.
detach = not (config.get('AttachStderr') and config.get('AttachStdout'))
# "ExposedPorts": null returns None type & causes AttributeError - PR #5517
if config.get('ExposedPorts') is not None:
expected_exposed = [self._normalize_port(p) for p in config.get('ExposedPorts', dict()).keys()]
else:
expected_exposed = []
# Map parameters to container inspect results
config_mapping = dict(
expected_cmd=config.get('Cmd'),
domainname=config.get('Domainname'),
hostname=config.get('Hostname'),
user=config.get('User'),
detach=detach,
init=host_config.get('Init'),
interactive=config.get('OpenStdin'),
capabilities=host_config.get('CapAdd'),
cap_drop=host_config.get('CapDrop'),
expected_devices=host_config.get('Devices'),
dns_servers=host_config.get('Dns'),
dns_opts=host_config.get('DnsOptions'),
dns_search_domains=host_config.get('DnsSearch'),
expected_env=(config.get('Env') or []),
expected_entrypoint=config.get('Entrypoint'),
expected_etc_hosts=host_config['ExtraHosts'],
expected_exposed=expected_exposed,
groups=host_config.get('GroupAdd'),
ipc_mode=host_config.get("IpcMode"),
labels=config.get('Labels'),
expected_links=host_config.get('Links'),
mac_address=network.get('MacAddress'),
memory_swappiness=host_config.get('MemorySwappiness'),
network_mode=host_config.get('NetworkMode'),
userns_mode=host_config.get('UsernsMode'),
oom_killer=host_config.get('OomKillDisable'),
oom_score_adj=host_config.get('OomScoreAdj'),
pid_mode=host_config.get('PidMode'),
privileged=host_config.get('Privileged'),
expected_ports=host_config.get('PortBindings'),
read_only=host_config.get('ReadonlyRootfs'),
restart_policy=restart_policy.get('Name'),
runtime=host_config.get('Runtime'),
shm_size=host_config.get('ShmSize'),
security_opts=host_config.get("SecurityOpt"),
stop_signal=config.get("StopSignal"),
tmpfs=host_config.get('Tmpfs'),
tty=config.get('Tty'),
expected_ulimits=host_config.get('Ulimits'),
expected_sysctls=host_config.get('Sysctls'),
uts=host_config.get('UTSMode'),
expected_volumes=config.get('Volumes'),
expected_binds=host_config.get('Binds'),
volume_driver=host_config.get('VolumeDriver'),
volumes_from=host_config.get('VolumesFrom'),
working_dir=config.get('WorkingDir'),
publish_all_ports=host_config.get('PublishAllPorts'),
expected_healthcheck=config.get('Healthcheck'),
disable_healthcheck=(not config.get('Healthcheck') or config.get('Healthcheck').get('Test') == ['NONE']),
device_read_bps=host_config.get('BlkioDeviceReadBps'),
device_write_bps=host_config.get('BlkioDeviceWriteBps'),
device_read_iops=host_config.get('BlkioDeviceReadIOps'),
device_write_iops=host_config.get('BlkioDeviceWriteIOps'),
pids_limit=host_config.get('PidsLimit'),
# According to https://github.com/moby/moby/, support for HostConfig.Mounts
# has been included at least since v17.03.0-ce, which has API version 1.26.
# The previous tag, v1.9.1, has API version 1.21 and does not have
# HostConfig.Mounts. I have no idea what about API 1.25...
expected_mounts=self._decode_mounts(host_config.get('Mounts')),
cpus=host_config.get('NanoCpus'),
)
# Options which don't make sense without their accompanying option
if self.parameters.restart_policy:
config_mapping['restart_retries'] = restart_policy.get('MaximumRetryCount')
if self.parameters.log_driver:
config_mapping['log_driver'] = log_config.get('Type')
config_mapping['log_options'] = log_config.get('Config')
if self.parameters.client.option_minimal_versions['auto_remove']['supported']:
# auto_remove is only supported in Docker SDK for Python >= 2.0.0; unfortunately
# it has a default value, that's why we have to jump through the hoops here
config_mapping['auto_remove'] = host_config.get('AutoRemove')
if self.parameters.client.option_minimal_versions['stop_timeout']['supported']:
# stop_timeout is only supported in Docker SDK for Python >= 2.1. Note that
# stop_timeout has a hybrid role, in that it used to be something only used
# for stopping containers, and is now also used as a container property.
# That's why it needs special handling here.
config_mapping['stop_timeout'] = config.get('StopTimeout')
if self.parameters.client.docker_api_version < LooseVersion('1.22'):
# For docker API < 1.22, update_container() is not supported. Thus
# we need to handle all limits which are usually handled by
# update_container() as configuration changes which require a container
# restart.
config_mapping.update(dict(
blkio_weight=host_config.get('BlkioWeight'),
cpu_period=host_config.get('CpuPeriod'),
cpu_quota=host_config.get('CpuQuota'),
cpu_shares=host_config.get('CpuShares'),
cpuset_cpus=host_config.get('CpusetCpus'),
cpuset_mems=host_config.get('CpusetMems'),
kernel_memory=host_config.get("KernelMemory"),
memory=host_config.get('Memory'),
memory_reservation=host_config.get('MemoryReservation'),
memory_swap=host_config.get('MemorySwap'),
))
differences = DifferenceTracker()
for key, value in config_mapping.items():
minimal_version = self.parameters.client.option_minimal_versions.get(key, {})
if not minimal_version.get('supported', True):
continue
compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)]
self.log('check differences %s %s vs %s (%s)' % (key, getattr(self.parameters, key), str(value), compare))
if getattr(self.parameters, key, None) is not None:
match = self._compare(getattr(self.parameters, key), value, compare)
if not match:
# no match. record the differences
p = getattr(self.parameters, key)
c = value
if compare['type'] == 'set':
# Since the order does not matter, sort so that the diff output is better.
if p is not None:
p = sorted(p)
if c is not None:
c = sorted(c)
elif compare['type'] == 'set(dict)':
# Since the order does not matter, sort so that the diff output is better.
if key == 'expected_mounts':
# For selected values, use one entry as key
def sort_key_fn(x):
return x['target']
else:
# We sort the list of dictionaries by using the sorted items of a dict as its key.
def sort_key_fn(x):
return sorted((a, str(b)) for a, b in x.items())
if p is not None:
p = sorted(p, key=sort_key_fn)
if c is not None:
c = sorted(c, key=sort_key_fn)
differences.add(key, parameter=p, active=c)
has_differences = not differences.empty
return has_differences, differences
def has_different_resource_limits(self):
'''
Diff parameters and container resource limits
'''
if not self.container.get('HostConfig'):
self.fail("limits_differ_from_container: Error parsing container properties. HostConfig missing.")
if self.parameters.client.docker_api_version < LooseVersion('1.22'):
# update_container() call not supported
return False, []
host_config = self.container['HostConfig']
config_mapping = dict(
blkio_weight=host_config.get('BlkioWeight'),
cpu_period=host_config.get('CpuPeriod'),
cpu_quota=host_config.get('CpuQuota'),
cpu_shares=host_config.get('CpuShares'),
cpuset_cpus=host_config.get('CpusetCpus'),
cpuset_mems=host_config.get('CpusetMems'),
kernel_memory=host_config.get("KernelMemory"),
memory=host_config.get('Memory'),
memory_reservation=host_config.get('MemoryReservation'),
memory_swap=host_config.get('MemorySwap'),
)
differences = DifferenceTracker()
for key, value in config_mapping.items():
if getattr(self.parameters, key, None):
compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)]
match = self._compare(getattr(self.parameters, key), value, compare)
if not match:
# no match. record the differences
differences.add(key, parameter=getattr(self.parameters, key), active=value)
different = not differences.empty
return different, differences
def has_network_differences(self):
'''
Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6
'''
different = False
differences = []
if not self.parameters.networks:
return different, differences
if not self.container.get('NetworkSettings'):
self.fail("has_missing_networks: Error parsing container properties. NetworkSettings missing.")
connected_networks = self.container['NetworkSettings']['Networks']
for network in self.parameters.networks:
network_info = connected_networks.get(network['name'])
if network_info is None:
different = True
differences.append(dict(
parameter=network,
container=None
))
else:
diff = False
network_info_ipam = network_info.get('IPAMConfig') or {}
if network.get('ipv4_address') and network['ipv4_address'] != network_info_ipam.get('IPv4Address'):
diff = True
if network.get('ipv6_address') and network['ipv6_address'] != network_info_ipam.get('IPv6Address'):
diff = True
if network.get('aliases'):
if not compare_generic(network['aliases'], network_info.get('Aliases'), 'allow_more_present', 'set'):
diff = True
if network.get('links'):
expected_links = []
for link, alias in network['links']:
expected_links.append("%s:%s" % (link, alias))
if not compare_generic(expected_links, network_info.get('Links'), 'allow_more_present', 'set'):
diff = True
if diff:
different = True
differences.append(dict(
parameter=network,
container=dict(
name=network['name'],
ipv4_address=network_info_ipam.get('IPv4Address'),
ipv6_address=network_info_ipam.get('IPv6Address'),
aliases=network_info.get('Aliases'),
links=network_info.get('Links')
)
))
return different, differences
def has_extra_networks(self):
'''
Check if the container is connected to non-requested networks
'''
extra_networks = []
extra = False
if not self.container.get('NetworkSettings'):
self.fail("has_extra_networks: Error parsing container properties. NetworkSettings missing.")
connected_networks = self.container['NetworkSettings'].get('Networks')
if connected_networks:
for network, network_config in connected_networks.items():
keep = False
if self.parameters.networks:
for expected_network in self.parameters.networks:
if expected_network['name'] == network:
keep = True
if not keep:
extra = True
extra_networks.append(dict(name=network, id=network_config['NetworkID']))
return extra, extra_networks
def _get_expected_devices(self):
if not self.parameters.devices:
return None
expected_devices = []
for device in self.parameters.devices:
parts = device.split(':')
if len(parts) == 1:
expected_devices.append(
dict(
CgroupPermissions='rwm',
PathInContainer=parts[0],
PathOnHost=parts[0]
))
elif len(parts) == 2:
parts = device.split(':')
expected_devices.append(
dict(
CgroupPermissions='rwm',
PathInContainer=parts[1],
PathOnHost=parts[0]
)
)
else:
expected_devices.append(
dict(
CgroupPermissions=parts[2],
PathInContainer=parts[1],
PathOnHost=parts[0]
))
return expected_devices
def _get_expected_entrypoint(self):
if not self.parameters.entrypoint:
return None
return shlex.split(self.parameters.entrypoint)
def _get_expected_ports(self):
if not self.parameters.published_ports:
return None
expected_bound_ports = {}
for container_port, config in self.parameters.published_ports.items():
if isinstance(container_port, int):
container_port = "%s/tcp" % container_port
if len(config) == 1:
if isinstance(config[0], int):
expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}]
else:
expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': ""}]
elif isinstance(config[0], tuple):
expected_bound_ports[container_port] = []
for host_ip, host_port in config:
expected_bound_ports[container_port].append({'HostIp': host_ip, 'HostPort': str(host_port)})
else:
expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}]
return expected_bound_ports
def _get_expected_links(self):
if self.parameters.links is None:
return None
self.log('parameter links:')
self.log(self.parameters.links, pretty_print=True)
exp_links = []
for link, alias in self.parameters.links:
exp_links.append("/%s:%s/%s" % (link, ('/' + self.parameters.name), alias))
return exp_links
def _get_expected_binds(self, image):
self.log('_get_expected_binds')
image_vols = []
if image:
image_vols = self._get_image_binds(image[self.parameters.client.image_inspect_source].get('Volumes'))
param_vols = []
if self.parameters.volumes:
for vol in self.parameters.volumes:
host = None
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
host, container, mode = vol.split(':') + ['rw']
if host:
param_vols.append("%s:%s:%s" % (host, container, mode))
result = list(set(image_vols + param_vols))
self.log("expected_binds:")
self.log(result, pretty_print=True)
return result
def _get_image_binds(self, volumes):
'''
Convert array of binds to array of strings with format host_path:container_path:mode
:param volumes: array of bind dicts
:return: array of strings
'''
results = []
if isinstance(volumes, dict):
results += self._get_bind_from_dict(volumes)
elif isinstance(volumes, list):
for vol in volumes:
results += self._get_bind_from_dict(vol)
return results
@staticmethod
def _get_bind_from_dict(volume_dict):
results = []
if volume_dict:
for host_path, config in volume_dict.items():
if isinstance(config, dict) and config.get('bind'):
container_path = config.get('bind')
mode = config.get('mode', 'rw')
results.append("%s:%s:%s" % (host_path, container_path, mode))
return results
def _get_expected_volumes(self, image):
self.log('_get_expected_volumes')
expected_vols = dict()
if image and image[self.parameters.client.image_inspect_source].get('Volumes'):
expected_vols.update(image[self.parameters.client.image_inspect_source].get('Volumes'))
if self.parameters.volumes:
for vol in self.parameters.volumes:
container = None
if ':' in vol:
if len(vol.split(':')) == 3:
dummy, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
dummy, container, mode = vol.split(':') + ['rw']
new_vol = dict()
if container:
new_vol[container] = dict()
else:
new_vol[vol] = dict()
expected_vols.update(new_vol)
if not expected_vols:
expected_vols = None
self.log("expected_volumes:")
self.log(expected_vols, pretty_print=True)
return expected_vols
def _get_expected_env(self, image):
self.log('_get_expected_env')
expected_env = dict()
if image and image[self.parameters.client.image_inspect_source].get('Env'):
for env_var in image[self.parameters.client.image_inspect_source]['Env']:
parts = env_var.split('=', 1)
expected_env[parts[0]] = parts[1]
if self.parameters.env:
expected_env.update(self.parameters.env)
param_env = []
for key, value in expected_env.items():
param_env.append("%s=%s" % (key, value))
return param_env
def _get_expected_exposed(self, image):
self.log('_get_expected_exposed')
image_ports = []
if image:
image_exposed_ports = image[self.parameters.client.image_inspect_source].get('ExposedPorts') or {}
image_ports = [self._normalize_port(p) for p in image_exposed_ports.keys()]
param_ports = []
if self.parameters.ports:
param_ports = [str(p[0]) + '/' + p[1] for p in self.parameters.ports]
result = list(set(image_ports + param_ports))
self.log(result, pretty_print=True)
return result
def _get_expected_ulimits(self, config_ulimits):
self.log('_get_expected_ulimits')
if config_ulimits is None:
return None
results = []
for limit in config_ulimits:
results.append(dict(
Name=limit.name,
Soft=limit.soft,
Hard=limit.hard
))
return results
def _get_expected_sysctls(self, config_sysctls):
self.log('_get_expected_sysctls')
if config_sysctls is None:
return None
result = dict()
for key, value in config_sysctls.items():
result[key] = str(value)
return result
def _get_expected_cmd(self):
self.log('_get_expected_cmd')
if not self.parameters.command:
return None
return shlex.split(self.parameters.command)
def _convert_simple_dict_to_list(self, param_name, join_with=':'):
if getattr(self.parameters, param_name, None) is None:
return None
results = []
for key, value in getattr(self.parameters, param_name).items():
results.append("%s%s%s" % (key, join_with, value))
return results
def _normalize_port(self, port):
if '/' not in port:
return port + '/tcp'
return port
def _get_expected_healthcheck(self):
self.log('_get_expected_healthcheck')
expected_healthcheck = dict()
if self.parameters.healthcheck:
expected_healthcheck.update([(k.title().replace("_", ""), v)
for k, v in self.parameters.healthcheck.items()])
return expected_healthcheck
class ContainerManager(DockerBaseClass):
'''
Perform container management tasks
'''
def __init__(self, client):
super(ContainerManager, self).__init__()
if client.module.params.get('log_options') and not client.module.params.get('log_driver'):
client.module.warn('log_options is ignored when log_driver is not specified')
if client.module.params.get('healthcheck') and not client.module.params.get('healthcheck').get('test'):
client.module.warn('healthcheck is ignored when test is not specified')
if client.module.params.get('restart_retries') is not None and not client.module.params.get('restart_policy'):
client.module.warn('restart_retries is ignored when restart_policy is not specified')
self.client = client
self.parameters = TaskParameters(client)
self.check_mode = self.client.check_mode
self.results = {'changed': False, 'actions': []}
self.diff = {}
self.diff_tracker = DifferenceTracker()
self.facts = {}
state = self.parameters.state
if state in ('stopped', 'started', 'present'):
self.present(state)
elif state == 'absent':
self.absent()
if not self.check_mode and not self.parameters.debug:
self.results.pop('actions')
if self.client.module._diff or self.parameters.debug:
self.diff['before'], self.diff['after'] = self.diff_tracker.get_before_after()
self.results['diff'] = self.diff
if self.facts:
self.results['ansible_facts'] = {'docker_container': self.facts}
self.results['container'] = self.facts
def present(self, state):
container = self._get_container(self.parameters.name)
was_running = container.running
was_paused = container.paused
container_created = False
# If the image parameter was passed then we need to deal with the image
# version comparison. Otherwise we handle this depending on whether
# the container already runs or not; in the former case, in case the
# container needs to be restarted, we use the existing container's
# image ID.
image = self._get_image()
self.log(image, pretty_print=True)
if not container.exists:
# New container
self.log('No container found')
if not self.parameters.image:
self.fail('Cannot create container when image is not specified!')
self.diff_tracker.add('exists', parameter=True, active=False)
new_container = self.container_create(self.parameters.image, self.parameters.create_parameters)
if new_container:
container = new_container
container_created = True
else:
# Existing container
different, differences = container.has_different_configuration(image)
image_different = False
if self.parameters.comparisons['image']['comparison'] == 'strict':
image_different = self._image_is_different(image, container)
if image_different or different or self.parameters.recreate:
self.diff_tracker.merge(differences)
self.diff['differences'] = differences.get_legacy_docker_container_diffs()
if image_different:
self.diff['image_different'] = True
self.log("differences")
self.log(differences.get_legacy_docker_container_diffs(), pretty_print=True)
image_to_use = self.parameters.image
if not image_to_use and container and container.Image:
image_to_use = container.Image
if not image_to_use:
self.fail('Cannot recreate container when image is not specified or cannot be extracted from current container!')
if container.running:
self.container_stop(container.Id)
self.container_remove(container.Id)
new_container = self.container_create(image_to_use, self.parameters.create_parameters)
if new_container:
container = new_container
container_created = True
if container and container.exists:
container = self.update_limits(container)
container = self.update_networks(container, container_created)
if state == 'started' and not container.running:
self.diff_tracker.add('running', parameter=True, active=was_running)
container = self.container_start(container.Id)
elif state == 'started' and self.parameters.restart:
self.diff_tracker.add('running', parameter=True, active=was_running)
self.diff_tracker.add('restarted', parameter=True, active=False)
container = self.container_restart(container.Id)
elif state == 'stopped' and container.running:
self.diff_tracker.add('running', parameter=False, active=was_running)
self.container_stop(container.Id)
container = self._get_container(container.Id)
if state == 'started' and container.paused is not None and container.paused != self.parameters.paused:
self.diff_tracker.add('paused', parameter=self.parameters.paused, active=was_paused)
if not self.check_mode:
try:
if self.parameters.paused:
self.client.pause(container=container.Id)
else:
self.client.unpause(container=container.Id)
except Exception as exc:
self.fail("Error %s container %s: %s" % (
"pausing" if self.parameters.paused else "unpausing", container.Id, str(exc)
))
container = self._get_container(container.Id)
self.results['changed'] = True
self.results['actions'].append(dict(set_paused=self.parameters.paused))
self.facts = container.raw
def absent(self):
container = self._get_container(self.parameters.name)
if container.exists:
if container.running:
self.diff_tracker.add('running', parameter=False, active=True)
self.container_stop(container.Id)
self.diff_tracker.add('exists', parameter=False, active=True)
self.container_remove(container.Id)
def fail(self, msg, **kwargs):
self.client.fail(msg, **kwargs)
def _output_logs(self, msg):
self.client.module.log(msg=msg)
def _get_container(self, container):
'''
Expects container ID or Name. Returns a container object
'''
return Container(self.client.get_container(container), self.parameters)
def _get_image(self):
if not self.parameters.image:
self.log('No image specified')
return None
if is_image_name_id(self.parameters.image):
image = self.client.find_image_by_id(self.parameters.image)
else:
repository, tag = utils.parse_repository_tag(self.parameters.image)
if not tag:
tag = "latest"
image = self.client.find_image(repository, tag)
if not image or self.parameters.pull:
if not self.check_mode:
self.log("Pull the image.")
image, alreadyToLatest = self.client.pull_image(repository, tag)
if alreadyToLatest:
self.results['changed'] = False
else:
self.results['changed'] = True
self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag)))
elif not image:
# If the image isn't there, claim we'll pull.
# (Implicitly: if the image is there, claim it already was latest.)
self.results['changed'] = True
self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag)))
self.log("image")
self.log(image, pretty_print=True)
return image
def _image_is_different(self, image, container):
if image and image.get('Id'):
if container and container.Image:
if image.get('Id') != container.Image:
self.diff_tracker.add('image', parameter=image.get('Id'), active=container.Image)
return True
return False
def update_limits(self, container):
limits_differ, different_limits = container.has_different_resource_limits()
if limits_differ:
self.log("limit differences:")
self.log(different_limits.get_legacy_docker_container_diffs(), pretty_print=True)
self.diff_tracker.merge(different_limits)
if limits_differ and not self.check_mode:
self.container_update(container.Id, self.parameters.update_parameters)
return self._get_container(container.Id)
return container
def update_networks(self, container, container_created):
updated_container = container
if self.parameters.comparisons['networks']['comparison'] != 'ignore' or container_created:
has_network_differences, network_differences = container.has_network_differences()
if has_network_differences:
if self.diff.get('differences'):
self.diff['differences'].append(dict(network_differences=network_differences))
else:
self.diff['differences'] = [dict(network_differences=network_differences)]
for netdiff in network_differences:
self.diff_tracker.add(
'network.{0}'.format(netdiff['parameter']['name']),
parameter=netdiff['parameter'],
active=netdiff['container']
)
self.results['changed'] = True
updated_container = self._add_networks(container, network_differences)
if (self.parameters.comparisons['networks']['comparison'] == 'strict' and self.parameters.networks is not None) or self.parameters.purge_networks:
has_extra_networks, extra_networks = container.has_extra_networks()
if has_extra_networks:
if self.diff.get('differences'):
self.diff['differences'].append(dict(purge_networks=extra_networks))
else:
self.diff['differences'] = [dict(purge_networks=extra_networks)]
for extra_network in extra_networks:
self.diff_tracker.add(
'network.{0}'.format(extra_network['name']),
active=extra_network
)
self.results['changed'] = True
updated_container = self._purge_networks(container, extra_networks)
return updated_container
def _add_networks(self, container, differences):
for diff in differences:
# remove the container from the network, if connected
if diff.get('container'):
self.results['actions'].append(dict(removed_from_network=diff['parameter']['name']))
if not self.check_mode:
try:
self.client.disconnect_container_from_network(container.Id, diff['parameter']['id'])
except Exception as exc:
self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'],
str(exc)))
# connect to the network
params = dict()
for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'):
if diff['parameter'].get(para):
params[para] = diff['parameter'][para]
self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=params))
if not self.check_mode:
try:
self.log("Connecting container to network %s" % diff['parameter']['id'])
self.log(params, pretty_print=True)
self.client.connect_container_to_network(container.Id, diff['parameter']['id'], **params)
except Exception as exc:
self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], str(exc)))
return self._get_container(container.Id)
def _purge_networks(self, container, networks):
for network in networks:
self.results['actions'].append(dict(removed_from_network=network['name']))
if not self.check_mode:
try:
self.client.disconnect_container_from_network(container.Id, network['name'])
except Exception as exc:
self.fail("Error disconnecting container from network %s - %s" % (network['name'],
str(exc)))
return self._get_container(container.Id)
def container_create(self, image, create_parameters):
self.log("create container")
self.log("image: %s parameters:" % image)
self.log(create_parameters, pretty_print=True)
self.results['actions'].append(dict(created="Created container", create_parameters=create_parameters))
self.results['changed'] = True
new_container = None
if not self.check_mode:
try:
new_container = self.client.create_container(image, **create_parameters)
self.client.report_warnings(new_container)
except Exception as exc:
self.fail("Error creating container: %s" % str(exc))
return self._get_container(new_container['Id'])
return new_container
def container_start(self, container_id):
self.log("start container %s" % (container_id))
self.results['actions'].append(dict(started=container_id))
self.results['changed'] = True
if not self.check_mode:
try:
self.client.start(container=container_id)
except Exception as exc:
self.fail("Error starting container %s: %s" % (container_id, str(exc)))
if self.parameters.detach is False:
if self.client.docker_py_version >= LooseVersion('3.0'):
status = self.client.wait(container_id)['StatusCode']
else:
status = self.client.wait(container_id)
if self.parameters.auto_remove:
output = "Cannot retrieve result as auto_remove is enabled"
if self.parameters.output_logs:
self.client.module.warn('Cannot output_logs if auto_remove is enabled!')
else:
config = self.client.inspect_container(container_id)
logging_driver = config['HostConfig']['LogConfig']['Type']
if logging_driver in ('json-file', 'journald'):
output = self.client.logs(container_id, stdout=True, stderr=True, stream=False, timestamps=False)
if self.parameters.output_logs:
self._output_logs(msg=output)
else:
output = "Result logged using `%s` driver" % logging_driver
if status != 0:
self.fail(output, status=status)
if self.parameters.cleanup:
self.container_remove(container_id, force=True)
insp = self._get_container(container_id)
if insp.raw:
insp.raw['Output'] = output
else:
insp.raw = dict(Output=output)
return insp
return self._get_container(container_id)
def container_remove(self, container_id, link=False, force=False):
volume_state = (not self.parameters.keep_volumes)
self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force))
self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force))
self.results['changed'] = True
response = None
if not self.check_mode:
count = 0
while True:
try:
response = self.client.remove_container(container_id, v=volume_state, link=link, force=force)
except NotFound as dummy:
pass
except APIError as exc:
if 'Unpause the container before stopping or killing' in exc.explanation:
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we don't end up in an infinite loop.
if count == 3:
self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc)))
count += 1
# Unpause
try:
self.client.unpause(container=container_id)
except Exception as exc2:
self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2)))
# Now try again
continue
if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation:
pass
else:
self.fail("Error removing container %s: %s" % (container_id, str(exc)))
except Exception as exc:
self.fail("Error removing container %s: %s" % (container_id, str(exc)))
# We only loop when explicitly requested by 'continue'
break
return response
def container_update(self, container_id, update_parameters):
if update_parameters:
self.log("update container %s" % (container_id))
self.log(update_parameters, pretty_print=True)
self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters))
self.results['changed'] = True
if not self.check_mode and callable(getattr(self.client, 'update_container')):
try:
result = self.client.update_container(container_id, **update_parameters)
self.client.report_warnings(result)
except Exception as exc:
self.fail("Error updating container %s: %s" % (container_id, str(exc)))
return self._get_container(container_id)
def container_kill(self, container_id):
self.results['actions'].append(dict(killed=container_id, signal=self.parameters.kill_signal))
self.results['changed'] = True
response = None
if not self.check_mode:
try:
if self.parameters.kill_signal:
response = self.client.kill(container_id, signal=self.parameters.kill_signal)
else:
response = self.client.kill(container_id)
except Exception as exc:
self.fail("Error killing container %s: %s" % (container_id, exc))
return response
def container_restart(self, container_id):
self.results['actions'].append(dict(restarted=container_id, timeout=self.parameters.stop_timeout))
self.results['changed'] = True
if not self.check_mode:
try:
if self.parameters.stop_timeout:
dummy = self.client.restart(container_id, timeout=self.parameters.stop_timeout)
else:
dummy = self.client.restart(container_id)
except Exception as exc:
self.fail("Error restarting container %s: %s" % (container_id, str(exc)))
return self._get_container(container_id)
def container_stop(self, container_id):
if self.parameters.force_kill:
self.container_kill(container_id)
return
self.results['actions'].append(dict(stopped=container_id, timeout=self.parameters.stop_timeout))
self.results['changed'] = True
response = None
if not self.check_mode:
count = 0
while True:
try:
if self.parameters.stop_timeout:
response = self.client.stop(container_id, timeout=self.parameters.stop_timeout)
else:
response = self.client.stop(container_id)
except APIError as exc:
if 'Unpause the container before stopping or killing' in exc.explanation:
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we don't end up in an infinite loop.
if count == 3:
self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc)))
count += 1
# Unpause
try:
self.client.unpause(container=container_id)
except Exception as exc2:
self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2)))
# Now try again
continue
self.fail("Error stopping container %s: %s" % (container_id, str(exc)))
except Exception as exc:
self.fail("Error stopping container %s: %s" % (container_id, str(exc)))
# We only loop when explicitly requested by 'continue'
break
return response
def detect_ipvX_address_usage(client):
'''
Helper function to detect whether any specified network uses ipv4_address or ipv6_address
'''
for network in client.module.params.get("networks") or []:
if network.get('ipv4_address') is not None or network.get('ipv6_address') is not None:
return True
return False
class AnsibleDockerClientContainer(AnsibleDockerClient):
# A list of module options which are not docker container properties
__NON_CONTAINER_PROPERTY_OPTIONS = tuple([
'env_file', 'force_kill', 'keep_volumes', 'ignore_image', 'name', 'pull', 'purge_networks',
'recreate', 'restart', 'state', 'trust_image_content', 'networks', 'cleanup', 'kill_signal',
'output_logs', 'paused'
] + list(DOCKER_COMMON_ARGS.keys()))
def _parse_comparisons(self):
comparisons = {}
comp_aliases = {}
# Put in defaults
explicit_types = dict(
command='list',
devices='set(dict)',
dns_search_domains='list',
dns_servers='list',
env='set',
entrypoint='list',
etc_hosts='set',
mounts='set(dict)',
networks='set(dict)',
ulimits='set(dict)',
device_read_bps='set(dict)',
device_write_bps='set(dict)',
device_read_iops='set(dict)',
device_write_iops='set(dict)',
)
all_options = set() # this is for improving user feedback when a wrong option was specified for comparison
default_values = dict(
stop_timeout='ignore',
)
for option, data in self.module.argument_spec.items():
all_options.add(option)
for alias in data.get('aliases', []):
all_options.add(alias)
# Ignore options which aren't used as container properties
if option in self.__NON_CONTAINER_PROPERTY_OPTIONS and option != 'networks':
continue
# Determine option type
if option in explicit_types:
datatype = explicit_types[option]
elif data['type'] == 'list':
datatype = 'set'
elif data['type'] == 'dict':
datatype = 'dict'
else:
datatype = 'value'
# Determine comparison type
if option in default_values:
comparison = default_values[option]
elif datatype in ('list', 'value'):
comparison = 'strict'
else:
comparison = 'allow_more_present'
comparisons[option] = dict(type=datatype, comparison=comparison, name=option)
# Keep track of aliases
comp_aliases[option] = option
for alias in data.get('aliases', []):
comp_aliases[alias] = option
# Process legacy ignore options
if self.module.params['ignore_image']:
comparisons['image']['comparison'] = 'ignore'
if self.module.params['purge_networks']:
comparisons['networks']['comparison'] = 'strict'
# Process options
if self.module.params.get('comparisons'):
# If '*' appears in comparisons, process it first
if '*' in self.module.params['comparisons']:
value = self.module.params['comparisons']['*']
if value not in ('strict', 'ignore'):
self.fail("The wildcard can only be used with comparison modes 'strict' and 'ignore'!")
for option, v in comparisons.items():
if option == 'networks':
# `networks` is special: only update if
# some value is actually specified
if self.module.params['networks'] is None:
continue
v['comparison'] = value
# Now process all other comparisons.
comp_aliases_used = {}
for key, value in self.module.params['comparisons'].items():
if key == '*':
continue
# Find main key
key_main = comp_aliases.get(key)
if key_main is None:
if key_main in all_options:
self.fail("The module option '%s' cannot be specified in the comparisons dict, "
"since it does not correspond to container's state!" % key)
self.fail("Unknown module option '%s' in comparisons dict!" % key)
if key_main in comp_aliases_used:
self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main))
comp_aliases_used[key_main] = key
# Check value and update accordingly
if value in ('strict', 'ignore'):
comparisons[key_main]['comparison'] = value
elif value == 'allow_more_present':
if comparisons[key_main]['type'] == 'value':
self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value))
comparisons[key_main]['comparison'] = value
else:
self.fail("Unknown comparison mode '%s'!" % value)
# Add implicit options
comparisons['publish_all_ports'] = dict(type='value', comparison='strict', name='published_ports')
comparisons['expected_ports'] = dict(type='dict', comparison=comparisons['published_ports']['comparison'], name='expected_ports')
comparisons['disable_healthcheck'] = dict(type='value',
comparison='ignore' if comparisons['healthcheck']['comparison'] == 'ignore' else 'strict',
name='disable_healthcheck')
# Check legacy values
if self.module.params['ignore_image'] and comparisons['image']['comparison'] != 'ignore':
self.module.warn('The ignore_image option has been overridden by the comparisons option!')
if self.module.params['purge_networks'] and comparisons['networks']['comparison'] != 'strict':
self.module.warn('The purge_networks option has been overridden by the comparisons option!')
self.comparisons = comparisons
def _get_additional_minimal_versions(self):
stop_timeout_supported = self.docker_api_version >= LooseVersion('1.25')
stop_timeout_needed_for_update = self.module.params.get("stop_timeout") is not None and self.module.params.get('state') != 'absent'
if stop_timeout_supported:
stop_timeout_supported = self.docker_py_version >= LooseVersion('2.1')
if stop_timeout_needed_for_update and not stop_timeout_supported:
# We warn (instead of fail) since in older versions, stop_timeout was not used
# to update the container's configuration, but only when stopping a container.
self.module.warn("Docker SDK for Python's version is %s. Minimum version required is 2.1 to update "
"the container's stop_timeout configuration. "
"If you use the 'docker-py' module, you have to switch to the 'docker' Python package." % (docker_version,))
else:
if stop_timeout_needed_for_update and not stop_timeout_supported:
# We warn (instead of fail) since in older versions, stop_timeout was not used
# to update the container's configuration, but only when stopping a container.
self.module.warn("Docker API version is %s. Minimum version required is 1.25 to set or "
"update the container's stop_timeout configuration." % (self.docker_api_version_str,))
self.option_minimal_versions['stop_timeout']['supported'] = stop_timeout_supported
def __init__(self, **kwargs):
option_minimal_versions = dict(
# internal options
log_config=dict(),
publish_all_ports=dict(),
ports=dict(),
volume_binds=dict(),
name=dict(),
# normal options
device_read_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_read_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_write_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_write_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
dns_opts=dict(docker_api_version='1.21', docker_py_version='1.10.0'),
ipc_mode=dict(docker_api_version='1.25'),
mac_address=dict(docker_api_version='1.25'),
oom_score_adj=dict(docker_api_version='1.22'),
shm_size=dict(docker_api_version='1.22'),
stop_signal=dict(docker_api_version='1.21'),
tmpfs=dict(docker_api_version='1.22'),
volume_driver=dict(docker_api_version='1.21'),
memory_reservation=dict(docker_api_version='1.21'),
kernel_memory=dict(docker_api_version='1.21'),
auto_remove=dict(docker_py_version='2.1.0', docker_api_version='1.25'),
healthcheck=dict(docker_py_version='2.0.0', docker_api_version='1.24'),
init=dict(docker_py_version='2.2.0', docker_api_version='1.25'),
runtime=dict(docker_py_version='2.4.0', docker_api_version='1.25'),
sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'),
userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'),
pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
mounts=dict(docker_py_version='2.6.0', docker_api_version='1.25'),
cpus=dict(docker_py_version='2.3.0', docker_api_version='1.25'),
# specials
ipvX_address_supported=dict(docker_py_version='1.9.0', docker_api_version='1.22',
detect_usage=detect_ipvX_address_usage,
usage_msg='ipv4_address or ipv6_address in networks'),
stop_timeout=dict(), # see _get_additional_minimal_versions()
)
super(AnsibleDockerClientContainer, self).__init__(
option_minimal_versions=option_minimal_versions,
option_minimal_versions_ignore_params=self.__NON_CONTAINER_PROPERTY_OPTIONS,
**kwargs
)
self.image_inspect_source = 'Config'
if self.docker_api_version < LooseVersion('1.21'):
self.image_inspect_source = 'ContainerConfig'
self._get_additional_minimal_versions()
self._parse_comparisons()
if self.module.params['container_default_behavior'] is None:
self.module.params['container_default_behavior'] = 'compatibility'
self.module.deprecate(
'The container_default_behavior option will change its default value from "compatibility" to '
'"no_defaults" in Ansible 2.14. To remove this warning, please specify an explicit value for it now',
version='2.14'
)
if self.module.params['container_default_behavior'] == 'compatibility':
old_default_values = dict(
auto_remove=False,
detach=True,
init=False,
interactive=False,
memory="0",
paused=False,
privileged=False,
read_only=False,
tty=False,
)
for param, value in old_default_values.items():
if self.module.params[param] is None:
self.module.params[param] = value
def main():
argument_spec = dict(
auto_remove=dict(type='bool'),
blkio_weight=dict(type='int'),
capabilities=dict(type='list', elements='str'),
cap_drop=dict(type='list', elements='str'),
cleanup=dict(type='bool', default=False),
command=dict(type='raw'),
comparisons=dict(type='dict'),
container_default_behavior=dict(type='str', choices=['compatibility', 'no_defaults']),
cpu_period=dict(type='int'),
cpu_quota=dict(type='int'),
cpus=dict(type='float'),
cpuset_cpus=dict(type='str'),
cpuset_mems=dict(type='str'),
cpu_shares=dict(type='int'),
detach=dict(type='bool'),
devices=dict(type='list', elements='str'),
device_read_bps=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='str'),
)),
device_write_bps=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='str'),
)),
device_read_iops=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='int'),
)),
device_write_iops=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='int'),
)),
dns_servers=dict(type='list', elements='str'),
dns_opts=dict(type='list', elements='str'),
dns_search_domains=dict(type='list', elements='str'),
domainname=dict(type='str'),
entrypoint=dict(type='list', elements='str'),
env=dict(type='dict'),
env_file=dict(type='path'),
etc_hosts=dict(type='dict'),
exposed_ports=dict(type='list', elements='str', aliases=['exposed', 'expose']),
force_kill=dict(type='bool', default=False, aliases=['forcekill']),
groups=dict(type='list', elements='str'),
healthcheck=dict(type='dict', options=dict(
test=dict(type='raw'),
interval=dict(type='str'),
timeout=dict(type='str'),
start_period=dict(type='str'),
retries=dict(type='int'),
)),
hostname=dict(type='str'),
ignore_image=dict(type='bool', default=False),
image=dict(type='str'),
init=dict(type='bool'),
interactive=dict(type='bool'),
ipc_mode=dict(type='str'),
keep_volumes=dict(type='bool', default=True),
kernel_memory=dict(type='str'),
kill_signal=dict(type='str'),
labels=dict(type='dict'),
links=dict(type='list', elements='str'),
log_driver=dict(type='str'),
log_options=dict(type='dict', aliases=['log_opt']),
mac_address=dict(type='str'),
memory=dict(type='str'),
memory_reservation=dict(type='str'),
memory_swap=dict(type='str'),
memory_swappiness=dict(type='int'),
mounts=dict(type='list', elements='dict', options=dict(
target=dict(type='str', required=True),
source=dict(type='str'),
type=dict(type='str', choices=['bind', 'volume', 'tmpfs', 'npipe'], default='volume'),
read_only=dict(type='bool'),
consistency=dict(type='str', choices=['default', 'consistent', 'cached', 'delegated']),
propagation=dict(type='str', choices=['private', 'rprivate', 'shared', 'rshared', 'slave', 'rslave']),
no_copy=dict(type='bool'),
labels=dict(type='dict'),
volume_driver=dict(type='str'),
volume_options=dict(type='dict'),
tmpfs_size=dict(type='str'),
tmpfs_mode=dict(type='str'),
)),
name=dict(type='str', required=True),
network_mode=dict(type='str'),
networks=dict(type='list', elements='dict', options=dict(
name=dict(type='str', required=True),
ipv4_address=dict(type='str'),
ipv6_address=dict(type='str'),
aliases=dict(type='list', elements='str'),
links=dict(type='list', elements='str'),
)),
networks_cli_compatible=dict(type='bool'),
oom_killer=dict(type='bool'),
oom_score_adj=dict(type='int'),
output_logs=dict(type='bool', default=False),
paused=dict(type='bool'),
pid_mode=dict(type='str'),
pids_limit=dict(type='int'),
privileged=dict(type='bool'),
published_ports=dict(type='list', elements='str', aliases=['ports']),
pull=dict(type='bool', default=False),
purge_networks=dict(type='bool', default=False),
read_only=dict(type='bool'),
recreate=dict(type='bool', default=False),
restart=dict(type='bool', default=False),
restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']),
restart_retries=dict(type='int'),
runtime=dict(type='str'),
security_opts=dict(type='list', elements='str'),
shm_size=dict(type='str'),
state=dict(type='str', default='started', choices=['absent', 'present', 'started', 'stopped']),
stop_signal=dict(type='str'),
stop_timeout=dict(type='int'),
sysctls=dict(type='dict'),
tmpfs=dict(type='list', elements='str'),
trust_image_content=dict(type='bool', default=False, removed_in_version='2.14'),
tty=dict(type='bool'),
ulimits=dict(type='list', elements='str'),
user=dict(type='str'),
userns_mode=dict(type='str'),
uts=dict(type='str'),
volume_driver=dict(type='str'),
volumes=dict(type='list', elements='str'),
volumes_from=dict(type='list', elements='str'),
working_dir=dict(type='str'),
)
required_if = [
('state', 'present', ['image'])
]
client = AnsibleDockerClientContainer(
argument_spec=argument_spec,
required_if=required_if,
supports_check_mode=True,
min_docker_api_version='1.20',
)
if client.module.params['networks_cli_compatible'] is None and client.module.params['networks']:
client.module.deprecate(
'Please note that docker_container handles networks slightly different than docker CLI. '
'If you specify networks, the default network will still be attached as the first network. '
'(You can specify purge_networks to remove all networks not explicitly listed.) '
'This behavior will change in Ansible 2.12. You can change the behavior now by setting '
'the new `networks_cli_compatible` option to `yes`, and remove this warning by setting '
'it to `no`',
version='2.12'
)
if client.module.params['networks_cli_compatible'] is True and client.module.params['networks'] and client.module.params['network_mode'] is None:
client.module.deprecate(
'Please note that the default value for `network_mode` will change from not specified '
'(which is equal to `default`) to the name of the first network in `networks` if '
'`networks` has at least one entry and `networks_cli_compatible` is `true`. You can '
'change the behavior now by explicitly setting `network_mode` to the name of the first '
'network in `networks`, and remove this warning by setting `network_mode` to `default`. '
'Please make sure that the value you set to `network_mode` equals the inspection result '
'for existing containers, otherwise the module will recreate them. You can find out the '
'correct value by running "docker inspect --format \'{{.HostConfig.NetworkMode}}\' <container_name>"',
version='2.14'
)
try:
cm = ContainerManager(client)
client.module.exit_json(**sanitize_result(cm.results))
except DockerException as e:
client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc())
except RequestException as e:
client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc())
if __name__ == '__main__':
main()
| Lujeni/ansible | lib/ansible/modules/cloud/docker/docker_container.py | Python | gpl-3.0 | 143,393 |
/*
* WebSocketMessage.cpp
*
* Created on: Sep 10, 2015
* Author: lion
*/
#include "object.h"
#include "ifs/io.h"
#include "WebSocketMessage.h"
#include "Buffer.h"
#include "MemoryStream.h"
namespace fibjs {
result_t WebSocketMessage_base::_new(int32_t type, bool masked, int32_t maxSize,
obj_ptr<WebSocketMessage_base>& retVal,
v8::Local<v8::Object> This)
{
retVal = new WebSocketMessage(type, masked, maxSize);
return 0;
}
result_t WebSocketMessage::get_value(exlib::string& retVal)
{
return m_message->get_value(retVal);
}
result_t WebSocketMessage::set_value(exlib::string newVal)
{
return m_message->set_value(newVal);
}
result_t WebSocketMessage::get_params(obj_ptr<List_base>& retVal)
{
return m_message->get_params(retVal);
}
result_t WebSocketMessage::set_params(List_base* newVal)
{
return m_message->set_params(newVal);
}
result_t WebSocketMessage::get_body(obj_ptr<SeekableStream_base>& retVal)
{
return m_message->get_body(retVal);
}
result_t WebSocketMessage::set_body(SeekableStream_base* newVal)
{
return m_message->set_body(newVal);
}
result_t WebSocketMessage::read(int32_t bytes, obj_ptr<Buffer_base>& retVal,
AsyncEvent* ac)
{
return m_message->read(bytes, retVal, ac);
}
result_t WebSocketMessage::readAll(obj_ptr<Buffer_base>& retVal, AsyncEvent* ac)
{
return m_message->readAll(retVal, ac);
}
result_t WebSocketMessage::write(Buffer_base* data, AsyncEvent* ac)
{
return m_message->write(data, ac);
}
result_t WebSocketMessage::get_length(int64_t& retVal)
{
return m_message->get_length(retVal);
}
result_t WebSocketMessage::get_lastError(exlib::string& retVal)
{
return m_message->get_lastError(retVal);
}
result_t WebSocketMessage::set_lastError(exlib::string newVal)
{
return m_message->set_lastError(newVal);
}
result_t WebSocketMessage::end()
{
return m_message->end();
}
result_t WebSocketMessage::isEnded(bool& retVal)
{
return m_message->isEnded(retVal);
}
result_t WebSocketMessage::clear()
{
m_message = new Message(m_bRep);
return 0;
}
result_t WebSocketMessage::copy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac)
{
class asyncCopy : public AsyncState {
public:
asyncCopy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac)
: AsyncState(ac)
, m_from(from)
, m_to(to)
, m_bytes(bytes)
, m_mask(mask)
, m_copyed(0)
{
set(read);
}
static int32_t read(AsyncState* pState, int32_t n)
{
asyncCopy* pThis = (asyncCopy*)pState;
int64_t len;
pThis->set(write);
if (pThis->m_bytes == 0)
return pThis->done();
if (pThis->m_bytes > STREAM_BUFF_SIZE)
len = STREAM_BUFF_SIZE;
else
len = pThis->m_bytes;
pThis->m_buf.Release();
return pThis->m_from->read((int32_t)len, pThis->m_buf, pThis);
}
static int32_t write(AsyncState* pState, int32_t n)
{
asyncCopy* pThis = (asyncCopy*)pState;
int32_t blen;
pThis->set(read);
if (n == CALL_RETURN_NULL)
return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed."));
if (pThis->m_mask != 0) {
exlib::string strBuffer;
int32_t i, n;
uint8_t* mask = (uint8_t*)&pThis->m_mask;
pThis->m_buf->toString(strBuffer);
n = (int32_t)strBuffer.length();
for (i = 0; i < n; i++)
strBuffer[i] ^= mask[(pThis->m_copyed + i) & 3];
pThis->m_buf = new Buffer(strBuffer);
}
pThis->m_buf->get_length(blen);
pThis->m_copyed += blen;
if (pThis->m_bytes > 0)
pThis->m_bytes -= blen;
return pThis->m_to->write(pThis->m_buf, pThis);
}
public:
obj_ptr<Stream_base> m_from;
obj_ptr<Stream_base> m_to;
int64_t m_bytes;
uint32_t m_mask;
int64_t m_copyed;
obj_ptr<Buffer_base> m_buf;
};
if (!ac)
return CHECK_ERROR(CALL_E_NOSYNC);
return (new asyncCopy(from, to, bytes, mask, ac))->post(0);
}
result_t WebSocketMessage::sendTo(Stream_base* stm, AsyncEvent* ac)
{
class asyncSendTo : public AsyncState {
public:
asyncSendTo(WebSocketMessage* pThis, Stream_base* stm,
AsyncEvent* ac)
: AsyncState(ac)
, m_pThis(pThis)
, m_stm(stm)
, m_mask(0)
{
m_pThis->get_body(m_body);
m_body->rewind();
m_body->size(m_size);
m_ms = new MemoryStream();
set(head);
}
static int32_t head(AsyncState* pState, int32_t n)
{
asyncSendTo* pThis = (asyncSendTo*)pState;
uint8_t buf[16];
int32_t pos = 0;
int32_t type;
pThis->m_pThis->get_type(type);
buf[0] = 0x80 | (type & 0x0f);
int64_t size = pThis->m_size;
if (size < 126) {
buf[1] = (uint8_t)size;
pos = 2;
} else if (size < 65536) {
buf[1] = 126;
buf[2] = (uint8_t)(size >> 8);
buf[3] = (uint8_t)(size & 0xff);
pos = 4;
} else {
buf[1] = 127;
buf[2] = (uint8_t)((size >> 56) & 0xff);
buf[3] = (uint8_t)((size >> 48) & 0xff);
buf[4] = (uint8_t)((size >> 40) & 0xff);
buf[5] = (uint8_t)((size >> 32) & 0xff);
buf[6] = (uint8_t)((size >> 24) & 0xff);
buf[7] = (uint8_t)((size >> 16) & 0xff);
buf[8] = (uint8_t)((size >> 8) & 0xff);
buf[9] = (uint8_t)(size & 0xff);
pos = 10;
}
if (pThis->m_pThis->m_masked) {
buf[1] |= 0x80;
uint32_t r = 0;
while (r == 0)
r = rand();
pThis->m_mask = r;
buf[pos++] = (uint8_t)(r & 0xff);
buf[pos++] = (uint8_t)((r >> 8) & 0xff);
buf[pos++] = (uint8_t)((r >> 16) & 0xff);
buf[pos++] = (uint8_t)((r >> 24) & 0xff);
}
pThis->m_buffer = new Buffer((const char*)buf, pos);
pThis->set(sendData);
return pThis->m_ms->write(pThis->m_buffer, pThis);
}
static int32_t sendData(AsyncState* pState, int32_t n)
{
asyncSendTo* pThis = (asyncSendTo*)pState;
pThis->set(sendToStream);
return copy(pThis->m_body, pThis->m_ms, pThis->m_size, pThis->m_mask, pThis);
}
static int32_t sendToStream(AsyncState* pState, int32_t n)
{
asyncSendTo* pThis = (asyncSendTo*)pState;
pThis->m_ms->rewind();
pThis->set(NULL);
return io_base::copyStream(pThis->m_ms, pThis->m_stm, -1, pThis->m_size, pThis);
}
public:
obj_ptr<MemoryStream_base> m_ms;
WebSocketMessage* m_pThis;
obj_ptr<Stream_base> m_stm;
obj_ptr<SeekableStream_base> m_body;
int64_t m_size;
uint32_t m_mask;
obj_ptr<Buffer_base> m_buffer;
};
if (!ac)
return CHECK_ERROR(CALL_E_NOSYNC);
return (new asyncSendTo(this, stm, ac))->post(0);
}
result_t WebSocketMessage::readFrom(Stream_base* stm, AsyncEvent* ac)
{
class asyncReadFrom : public AsyncState {
public:
asyncReadFrom(WebSocketMessage* pThis, Stream_base* stm,
AsyncEvent* ac)
: AsyncState(ac)
, m_pThis(pThis)
, m_stm(stm)
, m_fin(false)
, m_masked(false)
, m_fragmented(false)
, m_size(0)
, m_fullsize(0)
, m_mask(0)
{
m_pThis->get_body(m_body);
set(head);
}
static int32_t head(AsyncState* pState, int32_t n)
{
asyncReadFrom* pThis = (asyncReadFrom*)pState;
pThis->set(extHead);
return pThis->m_stm->read(2, pThis->m_buffer, pThis);
}
static int32_t extHead(AsyncState* pState, int32_t n)
{
asyncReadFrom* pThis = (asyncReadFrom*)pState;
if (n == CALL_RETURN_NULL) {
pThis->m_pThis->m_error = 1001;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed."));
}
exlib::string strBuffer;
char ch;
int32_t sz = 0;
pThis->m_buffer->toString(strBuffer);
pThis->m_buffer.Release();
ch = strBuffer[0];
if (ch & 0x70) {
pThis->m_pThis->m_error = 1007;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: non-zero RSV values."));
}
pThis->m_fin = (ch & 0x80) != 0;
if (pThis->m_fragmented) {
if ((ch & 0x0f) != ws_base::_CONTINUE) {
pThis->m_pThis->m_error = 1007;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed."));
}
} else
pThis->m_pThis->set_type(ch & 0x0f);
ch = strBuffer[1];
if (pThis->m_fragmented) {
if (pThis->m_masked != (pThis->m_pThis->m_masked = (ch & 0x80) != 0)) {
pThis->m_pThis->m_error = 1007;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed."));
}
} else
pThis->m_masked = pThis->m_pThis->m_masked = (ch & 0x80) != 0;
if (pThis->m_masked)
sz += 4;
pThis->m_size = ch & 0x7f;
if (pThis->m_size == 126)
sz += 2;
else if (pThis->m_size == 127)
sz += 8;
if (sz) {
pThis->set(extReady);
return pThis->m_stm->read(sz, pThis->m_buffer, pThis);
}
pThis->set(body);
return 0;
}
static int32_t extReady(AsyncState* pState, int32_t n)
{
asyncReadFrom* pThis = (asyncReadFrom*)pState;
if (n == CALL_RETURN_NULL) {
pThis->m_pThis->m_error = 1007;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed."));
}
exlib::string strBuffer;
int32_t pos = 0;
pThis->m_buffer->toString(strBuffer);
pThis->m_buffer.Release();
if (pThis->m_size == 126) {
pThis->m_size = ((uint32_t)(uint8_t)strBuffer[0] << 8) + (uint8_t)strBuffer[1];
pos += 2;
} else if (pThis->m_size == 127) {
pThis->m_size = ((int64_t)(uint8_t)strBuffer[0] << 56) + ((int64_t)(uint8_t)strBuffer[1] << 48) + ((int64_t)(uint8_t)strBuffer[2] << 40) + ((int64_t)(uint8_t)strBuffer[3] << 32) + ((int64_t)(uint8_t)strBuffer[4] << 24) + ((int64_t)(uint8_t)strBuffer[5] << 16) + ((int64_t)(uint8_t)strBuffer[6] << 8) + (int64_t)(uint8_t)strBuffer[7];
pos += 8;
}
if (pThis->m_masked)
memcpy(&pThis->m_mask, &strBuffer[pos], 4);
pThis->set(body);
return 0;
}
static int32_t body(AsyncState* pState, int32_t n)
{
asyncReadFrom* pThis = (asyncReadFrom*)pState;
if (pThis->m_fullsize + pThis->m_size > pThis->m_pThis->m_maxSize) {
pThis->m_pThis->m_error = 1009;
return CHECK_ERROR(Runtime::setError("WebSocketMessage: Message Too Big."));
}
pThis->set(body_end);
return copy(pThis->m_stm, pThis->m_body, pThis->m_size, pThis->m_mask, pThis);
}
static int32_t body_end(AsyncState* pState, int32_t n)
{
asyncReadFrom* pThis = (asyncReadFrom*)pState;
if (!pThis->m_fin) {
pThis->m_fragmented = true;
pThis->m_mask = 0;
pThis->m_fullsize += pThis->m_size;
pThis->set(head);
return 0;
}
pThis->m_body->rewind();
return pThis->done();
}
public:
WebSocketMessage* m_pThis;
obj_ptr<Stream_base> m_stm;
obj_ptr<SeekableStream_base> m_body;
obj_ptr<Buffer_base> m_buffer;
bool m_fin;
bool m_masked;
bool m_fragmented;
int64_t m_size;
int64_t m_fullsize;
uint32_t m_mask;
};
if (!ac)
return CHECK_ERROR(CALL_E_NOSYNC);
m_stm = stm;
return (new asyncReadFrom(this, stm, ac))->post(0);
}
result_t WebSocketMessage::get_stream(obj_ptr<Stream_base>& retVal)
{
if (!m_stm)
return CALL_RETURN_NULL;
retVal = m_stm;
return 0;
}
result_t WebSocketMessage::get_response(obj_ptr<Message_base>& retVal)
{
if (m_bRep)
return CHECK_ERROR(CALL_E_INVALID_CALL);
if (!m_message->m_response) {
int32_t type;
get_type(type);
if (type == ws_base::_PING)
type = ws_base::_PONG;
m_message->m_response = new WebSocketMessage(type, false, m_maxSize, true);
}
return m_message->get_response(retVal);
}
result_t WebSocketMessage::get_type(int32_t& retVal)
{
return m_message->get_type(retVal);
}
result_t WebSocketMessage::set_type(int32_t newVal)
{
return m_message->set_type(newVal);
}
result_t WebSocketMessage::get_data(v8::Local<v8::Value>& retVal)
{
return m_message->get_data(retVal);
}
result_t WebSocketMessage::get_masked(bool& retVal)
{
retVal = m_masked;
return 0;
}
result_t WebSocketMessage::set_masked(bool newVal)
{
m_masked = newVal;
return 0;
}
result_t WebSocketMessage::get_maxSize(int32_t& retVal)
{
retVal = m_maxSize;
return 0;
}
result_t WebSocketMessage::set_maxSize(int32_t newVal)
{
if (newVal < 0)
return CHECK_ERROR(CALL_E_OUTRANGE);
m_maxSize = newVal;
return 0;
}
} /* namespace fibjs */
| ngot/nightly-test | fibjs/src/websocket/WebSocketMessage.cpp | C++ | gpl-3.0 | 14,485 |
# This file is part of GxSubOS.
# Copyright (C) 2014 Christopher Kyle Horton <christhehorton@gmail.com>
# GxSubOS 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.
# GxSubOS 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 GxSubOS. If not, see <http://www.gnu.org/licenses/>.
import sys, pygame
from indicator import Indicator
import glass, shadow
transparent = pygame.color.Color(0, 0, 0, 0)
class IndicatorTray():
'''A class implementing a tray where various Indicators are displayed.'''
tray_color = glass.glass_color
tray_color_opaque = glass.glass_color
tray_color.a = glass.glass_alpha
tray_height = 24
shadow_height = 10
def __init__(self, screenw, screenh, wm=None):
self.indicator_list = []
self.surface = glass.MakeTransparentSurface(screenw, self.tray_height + self.shadow_height)
if glass.enable_transparency:
self.surface.fill(self.tray_color)
self.color_surface = pygame.Surface((screenw, self.tray_height), pygame.SRCALPHA)
self.color_surface.fill(self.tray_color)
else:
self.surface.fill(self.tray_color_opaque)
self.color_surface = pygame.Surface((screenw, self.tray_height))
self.color_surface.fill(self.tray_color_opaque)
self.update_rect = pygame.Rect(0, 0, 0, 0)
self.wm = wm
def SetWindowManager(self, windowmanager):
'''Sets the WindowManager that this IndicatorTray will connect to.'''
self.wm = windowmanager
def GetIndicatorsWidth(self):
'''Returns the total width in pixels of all the Indicators currently stored
in the indicator_list.'''
width = 0
for indicator in self.indicator_list:
width += indicator.width
return width
def UpdateIndicatorPositions(self):
'''Updates the positions of all the Indicators in the list.'''
next_right = 0
for indicator in self.indicator_list:
new_x = pygame.display.Info().current_w - next_right - indicator.width
self.update_rect.union_ip(indicator.UpdatePosition(new_x))
next_right += indicator.width
def RedrawBackground(self, screen):
'''Redraw the background behind the Indicators.'''
tray_width = self.GetIndicatorsWidth()
tray_left = pygame.display.Info().current_w - tray_width
glass.DrawBackground(screen, self.surface, self.surface.get_rect())
if glass.enable_transparency:
self.surface = glass.Blur(self.surface)
self.surface.blit(self.color_surface, [0, 0, 0, 0])
triangle_points = [(tray_left - self.tray_height, 0), (tray_left - self.tray_height, self.tray_height), (tray_left, self.tray_height)]
pygame.draw.polygon(self.surface, transparent, triangle_points)
pygame.draw.rect(self.surface, transparent, pygame.Rect(0, 0, tray_left - self.tray_height, self.tray_height))
pygame.draw.rect(self.surface, transparent, pygame.Rect(0, self.tray_height, self.surface.get_width(), self.surface.get_height() - self.tray_height))
shadow.DrawIndicatorTrayShadow(self)
def DrawTray(self, screen):
'''Draws this IndicatorTray onto the provided Surface. Returns a Rect
containing the area which was drawn to.'''
screen.blit(self.surface, (0, 0))
for indicator in self.indicator_list:
screen.blit(indicator.image, indicator.rect)
return self.update_rect
def UpdateWholeTray(self, screen):
'''Update the whole IndicatorTray and its Indicators.'''
self.UpdateIndicatorPositions()
for indicator in self.indicator_list:
indicator.RunFrameCode()
self.RemoveClosedIndicators()
self.RedrawBackground(screen)
def AddIndicator(self, indicator_name):
'''Adds the given Indicator based on the provided name.
Returns a reference to the Indicator added.'''
indicator = Indicator(len(self.indicator_list), indicator_name, self.wm)
self.indicator_list.append(indicator)
return indicator
def RemoveClosedIndicators(self):
'''Removes any Indicators which indicate that they are closed.'''
for indicator in self.indicator_list:
if indicator.closed == True:
self.indicator_list.remove(indicator)
# Maintain indicator order
new_number = 0
for indicator in self.indicator_list:
indicator.number = new_number
def HandleMouseButtonDownEvent(self, mouse_event, mouse_button):
'''Pass MOUSEDOWN events to the Indicators this holds.'''
for indicator in self.indicator_list:
indicator.HandleMouseButtonDownEvent(mouse_event, mouse_button)
| WarriorIng64/GxSubOS | indicatortray.py | Python | gpl-3.0 | 4,871 |
package com.glue.feed.youtube;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.glue.domain.Event;
import com.glue.domain.Link;
import com.glue.domain.LinkType;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;
public class YoutubeRequester {
static final Logger LOG = LoggerFactory.getLogger(YoutubeRequester.class);
/** Global instance properties filename. */
private static String PROPERTIES_FILENAME = "/com/glue/feed/youtube.properties";
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
/**
* Global instance of the max number of videos we want returned (50 = upper
* limit per page).
*/
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
/** Global instance of Youtube object to make all API requests. */
private static YouTube youtube;
/** Properties */
private Properties properties;
private DateFormat formater = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
private Calendar calendar = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
// Current research
private YouTube.Search.List search;
// Videos details
private YouTube.Videos.List searchForVideos;
private YoutubeRequester() {
initialize();
}
/** Singleton Holder */
private static class YoutubeRequesterHolder {
/** Singleton */
private final static YoutubeRequester instance = new YoutubeRequester();
}
/** Get Singleton */
public static YoutubeRequester getInstance() {
return YoutubeRequesterHolder.instance;
}
private void initialize() {
// youtube.properties
properties = new Properties();
try {
InputStream in = YoutubeRequester.class
.getResourceAsStream(PROPERTIES_FILENAME);
properties.load(in);
} catch (IOException e) {
System.err.println("There was an error reading "
+ PROPERTIES_FILENAME + ": " + e.getCause() + " : "
+ e.getMessage());
System.exit(1);
}
try {
/*
* The YouTube object is used to make all API requests. The last
* argument is required, but because we don't need anything
* initialized when the HttpRequest is initialized, we override the
* interface and provide a no-op function.
*/
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY,
new HttpRequestInitializer() {
public void initialize(HttpRequest request)
throws IOException {
}
}).setApplicationName("Glue").build();
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
}
public Event search(Event event) throws IOException {
// Create a youtube search list
search = youtube.search().list("id,snippet");
String apiKey = properties.getProperty("youtube.apikey");
search.setKey(apiKey);
search.set("safeSearch", "moderate");
search.set("videoEmbeddable", "true");
search.setType("video");
search.setFields("items(id/videoId,snippet/title)");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
// Set calendar to enddate
calendar.setTime(event.getStopTime());
// Query stream title + stream venue + day + month (january = 0)
search.setQ(event.getTitle() + " " + event.getVenue().getName());
// Published after stream end_date
search.set("publishedAfter", formater.format(calendar.getTime()));
// Published before enddate +30
calendar.add(Calendar.DATE, +30);
search.set("publishedBefore", formater.format(calendar.getTime()));
// Search
SearchListResponse searchResponse = search.execute();
// If videos found
if (!searchResponse.getItems().isEmpty()) {
// Create a string a videos ids separated by comma
List<String> videosIds = new ArrayList<>();
for (SearchResult video : searchResponse.getItems()) {
videosIds.add(video.getId().getVideoId());
}
String ids = "";
for (String vId : videosIds) {
ids += vId + ",";
}
// Remove last comma
ids = ids.substring(0, ids.lastIndexOf(","));
// Search for videos details
searchForVideos = youtube.videos().list(ids, "snippet");
searchForVideos.setKey(properties.getProperty("youtube.apikey"));
search.setFields("items(snippet/title,snippet/description)");
VideoListResponse videosResponse = searchForVideos.execute();
// for each videos, check similarity and create media
for (Video video : videosResponse.getItems()) {
if (checkSimilarity(event, video)) {
LOG.info(video.getSnippet().getTitle());
Link link = new Link();
link.setType(LinkType.WEBCAST);
link.setUrl("http://www.youtube.com/embed/" + video.getId());
event.getLinks().add(link);
}
}
}
return event;
}
// Check similarity between youtube video and stream
private boolean checkSimilarity(Event event, Video video) {
// Get title and description from video
String vTitle = video.getSnippet().getTitle().toLowerCase().trim();
String vDescription = video.getSnippet().getDescription().toLowerCase()
.trim();
// Stream title
String sTitle = event.getTitle().toLowerCase();
// Stream description, remove "le" "la"
String venue = event.getVenue().getName().toLowerCase();
if (venue.startsWith("le ")) {
venue = venue.substring(3);
} else if (venue.startsWith("la ")) {
venue = venue.substring(3);
}
// Video title must contain stream title
boolean filterOne = vTitle.matches(".*\\b" + sTitle + "\\b.*");
// Title or description must contain venue name
boolean filterTwo = (vTitle.contains(venue))
|| (vDescription.contains(venue));
return filterOne && filterTwo;
}
} | pgillet/Glue | glue-feed/src/main/java/com/glue/feed/youtube/YoutubeRequester.java | Java | gpl-3.0 | 6,629 |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Security.Claims;
using Microsoft.AspNet.Identity;
namespace LanAdeptData.Model
{
public class User : IdentityUser
{
[Required]
[Display(Name = "Nom complet")]
public string CompleteName { get; set; }
public string Barcode { get; set; }
#region Navigation properties
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual ICollection<Team> Teams { get; set; }
public virtual ICollection<Order> Orders { get; set; }
#endregion
#region Calculated properties
public Reservation LastReservation
{
get
{
return Reservations.OrderBy(r => r.CreationDate).LastOrDefault();
}
}
#endregion
#region Identity Methods
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
#endregion
}
}
| ADEPT-Informatique/LanAdept | LanAdeptData/Model/Users/User.cs | C# | gpl-3.0 | 1,133 |
package to.oa.qha98.ballisticCalculator.test;
import static org.junit.Assert.*;
import org.bukkit.util.Vector;
import org.junit.Test;
public class VectorDefaultConstructorTest {
@Test
public void test() {
Vector v=new Vector();
assertEquals(0d, v.length(), 0.0000001d);
}
}
| qha98/BallisticCalculator | BalisticCalculator/BallisticCalculator/to/oa/qha98/ballisticCalculator/test/VectorDefaultConstructorTest.java | Java | gpl-3.0 | 298 |