code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package net.minecartrapidtransit.path.launcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileStoreUtils {
private String version;
public FileStoreUtils(String versionFile) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(new File(getDataFilePath(versionFile))));
version = br.readLine();
br.close();
}
public String getVersionedFile(String filename, String type){
return String.format("%s-%s.%s", filename, version, type);
}
public boolean fileNeedsUpdating(String filename, String type) {
return(new File(getVersionedFile(filename, type)).exists());
}
public String getVersionedDataFilePath(String filename, String type){
return getDataFilePath(getVersionedFile(filename, type));
}
public static String getDataFolderPath(){
String os = System.getProperty("os.name").toLowerCase();
boolean windows = os.contains("windows");
boolean mac = os.contains("macosx");
if(windows){
return System.getenv("APPDATA") + "\\MRTPath2";
}else{
String home = System.getProperty("user.home");
if(mac){
return home + "/Library/Application Support/MRTPath2";
}else{ // Linux
return home + "/.mrtpath2";
}
}
}
public static String getDataFilePath(String file){
return getDataFolderPath() + File.separator + file.replace('/', File.separatorChar);
}
}
| MinecartRapidTransit/MRTPath2 | launcher/src/main/java/net/minecartrapidtransit/path/launcher/FileStoreUtils.java | Java | gpl-2.0 | 1,412 |
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2016 Icinga Development Team (https://www.icinga.org/) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#include "livestatus/endpointstable.hpp"
#include "icinga/host.hpp"
#include "icinga/service.hpp"
#include "icinga/icingaapplication.hpp"
#include "remote/endpoint.hpp"
#include "remote/zone.hpp"
#include "base/configtype.hpp"
#include "base/objectlock.hpp"
#include "base/convert.hpp"
#include "base/utility.hpp"
#include <boost/algorithm/string/classification.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace icinga;
EndpointsTable::EndpointsTable(void)
{
AddColumns(this);
}
void EndpointsTable::AddColumns(Table *table, const String& prefix,
const Column::ObjectAccessor& objectAccessor)
{
table->AddColumn(prefix + "name", Column(&EndpointsTable::NameAccessor, objectAccessor));
table->AddColumn(prefix + "identity", Column(&EndpointsTable::IdentityAccessor, objectAccessor));
table->AddColumn(prefix + "node", Column(&EndpointsTable::NodeAccessor, objectAccessor));
table->AddColumn(prefix + "is_connected", Column(&EndpointsTable::IsConnectedAccessor, objectAccessor));
table->AddColumn(prefix + "zone", Column(&EndpointsTable::ZoneAccessor, objectAccessor));
}
String EndpointsTable::GetName(void) const
{
return "endpoints";
}
String EndpointsTable::GetPrefix(void) const
{
return "endpoint";
}
void EndpointsTable::FetchRows(const AddRowFunction& addRowFn)
{
for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) {
if (!addRowFn(endpoint, LivestatusGroupByNone, Empty))
return;
}
}
Value EndpointsTable::NameAccessor(const Value& row)
{
Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row);
if (!endpoint)
return Empty;
return endpoint->GetName();
}
Value EndpointsTable::IdentityAccessor(const Value& row)
{
Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row);
if (!endpoint)
return Empty;
return endpoint->GetName();
}
Value EndpointsTable::NodeAccessor(const Value& row)
{
Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row);
if (!endpoint)
return Empty;
return IcingaApplication::GetInstance()->GetNodeName();
}
Value EndpointsTable::IsConnectedAccessor(const Value& row)
{
Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row);
if (!endpoint)
return Empty;
unsigned int is_connected = endpoint->GetConnected() ? 1 : 0;
/* if identity is equal to node, fake is_connected */
if (endpoint->GetName() == IcingaApplication::GetInstance()->GetNodeName())
is_connected = 1;
return is_connected;
}
Value EndpointsTable::ZoneAccessor(const Value& row)
{
Endpoint::Ptr endpoint = static_cast<Endpoint::Ptr>(row);
if (!endpoint)
return Empty;
Zone::Ptr zone = endpoint->GetZone();
if (!zone)
return Empty;
return zone->GetName();
}
| zearan/icinga2 | lib/livestatus/endpointstable.cpp | C++ | gpl-2.0 | 4,193 |
<?php
/**
* @file
* Banana class.
*/
namespace Drupal\oop_example_12\BusinessLogic\Fruit;
/**
* Banana class.
*/
class Banana extends Fruit {
/**
* Returns color of the object.
*/
public function getColor() {
return t('yellow');
}
}
| nfouka/poo_d8 | oop_examples/oop_example_12/src/BusinessLogic/Fruit/Banana.php | PHP | gpl-2.0 | 258 |
/*
* Copyright (c) 2011 Picochip Ltd., Jamie Iles
*
* This file contains the hardware definitions of the picoXcell SoC devices.
*
* 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.
*/
#ifndef __ASM_ARCH_HARDWARE_H
#define __ASM_ARCH_HARDWARE_H
#include <mach/picoxcell_soc.h>
#endif
| Jackeagle/android_kernel_sony_c2305 | arch/arm/mach-picoxcell/include/mach/hardware.h | C | gpl-2.0 | 761 |
<?php
/**
* The template for displaying the footer.
*
* @package WordPress
*/
?>
</div>
</div>
<!-- Begin footer -->
<div id="footer">
<?php
$pp_footer_display_sidebar = get_option('pp_footer_display_sidebar');
if(!empty($pp_footer_display_sidebar))
{
$pp_footer_style = get_option('pp_footer_style');
$footer_class = '';
switch($pp_footer_style)
{
case 1:
$footer_class = 'one';
break;
case 2:
$footer_class = 'two';
break;
case 3:
$footer_class = 'three';
break;
case 4:
$footer_class = 'four';
break;
default:
$footer_class = 'four';
break;
}
?>
<ul class="sidebar_widget <?php echo $footer_class; ?>">
<?php dynamic_sidebar('Footer Sidebar'); ?>
</ul>
<br class="clear"/>
<?php
}
?>
</div>
<!-- End footer -->
<div>
<div>
<div id="copyright" <?php if(empty($pp_footer_display_sidebar)) { echo 'style="border-top:0"'; } ?>>
<div class="copyright_wrapper">
<div class="one_fourth">
<?php
/**
* Get footer left text
*/
$pp_footer_text = get_option('pp_footer_text');
if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
$pp_footer_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_text);
}
if(empty($pp_footer_text))
{
$pp_footer_text = 'Copyright © 2012 Nemesis Theme. Powered by <a href="http://wordpress.org/">Wordpress</a>.<br/>Wordpress theme by <a href="http://themeforest.net/user/peerapong/portfolio" target="_blank">Peerapong</a>';
}
echo nl2br(stripslashes(html_entity_decode($pp_footer_text)));
?>
</div>
<div class="one_fourth">
<?php
/**
* Get footer left text
*/
$pp_footer_second_text = get_option('pp_footer_second_text');
if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
$pp_footer_second_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_second_text);
}
if(empty($pp_footer_second_text))
{
$pp_footer_second_text = ' ';
}
echo nl2br(stripslashes(html_entity_decode($pp_footer_second_text)));
?>
</div>
<div class="one_fourth">
<?php
/**
* Get footer left text
*/
$pp_footer_third_text = get_option('pp_footer_third_text');
if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
$pp_footer_third_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_third_text);
}
if(empty($pp_footer_third_text))
{
$pp_footer_third_text = ' ';
}
echo nl2br(stripslashes(html_entity_decode($pp_footer_third_text)));
?>
</div>
<div class="one_fourth last">
<?php
/**
* Get footer right text
*/
$pp_footer_right_text = get_option('pp_footer_right_text');
if (function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
$pp_footer_right_text = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($pp_footer_right_text);
}
if(empty($pp_footer_right_text))
{
$pp_footer_right_text = 'All images are copyrighted to their respective owners.';
}
echo nl2br(stripslashes(html_entity_decode($pp_footer_right_text)));
?>
</div>
<br class="clear"/>
</div>
</div>
</div>
</div>
<?php
/**
* Setup Google Analyric Code
**/
include (TEMPLATEPATH . "/google-analytic.php");
?>
<?php
/* Always have wp_footer() just before the closing </body>
* tag of your theme, or you will break many plugins, which
* generally use this hook to reference JavaScript files.
*/
wp_footer();
?>
<?php
$pp_blog_share = get_option('pp_blog_share');
if(!empty($pp_blog_share))
{
?>
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
<?php
}
?>
</body>
</html>
| Seizam/atelierweb | wp-content/themes/nemesis/footer.php | PHP | gpl-2.0 | 4,069 |
#include "logging.hpp"
#include <fstream>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sinks.hpp>
namespace p2l { namespace common {
//=====================================================================
void _init_logging()
{
boost::log::add_common_attributes();
boost::log::core::get()->set_filter
(
boost::log::trivial::severity >= boost::log::trivial::trace
);
typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_ostream_backend > text_sink;
// the file sink for hte default logger
boost::shared_ptr< text_sink > default_sink = boost::make_shared< text_sink >();
default_sink->locked_backend()->add_stream
( boost::make_shared< std::ofstream >( "default_log.log" ) );
boost::log::core::get()->add_sink( default_sink );
// the file sink for hte stat logger
boost::shared_ptr< text_sink > stat_sink = boost::make_shared< text_sink >();
stat_sink->locked_backend()->add_stream
( boost::make_shared< std::ofstream >( "stat_log.log" ) );
boost::log::core::get()->add_sink( stat_sink );
}
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
//=====================================================================
}
}
| velezj/pods.ptp.object-search.common | src/logging.cpp | C++ | gpl-2.0 | 2,078 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.dialect.unique;
import org.hibernate.boot.Metadata;
import org.hibernate.dialect.Dialect;
import org.hibernate.mapping.UniqueKey;
/**
* Informix requires the constraint name to come last on the alter table.
*
* @author Brett Meyer
*/
public class InformixUniqueDelegate extends DefaultUniqueDelegate {
public InformixUniqueDelegate( Dialect dialect ) {
super( dialect );
}
// legacy model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata) {
// Do this here, rather than allowing UniqueKey/Constraint to do it.
// We need full, simplified control over whether or not it happens.
final String tableName = metadata.getDatabase().getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
uniqueKey.getTable().getQualifiedTableName(),
metadata.getDatabase().getJdbcEnvironment().getDialect()
);
final String constraintName = dialect.quote( uniqueKey.getName() );
return dialect.getAlterTableString( tableName )
+ " add constraint " + uniqueConstraintSql( uniqueKey ) + " constraint " + constraintName;
}
}
| lamsfoundation/lams | 3rdParty_sources/hibernate-core/org/hibernate/dialect/unique/InformixUniqueDelegate.java | Java | gpl-2.0 | 1,458 |
/*
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright 2007 Johannes Berg <[email protected]>
* Copyright 2008 Luis R. Rodriguez <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* DOC: Wireless regulatory infrastructure
*
* The usual implementation is for a driver to read a device EEPROM to
* determine which regulatory domain it should be operating under, then
* looking up the allowable channels in a driver-local table and finally
* registering those channels in the wiphy structure.
*
* Another set of compliance enforcement is for drivers to use their
* own compliance limits which can be stored on the EEPROM. The host
* driver or firmware may ensure these are used.
*
* In addition to all this we provide an extra layer of regulatory
* conformance. For drivers which do not have any regulatory
* information CRDA provides the complete regulatory solution.
* For others it provides a community effort on further restrictions
* to enhance compliance.
*
* Note: When number of rules --> infinity we will not be able to
* index on alpha2 any more, instead we'll probably have to
* rely on some SHA1 checksum of the regdomain for example.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/random.h>
#include <linux/ctype.h>
#include <linux/nl80211.h>
#include <linux/platform_device.h>
#include <net/cfg80211.h>
#include "core.h"
#include "reg.h"
#include "regdb.h"
#include "nl80211.h"
#ifdef CONFIG_CFG80211_REG_DEBUG
#define REG_DBG_PRINT(format, args...) \
do { \
printk(KERN_DEBUG pr_fmt(format), ##args); \
} while (0)
#else
#define REG_DBG_PRINT(args...)
#endif
/* Receipt of information from last regulatory request */
static struct regulatory_request *last_request;
/* To trigger userspace events */
static struct platform_device *reg_pdev;
static struct device_type reg_device_type = {
.uevent = reg_device_uevent,
};
/*
* Central wireless core regulatory domains, we only need two,
* the current one and a world regulatory domain in case we have no
* information to give us an alpha2
*/
const struct ieee80211_regdomain *cfg80211_regdomain;
/*
* Protects static reg.c components:
* - cfg80211_world_regdom
* - cfg80211_regdom
* - last_request
*/
static DEFINE_MUTEX(reg_mutex);
static inline void assert_reg_lock(void)
{
lockdep_assert_held(®_mutex);
}
/* Used to queue up regulatory hints */
static LIST_HEAD(reg_requests_list);
static spinlock_t reg_requests_lock;
/* Used to queue up beacon hints for review */
static LIST_HEAD(reg_pending_beacons);
static spinlock_t reg_pending_beacons_lock;
/* Used to keep track of processed beacon hints */
static LIST_HEAD(reg_beacon_list);
struct reg_beacon {
struct list_head list;
struct ieee80211_channel chan;
};
static void reg_todo(struct work_struct *work);
static DECLARE_WORK(reg_work, reg_todo);
static void reg_timeout_work(struct work_struct *work);
static DECLARE_DELAYED_WORK(reg_timeout, reg_timeout_work);
/* We keep a static world regulatory domain in case of the absence of CRDA */
static const struct ieee80211_regdomain world_regdom = {
.n_reg_rules = 5,
.alpha2 = "00",
.reg_rules = {
/* IEEE 802.11b/g, channels 1..11 */
REG_RULE(2412-10, 2462+10, 40, 6, 20, 0),
/* IEEE 802.11b/g, channels 12..13. No HT40
* channel fits here. */
REG_RULE(2467-10, 2472+10, 20, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
/* IEEE 802.11 channel 14 - Only JP enables
* this and for 802.11b only */
REG_RULE(2484-10, 2484+10, 20, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS |
NL80211_RRF_NO_OFDM),
/* IEEE 802.11a, channel 36..48 */
REG_RULE(5180-10, 5240+10, 40, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
/* NB: 5260 MHz - 5700 MHz requies DFS */
/* IEEE 802.11a, channel 149..165 */
REG_RULE(5745-10, 5825+10, 40, 6, 20,
NL80211_RRF_PASSIVE_SCAN |
NL80211_RRF_NO_IBSS),
}
};
static const struct ieee80211_regdomain *cfg80211_world_regdom =
&world_regdom;
static char *ieee80211_regdom = "00";
static char user_alpha2[2];
module_param(ieee80211_regdom, charp, 0444);
MODULE_PARM_DESC(ieee80211_regdom, "IEEE 802.11 regulatory domain code");
static void reset_regdomains(void)
{
/* avoid freeing static information or freeing something twice */
if (cfg80211_regdomain == cfg80211_world_regdom)
cfg80211_regdomain = NULL;
if (cfg80211_world_regdom == &world_regdom)
cfg80211_world_regdom = NULL;
if (cfg80211_regdomain == &world_regdom)
cfg80211_regdomain = NULL;
kfree(cfg80211_regdomain);
kfree(cfg80211_world_regdom);
cfg80211_world_regdom = &world_regdom;
cfg80211_regdomain = NULL;
}
/*
* Dynamic world regulatory domain requested by the wireless
* core upon initialization
*/
static void update_world_regdomain(const struct ieee80211_regdomain *rd)
{
BUG_ON(!last_request);
reset_regdomains();
cfg80211_world_regdom = rd;
cfg80211_regdomain = rd;
}
bool is_world_regdom(const char *alpha2)
{
if (!alpha2)
return false;
if (alpha2[0] == '0' && alpha2[1] == '0')
return true;
return false;
}
static bool is_alpha2_set(const char *alpha2)
{
if (!alpha2)
return false;
if (alpha2[0] != 0 && alpha2[1] != 0)
return true;
return false;
}
static bool is_unknown_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
/*
* Special case where regulatory domain was built by driver
* but a specific alpha2 cannot be determined
*/
if (alpha2[0] == '9' && alpha2[1] == '9')
return true;
return false;
}
static bool is_intersected_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
/*
* Special case where regulatory domain is the
* result of an intersection between two regulatory domain
* structures
*/
if (alpha2[0] == '9' && alpha2[1] == '8')
return true;
return false;
}
static bool is_an_alpha2(const char *alpha2)
{
if (!alpha2)
return false;
if (isalpha(alpha2[0]) && isalpha(alpha2[1]))
return true;
return false;
}
static bool alpha2_equal(const char *alpha2_x, const char *alpha2_y)
{
if (!alpha2_x || !alpha2_y)
return false;
if (alpha2_x[0] == alpha2_y[0] &&
alpha2_x[1] == alpha2_y[1])
return true;
return false;
}
static bool regdom_changes(const char *alpha2)
{
assert_cfg80211_lock();
if (!cfg80211_regdomain)
return true;
if (alpha2_equal(cfg80211_regdomain->alpha2, alpha2))
return false;
return true;
}
/*
* The NL80211_REGDOM_SET_BY_USER regdom alpha2 is cached, this lets
* you know if a valid regulatory hint with NL80211_REGDOM_SET_BY_USER
* has ever been issued.
*/
static bool is_user_regdom_saved(void)
{
if (user_alpha2[0] == '9' && user_alpha2[1] == '7')
return false;
/* This would indicate a mistake on the design */
if (WARN((!is_world_regdom(user_alpha2) &&
!is_an_alpha2(user_alpha2)),
"Unexpected user alpha2: %c%c\n",
user_alpha2[0],
user_alpha2[1]))
return false;
return true;
}
static int reg_copy_regd(const struct ieee80211_regdomain **dst_regd,
const struct ieee80211_regdomain *src_regd)
{
struct ieee80211_regdomain *regd;
int size_of_regd = 0;
unsigned int i;
size_of_regd = sizeof(struct ieee80211_regdomain) +
((src_regd->n_reg_rules + 1) * sizeof(struct ieee80211_reg_rule));
regd = kzalloc(size_of_regd, GFP_KERNEL);
if (!regd)
return -ENOMEM;
memcpy(regd, src_regd, sizeof(struct ieee80211_regdomain));
for (i = 0; i < src_regd->n_reg_rules; i++)
memcpy(®d->reg_rules[i], &src_regd->reg_rules[i],
sizeof(struct ieee80211_reg_rule));
*dst_regd = regd;
return 0;
}
#ifdef CONFIG_CFG80211_INTERNAL_REGDB
struct reg_regdb_search_request {
char alpha2[2];
struct list_head list;
};
static LIST_HEAD(reg_regdb_search_list);
static DEFINE_MUTEX(reg_regdb_search_mutex);
static void reg_regdb_search(struct work_struct *work)
{
struct reg_regdb_search_request *request;
const struct ieee80211_regdomain *curdom, *regdom;
int i, r;
mutex_lock(®_regdb_search_mutex);
while (!list_empty(®_regdb_search_list)) {
request = list_first_entry(®_regdb_search_list,
struct reg_regdb_search_request,
list);
list_del(&request->list);
for (i=0; i<reg_regdb_size; i++) {
curdom = reg_regdb[i];
if (!memcmp(request->alpha2, curdom->alpha2, 2)) {
r = reg_copy_regd(®dom, curdom);
if (r)
break;
mutex_lock(&cfg80211_mutex);
set_regdom(regdom);
mutex_unlock(&cfg80211_mutex);
break;
}
}
kfree(request);
}
mutex_unlock(®_regdb_search_mutex);
}
static DECLARE_WORK(reg_regdb_work, reg_regdb_search);
static void reg_regdb_query(const char *alpha2)
{
struct reg_regdb_search_request *request;
if (!alpha2)
return;
request = kzalloc(sizeof(struct reg_regdb_search_request), GFP_KERNEL);
if (!request)
return;
memcpy(request->alpha2, alpha2, 2);
mutex_lock(®_regdb_search_mutex);
list_add_tail(&request->list, ®_regdb_search_list);
mutex_unlock(®_regdb_search_mutex);
schedule_work(®_regdb_work);
}
#else
static inline void reg_regdb_query(const char *alpha2) {}
#endif /* CONFIG_CFG80211_INTERNAL_REGDB */
/*
* This lets us keep regulatory code which is updated on a regulatory
* basis in userspace. Country information is filled in by
* reg_device_uevent
*/
static int call_crda(const char *alpha2)
{
if (!is_world_regdom((char *) alpha2))
pr_info("Calling CRDA for country: %c%c\n",
alpha2[0], alpha2[1]);
else
pr_info("Calling CRDA to update world regulatory domain\n");
/* query internal regulatory database (if it exists) */
reg_regdb_query(alpha2);
return kobject_uevent(®_pdev->dev.kobj, KOBJ_CHANGE);
}
/* Used by nl80211 before kmalloc'ing our regulatory domain */
bool reg_is_valid_request(const char *alpha2)
{
assert_cfg80211_lock();
if (!last_request)
return false;
return alpha2_equal(last_request->alpha2, alpha2);
}
/* Sanity check on a regulatory rule */
static bool is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
{
const struct ieee80211_freq_range *freq_range = &rule->freq_range;
u32 freq_diff;
if (freq_range->start_freq_khz <= 0 || freq_range->end_freq_khz <= 0)
return false;
if (freq_range->start_freq_khz > freq_range->end_freq_khz)
return false;
freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
freq_range->max_bandwidth_khz > freq_diff)
return false;
return true;
}
static bool is_valid_rd(const struct ieee80211_regdomain *rd)
{
const struct ieee80211_reg_rule *reg_rule = NULL;
unsigned int i;
if (!rd->n_reg_rules)
return false;
if (WARN_ON(rd->n_reg_rules > NL80211_MAX_SUPP_REG_RULES))
return false;
for (i = 0; i < rd->n_reg_rules; i++) {
reg_rule = &rd->reg_rules[i];
if (!is_valid_reg_rule(reg_rule))
return false;
}
return true;
}
static bool reg_does_bw_fit(const struct ieee80211_freq_range *freq_range,
u32 center_freq_khz,
u32 bw_khz)
{
u32 start_freq_khz, end_freq_khz;
start_freq_khz = center_freq_khz - (bw_khz/2);
end_freq_khz = center_freq_khz + (bw_khz/2);
if (start_freq_khz >= freq_range->start_freq_khz &&
end_freq_khz <= freq_range->end_freq_khz)
return true;
return false;
}
/**
* freq_in_rule_band - tells us if a frequency is in a frequency band
* @freq_range: frequency rule we want to query
* @freq_khz: frequency we are inquiring about
*
* This lets us know if a specific frequency rule is or is not relevant to
* a specific frequency's band. Bands are device specific and artificial
* definitions (the "2.4 GHz band" and the "5 GHz band"), however it is
* safe for now to assume that a frequency rule should not be part of a
* frequency's band if the start freq or end freq are off by more than 2 GHz.
* This resolution can be lowered and should be considered as we add
* regulatory rule support for other "bands".
**/
static bool freq_in_rule_band(const struct ieee80211_freq_range *freq_range,
u32 freq_khz)
{
#define ONE_GHZ_IN_KHZ 1000000
if (abs(freq_khz - freq_range->start_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
return true;
if (abs(freq_khz - freq_range->end_freq_khz) <= (2 * ONE_GHZ_IN_KHZ))
return true;
return false;
#undef ONE_GHZ_IN_KHZ
}
/*
* Helper for regdom_intersect(), this does the real
* mathematical intersection fun
*/
static int reg_rules_intersect(
const struct ieee80211_reg_rule *rule1,
const struct ieee80211_reg_rule *rule2,
struct ieee80211_reg_rule *intersected_rule)
{
const struct ieee80211_freq_range *freq_range1, *freq_range2;
struct ieee80211_freq_range *freq_range;
const struct ieee80211_power_rule *power_rule1, *power_rule2;
struct ieee80211_power_rule *power_rule;
u32 freq_diff;
freq_range1 = &rule1->freq_range;
freq_range2 = &rule2->freq_range;
freq_range = &intersected_rule->freq_range;
power_rule1 = &rule1->power_rule;
power_rule2 = &rule2->power_rule;
power_rule = &intersected_rule->power_rule;
freq_range->start_freq_khz = max(freq_range1->start_freq_khz,
freq_range2->start_freq_khz);
freq_range->end_freq_khz = min(freq_range1->end_freq_khz,
freq_range2->end_freq_khz);
freq_range->max_bandwidth_khz = min(freq_range1->max_bandwidth_khz,
freq_range2->max_bandwidth_khz);
freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
if (freq_range->max_bandwidth_khz > freq_diff)
freq_range->max_bandwidth_khz = freq_diff;
power_rule->max_eirp = min(power_rule1->max_eirp,
power_rule2->max_eirp);
power_rule->max_antenna_gain = min(power_rule1->max_antenna_gain,
power_rule2->max_antenna_gain);
intersected_rule->flags = (rule1->flags | rule2->flags);
if (!is_valid_reg_rule(intersected_rule))
return -EINVAL;
return 0;
}
/**
* regdom_intersect - do the intersection between two regulatory domains
* @rd1: first regulatory domain
* @rd2: second regulatory domain
*
* Use this function to get the intersection between two regulatory domains.
* Once completed we will mark the alpha2 for the rd as intersected, "98",
* as no one single alpha2 can represent this regulatory domain.
*
* Returns a pointer to the regulatory domain structure which will hold the
* resulting intersection of rules between rd1 and rd2. We will
* kzalloc() this structure for you.
*/
static struct ieee80211_regdomain *regdom_intersect(
const struct ieee80211_regdomain *rd1,
const struct ieee80211_regdomain *rd2)
{
int r, size_of_regd;
unsigned int x, y;
unsigned int num_rules = 0, rule_idx = 0;
const struct ieee80211_reg_rule *rule1, *rule2;
struct ieee80211_reg_rule *intersected_rule;
struct ieee80211_regdomain *rd;
/* This is just a dummy holder to help us count */
struct ieee80211_reg_rule irule;
/* Uses the stack temporarily for counter arithmetic */
intersected_rule = &irule;
memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule));
if (!rd1 || !rd2)
return NULL;
/*
* First we get a count of the rules we'll need, then we actually
* build them. This is to so we can malloc() and free() a
* regdomain once. The reason we use reg_rules_intersect() here
* is it will return -EINVAL if the rule computed makes no sense.
* All rules that do check out OK are valid.
*/
for (x = 0; x < rd1->n_reg_rules; x++) {
rule1 = &rd1->reg_rules[x];
for (y = 0; y < rd2->n_reg_rules; y++) {
rule2 = &rd2->reg_rules[y];
if (!reg_rules_intersect(rule1, rule2,
intersected_rule))
num_rules++;
memset(intersected_rule, 0,
sizeof(struct ieee80211_reg_rule));
}
}
if (!num_rules)
return NULL;
size_of_regd = sizeof(struct ieee80211_regdomain) +
((num_rules + 1) * sizeof(struct ieee80211_reg_rule));
rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd)
return NULL;
for (x = 0; x < rd1->n_reg_rules; x++) {
rule1 = &rd1->reg_rules[x];
for (y = 0; y < rd2->n_reg_rules; y++) {
rule2 = &rd2->reg_rules[y];
/*
* This time around instead of using the stack lets
* write to the target rule directly saving ourselves
* a memcpy()
*/
intersected_rule = &rd->reg_rules[rule_idx];
r = reg_rules_intersect(rule1, rule2,
intersected_rule);
/*
* No need to memset here the intersected rule here as
* we're not using the stack anymore
*/
if (r)
continue;
rule_idx++;
}
}
if (rule_idx != num_rules) {
kfree(rd);
return NULL;
}
rd->n_reg_rules = num_rules;
rd->alpha2[0] = '9';
rd->alpha2[1] = '8';
return rd;
}
/*
* XXX: add support for the rest of enum nl80211_reg_rule_flags, we may
* want to just have the channel structure use these
*/
static u32 map_regdom_flags(u32 rd_flags)
{
u32 channel_flags = 0;
if (rd_flags & NL80211_RRF_PASSIVE_SCAN)
channel_flags |= IEEE80211_CHAN_PASSIVE_SCAN;
if (rd_flags & NL80211_RRF_NO_IBSS)
channel_flags |= IEEE80211_CHAN_NO_IBSS;
if (rd_flags & NL80211_RRF_DFS)
channel_flags |= IEEE80211_CHAN_RADAR;
return channel_flags;
}
static int freq_reg_info_regd(struct wiphy *wiphy,
u32 center_freq,
u32 desired_bw_khz,
const struct ieee80211_reg_rule **reg_rule,
const struct ieee80211_regdomain *custom_regd)
{
int i;
bool band_rule_found = false;
const struct ieee80211_regdomain *regd;
bool bw_fits = false;
if (!desired_bw_khz)
desired_bw_khz = MHZ_TO_KHZ(20);
regd = custom_regd ? custom_regd : cfg80211_regdomain;
/*
* Follow the driver's regulatory domain, if present, unless a country
* IE has been processed or a user wants to help complaince further
*/
if (!custom_regd &&
last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
last_request->initiator != NL80211_REGDOM_SET_BY_USER &&
wiphy->regd)
regd = wiphy->regd;
if (!regd)
return -EINVAL;
for (i = 0; i < regd->n_reg_rules; i++) {
const struct ieee80211_reg_rule *rr;
const struct ieee80211_freq_range *fr = NULL;
rr = ®d->reg_rules[i];
fr = &rr->freq_range;
/*
* We only need to know if one frequency rule was
* was in center_freq's band, that's enough, so lets
* not overwrite it once found
*/
if (!band_rule_found)
band_rule_found = freq_in_rule_band(fr, center_freq);
bw_fits = reg_does_bw_fit(fr,
center_freq,
desired_bw_khz);
if (band_rule_found && bw_fits) {
*reg_rule = rr;
return 0;
}
}
if (!band_rule_found)
return -ERANGE;
return -EINVAL;
}
int freq_reg_info(struct wiphy *wiphy,
u32 center_freq,
u32 desired_bw_khz,
const struct ieee80211_reg_rule **reg_rule)
{
assert_cfg80211_lock();
return freq_reg_info_regd(wiphy,
center_freq,
desired_bw_khz,
reg_rule,
NULL);
}
EXPORT_SYMBOL(freq_reg_info);
#ifdef CONFIG_CFG80211_REG_DEBUG
static const char *reg_initiator_name(enum nl80211_reg_initiator initiator)
{
switch (initiator) {
case NL80211_REGDOM_SET_BY_CORE:
return "Set by core";
case NL80211_REGDOM_SET_BY_USER:
return "Set by user";
case NL80211_REGDOM_SET_BY_DRIVER:
return "Set by driver";
case NL80211_REGDOM_SET_BY_COUNTRY_IE:
return "Set by country IE";
default:
WARN_ON(1);
return "Set by bug";
}
}
static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
u32 desired_bw_khz,
const struct ieee80211_reg_rule *reg_rule)
{
const struct ieee80211_power_rule *power_rule;
const struct ieee80211_freq_range *freq_range;
char max_antenna_gain[32];
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (!power_rule->max_antenna_gain)
snprintf(max_antenna_gain, 32, "N/A");
else
snprintf(max_antenna_gain, 32, "%d", power_rule->max_antenna_gain);
REG_DBG_PRINT("Updating information on frequency %d MHz "
"for a %d MHz width channel with regulatory rule:\n",
chan->center_freq,
KHZ_TO_MHZ(desired_bw_khz));
REG_DBG_PRINT("%d KHz - %d KHz @ KHz), (%s mBi, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
max_antenna_gain,
power_rule->max_eirp);
}
#else
static void chan_reg_rule_print_dbg(struct ieee80211_channel *chan,
u32 desired_bw_khz,
const struct ieee80211_reg_rule *reg_rule)
{
return;
}
#endif
/*
* Note that right now we assume the desired channel bandwidth
* is always 20 MHz for each individual channel (HT40 uses 20 MHz
* per channel, the primary and the extension channel). To support
* smaller custom bandwidths such as 5 MHz or 10 MHz we'll need a
* new ieee80211_channel.target_bw and re run the regulatory check
* on the wiphy with the target_bw specified. Then we can simply use
* that below for the desired_bw_khz below.
*/
static void handle_channel(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator,
enum ieee80211_band band,
unsigned int chan_idx)
{
int r;
u32 flags, bw_flags = 0;
u32 desired_bw_khz = MHZ_TO_KHZ(20);
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
struct wiphy *request_wiphy = NULL;
assert_cfg80211_lock();
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
chan = &sband->channels[chan_idx];
flags = chan->orig_flags;
r = freq_reg_info(wiphy,
MHZ_TO_KHZ(chan->center_freq),
desired_bw_khz,
®_rule);
if (r) {
/*
* We will disable all channels that do not match our
* received regulatory rule unless the hint is coming
* from a Country IE and the Country IE had no information
* about a band. The IEEE 802.11 spec allows for an AP
* to send only a subset of the regulatory rules allowed,
* so an AP in the US that only supports 2.4 GHz may only send
* a country IE with information for the 2.4 GHz band
* while 5 GHz is still supported.
*/
if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
r == -ERANGE)
return;
REG_DBG_PRINT("Disabling freq %d MHz\n", chan->center_freq);
chan->flags = IEEE80211_CHAN_DISABLED;
return;
}
chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
bw_flags = IEEE80211_CHAN_NO_HT40;
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
request_wiphy && request_wiphy == wiphy &&
request_wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
/*
* This guarantees the driver's requested regulatory domain
* will always be used as a base for further regulatory
* settings
*/
chan->flags = chan->orig_flags =
map_regdom_flags(reg_rule->flags) | bw_flags;
chan->max_antenna_gain = chan->orig_mag =
(int) MBI_TO_DBI(power_rule->max_antenna_gain);
chan->max_power = chan->orig_mpwr =
(int) MBM_TO_DBM(power_rule->max_eirp);
return;
}
chan->beacon_found = false;
chan->flags = flags | bw_flags | map_regdom_flags(reg_rule->flags);
chan->max_antenna_gain = min(chan->orig_mag,
(int) MBI_TO_DBI(power_rule->max_antenna_gain));
if (chan->orig_mpwr) {
/*
* Devices that have their own custom regulatory domain
* but also use WIPHY_FLAG_STRICT_REGULATORY will follow the
* passed country IE power settings.
*/
if (initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY &&
wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
chan->max_power =
MBM_TO_DBM(power_rule->max_eirp);
} else {
chan->max_power = min(chan->orig_mpwr,
(int) MBM_TO_DBM(power_rule->max_eirp));
}
} else
chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
}
static void handle_band(struct wiphy *wiphy,
enum ieee80211_band band,
enum nl80211_reg_initiator initiator)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
handle_channel(wiphy, initiator, band, i);
}
static bool ignore_reg_update(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
if (!last_request) {
REG_DBG_PRINT("Ignoring regulatory request %s since "
"last_request is not set\n",
reg_initiator_name(initiator));
return true;
}
if (initiator == NL80211_REGDOM_SET_BY_CORE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY) {
REG_DBG_PRINT("Ignoring regulatory request %s "
"since the driver uses its own custom "
"regulatory domain ",
reg_initiator_name(initiator));
return true;
}
/*
* wiphy->regd will be set once the device has its own
* desired regulatory domain set
*/
if (wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY && !wiphy->regd &&
initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
!is_world_regdom(last_request->alpha2)) {
REG_DBG_PRINT("Ignoring regulatory request %s "
"since the driver requires its own regulaotry "
"domain to be set first",
reg_initiator_name(initiator));
return true;
}
return false;
}
static void update_all_wiphy_regulatory(enum nl80211_reg_initiator initiator)
{
struct cfg80211_registered_device *rdev;
struct wiphy *wiphy;
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
wiphy = &rdev->wiphy;
wiphy_update_regulatory(wiphy, initiator);
/*
* Regulatory updates set by CORE are ignored for custom
* regulatory cards. Let us notify the changes to the driver,
* as some drivers used this to restore its orig_* reg domain.
*/
if (initiator == NL80211_REGDOM_SET_BY_CORE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY &&
wiphy->reg_notifier)
wiphy->reg_notifier(wiphy, last_request);
}
}
static void handle_reg_beacon(struct wiphy *wiphy,
unsigned int chan_idx,
struct reg_beacon *reg_beacon)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
bool channel_changed = false;
struct ieee80211_channel chan_before;
assert_cfg80211_lock();
sband = wiphy->bands[reg_beacon->chan.band];
chan = &sband->channels[chan_idx];
if (likely(chan->center_freq != reg_beacon->chan.center_freq))
return;
if (chan->beacon_found)
return;
chan->beacon_found = true;
if (wiphy->flags & WIPHY_FLAG_DISABLE_BEACON_HINTS)
return;
chan_before.center_freq = chan->center_freq;
chan_before.flags = chan->flags;
if (chan->flags & IEEE80211_CHAN_PASSIVE_SCAN) {
chan->flags &= ~IEEE80211_CHAN_PASSIVE_SCAN;
channel_changed = true;
}
if (chan->flags & IEEE80211_CHAN_NO_IBSS) {
chan->flags &= ~IEEE80211_CHAN_NO_IBSS;
channel_changed = true;
}
if (channel_changed)
nl80211_send_beacon_hint_event(wiphy, &chan_before, chan);
}
/*
* Called when a scan on a wiphy finds a beacon on
* new channel
*/
static void wiphy_update_new_beacon(struct wiphy *wiphy,
struct reg_beacon *reg_beacon)
{
unsigned int i;
struct ieee80211_supported_band *sband;
assert_cfg80211_lock();
if (!wiphy->bands[reg_beacon->chan.band])
return;
sband = wiphy->bands[reg_beacon->chan.band];
for (i = 0; i < sband->n_channels; i++)
handle_reg_beacon(wiphy, i, reg_beacon);
}
/*
* Called upon reg changes or a new wiphy is added
*/
static void wiphy_update_beacon_reg(struct wiphy *wiphy)
{
unsigned int i;
struct ieee80211_supported_band *sband;
struct reg_beacon *reg_beacon;
assert_cfg80211_lock();
if (list_empty(®_beacon_list))
return;
list_for_each_entry(reg_beacon, ®_beacon_list, list) {
if (!wiphy->bands[reg_beacon->chan.band])
continue;
sband = wiphy->bands[reg_beacon->chan.band];
for (i = 0; i < sband->n_channels; i++)
handle_reg_beacon(wiphy, i, reg_beacon);
}
}
static bool reg_is_world_roaming(struct wiphy *wiphy)
{
if (is_world_regdom(cfg80211_regdomain->alpha2) ||
(wiphy->regd && is_world_regdom(wiphy->regd->alpha2)))
return true;
if (last_request &&
last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy->flags & WIPHY_FLAG_CUSTOM_REGULATORY)
return true;
return false;
}
/* Reap the advantages of previously found beacons */
static void reg_process_beacons(struct wiphy *wiphy)
{
/*
* Means we are just firing up cfg80211, so no beacons would
* have been processed yet.
*/
if (!last_request)
return;
if (!reg_is_world_roaming(wiphy))
return;
wiphy_update_beacon_reg(wiphy);
}
static bool is_ht40_not_allowed(struct ieee80211_channel *chan)
{
if (!chan)
return true;
if (chan->flags & IEEE80211_CHAN_DISABLED)
return true;
/* This would happen when regulatory rules disallow HT40 completely */
if (IEEE80211_CHAN_NO_HT40 == (chan->flags & (IEEE80211_CHAN_NO_HT40)))
return true;
return false;
}
static void reg_process_ht_flags_channel(struct wiphy *wiphy,
enum ieee80211_band band,
unsigned int chan_idx)
{
struct ieee80211_supported_band *sband;
struct ieee80211_channel *channel;
struct ieee80211_channel *channel_before = NULL, *channel_after = NULL;
unsigned int i;
assert_cfg80211_lock();
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
channel = &sband->channels[chan_idx];
if (is_ht40_not_allowed(channel)) {
channel->flags |= IEEE80211_CHAN_NO_HT40;
return;
}
/*
* We need to ensure the extension channels exist to
* be able to use HT40- or HT40+, this finds them (or not)
*/
for (i = 0; i < sband->n_channels; i++) {
struct ieee80211_channel *c = &sband->channels[i];
if (c->center_freq == (channel->center_freq - 20))
channel_before = c;
if (c->center_freq == (channel->center_freq + 20))
channel_after = c;
}
/*
* Please note that this assumes target bandwidth is 20 MHz,
* if that ever changes we also need to change the below logic
* to include that as well.
*/
if (is_ht40_not_allowed(channel_before))
channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
else
channel->flags &= ~IEEE80211_CHAN_NO_HT40MINUS;
if (is_ht40_not_allowed(channel_after))
channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
else
channel->flags &= ~IEEE80211_CHAN_NO_HT40PLUS;
}
static void reg_process_ht_flags_band(struct wiphy *wiphy,
enum ieee80211_band band)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
reg_process_ht_flags_channel(wiphy, band, i);
}
static void reg_process_ht_flags(struct wiphy *wiphy)
{
enum ieee80211_band band;
if (!wiphy)
return;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (wiphy->bands[band])
reg_process_ht_flags_band(wiphy, band);
}
}
void wiphy_update_regulatory(struct wiphy *wiphy,
enum nl80211_reg_initiator initiator)
{
enum ieee80211_band band;
if (ignore_reg_update(wiphy, initiator))
return;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (wiphy->bands[band])
handle_band(wiphy, band, initiator);
}
reg_process_beacons(wiphy);
reg_process_ht_flags(wiphy);
if (wiphy->reg_notifier)
wiphy->reg_notifier(wiphy, last_request);
}
static void handle_channel_custom(struct wiphy *wiphy,
enum ieee80211_band band,
unsigned int chan_idx,
const struct ieee80211_regdomain *regd)
{
int r;
u32 desired_bw_khz = MHZ_TO_KHZ(20);
u32 bw_flags = 0;
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
assert_reg_lock();
sband = wiphy->bands[band];
BUG_ON(chan_idx >= sband->n_channels);
chan = &sband->channels[chan_idx];
r = freq_reg_info_regd(wiphy,
MHZ_TO_KHZ(chan->center_freq),
desired_bw_khz,
®_rule,
regd);
if (r) {
REG_DBG_PRINT("Disabling freq %d MHz as custom "
"regd has no rule that fits a %d MHz "
"wide channel\n",
chan->center_freq,
KHZ_TO_MHZ(desired_bw_khz));
chan->flags = IEEE80211_CHAN_DISABLED;
return;
}
chan_reg_rule_print_dbg(chan, desired_bw_khz, reg_rule);
power_rule = ®_rule->power_rule;
freq_range = ®_rule->freq_range;
if (freq_range->max_bandwidth_khz < MHZ_TO_KHZ(40))
bw_flags = IEEE80211_CHAN_NO_HT40;
chan->flags |= map_regdom_flags(reg_rule->flags) | bw_flags;
chan->max_antenna_gain = (int) MBI_TO_DBI(power_rule->max_antenna_gain);
chan->max_power = (int) MBM_TO_DBM(power_rule->max_eirp);
}
static void handle_band_custom(struct wiphy *wiphy, enum ieee80211_band band,
const struct ieee80211_regdomain *regd)
{
unsigned int i;
struct ieee80211_supported_band *sband;
BUG_ON(!wiphy->bands[band]);
sband = wiphy->bands[band];
for (i = 0; i < sband->n_channels; i++)
handle_channel_custom(wiphy, band, i, regd);
}
/* Used by drivers prior to wiphy registration */
void wiphy_apply_custom_regulatory(struct wiphy *wiphy,
const struct ieee80211_regdomain *regd)
{
enum ieee80211_band band;
unsigned int bands_set = 0;
mutex_lock(®_mutex);
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!wiphy->bands[band])
continue;
handle_band_custom(wiphy, band, regd);
bands_set++;
}
mutex_unlock(®_mutex);
/*
* no point in calling this if it won't have any effect
* on your device's supportd bands.
*/
WARN_ON(!bands_set);
}
EXPORT_SYMBOL(wiphy_apply_custom_regulatory);
/*
* Return value which can be used by ignore_request() to indicate
* it has been determined we should intersect two regulatory domains
*/
#define REG_INTERSECT 1
/* This has the logic which determines when a new request
* should be ignored. */
static int ignore_request(struct wiphy *wiphy,
struct regulatory_request *pending_request)
{
struct wiphy *last_wiphy = NULL;
assert_cfg80211_lock();
/* All initial requests are respected */
if (!last_request)
return 0;
switch (pending_request->initiator) {
case NL80211_REGDOM_SET_BY_CORE:
return 0;
case NL80211_REGDOM_SET_BY_COUNTRY_IE:
last_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (unlikely(!is_an_alpha2(pending_request->alpha2)))
return -EINVAL;
if (last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE) {
if (last_wiphy != wiphy) {
/*
* Two cards with two APs claiming different
* Country IE alpha2s. We could
* intersect them, but that seems unlikely
* to be correct. Reject second one for now.
*/
if (regdom_changes(pending_request->alpha2))
return -EOPNOTSUPP;
return -EALREADY;
}
/*
* Two consecutive Country IE hints on the same wiphy.
* This should be picked up early by the driver/stack
*/
if (WARN_ON(regdom_changes(pending_request->alpha2)))
return 0;
return -EALREADY;
}
return 0;
case NL80211_REGDOM_SET_BY_DRIVER:
if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE) {
if (regdom_changes(pending_request->alpha2))
return 0;
return -EALREADY;
}
/*
* This would happen if you unplug and plug your card
* back in or if you add a new device for which the previously
* loaded card also agrees on the regulatory domain.
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
!regdom_changes(pending_request->alpha2))
return -EALREADY;
return REG_INTERSECT;
case NL80211_REGDOM_SET_BY_USER:
if (last_request->initiator == NL80211_REGDOM_SET_BY_COUNTRY_IE)
return REG_INTERSECT;
/*
* If the user knows better the user should set the regdom
* to their country before the IE is picked up
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER &&
last_request->intersect)
return -EOPNOTSUPP;
/*
* Process user requests only after previous user/driver/core
* requests have been processed
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_CORE ||
last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER ||
last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
if (regdom_changes(last_request->alpha2))
return -EAGAIN;
}
if (!regdom_changes(pending_request->alpha2))
return -EALREADY;
return 0;
}
return -EINVAL;
}
static void reg_set_request_processed(void)
{
bool need_more_processing = false;
last_request->processed = true;
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list))
need_more_processing = true;
spin_unlock(®_requests_lock);
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER)
cancel_delayed_work_sync(®_timeout);
if (need_more_processing)
schedule_work(®_work);
}
/**
* __regulatory_hint - hint to the wireless core a regulatory domain
* @wiphy: if the hint comes from country information from an AP, this
* is required to be set to the wiphy that received the information
* @pending_request: the regulatory request currently being processed
*
* The Wireless subsystem can use this function to hint to the wireless core
* what it believes should be the current regulatory domain.
*
* Returns zero if all went fine, %-EALREADY if a regulatory domain had
* already been set or other standard error codes.
*
* Caller must hold &cfg80211_mutex and ®_mutex
*/
static int __regulatory_hint(struct wiphy *wiphy,
struct regulatory_request *pending_request)
{
bool intersect = false;
int r = 0;
assert_cfg80211_lock();
r = ignore_request(wiphy, pending_request);
if (r == REG_INTERSECT) {
if (pending_request->initiator ==
NL80211_REGDOM_SET_BY_DRIVER) {
r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
if (r) {
kfree(pending_request);
return r;
}
}
intersect = true;
} else if (r) {
/*
* If the regulatory domain being requested by the
* driver has already been set just copy it to the
* wiphy
*/
if (r == -EALREADY &&
pending_request->initiator ==
NL80211_REGDOM_SET_BY_DRIVER) {
r = reg_copy_regd(&wiphy->regd, cfg80211_regdomain);
if (r) {
kfree(pending_request);
return r;
}
r = -EALREADY;
goto new_request;
}
kfree(pending_request);
return r;
}
new_request:
kfree(last_request);
last_request = pending_request;
last_request->intersect = intersect;
pending_request = NULL;
if (last_request->initiator == NL80211_REGDOM_SET_BY_USER) {
user_alpha2[0] = last_request->alpha2[0];
user_alpha2[1] = last_request->alpha2[1];
}
/* When r == REG_INTERSECT we do need to call CRDA */
if (r < 0) {
/*
* Since CRDA will not be called in this case as we already
* have applied the requested regulatory domain before we just
* inform userspace we have processed the request
*/
if (r == -EALREADY) {
nl80211_send_reg_change_event(last_request);
reg_set_request_processed();
}
return r;
}
return call_crda(last_request->alpha2);
}
/* This processes *all* regulatory hints */
static void reg_process_hint(struct regulatory_request *reg_request)
{
int r = 0;
struct wiphy *wiphy = NULL;
enum nl80211_reg_initiator initiator = reg_request->initiator;
BUG_ON(!reg_request->alpha2);
if (wiphy_idx_valid(reg_request->wiphy_idx))
wiphy = wiphy_idx_to_wiphy(reg_request->wiphy_idx);
if (reg_request->initiator == NL80211_REGDOM_SET_BY_DRIVER &&
!wiphy) {
kfree(reg_request);
return;
}
r = __regulatory_hint(wiphy, reg_request);
/* This is required so that the orig_* parameters are saved */
if (r == -EALREADY && wiphy &&
wiphy->flags & WIPHY_FLAG_STRICT_REGULATORY) {
wiphy_update_regulatory(wiphy, initiator);
return;
}
/*
* We only time out user hints, given that they should be the only
* source of bogus requests.
*/
if (r != -EALREADY &&
reg_request->initiator == NL80211_REGDOM_SET_BY_USER)
schedule_delayed_work(®_timeout, msecs_to_jiffies(3142));
}
/*
* Processes regulatory hints, this is all the NL80211_REGDOM_SET_BY_*
* Regulatory hints come on a first come first serve basis and we
* must process each one atomically.
*/
static void reg_process_pending_hints(void)
{
struct regulatory_request *reg_request;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
/* When last_request->processed becomes true this will be rescheduled */
if (last_request && !last_request->processed) {
REG_DBG_PRINT("Pending regulatory request, waiting "
"for it to be processed...");
goto out;
}
spin_lock(®_requests_lock);
if (list_empty(®_requests_list)) {
spin_unlock(®_requests_lock);
goto out;
}
reg_request = list_first_entry(®_requests_list,
struct regulatory_request,
list);
list_del_init(®_request->list);
spin_unlock(®_requests_lock);
reg_process_hint(reg_request);
out:
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
}
/* Processes beacon hints -- this has nothing to do with country IEs */
static void reg_process_pending_beacon_hints(void)
{
struct cfg80211_registered_device *rdev;
struct reg_beacon *pending_beacon, *tmp;
/*
* No need to hold the reg_mutex here as we just touch wiphys
* and do not read or access regulatory variables.
*/
mutex_lock(&cfg80211_mutex);
/* This goes through the _pending_ beacon list */
spin_lock_bh(®_pending_beacons_lock);
if (list_empty(®_pending_beacons)) {
spin_unlock_bh(®_pending_beacons_lock);
goto out;
}
list_for_each_entry_safe(pending_beacon, tmp,
®_pending_beacons, list) {
list_del_init(&pending_beacon->list);
/* Applies the beacon hint to current wiphys */
list_for_each_entry(rdev, &cfg80211_rdev_list, list)
wiphy_update_new_beacon(&rdev->wiphy, pending_beacon);
/* Remembers the beacon hint for new wiphys or reg changes */
list_add_tail(&pending_beacon->list, ®_beacon_list);
}
spin_unlock_bh(®_pending_beacons_lock);
out:
mutex_unlock(&cfg80211_mutex);
}
static void reg_todo(struct work_struct *work)
{
reg_process_pending_hints();
reg_process_pending_beacon_hints();
}
static void queue_regulatory_request(struct regulatory_request *request)
{
if (isalpha(request->alpha2[0]))
request->alpha2[0] = toupper(request->alpha2[0]);
if (isalpha(request->alpha2[1]))
request->alpha2[1] = toupper(request->alpha2[1]);
spin_lock(®_requests_lock);
list_add_tail(&request->list, ®_requests_list);
spin_unlock(®_requests_lock);
schedule_work(®_work);
}
/*
* Core regulatory hint -- happens during cfg80211_init()
* and when we restore regulatory settings.
*/
static int regulatory_hint_core(const char *alpha2)
{
struct regulatory_request *request;
kfree(last_request);
last_request = NULL;
request = kzalloc(sizeof(struct regulatory_request),
GFP_KERNEL);
if (!request)
return -ENOMEM;
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_CORE;
queue_regulatory_request(request);
return 0;
}
/* User hints */
int regulatory_hint_user(const char *alpha2)
{
struct regulatory_request *request;
BUG_ON(!alpha2);
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
return -ENOMEM;
request->wiphy_idx = WIPHY_IDX_STALE;
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_USER;
queue_regulatory_request(request);
return 0;
}
/* Driver hints */
int regulatory_hint(struct wiphy *wiphy, const char *alpha2)
{
struct regulatory_request *request;
BUG_ON(!alpha2);
BUG_ON(!wiphy);
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
return -ENOMEM;
request->wiphy_idx = get_wiphy_idx(wiphy);
/* Must have registered wiphy first */
BUG_ON(!wiphy_idx_valid(request->wiphy_idx));
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_DRIVER;
queue_regulatory_request(request);
return 0;
}
EXPORT_SYMBOL(regulatory_hint);
/*
* We hold wdev_lock() here so we cannot hold cfg80211_mutex() and
* therefore cannot iterate over the rdev list here.
*/
void regulatory_hint_11d(struct wiphy *wiphy,
enum ieee80211_band band,
u8 *country_ie,
u8 country_ie_len)
{
char alpha2[2];
enum environment_cap env = ENVIRON_ANY;
struct regulatory_request *request;
mutex_lock(®_mutex);
if (unlikely(!last_request))
goto out;
/* IE len must be evenly divisible by 2 */
if (country_ie_len & 0x01)
goto out;
if (country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
goto out;
alpha2[0] = country_ie[0];
alpha2[1] = country_ie[1];
if (country_ie[2] == 'I')
env = ENVIRON_INDOOR;
else if (country_ie[2] == 'O')
env = ENVIRON_OUTDOOR;
/*
* We will run this only upon a successful connection on cfg80211.
* We leave conflict resolution to the workqueue, where can hold
* cfg80211_mutex.
*/
if (likely(last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE &&
wiphy_idx_valid(last_request->wiphy_idx)))
goto out;
request = kzalloc(sizeof(struct regulatory_request), GFP_KERNEL);
if (!request)
goto out;
request->wiphy_idx = get_wiphy_idx(wiphy);
request->alpha2[0] = alpha2[0];
request->alpha2[1] = alpha2[1];
request->initiator = NL80211_REGDOM_SET_BY_COUNTRY_IE;
request->country_ie_env = env;
mutex_unlock(®_mutex);
queue_regulatory_request(request);
return;
out:
mutex_unlock(®_mutex);
}
static void restore_alpha2(char *alpha2, bool reset_user)
{
/* indicates there is no alpha2 to consider for restoration */
alpha2[0] = '9';
alpha2[1] = '7';
/* The user setting has precedence over the module parameter */
if (is_user_regdom_saved()) {
/* Unless we're asked to ignore it and reset it */
if (reset_user) {
REG_DBG_PRINT("Restoring regulatory settings "
"including user preference\n");
user_alpha2[0] = '9';
user_alpha2[1] = '7';
/*
* If we're ignoring user settings, we still need to
* check the module parameter to ensure we put things
* back as they were for a full restore.
*/
if (!is_world_regdom(ieee80211_regdom)) {
REG_DBG_PRINT("Keeping preference on "
"module parameter ieee80211_regdom: %c%c\n",
ieee80211_regdom[0],
ieee80211_regdom[1]);
alpha2[0] = ieee80211_regdom[0];
alpha2[1] = ieee80211_regdom[1];
}
} else {
REG_DBG_PRINT("Restoring regulatory settings "
"while preserving user preference for: %c%c\n",
user_alpha2[0],
user_alpha2[1]);
alpha2[0] = user_alpha2[0];
alpha2[1] = user_alpha2[1];
}
} else if (!is_world_regdom(ieee80211_regdom)) {
REG_DBG_PRINT("Keeping preference on "
"module parameter ieee80211_regdom: %c%c\n",
ieee80211_regdom[0],
ieee80211_regdom[1]);
alpha2[0] = ieee80211_regdom[0];
alpha2[1] = ieee80211_regdom[1];
} else
REG_DBG_PRINT("Restoring regulatory settings\n");
}
static void restore_custom_reg_settings(struct wiphy *wiphy)
{
struct ieee80211_supported_band *sband;
enum ieee80211_band band;
struct ieee80211_channel *chan;
int i;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
sband = wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_channels; i++) {
chan = &sband->channels[i];
chan->flags = chan->orig_flags;
chan->max_antenna_gain = chan->orig_mag;
chan->max_power = chan->orig_mpwr;
}
}
}
/*
* Restoring regulatory settings involves ingoring any
* possibly stale country IE information and user regulatory
* settings if so desired, this includes any beacon hints
* learned as we could have traveled outside to another country
* after disconnection. To restore regulatory settings we do
* exactly what we did at bootup:
*
* - send a core regulatory hint
* - send a user regulatory hint if applicable
*
* Device drivers that send a regulatory hint for a specific country
* keep their own regulatory domain on wiphy->regd so that does does
* not need to be remembered.
*/
static void restore_regulatory_settings(bool reset_user)
{
char alpha2[2];
struct reg_beacon *reg_beacon, *btmp;
struct regulatory_request *reg_request, *tmp;
LIST_HEAD(tmp_reg_req_list);
struct cfg80211_registered_device *rdev;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
reset_regdomains();
restore_alpha2(alpha2, reset_user);
/*
* If there's any pending requests we simply
* stash them to a temporary pending queue and
* add then after we've restored regulatory
* settings.
*/
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list)) {
list_for_each_entry_safe(reg_request, tmp,
®_requests_list, list) {
if (reg_request->initiator !=
NL80211_REGDOM_SET_BY_USER)
continue;
list_del(®_request->list);
list_add_tail(®_request->list, &tmp_reg_req_list);
}
}
spin_unlock(®_requests_lock);
/* Clear beacon hints */
spin_lock_bh(®_pending_beacons_lock);
if (!list_empty(®_pending_beacons)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_pending_beacons, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_unlock_bh(®_pending_beacons_lock);
if (!list_empty(®_beacon_list)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_beacon_list, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
/* First restore to the basic regulatory settings */
cfg80211_regdomain = cfg80211_world_regdom;
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
if (rdev->wiphy.flags & WIPHY_FLAG_CUSTOM_REGULATORY)
restore_custom_reg_settings(&rdev->wiphy);
}
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
regulatory_hint_core(cfg80211_regdomain->alpha2);
/*
* This restores the ieee80211_regdom module parameter
* preference or the last user requested regulatory
* settings, user regulatory settings takes precedence.
*/
if (is_an_alpha2(alpha2))
regulatory_hint_user(user_alpha2);
if (list_empty(&tmp_reg_req_list))
return;
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
spin_lock(®_requests_lock);
list_for_each_entry_safe(reg_request, tmp, &tmp_reg_req_list, list) {
REG_DBG_PRINT("Adding request for country %c%c back "
"into the queue\n",
reg_request->alpha2[0],
reg_request->alpha2[1]);
list_del(®_request->list);
list_add_tail(®_request->list, ®_requests_list);
}
spin_unlock(®_requests_lock);
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
REG_DBG_PRINT("Kicking the queue\n");
schedule_work(®_work);
}
void regulatory_hint_disconnect(void)
{
REG_DBG_PRINT("All devices are disconnected, going to "
"restore regulatory settings\n");
restore_regulatory_settings(false);
}
static bool freq_is_chan_12_13_14(u16 freq)
{
if (freq == ieee80211_channel_to_frequency(12, IEEE80211_BAND_2GHZ) ||
freq == ieee80211_channel_to_frequency(13, IEEE80211_BAND_2GHZ) ||
freq == ieee80211_channel_to_frequency(14, IEEE80211_BAND_2GHZ))
return true;
return false;
}
int regulatory_hint_found_beacon(struct wiphy *wiphy,
struct ieee80211_channel *beacon_chan,
gfp_t gfp)
{
struct reg_beacon *reg_beacon;
if (likely((beacon_chan->beacon_found ||
(beacon_chan->flags & IEEE80211_CHAN_RADAR) ||
(beacon_chan->band == IEEE80211_BAND_2GHZ &&
!freq_is_chan_12_13_14(beacon_chan->center_freq)))))
return 0;
reg_beacon = kzalloc(sizeof(struct reg_beacon), gfp);
if (!reg_beacon)
return -ENOMEM;
REG_DBG_PRINT("Found new beacon on "
"frequency: %d MHz (Ch %d) on %s\n",
beacon_chan->center_freq,
ieee80211_frequency_to_channel(beacon_chan->center_freq),
wiphy_name(wiphy));
memcpy(®_beacon->chan, beacon_chan,
sizeof(struct ieee80211_channel));
/*
* Since we can be called from BH or and non-BH context
* we must use spin_lock_bh()
*/
spin_lock_bh(®_pending_beacons_lock);
list_add_tail(®_beacon->list, ®_pending_beacons);
spin_unlock_bh(®_pending_beacons_lock);
schedule_work(®_work);
return 0;
}
static void print_rd_rules(const struct ieee80211_regdomain *rd)
{
unsigned int i;
const struct ieee80211_reg_rule *reg_rule = NULL;
const struct ieee80211_freq_range *freq_range = NULL;
const struct ieee80211_power_rule *power_rule = NULL;
pr_info(" (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp)\n");
for (i = 0; i < rd->n_reg_rules; i++) {
reg_rule = &rd->reg_rules[i];
freq_range = ®_rule->freq_range;
power_rule = ®_rule->power_rule;
/*
* There may not be documentation for max antenna gain
* in certain regions
*/
if (power_rule->max_antenna_gain)
pr_info(" (%d KHz - %d KHz @ %d KHz), (%d mBi, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
freq_range->max_bandwidth_khz,
power_rule->max_antenna_gain,
power_rule->max_eirp);
else
pr_info(" (%d KHz - %d KHz @ %d KHz), (N/A, %d mBm)\n",
freq_range->start_freq_khz,
freq_range->end_freq_khz,
freq_range->max_bandwidth_khz,
power_rule->max_eirp);
}
}
static void print_regdomain(const struct ieee80211_regdomain *rd)
{
if (is_intersected_alpha2(rd->alpha2)) {
if (last_request->initiator ==
NL80211_REGDOM_SET_BY_COUNTRY_IE) {
struct cfg80211_registered_device *rdev;
rdev = cfg80211_rdev_by_wiphy_idx(
last_request->wiphy_idx);
if (rdev) {
pr_info("Current regulatory domain updated by AP to: %c%c\n",
rdev->country_ie_alpha2[0],
rdev->country_ie_alpha2[1]);
} else
pr_info("Current regulatory domain intersected:\n");
} else
pr_info("Current regulatory domain intersected:\n");
} else if (is_world_regdom(rd->alpha2))
pr_info("World regulatory domain updated:\n");
else {
if (is_unknown_alpha2(rd->alpha2))
pr_info("Regulatory domain changed to driver built-in settings (unknown country)\n");
else
pr_info("Regulatory domain changed to country: %c%c\n",
rd->alpha2[0], rd->alpha2[1]);
}
print_rd_rules(rd);
}
static void print_regdomain_info(const struct ieee80211_regdomain *rd)
{
pr_info("Regulatory domain: %c%c\n", rd->alpha2[0], rd->alpha2[1]);
print_rd_rules(rd);
}
/* Takes ownership of rd only if it doesn't fail */
static int __set_regdom(const struct ieee80211_regdomain *rd)
{
const struct ieee80211_regdomain *intersected_rd = NULL;
struct cfg80211_registered_device *rdev = NULL;
struct wiphy *request_wiphy;
/* Some basic sanity checks first */
if (is_world_regdom(rd->alpha2)) {
if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
return -EINVAL;
update_world_regdomain(rd);
return 0;
}
if (!is_alpha2_set(rd->alpha2) && !is_an_alpha2(rd->alpha2) &&
!is_unknown_alpha2(rd->alpha2))
return -EINVAL;
if (!last_request)
return -EINVAL;
/*
* Lets only bother proceeding on the same alpha2 if the current
* rd is non static (it means CRDA was present and was used last)
* and the pending request came in from a country IE
*/
if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
/*
* If someone else asked us to change the rd lets only bother
* checking if the alpha2 changes if CRDA was already called
*/
if (!regdom_changes(rd->alpha2))
return -EINVAL;
}
/*
* Now lets set the regulatory domain, update all driver channels
* and finally inform them of what we have done, in case they want
* to review or adjust their own settings based on their own
* internal EEPROM data
*/
if (WARN_ON(!reg_is_valid_request(rd->alpha2)))
return -EINVAL;
if (!is_valid_rd(rd)) {
pr_err("Invalid regulatory domain detected:\n");
print_regdomain_info(rd);
return -EINVAL;
}
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (!last_request->intersect) {
int r;
if (last_request->initiator != NL80211_REGDOM_SET_BY_DRIVER) {
reset_regdomains();
cfg80211_regdomain = rd;
return 0;
}
/*
* For a driver hint, lets copy the regulatory domain the
* driver wanted to the wiphy to deal with conflicts
*/
/*
* Userspace could have sent two replies with only
* one kernel request.
*/
if (request_wiphy->regd)
return -EALREADY;
r = reg_copy_regd(&request_wiphy->regd, rd);
if (r)
return r;
reset_regdomains();
cfg80211_regdomain = rd;
return 0;
}
/* Intersection requires a bit more work */
if (last_request->initiator != NL80211_REGDOM_SET_BY_COUNTRY_IE) {
intersected_rd = regdom_intersect(rd, cfg80211_regdomain);
if (!intersected_rd)
return -EINVAL;
/*
* We can trash what CRDA provided now.
* However if a driver requested this specific regulatory
* domain we keep it for its private use
*/
if (last_request->initiator == NL80211_REGDOM_SET_BY_DRIVER)
request_wiphy->regd = rd;
else
kfree(rd);
rd = NULL;
reset_regdomains();
cfg80211_regdomain = intersected_rd;
return 0;
}
if (!intersected_rd)
return -EINVAL;
rdev = wiphy_to_dev(request_wiphy);
rdev->country_ie_alpha2[0] = rd->alpha2[0];
rdev->country_ie_alpha2[1] = rd->alpha2[1];
rdev->env = last_request->country_ie_env;
BUG_ON(intersected_rd == rd);
kfree(rd);
rd = NULL;
reset_regdomains();
cfg80211_regdomain = intersected_rd;
return 0;
}
/*
* Use this call to set the current regulatory domain. Conflicts with
* multiple drivers can be ironed out later. Caller must've already
* kmalloc'd the rd structure. Caller must hold cfg80211_mutex
*/
int set_regdom(const struct ieee80211_regdomain *rd)
{
int r;
assert_cfg80211_lock();
mutex_lock(®_mutex);
/* Note that this doesn't update the wiphys, this is done below */
r = __set_regdom(rd);
if (r) {
kfree(rd);
mutex_unlock(®_mutex);
return r;
}
/* This would make this whole thing pointless */
if (!last_request->intersect)
BUG_ON(rd != cfg80211_regdomain);
/* update all wiphys now with the new established regulatory domain */
update_all_wiphy_regulatory(last_request->initiator);
print_regdomain(cfg80211_regdomain);
nl80211_send_reg_change_event(last_request);
reg_set_request_processed();
mutex_unlock(®_mutex);
return r;
}
#ifdef CONFIG_HOTPLUG
int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
if (last_request && !last_request->processed) {
if (add_uevent_var(env, "COUNTRY=%c%c",
last_request->alpha2[0],
last_request->alpha2[1]))
return -ENOMEM;
}
return 0;
}
#else
int reg_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
return -ENODEV;
}
#endif /* CONFIG_HOTPLUG */
/* Caller must hold cfg80211_mutex */
void reg_device_remove(struct wiphy *wiphy)
{
struct wiphy *request_wiphy = NULL;
assert_cfg80211_lock();
mutex_lock(®_mutex);
kfree(wiphy->regd);
if (last_request)
request_wiphy = wiphy_idx_to_wiphy(last_request->wiphy_idx);
if (!request_wiphy || request_wiphy != wiphy)
goto out;
last_request->wiphy_idx = WIPHY_IDX_STALE;
last_request->country_ie_env = ENVIRON_ANY;
out:
mutex_unlock(®_mutex);
}
static void reg_timeout_work(struct work_struct *work)
{
REG_DBG_PRINT("Timeout while waiting for CRDA to reply, "
"restoring regulatory settings");
restore_regulatory_settings(true);
}
int __init regulatory_init(void)
{
int err = 0;
reg_pdev = platform_device_register_simple("regulatory", 0, NULL, 0);
if (IS_ERR(reg_pdev))
return PTR_ERR(reg_pdev);
reg_pdev->dev.type = ®_device_type;
spin_lock_init(®_requests_lock);
spin_lock_init(®_pending_beacons_lock);
cfg80211_regdomain = cfg80211_world_regdom;
user_alpha2[0] = '9';
user_alpha2[1] = '7';
/* We always try to get an update for the static regdomain */
err = regulatory_hint_core(cfg80211_regdomain->alpha2);
if (err) {
if (err == -ENOMEM)
return err;
/*
* N.B. kobject_uevent_env() can fail mainly for when we're out
* memory which is handled and propagated appropriately above
* but it can also fail during a netlink_broadcast() or during
* early boot for call_usermodehelper(). For now treat these
* errors as non-fatal.
*/
pr_err("kobject_uevent_env() was unable to call CRDA during init\n");
#ifdef CONFIG_CFG80211_REG_DEBUG
/* We want to find out exactly why when debugging */
WARN_ON(err);
#endif
}
/*
* Finally, if the user set the module parameter treat it
* as a user hint.
*/
if (!is_world_regdom(ieee80211_regdom))
regulatory_hint_user(ieee80211_regdom);
return 0;
}
void /* __init_or_exit */ regulatory_exit(void)
{
struct regulatory_request *reg_request, *tmp;
struct reg_beacon *reg_beacon, *btmp;
cancel_work_sync(®_work);
cancel_delayed_work_sync(®_timeout);
mutex_lock(&cfg80211_mutex);
mutex_lock(®_mutex);
reset_regdomains();
kfree(last_request);
platform_device_unregister(reg_pdev);
spin_lock_bh(®_pending_beacons_lock);
if (!list_empty(®_pending_beacons)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_pending_beacons, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_unlock_bh(®_pending_beacons_lock);
if (!list_empty(®_beacon_list)) {
list_for_each_entry_safe(reg_beacon, btmp,
®_beacon_list, list) {
list_del(®_beacon->list);
kfree(reg_beacon);
}
}
spin_lock(®_requests_lock);
if (!list_empty(®_requests_list)) {
list_for_each_entry_safe(reg_request, tmp,
®_requests_list, list) {
list_del(®_request->list);
kfree(reg_request);
}
}
spin_unlock(®_requests_lock);
mutex_unlock(®_mutex);
mutex_unlock(&cfg80211_mutex);
}
| vSlipenchuk/ac100hd | net/wireless/reg.c | C | gpl-2.0 | 61,693 |
/* Copyright (C) 2004 - 2009 Versant Inc. http://www.db4o.com */
using Db4objects.Db4o.Query;
using Db4objects.Db4o.Tests.Common.Soda.Util;
using Sharpen;
namespace Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed
{
public class STArrIntegerTNTestCase : SodaBaseTestCase
{
public int[][][] intArr;
public STArrIntegerTNTestCase()
{
}
public STArrIntegerTNTestCase(int[][][] arr)
{
intArr = arr;
}
public override object[] CreateData()
{
Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase[] arr = new
Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase[5];
arr[0] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
();
int[][][] content = new int[][][] { };
arr[1] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content);
content = new int[][][] { new int[][] { new int[3], new int[3] } };
content[0][0][1] = 0;
content[0][1][0] = 0;
arr[2] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content);
content = new int[][][] { new int[][] { new int[3], new int[3] } };
content[0][0][0] = 1;
content[0][1][0] = 17;
content[0][1][1] = int.MaxValue - 1;
arr[3] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content);
content = new int[][][] { new int[][] { new int[2], new int[2] } };
content[0][0][0] = 3;
content[0][0][1] = 17;
content[0][1][0] = 25;
content[0][1][1] = int.MaxValue - 2;
arr[4] = new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content);
object[] ret = new object[arr.Length];
System.Array.Copy(arr, 0, ret, 0, arr.Length);
return ret;
}
public virtual void TestDefaultContainsOne()
{
IQuery q = NewQuery();
int[][][] content = new int[][][] { new int[][] { new int[1] } };
content[0][0][0] = 17;
q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content));
Expect(q, new int[] { 3, 4 });
}
public virtual void TestDefaultContainsTwo()
{
IQuery q = NewQuery();
int[][][] content = new int[][][] { new int[][] { new int[1] }, new int[][] { new
int[1] } };
content[0][0][0] = 17;
content[1][0][0] = 25;
q.Constrain(new Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
(content));
Expect(q, new int[] { 4 });
}
public virtual void TestDescendOne()
{
IQuery q = NewQuery();
q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
));
q.Descend("intArr").Constrain(17);
Expect(q, new int[] { 3, 4 });
}
public virtual void TestDescendTwo()
{
IQuery q = NewQuery();
q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
));
IQuery qElements = q.Descend("intArr");
qElements.Constrain(17);
qElements.Constrain(25);
Expect(q, new int[] { 4 });
}
public virtual void TestDescendSmaller()
{
IQuery q = NewQuery();
q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
));
IQuery qElements = q.Descend("intArr");
qElements.Constrain(3).Smaller();
Expect(q, new int[] { 2, 3 });
}
public virtual void TestDescendNotSmaller()
{
IQuery q = NewQuery();
q.Constrain(typeof(Db4objects.Db4o.Tests.Common.Soda.Arrays.Typed.STArrIntegerTNTestCase
));
IQuery qElements = q.Descend("intArr");
qElements.Constrain(3).Smaller();
Expect(q, new int[] { 2, 3 });
}
}
}
| meebey/smuxi-head-mirror | lib/db4o-net/Db4objects.Db4o.Tests/Db4objects.Db4o.Tests/Common/Soda/Arrays/Typed/STArrIntegerTNTestCase.cs | C# | gpl-2.0 | 3,696 |
showWord(["","Wayòm ki te nan pati Sidwès peyi Ispayola. Se Boyekyo ki te chèf endyen nan wayòm sa a. Kapital wayòm sa a te Lagwana, kounye a yo rele l Leogàn."
]) | georgejhunt/HaitiDictionary.activity | data/words/zaragwa.js | JavaScript | gpl-2.0 | 169 |
#include "steadystatetest.hh"
#include <models/REmodel.hh>
#include <models/LNAmodel.hh>
#include <models/IOSmodel.hh>
#include <models/sseinterpreter.hh>
#include <models/steadystateanalysis.hh>
#include <eval/jit/engine.hh>
#include <parser/sbml/sbml.hh>
using namespace iNA;
SteadyStateTest::~SteadyStateTest() {
// pass...
}
void
SteadyStateTest::testEnzymeKineticsRE() {
// Read doc and check for errors:
Ast::Model sbml_model;
Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml");
// Construct RE model to integrate
Models::REmodel model(sbml_model);
// Perform analysis:
Eigen::VectorXd state(model.getDimension());
Models::SteadyStateAnalysis<Models::REmodel> analysis(model);
analysis.setMaxIterations(1000);
analysis.calcSteadyState(state);
}
void
SteadyStateTest::testEnzymeKineticsLNA() {
// Read doc and check for errors:
Ast::Model sbml_model;
Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml");
// Construct LNA model to integrate
Models::LNAmodel model(sbml_model);
// Perform analysis:
Eigen::VectorXd state(model.getDimension());
Models::SteadyStateAnalysis<Models::LNAmodel> analysis(model);
analysis.setMaxIterations(1000);
analysis.calcSteadyState(state);
}
void
SteadyStateTest::testEnzymeKineticsIOS() {
// Read doc and check for errors:
Ast::Model sbml_model;
Parser::Sbml::importModel(sbml_model, "test/regression-tests/extended_goodwin.xml");
// Construct model to integrate
Models::IOSmodel model(sbml_model);
// Perform analysis:
Eigen::VectorXd state(model.getDimension());
Models::SteadyStateAnalysis<Models::IOSmodel> analysis(model);
analysis.setMaxIterations(1000);
analysis.calcSteadyState(state);
}
UnitTest::TestSuite *
SteadyStateTest::suite() {
UnitTest::TestSuite *s = new UnitTest::TestSuite("Steady State Tests");
s->addTest(new UnitTest::TestCaller<SteadyStateTest>(
"EnzymeKinetics Model (RE)", &SteadyStateTest::testEnzymeKineticsRE));
s->addTest(new UnitTest::TestCaller<SteadyStateTest>(
"EnzymeKinetics Model (LNA)", &SteadyStateTest::testEnzymeKineticsLNA));
s->addTest(new UnitTest::TestCaller<SteadyStateTest>(
"EnzymeKinetics Model (IOS)", &SteadyStateTest::testEnzymeKineticsIOS));
return s;
}
| hmatuschek/intrinsic-noise-analyzer | test/steadystatetest.cc | C++ | gpl-2.0 | 2,341 |
-- 17/03/2011 9h3min12s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Element (AD_Client_ID,AD_Element_ID,AD_Org_ID,ColumnName,Created,CreatedBy,Description,EntityType,Help,IsActive,Name,PrintName,Updated,UpdatedBy) VALUES (0,1120054,0,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 09:03:10','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA','Defines the Tax Status (PIS)','Y','Tax Status (PIS)','Tax Status (PIS)',TO_TIMESTAMP('2011-03-17 09:03:10','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 9h3min12s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Element_Trl (AD_Language,AD_Element_ID, Description,Help,Name,PO_Description,PO_Help,PO_Name,PO_PrintName,PrintName, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Element_ID, t.Description,t.Help,t.Name,t.PO_Description,t.PO_Help,t.PO_Name,t.PO_PrintName,t.PrintName, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Element t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Element_ID=1120054 AND NOT EXISTS (SELECT * FROM AD_Element_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Element_ID=t.AD_Element_ID)
;
-- 17/03/2011 9h3min43s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Element_Trl SET IsTranslated='Y',Name='Situação Tributária (PIS)',PrintName='Situação Tributária (PIS)',Description='Defines a Situação Tributária (PIS)',Help='Defines a Situação Tributária (PIS)',Updated=TO_TIMESTAMP('2011-03-17 09:03:43','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Element_ID=1120054 AND AD_Language='pt_BR'
;
-- 17/03/2011 9h4min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Reference (AD_Client_ID,AD_Org_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,IsOrderByValue,Name,Updated,UpdatedBy,ValidationType) VALUES (0,0,1120023,TO_TIMESTAMP('2011-03-17 09:04:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','N','lbr_TaxStatusPIS_COFINS',TO_TIMESTAMP('2011-03-17 09:04:43','YYYY-MM-DD HH24:MI:SS'),100,'L')
;
-- 17/03/2011 9h4min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Reference_Trl (AD_Language,AD_Reference_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Reference_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Reference t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Reference_ID=1120023 AND NOT EXISTS (SELECT * FROM AD_Reference_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Reference_ID=t.AD_Reference_ID)
;
-- 17/03/2011 9h5min17s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120096,1120023,TO_TIMESTAMP('2011-03-17 09:05:17','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','01 - Operação Tributável com Alíquota Básica',TO_TIMESTAMP('2011-03-17 09:05:17','YYYY-MM-DD HH24:MI:SS'),100,'01')
;
-- 17/03/2011 9h5min17s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120096 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h5min32s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120097,1120023,TO_TIMESTAMP('2011-03-17 09:05:32','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','02 - Operação Tributável com Alíquota Diferenciada',TO_TIMESTAMP('2011-03-17 09:05:32','YYYY-MM-DD HH24:MI:SS'),100,'02')
;
-- 17/03/2011 9h5min32s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120097 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h5min47s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120098,1120023,TO_TIMESTAMP('2011-03-17 09:05:46','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','03 - Operação Tributável com Alíquota por Unidade de Medida de Produto',TO_TIMESTAMP('2011-03-17 09:05:46','YYYY-MM-DD HH24:MI:SS'),100,'03')
;
-- 17/03/2011 9h5min47s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120098 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h6min4s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120099,1120023,TO_TIMESTAMP('2011-03-17 09:06:04','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','04 - Operação Tributável Monofásica - Revenda a Alíquota Zero',TO_TIMESTAMP('2011-03-17 09:06:04','YYYY-MM-DD HH24:MI:SS'),100,'04')
;
-- 17/03/2011 9h6min4s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120099 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h6min25s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120100,1120023,TO_TIMESTAMP('2011-03-17 09:06:24','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','05 - Operação Tributável por Substituição Tributária',TO_TIMESTAMP('2011-03-17 09:06:24','YYYY-MM-DD HH24:MI:SS'),100,'05')
;
-- 17/03/2011 9h6min25s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120100 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h6min58s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120101,1120023,TO_TIMESTAMP('2011-03-17 09:06:57','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','06 - Operação Tributável a Alíquota Zero',TO_TIMESTAMP('2011-03-17 09:06:57','YYYY-MM-DD HH24:MI:SS'),100,'06')
;
-- 17/03/2011 9h6min58s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120101 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h7min12s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120102,1120023,TO_TIMESTAMP('2011-03-17 09:07:12','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','07 - Operação Isenta da Contribuição',TO_TIMESTAMP('2011-03-17 09:07:12','YYYY-MM-DD HH24:MI:SS'),100,'07')
;
-- 17/03/2011 9h7min12s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120102 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h9min1s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120103,1120023,TO_TIMESTAMP('2011-03-17 09:09:00','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','08 - Operação sem Incidência da Contribuição',TO_TIMESTAMP('2011-03-17 09:09:00','YYYY-MM-DD HH24:MI:SS'),100,'08')
;
-- 17/03/2011 9h9min1s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120103 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h9min15s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120104,1120023,TO_TIMESTAMP('2011-03-17 09:09:14','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','09 - Operação com Suspensão da Contribuição',TO_TIMESTAMP('2011-03-17 09:09:14','YYYY-MM-DD HH24:MI:SS'),100,'09')
;
-- 17/03/2011 9h9min15s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120104 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h9min31s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120105,1120023,TO_TIMESTAMP('2011-03-17 09:09:31','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','49 - Outras Operações de Saída',TO_TIMESTAMP('2011-03-17 09:09:31','YYYY-MM-DD HH24:MI:SS'),100,'49')
;
-- 17/03/2011 9h9min31s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120105 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h9min49s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120106,1120023,TO_TIMESTAMP('2011-03-17 09:09:48','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','50 - Operação com Direito a Crédito - Vinculada Exclusivamente a Receita Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:09:48','YYYY-MM-DD HH24:MI:SS'),100,'50')
;
-- 17/03/2011 9h9min49s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120106 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h10min8s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120107,1120023,TO_TIMESTAMP('2011-03-17 09:10:07','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','51 - Operação com Direito a Crédito – Vinculada Exclusivamente a Receita Não Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:10:07','YYYY-MM-DD HH24:MI:SS'),100,'51')
;
-- 17/03/2011 9h10min8s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120107 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h10min24s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120108,1120023,TO_TIMESTAMP('2011-03-17 09:10:24','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','52 - Operação com Direito a Crédito - Vinculada Exclusivamente a Receita de Exportação',TO_TIMESTAMP('2011-03-17 09:10:24','YYYY-MM-DD HH24:MI:SS'),100,'52')
;
-- 17/03/2011 9h10min24s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120108 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h10min38s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120109,1120023,TO_TIMESTAMP('2011-03-17 09:10:37','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','53 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno',TO_TIMESTAMP('2011-03-17 09:10:37','YYYY-MM-DD HH24:MI:SS'),100,'53')
;
-- 17/03/2011 9h10min38s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120109 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h11min0s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120110,1120023,TO_TIMESTAMP('2011-03-17 09:11:00','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','54 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 09:11:00','YYYY-MM-DD HH24:MI:SS'),100,'54')
;
-- 17/03/2011 9h11min0s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120110 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 9h11min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120111,1120023,TO_TIMESTAMP('2011-03-17 09:11:20','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','55 - Operação com Direito a Crédito - Vinculada a Receitas Não-Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 09:11:20','YYYY-MM-DD HH24:MI:SS'),100,'55')
;
-- 17/03/2011 9h11min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120111 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h6min3s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120112,1120023,TO_TIMESTAMP('2011-03-17 10:06:02','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','56 - Operação com Direito a Crédito - Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno, e de Exportação',TO_TIMESTAMP('2011-03-17 10:06:02','YYYY-MM-DD HH24:MI:SS'),100,'56')
;
-- 17/03/2011 10h6min3s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120112 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h6min21s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120113,1120023,TO_TIMESTAMP('2011-03-17 10:06:20','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','60 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:06:20','YYYY-MM-DD HH24:MI:SS'),100,'60')
;
-- 17/03/2011 10h6min21s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120113 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h6min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120114,1120023,TO_TIMESTAMP('2011-03-17 10:06:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','61 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita Não-Tributada no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:06:43','YYYY-MM-DD HH24:MI:SS'),100,'61')
;
-- 17/03/2011 10h6min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120114 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h7min13s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120115,1120023,TO_TIMESTAMP('2011-03-17 10:07:13','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','62 - Crédito Presumido - Operação de Aquisição Vinculada Exclusivamente a Receita de Exportação',TO_TIMESTAMP('2011-03-17 10:07:13','YYYY-MM-DD HH24:MI:SS'),100,'62')
;
-- 17/03/2011 10h7min13s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120115 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h7min28s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120116,1120023,TO_TIMESTAMP('2011-03-17 10:07:27','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','63 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno',TO_TIMESTAMP('2011-03-17 10:07:27','YYYY-MM-DD HH24:MI:SS'),100,'63')
;
-- 17/03/2011 10h7min28s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120116 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h7min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120117,1120023,TO_TIMESTAMP('2011-03-17 10:07:43','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','64 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 10:07:43','YYYY-MM-DD HH24:MI:SS'),100,'64')
;
-- 17/03/2011 10h7min44s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120117 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h8min0s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120118,1120023,TO_TIMESTAMP('2011-03-17 10:07:59','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','65 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Não-Tributadas no Mercado Interno e de Exportação',TO_TIMESTAMP('2011-03-17 10:07:59','YYYY-MM-DD HH24:MI:SS'),100,'65')
;
-- 17/03/2011 10h8min0s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120118 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h8min28s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120119,1120023,TO_TIMESTAMP('2011-03-17 10:08:27','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','66 - Crédito Presumido - Operação de Aquisição Vinculada a Receitas Tributadas e Não-Tributadas no Mercado Interno e Exp.',TO_TIMESTAMP('2011-03-17 10:08:27','YYYY-MM-DD HH24:MI:SS'),100,'66')
;
-- 17/03/2011 10h8min28s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120119 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h8min45s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120120,1120023,TO_TIMESTAMP('2011-03-17 10:08:44','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','67 - Crédito Presumido - Outras Operações',TO_TIMESTAMP('2011-03-17 10:08:44','YYYY-MM-DD HH24:MI:SS'),100,'67')
;
-- 17/03/2011 10h8min45s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120120 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h9min11s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120121,1120023,TO_TIMESTAMP('2011-03-17 10:09:11','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','70 - Operação de Aquisição sem Direito a Crédito',TO_TIMESTAMP('2011-03-17 10:09:11','YYYY-MM-DD HH24:MI:SS'),100,'70')
;
-- 17/03/2011 10h9min11s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120121 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h10min31s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120122,1120023,TO_TIMESTAMP('2011-03-17 10:10:30','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','71 - Operação de Aquisição com Isenção',TO_TIMESTAMP('2011-03-17 10:10:30','YYYY-MM-DD HH24:MI:SS'),100,'71')
;
-- 17/03/2011 10h10min31s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120122 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h10min55s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120123,1120023,TO_TIMESTAMP('2011-03-17 10:10:54','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','72 - Operação de Aquisição com Suspensão',TO_TIMESTAMP('2011-03-17 10:10:54','YYYY-MM-DD HH24:MI:SS'),100,'72')
;
-- 17/03/2011 10h10min55s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120123 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h16min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120124,1120023,TO_TIMESTAMP('2011-03-17 10:16:19','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','73 - Operação de Aquisição a Alíquota Zero',TO_TIMESTAMP('2011-03-17 10:16:19','YYYY-MM-DD HH24:MI:SS'),100,'73')
;
-- 17/03/2011 10h16min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120124 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h16min35s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120125,1120023,TO_TIMESTAMP('2011-03-17 10:16:35','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','74 - Operação de Aquisição sem Incidência da Contribuição',TO_TIMESTAMP('2011-03-17 10:16:35','YYYY-MM-DD HH24:MI:SS'),100,'74')
;
-- 17/03/2011 10h16min35s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120125 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h16min52s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120126,1120023,TO_TIMESTAMP('2011-03-17 10:16:52','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','75 - Operação de Aquisição por Substituição Tributária',TO_TIMESTAMP('2011-03-17 10:16:52','YYYY-MM-DD HH24:MI:SS'),100,'75')
;
-- 17/03/2011 10h16min52s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120126 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h17min8s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120127,1120023,TO_TIMESTAMP('2011-03-17 10:17:07','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','98 - Outras Operações de Entrada',TO_TIMESTAMP('2011-03-17 10:17:07','YYYY-MM-DD HH24:MI:SS'),100,'98')
;
-- 17/03/2011 10h17min8s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120127 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h17min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List (AD_Client_ID,AD_Org_ID,AD_Ref_List_ID,AD_Reference_ID,Created,CreatedBy,EntityType,IsActive,Name,Updated,UpdatedBy,Value) VALUES (0,0,1120128,1120023,TO_TIMESTAMP('2011-03-17 10:17:19','YYYY-MM-DD HH24:MI:SS'),100,'LBRA','Y','99 - Outras Operações',TO_TIMESTAMP('2011-03-17 10:17:19','YYYY-MM-DD HH24:MI:SS'),100,'99')
;
-- 17/03/2011 10h17min20s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Ref_List_Trl (AD_Language,AD_Ref_List_ID, Description,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Ref_List_ID, t.Description,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Ref_List t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Ref_List_ID=1120128 AND NOT EXISTS (SELECT * FROM AD_Ref_List_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Ref_List_ID=t.AD_Ref_List_ID)
;
-- 17/03/2011 10h17min50s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120265,1120054,0,17,1120023,333,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 10:17:49','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA',2,'Defines the Tax Status (PIS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (PIS)',0,TO_TIMESTAMP('2011-03-17 10:17:49','YYYY-MM-DD HH24:MI:SS'),100,0)
;
-- 17/03/2011 10h17min50s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120265 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 17/03/2011 10h17min52s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
ALTER TABLE C_InvoiceLine ADD COLUMN lbr_TaxStatusPIS VARCHAR(2) DEFAULT NULL
;
-- 17/03/2011 10h26min38s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Element (AD_Client_ID,AD_Element_ID,AD_Org_ID,ColumnName,Created,CreatedBy,Description,EntityType,Help,IsActive,Name,PrintName,Updated,UpdatedBy) VALUES (0,1120055,0,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 10:26:37','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA','Defines the Tax Status (COFINS)','Y','Tax Status (COFINS)','Tax Status (COFINS)',TO_TIMESTAMP('2011-03-17 10:26:37','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 10h26min38s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Element_Trl (AD_Language,AD_Element_ID, Description,Help,Name,PO_Description,PO_Help,PO_Name,PO_PrintName,PrintName, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Element_ID, t.Description,t.Help,t.Name,t.PO_Description,t.PO_Help,t.PO_Name,t.PO_PrintName,t.PrintName, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Element t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Element_ID=1120055 AND NOT EXISTS (SELECT * FROM AD_Element_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Element_ID=t.AD_Element_ID)
;
-- 17/03/2011 10h27min16s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Element_Trl SET IsTranslated='Y',Name='Situação Tributária (COFINS)',PrintName='Situação Tributária (COFINS)',Description='Defines a Situação Tributária (COFINS)',Help='Defines a Situação Tributária (COFINS)',Updated=TO_TIMESTAMP('2011-03-17 10:27:16','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Element_ID=1120055 AND AD_Language='pt_BR'
;
-- 17/03/2011 10h27min29s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120266,1120055,0,17,1120023,333,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 10:27:28','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA',2,'Defines the Tax Status (COFINS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (COFINS)',0,TO_TIMESTAMP('2011-03-17 10:27:28','YYYY-MM-DD HH24:MI:SS'),100,0)
;
-- 17/03/2011 10h27min29s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120266 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 17/03/2011 10h27min30s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
ALTER TABLE C_InvoiceLine ADD COLUMN lbr_TaxStatusCOFINS VARCHAR(2) DEFAULT NULL
;
-- 17/03/2011 11h40min3s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120267,1120054,0,17,1120023,1000028,'lbr_TaxStatusPIS',TO_TIMESTAMP('2011-03-17 11:40:01','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)','LBRA',2,'Defines the Tax Status (PIS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (PIS)',0,TO_TIMESTAMP('2011-03-17 11:40:01','YYYY-MM-DD HH24:MI:SS'),100,0)
;
-- 17/03/2011 11h40min3s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120267 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 17/03/2011 11h41min24s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
ALTER TABLE LBR_NotaFiscalLine ADD COLUMN lbr_TaxStatusPIS VARCHAR(2) DEFAULT NULL
;
-- 17/03/2011 11h41min47s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column (AD_Client_ID,AD_Column_ID,AD_Element_ID,AD_Org_ID,AD_Reference_ID,AD_Reference_Value_ID,AD_Table_ID,ColumnName,Created,CreatedBy,Description,EntityType,FieldLength,Help,IsActive,IsAllowLogging,IsAlwaysUpdateable,IsAutocomplete,IsEncrypted,IsIdentifier,IsKey,IsMandatory,IsParent,IsSelectionColumn,IsSyncDatabase,IsTranslated,IsUpdateable,Name,SeqNo,Updated,UpdatedBy,Version) VALUES (0,1120268,1120055,0,17,1120023,1000028,'lbr_TaxStatusCOFINS',TO_TIMESTAMP('2011-03-17 11:41:47','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)','LBRA',2,'Defines the Tax Status (COFINS)','Y','Y','N','N','N','N','N','N','N','N','N','N','Y','Tax Status (COFINS)',0,TO_TIMESTAMP('2011-03-17 11:41:47','YYYY-MM-DD HH24:MI:SS'),100,0)
;
-- 17/03/2011 11h41min47s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=1120268 AND NOT EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 17/03/2011 11h41min49s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
ALTER TABLE LBR_NotaFiscalLine ADD COLUMN lbr_TaxStatusCOFINS VARCHAR(2) DEFAULT NULL
;
-- 17/03/2011 11h42min48s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120267,1120196,0,1000021,TO_TIMESTAMP('2011-03-17 11:42:47','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)',2,'LBRA','Defines the Tax Status (PIS)','Y','Y','Y','N','N','N','N','N','Tax Status (PIS)',201,TO_TIMESTAMP('2011-03-17 11:42:47','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 11h42min48s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120196 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID)
;
-- 17/03/2011 11h43min16s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120268,1120197,0,1000021,TO_TIMESTAMP('2011-03-17 11:43:15','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)',2,'LBRA','Defines the Tax Status (COFINS)','Y','Y','Y','N','N','N','N','Y','Tax Status (COFINS)',202,TO_TIMESTAMP('2011-03-17 11:43:15','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 11h43min16s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120197 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID)
;
-- 17/03/2011 11h44min9s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120267,1120198,0,1000030,TO_TIMESTAMP('2011-03-17 11:44:08','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (PIS)',2,'LBRA','Defines the Tax Status (PIS)','Y','Y','Y','N','N','N','N','N','Tax Status (PIS)',251,TO_TIMESTAMP('2011-03-17 11:44:08','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 11h44min9s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120198 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID)
;
-- 17/03/2011 11h44min32s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field (AD_Client_ID,AD_Column_ID,AD_Field_ID,AD_Org_ID,AD_Tab_ID,Created,CreatedBy,Description,DisplayLength,EntityType,Help,IsActive,IsCentrallyMaintained,IsDisplayed,IsEncrypted,IsFieldOnly,IsHeading,IsReadOnly,IsSameLine,Name,SeqNo,Updated,UpdatedBy) VALUES (0,1120268,1120199,0,1000030,TO_TIMESTAMP('2011-03-17 11:44:31','YYYY-MM-DD HH24:MI:SS'),100,'Defines the Tax Status (COFINS)',2,'LBRA','Defines the Tax Status (COFINS)','Y','Y','Y','N','N','N','N','Y','Tax Status (COFINS)',252,TO_TIMESTAMP('2011-03-17 11:44:31','YYYY-MM-DD HH24:MI:SS'),100)
;
-- 17/03/2011 11h44min32s BRT
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=1120199 AND NOT EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Field_ID=t.AD_Field_ID)
;
UPDATE AD_SysConfig SET Value='360-trunk/040-FR_3220195.sql' WHERE AD_SysConfig_ID=1100006;
| mgrigioni/oseb | db_scripts/360-370/postgresql/040-FR_3220195.sql | SQL | gpl-2.0 | 53,994 |
/*
* pcm audio input device
*
* Copyright (C) 2008 Google, Inc.
* Copyright (C) 2008 HTC Corporation
* Copyright (c) 2009-2010, Code Aurora Forum. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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.
*
*/
#include <mach/debug_audio_mm.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/dma-mapping.h>
#include <linux/msm_audio.h>
#include <asm/atomic.h>
#include <asm/ioctls.h>
#include <mach/msm_adsp.h>
#include <mach/qdsp5v2/qdsp5audreccmdi.h>
#include <mach/qdsp5v2/qdsp5audrecmsg.h>
#include <mach/qdsp5v2/audpreproc.h>
#include <mach/qdsp5v2/audio_dev_ctl.h>
/* FRAME_NUM must be a power of two */
#define FRAME_NUM (8)
#define FRAME_SIZE (2052 * 2)
#define MONO_DATA_SIZE (2048)
#define STEREO_DATA_SIZE (MONO_DATA_SIZE * 2)
#define DMASZ (FRAME_SIZE * FRAME_NUM)
struct buffer {
void *data;
uint32_t size;
uint32_t read;
uint32_t addr;
};
struct audio_in {
struct buffer in[FRAME_NUM];
spinlock_t dsp_lock;
atomic_t in_bytes;
atomic_t in_samples;
struct mutex lock;
struct mutex read_lock;
wait_queue_head_t wait;
wait_queue_head_t wait_enable;
struct msm_adsp_module *audrec;
/* configuration to use on next enable */
uint32_t samp_rate;
uint32_t channel_mode;
uint32_t buffer_size; /* 2048 for mono, 4096 for stereo */
uint32_t enc_type;
uint32_t dsp_cnt;
uint32_t in_head; /* next buffer dsp will write */
uint32_t in_tail; /* next buffer read() will read */
uint32_t in_count; /* number of buffers available to read() */
const char *module_name;
unsigned queue_ids;
uint16_t enc_id; /* Session Id */
uint16_t source; /* Encoding source bit mask */
uint32_t device_events; /* device events interested in */
uint32_t dev_cnt;
spinlock_t dev_lock;
/* data allocated for various buffers */
char *data;
dma_addr_t phys;
int opened;
int enabled;
int running;
int stopped; /* set when stopped, cleared on flush */
int abort; /* set when error, like sample rate mismatch */
};
static struct audio_in the_audio_in;
struct audio_frame {
uint16_t frame_count_lsw;
uint16_t frame_count_msw;
uint16_t frame_length;
uint16_t erased_pcm;
unsigned char raw_bitstream[]; /* samples */
} __attribute__((packed));
/* Audrec Queue command sent macro's */
#define audrec_send_bitstreamqueue(audio, cmd, len) \
msm_adsp_write(audio->audrec, ((audio->queue_ids & 0xFFFF0000) >> 16),\
cmd, len)
#define audrec_send_audrecqueue(audio, cmd, len) \
msm_adsp_write(audio->audrec, (audio->queue_ids & 0x0000FFFF),\
cmd, len)
/* DSP command send functions */
static int audpcm_in_enc_config(struct audio_in *audio, int enable);
static int audpcm_in_param_config(struct audio_in *audio);
static int audpcm_in_mem_config(struct audio_in *audio);
static int audpcm_in_record_config(struct audio_in *audio, int enable);
static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt);
static void audpcm_in_get_dsp_frames(struct audio_in *audio);
static void audpcm_in_flush(struct audio_in *audio);
static void pcm_in_listener(u32 evt_id, union auddev_evt_data *evt_payload,
void *private_data)
{
struct audio_in *audio = (struct audio_in *) private_data;
unsigned long flags;
MM_DBG("evt_id = 0x%8x\n", evt_id);
switch (evt_id) {
case AUDDEV_EVT_DEV_RDY: {
MM_DBG("AUDDEV_EVT_DEV_RDY\n");
spin_lock_irqsave(&audio->dev_lock, flags);
audio->dev_cnt++;
audio->source |= (0x1 << evt_payload->routing_id);
spin_unlock_irqrestore(&audio->dev_lock, flags);
if ((audio->running == 1) && (audio->enabled == 1))
audpcm_in_record_config(audio, 1);
break;
}
case AUDDEV_EVT_DEV_RLS: {
MM_DBG("AUDDEV_EVT_DEV_RLS\n");
spin_lock_irqsave(&audio->dev_lock, flags);
audio->dev_cnt--;
audio->source &= ~(0x1 << evt_payload->routing_id);
spin_unlock_irqrestore(&audio->dev_lock, flags);
if (!audio->running || !audio->enabled)
break;
/* Turn of as per source */
if (audio->source)
audpcm_in_record_config(audio, 1);
else
/* Turn off all */
audpcm_in_record_config(audio, 0);
break;
}
case AUDDEV_EVT_FREQ_CHG: {
MM_DBG("Encoder Driver got sample rate change event\n");
MM_DBG("sample rate %d\n", evt_payload->freq_info.sample_rate);
MM_DBG("dev_type %d\n", evt_payload->freq_info.dev_type);
MM_DBG("acdb_dev_id %d\n", evt_payload->freq_info.acdb_dev_id);
if (audio->running == 1) {
/* Stop Recording sample rate does not match
with device sample rate */
if (evt_payload->freq_info.sample_rate !=
audio->samp_rate) {
audpcm_in_record_config(audio, 0);
audio->abort = 1;
wake_up(&audio->wait);
}
}
break;
}
default:
MM_ERR("wrong event %d\n", evt_id);
break;
}
}
/* ------------------- dsp preproc event handler--------------------- */
static void audpreproc_dsp_event(void *data, unsigned id, void *msg)
{
struct audio_in *audio = data;
switch (id) {
case AUDPREPROC_ERROR_MSG: {
struct audpreproc_err_msg *err_msg = msg;
MM_ERR("ERROR_MSG: stream id %d err idx %d\n",
err_msg->stream_id, err_msg->aud_preproc_err_idx);
/* Error case */
wake_up(&audio->wait_enable);
break;
}
case AUDPREPROC_CMD_CFG_DONE_MSG: {
MM_DBG("CMD_CFG_DONE_MSG \n");
break;
}
case AUDPREPROC_CMD_ENC_CFG_DONE_MSG: {
struct audpreproc_cmd_enc_cfg_done_msg *enc_cfg_msg = msg;
MM_DBG("CMD_ENC_CFG_DONE_MSG: stream id %d enc type \
0x%8x\n", enc_cfg_msg->stream_id,
enc_cfg_msg->rec_enc_type);
/* Encoder enable success */
if (enc_cfg_msg->rec_enc_type & ENCODE_ENABLE)
audpcm_in_param_config(audio);
else { /* Encoder disable success */
audio->running = 0;
audpcm_in_record_config(audio, 0);
}
break;
}
case AUDPREPROC_CMD_ENC_PARAM_CFG_DONE_MSG: {
MM_DBG("CMD_ENC_PARAM_CFG_DONE_MSG \n");
audpcm_in_mem_config(audio);
break;
}
case AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG: {
MM_DBG("AFE_CMD_AUDIO_RECORD_CFG_DONE_MSG \n");
wake_up(&audio->wait_enable);
break;
}
default:
MM_ERR("Unknown Event id %d\n", id);
}
}
/* ------------------- dsp audrec event handler--------------------- */
static void audrec_dsp_event(void *data, unsigned id, size_t len,
void (*getevent)(void *ptr, size_t len))
{
struct audio_in *audio = data;
switch (id) {
case AUDREC_CMD_MEM_CFG_DONE_MSG: {
MM_DBG("CMD_MEM_CFG_DONE MSG DONE\n");
audio->running = 1;
if (audio->dev_cnt > 0)
audpcm_in_record_config(audio, 1);
break;
}
case AUDREC_FATAL_ERR_MSG: {
struct audrec_fatal_err_msg fatal_err_msg;
getevent(&fatal_err_msg, AUDREC_FATAL_ERR_MSG_LEN);
MM_ERR("FATAL_ERR_MSG: err id %d\n",
fatal_err_msg.audrec_err_id);
/* Error stop the encoder */
audio->stopped = 1;
wake_up(&audio->wait);
break;
}
case AUDREC_UP_PACKET_READY_MSG: {
struct audrec_up_pkt_ready_msg pkt_ready_msg;
getevent(&pkt_ready_msg, AUDREC_UP_PACKET_READY_MSG_LEN);
MM_DBG("UP_PACKET_READY_MSG: write cnt lsw %d \
write cnt msw %d read cnt lsw %d read cnt msw %d \n",\
pkt_ready_msg.audrec_packet_write_cnt_lsw, \
pkt_ready_msg.audrec_packet_write_cnt_msw, \
pkt_ready_msg.audrec_up_prev_read_cnt_lsw, \
pkt_ready_msg.audrec_up_prev_read_cnt_msw);
audpcm_in_get_dsp_frames(audio);
break;
}
default:
MM_ERR("Unknown Event id %d\n", id);
}
}
static void audpcm_in_get_dsp_frames(struct audio_in *audio)
{
struct audio_frame *frame;
uint32_t index;
unsigned long flags;
index = audio->in_head;
frame = (void *) (((char *)audio->in[index].data) - \
sizeof(*frame));
spin_lock_irqsave(&audio->dsp_lock, flags);
audio->in[index].size = frame->frame_length;
/* statistics of read */
atomic_add(audio->in[index].size, &audio->in_bytes);
atomic_add(1, &audio->in_samples);
audio->in_head = (audio->in_head + 1) & (FRAME_NUM - 1);
/* If overflow, move the tail index foward. */
if (audio->in_head == audio->in_tail)
audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1);
else
audio->in_count++;
audpcm_dsp_read_buffer(audio, audio->dsp_cnt++);
spin_unlock_irqrestore(&audio->dsp_lock, flags);
wake_up(&audio->wait);
}
struct msm_adsp_ops audrec_adsp_ops = {
.event = audrec_dsp_event,
};
static int audpcm_in_enc_config(struct audio_in *audio, int enable)
{
struct audpreproc_audrec_cmd_enc_cfg cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.cmd_id = AUDPREPROC_AUDREC_CMD_ENC_CFG;
cmd.stream_id = audio->enc_id;
if (enable)
cmd.audrec_enc_type = audio->enc_type | ENCODE_ENABLE;
else
cmd.audrec_enc_type &= ~(ENCODE_ENABLE);
return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd));
}
static int audpcm_in_param_config(struct audio_in *audio)
{
struct audpreproc_audrec_cmd_parm_cfg_wav cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.common.cmd_id = AUDPREPROC_AUDREC_CMD_PARAM_CFG;
cmd.common.stream_id = audio->enc_id;
cmd.aud_rec_samplerate_idx = audio->samp_rate;
cmd.aud_rec_stereo_mode = audio->channel_mode;
return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd));
}
/* To Do: msm_snddev_route_enc(audio->enc_id); */
static int audpcm_in_record_config(struct audio_in *audio, int enable)
{
struct audpreproc_afe_cmd_audio_record_cfg cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.cmd_id = AUDPREPROC_AFE_CMD_AUDIO_RECORD_CFG;
cmd.stream_id = audio->enc_id;
if (enable)
cmd.destination_activity = AUDIO_RECORDING_TURN_ON;
else
cmd.destination_activity = AUDIO_RECORDING_TURN_OFF;
cmd.source_mix_mask = audio->source;
return audpreproc_send_audreccmdqueue(&cmd, sizeof(cmd));
}
static int audpcm_in_mem_config(struct audio_in *audio)
{
struct audrec_cmd_arecmem_cfg cmd;
uint16_t *data = (void *) audio->data;
int n;
memset(&cmd, 0, sizeof(cmd));
cmd.cmd_id = AUDREC_CMD_MEM_CFG_CMD;
cmd.audrec_up_pkt_intm_count = 1;
cmd.audrec_ext_pkt_start_addr_msw = audio->phys >> 16;
cmd.audrec_ext_pkt_start_addr_lsw = audio->phys;
cmd.audrec_ext_pkt_buf_number = FRAME_NUM;
/* prepare buffer pointers:
* Mono: 1024 samples + 4 halfword header
* Stereo: 2048 samples + 4 halfword header
*/
for (n = 0; n < FRAME_NUM; n++) {
audio->in[n].data = data + 4;
data += (4 + (audio->channel_mode ? 2048 : 1024));
MM_DBG("0x%8x\n", (int)(audio->in[n].data - 8));
}
return audrec_send_audrecqueue(audio, &cmd, sizeof(cmd));
}
static int audpcm_dsp_read_buffer(struct audio_in *audio, uint32_t read_cnt)
{
struct up_audrec_packet_ext_ptr cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.cmd_id = UP_AUDREC_PACKET_EXT_PTR;
cmd.audrec_up_curr_read_count_msw = read_cnt >> 16;
cmd.audrec_up_curr_read_count_lsw = read_cnt;
return audrec_send_bitstreamqueue(audio, &cmd, sizeof(cmd));
}
/* must be called with audio->lock held */
static int audpcm_in_enable(struct audio_in *audio)
{
if (audio->enabled)
return 0;
if (audpreproc_enable(audio->enc_id, &audpreproc_dsp_event, audio)) {
MM_ERR("msm_adsp_enable(audpreproc) failed\n");
return -ENODEV;
}
if (msm_adsp_enable(audio->audrec)) {
MM_ERR("msm_adsp_enable(audrec) failed\n");
audpreproc_disable(audio->enc_id, audio);
return -ENODEV;
}
audio->enabled = 1;
audpcm_in_enc_config(audio, 1);
return 0;
}
/* must be called with audio->lock held */
static int audpcm_in_disable(struct audio_in *audio)
{
if (audio->enabled) {
audio->enabled = 0;
audpcm_in_enc_config(audio, 0);
wake_up(&audio->wait);
wait_event_interruptible_timeout(audio->wait_enable,
audio->running == 0, 1*HZ);
msm_adsp_disable(audio->audrec);
audpreproc_disable(audio->enc_id, audio);
}
return 0;
}
static void audpcm_in_flush(struct audio_in *audio)
{
int i;
audio->dsp_cnt = 0;
audio->in_head = 0;
audio->in_tail = 0;
audio->in_count = 0;
for (i = 0; i < FRAME_NUM; i++) {
audio->in[i].size = 0;
audio->in[i].read = 0;
}
MM_DBG("in_bytes %d\n", atomic_read(&audio->in_bytes));
MM_DBG("in_samples %d\n", atomic_read(&audio->in_samples));
atomic_set(&audio->in_bytes, 0);
atomic_set(&audio->in_samples, 0);
}
/* ------------------- device --------------------- */
static long audpcm_in_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
struct audio_in *audio = file->private_data;
int rc = 0;
if (cmd == AUDIO_GET_STATS) {
struct msm_audio_stats stats;
stats.byte_count = atomic_read(&audio->in_bytes);
stats.sample_count = atomic_read(&audio->in_samples);
if (copy_to_user((void *) arg, &stats, sizeof(stats)))
return -EFAULT;
return rc;
}
mutex_lock(&audio->lock);
switch (cmd) {
case AUDIO_START: {
uint32_t freq;
/* Poll at 48KHz always */
freq = 48000;
MM_DBG("AUDIO_START\n");
rc = msm_snddev_request_freq(&freq, audio->enc_id,
SNDDEV_CAP_TX, AUDDEV_CLNT_ENC);
MM_DBG("sample rate configured %d sample rate requested %d\n",
freq, audio->samp_rate);
if (rc < 0) {
MM_DBG("sample rate can not be set, return code %d\n",\
rc);
msm_snddev_withdraw_freq(audio->enc_id,
SNDDEV_CAP_TX, AUDDEV_CLNT_ENC);
MM_DBG("msm_snddev_withdraw_freq\n");
break;
}
rc = audpcm_in_enable(audio);
if (!rc) {
rc =
wait_event_interruptible_timeout(audio->wait_enable,
audio->running != 0, 1*HZ);
MM_DBG("state %d rc = %d\n", audio->running, rc);
if (audio->running == 0)
rc = -ENODEV;
else
rc = 0;
}
break;
}
case AUDIO_STOP: {
rc = audpcm_in_disable(audio);
rc = msm_snddev_withdraw_freq(audio->enc_id,
SNDDEV_CAP_TX, AUDDEV_CLNT_ENC);
MM_DBG("msm_snddev_withdraw_freq\n");
audio->stopped = 1;
audio->abort = 0;
break;
}
case AUDIO_FLUSH: {
if (audio->stopped) {
/* Make sure we're stopped and we wake any threads
* that might be blocked holding the read_lock.
* While audio->stopped read threads will always
* exit immediately.
*/
wake_up(&audio->wait);
mutex_lock(&audio->read_lock);
audpcm_in_flush(audio);
mutex_unlock(&audio->read_lock);
}
break;
}
case AUDIO_SET_CONFIG: {
struct msm_audio_config cfg;
if (copy_from_user(&cfg, (void *) arg, sizeof(cfg))) {
rc = -EFAULT;
break;
}
if (cfg.channel_count == 1) {
cfg.channel_count = AUDREC_CMD_MODE_MONO;
} else if (cfg.channel_count == 2) {
cfg.channel_count = AUDREC_CMD_MODE_STEREO;
} else {
rc = -EINVAL;
break;
}
audio->samp_rate = cfg.sample_rate;
audio->channel_mode = cfg.channel_count;
audio->buffer_size =
audio->channel_mode ? STEREO_DATA_SIZE : \
MONO_DATA_SIZE;
break;
}
case AUDIO_GET_CONFIG: {
struct msm_audio_config cfg;
memset(&cfg, 0, sizeof(cfg));
cfg.buffer_size = audio->buffer_size;
cfg.buffer_count = FRAME_NUM;
cfg.sample_rate = audio->samp_rate;
if (audio->channel_mode == AUDREC_CMD_MODE_MONO)
cfg.channel_count = 1;
else
cfg.channel_count = 2;
if (copy_to_user((void *) arg, &cfg, sizeof(cfg)))
rc = -EFAULT;
break;
}
case AUDIO_GET_SESSION_ID: {
if (copy_to_user((void *) arg, &audio->enc_id,
sizeof(unsigned short))) {
rc = -EFAULT;
}
break;
}
default:
rc = -EINVAL;
}
mutex_unlock(&audio->lock);
return rc;
}
static ssize_t audpcm_in_read(struct file *file,
char __user *buf,
size_t count, loff_t *pos)
{
struct audio_in *audio = file->private_data;
unsigned long flags;
const char __user *start = buf;
void *data;
uint32_t index;
uint32_t size;
int rc = 0;
mutex_lock(&audio->read_lock);
while (count > 0) {
rc = wait_event_interruptible(
audio->wait, (audio->in_count > 0) || audio->stopped ||
audio->abort);
if (rc < 0)
break;
if (audio->stopped && !audio->in_count) {
MM_DBG("Driver in stop state, No more buffer to read");
rc = 0;/* End of File */
break;
}
if (audio->abort) {
rc = -EPERM; /* Not permitted due to abort */
break;
}
index = audio->in_tail;
data = (uint8_t *) audio->in[index].data;
size = audio->in[index].size;
if (count >= size) {
if (copy_to_user(buf, data, size)) {
rc = -EFAULT;
break;
}
spin_lock_irqsave(&audio->dsp_lock, flags);
if (index != audio->in_tail) {
/* overrun -- data is
* invalid and we need to retry */
spin_unlock_irqrestore(&audio->dsp_lock, flags);
continue;
}
audio->in[index].size = 0;
audio->in_tail = (audio->in_tail + 1) & (FRAME_NUM - 1);
audio->in_count--;
spin_unlock_irqrestore(&audio->dsp_lock, flags);
count -= size;
buf += size;
} else {
MM_ERR("short read\n");
break;
}
}
mutex_unlock(&audio->read_lock);
if (buf > start)
return buf - start;
return rc;
}
static ssize_t audpcm_in_write(struct file *file,
const char __user *buf,
size_t count, loff_t *pos)
{
return -EINVAL;
}
static int audpcm_in_release(struct inode *inode, struct file *file)
{
struct audio_in *audio = file->private_data;
mutex_lock(&audio->lock);
/* with draw frequency for session
incase not stopped the driver */
msm_snddev_withdraw_freq(audio->enc_id, SNDDEV_CAP_TX,
AUDDEV_CLNT_ENC);
auddev_unregister_evt_listner(AUDDEV_CLNT_ENC, audio->enc_id);
audpcm_in_disable(audio);
audpcm_in_flush(audio);
msm_adsp_put(audio->audrec);
audpreproc_aenc_free(audio->enc_id);
audio->audrec = NULL;
audio->opened = 0;
mutex_unlock(&audio->lock);
return 0;
}
static int audpcm_in_open(struct inode *inode, struct file *file)
{
struct audio_in *audio = &the_audio_in;
int rc;
int encid;
mutex_lock(&audio->lock);
if (audio->opened) {
rc = -EBUSY;
goto done;
}
/* Settings will be re-config at AUDIO_SET_CONFIG,
* but at least we need to have initial config
*/
audio->channel_mode = AUDREC_CMD_MODE_MONO;
audio->buffer_size = MONO_DATA_SIZE;
audio->samp_rate = 8000;
audio->enc_type = ENC_TYPE_WAV;
audio->source = INTERNAL_CODEC_TX_SOURCE_MIX_MASK;
encid = audpreproc_aenc_alloc(audio->enc_type, &audio->module_name,
&audio->queue_ids);
if (encid < 0) {
MM_ERR("No free encoder available\n");
rc = -ENODEV;
goto done;
}
audio->enc_id = encid;
rc = msm_adsp_get(audio->module_name, &audio->audrec,
&audrec_adsp_ops, audio);
if (rc) {
audpreproc_aenc_free(audio->enc_id);
goto done;
}
audio->stopped = 0;
audio->source = 0;
audio->abort = 0;
audpcm_in_flush(audio);
audio->device_events = AUDDEV_EVT_DEV_RDY | AUDDEV_EVT_DEV_RLS |
AUDDEV_EVT_FREQ_CHG;
rc = auddev_register_evt_listner(audio->device_events,
AUDDEV_CLNT_ENC, audio->enc_id,
pcm_in_listener, (void *) audio);
if (rc) {
MM_ERR("failed to register device event listener\n");
goto evt_error;
}
file->private_data = audio;
audio->opened = 1;
rc = 0;
done:
mutex_unlock(&audio->lock);
return rc;
evt_error:
msm_adsp_put(audio->audrec);
audpreproc_aenc_free(audio->enc_id);
mutex_unlock(&audio->lock);
return rc;
}
static const struct file_operations audio_in_fops = {
.owner = THIS_MODULE,
.open = audpcm_in_open,
.release = audpcm_in_release,
.read = audpcm_in_read,
.write = audpcm_in_write,
.unlocked_ioctl = audpcm_in_ioctl,
};
struct miscdevice audio_in_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "msm_pcm_in",
.fops = &audio_in_fops,
};
static int __init audpcm_in_init(void)
{
the_audio_in.data = dma_alloc_coherent(NULL, DMASZ,
&the_audio_in.phys, GFP_KERNEL);
MM_DBG("Memory addr = 0x%8x phy addr = 0x%8x ---- \n", \
(int) the_audio_in.data, (int) the_audio_in.phys);
if (!the_audio_in.data) {
MM_ERR("Unable to allocate DMA buffer\n");
return -ENOMEM;
}
mutex_init(&the_audio_in.lock);
mutex_init(&the_audio_in.read_lock);
spin_lock_init(&the_audio_in.dsp_lock);
spin_lock_init(&the_audio_in.dev_lock);
init_waitqueue_head(&the_audio_in.wait);
init_waitqueue_head(&the_audio_in.wait_enable);
return misc_register(&audio_in_misc);
}
device_initcall(audpcm_in_init);
| marcOcram/Acer-Liquid-MT-Kernel | arch/arm/mach-msm/qdsp5v2/audio_pcm_in.c | C | gpl-2.0 | 20,064 |
table, th, td {border: 1px solid black; border-collapse: collapse}
.right {text-align: right}
tr.even {background-color: #FFEEEE}
td.right {text-align: right}
a {color: #880000; text-decoration: none}
a:hover {background-color:#FFCCCC}
tr.click:hover {background-color:#FFCCCC}
img.right {float: right}
div.bar {background-color: #EEEEEE; width: 100%; padding: 10px; border: 1px solid black}
| PHOTOX/fuase | ase/ase/db/static/style.css | CSS | gpl-2.0 | 392 |
/**!
* The MIT License
*
* Copyright (c) 2010-2012 Google, Inc. http://angularjs.org
*
* 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.
*
* angular-google-maps
* https://github.com/nlaplante/angular-google-maps
*
* @author Nicolas Laplante https://plus.google.com/108189012221374960701
*/
(function () {
"use strict";
/*
* Utility functions
*/
/**
* Check if 2 floating point numbers are equal
*
* @see http://stackoverflow.com/a/588014
*/
function floatEqual (f1, f2) {
return (Math.abs(f1 - f2) < 0.000001);
}
/*
* Create the model in a self-contained class where map-specific logic is
* done. This model will be used in the directive.
*/
var MapModel = (function () {
var _defaults = {
zoom: 8,
draggable: false,
container: null
};
/**
*
*/
function PrivateMapModel(opts) {
var _instance = null,
_markers = [], // caches the instances of google.maps.Marker
_handlers = [], // event handlers
_windows = [], // InfoWindow objects
o = angular.extend({}, _defaults, opts),
that = this,
currentInfoWindow = null;
this.center = opts.center;
this.zoom = o.zoom;
this.draggable = o.draggable;
this.dragging = false;
this.selector = o.container;
this.markers = [];
this.options = o.options;
this.draw = function () {
if (that.center == null) {
// TODO log error
return;
}
if (_instance == null) {
// Create a new map instance
_instance = new google.maps.Map(that.selector, angular.extend(that.options, {
center: that.center,
zoom: that.zoom,
draggable: that.draggable,
mapTypeId : google.maps.MapTypeId.ROADMAP
}));
google.maps.event.addListener(_instance, "dragstart",
function () {
that.dragging = true;
}
);
google.maps.event.addListener(_instance, "idle",
function () {
that.dragging = false;
}
);
google.maps.event.addListener(_instance, "drag",
function () {
that.dragging = true;
}
);
google.maps.event.addListener(_instance, "zoom_changed",
function () {
that.zoom = _instance.getZoom();
that.center = _instance.getCenter();
}
);
google.maps.event.addListener(_instance, "center_changed",
function () {
that.center = _instance.getCenter();
}
);
// Attach additional event listeners if needed
if (_handlers.length) {
angular.forEach(_handlers, function (h, i) {
google.maps.event.addListener(_instance,
h.on, h.handler);
});
}
}
else {
// Refresh the existing instance
google.maps.event.trigger(_instance, "resize");
var instanceCenter = _instance.getCenter();
if (!floatEqual(instanceCenter.lat(), that.center.lat())
|| !floatEqual(instanceCenter.lng(), that.center.lng())) {
_instance.setCenter(that.center);
}
if (_instance.getZoom() != that.zoom) {
_instance.setZoom(that.zoom);
}
}
};
this.fit = function () {
if (_instance && _markers.length) {
var bounds = new google.maps.LatLngBounds();
angular.forEach(_markers, function (m, i) {
bounds.extend(m.getPosition());
});
_instance.fitBounds(bounds);
}
};
this.on = function(event, handler) {
_handlers.push({
"on": event,
"handler": handler
});
};
this.addMarker = function (lat, lng, icon, infoWindowContent, label, url,
thumbnail) {
if (that.findMarker(lat, lng) != null) {
return;
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: _instance,
icon: icon
});
if (label) {
}
if (url) {
}
if (infoWindowContent != null) {
var infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
});
google.maps.event.addListener(marker, 'click', function() {
if (currentInfoWindow != null) {
currentInfoWindow.close();
}
infoWindow.open(_instance, marker);
currentInfoWindow = infoWindow;
});
}
// Cache marker
_markers.unshift(marker);
// Cache instance of our marker for scope purposes
that.markers.unshift({
"lat": lat,
"lng": lng,
"draggable": false,
"icon": icon,
"infoWindowContent": infoWindowContent,
"label": label,
"url": url,
"thumbnail": thumbnail
});
// Return marker instance
return marker;
};
this.findMarker = function (lat, lng) {
for (var i = 0; i < _markers.length; i++) {
var pos = _markers[i].getPosition();
if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) {
return _markers[i];
}
}
return null;
};
this.findMarkerIndex = function (lat, lng) {
for (var i = 0; i < _markers.length; i++) {
var pos = _markers[i].getPosition();
if (floatEqual(pos.lat(), lat) && floatEqual(pos.lng(), lng)) {
return i;
}
}
return -1;
};
this.addInfoWindow = function (lat, lng, html) {
var win = new google.maps.InfoWindow({
content: html,
position: new google.maps.LatLng(lat, lng)
});
_windows.push(win);
return win;
};
this.hasMarker = function (lat, lng) {
return that.findMarker(lat, lng) !== null;
};
this.getMarkerInstances = function () {
return _markers;
};
this.removeMarkers = function (markerInstances) {
var s = this;
angular.forEach(markerInstances, function (v, i) {
var pos = v.getPosition(),
lat = pos.lat(),
lng = pos.lng(),
index = s.findMarkerIndex(lat, lng);
// Remove from local arrays
_markers.splice(index, 1);
s.markers.splice(index, 1);
// Remove from map
v.setMap(null);
});
};
}
// Done
return PrivateMapModel;
}());
// End model
// Start Angular directive
var googleMapsModule = angular.module("google-maps", []);
/**
* Map directive
*/
googleMapsModule.directive("googleMap", ["$log", "$timeout", "$filter", function ($log, $timeout,
$filter) {
var controller = function ($scope, $element) {
var _m = $scope.map;
self.addInfoWindow = function (lat, lng, content) {
_m.addInfoWindow(lat, lng, content);
};
};
controller.$inject = ['$scope', '$element'];
return {
restrict: "EC",
priority: 100,
transclude: true,
template: "<div class='angular-google-map' ng-transclude></div>",
replace: false,
scope: {
center: "=center", // required
markers: "=markers", // optional
latitude: "=latitude", // required
longitude: "=longitude", // required
zoom: "=zoom", // required
refresh: "&refresh", // optional
windows: "=windows" // optional"
},
controller: controller,
link: function (scope, element, attrs, ctrl) {
// Center property must be specified and provide lat &
// lng properties
if (!angular.isDefined(scope.center) ||
(!angular.isDefined(scope.center.lat) ||
!angular.isDefined(scope.center.lng))) {
$log.error("angular-google-maps: ould not find a valid center property");
return;
}
if (!angular.isDefined(scope.zoom)) {
$log.error("angular-google-maps: map zoom property not set");
return;
}
angular.element(element).addClass("angular-google-map");
// Parse options
var opts = {options: {}};
if (attrs.options) {
opts.options = angular.fromJson(attrs.options);
}
// Create our model
var _m = new MapModel(angular.extend(opts, {
container: element[0],
center: new google.maps.LatLng(scope.center.lat, scope.center.lng),
draggable: attrs.draggable == "true",
zoom: scope.zoom
}));
_m.on("drag", function () {
var c = _m.center;
$timeout(function () {
scope.$apply(function (s) {
scope.center.lat = c.lat();
scope.center.lng = c.lng();
});
});
});
_m.on("zoom_changed", function () {
if (scope.zoom != _m.zoom) {
$timeout(function () {
scope.$apply(function (s) {
scope.zoom = _m.zoom;
});
});
}
});
_m.on("center_changed", function () {
var c = _m.center;
$timeout(function () {
scope.$apply(function (s) {
if (!_m.dragging) {
scope.center.lat = c.lat();
scope.center.lng = c.lng();
}
});
});
});
if (attrs.markClick == "true") {
(function () {
var cm = null;
_m.on("click", function (e) {
if (cm == null) {
cm = {
latitude: e.latLng.lat(),
longitude: e.latLng.lng()
};
scope.markers.push(cm);
}
else {
cm.latitude = e.latLng.lat();
cm.longitude = e.latLng.lng();
}
$timeout(function () {
scope.latitude = cm.latitude;
scope.longitude = cm.longitude;
scope.$apply();
});
});
}());
}
// Put the map into the scope
scope.map = _m;
// Check if we need to refresh the map
if (angular.isUndefined(scope.refresh())) {
// No refresh property given; draw the map immediately
_m.draw();
}
else {
scope.$watch("refresh()", function (newValue, oldValue) {
if (newValue && !oldValue) {
_m.draw();
}
});
}
// Markers
scope.$watch("markers", function (newValue, oldValue) {
$timeout(function () {
angular.forEach(newValue, function (v, i) {
if (!_m.hasMarker(v.latitude, v.longitude)) {
_m.addMarker(v.latitude, v.longitude, v.icon, v.infoWindow);
}
});
// Clear orphaned markers
var orphaned = [];
angular.forEach(_m.getMarkerInstances(), function (v, i) {
// Check our scope if a marker with equal latitude and longitude.
// If not found, then that marker has been removed form the scope.
var pos = v.getPosition(),
lat = pos.lat(),
lng = pos.lng(),
found = false;
// Test against each marker in the scope
for (var si = 0; si < scope.markers.length; si++) {
var sm = scope.markers[si];
if (floatEqual(sm.latitude, lat) && floatEqual(sm.longitude, lng)) {
// Map marker is present in scope too, don't remove
found = true;
}
}
// Marker in map has not been found in scope. Remove.
if (!found) {
orphaned.push(v);
}
});
orphaned.length && _m.removeMarkers(orphaned);
// Fit map when there are more than one marker.
// This will change the map center coordinates
if (attrs.fit == "true" && newValue.length > 1) {
_m.fit();
}
});
}, true);
// Update map when center coordinates change
scope.$watch("center", function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
if (!_m.dragging) {
_m.center = new google.maps.LatLng(newValue.lat,
newValue.lng);
_m.draw();
}
}, true);
scope.$watch("zoom", function (newValue, oldValue) {
if (newValue === oldValue) {
return;
}
_m.zoom = newValue;
_m.draw();
});
}
};
}]);
}()); | HediMaiza/SmoothieParis | js/vendor/google-maps.js | JavaScript | gpl-2.0 | 15,335 |
<?php die("Access Denied"); ?>#x#s:4516:" 1448241693
<!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="zh-tw" lang="zh-tw">
<head>
<script type="text/javascript">
var siteurl='/';
var tmplurl='/templates/ja_mendozite/';
var isRTL = false;
</script>
<base href="http://www.zon.com.tw/zh/component/mailto/" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="generator" content="榮憶橡膠工業股份有限公司" />
<title>榮憶橡膠工業股份有限公司 | 榮憶橡膠工業股份有限公司</title>
<link href="http://www.zon.com.tw/zh/component/mailto/?link=5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4&template=ja_mendozite&tmpl=component" rel="canonical" />
<link rel="stylesheet" href="/t3-assets/css_9ce88.css" type="text/css" />
<link rel="stylesheet" href="/t3-assets/css_31cec.css" type="text/css" />
<script src="/en/?jat3action=gzip&jat3type=js&jat3file=t3-assets%2Fjs_7f13c.js" type="text/javascript"></script>
<script type="text/javascript">
function keepAlive() { var myAjax = new Request({method: "get", url: "index.php"}).send();} window.addEvent("domready", function(){ keepAlive.periodical(840000); });
</script>
<script type="text/javascript">
var akoption = {
"colorTable" : true ,
"opacityEffect" : true ,
"foldContent" : true ,
"fixingElement" : true ,
"smoothScroll" : false
} ;
var akconfig = new Object();
akconfig.root = 'http://www.zon.com.tw/' ;
akconfig.host = 'http://'+location.host+'/' ;
AsikartEasySet.init( akoption , akconfig );
</script>
<link href="/plugins/system/jat3/jat3/base-themes/default/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-60602086-1', 'auto');
ga('send', 'pageview');
</script>
<link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom-typo.css" type="text/css" />
<link rel="stylesheet" href="http://www.zon.com.tw/easyset/css/custom.css" type="text/css" />
</head>
<body id="bd" class="fs3 com_mailto contentpane">
<div id="system-message-container">
<div id="system-message">
</div>
</div>
<script type="text/javascript">
Joomla.submitbutton = function(pressbutton)
{
var form = document.getElementById('mailtoForm');
// do field validation
if (form.mailto.value == "" || form.from.value == "")
{
alert('請提供正確的電子郵件。');
return false;
}
form.submit();
}
</script>
<div id="mailto-window">
<h2>
推薦此連結給朋友。 </h2>
<div class="mailto-close">
<a href="javascript: void window.close()" title="關閉視窗">
<span>關閉視窗 </span></a>
</div>
<form action="http://www.zon.com.tw/index.php" id="mailtoForm" method="post">
<div class="formelm">
<label for="mailto_field">寄信給</label>
<input type="text" id="mailto_field" name="mailto" class="inputbox" size="25" value=""/>
</div>
<div class="formelm">
<label for="sender_field">
寄件者</label>
<input type="text" id="sender_field" name="sender" class="inputbox" value="" size="25" />
</div>
<div class="formelm">
<label for="from_field">
您的郵件</label>
<input type="text" id="from_field" name="from" class="inputbox" value="" size="25" />
</div>
<div class="formelm">
<label for="subject_field">
主旨</label>
<input type="text" id="subject_field" name="subject" class="inputbox" value="" size="25" />
</div>
<p>
<button class="button" onclick="return Joomla.submitbutton('send');">
送出 </button>
<button class="button" onclick="window.close();return false;">
取消 </button>
</p>
<input type="hidden" name="layout" value="default" />
<input type="hidden" name="option" value="com_mailto" />
<input type="hidden" name="task" value="send" />
<input type="hidden" name="tmpl" value="component" />
<input type="hidden" name="link" value="5b01b8f2ca3ca1e431fb7082348e60a75d09bcb4" />
<input type="hidden" name="3431db301dbcf490ccf76011c9360ad9" value="1" />
</form>
</div>
</body>
</html>"; | ForAEdesWeb/AEW32 | cache/t3_pages/e8efe7956197beb28b5e158ad88f292e-cache-t3_pages-160aa8f95d30404c7ac89ff054f766d9.php | PHP | gpl-2.0 | 4,524 |
<?php foreach ($content as $key => $value): ?>
<div class="product-item-viewed product-node-id-<?php print $key; ?>">
<?php print l($value['title'], $value['path']); ?>
<?php if (isset($value['image'])): ?>
<div class='image-viewed'><img src='<?php print $value['image']; ?>' /></div>
<?php endif; ?>
</div>
<?php endforeach; ?>
| Fant0m771/commerce | sites/all/modules/custom/last_viewed_products/templates/last_viewed_products.tpl.php | PHP | gpl-2.0 | 363 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LetsSolveIt.WebService.SmokeTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pioneer Hi-Bred")]
[assembly: AssemblyProduct("LetsSolveIt.WebService.SmokeTest")]
[assembly: AssemblyCopyright("Copyright © Pioneer Hi-Bred 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f01d6f18-3205-4e06-91be-4e20781b83c5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| jasonweibel/LetsSolveIt | LetsSolveIt.WebService.SmokeTest/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,470 |
package kieranvs.avatar.bending.earth;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import kieranvs.avatar.Protection;
import kieranvs.avatar.bending.Ability;
import kieranvs.avatar.bending.AsynchronousAbility;
import kieranvs.avatar.bukkit.BlockBukkit;
import kieranvs.avatar.bukkit.Location;
import kieranvs.avatar.bukkit.Vector;
import kieranvs.avatar.util.AvatarDamageSource;
import kieranvs.avatar.util.BendingUtils;
public class EarthStream extends AsynchronousAbility {
private long interval = 200L;
private long risetime = 600L;
private ConcurrentHashMap<BlockBukkit, Long> movedBlocks = new ConcurrentHashMap<BlockBukkit, Long>();
private Location origin;
private Location location;
private Vector direction;
private int range;
private long time;
private boolean finished = false;
public EarthStream(EntityLivingBase user, Location location, Vector direction, int range) {
super(user, 2000);
this.time = System.currentTimeMillis();
this.range = range;
this.origin = location.clone();
this.location = location.clone();
this.direction = direction.clone();
this.direction.setY(0);
this.direction.normalize();
this.location.add(this.direction);
}
@Override
public void update() {
for (BlockBukkit block : movedBlocks.keySet()) {
long time = movedBlocks.get(block).longValue();
if (System.currentTimeMillis() > time + risetime) {
Protection.trySetBlock(user.worldObj, Blocks.air, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(),
block.getRelative(BlockBukkit.UP).getZ());
movedBlocks.remove(block);
}
}
if (finished) {
if (movedBlocks.isEmpty()) {
destroy();
}
else {
return;
}
}
if (System.currentTimeMillis() - time >= interval) {
time = System.currentTimeMillis();
location.add(direction);
if (location.distance(origin) > range) {
finished = true;
return;
}
BlockBukkit block = this.location.getBlock();
if (isMoveable(block)) {
moveBlock(block);
}
if (isMoveable(block.getRelative(BlockBukkit.DOWN))) {
moveBlock(block.getRelative(BlockBukkit.DOWN));
location = block.getRelative(BlockBukkit.DOWN).getLocation();
return;
}
if (isMoveable(block.getRelative(BlockBukkit.UP))) {
moveBlock(block.getRelative(BlockBukkit.UP));
location = block.getRelative(BlockBukkit.UP).getLocation();
return;
}
else {
finished = true;
}
return;
}
}
public void moveBlock(BlockBukkit block) {
// block.getRelative(Block.UP).breakNaturally();
//block.getRelative(Block.UP).setType(block.getType());
//movedBlocks.put(block, System.currentTimeMillis());
//damageEntities(block.getLocation());
//BendingUtils.damageEntities(block.getLocation(), 3.5F, AvatarDamageSource.earthbending, 3);
Protection.trySetBlock(user.worldObj, Blocks.dirt, block.getRelative(BlockBukkit.UP).getX(), block.getRelative(BlockBukkit.UP).getY(),
block.getRelative(BlockBukkit.UP).getZ());
movedBlocks.put(block, System.currentTimeMillis());
}
public void damageEntities(Location loc) {
for (Object o : loc.getWorld().getLoadedEntityList()) {
if (o instanceof EntityLivingBase) {
EntityLivingBase e = (EntityLivingBase) o;
if (loc.distance(e) < 3.5) {
e.attackEntityFrom(AvatarDamageSource.earthbending, 3);
}
}
}
}
public static boolean isMoveable(BlockBukkit block) {
Block[] overwriteable = { Blocks.air, Blocks.sapling, Blocks.tallgrass, Blocks.deadbush, Blocks.yellow_flower, Blocks.red_flower, Blocks.brown_mushroom, Blocks.red_mushroom, Blocks.fire, Blocks.snow, Blocks.torch, Blocks.leaves, Blocks.cactus, Blocks.reeds, Blocks.web, Blocks.waterlily, Blocks.vine };
if (!Arrays.asList(overwriteable).contains(block.getRelative(BlockBukkit.UP).getType())) {
return false;
}
Block[] moveable = { Blocks.brick_block, Blocks.clay, Blocks.coal_ore, Blocks.cobblestone, Blocks.dirt, Blocks.grass, Blocks.gravel, Blocks.mossy_cobblestone, Blocks.mycelium, Blocks.nether_brick, Blocks.netherrack, Blocks.obsidian, Blocks.sand, Blocks.sandstone, Blocks.farmland, Blocks.soul_sand, Blocks.stone };
if (Arrays.asList(moveable).contains(block.getType())) {
return true;
}
return false;
}
}
| kieranvs/Blockbender | Blockbender/src/kieranvs/avatar/bending/earth/EarthStream.java | Java | gpl-2.0 | 4,514 |
#include <iostream>
#include <stdint.h>
#include <map>
#include <set>
#include "macros.h"
#include <assert.h>
using namespace std;
#include <fstream>
struct defsetcmp {
bool operator() (const pair<uint64_t, uint64_t> &l, const pair<uint64_t, uint64_t> &r) {
return (l.first < r.first || l.second < r.second);
}
};
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: ./parse file" << endl;
return(1);
}
ifstream inFile(argv[1]);
map<uint64_t, uint64_t> latestWrite;
typedef map<pair<uint64_t, uint64_t>, set<uint64_t>, defsetcmp> defsett;
defsett defset;
map<uint64_t, bool> localread;
map<uint64_t, bool> nonlocalread;
map<uint64_t, uint64_t> ins2tid;
map<uint64_t, map<uint64_t, bool> > has_read;
map<uint64_t, bool> follower;
while (inFile.good()) {
uint64_t ins, tid, rw, addr;
inFile >> ins >> tid >> rw >> addr;
if (ins == END && addr == END) {
latestWrite.clear();
ins2tid.clear();
has_read.clear();
} else if (rw == READ) {
ins2tid[ins] = tid;
//if there are no writes to current variable yet then continue
if (latestWrite.find(addr) == latestWrite.end()) {
continue;
}
uint64_t latestWriteIns = latestWrite[addr];
//defset
defset[make_pair(addr,ins)].insert(latestWriteIns);
//local non-local
bool isLocal = (tid == ins2tid[latestWriteIns]);
if (localread.find(ins) == localread.end()) {
localread[ins] = isLocal;
nonlocalread[ins] = !isLocal;
} else {
localread[ins] = localread[ins] && isLocal;
nonlocalread[ins] = nonlocalread[ins] && !isLocal;
}
//follower
if (has_read.find(addr) != has_read.end()
&& has_read[addr].find(tid) != has_read[addr].end()) {
if (follower.find(ins) != follower.end()) {
follower[ins] = follower[ins] && has_read[addr][tid];
} else {
follower[ins] = has_read[addr][tid];
}
}
has_read[addr][tid] = true;
} else {
assert(rw == WRITE);
ins2tid[ins] = tid;
latestWrite[addr] = ins;
if(has_read.find(addr) != has_read.end()) {
for(map<uint64_t, bool>::iterator titr = has_read[addr].begin();
titr != has_read[addr].end();
++titr) {
titr->second = false;
}
}
}
}
inFile.close();
//print defset
//variable read_ins_addr #writes write_ins_add0 ...
for (defsett::const_iterator defsetitr = defset.begin();
defsetitr != defset.end();
++defsetitr) {
cout << defsetitr->first.first << " " << defsetitr->first.second << " ";
cout << (defsetitr->second).size() << " ";
for (set<uint64_t>::const_iterator witr = (defsetitr->second).begin();
witr != (defsetitr->second).end();
++witr) {
cout << *witr << " ";
}
cout << endl;
}
//print local and non local
cout << "#local: " << endl;
for(map<uint64_t, bool>::const_iterator litr = localread.begin();
litr != localread.end();
++litr) {
if (litr->second) {
cout << litr->first << endl;
}
}
cout << "#nonlocal: " << endl;
for(map<uint64_t, bool>::const_iterator nlitr = nonlocalread.begin();
nlitr != nonlocalread.end();
++nlitr) {
if (nlitr->second) {
cout << nlitr->first << endl;
}
}
//print follower
cout << "#follower: " << endl;
for(map<uint64_t, bool>::const_iterator fitr = follower.begin();
fitr != follower.end();
++fitr) {
if (fitr->second) {
cout << fitr->first << endl;
}
}
return 0;
}
| sumanthsprabhu/atva_tool | parse.cpp | C++ | gpl-2.0 | 3,546 |
/*****************************************************************
Copyright (c) 1996-2000 the kicker authors. See file AUTHORS.
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 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.
******************************************************************/
#include <qdragobject.h>
#include <qstring.h>
#include <qstringlist.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kmimetype.h>
#include <klocale.h>
#include <kdesktopfile.h>
#include <kglobalsettings.h>
#include <kapplication.h>
#include <kurldrag.h>
#include <krecentdocument.h>
#include "recentdocsmenu.h"
K_EXPORT_KICKER_MENUEXT(recentdocs, RecentDocsMenu)
RecentDocsMenu::RecentDocsMenu(QWidget *parent, const char *name,
const QStringList &/*args*/)
: KPanelMenu(KRecentDocument::recentDocumentDirectory(), parent, name)
{
}
RecentDocsMenu::~RecentDocsMenu()
{
}
void RecentDocsMenu::initialize() {
if (initialized()) clear();
insertItem(SmallIconSet("history_clear"), i18n("Clear History"), this, SLOT(slotClearHistory()));
insertSeparator();
_fileList = KRecentDocument::recentDocuments();
if (_fileList.isEmpty()) {
insertItem(i18n("No Entries"), 0);
setItemEnabled(0, false);
return;
}
int id = 0;
char alreadyPresentInMenu;
QStringList previousEntries;
for (QStringList::ConstIterator it = _fileList.begin(); it != _fileList.end(); ++it) {
KDesktopFile f(*it, true /* read only */);
// Make sure this entry is not already present in the menu
alreadyPresentInMenu = 0;
for ( QStringList::Iterator previt = previousEntries.begin(); previt != previousEntries.end(); ++previt ) {
if (QString::localeAwareCompare(*previt, f.readName().replace('&', QString::fromAscii("&&") )) == 0) {
alreadyPresentInMenu = 1;
}
}
if (alreadyPresentInMenu == 0) {
// Add item to menu
insertItem(SmallIconSet(f.readIcon()), f.readName().replace('&', QString::fromAscii("&&") ), id++);
// Append to duplicate checking list
previousEntries.append(f.readName().replace('&', QString::fromAscii("&&") ));
}
}
setInitialized(true);
}
void RecentDocsMenu::slotClearHistory() {
KRecentDocument::clear();
reinitialize();
}
void RecentDocsMenu::slotExec(int id) {
if (id >= 0) {
kapp->propagateSessionManager();
KURL u;
u.setPath(_fileList[id]);
KDEDesktopMimeType::run(u, true);
}
}
void RecentDocsMenu::mousePressEvent(QMouseEvent* e) {
_mouseDown = e->pos();
QPopupMenu::mousePressEvent(e);
}
void RecentDocsMenu::mouseMoveEvent(QMouseEvent* e) {
KPanelMenu::mouseMoveEvent(e);
if (!(e->state() & LeftButton))
return;
if (!rect().contains(_mouseDown))
return;
int dragLength = (e->pos() - _mouseDown).manhattanLength();
if (dragLength <= KGlobalSettings::dndEventDelay())
return; // ignore it
int id = idAt(_mouseDown);
// Don't drag 'manual' items.
if (id < 0)
return;
KDesktopFile f(_fileList[id], true /* read only */);
KURL url ( f.readURL() );
if (url.isEmpty()) // What are we to do ?
return;
KURL::List lst;
lst.append(url);
KURLDrag* d = new KURLDrag(lst, this);
d->setPixmap(SmallIcon(f.readIcon()));
d->dragCopy();
close();
}
void RecentDocsMenu::slotAboutToShow()
{
reinitialize();
KPanelMenu::slotAboutToShow();
}
#include "recentdocsmenu.moc"
| iegor/kdebase | kicker/menuext/recentdocs/recentdocsmenu.cpp | C++ | gpl-2.0 | 4,232 |
/* linux/arch/arm/mach-s3c2410/mach-bast.c
*
* Copyright 2003-2008 Simtec Electronics
* Ben Dooks <[email protected]>
*
* http://www.simtec.co.uk/products/EB2410ITX/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/syscore_ops.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/dm9000.h>
#include <linux/ata_platform.h>
#include <linux/i2c.h>
#include <linux/io.h>
#include <linux/serial_8250.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <linux/platform_data/asoc-s3c24xx_simtec.h>
#include <linux/platform_data/hwmon-s3c.h>
#include <linux/platform_data/i2c-s3c2410.h>
#include <linux/platform_data/mtd-nand-s3c2410.h>
#include <net/ax88796.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach-types.h>
#include <mach/fb.h>
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-lcd.h>
#include <mach/regs-mem.h>
#include <plat/clock.h>
#include <plat/cpu.h>
#include <plat/cpu-freq.h>
#include <plat/devs.h>
#include <plat/gpio-cfg.h>
#include <plat/regs-serial.h>
#include "bast.h"
#include "common.h"
#include "simtec.h"
#define COPYRIGHT ", Copyright 2004-2008 Simtec Electronics"
/* macros for virtual address mods for the io space entries */
#define VA_C5(item) ((unsigned long)(item) + BAST_VAM_CS5)
#define VA_C4(item) ((unsigned long)(item) + BAST_VAM_CS4)
#define VA_C3(item) ((unsigned long)(item) + BAST_VAM_CS3)
#define VA_C2(item) ((unsigned long)(item) + BAST_VAM_CS2)
/* macros to modify the physical addresses for io space */
#define PA_CS2(item) (__phys_to_pfn((item) + S3C2410_CS2))
#define PA_CS3(item) (__phys_to_pfn((item) + S3C2410_CS3))
#define PA_CS4(item) (__phys_to_pfn((item) + S3C2410_CS4))
#define PA_CS5(item) (__phys_to_pfn((item) + S3C2410_CS5))
static struct map_desc bast_iodesc[] __initdata = {
/* ISA IO areas */
{
.virtual = (u32)S3C24XX_VA_ISA_BYTE,
.pfn = PA_CS2(BAST_PA_ISAIO),
.length = SZ_16M,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_WORD,
.pfn = PA_CS3(BAST_PA_ISAIO),
.length = SZ_16M,
.type = MT_DEVICE,
},
/* bast CPLD control registers, and external interrupt controls */
{
.virtual = (u32)BAST_VA_CTRL1,
.pfn = __phys_to_pfn(BAST_PA_CTRL1),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)BAST_VA_CTRL2,
.pfn = __phys_to_pfn(BAST_PA_CTRL2),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)BAST_VA_CTRL3,
.pfn = __phys_to_pfn(BAST_PA_CTRL3),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)BAST_VA_CTRL4,
.pfn = __phys_to_pfn(BAST_PA_CTRL4),
.length = SZ_1M,
.type = MT_DEVICE,
},
/* PC104 IRQ mux */
{
.virtual = (u32)BAST_VA_PC104_IRQREQ,
.pfn = __phys_to_pfn(BAST_PA_PC104_IRQREQ),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)BAST_VA_PC104_IRQRAW,
.pfn = __phys_to_pfn(BAST_PA_PC104_IRQRAW),
.length = SZ_1M,
.type = MT_DEVICE,
}, {
.virtual = (u32)BAST_VA_PC104_IRQMASK,
.pfn = __phys_to_pfn(BAST_PA_PC104_IRQMASK),
.length = SZ_1M,
.type = MT_DEVICE,
},
/* peripheral space... one for each of fast/slow/byte/16bit */
/* note, ide is only decoded in word space, even though some registers
* are only 8bit */
/* slow, byte */
{ VA_C2(BAST_VA_ISAIO), PA_CS2(BAST_PA_ISAIO), SZ_16M, MT_DEVICE },
{ VA_C2(BAST_VA_ISAMEM), PA_CS2(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE },
{ VA_C2(BAST_VA_SUPERIO), PA_CS2(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE },
/* slow, word */
{ VA_C3(BAST_VA_ISAIO), PA_CS3(BAST_PA_ISAIO), SZ_16M, MT_DEVICE },
{ VA_C3(BAST_VA_ISAMEM), PA_CS3(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE },
{ VA_C3(BAST_VA_SUPERIO), PA_CS3(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE },
/* fast, byte */
{ VA_C4(BAST_VA_ISAIO), PA_CS4(BAST_PA_ISAIO), SZ_16M, MT_DEVICE },
{ VA_C4(BAST_VA_ISAMEM), PA_CS4(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE },
{ VA_C4(BAST_VA_SUPERIO), PA_CS4(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE },
/* fast, word */
{ VA_C5(BAST_VA_ISAIO), PA_CS5(BAST_PA_ISAIO), SZ_16M, MT_DEVICE },
{ VA_C5(BAST_VA_ISAMEM), PA_CS5(BAST_PA_ISAMEM), SZ_16M, MT_DEVICE },
{ VA_C5(BAST_VA_SUPERIO), PA_CS5(BAST_PA_SUPERIO), SZ_1M, MT_DEVICE },
};
#define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg bast_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
/* port 2 is not actually used */
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
/* NAND Flash on BAST board */
#ifdef CONFIG_PM
static int bast_pm_suspend(void)
{
/* ensure that an nRESET is not generated on resume. */
gpio_direction_output(S3C2410_GPA(21), 1);
return 0;
}
static void bast_pm_resume(void)
{
s3c_gpio_cfgpin(S3C2410_GPA(21), S3C2410_GPA21_nRSTOUT);
}
#else
#define bast_pm_suspend NULL
#define bast_pm_resume NULL
#endif
static struct syscore_ops bast_pm_syscore_ops = {
.suspend = bast_pm_suspend,
.resume = bast_pm_resume,
};
static int smartmedia_map[] = { 0 };
static int chip0_map[] = { 1 };
static int chip1_map[] = { 2 };
static int chip2_map[] = { 3 };
static struct mtd_partition __initdata bast_default_nand_part[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_16K,
.offset = 0,
},
[1] = {
.name = "/boot",
.size = SZ_4M - SZ_16K,
.offset = SZ_16K,
},
[2] = {
.name = "user",
.offset = SZ_4M,
.size = MTDPART_SIZ_FULL,
}
};
/* the bast has 4 selectable slots for nand-flash, the three
* on-board chip areas, as well as the external SmartMedia
* slot.
*
* Note, there is no current hot-plug support for the SmartMedia
* socket.
*/
static struct s3c2410_nand_set __initdata bast_nand_sets[] = {
[0] = {
.name = "SmartMedia",
.nr_chips = 1,
.nr_map = smartmedia_map,
.options = NAND_SCAN_SILENT_NODEV,
.nr_partitions = ARRAY_SIZE(bast_default_nand_part),
.partitions = bast_default_nand_part,
},
[1] = {
.name = "chip0",
.nr_chips = 1,
.nr_map = chip0_map,
.nr_partitions = ARRAY_SIZE(bast_default_nand_part),
.partitions = bast_default_nand_part,
},
[2] = {
.name = "chip1",
.nr_chips = 1,
.nr_map = chip1_map,
.options = NAND_SCAN_SILENT_NODEV,
.nr_partitions = ARRAY_SIZE(bast_default_nand_part),
.partitions = bast_default_nand_part,
},
[3] = {
.name = "chip2",
.nr_chips = 1,
.nr_map = chip2_map,
.options = NAND_SCAN_SILENT_NODEV,
.nr_partitions = ARRAY_SIZE(bast_default_nand_part),
.partitions = bast_default_nand_part,
}
};
static void bast_nand_select(struct s3c2410_nand_set *set, int slot)
{
unsigned int tmp;
slot = set->nr_map[slot] & 3;
pr_debug("bast_nand: selecting slot %d (set %p,%p)\n",
slot, set, set->nr_map);
tmp = __raw_readb(BAST_VA_CTRL2);
tmp &= BAST_CPLD_CTLR2_IDERST;
tmp |= slot;
tmp |= BAST_CPLD_CTRL2_WNAND;
pr_debug("bast_nand: ctrl2 now %02x\n", tmp);
__raw_writeb(tmp, BAST_VA_CTRL2);
}
static struct s3c2410_platform_nand __initdata bast_nand_info = {
.tacls = 30,
.twrph0 = 60,
.twrph1 = 60,
.nr_sets = ARRAY_SIZE(bast_nand_sets),
.sets = bast_nand_sets,
.select_chip = bast_nand_select,
};
/* DM9000 */
static struct resource bast_dm9k_resource[] = {
[0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000, 4),
[1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_DM9000 + 0x40, 0x40),
[2] = DEFINE_RES_NAMED(BAST_IRQ_DM9000 , 1, NULL, IORESOURCE_IRQ \
| IORESOURCE_IRQ_HIGHLEVEL),
};
/* for the moment we limit ourselves to 16bit IO until some
* better IO routines can be written and tested
*/
static struct dm9000_plat_data bast_dm9k_platdata = {
.flags = DM9000_PLATF_16BITONLY,
};
static struct platform_device bast_device_dm9k = {
.name = "dm9000",
.id = 0,
.num_resources = ARRAY_SIZE(bast_dm9k_resource),
.resource = bast_dm9k_resource,
.dev = {
.platform_data = &bast_dm9k_platdata,
}
};
/* serial devices */
#define SERIAL_BASE (S3C2410_CS2 + BAST_PA_SUPERIO)
#define SERIAL_FLAGS (UPF_BOOT_AUTOCONF | UPF_IOREMAP | UPF_SHARE_IRQ)
#define SERIAL_CLK (1843200)
static struct plat_serial8250_port bast_sio_data[] = {
[0] = {
.mapbase = SERIAL_BASE + 0x2f8,
.irq = BAST_IRQ_PCSERIAL1,
.flags = SERIAL_FLAGS,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = SERIAL_CLK,
},
[1] = {
.mapbase = SERIAL_BASE + 0x3f8,
.irq = BAST_IRQ_PCSERIAL2,
.flags = SERIAL_FLAGS,
.iotype = UPIO_MEM,
.regshift = 0,
.uartclk = SERIAL_CLK,
},
{ }
};
static struct platform_device bast_sio = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = &bast_sio_data,
},
};
/* we have devices on the bus which cannot work much over the
* standard 100KHz i2c bus frequency
*/
static struct s3c2410_platform_i2c __initdata bast_i2c_info = {
.flags = 0,
.slave_addr = 0x10,
.frequency = 100*1000,
};
/* Asix AX88796 10/100 ethernet controller */
static struct ax_plat_data bast_asix_platdata = {
.flags = AXFLG_MAC_FROMDEV,
.wordlength = 2,
.dcr_val = 0x48,
.rcr_val = 0x40,
};
static struct resource bast_asix_resource[] = {
[0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET, 0x18 * 0x20),
[1] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x1f * 0x20), 1),
[2] = DEFINE_RES_IRQ(BAST_IRQ_ASIX),
};
static struct platform_device bast_device_asix = {
.name = "ax88796",
.id = 0,
.num_resources = ARRAY_SIZE(bast_asix_resource),
.resource = bast_asix_resource,
.dev = {
.platform_data = &bast_asix_platdata
}
};
/* Asix AX88796 10/100 ethernet controller parallel port */
static struct resource bast_asixpp_resource[] = {
[0] = DEFINE_RES_MEM(S3C2410_CS5 + BAST_PA_ASIXNET + (0x18 * 0x20), \
0x30 * 0x20),
};
static struct platform_device bast_device_axpp = {
.name = "ax88796-pp",
.id = 0,
.num_resources = ARRAY_SIZE(bast_asixpp_resource),
.resource = bast_asixpp_resource,
};
/* LCD/VGA controller */
static struct s3c2410fb_display __initdata bast_lcd_info[] = {
{
.type = S3C2410_LCDCON1_TFT,
.width = 640,
.height = 480,
.pixclock = 33333,
.xres = 640,
.yres = 480,
.bpp = 4,
.left_margin = 40,
.right_margin = 20,
.hsync_len = 88,
.upper_margin = 30,
.lower_margin = 32,
.vsync_len = 3,
.lcdcon5 = 0x00014b02,
},
{
.type = S3C2410_LCDCON1_TFT,
.width = 640,
.height = 480,
.pixclock = 33333,
.xres = 640,
.yres = 480,
.bpp = 8,
.left_margin = 40,
.right_margin = 20,
.hsync_len = 88,
.upper_margin = 30,
.lower_margin = 32,
.vsync_len = 3,
.lcdcon5 = 0x00014b02,
},
{
.type = S3C2410_LCDCON1_TFT,
.width = 640,
.height = 480,
.pixclock = 33333,
.xres = 640,
.yres = 480,
.bpp = 16,
.left_margin = 40,
.right_margin = 20,
.hsync_len = 88,
.upper_margin = 30,
.lower_margin = 32,
.vsync_len = 3,
.lcdcon5 = 0x00014b02,
},
};
/* LCD/VGA controller */
static struct s3c2410fb_mach_info __initdata bast_fb_info = {
.displays = bast_lcd_info,
.num_displays = ARRAY_SIZE(bast_lcd_info),
.default_display = 1,
};
/* I2C devices fitted. */
static struct i2c_board_info bast_i2c_devs[] __initdata = {
{
I2C_BOARD_INFO("tlv320aic23", 0x1a),
}, {
I2C_BOARD_INFO("simtec-pmu", 0x6b),
}, {
I2C_BOARD_INFO("ch7013", 0x75),
},
};
static struct s3c_hwmon_pdata bast_hwmon_info = {
/* LCD contrast (0-6.6V) */
.in[0] = &(struct s3c_hwmon_chcfg) {
.name = "lcd-contrast",
.mult = 3300,
.div = 512,
},
/* LED current feedback */
.in[1] = &(struct s3c_hwmon_chcfg) {
.name = "led-feedback",
.mult = 3300,
.div = 1024,
},
/* LCD feedback (0-6.6V) */
.in[2] = &(struct s3c_hwmon_chcfg) {
.name = "lcd-feedback",
.mult = 3300,
.div = 512,
},
/* Vcore (1.8-2.0V), Vref 3.3V */
.in[3] = &(struct s3c_hwmon_chcfg) {
.name = "vcore",
.mult = 3300,
.div = 1024,
},
};
/* Standard BAST devices */
// cat /sys/devices/platform/s3c24xx-adc/s3c-hwmon/in_0
static struct platform_device *bast_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_rtc,
&s3c_device_nand,
&s3c_device_adc,
&s3c_device_hwmon,
&bast_device_dm9k,
&bast_device_asix,
&bast_device_axpp,
&bast_sio,
};
static struct clk *bast_clocks[] __initdata = {
&s3c24xx_dclk0,
&s3c24xx_dclk1,
&s3c24xx_clkout0,
&s3c24xx_clkout1,
&s3c24xx_uclk,
};
static struct s3c_cpufreq_board __initdata bast_cpufreq = {
.refresh = 7800, /* 7.8usec */
.auto_io = 1,
.need_io = 1,
};
static struct s3c24xx_audio_simtec_pdata __initdata bast_audio = {
.have_mic = 1,
.have_lout = 1,
};
static void __init bast_map_io(void)
{
/* initialise the clocks */
s3c24xx_dclk0.parent = &clk_upll;
s3c24xx_dclk0.rate = 12*1000*1000;
s3c24xx_dclk1.parent = &clk_upll;
s3c24xx_dclk1.rate = 24*1000*1000;
s3c24xx_clkout0.parent = &s3c24xx_dclk0;
s3c24xx_clkout1.parent = &s3c24xx_dclk1;
s3c24xx_uclk.parent = &s3c24xx_clkout1;
s3c24xx_register_clocks(bast_clocks, ARRAY_SIZE(bast_clocks));
s3c_hwmon_set_platdata(&bast_hwmon_info);
s3c24xx_init_io(bast_iodesc, ARRAY_SIZE(bast_iodesc));
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(bast_uartcfgs, ARRAY_SIZE(bast_uartcfgs));
}
static void __init bast_init(void)
{
register_syscore_ops(&bast_pm_syscore_ops);
s3c_i2c0_set_platdata(&bast_i2c_info);
s3c_nand_set_platdata(&bast_nand_info);
s3c24xx_fb_set_platdata(&bast_fb_info);
platform_add_devices(bast_devices, ARRAY_SIZE(bast_devices));
i2c_register_board_info(0, bast_i2c_devs,
ARRAY_SIZE(bast_i2c_devs));
usb_simtec_init();
nor_simtec_init();
simtec_audio_add(NULL, true, &bast_audio);
WARN_ON(gpio_request(S3C2410_GPA(21), "bast nreset"));
s3c_cpufreq_setboard(&bast_cpufreq);
}
MACHINE_START(BAST, "Simtec-BAST")
/* Maintainer: Ben Dooks <[email protected]> */
.atag_offset = 0x100,
.map_io = bast_map_io,
.init_irq = s3c24xx_init_irq,
.init_machine = bast_init,
.init_time = s3c24xx_timer_init,
.restart = s3c2410_restart,
MACHINE_END
| Oleh-Kravchenko/asusp535 | arch/arm/mach-s3c24xx/mach-bast.c | C | gpl-2.0 | 14,795 |
# Portions Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# match.py - filename matching
#
# Copyright 2008, 2009 Matt Mackall <[email protected]> and others
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function
import copy
import os
import re
from bindings import pathmatcher
from . import error, pathutil, pycompat, util
from .i18n import _
from .pycompat import decodeutf8
allpatternkinds = (
"re",
"glob",
"path",
"relglob",
"relpath",
"relre",
"listfile",
"listfile0",
"set",
"include",
"subinclude",
"rootfilesin",
)
cwdrelativepatternkinds = ("relpath", "glob")
propertycache = util.propertycache
def _rematcher(regex):
"""compile the regexp with the best available regexp engine and return a
matcher function"""
m = util.re.compile(regex)
try:
# slightly faster, provided by facebook's re2 bindings
return m.test_match
except AttributeError:
return m.match
def _expandsets(kindpats, ctx):
"""Returns the kindpats list with the 'set' patterns expanded."""
fset = set()
other = []
for kind, pat, source in kindpats:
if kind == "set":
if not ctx:
raise error.ProgrammingError("fileset expression with no " "context")
s = ctx.getfileset(pat)
fset.update(s)
continue
other.append((kind, pat, source))
return fset, other
def _expandsubinclude(kindpats, root):
"""Returns the list of subinclude matcher args and the kindpats without the
subincludes in it."""
relmatchers = []
other = []
for kind, pat, source in kindpats:
if kind == "subinclude":
sourceroot = pathutil.dirname(util.normpath(source))
pat = util.pconvert(pat)
path = pathutil.join(sourceroot, pat)
newroot = pathutil.dirname(path)
matcherargs = (newroot, "", [], ["include:%s" % path])
prefix = pathutil.canonpath(root, root, newroot)
if prefix:
prefix += "/"
relmatchers.append((prefix, matcherargs))
else:
other.append((kind, pat, source))
return relmatchers, other
def _kindpatsalwaysmatch(kindpats):
""" "Checks whether the kindspats match everything, as e.g.
'relpath:.' does.
"""
for kind, pat, source in kindpats:
# TODO: update me?
if pat != "" or kind not in ["relpath", "glob"]:
return False
return True
def match(
root,
cwd,
patterns=None,
include=None,
exclude=None,
default="glob",
exact=False,
auditor=None,
ctx=None,
warn=None,
badfn=None,
icasefs=False,
):
"""build an object to match a set of file patterns
arguments:
root - the canonical root of the tree you're matching against
cwd - the current working directory, if relevant
patterns - patterns to find
include - patterns to include (unless they are excluded)
exclude - patterns to exclude (even if they are included)
default - if a pattern in patterns has no explicit type, assume this one
exact - patterns are actually filenames (include/exclude still apply)
warn - optional function used for printing warnings
badfn - optional bad() callback for this matcher instead of the default
icasefs - make a matcher for wdir on case insensitive filesystems, which
normalizes the given patterns to the case in the filesystem
a pattern is one of:
'glob:<glob>' - a glob relative to cwd
're:<regexp>' - a regular expression
'path:<path>' - a path relative to repository root, which is matched
recursively
'rootfilesin:<path>' - a path relative to repository root, which is
matched non-recursively (will not match subdirectories)
'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs)
'relpath:<path>' - a path relative to cwd
'relre:<regexp>' - a regexp that needn't match the start of a name
'set:<fileset>' - a fileset expression
'include:<path>' - a file of patterns to read and include
'subinclude:<path>' - a file of patterns to match against files under
the same directory
'<something>' - a pattern of the specified default type
"""
if auditor is None:
auditor = pathutil.pathauditor(root)
normalize = _donormalize
if icasefs:
if exact:
raise error.ProgrammingError(
"a case-insensitive exact matcher " "doesn't make sense"
)
dirstate = ctx.repo().dirstate
dsnormalize = dirstate.normalize
def normalize(patterns, default, root, cwd, auditor, warn):
kp = _donormalize(patterns, default, root, cwd, auditor, warn)
kindpats = []
for kind, pats, source in kp:
if kind not in ("re", "relre"): # regex can't be normalized
p = pats
pats = dsnormalize(pats)
# Preserve the original to handle a case only rename.
if p != pats and p in dirstate:
kindpats.append((kind, p, source))
kindpats.append((kind, pats, source))
return kindpats
if exact:
m = exactmatcher(root, cwd, patterns, badfn)
elif patterns:
kindpats = normalize(patterns, default, root, cwd, auditor, warn)
if _kindpatsalwaysmatch(kindpats):
m = alwaysmatcher(root, cwd, badfn, relativeuipath=True)
else:
m = patternmatcher(root, cwd, kindpats, ctx=ctx, badfn=badfn)
else:
# It's a little strange that no patterns means to match everything.
# Consider changing this to match nothing (probably using nevermatcher).
m = alwaysmatcher(root, cwd, badfn)
if include:
kindpats = normalize(include, "glob", root, cwd, auditor, warn)
im = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None)
m = intersectmatchers(m, im)
if exclude:
kindpats = normalize(exclude, "glob", root, cwd, auditor, warn)
em = includematcher(root, cwd, kindpats, ctx=ctx, badfn=None)
m = differencematcher(m, em)
return m
def exact(root, cwd, files, badfn=None):
return exactmatcher(root, cwd, files, badfn=badfn)
def always(root, cwd):
return alwaysmatcher(root, cwd)
def never(root, cwd):
return nevermatcher(root, cwd)
def union(matches, root, cwd):
"""Union a list of matchers.
If the list is empty, return nevermatcher.
If the list only contains one non-None value, return that matcher.
Otherwise return a union matcher.
"""
matches = list(filter(None, matches))
if len(matches) == 0:
return nevermatcher(root, cwd)
elif len(matches) == 1:
return matches[0]
else:
return unionmatcher(matches)
def badmatch(match, badfn):
"""Make a copy of the given matcher, replacing its bad method with the given
one.
"""
m = copy.copy(match)
m.bad = badfn
return m
def _donormalize(patterns, default, root, cwd, auditor, warn):
"""Convert 'kind:pat' from the patterns list to tuples with kind and
normalized and rooted patterns and with listfiles expanded."""
kindpats = []
for kind, pat in [_patsplit(p, default) for p in patterns]:
if kind in cwdrelativepatternkinds:
pat = pathutil.canonpath(root, cwd, pat, auditor)
elif kind in ("relglob", "path", "rootfilesin"):
pat = util.normpath(pat)
elif kind in ("listfile", "listfile0"):
try:
files = decodeutf8(util.readfile(pat))
if kind == "listfile0":
files = files.split("\0")
else:
files = files.splitlines()
files = [f for f in files if f]
except EnvironmentError:
raise error.Abort(_("unable to read file list (%s)") % pat)
for k, p, source in _donormalize(files, default, root, cwd, auditor, warn):
kindpats.append((k, p, pat))
continue
elif kind == "include":
try:
fullpath = os.path.join(root, util.localpath(pat))
includepats = readpatternfile(fullpath, warn)
for k, p, source in _donormalize(
includepats, default, root, cwd, auditor, warn
):
kindpats.append((k, p, source or pat))
except error.Abort as inst:
raise error.Abort("%s: %s" % (pat, inst[0]))
except IOError as inst:
if warn:
warn(
_("skipping unreadable pattern file '%s': %s\n")
% (pat, inst.strerror)
)
continue
# else: re or relre - which cannot be normalized
kindpats.append((kind, pat, ""))
return kindpats
def _testrefastpath(repat):
"""Test if a re pattern can use fast path.
That is, for every "$A/$B" path the pattern matches, "$A" must also be
matched,
Return True if we're sure it is. Return False otherwise.
"""
# XXX: It's very hard to implement this. These are what need to be
# supported in production and tests. Very hacky. But we plan to get rid
# of re matchers eventually.
# Rules like "(?!experimental/)"
if repat.startswith("(?!") and repat.endswith(")") and repat.count(")") == 1:
return True
# Rules used in doctest
if repat == "(i|j)$":
return True
return False
def _globpatsplit(pat):
"""Split a glob pattern. Return a list.
A naive version is "path.split("/")". This function handles more cases, like
"{*,{a,b}*/*}".
>>> _globpatsplit("*/**/x/{a,b/c}")
['*', '**', 'x', '{a,b/c}']
"""
result = []
buf = ""
parentheses = 0
for ch in pat:
if ch == "{":
parentheses += 1
elif ch == "}":
parentheses -= 1
if parentheses == 0 and ch == "/":
if buf:
result.append(buf)
buf = ""
else:
buf += ch
if buf:
result.append(buf)
return result
class _tree(dict):
"""A tree intended to answer "visitdir" questions with more efficient
answers (ex. return "all" or False if possible).
"""
def __init__(self, *args, **kwargs):
# If True, avoid entering subdirectories, and match everything recursively,
# unconditionally.
self.matchrecursive = False
# If True, avoid entering subdirectories, and return "unsure" for
# everything. This is set to True when complex re patterns (potentially
# including "/") are used.
self.unsurerecursive = False
# Patterns for matching paths in this directory.
self._kindpats = []
# Glob patterns used to match parent directories of another glob
# pattern.
self._globdirpats = []
super(_tree, self).__init__(*args, **kwargs)
def insert(self, path, matchrecursive=True, globpats=None, repats=None):
"""Insert a directory path to this tree.
If matchrecursive is True, mark the directory as unconditionally
include files and subdirs recursively.
If globpats or repats are specified, append them to the patterns being
applied at this directory. The tricky part is those patterns can match
"x/y/z" and visit("x"), visit("x/y") need to return True, while we
still want visit("x/a") to return False.
"""
if path == "":
self.matchrecursive |= matchrecursive
if globpats:
# Need to match parent directories too.
for pat in globpats:
components = _globpatsplit(pat)
parentpat = ""
for comp in components:
if parentpat:
parentpat += "/"
parentpat += comp
if "/" in comp:
# Giving up - fallback to slow paths.
self.unsurerecursive = True
self._globdirpats.append(parentpat)
if any("**" in p for p in globpats):
# Giving up - "**" matches paths including "/"
self.unsurerecursive = True
self._kindpats += [("glob", pat, "") for pat in globpats]
if repats:
if not all(map(_testrefastpath, repats)):
# Giving up - fallback to slow paths.
self.unsurerecursive = True
self._kindpats += [("re", pat, "") for pat in repats]
return
subdir, rest = self._split(path)
self.setdefault(subdir, _tree()).insert(rest, matchrecursive, globpats, repats)
def visitdir(self, path):
"""Similar to matcher.visitdir"""
path = normalizerootdir(path, "visitdir")
if self.matchrecursive:
return "all"
elif self.unsurerecursive:
return True
elif path == "":
return True
if self._kindpats and self._compiledpats(path):
# XXX: This is incorrect. But re patterns are already used in
# production. We should kill them!
# Need to test "if every string starting with 'path' matches".
# Obviously it's impossible to test *every* string with the
# standard regex API, therefore pick a random strange path to test
# it approximately.
if self._compiledpats("%s/*/_/-/0/*" % path):
return "all"
else:
return True
if self._globdirpats and self._compileddirpats(path):
return True
subdir, rest = self._split(path)
subtree = self.get(subdir)
if subtree is None:
return False
else:
return subtree.visitdir(rest)
@util.propertycache
def _compiledpats(self):
pat, matchfunc = _buildregexmatch(self._kindpats, "")
return matchfunc
@util.propertycache
def _compileddirpats(self):
pat, matchfunc = _buildregexmatch(
[("glob", p, "") for p in self._globdirpats], "$"
)
return matchfunc
def _split(self, path):
if "/" in path:
subdir, rest = path.split("/", 1)
else:
subdir, rest = path, ""
if not subdir:
raise error.ProgrammingError("path cannot be absolute")
return subdir, rest
def _remainingpats(pat, prefix):
"""list of patterns with prefix stripped
>>> _remainingpats("a/b/c", "")
['a/b/c']
>>> _remainingpats("a/b/c", "a")
['b/c']
>>> _remainingpats("a/b/c", "a/b")
['c']
>>> _remainingpats("a/b/c", "a/b/c")
[]
>>> _remainingpats("", "")
[]
"""
if prefix:
if prefix == pat:
return []
else:
assert pat[len(prefix)] == "/"
return [pat[len(prefix) + 1 :]]
else:
if pat:
return [pat]
else:
return []
def _buildvisitdir(kindpats):
"""Try to build an efficient visitdir function
Return a visitdir function if it's built. Otherwise return None
if there are unsupported patterns.
>>> _buildvisitdir([('include', 'foo', '')])
>>> _buildvisitdir([('relglob', 'foo', '')])
>>> t = _buildvisitdir([
... ('glob', 'a/b', ''),
... ('glob', 'c/*.d', ''),
... ('glob', 'e/**/*.c', ''),
... ('re', '^f/(?!g)', ''), # no "$", only match prefix
... ('re', '^h/(i|j)$', ''),
... ('glob', 'i/a*/b*/c*', ''),
... ('glob', 'i/a5/b7/d', ''),
... ('glob', 'j/**.c', ''),
... ])
>>> t('a')
True
>>> t('a/b')
'all'
>>> t('a/b/c')
'all'
>>> t('c')
True
>>> t('c/d')
False
>>> t('c/rc.d')
'all'
>>> t('c/rc.d/foo')
'all'
>>> t('e')
True
>>> t('e/a')
True
>>> t('e/a/b.c')
True
>>> t('e/a/b.d')
True
>>> t('f')
True
>>> t('f/g')
False
>>> t('f/g2')
False
>>> t('f/g/a')
False
>>> t('f/h')
'all'
>>> t('f/h/i')
'all'
>>> t('h/i')
True
>>> t('h/i/k')
False
>>> t('h/k')
False
>>> t('i')
True
>>> t('i/a1')
True
>>> t('i/b2')
False
>>> t('i/a/b2/c3')
'all'
>>> t('i/a/b2/d4')
False
>>> t('i/a5/b7/d')
'all'
>>> t('j/x/y')
True
>>> t('z')
False
"""
tree = _tree()
for kind, pat, _source in kindpats:
if kind == "glob":
components = []
for p in pat.split("/"):
if "[" in p or "{" in p or "*" in p or "?" in p:
break
components.append(p)
prefix = "/".join(components)
matchrecursive = prefix == pat
tree.insert(
prefix,
matchrecursive=matchrecursive,
globpats=_remainingpats(pat, prefix),
)
elif kind == "re":
# Still try to get a plain prefix from the regular expression so we
# can still have fast paths.
if pat.startswith("^"):
# "re" already matches from the beginning, unlike "relre"
pat = pat[1:]
components = []
for p in pat.split("/"):
if re.escape(p) != p:
# contains special characters
break
components.append(p)
prefix = "/".join(components)
tree.insert(
prefix, matchrecursive=False, repats=_remainingpats(pat, prefix)
)
else:
# Unsupported kind
return None
return tree.visitdir
class basematcher(object):
def __init__(self, root, cwd, badfn=None, relativeuipath=True):
self._root = root
self._cwd = cwd
if badfn is not None:
self.bad = badfn
self._relativeuipath = relativeuipath
def __repr__(self):
return "<%s>" % self.__class__.__name__
def __call__(self, fn):
return self.matchfn(fn)
def __iter__(self):
for f in self._files:
yield f
# Callbacks related to how the matcher is used by dirstate.walk.
# Subscribers to these events must monkeypatch the matcher object.
def bad(self, f, msg):
"""Callback from dirstate.walk for each explicit file that can't be
found/accessed, with an error message."""
# If an traversedir is set, it will be called when a directory discovered
# by recursive traversal is visited.
traversedir = None
def abs(self, f):
"""Convert a repo path back to path that is relative to the root of the
matcher."""
return f
def rel(self, f):
"""Convert repo path back to path that is relative to cwd of matcher."""
return util.pathto(self._root, self._cwd, f)
def uipath(self, f):
"""Convert repo path to a display path. If patterns or -I/-X were used
to create this matcher, the display path will be relative to cwd.
Otherwise it is relative to the root of the repo."""
return (self._relativeuipath and self.rel(f)) or self.abs(f)
@propertycache
def _files(self):
return []
def files(self):
"""Explicitly listed files or patterns or roots:
if no patterns or .always(): empty list,
if exact: list exact files,
if not .anypats(): list all files and dirs,
else: optimal roots"""
return self._files
@propertycache
def _fileset(self):
return set(self._files)
def exact(self, f):
"""Returns True if f is in .files()."""
return f in self._fileset
def matchfn(self, f):
return False
def visitdir(self, dir):
"""Decides whether a directory should be visited based on whether it
has potential matches in it or one of its subdirectories. This is
based on the match's primary, included, and excluded patterns.
Returns the string 'all' if the given directory and all subdirectories
should be visited. Otherwise returns True or False indicating whether
the given directory should be visited.
"""
return True
def always(self):
"""Matcher will match everything and .files() will be empty --
optimization might be possible."""
return False
def isexact(self):
"""Matcher will match exactly the list of files in .files() --
optimization might be possible."""
return False
def prefix(self):
"""Matcher will match the paths in .files() recursively --
optimization might be possible."""
return False
def anypats(self):
"""None of .always(), .isexact(), and .prefix() is true --
optimizations will be difficult."""
return not self.always() and not self.isexact() and not self.prefix()
class alwaysmatcher(basematcher):
"""Matches everything."""
def __init__(self, root, cwd, badfn=None, relativeuipath=False):
super(alwaysmatcher, self).__init__(
root, cwd, badfn, relativeuipath=relativeuipath
)
def always(self):
return True
def matchfn(self, f):
return True
def visitdir(self, dir):
return "all"
def __repr__(self):
return "<alwaysmatcher>"
class nevermatcher(basematcher):
"""Matches nothing."""
def __init__(self, root, cwd, badfn=None):
super(nevermatcher, self).__init__(root, cwd, badfn)
# It's a little weird to say that the nevermatcher is an exact matcher
# or a prefix matcher, but it seems to make sense to let callers take
# fast paths based on either. There will be no exact matches, nor any
# prefixes (files() returns []), so fast paths iterating over them should
# be efficient (and correct).
def isexact(self):
return True
def prefix(self):
return True
def visitdir(self, dir):
return False
def __repr__(self):
return "<nevermatcher>"
class gitignorematcher(basematcher):
"""Match files specified by ".gitignore"s"""
def __init__(self, root, cwd, badfn=None, gitignorepaths=None):
super(gitignorematcher, self).__init__(root, cwd, badfn)
gitignorepaths = gitignorepaths or []
self._matcher = pathmatcher.gitignorematcher(root, gitignorepaths)
def matchfn(self, f):
# XXX: is_dir is set to True here for performance.
# It should be set to whether "f" is actually a directory or not.
return self._matcher.match_relative(f, True)
def explain(self, f):
return self._matcher.explain(f, True)
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
matched = self._matcher.match_relative(dir, True)
if matched:
# Everything in the directory is selected (ignored)
return "all"
else:
# Not sure
return True
def __repr__(self):
return "<gitignorematcher>"
class treematcher(basematcher):
"""Match glob patterns with negative pattern support.
Have a smarter 'visitdir' implementation.
"""
def __init__(self, root, cwd, badfn=None, rules=[]):
super(treematcher, self).__init__(root, cwd, badfn)
rules = list(rules)
self._matcher = pathmatcher.treematcher(rules)
self._rules = rules
def matchfn(self, f):
return self._matcher.matches(f)
def visitdir(self, dir):
matched = self._matcher.match_recursive(dir)
if matched is None:
return True
elif matched is True:
return "all"
else:
assert matched is False
return False
def __repr__(self):
return "<treematcher rules=%r>" % self._rules
def normalizerootdir(dir, funcname):
if dir == ".":
util.nouideprecwarn(
"match.%s() no longer accepts '.', use '' instead." % funcname, "20190805"
)
return ""
return dir
def _kindpatstoglobs(kindpats, recursive=False):
"""Attempt to convert 'kindpats' to glob patterns that can be used in a
treematcher.
kindpats should be already normalized to be relative to repo root.
If recursive is True, `glob:a*` will match both `a1/b` and `a1`, otherwise
`glob:a*` will only match `a1` but not `a1/b`.
Return None if there are unsupported patterns (ex. regular expressions).
"""
if not _usetreematcher:
return None
globs = []
for kindpat in kindpats:
kind, pat = kindpat[0:2]
if kind == "re":
# Attempt to convert the re pat to globs
reglobs = _convertretoglobs(pat)
if reglobs is not None:
globs += reglobs
else:
return None
elif kind == "glob":
# The treematcher (man gitignore) does not support csh-style
# brackets (ex. "{a,b,c}"). Expand the brackets to patterns.
for subpat in pathmatcher.expandcurlybrackets(pat):
normalized = pathmatcher.normalizeglob(subpat)
if recursive:
normalized = _makeglobrecursive(normalized)
globs.append(normalized)
elif kind == "path":
if pat == ".":
# Special case. Comes from `util.normpath`.
pat = ""
else:
pat = pathmatcher.plaintoglob(pat)
pat = _makeglobrecursive(pat)
globs.append(pat)
else:
return None
return globs
def _makeglobrecursive(pat):
"""Make a glob pattern recursive by appending "/**" to it"""
if pat.endswith("/") or not pat:
return pat + "**"
else:
return pat + "/**"
# re:x/(?!y/)
# meaning: include x, but not x/y.
_repat1 = re.compile(r"^\^?([\w._/]+)/\(\?\!([\w._/]+)/?\)$")
# re:x/(?:.*/)?y
# meaning: glob:x/**/y
_repat2 = re.compile(r"^\^?([\w._/]+)/\(\?:\.\*/\)\?([\w._]+)(?:\(\?\:\/\|\$\))?$")
def _convertretoglobs(repat):
"""Attempt to convert a regular expression pattern to glob patterns.
A single regular expression pattern might be converted into multiple
glob patterns.
Return None if conversion is unsupported.
>>> _convertretoglobs("abc*") is None
True
>>> _convertretoglobs("xx/yy/(?!zz/kk)")
['xx/yy/**', '!xx/yy/zz/kk/**']
>>> _convertretoglobs("x/y/(?:.*/)?BUCK")
['x/y/**/BUCK']
"""
m = _repat1.match(repat)
if m:
prefix, excluded = m.groups()
return ["%s/**" % prefix, "!%s/%s/**" % (prefix, excluded)]
m = _repat2.match(repat)
if m:
prefix, name = m.groups()
return ["%s/**/%s" % (prefix, name)]
return None
class patternmatcher(basematcher):
def __init__(self, root, cwd, kindpats, ctx=None, badfn=None):
super(patternmatcher, self).__init__(root, cwd, badfn)
# kindpats are already normalized to be relative to repo-root.
# Can we use tree matcher?
rules = _kindpatstoglobs(kindpats, recursive=False)
fallback = True
if rules is not None:
try:
matcher = treematcher(root, cwd, badfn=badfn, rules=rules)
# Replace self to 'matcher'.
self.__dict__ = matcher.__dict__
self.__class__ = matcher.__class__
fallback = False
except ValueError:
# for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.")
pass
if fallback:
self._prefix = _prefix(kindpats)
self._pats, self.matchfn = _buildmatch(ctx, kindpats, "$", root)
self._files = _explicitfiles(kindpats)
@propertycache
def _dirs(self):
return set(util.dirs(self._fileset))
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if self._prefix and dir in self._fileset:
return "all"
if not self._prefix:
return True
return (
dir in self._fileset
or dir in self._dirs
or any(parentdir in self._fileset for parentdir in util.finddirs(dir))
)
def prefix(self):
return self._prefix
def __repr__(self):
return "<patternmatcher patterns=%r>" % self._pats
class includematcher(basematcher):
def __init__(self, root, cwd, kindpats, ctx=None, badfn=None):
super(includematcher, self).__init__(root, cwd, badfn)
# Can we use tree matcher?
rules = _kindpatstoglobs(kindpats, recursive=True)
fallback = True
if rules is not None:
try:
matcher = treematcher(root, cwd, badfn=badfn, rules=rules)
# Replace self to 'matcher'.
self.__dict__ = matcher.__dict__
self.__class__ = matcher.__class__
fallback = False
except ValueError:
# for example, Regex("Compiled regex exceeds size limit of 10485760 bytes.")
pass
if fallback:
self._pats, self.matchfn = _buildmatch(ctx, kindpats, "(?:/|$)", root)
# prefix is True if all patterns are recursive, so certain fast paths
# can be enabled. Unfortunately, it's too easy to break it (ex. by
# using "glob:*.c", "re:...", etc).
self._prefix = _prefix(kindpats)
roots, dirs = _rootsanddirs(kindpats)
# roots are directories which are recursively included.
# If self._prefix is True, then _roots can have a fast path for
# visitdir to return "all", marking things included unconditionally.
# If self._prefix is False, then that optimization is unsound because
# "roots" might contain entries that is not recursive (ex. roots will
# include "foo/bar" for pattern "glob:foo/bar/*.c").
self._roots = set(roots)
# dirs are directories which are non-recursively included.
# That is, files under that directory are included. But not
# subdirectories.
self._dirs = set(dirs)
# Try to use a more efficient visitdir implementation
visitdir = _buildvisitdir(kindpats)
if visitdir:
self.visitdir = visitdir
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if self._prefix and dir in self._roots:
return "all"
return (
dir in self._roots
or dir in self._dirs
or any(parentdir in self._roots for parentdir in util.finddirs(dir))
)
def __repr__(self):
return "<includematcher includes=%r>" % self._pats
class exactmatcher(basematcher):
"""Matches the input files exactly. They are interpreted as paths, not
patterns (so no kind-prefixes).
"""
def __init__(self, root, cwd, files, badfn=None):
super(exactmatcher, self).__init__(root, cwd, badfn)
if isinstance(files, list):
self._files = files
else:
self._files = list(files)
matchfn = basematcher.exact
@propertycache
def _dirs(self):
return set(util.dirs(self._fileset))
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
return dir in self._dirs
def isexact(self):
return True
def __repr__(self):
return "<exactmatcher files=%r>" % self._files
class differencematcher(basematcher):
"""Composes two matchers by matching if the first matches and the second
does not. Well, almost... If the user provides a pattern like "-X foo foo",
Mercurial actually does match "foo" against that. That's because exact
matches are treated specially. So, since this differencematcher is used for
excludes, it needs to special-case exact matching.
The second matcher's non-matching-attributes (root, cwd, bad, traversedir)
are ignored.
TODO: If we want to keep the behavior described above for exact matches, we
should consider instead treating the above case something like this:
union(exact(foo), difference(pattern(foo), include(foo)))
"""
def __init__(self, m1, m2):
super(differencematcher, self).__init__(m1._root, m1._cwd)
self._m1 = m1
self._m2 = m2
self.bad = m1.bad
self.traversedir = m1.traversedir
def matchfn(self, f):
return self._m1(f) and (not self._m2(f) or self._m1.exact(f))
@propertycache
def _files(self):
if self.isexact():
return [f for f in self._m1.files() if self(f)]
# If m1 is not an exact matcher, we can't easily figure out the set of
# files, because its files() are not always files. For example, if
# m1 is "path:dir" and m2 is "rootfileins:.", we don't
# want to remove "dir" from the set even though it would match m2,
# because the "dir" in m1 may not be a file.
return self._m1.files()
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if not self._m2.visitdir(dir):
return self._m1.visitdir(dir)
if self._m2.visitdir(dir) == "all":
# There's a bug here: If m1 matches file 'dir/file' and m2 excludes
# 'dir' (recursively), we should still visit 'dir' due to the
# exception we have for exact matches.
return False
return bool(self._m1.visitdir(dir))
def isexact(self):
return self._m1.isexact()
def __repr__(self):
return "<differencematcher m1=%r, m2=%r>" % (self._m1, self._m2)
def intersectmatchers(m1, m2):
"""Composes two matchers by matching if both of them match.
The second matcher's non-matching-attributes (root, cwd, bad, traversedir)
are ignored.
"""
if m1 is None or m2 is None:
return m1 or m2
if m1.always():
m = copy.copy(m2)
# TODO: Consider encapsulating these things in a class so there's only
# one thing to copy from m1.
m.bad = m1.bad
m.traversedir = m1.traversedir
m.abs = m1.abs
m.rel = m1.rel
m._relativeuipath |= m1._relativeuipath
return m
if m2.always():
m = copy.copy(m1)
m._relativeuipath |= m2._relativeuipath
return m
return intersectionmatcher(m1, m2)
class intersectionmatcher(basematcher):
def __init__(self, m1, m2):
super(intersectionmatcher, self).__init__(m1._root, m1._cwd)
self._m1 = m1
self._m2 = m2
self.bad = m1.bad
self.traversedir = m1.traversedir
@propertycache
def _files(self):
if self.isexact():
m1, m2 = self._m1, self._m2
if not m1.isexact():
m1, m2 = m2, m1
return [f for f in m1.files() if m2(f)]
# It neither m1 nor m2 is an exact matcher, we can't easily intersect
# the set of files, because their files() are not always files. For
# example, if intersecting a matcher "-I glob:foo.txt" with matcher of
# "path:dir2", we don't want to remove "dir2" from the set.
return self._m1.files() + self._m2.files()
def matchfn(self, f):
return self._m1(f) and self._m2(f)
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
visit1 = self._m1.visitdir(dir)
if visit1 == "all":
return self._m2.visitdir(dir)
# bool() because visit1=True + visit2='all' should not be 'all'
return bool(visit1 and self._m2.visitdir(dir))
def always(self):
return self._m1.always() and self._m2.always()
def isexact(self):
return self._m1.isexact() or self._m2.isexact()
def __repr__(self):
return "<intersectionmatcher m1=%r, m2=%r>" % (self._m1, self._m2)
class subdirmatcher(basematcher):
"""Adapt a matcher to work on a subdirectory only.
The paths are remapped to remove/insert the path as needed:
>>> from . import pycompat
>>> m1 = match(b'root', b'', [b'a.txt', b'sub/b.txt'])
>>> m2 = subdirmatcher(b'sub', m1)
>>> bool(m2(b'a.txt'))
False
>>> bool(m2(b'b.txt'))
True
>>> bool(m2.matchfn(b'a.txt'))
False
>>> bool(m2.matchfn(b'b.txt'))
True
>>> m2.files()
['b.txt']
>>> m2.exact(b'b.txt')
True
>>> util.pconvert(m2.rel(b'b.txt'))
'sub/b.txt'
>>> def bad(f, msg):
... print(b"%s: %s" % (f, msg))
>>> m1.bad = bad
>>> m2.bad(b'x.txt', b'No such file')
sub/x.txt: No such file
>>> m2.abs(b'c.txt')
'sub/c.txt'
"""
def __init__(self, path, matcher):
super(subdirmatcher, self).__init__(matcher._root, matcher._cwd)
self._path = path
self._matcher = matcher
self._always = matcher.always()
self._files = [
f[len(path) + 1 :] for f in matcher._files if f.startswith(path + "/")
]
# If the parent repo had a path to this subrepo and the matcher is
# a prefix matcher, this submatcher always matches.
if matcher.prefix():
self._always = any(f == path for f in matcher._files)
def bad(self, f, msg):
self._matcher.bad(self._path + "/" + f, msg)
def abs(self, f):
return self._matcher.abs(self._path + "/" + f)
def rel(self, f):
return self._matcher.rel(self._path + "/" + f)
def uipath(self, f):
return self._matcher.uipath(self._path + "/" + f)
def matchfn(self, f):
# Some information is lost in the superclass's constructor, so we
# can not accurately create the matching function for the subdirectory
# from the inputs. Instead, we override matchfn() and visitdir() to
# call the original matcher with the subdirectory path prepended.
return self._matcher.matchfn(self._path + "/" + f)
def visitdir(self, dir):
dir = normalizerootdir(dir, "visitdir")
if dir == "":
dir = self._path
else:
dir = self._path + "/" + dir
return self._matcher.visitdir(dir)
def always(self):
return self._always
def prefix(self):
return self._matcher.prefix() and not self._always
def __repr__(self):
return "<subdirmatcher path=%r, matcher=%r>" % (self._path, self._matcher)
class unionmatcher(basematcher):
"""A matcher that is the union of several matchers.
The non-matching-attributes (root, cwd, bad, traversedir) are
taken from the first matcher.
"""
def __init__(self, matchers):
m1 = matchers[0]
super(unionmatcher, self).__init__(m1._root, m1._cwd)
self.traversedir = m1.traversedir
self._matchers = matchers
def matchfn(self, f):
for match in self._matchers:
if match(f):
return True
return False
def visitdir(self, dir):
r = False
for m in self._matchers:
v = m.visitdir(dir)
if v == "all":
return v
r |= v
return r
def __repr__(self):
return "<unionmatcher matchers=%r>" % self._matchers
class xormatcher(basematcher):
"""A matcher that is the xor of two matchers i.e. match returns true if there's at least
one false and one true.
The non-matching-attributes (root, cwd, bad, traversedir) are
taken from the first matcher.
"""
def __init__(self, m1, m2):
super(xormatcher, self).__init__(m1._root, m1._cwd)
self.traversedir = m1.traversedir
self.m1 = m1
self.m2 = m2
def matchfn(self, f):
return bool(self.m1(f)) ^ bool(self.m2(f))
def visitdir(self, dir):
m1dir = self.m1.visitdir(dir)
m2dir = self.m2.visitdir(dir)
# if both matchers return "all" then we know for sure we don't need
# to visit this directory. Same if all matchers return False. In all
# other case we have to visit a directory.
if m1dir == "all" and m2dir == "all":
return False
if not m1dir and not m2dir:
return False
return True
def __repr__(self):
return "<xormatcher matchers=%r>" % self._matchers
class recursivematcher(basematcher):
"""Make matchers recursive. If "a/b/c" matches, match "a/b/c/**".
It is intended to be used by hgignore only. Other matchers would want to
fix "visitdir" and "matchfn" to take parent directories into consideration.
"""
def __init__(self, matcher):
self._matcher = matcher
def matchfn(self, f):
match = self._matcher
return match(f) or any(map(match, util.dirs((f,))))
def visitdir(self, dir):
if self(dir):
return "all"
return self._matcher.visitdir(dir)
def __repr__(self):
return "<recursivematcher %r>" % self._matcher
def patkind(pattern, default=None):
"""If pattern is 'kind:pat' with a known kind, return kind."""
return _patsplit(pattern, default)[0]
def _patsplit(pattern, default):
"""Split a string into the optional pattern kind prefix and the actual
pattern."""
if ":" in pattern:
kind, pat = pattern.split(":", 1)
if kind in allpatternkinds:
return kind, pat
return default, pattern
def _globre(pat):
r"""Convert an extended glob string to a regexp string.
>>> from . import pycompat
>>> def bprint(s):
... print(s)
>>> bprint(_globre(br'?'))
.
>>> bprint(_globre(br'*'))
[^/]*
>>> bprint(_globre(br'**'))
.*
>>> bprint(_globre(br'**/a'))
(?:.*/)?a
>>> bprint(_globre(br'a/**/b'))
a/(?:.*/)?b
>>> bprint(_globre(br'[a*?!^][^b][!c]'))
[a*?!^][\^b][^c]
>>> bprint(_globre(br'{a,b}'))
(?:a|b)
>>> bprint(_globre(br'.\*\?'))
\.\*\?
"""
i, n = 0, len(pat)
res = ""
group = 0
escape = util.re.escape
def peek():
return i < n and pat[i : i + 1]
while i < n:
c = pat[i : i + 1]
i += 1
if c not in "*?[{},\\":
res += escape(c)
elif c == "*":
if peek() == "*":
i += 1
if peek() == "/":
i += 1
res += "(?:.*/)?"
else:
res += ".*"
else:
res += "[^/]*"
elif c == "?":
res += "."
elif c == "[":
j = i
if j < n and pat[j : j + 1] in "!]":
j += 1
while j < n and pat[j : j + 1] != "]":
j += 1
if j >= n:
res += "\\["
else:
stuff = pat[i:j].replace("\\", "\\\\")
i = j + 1
if stuff[0:1] == "!":
stuff = "^" + stuff[1:]
elif stuff[0:1] == "^":
stuff = "\\" + stuff
res = "%s[%s]" % (res, stuff)
elif c == "{":
group += 1
res += "(?:"
elif c == "}" and group:
res += ")"
group -= 1
elif c == "," and group:
res += "|"
elif c == "\\":
p = peek()
if p:
i += 1
res += escape(p)
else:
res += escape(c)
else:
res += escape(c)
return res
def _regex(kind, pat, globsuffix):
"""Convert a (normalized) pattern of any kind into a regular expression.
globsuffix is appended to the regexp of globs."""
if not pat and kind in ("glob", "relpath"):
return ""
if kind == "re":
return pat
if kind in ("path", "relpath"):
if pat == ".":
return ""
return util.re.escape(pat) + "(?:/|$)"
if kind == "rootfilesin":
if pat == ".":
escaped = ""
else:
# Pattern is a directory name.
escaped = util.re.escape(pat) + "/"
# Anything after the pattern must be a non-directory.
return escaped + "[^/]+$"
if kind == "relglob":
return "(?:|.*/)" + _globre(pat) + globsuffix
if kind == "relre":
if pat.startswith("^"):
return pat
return ".*" + pat
return _globre(pat) + globsuffix
def _buildmatch(ctx, kindpats, globsuffix, root):
"""Return regexp string and a matcher function for kindpats.
globsuffix is appended to the regexp of globs."""
matchfuncs = []
subincludes, kindpats = _expandsubinclude(kindpats, root)
if subincludes:
submatchers = {}
def matchsubinclude(f):
for prefix, matcherargs in subincludes:
if f.startswith(prefix):
mf = submatchers.get(prefix)
if mf is None:
mf = match(*matcherargs)
submatchers[prefix] = mf
if mf(f[len(prefix) :]):
return True
return False
matchfuncs.append(matchsubinclude)
fset, kindpats = _expandsets(kindpats, ctx)
if fset:
matchfuncs.append(fset.__contains__)
regex = ""
if kindpats:
regex, mf = _buildregexmatch(kindpats, globsuffix)
matchfuncs.append(mf)
if len(matchfuncs) == 1:
return regex, matchfuncs[0]
else:
return regex, lambda f: any(mf(f) for mf in matchfuncs)
def _buildregexmatch(kindpats, globsuffix):
"""Build a match function from a list of kinds and kindpats,
return regexp string and a matcher function."""
try:
regex = "(?:%s)" % "|".join(
[_regex(k, p, globsuffix) for (k, p, s) in kindpats]
)
if len(regex) > 20000:
raise OverflowError
return regex, _rematcher(regex)
except OverflowError:
# We're using a Python with a tiny regex engine and we
# made it explode, so we'll divide the pattern list in two
# until it works
l = len(kindpats)
if l < 2:
raise
regexa, a = _buildregexmatch(kindpats[: l // 2], globsuffix)
regexb, b = _buildregexmatch(kindpats[l // 2 :], globsuffix)
return regex, lambda s: a(s) or b(s)
except re.error:
for k, p, s in kindpats:
try:
_rematcher("(?:%s)" % _regex(k, p, globsuffix))
except re.error:
if s:
raise error.Abort(_("%s: invalid pattern (%s): %s") % (s, k, p))
else:
raise error.Abort(_("invalid pattern (%s): %s") % (k, p))
raise error.Abort(_("invalid pattern"))
def _patternrootsanddirs(kindpats):
"""Returns roots and directories corresponding to each pattern.
This calculates the roots and directories exactly matching the patterns and
returns a tuple of (roots, dirs) for each. It does not return other
directories which may also need to be considered, like the parent
directories.
"""
r = []
d = []
for kind, pat, source in kindpats:
if kind == "glob": # find the non-glob prefix
root = []
for p in pat.split("/"):
if "[" in p or "{" in p or "*" in p or "?" in p:
break
root.append(p)
r.append("/".join(root))
elif kind in ("relpath", "path"):
if pat == ".":
pat = ""
r.append(pat)
elif kind in ("rootfilesin",):
if pat == ".":
pat = ""
d.append(pat)
else: # relglob, re, relre
r.append("")
return r, d
def _roots(kindpats):
"""Returns root directories to match recursively from the given patterns."""
roots, dirs = _patternrootsanddirs(kindpats)
return roots
def _rootsanddirs(kindpats):
"""Returns roots and exact directories from patterns.
roots are directories to match recursively, whereas exact directories should
be matched non-recursively. The returned (roots, dirs) tuple will also
include directories that need to be implicitly considered as either, such as
parent directories.
>>> _rootsanddirs(
... [(b'glob', b'g/h/*', b''), (b'glob', b'g/h', b''),
... (b'glob', b'g*', b'')])
(['g/h', 'g/h', ''], ['', 'g'])
>>> _rootsanddirs(
... [(b'rootfilesin', b'g/h', b''), (b'rootfilesin', b'', b'')])
([], ['g/h', '', '', 'g'])
>>> _rootsanddirs(
... [(b'relpath', b'r', b''), (b'path', b'p/p', b''),
... (b'path', b'', b'')])
(['r', 'p/p', ''], ['', 'p'])
>>> _rootsanddirs(
... [(b'relglob', b'rg*', b''), (b're', b're/', b''),
... (b'relre', b'rr', b'')])
(['', '', ''], [''])
"""
r, d = _patternrootsanddirs(kindpats)
# Append the parents as non-recursive/exact directories, since they must be
# scanned to get to either the roots or the other exact directories.
d.extend(sorted(util.dirs(d)))
d.extend(sorted(util.dirs(r)))
return r, d
def _explicitfiles(kindpats):
"""Returns the potential explicit filenames from the patterns.
>>> _explicitfiles([(b'path', b'foo/bar', b'')])
['foo/bar']
>>> _explicitfiles([(b'rootfilesin', b'foo/bar', b'')])
[]
"""
# Keep only the pattern kinds where one can specify filenames (vs only
# directory names).
filable = [kp for kp in kindpats if kp[0] not in ("rootfilesin",)]
return _roots(filable)
def _prefix(kindpats):
"""Whether all the patterns match a prefix (i.e. recursively)"""
for kind, pat, source in kindpats:
if kind not in ("path", "relpath"):
return False
return True
_commentre = None
def readpatternfile(filepath, warn, sourceinfo=False):
"""parse a pattern file, returning a list of
patterns. These patterns should be given to compile()
to be validated and converted into a match function.
trailing white space is dropped.
the escape character is backslash.
comments start with #.
empty lines are skipped.
lines can be of the following formats:
syntax: regexp # defaults following lines to non-rooted regexps
syntax: glob # defaults following lines to non-rooted globs
re:pattern # non-rooted regular expression
glob:pattern # non-rooted glob
pattern # pattern of the current default type
if sourceinfo is set, returns a list of tuples:
(pattern, lineno, originalline). This is useful to debug ignore patterns.
"""
syntaxes = {
"re": "relre:",
"regexp": "relre:",
"glob": "relglob:",
"include": "include",
"subinclude": "subinclude",
}
syntax = "relre:"
patterns = []
fp = open(filepath, "rb")
for lineno, line in enumerate(util.iterfile(fp), start=1):
if "#" in line:
global _commentre
if not _commentre:
_commentre = util.re.compile(br"((?:^|[^\\])(?:\\\\)*)#.*")
# remove comments prefixed by an even number of escapes
m = _commentre.search(line)
if m:
line = line[: m.end(1)]
# fixup properly escaped comments that survived the above
line = line.replace("\\#", "#")
line = line.rstrip()
if not line:
continue
if line.startswith("syntax:"):
s = line[7:].strip()
try:
syntax = syntaxes[s]
except KeyError:
if warn:
warn(_("%s: ignoring invalid syntax '%s'\n") % (filepath, s))
continue
linesyntax = syntax
for s, rels in pycompat.iteritems(syntaxes):
if line.startswith(rels):
linesyntax = rels
line = line[len(rels) :]
break
elif line.startswith(s + ":"):
linesyntax = rels
line = line[len(s) + 1 :]
break
if sourceinfo:
patterns.append((linesyntax + line, lineno, line))
else:
patterns.append(linesyntax + line)
fp.close()
return patterns
_usetreematcher = True
def init(ui):
global _usetreematcher
_usetreematcher = ui.configbool("experimental", "treematcher")
| facebookexperimental/eden | eden/hg-server/edenscm/mercurial/match.py | Python | gpl-2.0 | 53,143 |
import numpy as np
from OpenGL.GL import *
from OpenGL.GLU import *
import time
import freenect
import calibkinect
import pykinectwindow as wxwindow
# I probably need more help with these!
try:
TEXTURE_TARGET = GL_TEXTURE_RECTANGLE
except:
TEXTURE_TARGET = GL_TEXTURE_RECTANGLE_ARB
if not 'win' in globals():
win = wxwindow.Window(size=(640, 480))
def refresh():
win.Refresh()
print type(win)
if not 'rotangles' in globals(): rotangles = [0,0]
if not 'zoomdist' in globals(): zoomdist = 1
if not 'projpts' in globals(): projpts = (None, None)
if not 'rgb' in globals(): rgb = None
def create_texture():
global rgbtex
rgbtex = glGenTextures(1)
glBindTexture(TEXTURE_TARGET, rgbtex)
glTexImage2D(TEXTURE_TARGET,0,GL_RGB,640,480,0,GL_RGB,GL_UNSIGNED_BYTE,None)
if not '_mpos' in globals(): _mpos = None
@win.eventx
def EVT_LEFT_DOWN(event):
global _mpos
_mpos = event.Position
@win.eventx
def EVT_LEFT_UP(event):
global _mpos
_mpos = None
@win.eventx
def EVT_MOTION(event):
global _mpos
if event.LeftIsDown():
if _mpos:
(x,y),(mx,my) = event.Position,_mpos
rotangles[0] += y-my
rotangles[1] += x-mx
refresh()
_mpos = event.Position
@win.eventx
def EVT_MOUSEWHEEL(event):
global zoomdist
dy = event.WheelRotation
zoomdist *= np.power(0.95, -dy)
refresh()
clearcolor = [0,0,0,0]
@win.event
def on_draw():
if not 'rgbtex' in globals():
create_texture()
xyz, uv = projpts
if xyz is None: return
if not rgb is None:
rgb_ = (rgb.astype(np.float32) * 4 + 70).clip(0,255).astype(np.uint8)
glBindTexture(TEXTURE_TARGET, rgbtex)
glTexSubImage2D(TEXTURE_TARGET, 0, 0, 0, 640, 480, GL_RGB, GL_UNSIGNED_BYTE, rgb_);
glClearColor(*clearcolor)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_DEPTH_TEST)
# flush that stack in case it's broken from earlier
glPushMatrix()
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60, 4/3., 0.3, 200)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def mouse_rotate(xAngle, yAngle, zAngle):
glRotatef(xAngle, 1.0, 0.0, 0.0);
glRotatef(yAngle, 0.0, 1.0, 0.0);
glRotatef(zAngle, 0.0, 0.0, 1.0);
glScale(zoomdist,zoomdist,1)
glTranslate(0, 0,-3.5)
mouse_rotate(rotangles[0], rotangles[1], 0);
glTranslate(0,0,1.5)
#glTranslate(0, 0,-1)
# Draw some axes
if 0:
glBegin(GL_LINES)
glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(1,0,0)
glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,1,0)
glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,1)
glEnd()
# We can either project the points ourselves, or embed it in the opengl matrix
if 0:
dec = 4
v,u = mgrid[:480,:640].astype(np.uint16)
points = np.vstack((u[::dec,::dec].flatten(),
v[::dec,::dec].flatten(),
depth[::dec,::dec].flatten())).transpose()
points = points[points[:,2]<2047,:]
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMultMatrixf(calibkinect.uv_matrix().transpose())
glMultMatrixf(calibkinect.xyz_matrix().transpose())
glTexCoordPointers(np.array(points))
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glMultMatrixf(calibkinect.xyz_matrix().transpose())
glVertexPointers(np.array(points))
else:
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glVertexPointerf(xyz)
glTexCoordPointerf(uv)
# Draw the points
glPointSize(2)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY)
glEnable(TEXTURE_TARGET)
glColor3f(1,1,1)
glDrawElementsui(GL_POINTS, np.array(range(xyz.shape[0])))
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY)
glDisable(TEXTURE_TARGET)
glPopMatrix()
#
if 0:
inds = np.nonzero(xyz[:,2]>-0.55)
glPointSize(10)
glColor3f(0,1,1)
glEnableClientState(GL_VERTEX_ARRAY)
glDrawElementsui(GL_POINTS, np.array(inds))
glDisableClientState(GL_VERTEX_ARRAY)
if 0:
# Draw only the points in the near plane
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_BLEND)
glColor(0.9,0.9,1.0,0.8)
glPushMatrix()
glTranslate(0,0,-0.55)
glScale(0.6,0.6,1)
glBegin(GL_QUADS)
glVertex3f(-1,-1,0); glVertex3f( 1,-1,0);
glVertex3f( 1, 1,0); glVertex3f(-1, 1,0);
glEnd()
glPopMatrix()
glDisable(GL_BLEND)
glPopMatrix()
# A silly loop that shows you can busy the ipython thread while opengl runs
def playcolors():
while 1:
global clearcolor
clearcolor = [np.random.random(),0,0,0]
time.sleep(0.1)
refresh()
# Update the point cloud from the shell or from a background thread!
def update(dt=0):
global projpts, rgb, depth
depth,_ = freenect.sync_get_depth()
rgb,_ = freenect.sync_get_video()
q = depth
X,Y = np.meshgrid(range(640),range(480))
# YOU CAN CHANGE THIS AND RERUN THE PROGRAM!
# Point cloud downsampling
d = 4
projpts = calibkinect.depth2xyzuv(q[::d,::d],X[::d,::d],Y[::d,::d])
refresh()
def update_join():
update_on()
try:
_thread.join()
except:
update_off()
def update_on():
global _updating
if not '_updating' in globals(): _updating = False
if _updating: return
_updating = True
from threading import Thread
global _thread
def _run():
while _updating:
update()
_thread = Thread(target=_run)
_thread.start()
def update_off():
global _updating
_updating = False
# Get frames in a loop and display with opencv
def loopcv():
import cv
while 1:
cv.ShowImage('hi',get_depth().astype(np.uint8))
cv.WaitKey(10)
update()
#update_on()
| Dining-Engineers/left-luggage-detection | misc/demo/ipython/demo_pclview.py | Python | gpl-2.0 | 5,742 |
/*#discipline{
margin-right: 8px;
}
.list li p{
font-size: 14px;
}
.list li h3{
font-size: 16px;
margin-bottom: -4px;
margin-top: 8px;
}
.pagination, .pag-nav{
width: 100%;
position: relative;
left: -25px;
list-style: none;
}
.pag-nav{
margin-bottom:-29.5px;
}
.pag-nav li{
position: relative;
z-index: 10;
}
.pagination{
box-sizing:border-box;
}
.img-wrap{
display:flex;
justify-content:center;
align-items:center;
overflow:hidden;
min-height: 127px;
max-height: 127px;
}
.img-wrap img {
flex-shrink:2;
min-width:100%;
min-height:100%;
min-height: 127px;
}
.catagories{
display: inline-block;
margin-top:8px;
float:left;
margin-right:20px;
}
.pagination li, .pag-nav li{
background:#eee;
width: 19.5px;
height: 19.5px;
display: inline-block;
padding:5px;
text-align: center;
}
.pagination li.active, .pagination li.active:hover{
background:#1B8ABA;
}
.pagination li.active a{
color:white;
}
.pagination li:hover, .pag-nav li:hover{
background: rgba(0, 0, 0, 0.1);
}
.pag-nav li{
background:rgba(0,0,0,.05);
}
.pag-nav li:last-child{
float:right;
}
.list {
font-family:sans-serif;
margin:0;
padding:20px 0 0;
}
.list > li {
display:block;
background-color: #eee;
box-shadow: inset 0 1px 0 #fff;
box-sizing: border-box;
margin-right: 1.5%;
margin-bottom: 1.5%;
float: left;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
/* 480*/
}
/*
#programList .weak, #programList #found{
display: none !important;
}
*/
.list > li .content{
padding:10px;
height: 116px;
/*border: 1px solid rgba(0, 0, 0, 0.05);*/
}
@media (max-width: 480px) {
.list > li{
width:100%;
margin-right:0px;
}
.catagories{
margin-left: -8px;
}
}
.avatar {
max-width: 150px;
}
img {
max-width: 100%;
}
h3 {
font-size: 16px;
margin:0 0 0.3rem;
font-weight: normal;
font-weight:bold;
}
p {
margin:0;
}
input {
border:solid 1px #ccc;
border-radius: 5px;
padding:7px 14px;
margin-bottom:10px
}
input:focus {
outline:none;
border-color:#aaa;
}
.sort {
padding:8px 30px;
border-radius: 6px;
border:none;
display:inline-block;
color:#fff;
text-decoration: none;
background-color: #DDE028;
height:30px;
}
.sort:hover {
text-decoration: none;
background-color:#1b8aba;
}
.sort:focus {
outline:none;
}
.sort:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid transparent;
content:"";
position: relative;
top:-10px;
right:-5px;
}
.sort.asc:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #fff;
content:"";
position: relative;
top:13px;
right:-5px;
}
.sort.desc:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #fff;
content:"";
position: relative;
top:-10px;
right:-5px;
}
#question{
text-align: center;
min-height: 50vh;
}
#programs{
display: none;
}
#change{
color:#DDE028;
text-decoration: underline;
}
/*MULTI SELECT STUFF*/
.list {
font-family:sans-serif;
margin:0;
/*padding:20px 0 0;*/
}
.list > li {
display:block;
background-color: #eee;
/*padding:10px;*/
box-shadow: inset 0 1px 0 #fff;
}
.avatar {
max-width: 150px;
}
img {
max-width: 100%;
}
h3 {
font-size: 16px;
margin:0 0 0.3rem;
font-weight: normal;
font-weight:bold;
}
p {
margin:0;
}
input {
border:solid 1px #ccc;
border-radius: 5px;
padding:7px 14px;
margin-bottom:10px
}
input:focus {
outline:none;
border-color:#aaa;
}
.sort {
padding:8px 30px;
border-radius: 6px;
border:none;
display:inline-block;
color:#fff;
text-decoration: none;
background-color: #DDE028;
height:30px;
}
.sort:hover {
text-decoration: none;
background-color:#E0D228;
}
.sort:focus {
outline:none;
}
.sort:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid transparent;
content:"";
position: relative;
top:-10px;
right:-5px;
}
.sort.asc:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #fff;
content:"";
position: relative;
top:13px;
right:-5px;
}
.sort.desc:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #fff;
content:"";
position: relative;
top:-10px;
right:-5px;
}
#catagories, .search{
float:left !important;
/*margin-top:1rem;*/
}
.search{
margin-right:2rem;
}
#programList{
display: none;
}
#programList .content{
padding: .5rem 0rem .5rem 1rem !important;
}
#programList .content *{
display: inline-block;
}
#programList ul.list{
padding-left: 0rem !important;
}
#programList thead td{
padding: 0px 0px 0px 0px;
}
#programList td .sort{
border-radius: 0;
width: 100%;
box-sizing: border-box;
padding-left: .75rem;
border: 0PX;
FONT-WEIGHT: 700;
TEXT-TRANSFORM: UPPERCASE
}
#catagories{
margin-right:0px !important;
}
.ms-choice{
width: 307px;
}
.ms-drop.bottom ul{
width: 307px;
box-sizing:border-box;
padding-left:1rem;
}
| nwpointer/facultymodule | program.css | CSS | gpl-2.0 | 5,353 |
using GitHubWin8Phone.Resources;
namespace GitHubWin8Phone
{
/// <summary>
/// Provides access to string resources.
/// </summary>
public class LocalizedStrings
{
private static AppResources _localizedResources = new AppResources();
public AppResources LocalizedResources { get { return _localizedResources; } }
}
} | davidkuhner/GitHubWin8 | GitHubWin8Phone/LocalizedStrings.cs | C# | gpl-2.0 | 360 |
showWord(["np. ","Avoka, politisyen. Madanm prezidan Jean Bertrand Aristide."
]) | georgejhunt/HaitiDictionary.activity | data/words/TwouyoMildr~ed_Trouillot.js | JavaScript | gpl-2.0 | 80 |
/*
* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/console.h>
#include <linux/regulator/consumer.h>
#include <asm/mach-types.h>
#include <asm/cpu.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/socinfo.h>
#include <mach/msm-krait-l2-accessors.h>
#include <mach/rpm-regulator.h>
#include <mach/rpm-regulator-smd.h>
#include <mach/msm_bus.h>
#include <mach/msm_dcvs.h>
#include "acpuclock.h"
#include "acpuclock-krait.h"
#include "avs.h"
#ifdef CONFIG_SEC_DEBUG_DCVS_LOG
#include <mach/sec_debug.h>
#endif
/* MUX source selects. */
#define PRI_SRC_SEL_SEC_SRC 0
#define PRI_SRC_SEL_HFPLL 1
#define PRI_SRC_SEL_HFPLL_DIV2 2
#define SECCLKAGD BIT(4)
#ifdef CONFIG_SEC_DEBUG_SUBSYS
int boost_uv;
int speed_bin;
int pvs_bin;
#endif
static DEFINE_MUTEX(driver_lock);
static DEFINE_SPINLOCK(l2_lock);
static struct drv_data {
struct acpu_level *acpu_freq_tbl;
const struct l2_level *l2_freq_tbl;
struct scalable *scalable;
struct hfpll_data *hfpll_data;
u32 bus_perf_client;
struct msm_bus_scale_pdata *bus_scale;
int boost_uv;
struct device *dev;
} drv;
static unsigned long acpuclk_krait_get_rate(int cpu)
{
return drv.scalable[cpu].cur_speed->khz;
}
/* Select a source on the primary MUX. */
static void set_pri_clk_src(struct scalable *sc, u32 pri_src_sel)
{
u32 regval;
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval &= ~0x3;
regval |= (pri_src_sel & 0x3);
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Wait for switch to complete. */
mb();
udelay(1);
}
/* Select a source on the secondary MUX. */
static void __cpuinit set_sec_clk_src(struct scalable *sc, u32 sec_src_sel)
{
u32 regval;
/* 8064 Errata: disable sec_src clock gating during switch. */
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval |= SECCLKAGD;
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Program the MUX */
regval &= ~(0x3 << 2);
regval |= ((sec_src_sel & 0x3) << 2);
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* 8064 Errata: re-enabled sec_src clock gating. */
regval &= ~SECCLKAGD;
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Wait for switch to complete. */
mb();
udelay(1);
}
static int enable_rpm_vreg(struct vreg *vreg)
{
int ret = 0;
if (vreg->rpm_reg) {
ret = rpm_regulator_enable(vreg->rpm_reg);
if (ret)
dev_err(drv.dev, "%s regulator enable failed (%d)\n",
vreg->name, ret);
}
return ret;
}
static void disable_rpm_vreg(struct vreg *vreg)
{
int rc;
if (vreg->rpm_reg) {
rc = rpm_regulator_disable(vreg->rpm_reg);
if (rc)
dev_err(drv.dev, "%s regulator disable failed (%d)\n",
vreg->name, rc);
}
}
/* Enable an already-configured HFPLL. */
static void hfpll_enable(struct scalable *sc, bool skip_regulators)
{
if (!skip_regulators) {
/* Enable regulators required by the HFPLL. */
enable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]);
enable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]);
}
/* Disable PLL bypass mode. */
writel_relaxed(0x2, sc->hfpll_base + drv.hfpll_data->mode_offset);
/*
* H/W requires a 5us delay between disabling the bypass and
* de-asserting the reset. Delay 10us just to be safe.
*/
mb();
udelay(10);
/* De-assert active-low PLL reset. */
writel_relaxed(0x6, sc->hfpll_base + drv.hfpll_data->mode_offset);
/* Wait for PLL to lock. */
mb();
udelay(60);
/* Enable PLL output. */
writel_relaxed(0x7, sc->hfpll_base + drv.hfpll_data->mode_offset);
}
/* Disable a HFPLL for power-savings or while it's being reprogrammed. */
static void hfpll_disable(struct scalable *sc, bool skip_regulators)
{
/*
* Disable the PLL output, disable test mode, enable the bypass mode,
* and assert the reset.
*/
writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->mode_offset);
if (!skip_regulators) {
/* Remove voltage votes required by the HFPLL. */
disable_rpm_vreg(&sc->vreg[VREG_HFPLL_B]);
disable_rpm_vreg(&sc->vreg[VREG_HFPLL_A]);
}
}
/* Program the HFPLL rate. Assumes HFPLL is already disabled. */
static void hfpll_set_rate(struct scalable *sc, const struct core_speed *tgt_s)
{
void __iomem *base = sc->hfpll_base;
u32 regval;
writel_relaxed(tgt_s->pll_l_val, base + drv.hfpll_data->l_offset);
if (drv.hfpll_data->has_user_reg) {
regval = readl_relaxed(base + drv.hfpll_data->user_offset);
if (tgt_s->pll_l_val <= drv.hfpll_data->low_vco_l_max)
regval &= ~drv.hfpll_data->user_vco_mask;
else
regval |= drv.hfpll_data->user_vco_mask;
writel_relaxed(regval, base + drv.hfpll_data->user_offset);
}
}
/* Return the L2 speed that should be applied. */
static unsigned int compute_l2_level(struct scalable *sc, unsigned int vote_l)
{
unsigned int new_l = 0;
int cpu;
/* Find max L2 speed vote. */
sc->l2_vote = vote_l;
for_each_present_cpu(cpu)
new_l = max(new_l, drv.scalable[cpu].l2_vote);
return new_l;
}
/* Update the bus bandwidth request. */
static void set_bus_bw(unsigned int bw)
{
int ret;
/* Update bandwidth if request has changed. This may sleep. */
ret = msm_bus_scale_client_update_request(drv.bus_perf_client, bw);
if (ret)
dev_err(drv.dev, "bandwidth request failed (%d)\n", ret);
}
/* Set the CPU or L2 clock speed. */
static void set_speed(struct scalable *sc, const struct core_speed *tgt_s,
bool skip_regulators)
{
const struct core_speed *strt_s = sc->cur_speed;
if (strt_s == tgt_s)
return;
if (strt_s->src == HFPLL && tgt_s->src == HFPLL) {
/*
* Move to an always-on source running at a frequency
* that does not require an elevated CPU voltage.
*/
set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC);
/* Re-program HFPLL. */
hfpll_disable(sc, true);
hfpll_set_rate(sc, tgt_s);
hfpll_enable(sc, true);
/* Move to HFPLL. */
set_pri_clk_src(sc, tgt_s->pri_src_sel);
} else if (strt_s->src == HFPLL && tgt_s->src != HFPLL) {
set_pri_clk_src(sc, tgt_s->pri_src_sel);
hfpll_disable(sc, skip_regulators);
} else if (strt_s->src != HFPLL && tgt_s->src == HFPLL) {
hfpll_set_rate(sc, tgt_s);
hfpll_enable(sc, skip_regulators);
set_pri_clk_src(sc, tgt_s->pri_src_sel);
}
sc->cur_speed = tgt_s;
}
struct vdd_data {
int vdd_mem;
int vdd_dig;
int vdd_core;
int ua_core;
};
/* Apply any per-cpu voltage increases. */
static int increase_vdd(int cpu, struct vdd_data *data,
enum setrate_reason reason)
{
struct scalable *sc = &drv.scalable[cpu];
int rc;
/*
* Increase vdd_mem active-set before vdd_dig.
* vdd_mem should be >= vdd_dig.
*/
if (data->vdd_mem > sc->vreg[VREG_MEM].cur_vdd) {
rc = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg,
data->vdd_mem, sc->vreg[VREG_MEM].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_mem (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem;
}
/* Increase vdd_dig active-set vote. */
if (data->vdd_dig > sc->vreg[VREG_DIG].cur_vdd) {
rc = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg,
data->vdd_dig, sc->vreg[VREG_DIG].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_dig (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig;
}
/* Increase current request. */
if (data->ua_core > sc->vreg[VREG_CORE].cur_ua) {
rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
data->ua_core);
if (rc < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, rc);
return rc;
}
sc->vreg[VREG_CORE].cur_ua = data->ua_core;
}
/*
* Update per-CPU core voltage. Don't do this for the hotplug path for
* which it should already be correct. Attempting to set it is bad
* because we don't know what CPU we are running on at this point, but
* the CPU regulator API requires we call it from the affected CPU.
*/
if (data->vdd_core > sc->vreg[VREG_CORE].cur_vdd
&& reason != SETRATE_HOTPLUG) {
rc = regulator_set_voltage(sc->vreg[VREG_CORE].reg,
data->vdd_core, sc->vreg[VREG_CORE].max_vdd);
if (rc) {
dev_err(drv.dev,
"vdd_core (cpu%d) increase failed (%d)\n",
cpu, rc);
return rc;
}
sc->vreg[VREG_CORE].cur_vdd = data->vdd_core;
}
return 0;
}
/* Apply any per-cpu voltage decreases. */
static void decrease_vdd(int cpu, struct vdd_data *data,
enum setrate_reason reason)
{
struct scalable *sc = &drv.scalable[cpu];
int ret;
/*
* Update per-CPU core voltage. This must be called on the CPU
* that's being affected. Don't do this in the hotplug remove path,
* where the rail is off and we're executing on the other CPU.
*/
if (data->vdd_core < sc->vreg[VREG_CORE].cur_vdd
&& reason != SETRATE_HOTPLUG) {
ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg,
data->vdd_core, sc->vreg[VREG_CORE].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_core (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_CORE].cur_vdd = data->vdd_core;
}
/* Decrease current request. */
if (data->ua_core < sc->vreg[VREG_CORE].cur_ua) {
ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
data->ua_core);
if (ret < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
return;
}
sc->vreg[VREG_CORE].cur_ua = data->ua_core;
}
/* Decrease vdd_dig active-set vote. */
if (data->vdd_dig < sc->vreg[VREG_DIG].cur_vdd) {
ret = rpm_regulator_set_voltage(sc->vreg[VREG_DIG].rpm_reg,
data->vdd_dig, sc->vreg[VREG_DIG].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_dig (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_DIG].cur_vdd = data->vdd_dig;
}
/*
* Decrease vdd_mem active-set after vdd_dig.
* vdd_mem should be >= vdd_dig.
*/
if (data->vdd_mem < sc->vreg[VREG_MEM].cur_vdd) {
ret = rpm_regulator_set_voltage(sc->vreg[VREG_MEM].rpm_reg,
data->vdd_mem, sc->vreg[VREG_MEM].max_vdd);
if (ret) {
dev_err(drv.dev,
"vdd_mem (cpu%d) decrease failed (%d)\n",
cpu, ret);
return;
}
sc->vreg[VREG_MEM].cur_vdd = data->vdd_mem;
}
}
static int calculate_vdd_mem(const struct acpu_level *tgt)
{
return drv.l2_freq_tbl[tgt->l2_level].vdd_mem;
}
static int get_src_dig(const struct core_speed *s)
{
const int *hfpll_vdd = drv.hfpll_data->vdd;
const u32 low_vdd_l_max = drv.hfpll_data->low_vdd_l_max;
const u32 nom_vdd_l_max = drv.hfpll_data->nom_vdd_l_max;
if (s->src != HFPLL)
return hfpll_vdd[HFPLL_VDD_NONE];
else if (s->pll_l_val > nom_vdd_l_max)
return hfpll_vdd[HFPLL_VDD_HIGH];
else if (s->pll_l_val > low_vdd_l_max)
return hfpll_vdd[HFPLL_VDD_NOM];
else
return hfpll_vdd[HFPLL_VDD_LOW];
}
static int calculate_vdd_dig(const struct acpu_level *tgt)
{
int l2_pll_vdd_dig, cpu_pll_vdd_dig;
l2_pll_vdd_dig = get_src_dig(&drv.l2_freq_tbl[tgt->l2_level].speed);
cpu_pll_vdd_dig = get_src_dig(&tgt->speed);
return max(drv.l2_freq_tbl[tgt->l2_level].vdd_dig,
max(l2_pll_vdd_dig, cpu_pll_vdd_dig));
}
static bool enable_boost = true;
module_param_named(boost, enable_boost, bool, S_IRUGO | S_IWUSR);
static int calculate_vdd_core(const struct acpu_level *tgt)
{
return tgt->vdd_core + (enable_boost ? drv.boost_uv : 0);
}
static DEFINE_MUTEX(l2_regulator_lock);
static int l2_vreg_count;
static int enable_l2_regulators(void)
{
int ret = 0;
mutex_lock(&l2_regulator_lock);
if (l2_vreg_count == 0) {
ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
if (ret)
goto out;
ret = enable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]);
if (ret) {
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
goto out;
}
}
l2_vreg_count++;
out:
mutex_unlock(&l2_regulator_lock);
return ret;
}
static void disable_l2_regulators(void)
{
mutex_lock(&l2_regulator_lock);
if (WARN(!l2_vreg_count, "L2 regulator votes are unbalanced!"))
goto out;
if (l2_vreg_count == 1) {
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_B]);
disable_rpm_vreg(&drv.scalable[L2].vreg[VREG_HFPLL_A]);
}
l2_vreg_count--;
out:
mutex_unlock(&l2_regulator_lock);
}
static int minus_vc;
module_param_named(
mclk, minus_vc, int, S_IRUGO | S_IWUSR | S_IWGRP
);
/* Set the CPU's clock rate and adjust the L2 rate, voltage and BW requests. */
static int acpuclk_krait_set_rate(int cpu, unsigned long rate,
enum setrate_reason reason)
{
const struct core_speed *strt_acpu_s, *tgt_acpu_s;
const struct acpu_level *tgt;
int tgt_l2_l;
enum src_id prev_l2_src = NUM_SRC_ID;
struct vdd_data vdd_data;
bool skip_regulators;
int rc = 0;
if (cpu > num_possible_cpus())
return -EINVAL;
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG)
mutex_lock(&driver_lock);
strt_acpu_s = drv.scalable[cpu].cur_speed;
/* Return early if rate didn't change. */
if (rate == strt_acpu_s->khz)
goto out;
/* Find target frequency. */
for (tgt = drv.acpu_freq_tbl; tgt->speed.khz != 0; tgt++) {
if (tgt->speed.khz == rate) {
tgt_acpu_s = &tgt->speed;
break;
}
}
if (tgt->speed.khz == 0) {
rc = -EINVAL;
goto out;
}
/* Calculate voltage requirements for the current CPU. */
vdd_data.vdd_mem = calculate_vdd_mem(tgt);
vdd_data.vdd_dig = calculate_vdd_dig(tgt);
vdd_data.vdd_core = calculate_vdd_core(tgt) + minus_vc;
vdd_data.ua_core = tgt->ua_core;
/* Disable AVS before voltage switch */
if (reason == SETRATE_CPUFREQ && drv.scalable[cpu].avs_enabled) {
AVS_DISABLE(cpu);
drv.scalable[cpu].avs_enabled = false;
}
/* Increase VDD levels if needed. */
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG) {
rc = increase_vdd(cpu, &vdd_data, reason);
if (rc)
goto out;
prev_l2_src =
drv.l2_freq_tbl[drv.scalable[cpu].l2_vote].speed.src;
/* Vote for the L2 regulators here if necessary. */
if (drv.l2_freq_tbl[tgt->l2_level].speed.src == HFPLL) {
rc = enable_l2_regulators();
if (rc)
goto out;
}
}
dev_dbg(drv.dev, "Switching from ACPU%d rate %lu KHz -> %lu KHz\n",
cpu, strt_acpu_s->khz, tgt_acpu_s->khz);
/*
* If we are setting the rate as part of power collapse or in the resume
* path after power collapse, skip the vote for the HFPLL regulators,
* which are active-set-only votes that will be removed when apps enters
* its sleep set. This is needed to avoid voting for regulators with
* sleeping APIs from an atomic context.
*/
skip_regulators = (reason == SETRATE_PC);
#ifdef CONFIG_SEC_DEBUG_DCVS_LOG
sec_debug_dcvs_log(cpu, strt_acpu_s->khz, tgt_acpu_s->khz);
#endif
/* Set the new CPU speed. */
set_speed(&drv.scalable[cpu], tgt_acpu_s, skip_regulators);
/*
* Update the L2 vote and apply the rate change. A spinlock is
* necessary to ensure L2 rate is calculated and set atomically
* with the CPU frequency, even if acpuclk_krait_set_rate() is
* called from an atomic context and the driver_lock mutex is not
* acquired.
*/
spin_lock(&l2_lock);
tgt_l2_l = compute_l2_level(&drv.scalable[cpu], tgt->l2_level);
set_speed(&drv.scalable[L2],
&drv.l2_freq_tbl[tgt_l2_l].speed, true);
spin_unlock(&l2_lock);
/* Nothing else to do for power collapse or SWFI. */
if (reason == SETRATE_PC || reason == SETRATE_SWFI)
goto out;
/*
* Remove the vote for the L2 HFPLL regulators only if the L2
* was already on an HFPLL source.
*/
if (prev_l2_src == HFPLL)
disable_l2_regulators();
/* Update bus bandwith request. */
set_bus_bw(drv.l2_freq_tbl[tgt_l2_l].bw_level);
/* Drop VDD levels if we can. */
decrease_vdd(cpu, &vdd_data, reason);
/* Re-enable AVS */
if (reason == SETRATE_CPUFREQ && tgt->avsdscr_setting) {
AVS_ENABLE(cpu, tgt->avsdscr_setting);
drv.scalable[cpu].avs_enabled = true;
}
dev_dbg(drv.dev, "ACPU%d speed change complete\n", cpu);
out:
if (reason == SETRATE_CPUFREQ || reason == SETRATE_HOTPLUG)
mutex_unlock(&driver_lock);
return rc;
}
static struct acpuclk_data acpuclk_krait_data = {
.set_rate = acpuclk_krait_set_rate,
.get_rate = acpuclk_krait_get_rate,
};
/* Initialize a HFPLL at a given rate and enable it. */
static void __cpuinit hfpll_init(struct scalable *sc,
const struct core_speed *tgt_s)
{
dev_dbg(drv.dev, "Initializing HFPLL%d\n", sc - drv.scalable);
/* Disable the PLL for re-programming. */
hfpll_disable(sc, true);
/* Configure PLL parameters for integer mode. */
writel_relaxed(drv.hfpll_data->config_val,
sc->hfpll_base + drv.hfpll_data->config_offset);
writel_relaxed(0, sc->hfpll_base + drv.hfpll_data->m_offset);
writel_relaxed(1, sc->hfpll_base + drv.hfpll_data->n_offset);
if (drv.hfpll_data->has_user_reg)
writel_relaxed(drv.hfpll_data->user_val,
sc->hfpll_base + drv.hfpll_data->user_offset);
/* Program droop controller, if supported */
if (drv.hfpll_data->has_droop_ctl)
writel_relaxed(drv.hfpll_data->droop_val,
sc->hfpll_base + drv.hfpll_data->droop_offset);
/* Set an initial PLL rate. */
hfpll_set_rate(sc, tgt_s);
}
static int __cpuinit rpm_regulator_init(struct scalable *sc, enum vregs vreg,
int vdd, bool enable)
{
int ret;
if (!sc->vreg[vreg].name)
return 0;
sc->vreg[vreg].rpm_reg = rpm_regulator_get(drv.dev,
sc->vreg[vreg].name);
if (IS_ERR(sc->vreg[vreg].rpm_reg)) {
ret = PTR_ERR(sc->vreg[vreg].rpm_reg);
dev_err(drv.dev, "rpm_regulator_get(%s) failed (%d)\n",
sc->vreg[vreg].name, ret);
goto err_get;
}
ret = rpm_regulator_set_voltage(sc->vreg[vreg].rpm_reg, vdd,
sc->vreg[vreg].max_vdd);
if (ret) {
dev_err(drv.dev, "%s initialization failed (%d)\n",
sc->vreg[vreg].name, ret);
goto err_conf;
}
sc->vreg[vreg].cur_vdd = vdd;
if (enable) {
ret = enable_rpm_vreg(&sc->vreg[vreg]);
if (ret)
goto err_conf;
}
return 0;
err_conf:
rpm_regulator_put(sc->vreg[vreg].rpm_reg);
err_get:
return ret;
}
static void __cpuinit rpm_regulator_cleanup(struct scalable *sc,
enum vregs vreg)
{
if (!sc->vreg[vreg].rpm_reg)
return;
disable_rpm_vreg(&sc->vreg[vreg]);
rpm_regulator_put(sc->vreg[vreg].rpm_reg);
}
/* Voltage regulator initialization. */
static int __cpuinit regulator_init(struct scalable *sc,
const struct acpu_level *acpu_level)
{
int ret, vdd_mem, vdd_dig, vdd_core;
vdd_mem = calculate_vdd_mem(acpu_level);
ret = rpm_regulator_init(sc, VREG_MEM, vdd_mem, true);
if (ret)
goto err_mem;
vdd_dig = calculate_vdd_dig(acpu_level);
ret = rpm_regulator_init(sc, VREG_DIG, vdd_dig, true);
if (ret)
goto err_dig;
ret = rpm_regulator_init(sc, VREG_HFPLL_A,
sc->vreg[VREG_HFPLL_A].max_vdd, false);
if (ret)
goto err_hfpll_a;
ret = rpm_regulator_init(sc, VREG_HFPLL_B,
sc->vreg[VREG_HFPLL_B].max_vdd, false);
if (ret)
goto err_hfpll_b;
/* Setup Krait CPU regulators and initial core voltage. */
sc->vreg[VREG_CORE].reg = regulator_get(drv.dev,
sc->vreg[VREG_CORE].name);
if (IS_ERR(sc->vreg[VREG_CORE].reg)) {
ret = PTR_ERR(sc->vreg[VREG_CORE].reg);
dev_err(drv.dev, "regulator_get(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_get;
}
ret = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
acpu_level->ua_core);
if (ret < 0) {
dev_err(drv.dev, "regulator_set_optimum_mode(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
sc->vreg[VREG_CORE].cur_ua = acpu_level->ua_core;
vdd_core = calculate_vdd_core(acpu_level);
ret = regulator_set_voltage(sc->vreg[VREG_CORE].reg, vdd_core,
sc->vreg[VREG_CORE].max_vdd);
if (ret) {
dev_err(drv.dev, "regulator_set_voltage(%s) (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
sc->vreg[VREG_CORE].cur_vdd = vdd_core;
ret = regulator_enable(sc->vreg[VREG_CORE].reg);
if (ret) {
dev_err(drv.dev, "regulator_enable(%s) failed (%d)\n",
sc->vreg[VREG_CORE].name, ret);
goto err_core_conf;
}
/*
* Increment the L2 HFPLL regulator refcount if _this_ CPU's frequency
* requires a corresponding target L2 frequency that needs the L2 to
* run off of an HFPLL.
*/
if (drv.l2_freq_tbl[acpu_level->l2_level].speed.src == HFPLL)
l2_vreg_count++;
return 0;
err_core_conf:
regulator_put(sc->vreg[VREG_CORE].reg);
err_core_get:
rpm_regulator_cleanup(sc, VREG_HFPLL_B);
err_hfpll_b:
rpm_regulator_cleanup(sc, VREG_HFPLL_A);
err_hfpll_a:
rpm_regulator_cleanup(sc, VREG_DIG);
err_dig:
rpm_regulator_cleanup(sc, VREG_MEM);
err_mem:
return ret;
}
static void __cpuinit regulator_cleanup(struct scalable *sc)
{
regulator_disable(sc->vreg[VREG_CORE].reg);
regulator_put(sc->vreg[VREG_CORE].reg);
rpm_regulator_cleanup(sc, VREG_HFPLL_B);
rpm_regulator_cleanup(sc, VREG_HFPLL_A);
rpm_regulator_cleanup(sc, VREG_DIG);
rpm_regulator_cleanup(sc, VREG_MEM);
}
/* Set initial rate for a given core. */
static int __cpuinit init_clock_sources(struct scalable *sc,
const struct core_speed *tgt_s)
{
u32 regval;
void __iomem *aux_reg;
/* Program AUX source input to the secondary MUX. */
if (sc->aux_clk_sel_phys) {
aux_reg = ioremap(sc->aux_clk_sel_phys, 4);
if (!aux_reg)
return -ENOMEM;
writel_relaxed(sc->aux_clk_sel, aux_reg);
iounmap(aux_reg);
}
/* Switch away from the HFPLL while it's re-initialized. */
set_sec_clk_src(sc, sc->sec_clk_sel);
set_pri_clk_src(sc, PRI_SRC_SEL_SEC_SRC);
hfpll_init(sc, tgt_s);
/* Set PRI_SRC_SEL_HFPLL_DIV2 divider to div-2. */
regval = get_l2_indirect_reg(sc->l2cpmr_iaddr);
regval &= ~(0x3 << 6);
set_l2_indirect_reg(sc->l2cpmr_iaddr, regval);
/* Enable and switch to the target clock source. */
if (tgt_s->src == HFPLL)
hfpll_enable(sc, false);
set_pri_clk_src(sc, tgt_s->pri_src_sel);
sc->cur_speed = tgt_s;
return 0;
}
static void __cpuinit fill_cur_core_speed(struct core_speed *s,
struct scalable *sc)
{
s->pri_src_sel = get_l2_indirect_reg(sc->l2cpmr_iaddr) & 0x3;
s->pll_l_val = readl_relaxed(sc->hfpll_base + drv.hfpll_data->l_offset);
}
static bool __cpuinit speed_equal(const struct core_speed *s1,
const struct core_speed *s2)
{
return (s1->pri_src_sel == s2->pri_src_sel &&
s1->pll_l_val == s2->pll_l_val);
}
static const struct acpu_level __cpuinit *find_cur_acpu_level(int cpu)
{
struct scalable *sc = &drv.scalable[cpu];
const struct acpu_level *l;
struct core_speed cur_speed;
fill_cur_core_speed(&cur_speed, sc);
for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++)
if (speed_equal(&l->speed, &cur_speed))
return l;
return NULL;
}
static const struct l2_level __init *find_cur_l2_level(void)
{
struct scalable *sc = &drv.scalable[L2];
const struct l2_level *l;
struct core_speed cur_speed;
fill_cur_core_speed(&cur_speed, sc);
for (l = drv.l2_freq_tbl; l->speed.khz != 0; l++)
if (speed_equal(&l->speed, &cur_speed))
return l;
return NULL;
}
static const struct acpu_level __cpuinit *find_min_acpu_level(void)
{
struct acpu_level *l;
for (l = drv.acpu_freq_tbl; l->speed.khz != 0; l++)
if (l->use_for_scaling)
return l;
return NULL;
}
static int __cpuinit per_cpu_init(int cpu)
{
struct scalable *sc = &drv.scalable[cpu];
const struct acpu_level *acpu_level;
int ret;
sc->hfpll_base = ioremap(sc->hfpll_phys_base, SZ_32);
if (!sc->hfpll_base) {
ret = -ENOMEM;
goto err_ioremap;
}
acpu_level = find_cur_acpu_level(cpu);
if (!acpu_level) {
acpu_level = find_min_acpu_level();
if (!acpu_level) {
ret = -ENODEV;
goto err_table;
}
dev_dbg(drv.dev, "CPU%d is running at an unknown rate. Defaulting to %lu KHz.\n",
cpu, acpu_level->speed.khz);
} else {
dev_dbg(drv.dev, "CPU%d is running at %lu KHz\n", cpu,
acpu_level->speed.khz);
}
ret = regulator_init(sc, acpu_level);
if (ret)
goto err_regulators;
ret = init_clock_sources(sc, &acpu_level->speed);
if (ret)
goto err_clocks;
sc->l2_vote = acpu_level->l2_level;
sc->initialized = true;
return 0;
err_clocks:
regulator_cleanup(sc);
err_regulators:
err_table:
iounmap(sc->hfpll_base);
err_ioremap:
return ret;
}
/* Register with bus driver. */
static void __init bus_init(const struct l2_level *l2_level)
{
int ret;
drv.bus_perf_client = msm_bus_scale_register_client(drv.bus_scale);
if (!drv.bus_perf_client) {
dev_err(drv.dev, "unable to register bus client\n");
BUG();
}
ret = msm_bus_scale_client_update_request(drv.bus_perf_client,
l2_level->bw_level);
if (ret)
dev_err(drv.dev, "initial bandwidth req failed (%d)\n", ret);
}
#ifdef CONFIG_CPU_FREQ_MSM
static struct cpufreq_frequency_table freq_table[NR_CPUS][35];
extern int console_batt_stat;
static void __init cpufreq_table_init(void)
{
int cpu;
for_each_possible_cpu(cpu) {
int i, freq_cnt = 0;
/* Construct the freq_table tables from acpu_freq_tbl. */
for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0
&& freq_cnt < ARRAY_SIZE(*freq_table); i++) {
if (drv.acpu_freq_tbl[i].use_for_scaling) {
#ifdef CONFIG_SEC_FACTORY
// if factory_condition, set the core freq limit.
//QMCK
if (console_set_on_cmdline && drv.acpu_freq_tbl[i].speed.khz > 1000000) {
if(console_batt_stat == 1) {
continue;
}
}
//QMCK
#endif
freq_table[cpu][freq_cnt].index = freq_cnt;
freq_table[cpu][freq_cnt].frequency
= drv.acpu_freq_tbl[i].speed.khz;
freq_cnt++;
}
}
/* freq_table not big enough to store all usable freqs. */
BUG_ON(drv.acpu_freq_tbl[i].speed.khz != 0);
freq_table[cpu][freq_cnt].index = freq_cnt;
freq_table[cpu][freq_cnt].frequency = CPUFREQ_TABLE_END;
dev_info(drv.dev, "CPU%d: %d frequencies supported\n",
cpu, freq_cnt);
/* Register table with CPUFreq. */
cpufreq_frequency_table_get_attr(freq_table[cpu], cpu);
}
}
#else
static void __init cpufreq_table_init(void) {}
#endif
static void __init dcvs_freq_init(void)
{
int i;
for (i = 0; drv.acpu_freq_tbl[i].speed.khz != 0; i++)
if (drv.acpu_freq_tbl[i].use_for_scaling)
msm_dcvs_register_cpu_freq(
drv.acpu_freq_tbl[i].speed.khz,
drv.acpu_freq_tbl[i].vdd_core / 1000);
}
static int __cpuinit acpuclk_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
static int prev_khz[NR_CPUS];
int rc, cpu = (int)hcpu;
struct scalable *sc = &drv.scalable[cpu];
unsigned long hot_unplug_khz = acpuclk_krait_data.power_collapse_khz;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_DEAD:
prev_khz[cpu] = acpuclk_krait_get_rate(cpu);
/* Fall through. */
case CPU_UP_CANCELED:
acpuclk_krait_set_rate(cpu, hot_unplug_khz, SETRATE_HOTPLUG);
regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg, 0);
break;
case CPU_UP_PREPARE:
if (!sc->initialized) {
rc = per_cpu_init(cpu);
if (rc)
return NOTIFY_BAD;
break;
}
if (WARN_ON(!prev_khz[cpu]))
return NOTIFY_BAD;
rc = regulator_set_optimum_mode(sc->vreg[VREG_CORE].reg,
sc->vreg[VREG_CORE].cur_ua);
if (rc < 0)
return NOTIFY_BAD;
acpuclk_krait_set_rate(cpu, prev_khz[cpu], SETRATE_HOTPLUG);
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata acpuclk_cpu_notifier = {
.notifier_call = acpuclk_cpu_callback,
};
static const int krait_needs_vmin(void)
{
switch (read_cpuid_id()) {
case 0x511F04D0: /* KR28M2A20 */
case 0x511F04D1: /* KR28M2A21 */
case 0x510F06F0: /* KR28M4A10 */
return 1;
default:
return 0;
};
}
static void krait_apply_vmin(struct acpu_level *tbl)
{
for (; tbl->speed.khz != 0; tbl++) {
if (tbl->vdd_core < 1150000)
tbl->vdd_core = 1150000;
tbl->avsdscr_setting = 0;
}
}
static int __init get_speed_bin(u32 pte_efuse)
{
uint32_t speed_bin;
speed_bin = pte_efuse & 0xF;
if (speed_bin == 0xF)
speed_bin = (pte_efuse >> 4) & 0xF;
if (speed_bin == 0xF) {
speed_bin = 0;
dev_warn(drv.dev, "SPEED BIN: Defaulting to %d\n", speed_bin);
} else {
dev_info(drv.dev, "SPEED BIN: %d\n", speed_bin);
}
return speed_bin;
}
static int __init get_pvs_bin(u32 pte_efuse)
{
uint32_t pvs_bin;
pvs_bin = (pte_efuse >> 10) & 0x7;
if (pvs_bin == 0x7)
pvs_bin = (pte_efuse >> 13) & 0x7;
if (pvs_bin == 0x7) {
pvs_bin = 0;
dev_warn(drv.dev, "ACPU PVS: Defaulting to %d\n", pvs_bin);
} else {
dev_info(drv.dev, "ACPU PVS: %d\n", pvs_bin);
}
return pvs_bin;
}
static struct pvs_table * __init select_freq_plan(u32 pte_efuse_phys,
struct pvs_table (*pvs_tables)[NUM_PVS])
{
void __iomem *pte_efuse;
u32 pte_efuse_val, tbl_idx, bin_idx;
pte_efuse = ioremap(pte_efuse_phys, 4);
if (!pte_efuse) {
dev_err(drv.dev, "Unable to map QFPROM base\n");
return NULL;
}
pte_efuse_val = readl_relaxed(pte_efuse);
iounmap(pte_efuse);
/* Select frequency tables. */
bin_idx = get_speed_bin(pte_efuse_val);
tbl_idx = get_pvs_bin(pte_efuse_val);
#ifdef CONFIG_SEC_DEBUG_SUBSYS
speed_bin = bin_idx;
pvs_bin = tbl_idx;
#endif
return &pvs_tables[bin_idx][tbl_idx];
}
static void __init drv_data_init(struct device *dev,
const struct acpuclk_krait_params *params)
{
struct pvs_table *pvs;
drv.dev = dev;
drv.scalable = kmemdup(params->scalable, params->scalable_size,
GFP_KERNEL);
BUG_ON(!drv.scalable);
drv.hfpll_data = kmemdup(params->hfpll_data, sizeof(*drv.hfpll_data),
GFP_KERNEL);
BUG_ON(!drv.hfpll_data);
drv.l2_freq_tbl = kmemdup(params->l2_freq_tbl, params->l2_freq_tbl_size,
GFP_KERNEL);
BUG_ON(!drv.l2_freq_tbl);
drv.bus_scale = kmemdup(params->bus_scale, sizeof(*drv.bus_scale),
GFP_KERNEL);
BUG_ON(!drv.bus_scale);
drv.bus_scale->usecase = kmemdup(drv.bus_scale->usecase,
drv.bus_scale->num_usecases * sizeof(*drv.bus_scale->usecase),
GFP_KERNEL);
BUG_ON(!drv.bus_scale->usecase);
pvs = select_freq_plan(params->pte_efuse_phys, params->pvs_tables);
BUG_ON(!pvs->table);
drv.acpu_freq_tbl = kmemdup(pvs->table, pvs->size, GFP_KERNEL);
BUG_ON(!drv.acpu_freq_tbl);
drv.boost_uv = pvs->boost_uv;
#ifdef CONFIG_SEC_DEBUG_SUBSYS
boost_uv = drv.boost_uv;
#endif
acpuclk_krait_data.power_collapse_khz = params->stby_khz;
acpuclk_krait_data.wait_for_irq_khz = params->stby_khz;
}
static void __init hw_init(void)
{
struct scalable *l2 = &drv.scalable[L2];
const struct l2_level *l2_level;
int cpu, rc;
if (krait_needs_vmin())
krait_apply_vmin(drv.acpu_freq_tbl);
l2->hfpll_base = ioremap(l2->hfpll_phys_base, SZ_32);
BUG_ON(!l2->hfpll_base);
rc = rpm_regulator_init(l2, VREG_HFPLL_A,
l2->vreg[VREG_HFPLL_A].max_vdd, false);
BUG_ON(rc);
rc = rpm_regulator_init(l2, VREG_HFPLL_B,
l2->vreg[VREG_HFPLL_B].max_vdd, false);
BUG_ON(rc);
l2_level = find_cur_l2_level();
if (!l2_level) {
l2_level = drv.l2_freq_tbl;
dev_dbg(drv.dev, "L2 is running at an unknown rate. Defaulting to %lu KHz.\n",
l2_level->speed.khz);
} else {
dev_dbg(drv.dev, "L2 is running at %lu KHz\n",
l2_level->speed.khz);
}
rc = init_clock_sources(l2, &l2_level->speed);
BUG_ON(rc);
for_each_online_cpu(cpu) {
rc = per_cpu_init(cpu);
BUG_ON(rc);
}
bus_init(l2_level);
}
int __init acpuclk_krait_init(struct device *dev,
const struct acpuclk_krait_params *params)
{
drv_data_init(dev, params);
hw_init();
cpufreq_table_init();
dcvs_freq_init();
acpuclk_register(&acpuclk_krait_data);
register_hotcpu_notifier(&acpuclk_cpu_notifier);
return 0;
}
| cnexus/NexTKernel-d2spr | arch/arm/mach-msm/acpuclock-krait.c | C | gpl-2.0 | 31,611 |
package org.erc.qmm.mq;
import java.util.EventListener;
/**
* The listener interface for receiving messageReaded events.
* The class that is interested in processing a messageReaded
* event implements this interface, and the object created
* with that class is registered with a component using the
* component's <code>addMessageReadedListener<code> method. When
* the messageReaded event occurs, that object's appropriate
* method is invoked.
*
* @see MessageReadedEvent
*/
public interface MessageReadedListener extends EventListener {
/**
* Message readed.
*
* @param message the message
*/
void messageReaded(JMQMessage message);
}
| dubasdey/MQQueueMonitor | src/main/java/org/erc/qmm/mq/MessageReadedListener.java | Java | gpl-2.0 | 659 |
import re
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
print re.DOTALL
print "p.pattern:", p.pattern
print "p.flags:", p.flags
print "p.groups:", p.groups
print "p.groupindex:", p.groupindex
| solvery/lang-features | python/use_lib/re.4.py | Python | gpl-2.0 | 204 |
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/jiffies.h>
#include <linux/uaccess.h>
#include <linux/atomic.h>
#include <linux/wait.h>
#include <sound/apr_audio-v2.h>
#include <linux/qdsp6v2/apr.h>
#include <sound/q6adm-v2.h>
#include <sound/q6audio-v2.h>
#include <sound/q6afe-v2.h>
#include <sound/hw_audio_log.h>
#include "audio_acdb.h"
#define TIMEOUT_MS 1000
#define RESET_COPP_ID 99
#define INVALID_COPP_ID 0xFF
/* Used for inband payload copy, max size is 4k */
/* 2 is to account for module & param ID in payload */
#define ADM_GET_PARAMETER_LENGTH (4096 - APR_HDR_SIZE - 2 * sizeof(uint32_t))
#define ULL_SUPPORTED_SAMPLE_RATE 48000
enum {
ADM_RX_AUDPROC_CAL,
ADM_TX_AUDPROC_CAL,
ADM_RX_AUDVOL_CAL,
ADM_TX_AUDVOL_CAL,
ADM_CUSTOM_TOP_CAL,
ADM_RTAC,
ADM_MAX_CAL_TYPES
};
struct adm_ctl {
void *apr;
atomic_t copp_id[AFE_MAX_PORTS];
atomic_t copp_cnt[AFE_MAX_PORTS];
atomic_t copp_low_latency_id[AFE_MAX_PORTS];
atomic_t copp_low_latency_cnt[AFE_MAX_PORTS];
atomic_t copp_perf_mode[AFE_MAX_PORTS];
atomic_t copp_stat[AFE_MAX_PORTS];
wait_queue_head_t wait[AFE_MAX_PORTS];
struct acdb_cal_block mem_addr_audproc[MAX_AUDPROC_TYPES];
struct acdb_cal_block mem_addr_audvol[MAX_AUDPROC_TYPES];
atomic_t mem_map_cal_handles[ADM_MAX_CAL_TYPES];
atomic_t mem_map_cal_index;
int set_custom_topology;
int ec_ref_rx;
};
static struct adm_ctl this_adm;
struct adm_multi_ch_map {
bool set_channel_map;
char channel_mapping[PCM_FORMAT_MAX_NUM_CHANNEL];
};
static struct adm_multi_ch_map multi_ch_map = { false,
{0, 0, 0, 0, 0, 0, 0, 0}
};
static int adm_get_parameters[ADM_GET_PARAMETER_LENGTH];
int srs_trumedia_open(int port_id, int srs_tech_id, void *srs_params)
{
struct adm_cmd_set_pp_params_inband_v5 *adm_params = NULL;
int ret = 0, sz = 0;
int index;
ad_logd("SRS - %s", __func__);
switch (srs_tech_id) {
case SRS_ID_GLOBAL: {
struct srs_trumedia_params_GLOBAL *glb_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_GLOBAL);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_GLOBAL) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_GLOBAL);
glb_params = (struct srs_trumedia_params_GLOBAL *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(glb_params, srs_params,
sizeof(struct srs_trumedia_params_GLOBAL));
ad_logd("SRS - %s: Global params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x\n",
__func__, (int)glb_params->v1,
(int)glb_params->v2, (int)glb_params->v3,
(int)glb_params->v4, (int)glb_params->v5,
(int)glb_params->v6, (int)glb_params->v7,
(int)glb_params->v8);
break;
}
case SRS_ID_WOWHD: {
struct srs_trumedia_params_WOWHD *whd_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_WOWHD);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_WOWHD) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_WOWHD;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_WOWHD);
whd_params = (struct srs_trumedia_params_WOWHD *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(whd_params, srs_params,
sizeof(struct srs_trumedia_params_WOWHD));
ad_logd("SRS - %s: WOWHD params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x, 10 = %x, 11 = %x\n",
__func__, (int)whd_params->v1,
(int)whd_params->v2, (int)whd_params->v3,
(int)whd_params->v4, (int)whd_params->v5,
(int)whd_params->v6, (int)whd_params->v7,
(int)whd_params->v8, (int)whd_params->v9,
(int)whd_params->v10, (int)whd_params->v11);
break;
}
case SRS_ID_CSHP: {
struct srs_trumedia_params_CSHP *chp_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_CSHP);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_CSHP) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_CSHP;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_CSHP);
chp_params = (struct srs_trumedia_params_CSHP *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(chp_params, srs_params,
sizeof(struct srs_trumedia_params_CSHP));
ad_logd("SRS - %s: CSHP params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x, 8 = %x, 9 = %x\n",
__func__, (int)chp_params->v1,
(int)chp_params->v2, (int)chp_params->v3,
(int)chp_params->v4, (int)chp_params->v5,
(int)chp_params->v6, (int)chp_params->v7,
(int)chp_params->v8, (int)chp_params->v9);
break;
}
case SRS_ID_HPF: {
struct srs_trumedia_params_HPF *hpf_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_HPF);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_HPF) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HPF;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_HPF);
hpf_params = (struct srs_trumedia_params_HPF *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(hpf_params, srs_params,
sizeof(struct srs_trumedia_params_HPF));
ad_logd("SRS - %s: HPF params - 1 = %x\n", __func__,
(int)hpf_params->v1);
break;
}
case SRS_ID_PEQ: {
struct srs_trumedia_params_PEQ *peq_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_PEQ);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_PEQ) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_PEQ;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_PEQ);
peq_params = (struct srs_trumedia_params_PEQ *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(peq_params, srs_params,
sizeof(struct srs_trumedia_params_PEQ));
ad_logd("SRS - %s: PEQ params - 1 = %x 2 = %x, 3 = %x, 4 = %x\n",
__func__, (int)peq_params->v1,
(int)peq_params->v2, (int)peq_params->v3,
(int)peq_params->v4);
break;
}
case SRS_ID_HL: {
struct srs_trumedia_params_HL *hl_params = NULL;
sz = sizeof(struct adm_cmd_set_pp_params_inband_v5) +
sizeof(struct srs_trumedia_params_HL);
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n",
__func__);
return -ENOMEM;
}
adm_params->payload_size =
sizeof(struct srs_trumedia_params_HL) +
sizeof(struct adm_param_data_v5);
adm_params->params.param_id = SRS_TRUMEDIA_PARAMS_HL;
adm_params->params.param_size =
sizeof(struct srs_trumedia_params_HL);
hl_params = (struct srs_trumedia_params_HL *)
((u8 *)adm_params +
sizeof(struct adm_cmd_set_pp_params_inband_v5));
memcpy(hl_params, srs_params,
sizeof(struct srs_trumedia_params_HL));
ad_logd("SRS - %s: HL params - 1 = %x, 2 = %x, 3 = %x, 4 = %x, 5 = %x, 6 = %x, 7 = %x\n",
__func__, (int)hl_params->v1,
(int)hl_params->v2, (int)hl_params->v3,
(int)hl_params->v4, (int)hl_params->v5,
(int)hl_params->v6, (int)hl_params->v7);
break;
}
default:
goto fail_cmd;
}
adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
adm_params->hdr.pkt_size = sz;
adm_params->hdr.src_svc = APR_SVC_ADM;
adm_params->hdr.src_domain = APR_DOMAIN_APPS;
adm_params->hdr.src_port = port_id;
adm_params->hdr.dest_svc = APR_SVC_ADM;
adm_params->hdr.dest_domain = APR_DOMAIN_ADSP;
index = afe_get_port_index(port_id);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d portid %#x\n",
__func__, index, port_id);
ret = -EINVAL;
goto fail_cmd;
}
adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
adm_params->hdr.token = port_id;
adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5;
adm_params->payload_addr_lsw = 0;
adm_params->payload_addr_msw = 0;
adm_params->mem_map_handle = 0;
adm_params->params.module_id = SRS_TRUMEDIA_MODULE_ID;
adm_params->params.reserved = 0;
ad_logd("SRS - %s: Command was sent now check Q6 - port id = %d, size %d, module id %x, param id %x.\n",
__func__, adm_params->hdr.dest_port,
adm_params->payload_size, adm_params->params.module_id,
adm_params->params.param_id);
ret = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params);
if (ret < 0) {
ad_loge("SRS - %s: ADM enable for port %d failed\n", __func__,
port_id);
ret = -EINVAL;
goto fail_cmd;
}
/* Wait for the callback with copp id */
ret = wait_event_timeout(this_adm.wait[index], 1,
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ad_loge("%s: SRS set params timed out port = %d\n",
__func__, port_id);
ret = -EINVAL;
goto fail_cmd;
}
fail_cmd:
kfree(adm_params);
return ret;
}
int adm_set_stereo_to_custom_stereo(int port_id, unsigned int session_id,
char *params, uint32_t params_length)
{
struct adm_cmd_set_pspd_mtmx_strtr_params_v5 *adm_params = NULL;
int sz, rc = 0, index = afe_get_port_index(port_id);
ad_logd("%s\n", __func__);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d port_id %#x\n", __func__, index,
port_id);
return -EINVAL;
}
sz = sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5) +
params_length;
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed\n", __func__);
return -ENOMEM;
}
memcpy(((u8 *)adm_params +
sizeof(struct adm_cmd_set_pspd_mtmx_strtr_params_v5)),
params, params_length);
adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
adm_params->hdr.pkt_size = sz;
adm_params->hdr.src_svc = APR_SVC_ADM;
adm_params->hdr.src_domain = APR_DOMAIN_APPS;
adm_params->hdr.src_port = port_id;
adm_params->hdr.dest_svc = APR_SVC_ADM;
adm_params->hdr.dest_domain = APR_DOMAIN_ADSP;
adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
adm_params->hdr.token = port_id;
adm_params->hdr.opcode = ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5;
adm_params->payload_addr_lsw = 0;
adm_params->payload_addr_msw = 0;
adm_params->mem_map_handle = 0;
adm_params->payload_size = params_length;
/* direction RX as 0 */
adm_params->direction = 0;
/* session id for this cmd to be applied on */
adm_params->sessionid = session_id;
/* valid COPP id for LPCM */
adm_params->deviceid = atomic_read(&this_adm.copp_id[index]);
adm_params->reserved = 0;
ad_logd("%s: deviceid %d, session_id %d, src_port %d, dest_port %d\n",
__func__, adm_params->deviceid, adm_params->sessionid,
adm_params->hdr.src_port, adm_params->hdr.dest_port);
atomic_set(&this_adm.copp_stat[index], 0);
rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params);
if (rc < 0) {
ad_loge("%s: Set params failed port = %#x\n",
__func__, port_id);
rc = -EINVAL;
goto set_stereo_to_custom_stereo_return;
}
/* Wait for the callback */
rc = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!rc) {
ad_loge("%s: Set params timed out port = %#x\n", __func__,
port_id);
rc = -EINVAL;
goto set_stereo_to_custom_stereo_return;
}
rc = 0;
set_stereo_to_custom_stereo_return:
kfree(adm_params);
return rc;
}
int adm_dolby_dap_send_params(int port_id, char *params, uint32_t params_length)
{
struct adm_cmd_set_pp_params_v5 *adm_params = NULL;
int sz, rc = 0, index = afe_get_port_index(port_id);
ad_logd("%s\n", __func__);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d portid %#x\n",
__func__, index, port_id);
return -EINVAL;
}
sz = sizeof(struct adm_cmd_set_pp_params_v5) + params_length;
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed", __func__);
return -ENOMEM;
}
memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_set_pp_params_v5)),
params, params_length);
adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
adm_params->hdr.pkt_size = sz;
adm_params->hdr.src_svc = APR_SVC_ADM;
adm_params->hdr.src_domain = APR_DOMAIN_APPS;
adm_params->hdr.src_port = port_id;
adm_params->hdr.dest_svc = APR_SVC_ADM;
adm_params->hdr.dest_domain = APR_DOMAIN_ADSP;
adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
adm_params->hdr.token = port_id;
adm_params->hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5;
adm_params->payload_addr_lsw = 0;
adm_params->payload_addr_msw = 0;
adm_params->mem_map_handle = 0;
adm_params->payload_size = params_length;
atomic_set(&this_adm.copp_stat[index], 0);
rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params);
if (rc < 0) {
ad_loge("%s: Set params failed port = %#x\n",
__func__, port_id);
rc = -EINVAL;
goto dolby_dap_send_param_return;
}
/* Wait for the callback */
rc = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!rc) {
ad_loge("%s: Set params timed out port = %#x\n",
__func__, port_id);
rc = -EINVAL;
goto dolby_dap_send_param_return;
}
rc = 0;
dolby_dap_send_param_return:
kfree(adm_params);
return rc;
}
int adm_get_params(int port_id, uint32_t module_id, uint32_t param_id,
uint32_t params_length, char *params)
{
struct adm_cmd_get_pp_params_v5 *adm_params = NULL;
int sz, rc = 0, i = 0, index = afe_get_port_index(port_id);
int *params_data = (int *)params;
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d portid %#x\n",
__func__, index, port_id);
return -EINVAL;
}
sz = sizeof(struct adm_cmd_get_pp_params_v5) + params_length;
adm_params = kzalloc(sz, GFP_KERNEL);
if (!adm_params) {
ad_loge("%s, adm params memory alloc failed", __func__);
return -ENOMEM;
}
memcpy(((u8 *)adm_params + sizeof(struct adm_cmd_get_pp_params_v5)),
params, params_length);
adm_params->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
adm_params->hdr.pkt_size = sz;
adm_params->hdr.src_svc = APR_SVC_ADM;
adm_params->hdr.src_domain = APR_DOMAIN_APPS;
adm_params->hdr.src_port = port_id;
adm_params->hdr.dest_svc = APR_SVC_ADM;
adm_params->hdr.dest_domain = APR_DOMAIN_ADSP;
adm_params->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
adm_params->hdr.token = port_id;
adm_params->hdr.opcode = ADM_CMD_GET_PP_PARAMS_V5;
adm_params->data_payload_addr_lsw = 0;
adm_params->data_payload_addr_msw = 0;
adm_params->mem_map_handle = 0;
adm_params->module_id = module_id;
adm_params->param_id = param_id;
adm_params->param_max_size = params_length;
adm_params->reserved = 0;
atomic_set(&this_adm.copp_stat[index], 0);
rc = apr_send_pkt(this_adm.apr, (uint32_t *)adm_params);
if (rc < 0) {
ad_loge("%s: Failed to Get Params on port %d\n", __func__,
port_id);
rc = -EINVAL;
goto adm_get_param_return;
}
/* Wait for the callback with copp id */
rc = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!rc) {
ad_loge("%s: get params timed out port = %d\n", __func__,
port_id);
rc = -EINVAL;
goto adm_get_param_return;
}
if ((params_data) && (ARRAY_SIZE(adm_get_parameters) >=
(1+adm_get_parameters[0])) &&
(params_length/sizeof(int) >=
adm_get_parameters[0])) {
for (i = 0; i < adm_get_parameters[0]; i++)
params_data[i] = adm_get_parameters[1+i];
} else {
pr_err("%s: Get param data not copied! get_param array size %zd, index %d, params array size %zd, index %d\n",
__func__, ARRAY_SIZE(adm_get_parameters),
(1+adm_get_parameters[0]),
params_length/sizeof(int),
adm_get_parameters[0]);
}
rc = 0;
adm_get_param_return:
kfree(adm_params);
return rc;
}
static void adm_callback_debug_print(struct apr_client_data *data)
{
uint32_t *payload;
payload = data->payload;
if (data->payload_size >= 8)
ad_logd("%s: code = 0x%x PL#0[%x], PL#1[%x], size = %d\n",
__func__, data->opcode, payload[0], payload[1],
data->payload_size);
else if (data->payload_size >= 4)
ad_logd("%s: code = 0x%x PL#0[%x], size = %d\n",
__func__, data->opcode, payload[0],
data->payload_size);
else
ad_logd("%s: code = 0x%x, size = %d\n",
__func__, data->opcode, data->payload_size);
}
void adm_set_multi_ch_map(char *channel_map)
{
memcpy(multi_ch_map.channel_mapping, channel_map,
PCM_FORMAT_MAX_NUM_CHANNEL);
multi_ch_map.set_channel_map = true;
}
void adm_get_multi_ch_map(char *channel_map)
{
if (multi_ch_map.set_channel_map) {
memcpy(channel_map, multi_ch_map.channel_mapping,
PCM_FORMAT_MAX_NUM_CHANNEL);
}
}
static int32_t adm_callback(struct apr_client_data *data, void *priv)
{
uint32_t *payload;
int i, index;
if (data == NULL) {
ad_loge("%s: data paramter is null\n", __func__);
return -EINVAL;
}
payload = data->payload;
if (data->opcode == RESET_EVENTS) {
ad_logd("adm_callback: Reset event is received: %d %d apr[%p]\n",
data->reset_event, data->reset_proc,
this_adm.apr);
if (this_adm.apr) {
apr_reset(this_adm.apr);
for (i = 0; i < AFE_MAX_PORTS; i++) {
atomic_set(&this_adm.copp_id[i],
RESET_COPP_ID);
atomic_set(&this_adm.copp_low_latency_id[i],
RESET_COPP_ID);
atomic_set(&this_adm.copp_cnt[i], 0);
atomic_set(&this_adm.copp_low_latency_cnt[i],
0);
atomic_set(&this_adm.copp_perf_mode[i], 0);
atomic_set(&this_adm.copp_stat[i], 0);
}
this_adm.apr = NULL;
reset_custom_topology_flags();
this_adm.set_custom_topology = 1;
for (i = 0; i < ADM_MAX_CAL_TYPES; i++)
atomic_set(&this_adm.mem_map_cal_handles[i],
0);
rtac_clear_mapping(ADM_RTAC_CAL);
}
ad_logd("Resetting calibration blocks");
for (i = 0; i < MAX_AUDPROC_TYPES; i++) {
/* Device calibration */
this_adm.mem_addr_audproc[i].cal_size = 0;
this_adm.mem_addr_audproc[i].cal_kvaddr = 0;
this_adm.mem_addr_audproc[i].cal_paddr = 0;
/* Volume calibration */
this_adm.mem_addr_audvol[i].cal_size = 0;
this_adm.mem_addr_audvol[i].cal_kvaddr = 0;
this_adm.mem_addr_audvol[i].cal_paddr = 0;
}
return 0;
}
adm_callback_debug_print(data);
if (data->payload_size) {
index = q6audio_get_port_index(data->token);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d token %d\n",
__func__, index, data->token);
return 0;
}
if (data->opcode == APR_BASIC_RSP_RESULT) {
ad_logd("APR_BASIC_RSP_RESULT id %x\n", payload[0]);
if (payload[1] != 0) {
ad_loge("%s: cmd = 0x%x returned error = 0x%x\n",
__func__, payload[0], payload[1]);
}
switch (payload[0]) {
case ADM_CMD_SET_PP_PARAMS_V5:
ad_logd("%s: ADM_CMD_SET_PP_PARAMS_V5\n",
__func__);
if (rtac_make_adm_callback(
payload, data->payload_size)) {
break;
}
case ADM_CMD_DEVICE_CLOSE_V5:
case ADM_CMD_SHARED_MEM_UNMAP_REGIONS:
case ADM_CMD_MATRIX_MAP_ROUTINGS_V5:
case ADM_CMD_ADD_TOPOLOGIES:
ad_logd("%s: Basic callback received, wake up.\n",
__func__);
atomic_set(&this_adm.copp_stat[index], 1);
wake_up(&this_adm.wait[index]);
break;
case ADM_CMD_SHARED_MEM_MAP_REGIONS:
ad_logd("%s: ADM_CMD_SHARED_MEM_MAP_REGIONS\n",
__func__);
/* Should only come here if there is an APR */
/* error or malformed APR packet. Otherwise */
/* response will be returned as */
if (payload[1] != 0) {
ad_loge("%s: ADM map error, resuming\n",
__func__);
atomic_set(&this_adm.copp_stat[index],
1);
wake_up(&this_adm.wait[index]);
}
break;
case ADM_CMD_GET_PP_PARAMS_V5:
ad_logd("%s: ADM_CMD_GET_PP_PARAMS_V5\n",
__func__);
/* Should only come here if there is an APR */
/* error or malformed APR packet. Otherwise */
/* response will be returned as */
/* ADM_CMDRSP_GET_PP_PARAMS_V5 */
if (payload[1] != 0) {
ad_loge("%s: ADM get param error = %d, resuming\n",
__func__, payload[1]);
rtac_make_adm_callback(payload,
data->payload_size);
}
break;
case ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5:
ad_logd("%s:ADM_CMD_SET_PSPD_MTMX_STRTR_PARAMS_V5\n",
__func__);
atomic_set(&this_adm.copp_stat[index], 1);
wake_up(&this_adm.wait[index]);
break;
default:
ad_loge("%s: Unknown Cmd: 0x%x\n", __func__,
payload[0]);
break;
}
return 0;
}
switch (data->opcode) {
case ADM_CMDRSP_DEVICE_OPEN_V5: {
struct adm_cmd_rsp_device_open_v5 *open =
(struct adm_cmd_rsp_device_open_v5 *)data->payload;
if (open->copp_id == INVALID_COPP_ID) {
ad_loge("%s: invalid coppid rxed %d\n",
__func__, open->copp_id);
atomic_set(&this_adm.copp_stat[index], 1);
wake_up(&this_adm.wait[index]);
break;
}
if (atomic_read(&this_adm.copp_perf_mode[index])) {
atomic_set(&this_adm.copp_low_latency_id[index],
open->copp_id);
} else {
atomic_set(&this_adm.copp_id[index],
open->copp_id);
}
atomic_set(&this_adm.copp_stat[index], 1);
ad_logd("%s: coppid rxed=%d\n", __func__,
open->copp_id);
wake_up(&this_adm.wait[index]);
}
break;
case ADM_CMDRSP_GET_PP_PARAMS_V5:
ad_logd("%s: ADM_CMDRSP_GET_PP_PARAMS_V5\n", __func__);
if (payload[0] != 0)
ad_loge("%s: ADM_CMDRSP_GET_PP_PARAMS_V5 returned error = 0x%x\n",
__func__, payload[0]);
if (rtac_make_adm_callback(payload,
data->payload_size))
break;
if ((payload[0] == 0) && (data->payload_size >
(4 * sizeof(*payload))) &&
(data->payload_size/sizeof(*payload)-4 >=
payload[3]) &&
(ARRAY_SIZE(adm_get_parameters)-1 >=
payload[3])) {
adm_get_parameters[0] = payload[3];
pr_debug("%s: GET_PP PARAM:received parameter length: 0x%x\n",
__func__, adm_get_parameters[0]);
/* storing param size then params */
for (i = 0; i < payload[3]; i++)
adm_get_parameters[1+i] = payload[4+i];
} else {
adm_get_parameters[0] = -1;
pr_err("%s: GET_PP_PARAMS failed, setting size to %d\n",
__func__, adm_get_parameters[0]);
}
atomic_set(&this_adm.copp_stat[index], 1);
wake_up(&this_adm.wait[index]);
break;
case ADM_CMDRSP_SHARED_MEM_MAP_REGIONS:
ad_logd("%s: ADM_CMDRSP_SHARED_MEM_MAP_REGIONS\n",
__func__);
atomic_set(&this_adm.mem_map_cal_handles[
atomic_read(&this_adm.mem_map_cal_index)],
*payload);
atomic_set(&this_adm.copp_stat[index], 1);
wake_up(&this_adm.wait[index]);
break;
default:
ad_loge("%s: Unknown cmd:0x%x\n", __func__,
data->opcode);
break;
}
}
return 0;
}
void send_adm_custom_topology(int port_id)
{
struct acdb_cal_block cal_block;
struct cmd_set_topologies adm_top;
int index;
int result;
int size = 4096;
get_adm_custom_topology(&cal_block);
if (cal_block.cal_size == 0) {
ad_logd("%s: no cal to send addr= 0x%pa\n",
__func__, &cal_block.cal_paddr);
goto done;
}
index = afe_get_port_index(port_id);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d portid %#x\n",
__func__, index, port_id);
goto done;
}
if (this_adm.set_custom_topology) {
/* specific index 4 for adm topology memory */
atomic_set(&this_adm.mem_map_cal_index, ADM_CUSTOM_TOP_CAL);
/* Only call this once */
this_adm.set_custom_topology = 0;
result = adm_memory_map_regions(port_id,
&cal_block.cal_paddr, 0, &size, 1);
if (result < 0) {
ad_loge("%s: mmap did not work! addr = 0x%pa, size = %zd\n",
__func__, &cal_block.cal_paddr,
cal_block.cal_size);
goto done;
}
}
adm_top.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(20), APR_PKT_VER);
adm_top.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(adm_top));
adm_top.hdr.src_svc = APR_SVC_ADM;
adm_top.hdr.src_domain = APR_DOMAIN_APPS;
adm_top.hdr.src_port = port_id;
adm_top.hdr.dest_svc = APR_SVC_ADM;
adm_top.hdr.dest_domain = APR_DOMAIN_ADSP;
adm_top.hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
adm_top.hdr.token = port_id;
adm_top.hdr.opcode = ADM_CMD_ADD_TOPOLOGIES;
adm_top.payload_addr_lsw = lower_32_bits(cal_block.cal_paddr);
adm_top.payload_addr_msw = upper_32_bits(cal_block.cal_paddr);
adm_top.mem_map_handle =
atomic_read(&this_adm.mem_map_cal_handles[ADM_CUSTOM_TOP_CAL]);
adm_top.payload_size = cal_block.cal_size;
atomic_set(&this_adm.copp_stat[index], 0);
ad_logd("%s: Sending ADM_CMD_ADD_TOPOLOGIES payload = 0x%x, size = %d\n",
__func__, adm_top.payload_addr_lsw,
adm_top.payload_size);
result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_top);
if (result < 0) {
ad_loge("%s: Set topologies failed port = 0x%x payload = 0x%pa\n",
__func__, port_id, &cal_block.cal_paddr);
goto done;
}
/* Wait for the callback */
result = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!result) {
ad_loge("%s: Set topologies timed out port = 0x%x, payload = 0x%pa\n",
__func__, port_id, &cal_block.cal_paddr);
goto done;
}
done:
return;
}
static int send_adm_cal_block(int port_id, struct acdb_cal_block *aud_cal,
int perf_mode)
{
s32 result = 0;
struct adm_cmd_set_pp_params_v5 adm_params;
int index = afe_get_port_index(port_id);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d portid %#x\n",
__func__, index, port_id);
return 0;
}
ad_logd("%s: Port id %#x, index %d\n", __func__, port_id, index);
if (!aud_cal || aud_cal->cal_size == 0) {
ad_logd("%s: No ADM cal to send for port_id = %#x!\n",
__func__, port_id);
result = -EINVAL;
goto done;
}
adm_params.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(20), APR_PKT_VER);
adm_params.hdr.pkt_size = APR_PKT_SIZE(APR_HDR_SIZE,
sizeof(adm_params));
adm_params.hdr.src_svc = APR_SVC_ADM;
adm_params.hdr.src_domain = APR_DOMAIN_APPS;
adm_params.hdr.src_port = port_id;
adm_params.hdr.dest_svc = APR_SVC_ADM;
adm_params.hdr.dest_domain = APR_DOMAIN_ADSP;
if (perf_mode == LEGACY_PCM_MODE)
adm_params.hdr.dest_port =
atomic_read(&this_adm.copp_id[index]);
else
adm_params.hdr.dest_port =
atomic_read(&this_adm.copp_low_latency_id[index]);
adm_params.hdr.token = port_id;
adm_params.hdr.opcode = ADM_CMD_SET_PP_PARAMS_V5;
adm_params.payload_addr_lsw = lower_32_bits(aud_cal->cal_paddr);
adm_params.payload_addr_msw = upper_32_bits(aud_cal->cal_paddr);
adm_params.mem_map_handle = atomic_read(&this_adm.mem_map_cal_handles[
atomic_read(&this_adm.mem_map_cal_index)]);
adm_params.payload_size = aud_cal->cal_size;
atomic_set(&this_adm.copp_stat[index], 0);
ad_logd("%s: Sending SET_PARAMS payload = 0x%x, size = %d\n",
__func__, adm_params.payload_addr_lsw,
adm_params.payload_size);
result = apr_send_pkt(this_adm.apr, (uint32_t *)&adm_params);
if (result < 0) {
ad_loge("%s: Set params failed port = %#x payload = 0x%pa\n",
__func__, port_id, &aud_cal->cal_paddr);
result = -EINVAL;
goto done;
}
/* Wait for the callback */
result = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!result) {
ad_loge("%s: Set params timed out port = %#x, payload = 0x%pa\n",
__func__, port_id, &aud_cal->cal_paddr);
result = -EINVAL;
goto done;
}
result = 0;
done:
return result;
}
static void send_adm_cal(int port_id, int path, int perf_mode)
{
int result = 0;
s32 acdb_path;
struct acdb_cal_block aud_cal;
int size;
ad_logd("%s\n", __func__);
/* Maps audio_dev_ctrl path definition to ACDB definition */
acdb_path = path - 1;
if (acdb_path == TX_CAL)
size = 4096 * 4;
else
size = 4096;
ad_logd("%s: Sending audproc cal\n", __func__);
get_audproc_cal(acdb_path, &aud_cal);
/* map & cache buffers used */
atomic_set(&this_adm.mem_map_cal_index, acdb_path);
if (((this_adm.mem_addr_audproc[acdb_path].cal_paddr !=
aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) ||
(aud_cal.cal_size >
this_adm.mem_addr_audproc[acdb_path].cal_size)) {
if (this_adm.mem_addr_audproc[acdb_path].cal_paddr != 0)
adm_memory_unmap_regions(port_id);
result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr,
0, &size, 1);
if (result < 0) {
ad_loge("ADM audproc mmap did not work! path = %d, addr = 0x%pa, size = %zd\n",
acdb_path, &aud_cal.cal_paddr,
aud_cal.cal_size);
} else {
this_adm.mem_addr_audproc[acdb_path].cal_paddr =
aud_cal.cal_paddr;
this_adm.mem_addr_audproc[acdb_path].cal_size = size;
}
}
if (!send_adm_cal_block(port_id, &aud_cal, perf_mode))
ad_logd("%s: Audproc cal sent for port id: %#x, path %d\n",
__func__, port_id, acdb_path);
else
ad_logd("%s: Audproc cal not sent for port id: %#x, path %d\n",
__func__, port_id, acdb_path);
ad_logd("%s: Sending audvol cal\n", __func__);
get_audvol_cal(acdb_path, &aud_cal);
/* map & cache buffers used */
atomic_set(&this_adm.mem_map_cal_index,
(acdb_path + MAX_AUDPROC_TYPES));
if (((this_adm.mem_addr_audvol[acdb_path].cal_paddr !=
aud_cal.cal_paddr) && (aud_cal.cal_size > 0)) ||
(aud_cal.cal_size >
this_adm.mem_addr_audvol[acdb_path].cal_size)) {
if (this_adm.mem_addr_audvol[acdb_path].cal_paddr != 0)
adm_memory_unmap_regions(port_id);
result = adm_memory_map_regions(port_id, &aud_cal.cal_paddr,
0, &size, 1);
if (result < 0) {
ad_loge("ADM audvol mmap did not work! path = %d, addr = 0x%pa, size = %zd\n",
acdb_path, &aud_cal.cal_paddr,
aud_cal.cal_size);
} else {
this_adm.mem_addr_audvol[acdb_path].cal_paddr =
aud_cal.cal_paddr;
this_adm.mem_addr_audvol[acdb_path].cal_size = size;
}
}
if (!send_adm_cal_block(port_id, &aud_cal, perf_mode))
ad_logd("%s: Audvol cal sent for port id: %#x, path %d\n",
__func__, port_id, acdb_path);
else
ad_logd("%s: Audvol cal not sent for port id: %#x, path %d\n",
__func__, port_id, acdb_path);
}
int adm_map_rtac_block(struct rtac_cal_block_data *cal_block)
{
int result = 0;
ad_logd("%s\n", __func__);
if (cal_block == NULL) {
ad_loge("%s: cal_block is NULL!\n",
__func__);
result = -EINVAL;
goto done;
}
if (cal_block->cal_data.paddr == 0) {
ad_logd("%s: No address to map!\n",
__func__);
result = -EINVAL;
goto done;
}
if (cal_block->map_data.map_size == 0) {
ad_logd("%s: map size is 0!\n",
__func__);
result = -EINVAL;
goto done;
}
/* valid port ID needed for callback use primary I2S */
atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC);
result = adm_memory_map_regions(PRIMARY_I2S_RX,
&cal_block->cal_data.paddr, 0,
&cal_block->map_data.map_size, 1);
if (result < 0) {
ad_loge("%s: RTAC mmap did not work! addr = 0x%pa, size = %d\n",
__func__, &cal_block->cal_data.paddr,
cal_block->map_data.map_size);
goto done;
}
cal_block->map_data.map_handle = atomic_read(
&this_adm.mem_map_cal_handles[ADM_RTAC]);
done:
return result;
}
int adm_unmap_rtac_block(uint32_t *mem_map_handle)
{
int result = 0;
ad_logd("%s\n", __func__);
if (mem_map_handle == NULL) {
ad_logd("%s: Map handle is NULL, nothing to unmap\n",
__func__);
goto done;
}
if (*mem_map_handle == 0) {
ad_logd("%s: Map handle is 0, nothing to unmap\n",
__func__);
goto done;
}
if (*mem_map_handle != atomic_read(
&this_adm.mem_map_cal_handles[ADM_RTAC])) {
ad_loge("%s: Map handles do not match! Unmapping RTAC, RTAC map 0x%x, ADM map 0x%x\n",
__func__, *mem_map_handle, atomic_read(
&this_adm.mem_map_cal_handles[ADM_RTAC]));
/* if mismatch use handle passed in to unmap */
atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC],
*mem_map_handle);
}
/* valid port ID needed for callback use primary I2S */
atomic_set(&this_adm.mem_map_cal_index, ADM_RTAC);
result = adm_memory_unmap_regions(PRIMARY_I2S_RX);
if (result < 0) {
ad_logd("%s: adm_memory_unmap_regions failed, error %d\n",
__func__, result);
} else {
atomic_set(&this_adm.mem_map_cal_handles[ADM_RTAC], 0);
*mem_map_handle = 0;
}
done:
return result;
}
int adm_unmap_cal_blocks(void)
{
int i;
int result = 0;
int result2 = 0;
for (i = 0; i < ADM_MAX_CAL_TYPES; i++) {
if (atomic_read(&this_adm.mem_map_cal_handles[i]) != 0) {
if (i <= ADM_TX_AUDPROC_CAL) {
this_adm.mem_addr_audproc[i].cal_paddr = 0;
this_adm.mem_addr_audproc[i].cal_size = 0;
} else if (i <= ADM_TX_AUDVOL_CAL) {
this_adm.mem_addr_audvol
[(i - ADM_RX_AUDVOL_CAL)].cal_paddr
= 0;
this_adm.mem_addr_audvol
[(i - ADM_RX_AUDVOL_CAL)].cal_size
= 0;
} else if (i == ADM_CUSTOM_TOP_CAL) {
this_adm.set_custom_topology = 1;
} else {
continue;
}
/* valid port ID needed for callback use primary I2S */
atomic_set(&this_adm.mem_map_cal_index, i);
result2 = adm_memory_unmap_regions(PRIMARY_I2S_RX);
if (result2 < 0) {
ad_loge("%s: adm_memory_unmap_regions failed, err %d\n",
__func__, result2);
result = result2;
} else {
atomic_set(&this_adm.mem_map_cal_handles[i],
0);
}
}
}
return result;
}
int adm_connect_afe_port(int mode, int session_id, int port_id)
{
struct adm_cmd_connect_afe_port_v5 cmd;
int ret = 0;
int index;
ad_logd("%s: port %d session id:%d mode:%d\n", __func__,
port_id, session_id, mode);
port_id = afe_convert_virtual_to_portid(port_id);
if (afe_validate_port(port_id) < 0) {
ad_loge("%s port idi[%d] is invalid\n", __func__, port_id);
return -ENODEV;
}
if (this_adm.apr == NULL) {
this_adm.apr = apr_register("ADSP", "ADM", adm_callback,
0xFFFFFFFF, &this_adm);
if (this_adm.apr == NULL) {
ad_loge("%s: Unable to register ADM\n", __func__);
ret = -ENODEV;
return ret;
}
rtac_set_adm_handle(this_adm.apr);
}
index = afe_get_port_index(port_id);
ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index);
cmd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
cmd.hdr.pkt_size = sizeof(cmd);
cmd.hdr.src_svc = APR_SVC_ADM;
cmd.hdr.src_domain = APR_DOMAIN_APPS;
cmd.hdr.src_port = port_id;
cmd.hdr.dest_svc = APR_SVC_ADM;
cmd.hdr.dest_domain = APR_DOMAIN_ADSP;
cmd.hdr.dest_port = port_id;
cmd.hdr.token = port_id;
cmd.hdr.opcode = ADM_CMD_CONNECT_AFE_PORT_V5;
cmd.mode = mode;
cmd.session_id = session_id;
cmd.afe_port_id = port_id;
atomic_set(&this_adm.copp_stat[index], 0);
ret = apr_send_pkt(this_adm.apr, (uint32_t *)&cmd);
if (ret < 0) {
ad_loge("%s:ADM enable for port %#x failed\n",
__func__, port_id);
ret = -EINVAL;
goto fail_cmd;
}
/* Wait for the callback with copp id */
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ad_loge("%s ADM connect AFE failed for port %#x\n", __func__,
port_id);
ret = -EINVAL;
goto fail_cmd;
}
atomic_inc(&this_adm.copp_cnt[index]);
return 0;
fail_cmd:
return ret;
}
int adm_open(int port_id, int path, int rate, int channel_mode, int topology,
int perf_mode, uint16_t bits_per_sample)
{
struct adm_cmd_device_open_v5 open;
int ret = 0;
int index;
int tmp_port = q6audio_get_port_id(port_id);
ad_logd("%s: port %#x path:%d rate:%d mode:%d perf_mode:%d\n",
__func__, port_id, path, rate, channel_mode, perf_mode);
port_id = q6audio_convert_virtual_to_portid(port_id);
if (q6audio_validate_port(port_id) < 0) {
ad_loge("%s port idi[%#x] is invalid\n", __func__, port_id);
return -ENODEV;
}
index = q6audio_get_port_index(port_id);
ad_logd("%s: Port ID %#x, index %d\n", __func__, port_id, index);
if (this_adm.apr == NULL) {
this_adm.apr = apr_register("ADSP", "ADM", adm_callback,
0xFFFFFFFF, &this_adm);
if (this_adm.apr == NULL) {
ad_loge("%s: Unable to register ADM\n", __func__);
ret = -ENODEV;
return ret;
}
rtac_set_adm_handle(this_adm.apr);
}
if (perf_mode == LEGACY_PCM_MODE) {
atomic_set(&this_adm.copp_perf_mode[index], 0);
send_adm_custom_topology(port_id);
} else {
atomic_set(&this_adm.copp_perf_mode[index], 1);
}
/* Create a COPP if port id are not enabled */
if ((perf_mode == LEGACY_PCM_MODE &&
(atomic_read(&this_adm.copp_cnt[index]) == 0)) ||
(perf_mode != LEGACY_PCM_MODE &&
(atomic_read(&this_adm.copp_low_latency_cnt[index]) == 0))) {
ad_logd("%s:opening ADM: perf_mode: %d\n", __func__,
perf_mode);
open.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
open.hdr.pkt_size = sizeof(open);
open.hdr.src_svc = APR_SVC_ADM;
open.hdr.src_domain = APR_DOMAIN_APPS;
open.hdr.src_port = tmp_port;
open.hdr.dest_svc = APR_SVC_ADM;
open.hdr.dest_domain = APR_DOMAIN_ADSP;
open.hdr.dest_port = tmp_port;
open.hdr.token = port_id;
open.hdr.opcode = ADM_CMD_DEVICE_OPEN_V5;
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE)
open.flags = ADM_ULTRA_LOW_LATENCY_DEVICE_SESSION;
else if (perf_mode == LOW_LATENCY_PCM_MODE)
open.flags = ADM_LOW_LATENCY_DEVICE_SESSION;
else
open.flags = ADM_LEGACY_DEVICE_SESSION;
open.mode_of_operation = path;
open.endpoint_id_1 = tmp_port;
if (this_adm.ec_ref_rx == -1) {
open.endpoint_id_2 = 0xFFFF;
} else if (this_adm.ec_ref_rx && (path != 1)) {
open.endpoint_id_2 = this_adm.ec_ref_rx;
this_adm.ec_ref_rx = -1;
}
open.topology_id = topology;
if ((open.topology_id == VPM_TX_SM_ECNS_COPP_TOPOLOGY) ||
(open.topology_id == VPM_TX_DM_FLUENCE_COPP_TOPOLOGY) ||
(open.topology_id == VPM_TX_DM_RFECNS_COPP_TOPOLOGY))
rate = 16000;
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE) {
open.topology_id = NULL_COPP_TOPOLOGY;
rate = ULL_SUPPORTED_SAMPLE_RATE;
} else if (perf_mode == LOW_LATENCY_PCM_MODE) {
if ((open.topology_id == DOLBY_ADM_COPP_TOPOLOGY_ID) ||
(open.topology_id == SRS_TRUMEDIA_TOPOLOGY_ID))
open.topology_id = DEFAULT_COPP_TOPOLOGY;
}
open.dev_num_channel = channel_mode & 0x00FF;
open.bit_width = bits_per_sample;
WARN_ON(perf_mode == ULTRA_LOW_LATENCY_PCM_MODE &&
(rate != 48000));
open.sample_rate = rate;
memset(open.dev_channel_mapping, 0, 8);
if (channel_mode == 1) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FC;
} else if (channel_mode == 2) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
} else if (channel_mode == 3) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
open.dev_channel_mapping[2] = PCM_CHANNEL_FC;
} else if (channel_mode == 4) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
open.dev_channel_mapping[2] = PCM_CHANNEL_RB;
open.dev_channel_mapping[3] = PCM_CHANNEL_LB;
} else if (channel_mode == 5) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
open.dev_channel_mapping[2] = PCM_CHANNEL_FC;
open.dev_channel_mapping[3] = PCM_CHANNEL_LB;
open.dev_channel_mapping[4] = PCM_CHANNEL_RB;
} else if (channel_mode == 6) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
open.dev_channel_mapping[2] = PCM_CHANNEL_LFE;
open.dev_channel_mapping[3] = PCM_CHANNEL_FC;
open.dev_channel_mapping[4] = PCM_CHANNEL_LS;
open.dev_channel_mapping[5] = PCM_CHANNEL_RS;
} else if (channel_mode == 8) {
open.dev_channel_mapping[0] = PCM_CHANNEL_FL;
open.dev_channel_mapping[1] = PCM_CHANNEL_FR;
open.dev_channel_mapping[2] = PCM_CHANNEL_LFE;
open.dev_channel_mapping[3] = PCM_CHANNEL_FC;
open.dev_channel_mapping[4] = PCM_CHANNEL_LB;
open.dev_channel_mapping[5] = PCM_CHANNEL_RB;
open.dev_channel_mapping[6] = PCM_CHANNEL_FLC;
open.dev_channel_mapping[7] = PCM_CHANNEL_FRC;
} else {
ad_loge("%s invalid num_chan %d\n", __func__,
channel_mode);
return -EINVAL;
}
if ((open.dev_num_channel > 2) &&
multi_ch_map.set_channel_map)
memcpy(open.dev_channel_mapping,
multi_ch_map.channel_mapping,
PCM_FORMAT_MAX_NUM_CHANNEL);
ad_logd("%s: port_id=%#x rate=%d topology_id=0x%X\n",
__func__, open.endpoint_id_1, open.sample_rate,
open.topology_id);
atomic_set(&this_adm.copp_stat[index], 0);
ret = apr_send_pkt(this_adm.apr, (uint32_t *)&open);
if (ret < 0) {
ad_loge("%s:ADM enable for port %#x for[%d] failed\n",
__func__, tmp_port, port_id);
ret = -EINVAL;
goto fail_cmd;
}
/* Wait for the callback with copp id */
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ad_loge("%s ADM open failed for port %#x for [%d]\n",
__func__, tmp_port, port_id);
ret = -EINVAL;
goto fail_cmd;
}
}
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE) {
atomic_inc(&this_adm.copp_low_latency_cnt[index]);
ad_logd("%s: index: %d coppid: %d", __func__, index,
atomic_read(&this_adm.copp_low_latency_id[index]));
} else {
atomic_inc(&this_adm.copp_cnt[index]);
ad_logd("%s: index: %d coppid: %d", __func__, index,
atomic_read(&this_adm.copp_id[index]));
}
return 0;
fail_cmd:
return ret;
}
int adm_multi_ch_copp_open(int port_id, int path, int rate, int channel_mode,
int topology, int perf_mode, uint16_t bits_per_sample)
{
int ret = 0;
ret = adm_open(port_id, path, rate, channel_mode,
topology, perf_mode, bits_per_sample);
return ret;
}
int adm_matrix_map(int session_id, int path, int num_copps,
unsigned int *port_id, int copp_id, int perf_mode)
{
struct adm_cmd_matrix_map_routings_v5 *route;
struct adm_session_map_node_v5 *node;
uint16_t *copps_list;
int cmd_size = 0;
int ret = 0, i = 0;
void *payload = NULL;
void *matrix_map = NULL;
/* Assumes port_ids have already been validated during adm_open */
int index = q6audio_get_port_index(copp_id);
if (index < 0 || index >= AFE_MAX_PORTS) {
ad_loge("%s: invalid port idx %d token %d\n",
__func__, index, copp_id);
return 0;
}
cmd_size = (sizeof(struct adm_cmd_matrix_map_routings_v5) +
sizeof(struct adm_session_map_node_v5) +
(sizeof(uint32_t) * num_copps));
matrix_map = kzalloc(cmd_size, GFP_KERNEL);
if (matrix_map == NULL) {
ad_loge("%s: Mem alloc failed\n", __func__);
ret = -EINVAL;
return ret;
}
route = (struct adm_cmd_matrix_map_routings_v5 *)matrix_map;
ad_logd("%s: session 0x%x path:%d num_copps:%d port_id[0]:%#x coppid[%d]\n",
__func__, session_id, path, num_copps, port_id[0], copp_id);
route->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
route->hdr.pkt_size = cmd_size;
route->hdr.src_svc = 0;
route->hdr.src_domain = APR_DOMAIN_APPS;
route->hdr.src_port = copp_id;
route->hdr.dest_svc = APR_SVC_ADM;
route->hdr.dest_domain = APR_DOMAIN_ADSP;
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE) {
route->hdr.dest_port =
atomic_read(&this_adm.copp_low_latency_id[index]);
} else {
route->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
}
route->hdr.token = copp_id;
route->hdr.opcode = ADM_CMD_MATRIX_MAP_ROUTINGS_V5;
route->num_sessions = 1;
switch (path) {
case 0x1:
route->matrix_id = ADM_MATRIX_ID_AUDIO_RX;
break;
case 0x2:
case 0x3:
route->matrix_id = ADM_MATRIX_ID_AUDIO_TX;
break;
default:
ad_loge("%s: Wrong path set[%d]\n", __func__, path);
break;
}
payload = ((u8 *)matrix_map +
sizeof(struct adm_cmd_matrix_map_routings_v5));
node = (struct adm_session_map_node_v5 *)payload;
node->session_id = session_id;
node->num_copps = num_copps;
payload = (u8 *)node + sizeof(struct adm_session_map_node_v5);
copps_list = (uint16_t *)payload;
for (i = 0; i < num_copps; i++) {
int tmp;
port_id[i] = q6audio_convert_virtual_to_portid(port_id[i]);
tmp = q6audio_get_port_index(port_id[i]);
if (tmp >= 0 && tmp < AFE_MAX_PORTS) {
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE)
copps_list[i] =
atomic_read(&this_adm.copp_low_latency_id[tmp]);
else
copps_list[i] =
atomic_read(&this_adm.copp_id[tmp]);
}
else
continue;
ad_logd("%s: port_id[%#x]: %d, index: %d act coppid[0x%x]\n",
__func__, i, port_id[i], tmp, copps_list[i]);
}
atomic_set(&this_adm.copp_stat[index], 0);
ret = apr_send_pkt(this_adm.apr, (uint32_t *)matrix_map);
if (ret < 0) {
ad_loge("%s: ADM routing for port %#x failed\n",
__func__, port_id[0]);
ret = -EINVAL;
goto fail_cmd;
}
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ad_loge("%s: ADM cmd Route failed for port %#x\n",
__func__, port_id[0]);
ret = -EINVAL;
goto fail_cmd;
}
if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) {
for (i = 0; i < num_copps; i++)
send_adm_cal(port_id[i], path, perf_mode);
for (i = 0; i < num_copps; i++) {
int tmp, copp_id;
tmp = afe_get_port_index(port_id[i]);
if (tmp >= 0 && tmp < AFE_MAX_PORTS) {
if (perf_mode == LEGACY_PCM_MODE)
copp_id = atomic_read(
&this_adm.copp_id[tmp]);
else
copp_id = atomic_read(
&this_adm.copp_low_latency_id[tmp]);
rtac_add_adm_device(port_id[i],
copp_id, path, session_id);
ad_logd("%s, copp_id: %d\n",
__func__, copp_id);
} else
ad_logd("%s: Invalid port index %d",
__func__, tmp);
}
}
fail_cmd:
kfree(matrix_map);
return ret;
}
int adm_memory_map_regions(int port_id,
phys_addr_t *buf_add, uint32_t mempool_id,
uint32_t *bufsz, uint32_t bufcnt)
{
struct avs_cmd_shared_mem_map_regions *mmap_regions = NULL;
struct avs_shared_map_region_payload *mregions = NULL;
void *mmap_region_cmd = NULL;
void *payload = NULL;
int ret = 0;
int i = 0;
int cmd_size = 0;
int index = 0;
ad_logd("%s\n", __func__);
if (this_adm.apr == NULL) {
this_adm.apr = apr_register("ADSP", "ADM", adm_callback,
0xFFFFFFFF, &this_adm);
if (this_adm.apr == NULL) {
ad_loge("%s: Unable to register ADM\n", __func__);
ret = -ENODEV;
return ret;
}
rtac_set_adm_handle(this_adm.apr);
}
port_id = q6audio_convert_virtual_to_portid(port_id);
if (q6audio_validate_port(port_id) < 0) {
ad_loge("%s port id[%#x] is invalid\n", __func__, port_id);
return -ENODEV;
}
index = q6audio_get_port_index(port_id);
cmd_size = sizeof(struct avs_cmd_shared_mem_map_regions)
+ sizeof(struct avs_shared_map_region_payload)
* bufcnt;
mmap_region_cmd = kzalloc(cmd_size, GFP_KERNEL);
if (!mmap_region_cmd) {
ad_loge("%s: allocate mmap_region_cmd failed\n", __func__);
return -ENOMEM;
}
mmap_regions = (struct avs_cmd_shared_mem_map_regions *)mmap_region_cmd;
mmap_regions->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
mmap_regions->hdr.pkt_size = cmd_size;
mmap_regions->hdr.src_port = 0;
mmap_regions->hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
mmap_regions->hdr.token = port_id;
mmap_regions->hdr.opcode = ADM_CMD_SHARED_MEM_MAP_REGIONS;
mmap_regions->mem_pool_id = ADSP_MEMORY_MAP_SHMEM8_4K_POOL & 0x00ff;
mmap_regions->num_regions = bufcnt & 0x00ff;
mmap_regions->property_flag = 0x00;
ad_logd("%s: map_regions->num_regions = %d\n", __func__,
mmap_regions->num_regions);
payload = ((u8 *) mmap_region_cmd +
sizeof(struct avs_cmd_shared_mem_map_regions));
mregions = (struct avs_shared_map_region_payload *)payload;
for (i = 0; i < bufcnt; i++) {
mregions->shm_addr_lsw = lower_32_bits(buf_add[i]);
mregions->shm_addr_msw = upper_32_bits(buf_add[i]);
mregions->mem_size_bytes = bufsz[i];
++mregions;
}
atomic_set(&this_adm.copp_stat[index], 0);
ret = apr_send_pkt(this_adm.apr, (uint32_t *) mmap_region_cmd);
if (ret < 0) {
ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__,
mmap_regions->hdr.opcode, ret);
ret = -EINVAL;
goto fail_cmd;
}
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]), 5 * HZ);
if (!ret) {
ad_loge("%s: timeout. waited for memory_map\n", __func__);
ret = -EINVAL;
goto fail_cmd;
}
fail_cmd:
kfree(mmap_region_cmd);
return ret;
}
int adm_memory_unmap_regions(int32_t port_id)
{
struct avs_cmd_shared_mem_unmap_regions unmap_regions;
int ret = 0;
int index = 0;
ad_logd("%s\n", __func__);
if (this_adm.apr == NULL) {
ad_loge("%s APR handle NULL\n", __func__);
return -EINVAL;
}
port_id = q6audio_convert_virtual_to_portid(port_id);
if (q6audio_validate_port(port_id) < 0) {
ad_loge("%s port idi[%d] is invalid\n", __func__, port_id);
return -ENODEV;
}
index = q6audio_get_port_index(port_id);
unmap_regions.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE),
APR_PKT_VER);
unmap_regions.hdr.pkt_size = sizeof(unmap_regions);
unmap_regions.hdr.src_port = 0;
unmap_regions.hdr.dest_port = atomic_read(&this_adm.copp_id[index]);
unmap_regions.hdr.token = port_id;
unmap_regions.hdr.opcode = ADM_CMD_SHARED_MEM_UNMAP_REGIONS;
unmap_regions.mem_map_handle = atomic_read(&this_adm.
mem_map_cal_handles[atomic_read(&this_adm.mem_map_cal_index)]);
atomic_set(&this_adm.copp_stat[index], 0);
ret = apr_send_pkt(this_adm.apr, (uint32_t *) &unmap_regions);
if (ret < 0) {
ad_loge("%s: mmap_regions op[0x%x]rc[%d]\n", __func__,
unmap_regions.hdr.opcode, ret);
ret = -EINVAL;
goto fail_cmd;
}
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
5 * HZ);
if (!ret) {
ad_loge("%s: timeout. waited for memory_unmap index %d\n",
__func__, index);
ret = -EINVAL;
goto fail_cmd;
} else {
ad_logd("%s: Unmap handle 0x%x succeeded\n", __func__,
unmap_regions.mem_map_handle);
}
fail_cmd:
return ret;
}
#ifdef CONFIG_RTAC
int adm_get_copp_id(int port_index)
{
int copp_id;
ad_logd("%s\n", __func__);
if (port_index < 0) {
ad_loge("%s: invalid port_id = %d\n", __func__, port_index);
return -EINVAL;
}
copp_id = atomic_read(&this_adm.copp_id[port_index]);
if (copp_id == RESET_COPP_ID)
copp_id = atomic_read(
&this_adm.copp_low_latency_id[port_index]);
return copp_id;
}
int adm_get_lowlatency_copp_id(int port_index)
{
ad_logd("%s\n", __func__);
if (port_index < 0) {
ad_loge("%s: invalid port_id = %d\n", __func__, port_index);
return -EINVAL;
}
return atomic_read(&this_adm.copp_low_latency_id[port_index]);
}
#else
int adm_get_copp_id(int port_index)
{
return -EINVAL;
}
int adm_get_lowlatency_copp_id(int port_index)
{
return -EINVAL;
}
#endif /* #ifdef CONFIG_RTAC */
void adm_ec_ref_rx_id(int port_id)
{
this_adm.ec_ref_rx = port_id;
ad_logd("%s ec_ref_rx:%d", __func__, this_adm.ec_ref_rx);
}
int adm_close(int port_id, int perf_mode)
{
struct apr_hdr close;
int ret = 0;
int index = 0;
int copp_id = RESET_COPP_ID;
port_id = q6audio_convert_virtual_to_portid(port_id);
index = q6audio_get_port_index(port_id);
if (q6audio_validate_port(port_id) < 0)
return -EINVAL;
ad_logd("%s port_id=%#x index %d perf_mode: %d\n", __func__, port_id,
index, perf_mode);
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE) {
if (!(atomic_read(&this_adm.copp_low_latency_cnt[index]))) {
ad_loge("%s: copp count for port[%#x]is 0\n", __func__,
port_id);
goto fail_cmd;
}
atomic_dec(&this_adm.copp_low_latency_cnt[index]);
} else {
if (!(atomic_read(&this_adm.copp_cnt[index]))) {
ad_loge("%s: copp count for port[%#x]is 0\n", __func__,
port_id);
goto fail_cmd;
}
atomic_dec(&this_adm.copp_cnt[index]);
}
if ((perf_mode == LEGACY_PCM_MODE &&
!(atomic_read(&this_adm.copp_cnt[index]))) ||
((perf_mode != LEGACY_PCM_MODE) &&
!(atomic_read(&this_adm.copp_low_latency_cnt[index])))) {
ad_logd("%s:Closing ADM: perf_mode: %d\n", __func__,
perf_mode);
close.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
close.pkt_size = sizeof(close);
close.src_svc = APR_SVC_ADM;
close.src_domain = APR_DOMAIN_APPS;
close.src_port = port_id;
close.dest_svc = APR_SVC_ADM;
close.dest_domain = APR_DOMAIN_ADSP;
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE)
close.dest_port =
atomic_read(&this_adm.copp_low_latency_id[index]);
else
close.dest_port = atomic_read(&this_adm.copp_id[index]);
close.token = port_id;
close.opcode = ADM_CMD_DEVICE_CLOSE_V5;
atomic_set(&this_adm.copp_stat[index], 0);
if (perf_mode == ULTRA_LOW_LATENCY_PCM_MODE ||
perf_mode == LOW_LATENCY_PCM_MODE) {
copp_id = atomic_read(
&this_adm.copp_low_latency_id[index]);
ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n",
__func__,
copp_id,
port_id, index,
atomic_read(
&this_adm.copp_low_latency_cnt[index]));
atomic_set(&this_adm.copp_low_latency_id[index],
RESET_COPP_ID);
} else {
copp_id = atomic_read(&this_adm.copp_id[index]);
ad_logd("%s:coppid %d portid=%#x index=%d coppcnt=%d\n",
__func__,
copp_id,
port_id, index,
atomic_read(&this_adm.copp_cnt[index]));
atomic_set(&this_adm.copp_id[index],
RESET_COPP_ID);
}
ret = apr_send_pkt(this_adm.apr, (uint32_t *)&close);
if (ret < 0) {
ad_loge("%s ADM close failed\n", __func__);
ret = -EINVAL;
goto fail_cmd;
}
ret = wait_event_timeout(this_adm.wait[index],
atomic_read(&this_adm.copp_stat[index]),
msecs_to_jiffies(TIMEOUT_MS));
if (!ret) {
ad_loge("%s: ADM cmd Route failed for port %#x\n",
__func__, port_id);
ret = -EINVAL;
goto fail_cmd;
}
}
if (perf_mode != ULTRA_LOW_LATENCY_PCM_MODE) {
ad_logd("%s: remove adm device from rtac\n", __func__);
rtac_remove_adm_device(port_id, copp_id);
}
fail_cmd:
return ret;
}
static int __init adm_init(void)
{
int i = 0;
this_adm.apr = NULL;
this_adm.set_custom_topology = 1;
this_adm.ec_ref_rx = -1;
for (i = 0; i < AFE_MAX_PORTS; i++) {
atomic_set(&this_adm.copp_id[i], RESET_COPP_ID);
atomic_set(&this_adm.copp_low_latency_id[i], RESET_COPP_ID);
atomic_set(&this_adm.copp_cnt[i], 0);
atomic_set(&this_adm.copp_low_latency_cnt[i], 0);
atomic_set(&this_adm.copp_stat[i], 0);
atomic_set(&this_adm.copp_perf_mode[i], 0);
init_waitqueue_head(&this_adm.wait[i]);
}
return 0;
}
device_initcall(adm_init);
| EloYGomeZ/test_kernel_g620s | sound/soc/msm/qdsp6v2/q6adm.c | C | gpl-2.0 | 55,954 |
/*
* PROJECT: ReactOS i8042 (ps/2 keyboard-mouse controller) driver
* LICENSE: GPL - See COPYING in the top level directory
* FILE: drivers/input/i8042prt/pnp.c
* PURPOSE: IRP_MJ_PNP operations
* PROGRAMMERS: Copyright 2006-2007 Hervé Poussineau ([email protected])
* Copyright 2008 Colin Finck ([email protected])
*/
/* INCLUDES ******************************************************************/
#include "i8042prt.h"
#include <debug.h>
/* FUNCTIONS *****************************************************************/
/* This is all pretty confusing. There's more than one way to
* disable/enable the keyboard. You can send KBD_ENABLE to the
* keyboard, and it will start scanning keys. Sending KBD_DISABLE
* will disable the key scanning but also reset the parameters to
* defaults.
*
* You can also send 0xAE to the controller for enabling the
* keyboard clock line and 0xAD for disabling it. Then it'll
* automatically get turned on at the next command. The last
* way is by modifying the bit that drives the clock line in the
* 'command byte' of the controller. This is almost, but not quite,
* the same as the AE/AD thing. The difference can be used to detect
* some really old broken keyboard controllers which I hope won't be
* necessary.
*
* We change the command byte, sending KBD_ENABLE/DISABLE seems to confuse
* some kvm switches.
*/
BOOLEAN
i8042ChangeMode(
IN PPORT_DEVICE_EXTENSION DeviceExtension,
IN UCHAR FlagsToDisable,
IN UCHAR FlagsToEnable)
{
UCHAR Value;
NTSTATUS Status;
if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_READ_MODE))
{
WARN_(I8042PRT, "Can't read i8042 mode\n");
return FALSE;
}
Status = i8042ReadDataWait(DeviceExtension, &Value);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "No response after read i8042 mode\n");
return FALSE;
}
Value &= ~FlagsToDisable;
Value |= FlagsToEnable;
if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, KBD_WRITE_MODE))
{
WARN_(I8042PRT, "Can't set i8042 mode\n");
return FALSE;
}
if (!i8042Write(DeviceExtension, DeviceExtension->DataPort, Value))
{
WARN_(I8042PRT, "Can't send i8042 mode\n");
return FALSE;
}
return TRUE;
}
static NTSTATUS
i8042BasicDetect(
IN PPORT_DEVICE_EXTENSION DeviceExtension)
{
NTSTATUS Status;
ULONG ResendIterations;
UCHAR Value = 0;
/* Don't enable keyboard and mouse interrupts, disable keyboard/mouse */
i8042Flush(DeviceExtension);
if (!i8042ChangeMode(DeviceExtension, CCB_KBD_INT_ENAB | CCB_MOUSE_INT_ENAB, CCB_KBD_DISAB | CCB_MOUSE_DISAB))
return STATUS_IO_DEVICE_ERROR;
i8042Flush(DeviceExtension);
/* Issue a CTRL_SELF_TEST command to check if this is really an i8042 controller */
ResendIterations = DeviceExtension->Settings.ResendIterations + 1;
while (ResendIterations--)
{
if (!i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST))
{
WARN_(I8042PRT, "Writing CTRL_SELF_TEST command failed\n");
return STATUS_IO_TIMEOUT;
}
Status = i8042ReadDataWait(DeviceExtension, &Value);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "Failed to read CTRL_SELF_TEST response, status 0x%08lx\n", Status);
return Status;
}
if (Value == KBD_SELF_TEST_OK)
{
INFO_(I8042PRT, "CTRL_SELF_TEST completed successfully!\n");
break;
}
else if (Value == KBD_RESEND)
{
TRACE_(I8042PRT, "Resending...\n");
KeStallExecutionProcessor(50);
}
else
{
WARN_(I8042PRT, "Got 0x%02x instead of 0x55\n", Value);
return STATUS_IO_DEVICE_ERROR;
}
}
return STATUS_SUCCESS;
}
static VOID
i8042DetectKeyboard(
IN PPORT_DEVICE_EXTENSION DeviceExtension)
{
NTSTATUS Status;
/* Set LEDs (that is not fatal if some error occurs) */
Status = i8042SynchWritePort(DeviceExtension, 0, KBD_CMD_SET_LEDS, TRUE);
if (NT_SUCCESS(Status))
{
Status = i8042SynchWritePort(DeviceExtension, 0, 0, TRUE);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "Can't finish SET_LEDS (0x%08lx)\n", Status);
return;
}
}
else
{
WARN_(I8042PRT, "Warning: can't write SET_LEDS (0x%08lx)\n", Status);
}
/* Turn on translation and SF (Some machines don't reboot if SF is not set, see ReactOS bug CORE-1713) */
if (!i8042ChangeMode(DeviceExtension, 0, CCB_TRANSLATE | CCB_SYSTEM_FLAG))
return;
/*
* We used to send a KBD_LINE_TEST (0xAB) command, but on at least HP
* Pavilion notebooks the response to that command was incorrect.
* So now we just assume that a keyboard is attached.
*/
DeviceExtension->Flags |= KEYBOARD_PRESENT;
INFO_(I8042PRT, "Keyboard detected\n");
}
static VOID
i8042DetectMouse(
IN PPORT_DEVICE_EXTENSION DeviceExtension)
{
NTSTATUS Status;
UCHAR Value;
UCHAR ExpectedReply[] = { MOUSE_ACK, 0xAA };
UCHAR ReplyByte;
/* First do a mouse line test */
if (i8042Write(DeviceExtension, DeviceExtension->ControlPort, MOUSE_LINE_TEST))
{
Status = i8042ReadDataWait(DeviceExtension, &Value);
if (!NT_SUCCESS(Status) || Value != 0)
{
WARN_(I8042PRT, "Mouse line test failed\n");
goto failure;
}
}
/* Now reset the mouse */
i8042Flush(DeviceExtension);
if(!i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE))
{
WARN_(I8042PRT, "Failed to write reset command to mouse\n");
goto failure;
}
/* The implementation of the "Mouse Reset" command differs much from chip to chip.
By default, the first byte is an ACK, when the mouse is plugged in and working and NACK when it's not.
On success, the next bytes are 0xAA and 0x00.
But on some systems (like ECS K7S5A Pro, SiS 735 chipset), we always get an ACK and 0xAA.
Only the last byte indicates, whether a mouse is plugged in.
It is either sent or not, so there is no byte, which indicates a failure here.
After the Mouse Reset command was issued, it usually takes some time until we get a response.
So get the first two bytes in a loop. */
for (ReplyByte = 0;
ReplyByte < sizeof(ExpectedReply) / sizeof(ExpectedReply[0]);
ReplyByte++)
{
ULONG Counter = 500;
do
{
Status = i8042ReadDataWait(DeviceExtension, &Value);
if(!NT_SUCCESS(Status))
{
/* Wait some time before trying again */
KeStallExecutionProcessor(50);
}
} while (Status == STATUS_IO_TIMEOUT && Counter--);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "No ACK after mouse reset, status 0x%08lx\n", Status);
goto failure;
}
else if (Value != ExpectedReply[ReplyByte])
{
WARN_(I8042PRT, "Unexpected reply: 0x%02x (expected 0x%02x)\n", Value, ExpectedReply[ReplyByte]);
goto failure;
}
}
/* Finally get the third byte, but only try it one time (see above).
Otherwise this takes around 45 seconds on a K7S5A Pro, when no mouse is plugged in. */
Status = i8042ReadDataWait(DeviceExtension, &Value);
if(!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "Last byte was not transmitted after mouse reset, status 0x%08lx\n", Status);
goto failure;
}
else if(Value != 0x00)
{
WARN_(I8042PRT, "Last byte after mouse reset was not 0x00, but 0x%02x\n", Value);
goto failure;
}
DeviceExtension->Flags |= MOUSE_PRESENT;
INFO_(I8042PRT, "Mouse detected\n");
return;
failure:
/* There is probably no mouse present. On some systems,
the probe locks the entire keyboard controller. Let's
try to get access to the keyboard again by sending a
reset */
i8042Flush(DeviceExtension);
i8042Write(DeviceExtension, DeviceExtension->ControlPort, CTRL_SELF_TEST);
i8042ReadDataWait(DeviceExtension, &Value);
i8042Flush(DeviceExtension);
INFO_(I8042PRT, "Mouse not detected\n");
}
static NTSTATUS
i8042ConnectKeyboardInterrupt(
IN PI8042_KEYBOARD_EXTENSION DeviceExtension)
{
PPORT_DEVICE_EXTENSION PortDeviceExtension;
KIRQL DirqlMax;
NTSTATUS Status;
TRACE_(I8042PRT, "i8042ConnectKeyboardInterrupt()\n");
PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension;
DirqlMax = MAX(
PortDeviceExtension->KeyboardInterrupt.Dirql,
PortDeviceExtension->MouseInterrupt.Dirql);
INFO_(I8042PRT, "KeyboardInterrupt.Vector %lu\n",
PortDeviceExtension->KeyboardInterrupt.Vector);
INFO_(I8042PRT, "KeyboardInterrupt.Dirql %lu\n",
PortDeviceExtension->KeyboardInterrupt.Dirql);
INFO_(I8042PRT, "KeyboardInterrupt.DirqlMax %lu\n",
DirqlMax);
INFO_(I8042PRT, "KeyboardInterrupt.InterruptMode %s\n",
PortDeviceExtension->KeyboardInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched");
INFO_(I8042PRT, "KeyboardInterrupt.ShareInterrupt %s\n",
PortDeviceExtension->KeyboardInterrupt.ShareInterrupt ? "yes" : "no");
INFO_(I8042PRT, "KeyboardInterrupt.Affinity 0x%lx\n",
PortDeviceExtension->KeyboardInterrupt.Affinity);
Status = IoConnectInterrupt(
&PortDeviceExtension->KeyboardInterrupt.Object,
i8042KbdInterruptService,
DeviceExtension, &PortDeviceExtension->SpinLock,
PortDeviceExtension->KeyboardInterrupt.Vector, PortDeviceExtension->KeyboardInterrupt.Dirql, DirqlMax,
PortDeviceExtension->KeyboardInterrupt.InterruptMode, PortDeviceExtension->KeyboardInterrupt.ShareInterrupt,
PortDeviceExtension->KeyboardInterrupt.Affinity, FALSE);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status);
return Status;
}
if (DirqlMax == PortDeviceExtension->KeyboardInterrupt.Dirql)
PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object;
PortDeviceExtension->Flags |= KEYBOARD_INITIALIZED;
return STATUS_SUCCESS;
}
static NTSTATUS
i8042ConnectMouseInterrupt(
IN PI8042_MOUSE_EXTENSION DeviceExtension)
{
PPORT_DEVICE_EXTENSION PortDeviceExtension;
KIRQL DirqlMax;
NTSTATUS Status;
TRACE_(I8042PRT, "i8042ConnectMouseInterrupt()\n");
Status = i8042MouInitialize(DeviceExtension);
if (!NT_SUCCESS(Status))
return Status;
PortDeviceExtension = DeviceExtension->Common.PortDeviceExtension;
DirqlMax = MAX(
PortDeviceExtension->KeyboardInterrupt.Dirql,
PortDeviceExtension->MouseInterrupt.Dirql);
INFO_(I8042PRT, "MouseInterrupt.Vector %lu\n",
PortDeviceExtension->MouseInterrupt.Vector);
INFO_(I8042PRT, "MouseInterrupt.Dirql %lu\n",
PortDeviceExtension->MouseInterrupt.Dirql);
INFO_(I8042PRT, "MouseInterrupt.DirqlMax %lu\n",
DirqlMax);
INFO_(I8042PRT, "MouseInterrupt.InterruptMode %s\n",
PortDeviceExtension->MouseInterrupt.InterruptMode == LevelSensitive ? "LevelSensitive" : "Latched");
INFO_(I8042PRT, "MouseInterrupt.ShareInterrupt %s\n",
PortDeviceExtension->MouseInterrupt.ShareInterrupt ? "yes" : "no");
INFO_(I8042PRT, "MouseInterrupt.Affinity 0x%lx\n",
PortDeviceExtension->MouseInterrupt.Affinity);
Status = IoConnectInterrupt(
&PortDeviceExtension->MouseInterrupt.Object,
i8042MouInterruptService,
DeviceExtension, &PortDeviceExtension->SpinLock,
PortDeviceExtension->MouseInterrupt.Vector, PortDeviceExtension->MouseInterrupt.Dirql, DirqlMax,
PortDeviceExtension->MouseInterrupt.InterruptMode, PortDeviceExtension->MouseInterrupt.ShareInterrupt,
PortDeviceExtension->MouseInterrupt.Affinity, FALSE);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "IoConnectInterrupt() failed with status 0x%08x\n", Status);
goto cleanup;
}
if (DirqlMax == PortDeviceExtension->MouseInterrupt.Dirql)
PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->MouseInterrupt.Object;
PortDeviceExtension->Flags |= MOUSE_INITIALIZED;
Status = STATUS_SUCCESS;
cleanup:
if (!NT_SUCCESS(Status))
{
PortDeviceExtension->Flags &= ~MOUSE_INITIALIZED;
if (PortDeviceExtension->MouseInterrupt.Object)
{
IoDisconnectInterrupt(PortDeviceExtension->MouseInterrupt.Object);
PortDeviceExtension->HighestDIRQLInterrupt = PortDeviceExtension->KeyboardInterrupt.Object;
}
}
return Status;
}
static NTSTATUS
EnableInterrupts(
IN PPORT_DEVICE_EXTENSION DeviceExtension,
IN UCHAR FlagsToDisable,
IN UCHAR FlagsToEnable)
{
i8042Flush(DeviceExtension);
if (!i8042ChangeMode(DeviceExtension, FlagsToDisable, FlagsToEnable))
return STATUS_UNSUCCESSFUL;
return STATUS_SUCCESS;
}
static NTSTATUS
StartProcedure(
IN PPORT_DEVICE_EXTENSION DeviceExtension)
{
NTSTATUS Status = STATUS_UNSUCCESSFUL;
UCHAR FlagsToDisable = 0;
UCHAR FlagsToEnable = 0;
KIRQL Irql;
if (DeviceExtension->DataPort == 0)
{
/* Unable to do something at the moment */
return STATUS_SUCCESS;
}
if (!(DeviceExtension->Flags & (KEYBOARD_PRESENT | MOUSE_PRESENT)))
{
/* Try to detect them */
TRACE_(I8042PRT, "Check if the controller is really a i8042\n");
Status = i8042BasicDetect(DeviceExtension);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "i8042BasicDetect() failed with status 0x%08lx\n", Status);
return STATUS_UNSUCCESSFUL;
}
/* First detect the mouse and then the keyboard!
If we do it the other way round, some systems throw away settings like the keyboard translation, when detecting the mouse. */
TRACE_(I8042PRT, "Detecting mouse\n");
i8042DetectMouse(DeviceExtension);
TRACE_(I8042PRT, "Detecting keyboard\n");
i8042DetectKeyboard(DeviceExtension);
INFO_(I8042PRT, "Keyboard present: %s\n", DeviceExtension->Flags & KEYBOARD_PRESENT ? "YES" : "NO");
INFO_(I8042PRT, "Mouse present : %s\n", DeviceExtension->Flags & MOUSE_PRESENT ? "YES" : "NO");
TRACE_(I8042PRT, "Enabling i8042 interrupts\n");
if (DeviceExtension->Flags & KEYBOARD_PRESENT)
{
FlagsToDisable |= CCB_KBD_DISAB;
FlagsToEnable |= CCB_KBD_INT_ENAB;
}
if (DeviceExtension->Flags & MOUSE_PRESENT)
{
FlagsToDisable |= CCB_MOUSE_DISAB;
FlagsToEnable |= CCB_MOUSE_INT_ENAB;
}
Status = EnableInterrupts(DeviceExtension, FlagsToDisable, FlagsToEnable);
if (!NT_SUCCESS(Status))
{
WARN_(I8042PRT, "EnableInterrupts failed: %lx\n", Status);
DeviceExtension->Flags &= ~(KEYBOARD_PRESENT | MOUSE_PRESENT);
return Status;
}
}
/* Connect interrupts */
if (DeviceExtension->Flags & KEYBOARD_PRESENT &&
DeviceExtension->Flags & KEYBOARD_CONNECTED &&
DeviceExtension->Flags & KEYBOARD_STARTED &&
!(DeviceExtension->Flags & KEYBOARD_INITIALIZED))
{
/* Keyboard is ready to be initialized */
Status = i8042ConnectKeyboardInterrupt(DeviceExtension->KeyboardExtension);
if (NT_SUCCESS(Status))
{
DeviceExtension->Flags |= KEYBOARD_INITIALIZED;
}
else
{
WARN_(I8042PRT, "i8042ConnectKeyboardInterrupt failed: %lx\n", Status);
}
}
if (DeviceExtension->Flags & MOUSE_PRESENT &&
DeviceExtension->Flags & MOUSE_CONNECTED &&
DeviceExtension->Flags & MOUSE_STARTED &&
!(DeviceExtension->Flags & MOUSE_INITIALIZED))
{
/* Mouse is ready to be initialized */
Status = i8042ConnectMouseInterrupt(DeviceExtension->MouseExtension);
if (NT_SUCCESS(Status))
{
DeviceExtension->Flags |= MOUSE_INITIALIZED;
}
else
{
WARN_(I8042PRT, "i8042ConnectMouseInterrupt failed: %lx\n", Status);
}
/* Start the mouse */
Irql = KeAcquireInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt);
/* HACK: the mouse has already been reset in i8042DetectMouse. This second
reset prevents some touchpads/mice from working (Dell D531, D600).
See CORE-6901 */
if (!(i8042HwFlags & FL_INITHACK))
{
i8042IsrWritePort(DeviceExtension, MOU_CMD_RESET, CTRL_WRITE_MOUSE);
}
KeReleaseInterruptSpinLock(DeviceExtension->HighestDIRQLInterrupt, Irql);
}
return Status;
}
static NTSTATUS
i8042PnpStartDevice(
IN PDEVICE_OBJECT DeviceObject,
IN PCM_RESOURCE_LIST AllocatedResources,
IN PCM_RESOURCE_LIST AllocatedResourcesTranslated)
{
PFDO_DEVICE_EXTENSION DeviceExtension;
PPORT_DEVICE_EXTENSION PortDeviceExtension;
PCM_PARTIAL_RESOURCE_DESCRIPTOR ResourceDescriptor, ResourceDescriptorTranslated;
INTERRUPT_DATA InterruptData = { NULL };
BOOLEAN FoundDataPort = FALSE;
BOOLEAN FoundControlPort = FALSE;
BOOLEAN FoundIrq = FALSE;
ULONG i;
NTSTATUS Status;
TRACE_(I8042PRT, "i8042PnpStartDevice(%p)\n", DeviceObject);
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PortDeviceExtension = DeviceExtension->PortDeviceExtension;
ASSERT(DeviceExtension->PnpState == dsStopped);
if (!AllocatedResources)
{
WARN_(I8042PRT, "No allocated resources sent to driver\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
if (AllocatedResources->Count != 1)
{
WARN_(I8042PRT, "Wrong number of allocated resources sent to driver\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
if (AllocatedResources->List[0].PartialResourceList.Version != 1
|| AllocatedResources->List[0].PartialResourceList.Revision != 1
|| AllocatedResourcesTranslated->List[0].PartialResourceList.Version != 1
|| AllocatedResourcesTranslated->List[0].PartialResourceList.Revision != 1)
{
WARN_(I8042PRT, "Revision mismatch: %u.%u != 1.1 or %u.%u != 1.1\n",
AllocatedResources->List[0].PartialResourceList.Version,
AllocatedResources->List[0].PartialResourceList.Revision,
AllocatedResourcesTranslated->List[0].PartialResourceList.Version,
AllocatedResourcesTranslated->List[0].PartialResourceList.Revision);
return STATUS_REVISION_MISMATCH;
}
/* Get Irq and optionally control port and data port */
for (i = 0; i < AllocatedResources->List[0].PartialResourceList.Count; i++)
{
ResourceDescriptor = &AllocatedResources->List[0].PartialResourceList.PartialDescriptors[i];
ResourceDescriptorTranslated = &AllocatedResourcesTranslated->List[0].PartialResourceList.PartialDescriptors[i];
switch (ResourceDescriptor->Type)
{
case CmResourceTypePort:
{
if (ResourceDescriptor->u.Port.Length == 1)
{
/* We assume that the first resource will
* be the control port and the second one
* will be the data port...
*/
if (!FoundDataPort)
{
PortDeviceExtension->DataPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart);
INFO_(I8042PRT, "Found data port: %p\n", PortDeviceExtension->DataPort);
FoundDataPort = TRUE;
}
else if (!FoundControlPort)
{
PortDeviceExtension->ControlPort = ULongToPtr(ResourceDescriptor->u.Port.Start.u.LowPart);
INFO_(I8042PRT, "Found control port: %p\n", PortDeviceExtension->ControlPort);
FoundControlPort = TRUE;
}
else
{
/* FIXME: implement PS/2 Active Multiplexing */
ERR_(I8042PRT, "Unhandled I/O ranges provided: 0x%lx\n", ResourceDescriptor->u.Port.Length);
}
}
else
WARN_(I8042PRT, "Invalid I/O range length: 0x%lx\n", ResourceDescriptor->u.Port.Length);
break;
}
case CmResourceTypeInterrupt:
{
if (FoundIrq)
return STATUS_INVALID_PARAMETER;
InterruptData.Dirql = (KIRQL)ResourceDescriptorTranslated->u.Interrupt.Level;
InterruptData.Vector = ResourceDescriptorTranslated->u.Interrupt.Vector;
InterruptData.Affinity = ResourceDescriptorTranslated->u.Interrupt.Affinity;
if (ResourceDescriptorTranslated->Flags & CM_RESOURCE_INTERRUPT_LATCHED)
InterruptData.InterruptMode = Latched;
else
InterruptData.InterruptMode = LevelSensitive;
InterruptData.ShareInterrupt = (ResourceDescriptorTranslated->ShareDisposition == CmResourceShareShared);
INFO_(I8042PRT, "Found irq resource: %lu\n", ResourceDescriptor->u.Interrupt.Level);
FoundIrq = TRUE;
break;
}
default:
WARN_(I8042PRT, "Unknown resource descriptor type 0x%x\n", ResourceDescriptor->Type);
}
}
if (!FoundIrq)
{
WARN_(I8042PRT, "Interrupt resource was not found in allocated resources list\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
else if (DeviceExtension->Type == Keyboard && (!FoundDataPort || !FoundControlPort))
{
WARN_(I8042PRT, "Some required resources were not found in allocated resources list\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
else if (DeviceExtension->Type == Mouse && (FoundDataPort || FoundControlPort))
{
WARN_(I8042PRT, "Too much resources were provided in allocated resources list\n");
return STATUS_INVALID_PARAMETER;
}
switch (DeviceExtension->Type)
{
case Keyboard:
{
RtlCopyMemory(
&PortDeviceExtension->KeyboardInterrupt,
&InterruptData,
sizeof(INTERRUPT_DATA));
PortDeviceExtension->Flags |= KEYBOARD_STARTED;
Status = StartProcedure(PortDeviceExtension);
break;
}
case Mouse:
{
RtlCopyMemory(
&PortDeviceExtension->MouseInterrupt,
&InterruptData,
sizeof(INTERRUPT_DATA));
PortDeviceExtension->Flags |= MOUSE_STARTED;
Status = StartProcedure(PortDeviceExtension);
break;
}
default:
{
WARN_(I8042PRT, "Unknown FDO type %u\n", DeviceExtension->Type);
ASSERT(!(PortDeviceExtension->Flags & KEYBOARD_CONNECTED) || !(PortDeviceExtension->Flags & MOUSE_CONNECTED));
Status = STATUS_INVALID_DEVICE_REQUEST;
}
}
if (NT_SUCCESS(Status))
DeviceExtension->PnpState = dsStarted;
return Status;
}
static VOID
i8042RemoveDevice(
IN PDEVICE_OBJECT DeviceObject)
{
PI8042_DRIVER_EXTENSION DriverExtension;
KIRQL OldIrql;
PFDO_DEVICE_EXTENSION DeviceExtension;
DriverExtension = (PI8042_DRIVER_EXTENSION)IoGetDriverObjectExtension(DeviceObject->DriverObject, DeviceObject->DriverObject);
DeviceExtension = (PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
KeAcquireSpinLock(&DriverExtension->DeviceListLock, &OldIrql);
RemoveEntryList(&DeviceExtension->ListEntry);
KeReleaseSpinLock(&DriverExtension->DeviceListLock, OldIrql);
IoDetachDevice(DeviceExtension->LowerDevice);
IoDeleteDevice(DeviceObject);
}
NTSTATUS NTAPI
i8042Pnp(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp)
{
PIO_STACK_LOCATION Stack;
ULONG MinorFunction;
I8042_DEVICE_TYPE DeviceType;
ULONG_PTR Information = 0;
NTSTATUS Status;
Stack = IoGetCurrentIrpStackLocation(Irp);
MinorFunction = Stack->MinorFunction;
DeviceType = ((PFDO_DEVICE_EXTENSION)DeviceObject->DeviceExtension)->Type;
switch (MinorFunction)
{
case IRP_MN_START_DEVICE: /* 0x00 */
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_START_DEVICE\n");
/* Call lower driver (if any) */
if (DeviceType != PhysicalDeviceObject)
{
Status = ForwardIrpAndWait(DeviceObject, Irp);
if (NT_SUCCESS(Status))
Status = i8042PnpStartDevice(
DeviceObject,
Stack->Parameters.StartDevice.AllocatedResources,
Stack->Parameters.StartDevice.AllocatedResourcesTranslated);
}
else
Status = STATUS_SUCCESS;
break;
}
case IRP_MN_QUERY_DEVICE_RELATIONS: /* (optional) 0x07 */
{
switch (Stack->Parameters.QueryDeviceRelations.Type)
{
case BusRelations:
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / BusRelations\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
case RemovalRelations:
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / RemovalRelations\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
default:
ERR_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_DEVICE_RELATIONS / Unknown type 0x%lx\n",
Stack->Parameters.QueryDeviceRelations.Type);
return ForwardIrpAndForget(DeviceObject, Irp);
}
break;
}
case IRP_MN_FILTER_RESOURCE_REQUIREMENTS: /* (optional) 0x0d */
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_FILTER_RESOURCE_REQUIREMENTS\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
case IRP_MN_QUERY_PNP_DEVICE_STATE: /* 0x14 */
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_PNP_DEVICE_STATE\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
case IRP_MN_QUERY_REMOVE_DEVICE:
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_QUERY_REMOVE_DEVICE\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
case IRP_MN_CANCEL_REMOVE_DEVICE:
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_CANCEL_REMOVE_DEVICE\n");
return ForwardIrpAndForget(DeviceObject, Irp);
}
case IRP_MN_REMOVE_DEVICE:
{
TRACE_(I8042PRT, "IRP_MJ_PNP / IRP_MN_REMOVE_DEVICE\n");
Status = ForwardIrpAndForget(DeviceObject, Irp);
i8042RemoveDevice(DeviceObject);
return Status;
}
default:
{
ERR_(I8042PRT, "IRP_MJ_PNP / unknown minor function 0x%x\n", MinorFunction);
return ForwardIrpAndForget(DeviceObject, Irp);
}
}
Irp->IoStatus.Information = Information;
Irp->IoStatus.Status = Status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Status;
}
| sunnyden/reactos | drivers/input/i8042prt/pnp.c | C | gpl-2.0 | 27,818 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 20978 2010-02-08 15:35:25Z matthew $
*/
/**
* @category Zend
* @package Zend
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Qlick_Sauth_SocialException extends Exception
{
/**
* @var null|Exception
*/
private $_previous = null;
/**
* Construct the exception
*
* @param string $msg
* @param int $code
* @param Exception $previous
* @return void
*/
public function __construct($msg = '', $code = 0, Exception $previous = null)
{
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
parent::__construct($msg, (int) $code);
$this->_previous = $previous;
} else {
parent::__construct($msg, (int) $code, $previous);
}
}
/**
* Overloading
*
* For PHP < 5.3.0, provides access to the getPrevious() method.
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, array $args)
{
if ('getprevious' == strtolower($method)) {
return $this->_getPrevious();
}
return null;
}
/**
* String representation of the exception
*
* @return string
*/
public function __toString()
{
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
if (null !== ($e = $this->getPrevious())) {
return $e->__toString()
. "\n\nNext "
. parent::__toString();
}
}
return parent::__toString();
}
/**
* Returns previous Exception
*
* @return Exception|null
*/
protected function _getPrevious()
{
return $this->_previous;
}
}
| whiteboss/motora | library/Qlick/Sauth/SocialException.php | PHP | gpl-2.0 | 2,575 |
#!/usr/bin/perl
#
# Controller - is4web.com.br
# 2007 - 2011
package Controller;
require 5.008;
require Exporter;
#use strict;
use vars qw(@ISA $VERSION $INSTANCE %SWITCH);
#CONTROLLER
use Controller::DBConnector;
use Controller::SQL;
use Controller::LOG;
use Controller::Date;
use Controller::iUtils;
use Controller::Is;
use Controller::Mail;
#use Controller::Financeiro;
use Error; #TODO ver pra q e usar neh
use File::Find;
use Scalar::Util qw(looks_like_number);
#use open ':utf8', ':std';
#Desta forma eu abro o Controller e tenho todos os modulos, é melhor escolher o modulo e ele conter o controller: @ISA = qw( Controller::Date Controller::DBConnector Controller::LOG Controller::Date Controller::iUtils Controller::Registros Controller::Financeiro Exporter);
@ISA = qw( Controller::Date Controller::DBConnector Controller::SQL Controller::LOG Controller::iUtils Controller::Is Controller::Mail Exporter); #modulos básicos
#@EXPORT = qw();
#@EXPORT_OK = qw();
$VERSION = "2.0";
=pod
########### ChangeLog ####################################################### VERSION #
=item variable # #
- Added # 1.6 #
=item constant # #
- Added accurancy # 1.7 #
=item staffGroups # #
- Added staffGroups # 1.9 #
=item constant # #
- Added constants # 2.0 #
############################################################################# #
=cut
##CONSTANTS##
use constant {
TICKETS_OWNER_USER => 0,
TICKETS_OWNER_STAFF => 1,
TICKETS_OWNER_SYSTEM => 2,
TICKETS_OWNER_ACTION => 3,
TICKETS_METHOD_SYSTEM => 'ss',
TICKETS_METHOD_HD => 'hd',
TICKETS_METHOD_EMAIL => 'em',
TICKETS_METHOD_CALL => 'cc',
VISIBLE => 1,
HIDDEN => 0,
SERVICE_STATUS_BLOQUEADO => 'B',
SERVICE_STATUS_CONGELADO => 'P',
SERVICE_STATUS_CANCELADO => 'C',
SERVICE_STATUS_FINALIZADO => 'F',
SERVICE_STATUS_TRAFEGO => 'T',
SERVICE_STATUS_ESPACO => 'E',
SERVICE_STATUS_ATIVO => 'A',
SERVICE_STATUS_SOLICITADO => 'S',
SERVICE_ACTION_CREATE => 'C',
SERVICE_ACTION_MODIFY => 'M',
SERVICE_ACTION_SUSPEND => 'B',
SERVICE_ACTION_SUSPENDRES => 'P',
SERVICE_ACTION_REMOVE => 'R',
SERVICE_ACTION_ACTIVATE => 'A',
SERVICE_ACTION_RENEW => 'A',
SERVICE_ACTION_NOTHINGTODO => 'N',
SERVICE_ACTION_TRAFEGO => 'T',
SERVICE_ACTION_ESPACO => 'E',
INVOICE_STATUS_PENDENTE => 'P',
INVOICE_STATUS_QUITADO => 'Q',
INVOICE_STATUS_CANCELED => 'D',
INVOICE_STATUS_CONFIRMATION => 'C',
TABLE_STAFFS => 'staff',
TABLE_USERS => 'users',
TABLE_SERVICES => 'servicos',
TABLE_INVOICES => 'invoices', #TODO COLOCAR NOME DE TABELAS COM CONSTANTES
TABLE_ACCOUNTS => 'cc',
TABLE_BALANCES => 'saldos',
TABLE_CREDITS => 'creditos',
TABLE_CALLS => 'calls',
TABLE_NOTES => 'notes',
TABLE_CREDITCARDS => 'cc_info',
TABLE_PLANS => 'planos',
TABLE_PAYMENTS => 'pagamento',
TABLE_FORMS => 'formularios',
TABLE_STATS => 'stats',
TABLE_PERMS => 'security',
TABLE_PERMSGROUP => 'securitygroups',
TABLE_SERVERS => 'servidores',
TABLE_SETTINGS => 'settings',
TABLE_USERS_CONFIG=> 'users_config',
VALOR_M => 30,
VALOR_A => 360,
VALOR_D => 1,
VALOR_U => -1,
accuracy => '%.5f',
};
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
#Provide a unique instance
$INSTANCE and return($INSTANCE);
my $self = { @_ };
%{ $self->{configs} } = @_;
my $log = Controller::LOG->new(@_);
%$self = (
%$self,
%$log,
);
bless($self, $class);
$INSTANCE = $self; #cache instance
$SIG{'__DIE__'} = sub { $self->traceback($_[0]); };
$self->connect() || return $self;
$self->_setswitchs;
$self->_settings;#Init settings
$self->_setlang($self->setting('language')); #set default language;
$self->_setskin($self->setting('skin'));#Init default interface settings
$self->_setCGI;
$self->_setqueries;
$self->_country_codes;
$self->_feriados;
$self->_templates;
$self->get_time;#Init time
return $self;
}
sub reDie {
my $self = shift;
$SIG{'__DIE__'} = sub { $self->traceback($_[0]); };
}
sub configs {
my $self = shift;
return %{ $self->{configs} };
}
# Abolir esse uso
#sub _username {
# my ($self) = shift;
#
# $self->{'username'} = shift;
#
# return 1;
#}
sub error_code {
my $self = shift;
return $self->{'errorCode'}=undef unless $self->error;
$self->{'errorCode'} = $_[0] if $_[0] >= 0 && !$self->{'errorCode'} && $self->error && $Controller::SWITCH{skip_error} != 1;
return $self->{'errorCode'};
}
sub set_error {
my $self = shift;
$self->{ERR} = "@_" if "@_" ne "" && !$self->error && $Controller::SWITCH{skip_error} != 1;
return 0; #para poder utilizar com o return $self->set_error, assim se está retornando erro deve voltar 0
}
#TODO fazer todo {ERR} virar error e {ERR} = virar set_error
sub error { #TODO modificar o erro pra ser o cara q so mostra o erro e nao apaga
my $self = shift;
return $self->{ERR};
}
sub clear_error {
my $self = shift;
my $handle = $self->{ERR};
$self->{ERR} = undef; #Error Acknowledge
return $handle;
}
sub nice_error {
my $self = shift;
return undef unless $self->error;
local $Controller::SWITCH{skip_error} = 1;
# Skip the first frame [0], because it's the call to dotb.
# Skip the second frame [1], because it's the call to die, with redirection
my $frame = 0;
my $tab = 1;
while (my ($package, $filename, $line, $sub) = caller($frame++)) {
if ($package eq 'main') {
$sub =~ s/main:://;
push(@trace, trim("$sub() called from $filename on line $line"));
} else {
return undef if $sub eq '(eval)'; #O Pacote tem direito de chamar um eval para fazer seu próprio handle de erro #CASO: cPanel::PublicAPI.pm eval { require $module; } if ( !$@ ) { };
push(@trace, trim("$package::$sub() called from $filename on line $line\n"));
}
}
my $mess = "Traceback (most recent call last):\n";
$mess .= join("\n", map { " "x$tab++ . $_ } reverse(@trace) )."\n";
$mess .= "Package error: ".$self->clear_error."\n";
$self->logevent($mess);
$self->email (To => $self->setting('controller_mail'), From => $self->setting('adminemail'), Subject => $self->lang('sbj_nice_error'), Body => "Error: $mess" );
return $self->lang(1);
}
sub soft_reset {
my $self = shift;
foreach (keys %$self) {
delete $self->{$_} if $_ =~ m/^_current/;
}
}
sub hard_reset {
my $self = shift;
my $class = ref($self);
my %configs = $self->configs;
$INSTANCE = undef;
$self = undef;
$self = new Controller ( %configs );
# bless($self, $class);
return $self;
}
#save itens info
sub save {
@_ = @_;
my $self = shift;
return if $self->error;
return unless @{$_[2]};
do { $self->set_error($self->lang(51,'save')); return undef; } unless @{$_[1]} == @{$_[2]} && @{$_[3]} == @{$_[4]};
$self->execute_sql(qq|UPDATE `$_[0]` SET |.Controller::iSQLjoin($_[1],1,",")
.qq| WHERE |.Controller::iSQLjoin($_[3],1,","), @{$_[2]}, @{$_[4]});
return $self->error ? 0 : 1;
}
#Itens info
sub sid { #independente
my $self = shift;
$self->{_currentsid} = $self->num($_[0]) if exists $_[0];
#nao tem logica verificar isso $self->set_error($self->lang(3,'sid')) if exists $_[0] && $_[0] ne $self->service('id');
return $self->{_currentsid};
}
sub pid {#pode depender
my $self = shift;
if (exists $_[0]) { #Forçando um pid então não está cuidando de um serviço
$self->{_currentpid} = $self->num($_[0]) ;
$self->sid(0);#Liberando dependencia
} else {
#return $self->{_currentpid} = $self->service('servicos') if !$self->{_currentpid} && $self->sid;
$self->{_currentpid} = $self->service('servicos') if $self->sid > 0;
$self->set_error($self->lang(3,'pid')) if $self->{_currentpid} <= 0 && ($self->sid > 0);
}
return $self->{_currentpid};
}
sub uid { #Nao eh mais #uid(0) é o real username do servico
my $self = shift;
if (exists $_[0]) { #Forçando um uid então não está cuidando de um usuario
$self->{_currentuid} = $self->num($_[0]);
$self->sid(0);#Liberando dependencia
$self->balanceid(0);
$self->invid(0);
$self->callid(0);
} else {
$self->{_currentuid} = $self->service('username') if $self->sid > 0;
$self->{_currentuid} = $self->balance('username') if $self->balanceid > 0;
$self->{_currentuid} = $self->invoice('username') if $self->invid > 0;
$self->{_currentuid} = $self->call('username') if $self->callid > 0 && $self->call('username') > 0;
$self->set_error($self->lang(3,'uid')) if $self->{_currentuid} <= 0 && ($self->sid > 0 || $self->balanceid > 0 || $self->invid > 0 || ($self->callid > 0 && $self->call('username') > 0) );
}
return $self->{_currentuid};
}
sub srvid {#pode depender
@_=@_;
my $self = shift;
if (exists $_[0]) {
$self->{_currentsrvid} = $self->num($_[0]) ;
$self->sid(0);#Liberando dependencia
} else {
$self->{_currentsrvid} = $self->service('servidor') if $self->sid > 0;
$self->set_error($self->lang(3,'srvid')) if $self->{_currentsrvid} <= 0 && ($self->sid > 0);
}
return $self->{_currentsrvid};
}
sub payid {#pode depender
my $self = shift;
if (exists $_[0]) {
$self->{_currentpayid} = $self->num($_[0]) ;
$self->sid(0);#Liberando dependencia
} else {
$self->{_currentpayid} = $self->service('pg') if $self->sid > 0;
$self->set_error($self->lang(3,'payid')) if $self->{_currentpayid} <= 0 && ($self->sid > 0);
}
return $self->{_currentpayid};
}
sub callid {
my $self = shift;
$self->{_currentcallid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentcallid};
}
sub creditid {
my $self = shift;
$self->{_currentcreditid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentcreditid};
}
sub balanceid {
my $self = shift;
$self->{_currentbalanceid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentbalanceid};
}
sub actid {
my $self = shift;
$self->{_currentaccountid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentaccountid};
}
sub invid {
my $self = shift;
$self->{_currentinvoiceid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentinvoiceid};
}
sub ccid {
my $self = shift;
$self->{_currentccid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentccid};
}
sub tid {
my $self = shift;
$self->{_currenttid} = $self->num($_[0]) if exists $_[0];
return $self->{_currenttid};
}
sub staffid {
my $self = shift;
$self->{_currentstaffid} = $_[0] if exists $_[0];
return $self->{_currentstaffid};
}
sub entid {
my $self = shift;
$self->{_currententid} = $self->num($_[0]) if exists $_[0];
return $self->{_currententid};
}
sub deptid {
my $self = shift;
$self->{_currentdeptid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentdeptid};
}
sub did {
my $self = shift;
$self->{_currentdid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentdid};
}
sub logmailid {
my $self = shift;
$self->{_currentlogmailid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentlogmailid};
}
sub bankid {
my $self = shift;
$self->{_currentbankid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentbankid};
}
sub formtypeid {
my $self = shift;
$self->{_currentformtypeid} = $self->num($_[0]) if exists $_[0];
return $self->{_currentformtypeid};
}
##########################################
sub payment {
my $self = shift;
$self->get_payment unless exists $self->{payments}{$self->payid}{$_[0]} || exists $_[1];
$self->{payments}{$self->payid}{$_[0]} = $_[1] if exists $_[1];
return $self->{payments}{$self->payid}{$_[0]};
}
sub payments {
my ($self) = shift;
return $self->get_payments(1034);
}
sub service {
@_ = @_;#See Pel Bug http://rt.perl.org/rt3/Public/Bug/Display.html?id=7508
my $self = shift;
return \%{$self->{services}{$self->sid}} unless exists $_[0]; #copy
%{ $self->{services}{$self->sid}{changed} } = %{ $_[1] } if $_[0] eq 'changed' && exists $_[1];
return keys %{ $self->{services}{$self->sid}{changed} } if $_[0] eq 'changed';
$self->get_service unless exists $self->{services}{$self->sid}{$_[0]} || $_[0] =~ m/^_/; #Create data hash if not exist
my $atual = $_[0] eq 'dados' ? $self->{services}{$self->sid}{$_[0]}{$_[1]} : $self->{services}{$self->sid}{$_[0]};
$self->{services}{$self->sid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'dados' && exists $_[1] && exists $_[2];#special field
$self->{services}{$self->sid}{$_[0]} = $_[1] if exists $_[1] && $_[0] ne 'dados';
if (looks_like_number($atual)) { # ==
$self->{services}{$self->sid}{changed}{ $_[0] } = 1 if (exists $_[1] && $_[0] ne 'dados' && $atual != $_[1]) || (exists $_[2] && $_[0] eq 'dados' && $atual != $_[2]);
} else { # eq
$self->{services}{$self->sid}{changed}{ $_[0] } = 1 if (exists $_[1] && $_[0] ne 'dados' && $atual ne $_[1]) || (exists $_[2] && $_[0] eq 'dados' && $atual ne $_[2]);
}
#$self->logevent("\nDados: ".join ',', keys %{ $self->{services}{$self->sid}{'dados'} });
#puta faz isso depois nao aki, return $self->action($self->{services}{$self->sid}{$_[0]}) if $_[0] eq 'action'; #special field
return $self->{services}{$self->sid}{$_[0]}{$_[1]} if $_[0] eq 'dados' && exists $_[1]; # "$_[1]" BUG de charset no campo de dados
return $self->{services}{$self->sid}{$_[0]};
}
sub services {
my ($self) = shift;
$self->set_error($self->lang(3,'services')) and return unless $self->uid;
return $self->get_services(781,$self->uid); #select * sobrescrevia alteracoes de runtime, se definisse um proximo, ele lia denovo e sobrescrevia pelo antigo
#return grep {$self->{services}{$_}{'username'} == $self->uid} keys %{ $self->{services} };
}
sub serviceprop {
my ($self) = shift;
$self->get_serviceprop unless exists $self->{services}{$self->sid}{'properties'}{$_[0]} || exists $_[1]; #Create data hash if not exist
$self->{services}{$self->sid}{'properties'}{$_[0]}{$_[1]}{$_[2]} = $_[3] if $_[0] == 3 && exists $_[1] && exists $_[2] && exists $_[3];#special field
$self->{services}{$self->sid}{'properties'}{$_[0]} = $_[1] if exists $_[1] && $_[0] != 3;
return $self->{services}{$self->sid}{'properties'}{$_[0]}{$_[1]} if $_[0] == 3 && exists $_[1];
return $self->{services}{$self->sid}{'properties'}{$_[0]};
}
sub servicesprop {
my ($self,@sids) = @_;
$self->set_error($self->lang(3,'servicesprop')) and return unless @sids;
$self->get_servicesprop(824,join ',',@sids);
}
sub plan {
my $self = shift;
$self->get_plan unless exists $self->{plans}{$self->pid}{$_[0]} || exists $_[1];
$self->{plans}{$self->pid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'descontos' && exists $_[1];
$self->{plans}{$self->pid}{$_[0]} = $_[1] if $_[0] ne 'descontos' && exists $_[1];
return $self->{plans}{$self->pid}{$_[0]}{$self->service('pg')} if $_[0] eq 'descontos' && exists $_[1];
return $self->{plans}{$self->pid}{$_[0]};
}
sub plans {
my ($self) = @_;
$self->set_error($self->lang(3,'plans')) and return unless $self->uid;
return $self->get_plans(608,'%',$self->uid);
}
sub server {
my $self = shift;
$self->get_server unless exists $self->{servers}{$self->srvid}{$_[0]} || exists $_[1];
$self->{servers}{$self->srvid}{$_[0]} = $_[1] if exists $_[1];
return $self->{servers}{$self->srvid}{$_[0]};
}
sub servers { #TODO REDO
my ($self,@srvids) = @_;
$self->set_error($self->lang(3,'servers')) and return unless @srvids;
return $self->get_servers(45,join ',', map { $self->{servers}{$_}{'id'} } @srvids);
}
sub user {
my $self = shift;
my @__ = @_; #Protect from split and grep
return \%{$self->{users}{$self->uid}} unless exists $__[0]; #copy
%{ $self->{users}{$self->uid}{changed} } = %{ $__[1] } if $__[0] eq 'changed' && exists $__[1];
return keys %{ $self->{users}{$self->uid}{changed} } if $__[0] eq 'changed';
$self->get_user unless exists $self->{users}{$self->uid}{$__[0]} || $__[0] eq 'emails' || $__[0] =~ m/^_/;
my $getter = $__[0] eq 'email' ? join(',', @{ $self->{users}{$self->uid}{$__[0]} }) : $self->{users}{$self->uid}{$__[0]};
if (exists $__[1]) { #Setter
my $setter = $__[0] eq 'email' ? join(',', grep { $self->is_valid_email($_) } split(/\s*?[,;]\s*?/,trim($__[1])) ) : $__[1];
if (looks_like_number($getter)) { # ==
$self->{users}{$self->uid}{changed}{ $__[0] } = 1 if $self->num($getter) != $self->num($setter);
} else { # eq
$self->{users}{$self->uid}{changed}{ $__[0] } = 1 if $getter ne $setter;
}
$self->{users}{$self->uid}{$__[0]} = $__[0] eq 'email' ? [ split(',',trim($setter)) ] : $setter;
}
return join ',', @{ $self->user('email') } if $__[0] eq 'emails';
#use Data::Dumper;
#die Dumper \%{$self->{users}{$self->uid}} unless exists $__[1];
return $self->{users}{$self->uid}{$__[0]};
}
sub user_config {
my $self = shift;
my @__ = @_; #Protect from split and grep
return \%{$self->{users_config}{$self->uid}} unless exists $__[0]; #copy
return keys %{ $self->{users_config}{$self->uid}{changed} } if $__[0] eq 'changed';
$self->get_user_config unless exists $self->{users_config}{$self->uid}{$__[0]} || $__[0] =~ m/^_/;
my $getter = $self->{users_config}{$self->uid}{$__[0]};
if (exists $__[1]) { #Setter
my $setter = $__[1];
$self->{users_config}{$self->uid}{changed}{ $__[0] } = 1 if $getter ne $setter && $getter != $setter;
$self->{users_config}{$self->uid}{$__[0]} = $__[1];
}
return $self->{users_config}{$self->uid}{$__[0]};
}
sub invoice {
@_=@_;
my $self = shift;
return \%{$self->{invoices}{$self->invid}} unless exists $_[0]; #copy
$self->get_invoice unless exists $self->{invoices}{$self->invid}{$_[0]} || exists $_[1];
$self->{invoices}{$self->invid}{$_[0]}{$_[1]} = $_[2] if $_[0] eq 'services' && exists $_[1] && exists $_[2];#special field
$self->{invoices}{$self->invid}{$_[0]} = $_[1] if exists $_[1] && $_[0] ne 'services';
return $self->{invoices}{$self->invid}{$_[0]}{$_[1]} if $_[0] eq 'services' && exists $_[1];
return $self->{invoices}{$self->invid}{$_[0]};
}
sub invoices {
my ($self) = shift;
$self->set_error($self->lang(3,'invoices')) and return unless $self->uid;
return $self->get_invoices(439,'%',$self->uid);
#return grep {$self->{balances}{$_}{'username'} == $self->uid} keys %{ $self->{balances} };
}
sub account {
my $self = shift;
$self->get_account unless exists $self->{accounts}{$self->actid}{$_[0]} || exists $_[1];
$self->{accounts}{$self->actid}{$_[0]} = $_[1] if exists $_[1];
return $self->{accounts}{$self->actid}{$_[0]};
}
sub accounts {
my $self = shift;
# $self->set_error($self->lang(3,'accounts')) and return unless $self->uid;
$self->get_accounts(424);
return keys %{ $self->{accounts} };
}
sub credit {
my $self = shift;
$self->get_credit unless exists $self->{credits}{$self->creditid}{$_[0]} || exists $_[1];
$self->{credits}{$self->creditid}{$_[0]} = $_[1] if exists $_[1];
return $self->{credits}{$self->creditid}{$_[0]};
}
sub credits {
my ($self) = shift;
$self->set_error($self->lang(3,'credits')) and return unless $self->uid;
return $self->get_credits(482,$self->uid);
}
sub balance {
my $self = shift;
$self->get_balance unless exists $self->{balances}{$self->balanceid}{$_[0]} || exists $_[1];
$self->{balances}{$self->balanceid}{$_[0]} = $_[1] if exists $_[1];
return $self->{balances}{$self->balanceid}{$_[0]};
}
sub balances {
my ($self) = shift;
$self->set_error($self->lang(3,'balances')) and return unless $self->uid;
return $self->get_balances(450,'O',$self->uid);
#return grep {$self->{balances}{$_}{'username'} == $self->uid} keys %{ $self->{balances} };
}
sub servicebalances {
my ($self) = shift;
$self->set_error($self->lang(3,'servicebalances')) and return unless $self->sid;
return $self->get_balances(454,'O',$self->sid);
}
sub call {
my $self = shift;
$self->get_call unless exists $self->{calls}{$self->callid}{$_[0]} || exists $_[1];
$self->{calls}{$self->callid}{$_[0]} = $_[1] if exists $_[1];
return $self->{calls}{$self->callid}{$_[0]};
}
sub calls {
my ($self) = shift;
$self->set_error($self->lang(3,'calls')) and return unless $self->uid; #se tem sid vai ter uid
return $self->get_calls(367,$self->sid) if $self->sid;
return $self->get_calls(366,$self->uid) if $self->uid;
return ();
}
sub followers {
my $self = shift;
$self->set_error($self->lang(3,'followers')) and return unless $self->callid;
my $sth = $self->select_sql(380,$self->callid);
my @followers = map {@{$_}} @{ $sth->fetchall_arrayref() };
$self->finish;
return @followers;
}
sub following {
my $self = shift;
$self->set_error($self->lang(3,'following')) and return unless $self->staffid;
my $sth = $self->select_sql(379,$self->staffid);
my @following = map {@{$_}} @{ $sth->fetchall_arrayref() };
$self->finish;
return @following;
}
sub creditcard {
my $self = shift;
$self->get_creditcard unless exists $self->{creditcards}{$self->ccid}{$_[0]} || exists $_[1];
$self->{creditcards}{$self->ccid}{$_[0]} = $_[1] if exists $_[1];
return $self->{creditcards}{$self->ccid}{$_[0]};
}
sub creditcards {
my $self = shift;
$self->set_error($self->lang(3,'creditcards')) and return unless $self->uid;
return $self->get_creditcards(855,$self->uid);
#return keys %{ $self->{creditcards} };
}
sub creditcard_active {
my $self = shift;
$self->set_error($self->lang(3,'creditcard_active')) and return unless $self->uid;
$self->get_creditcards(852,$self->tid,1,$self->uid);
my ($ccid) = grep { $self->{creditcards}{$_}{'active'} == 1 && $self->{creditcards}{$_}{'tarifa'} == $self->tid && $self->{creditcards}{$_}{'username'} == $self->uid} keys %{ $self->{creditcards} };
return $ccid;
}
sub tax {
my $self = shift;
$self->get_tax unless exists $self->{taxs}{$self->tid}{$_[0]} || exists $_[1];
$self->{taxs}{$self->tid}{$_[0]} = $_[1] if exists $_[1];
return $self->{taxs}{$self->tid}{$_[0]};
}
sub taxs {
my $self = shift;
# $self->set_error($self->lang(3,'taxs')) and return unless $self->uid;
return $self->get_taxs(872);
#return keys %{ $self->{taxs} };
}
sub enterprise {
my $self = shift;
$self->get_enterprise unless exists $self->{enterprises}{$self->entid}{$_[0]} || exists $_[1];
$self->{enterprises}{$self->entid}{$_[0]} = $_[1] if exists $_[1];
return $self->{enterprises}{$self->entid}{$_[0]};
}
sub enterprises {
my $self = shift;
return $self->get_enterprises(303);
#return keys %{ $self->{enterprises} };
}
sub department {
my $self = shift;
$self->get_department unless exists $self->{departments}{$self->deptid}{$_[0]} || exists $_[1];
$self->{departments}{$self->deptid}{$_[0]} = $_[1] if exists $_[1];
return $self->{departments}{$self->deptid}{$_[0]};
}
sub departments {
my $self = shift;
return $self->get_departments(266);
#return keys %{ $self->{departments} };
}
sub formtype {
my $self = shift;
$self->get_formtype unless exists $self->{formtypes}{$self->formtypeid}{$_[0]} || exists $_[1];
$self->{formtypes}{$self->formtypeid}{$_[0]} = $_[1] if exists $_[1];
return $self->{formtypes}{$self->formtypeid}{$_[0]};
}
sub staff {
my $self = shift;
$self->get_staff unless exists $self->{staffs}{$self->staffid}{$_[0]} || exists $_[1];
$self->{staffs}{$self->staffid}{$_[0]} = $_[1] if exists $_[1];
return join ',', @{ $self->{staffs}{$self->staffid}{'email'} } if $_[0] eq 'emails';
return $self->{staffs}{$self->staffid}{$_[0]};
}
sub staffGroups {
my $self = shift;
return undef if $self->error;
$self->set_error($self->lang(3,'get_staffGroups')) and return unless $self->staffid;
my $sth = $self->select_sql(1083, $self->staffid);
my @gids = map {@{$_}} @{ $sth->fetchall_arrayref() };
$self->finish;
return @gids;
}
sub groups {
my $self = shift;
return undef if $self->error;
my $sth = $self->select_sql(1084);
my @gids = map {@{$_}} @{ $sth->fetchall_arrayref() };
$self->finish;
return @gids;
}
sub logmail {
my $self = shift;
$self->get_logmail unless exists $self->{logmails}{$self->logmailid}{$_[0]} || exists $_[1];
$self->{logmails}{$self->logmailid}{$_[0]} = $_[1] if exists $_[1];
return $self->{logmails}{$self->logmailid}{$_[0]};
}
sub logmails {
my $self = shift;
return $self->get_logmails(163);
}
sub bank {
my $self = shift;
$self->get_bank unless exists $self->{banks}{$self->bankid}{$_[0]} || exists $_[1];
$self->{banks}{$self->bankid}{$_[0]} = $_[1] if exists $_[1];
return $self->{banks}{$self->bankid}{$_[0]};
}
sub banks {
my $self = shift;
return $self->get_banks(427);
}
sub perm {
my $self = shift;
my $id = $self->uid || $self->staffid;
$self->set_error($self->lang(3,'perm')) and return unless $id;
$self->get_perm unless exists $self->{perms}{$id};
return $self->{perms}{$id}{$_[0]}{$_[1]}{$_[2]} || $self->{perms}{$id}{$_[0]}{'all'}{$_[2]} if exists $_[2];
return \%{ $self->{perms}{$id}{$_[0]}{$_[1]} } if exists $_[1]; #copy
return \%{ $self->{perms}{$id}{$_[0]} } if exists $_[0]; #copy
return \%{ $self->{perms}{$id} }; #copy
}
sub perms {
#my $self = shift;
#my $id = $self->uid || $self->staffid;
#$self->set_error($self->lang(3,'perms')) and return unless $id;
#return keys %{$self->perm};
}
############################################
#Copy data
sub copy_service {
my ($self,$source,$target) = @_;
$self->sid($source);
my $ref = $self->service;
$self->sid($target);
my $ref2 = $self->service;
%$ref2 = %$ref;
return $self->sid($source);
}
sub shadow_copy {
my $self = shift;
if ($_[0] eq 'services') {
my $ref = $self->service;
%{ $self->{'shadow'}{$_[0]}{$self->sid} } = %$ref;
}
return 1;
}
sub AUTOLOAD { #Holds all undef methods
my $self = $_[0];
my $type = ref($self) or die "$AUTOLOAD is not an object";
my $name = $AUTOLOAD;
$name =~ s/.*://; # strip fully-qualified portion
#Determinar qual modulo usar e importar
#use Modulo e chama a funcao, é melhor determinar pelos modulos dos planos, serve para caso
#nao tenha buscar os padroes
if ($name =~ s/_shadow$//i) {
use B::RecDeparse;
my $deparse = B::RecDeparse->new;
my $newsub = $deparse->coderef2text( eval "\\&Controller::$name" );
$newsub =~ s/\$\$self{(.+?)}/\$self->{'shadow'}{$1}/g;
#$newsub =~ s/\$\$self{(.+?)}/\$\$self{'shadow'}{$1}/g;
$newsub =~ s/package.*//;
eval "sub func $newsub"; # the inverse operation
return func(@_);
}
if ($name =~ /registrar|renew|expire/i) {
$self->manual_action;
return $self->error ? 0 : 1;
}
if ($name =~ /availdomain/i) {
return 1; #sempre disponivel, já que nao foi consultado
}
$self->set_error("$name not implemented");
return undef;#Simular erro
}
############################################
sub lock_billing {
my ($self) = shift;
local $Controller::SWITCH{skip_log} = 1;
my $date = exists $_[1] ? $_[1] : $self->today();
my $time = exists $_[2] ? $_[2] : undef;
$self->execute_sql(21,$self->uid,$date,$time) if $self->uid;
return 1;
}
sub unlock_billing {
my ($self) = shift;
local $Controller::SWITCH{skip_log} = 1;
$self->execute_sql(22,$self->uid) if $self->uid;
return 1;
}
sub action {
my $self = shift;
my %act = ( 'C' => $self->lang("CREATE"),
'M' => $self->lang("MODIFY"),
'B' => $self->lang("SUSPEND"),
'P' => $self->lang("SUSPENDRES"),
'R' => $self->lang("REMOVE"),
'A' => $self->lang("ACTIVATE"),
'N' => $self->lang("NOTHINGTODO") );
return $act{uc shift};
}
sub valor {
my ($self,$opt) = @_;
if ($opt == 1) {
return $self->VALOR_M if $self->plan('valor_tipo') eq 'M';
return $self->VALOR_A if $self->plan('valor_tipo') eq 'A';
return $self->VALOR_D if $self->plan('valor_tipo') eq 'D';
return $self->VALOR_U if $self->plan('valor_tipo') eq 'U';
} else {
return $self->lang('Month') if $self->plan('valor_tipo') eq 'M';
return $self->lang('Year') if $self->plan('valor_tipo') eq 'A';
return $self->lang('Day') if $self->plan('valor_tipo') eq 'D';
return $self->lang('Unique') if $self->plan('valor_tipo') eq 'U';
}
$self->set_error($self->lang(1003));
die $self->lang(1003); #Valor tipo não reconhecido
}
sub installment {
my $self = shift;
my %inst = ( 'S' => $self->lang("INSTALLMENT_S"),
'O' => $self->lang("INSTALLMENT_O"),
'L' => $self->lang("INSTALLMENT_L"),
'D' => $self->lang("INSTALLMENT_D") );
return $inst{uc shift};
}
#######################################
#data mount
sub mount_service {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
#precisa sim #next if $ref->{"servidor"} == 1; # Não há informações sobre o servidor nenhum
my $sid = $ref->{'id'};
push @ids_matched, $sid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
#next if $q eq 'id'; TODO deixar o id pra verificar consistencia, ver sub sid()
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'services'}{$sid}{lc $q} = $self->date($ref->{$q});
} elsif ($q eq 'dados') {
$self->{'services'}{$sid}{lc $q} = undef;
foreach (split("::",$ref->{$q})) {
my ($col,$val) = split(" : ",$_);
$self->{'services'}{$sid}{lc $q}{trim($col)} = trim($val);
}
} else {
$self->{'services'}{$sid}{lc $q} = $ref->{$q};
}
}
}
return @ids_matched;
}
sub get_service {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_service')) and return unless $self->sid;
$self->select_sql(780,$self->sid);
$self->mount_service;
$self->finish;
#$self->logevent("Get DB: ".join ',', keys %{ $self->{services}{$self->sid}{'dados'} });
return $self->error ? 0 : 1;
}
sub get_services {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_services')) and return unless $sql;
$self->select_sql($sql,@params);
my @services = $self->mount_service;
$self->finish;
return $self->error ? undef : @services;
}
sub mount_serviceprop {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $sid = $ref->{'servico'};
push @ids_matched, $sid;
if ($ref->{'type'} == 3) {
#4.90::3,4,5,6::2008|6.65::1,8::2009
foreach ( split('\|',$ref->{'value'}) ) {
my($val,$months,$year) = split('::',$_,3);
#TODO Ajustar isso para ter valores diferente para cada mês. Valores em porcentagem também serem aceitos para variarem junto com o valor do plano.
#Adicionado tipo 7
$self->{services}{$sid}{'properties'}{$ref->{'type'}}{$year} = {
'value' => $val,
'months' => [split ',', $months],
}
}
} elsif ($ref->{'type'} == 7) {
#{} hash dump
$self->{services}{$sid}{'properties'}{$ref->{'type'}} = eval $ref->{'value'};
} else {
my $value = $self->num($ref->{'value'}) < 0 ? 0 : $self->num($ref->{'value'});
$self->{services}{$sid}{'properties'}{$ref->{'type'}} = $value;
}
}
return @ids_matched;
}
sub get_serviceprop {
my ($self) = shift;
return 0 if $self->error;
#types 1 - dias gratis 2 - Sem taxa de setup 3 - Descontos em meses
#4 - Nao se orientar pelo vc do usuario 5 - dias para finalizar 6 - fatura exclusiva
#7 - Valores +- por mes/ano % ou $
$self->set_error($self->lang(3,'get_serviceprop')) and return unless $self->sid;
$self->select_sql(824,$self->sid);
$self->mount_serviceprop;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_servicesprop {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_serviceprop')) and return unless $sql;
$self->select_sql($sql,@params);
my @props = $self->mount_serviceprop;
$self->finish;
return $self->error ? undef : @props;
}
sub mount_plan {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $pid = $ref->{'servicos'};
push @ids_matched, $pid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq 'servicos';
$self->{'plans'}{$pid}{lc $q} = $ref->{$q};
}
#isso nao existe, nao tem como acontecer $self->{'plans'}{$pid}{'descontos'}{$ref->{'pg'}} = $ref->{'desconto'};
}
return @ids_matched;
}
sub get_plan {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_plan')) and return unless $self->pid;
$self->select_sql(604,$self->pid);
$self->mount_plan;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_plans {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_plans')) and return unless $sql;
$self->select_sql($sql,@params);
my @plans = $self->mount_plan;
$self->finish;
return $self->error ? 0 : @plans;
}
sub mount_tax {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $tid = $ref->{'id'};
push @ids_matched, $tid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq 'id';
$self->{'taxs'}{$tid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_tax {
my ($self) = shift;
return 0 if $self->error;
#
$self->set_error($self->lang(3,'get_tax')) and return unless $self->tid;
$self->select_sql(871,$self->tid);
$self->mount_tax;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_taxs {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_taxs')) and return unless $sql;
$self->select_sql($sql,@params);
my @taxs = $self->mount_tax;
$self->finish;
return $self->error ? 0 : @taxs;
}
sub mount_server {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $srvid = $ref->{'id'};
push @ids_matched, $srvid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'servers'}{$srvid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_server {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_server')) and return unless $self->srvid;
$self->select_sql(45,$self->srvid);
$self->mount_server;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_servers {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_servers')) and return unless $sql;
$self->select_sql($sql,@params);
my @servers = $self->mount_server;
$self->finish;
return $self->error ? 0 : @servers;
}
sub mount_payment {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $payid = $ref->{'id'};
push @ids_matched, $payid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'payments'}{$payid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_payment {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_payment')) and return unless $self->payid;
$self->select_sql(1030,$self->payid);
my @payments = $self->mount_payment;
$self->finish;
return $self->error ? 0 : @payments;
}
sub get_payments {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_payments')) and return unless $sql;
$self->select_sql($sql,@params);
my @payments = $self->mount_payment;
$self->finish;
return $self->error ? undef : @payments;
}
sub mount_user {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $uid = $ref->{'username'};
push @ids_matched, $uid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "username";
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'users'}{$uid}{lc $q} = $self->date($ref->{$q});
} elsif ($q eq 'email') {
$self->{'users'}{$uid}{lc $q} = [ grep { $self->is_valid_email($_) } split(/\s*?[,;]\s*?/,trim($ref->{$q})) ];
} else {
$self->{'users'}{$uid}{lc $q} = $ref->{$q};
}
}
}
return @ids_matched;
}
sub mount_user_config {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while($sth and (my $ref = $sth->fetchrow_hashref())) {
my $set = lc $ref->{'setting'};
push @ids_matched, $set;
$self->{'users_config'}{$ref->{'username'}}{$set} = $ref->{'value'};
}
return @ids_matched;
}
sub get_user {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_user')) and return unless $self->uid;
$self->select_sql(680,$self->uid);
my @users = $self->mount_user;
$self->finish;
return $self->error ? 0 : @users;
}
sub get_user_config {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_user_config')) and return unless $self->uid;
$self->select_sql(681,$self->uid);
my @configs = $self->mount_user_config;
$self->finish;
return $self->error ? 0 : @configs;
}
sub get_users {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_users')) and return unless $sql;
$self->select_sql($sql,@params);
my @users = $self->mount_user;
$self->finish;
return $self->error ? undef : @users;
}
sub mount_invoice {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $invid = $ref->{'id'};
push @ids_matched, $invid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'invoices'}{$invid}{lc $q} = $self->date($ref->{$q});
} elsif ($q eq 'services') {
$self->{'invoices'}{$invid}{lc $q} = {}; #Inicializando
$self->{'invoices'}{$invid}{lc $q}{$2} = $1 while $ref->{$q} =~ m/(\d+?)x(\d+?) -\s?/g;
} else {
$self->{'invoices'}{$invid}{lc $q} = $ref->{$q};
}
}
}
return @ids_matched;
}
sub get_invoice {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_invoice')) and return unless $self->invid;
$self->select_sql(437,$self->invid);
$self->mount_invoice;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_invoices {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_invoices')) and return unless $sql;
$self->select_sql($sql,@params);
my @invoices = $self->mount_invoice;
$self->finish;
return $self->error ? undef : @invoices;
}
sub mount_account {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $actid = $ref->{'id'};
push @ids_matched, $actid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
if ($q eq 'agencia') {
my ($pre,$pos) = split('-',$ref->{$q});
$self->{'accounts'}{$actid}{lc ($q.'dv')} = $pos;
$self->{'accounts'}{$actid}{lc $q} = $pre;
} elsif ($q eq 'conta') {
my ($pre,$pos) = split('-',$ref->{$q});
$self->{'accounts'}{$actid}{lc ($q.'dv')} =$pos;
$self->{'accounts'}{$actid}{lc $q} =$pre;
} else {
$self->{'accounts'}{$actid}{lc $q} = $ref->{$q};
}
}
}
return @ids_matched;
}
sub get_account {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_acccount')) and return unless $self->actid;
my $sth = $self->select_sql(423,$self->actid);
$self->mount_account;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_accounts {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_accounts')) and return unless $sql;
$self->select_sql($sql,@params);
my @accounts = $self->mount_account;
$self->finish;
return $self->error ? undef : @accounts;
}
sub mount_balance {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $bid = $ref->{'id'};
push @ids_matched, $bid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'balances'}{$bid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_balance {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_balance')) and return unless $self->balanceid;
$self->select_sql(449,$self->balanceid);
$self->mount_balance;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_balances {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_balances')) and return unless $sql;
$self->select_sql($sql,@params);
my @balances = $self->mount_balance;
$self->finish;
return $self->error ? undef : @balances;
}
sub mount_credit {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $creditid = $ref->{'id'};
push @ids_matched, $creditid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'credits'}{$creditid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_credit {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_credit')) and return unless $self->creditid;
$self->select_sql(481,$self->creditid);
$self->mount_credit;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_credits {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_credits')) and return unless $sql;
$self->select_sql($sql,@params);
my @credits = $self->mount_credit;
$self->finish;
return $self->error ? undef : @credits;
}
sub mount_call {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $callid = $ref->{'id'};
push @ids_matched, $callid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'calls'}{$self->callid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_call {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_call')) and return unless $self->callid;
$self->select_sql(365,$self->callid);
$self->mount_call;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_calls {
my ($self,$sql,@params) = @_;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_calls')) and return unless $sql;
$self->select_sql($sql,@params);
my @calls = $self->mount_call;
$self->finish;
return $self->error ? undef : @calls;
}
sub mount_creditcard {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $ccid = $ref->{'id'};
push @ids_matched, $ccid;
#preciso listar mesmo que esteja recusado next if $ref->{'active'} == -1; #recusado
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
if ($q =~ m/^(?:ccn|cvv2)$/) { #campos criptografados
$self->{'creditcards'}{$ccid}{lc $q} = Controller::decrypt_mm($ref->{$q});
} else {
$self->{'creditcards'}{$ccid}{lc $q} = $ref->{$q};
}
}
#TODO ajustar isso, esses langs nem eram pra existir
# Vou mudar pra ficar um só cartão de cada tipo
my $status = $self->lang('Active') if $ref->{'active'} == 1;
$status = $self->lang('Activating') if $ref->{'active'} == 2;
$status = $self->lang('Deactivated') if $ref->{'active'} == 0;
$status = $self->lang('Refused') if $ref->{'active'} == -1;
$self->{'creditcards'}{$ccid}{'status'} = $status;
#last if $ref->{'active'} == 1;#1= Ativo -1= Recusado 0= Desativado 2= Ativando
}
return @ids_matched;
}
sub get_creditcard {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_creditcard')) and return unless $self->ccid;
$self->select_sql(851,$self->ccid);
$self->mount_creditcard;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_creditcards {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_creditcards')) and return unless $sql;
$self->select_sql($sql,@params);
my @creditcards = $self->mount_creditcard;
$self->finish;
return $self->error ? undef : @creditcards;
}
sub mount_formtype {
my ($self) = shift;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $id = $ref->{'id'};
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
if ($q eq 'properties') {
#[1=30][3=4.90::3,4,5,6::2008|6.65::1,8::2009]
foreach my $propertie ($ref->{$q} =~ /\[(.+?)\]/g) {
my ($type,$value) = split('=',$propertie);
$self->{'formtypes'}{$id}{'properties'}{$type} = $value;
#repassar as info pra salvar, elas processada de nada ainda servem
# if ($type == 3) {
# foreach ( split('\|',$value) ) {
# my($val,$months,$year) = split('::',$_,3);
# $self->{'formtypes'}{$id}{'properties'}{$type}{$year} = {
# 'value' => $val,
# 'months' => [split ',', $months],
# }
# }
# } else {
# my $value = $self->num($value) < 0 ? 0 : $self->num($value);
# $self->{'formtypes'}{$id}{'properties'}{$type} = $value;
# }
}
} elsif ($q eq 'planos') {
$self->{'formtypes'}{$id}{lc $q} = [ split ',', $ref->{$q} ];
} else {
$self->{'formtypes'}{$id}{lc $q} = $ref->{$q};
}
}
}
}
sub get_formtype {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_formtype')) and return unless $self->formtypeid;
$self->select_sql(1050,$self->formtypeid);
$self->mount_formtype;
$self->finish;
return $self->error ? 0 : 1;
}
sub mount_staff {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $staffid = $ref->{'username'};
push @ids_matched, $staffid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq 'username';
$self->{'staffs'}{$staffid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_staff {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_staff')) and return unless $self->staffid;
$self->select_sql(331,$self->staffid);
$self->mount_staff;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_staffs {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_staffs')) and return unless $sql;
$self->select_sql($sql,@params);
my @staffs = $self->mount_staff;
$self->finish;
return $self->error ? undef : @staffs;
}
sub mount_enterprise {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $entid = $ref->{'id'};
push @ids_matched, $entid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'enterprises'}{$entid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_enterprise {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_enterprise')) and return unless $self->entid;
$self->select_sql(304,$self->entid);
$self->mount_enterprise;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_enterprises {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_enterprises')) and return unless $sql;
$self->select_sql($sql,@params);
my @enterprises = $self->mount_enterprise;
$self->finish;
return $self->error ? 0 : @enterprises;
}
sub mount_department {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $deptid = $ref->{'id'};
push @ids_matched, $deptid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'departments'}{$deptid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_department {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_department')) and return unless $self->deptid;
$self->select_sql(267,$self->deptid);
$self->mount_department;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_departments {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_departments')) and return unless $sql;
$self->select_sql($sql,@params);
my @departments = $self->mount_department;
$self->finish;
return $self->error ? undef : @departments;
}
sub mount_discount {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $did = $ref->{'id'};
push @ids_matched, $did;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
$self->{'enterprises'}{$entid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_discount {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_enterprise')) and return unless $self->entid;
$self->select_sql(304,$self->entid);
$self->mount_enterprise;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_discounts {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_enterprises')) and return unless $sql;
$self->select_sql($sql,@params);
my @enterprises = $self->mount_enterprise;
$self->finish;
return $self->error ? 0 : @enterprises;
}
sub mount_logmail {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $logmailid = $ref->{'id'};
push @ids_matched, $logmailid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "id";
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'logmails'}{$logmailid}{lc $q} = $self->date($ref->{$q});
} elsif ($q eq 'body') {
$self->{'logmails'}{$logmailid}{lc $q} = $ref->{$q};
$self->{'logmails'}{$logmailid}{lc $q} =~ s/\\(\W)/$1/g; #Emails antigos
} else {
$self->{'logmails'}{$logmailid}{lc $q} = $ref->{$q};
}
}
}
return @ids_matched;
}
sub get_logmail {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_logmail')) and return unless $self->logmailid;
$self->select_sql(164,$self->logmailid);
$self->mount_logmail;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_logmails {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_logmails')) and return unless $sql;
$self->select_sql($sql,@params);
my @logmails = $self->mount_logmail;
$self->finish;
return $self->error ? 0 : @logmails;
}
sub mount_bank {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $bankid = $ref->{'codigo'};
push @ids_matched, $bankid;
foreach my $q (keys %{$sth->{NAME_hash}}) {
next if $q eq "codigo";
$self->{'banks'}{$bankid}{lc $q} = $ref->{$q};
}
}
return @ids_matched;
}
sub get_bank {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'get_bank')) and return unless $self->bankid;
$self->select_sql(426,$self->bankid);
$self->mount_bank;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_banks {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_banks')) and return unless $sql;
$self->select_sql($sql,@params);
my @banks = $self->mount_bank;
$self->finish;
return $self->error ? 0 : @banks;
}
sub mount_perm {
my ($self) = shift;
my @ids_matched;
my $sth = $self->last_select;
while(my $ref = $sth->fetchrow_hashref()) {
my $permid = $ref->{'username'};
push @ids_matched, $permid;
#foreach my $q (keys %{$sth->{NAME_hash}}) {
# next if $q eq "username";
my ($module,$type,$name) = split(/:/, $ref->{'right'}, 3);
$self->{'perms'}{$permid}{lc $module}{lc $type}{lc $name} = $ref->{'value'} if $module && $type && $name;
#}
}
return @ids_matched;
}
sub get_perm {
my ($self) = shift;
return 0 if $self->error;
my $id = $self->uid || $self->staffid;
$self->set_error($self->lang(3,'get_perm')) and return unless $id;
if ($self->staffid && $self->staffGroups) { #Staff groups
my $sql_1082 = $self->{queries}{1082};
my @gids = $self->staffGroups;
$sql_1082 .= qq| `groupname` IN ('|.join('\',\'', @gids).qq|')| if @gids;
$sql_1082 .= qq| ORDER BY (`username` = ?)|; #Permissao individual preferencial
$self->select_sql($sql_1082,$id,$id,$id);
} else {
$self->select_sql(1081,$id);
}
$self->mount_perm;
$self->finish;
return $self->error ? 0 : 1;
}
sub get_perms {
my ($self,$sql,@params) = @_;
return undef if $self->error;
$self->set_error($self->lang(3,'get_perms')) and return unless $sql;
$self->select_sql($sql,@params);
my @perms = $self->mount_perm;
$self->finish;
return $self->error ? 0 : @perms;
}
##########################################
#Search items
sub return_username {
my ($self) = shift;
#TODO sempre atualizar para novas tabelas
#MUITO CUIDADO COM O UID ou SID ou OUTRO, POIS PERDE A REFERENCIA
$self->invid($_[0]) and return $self->invoice('username') if ($self->TABLE_INVOICES && $_[1] =~ /(?:${\$self->TABLE_INVOICES})(?:,|$)/i);
$self->callid($_[0]) and return $self->call('username') if ($self->TABLE_CALLS && $_[1] =~ /(?:${\$self->TABLE_CALLS})(?:,|$)/i);
$self->callid($_[0]) and return $self->call('username') if ($self->TABLE_NOTES && $_[1] =~ /(?:${\$self->TABLE_NOTES})(?:,|$)/i);
$self->balanceid($_[0]) and return $self->balance('username') if ($self->TABLE_BALANCES && $_[1] =~ /(?:${\$self->TABLE_BALANCES})(?:,|$)/i);
$self->creditid($_[0]) and return $self->credit('username') if ($self->TABLE_CREDITS && $_[1] =~ /(?:${\$self->TABLE_CREDITS})(?:,|$)/i);
$self->ccid($_[0]) and return $self->creditcard('username') if ($self->TABLE_CREDITCARDS && $_[1] =~ /(?:${\$self->TABLE_CREDITCARDS})(?:,|$)/i);
}
sub return_sender {
my ($self) = shift;
if ($_[0] eq 'User' && $self->uid) {
my $level = $self->user('level');
#default will be the first
$level =~ s/^[:]+//;
my $entid = (split('::',$level))[0];
$self->entid($self->num($entid));
$sender = $self->enterprise('mail_account') if $self->entid;
}
if ($_[0] eq 'Billing' && $self->uid) {
my $level = $self->user('level');
#default will be the first
$level =~ s/^[:]+//;
my $entid = (split('::',$level))[0];
$self->entid($self->num($entid));
$sender = $self->enterprise('mail_billing') if $self->entid;
}
return $sender || $self->setting('adminemail');
}
sub search_srvid {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'search_server')) and return unless $_[0] || $_[1];
my $sth = $self->select_sql(qq|SELECT `id` FROM `servidores` WHERE `$_[0]` = ?|,$_[1]);
my ($id) = $sth->fetchrow_array if $sth;
$self->finish;
return $self->error ? '' : $id;
}
sub search_sid {
my ($self) = shift;
return 0 if $self->error;
$self->set_error($self->lang(3,'search_service')) and return unless $_[0] || $_[1];
my $op = '=';
my $value = $_[1];
if ($_[0] eq 'dados') {
$op = 'LIKE';
$value = '%'."$_[1] : $_[2]".'::%';
}
my $sth = $self->select_sql(qq|SELECT `id` FROM `servicos` WHERE `$_[0]` $op ?|,$value);
return 0 if $sth->rows != 1;
my ($id) = $sth->fetchrow_array if $sth;
$self->finish;
return $self->error ? 0 : $id;
}
#Template System
sub template {
@_=@_;
my $self = shift;
return \%{$self->{templates}} unless exists $_[0]; #copy
$self->{templates}{$_[0]} = $_[1] if exists $_[1];
return $self->{templates}{$_[0]};
}
sub template_html {
@_=@_;
my $self = shift;
return \%{$self->{templates}} unless exists $_[0]; #copy
$self->{templates}{$_[0]} = $_[1] if exists $_[1];
$self->{templates}{$_[0]} =~ s/\n/<br>/g;
return $self->{templates}{$_[0]};
}
sub template_parse {
my ($self,$ctype) = @_;
if ($ctype eq 'text/plain') {
$_ =~ s/\{(\S+?)\}/$self->template($1)/egi;
} else {
$_ =~ s/\{(\S+?)\}/$self->template_html($1)/egi;
}
}
#Lang System
sub lang_parse {
my ($self) = @_;
$_ =~ s/(\%(\S*?)\%)/$self->{lang}{$2} ? $self->{lang}{$2} : ( $2 ? "missing_$2": "%")/ge;
}
sub _setlang {
my ($self,$language) = @_;
return 0 if !$language;
#protect ourself
escape(\$language);
if (-e $self->setting('app')."/lang/$language/lang.inc") {
$self->{_setlang} = $language;
our %LANG = ();
my $ret = do($self->setting('app')."/lang/$language/lang.inc");
#Problemas com UTF-8, o arquivo tem que estar nesse formato para não deformar os caracteres do sistema
die "couldn't parse lang file: $@" if $@;
die "couldn't do lang file: $!" unless defined $ret;
die "couldn't run lang file" unless $ret;
$self->{'lang'} = { %LANG };
return 1;
} else {
$self->set_error('Lang not found at '.$self->setting('app')."/lang/$language/lang.inc");
return 0;
}
}
sub lang {
my ($self,$no,@values) = @_;
($no,@values) = @$no if (ref $no eq "ARRAY");
# return "missing_$no_" unless exists $self->{lang}{$no};
return $no unless exists $self->{lang}{$no}; #Broke non-translations, who needs must override
return sprintf("$self->{lang}{$no}",@values);
}
sub servicos {
my ($self) = shift;
my @q = split(" ","@_");
return 0 if $self->error;
$self->set_error($self->lang(3,'servicos')) and return unless $self->num($self->{'service'}{'id'});
my $sth = $self->select_sql(qq|SELECT * FROM `servicos` INNER JOIN `planos` ON `servicos`.`servicos`=`planos`.`servicos` WHERE `id` = ?|,$self->num($self->{'service'}{'id'}));
while(my $ref = $sth->fetchrow_hashref()) {
foreach my $q (@q) {
# next if $q eq "servidor" && $ref->{$q} eq 1;#pensar em utilizar isso
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'service'}{lc $q} = $self->date($ref->{$q});
} else {
$self->{'service'}{lc $q} = $ref->{$q};
}
}
}
$self->finish;
return $self->error ? 0 : 1;
}
#sub invoices {
# my ($self) = shift;
# my @q = split(" ","@_");
# return 0 if $self->error;
#
# $self->set_error($self->lang(3,'invoices')) and return unless $self->num($self->{'invoice'}{'id'});
#
# my $sth = $self->select_sql(qq|SELECT `invoices`.*, `users`.`vencimento` FROM `invoices` INNER JOIN `users` ON `invoices`.`username`=`users`.`username` WHERE `id` = ?|,$self->num($self->{'invoice'}{'id'}));
# while(my $ref = $sth->fetchrow_hashref()) {
# foreach my $q (@q) {
# if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
# $self->{'invoice'}{lc $q} = $self->date($ref->{$q});
# } else {
# $self->{'invoice'}{lc $q} = $ref->{$q};
# }
# }
# }
# $self->finish;
#
# return $self->error ? 0 : 1;
#}
sub users {
my ($self) = shift;
my @q = split(" ","@_");
return 0 if $self->error;
$self->set_error($self->lang(3,'users')) and return unless $self->num($self->{'user'}{'id'});
my $sth = $self->select_sql(qq|SELECT * FROM `users` WHERE `username` = ?|,$self->num($self->{'user'}{'id'}));
while(my $ref = $sth->fetchrow_hashref()) {
foreach my $q (@q) {
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'user'}{lc $q} = $self->date($ref->{$q});
} else {
$self->{'user'}{lc $q} = $ref->{$q};
}
}
}
$self->finish;
return $self->error ? 0 : 1;
}
sub pagamentos {
my ($self) = shift;
my @q = split(" ","@_");
return 0 if $self->error;
$self->set_error($self->lang(3,'pagamentos')) and return unless $self->num($self->{'pagamento'}{'id'});
my $sth = $self->select_sql(qq|SELECT * FROM `pagamento` WHERE `id` = ?|,$self->num($self->{'pagamento'}{'id'}));
while(my $ref = $sth->fetchrow_hashref()) {
foreach my $q (@q) {
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'pagamento'}{lc $q} = $self->date($ref->{$q});
} else {
$self->{'pagamento'}{lc $q} = $ref->{$q};
}
}
}
$self->finish;
return $self->error ? 0 : 1;
}
sub planos {
my ($self) = shift;
my @q = split(" ","@_");
return 0 if $self->error;
$self->set_error($self->lang(3,'planos')) && return unless $self->num($self->{'plano'}{'id'});
my $sth = $self->select_sql(qq|SELECT * FROM `planos` LEFT JOIN `planos_modules` ON `planos`.`servicos`=`planos_modules`.`plano` WHERE `servicos` = ?|,$self->num($self->{'plano'}{'id'}));
while(my $ref = $sth->fetchrow_hashref()) {
foreach my $q (@q) {
if ($sth->{TYPE}->[$sth->{NAME_hash}{$q}] == 9) {
$self->{'plano'}{lc $q} = $self->date($ref->{$q});
} else {
$self->{'plano'}{lc $q} = $ref->{$q};
}
}
}
$self->finish;
return $self->error ? 0 : 1;
}
sub promo {
my ($self,$type) = @_;
return 0 if $self->error;
#types 1 - dias gratis 2 - Sem taxa de setup 3 - Descontos em meses 4 - Nao se orientar pelo vc do usuario 5 - dias para finalizar 6 - fatura exclusiva
$self->set_error($self->lang(3,'promocao')) and return unless $self->num($self->sid);
$self->set_error($self->lang(3,'promocao')) and return unless $self->num($type);
unless (defined $self->service('_promo'.$type)) {
my $sth = $self->select_sql(qq|SELECT * FROM `promocao` WHERE `servico` = ?|,$self->sid);
while (my $ref = $sth->fetchrow_hashref()) {
my $r = $ref->{'value'};
$r = 0 if $r < 0 && $ref->{'type'} != 3;
$self->service('_promo'.$ref->{'type'}, $r);
}
}
if ($type == 1 || $type == 2 || $type == 4 || $type == 5 || $type == 6) {
my $r = $self->num($self->service('_promo'.$type));
$r = 0 if $r < 0;
return $r
}
return split("::",$self->service('_promo'.$type),3) if $type == 3;
return undef;
}
sub _feriados { #put in memory for fast access
my ($self) = @_;
my $sth = $self->select_sql(qq|SELECT * FROM `feriados`|);
while(my $ref = $sth->fetchrow_hashref()) {
$self->{'feriados'}{$ref->{'mes'}}{$ref->{'dia'}} = $ref->{'desc'};
}
$self->finish;
return $self->error ? 0 : 1;
}
sub _settings { #put in memory for fast access
my ($self) = @_;
my $sth = $self->select_sql(qq|SELECT * FROM `settings`|);
while(my $ref = $sth->fetchrow_hashref()) {
my $setting = $ref->{'setting'};
$self->{settings}{$setting} = $ref->{'value'};
}
$self->finish;
return $self->error ? 0 : 1;
}
sub _setskin {
my ($self,$skin) = @_;
return 0 if !$skin;
my $sth = $self->select_sql(qq|SELECT * FROM `skins` WHERE `name` = ?|,$skin);
while(my $ref = $sth->fetchrow_hashref()) {
my $setting = $ref->{'setting'};
$self->{skin}{$setting} = $ref->{'value'};
}
$self->finish;
#set name
$self->{skin}{name} = $skin;
return $self->error ? 0 : 1;
}
sub _templates {
my ($self) = shift;
$self->template('lang',$self->{_setlang});
$self->template('data',$self->setting('data'));
$self->template('title',$self->setting('title'));
$self->template('baseurl',$self->setting('baseurl'));
$self->template('timen',$self->calendar('timenow'));
$self->template('data_tpl',$self->skin('data_tpl'));
$self->template('url_tpl',$self->skin('url_tpl'));
$self->template('imgbase',$self->skin('imgbase'));
$self->template('logo',$self->skin('logo_url'));
return 1;
}
sub _country_codes { #put in memory for fast access
my ($self) = @_;
my $sth = $self->select_sql(qq|SELECT * FROM `countrycode`|);
while(my $ref = $sth->fetchrow_hashref()) {
my $country = $ref->{'id'};
$self->{country_codes}{uc $country} = { code => $ref->{'call'},
name => $ref->{'nome'} };
}
$self->finish;
return $self->error ? 0 : 1;
}
sub _setswitchs {
our %SWITCH;
#Defaults switchs
$SWITCH{skip_sql} = 0;
$SWITCH{skip_log} = 0;
$SWITCH{skip_mail} = 0;
$SWITCH{skip_logmail} = 0;
$SWITCH{skip_error} = 0;
return 1;
}
sub _setCGI {
my ($self) = shift;
require CGI;
my $q = CGI->new();
my @pairs = split(/;/, $q->query_string());
foreach my $pair (@pairs) {
my ($name, $value) = split(/=/, $pair);
#Problema de charset era o binmode utf8 que escrevia no arquivo errado e a tela do terminal tbm, mudei pra UTF8
$self->param($name,Controller::URLDecode($value));
}
foreach my $name ($q->cookie()) {
$self->cookie($name,$q->cookie($name));
}
return 1;
}
sub variable {
@_=@_;
my ($self) = shift;
$self->{_variables}{$_[0]} = $_[1] if exists $_[1];
return $self->{_variables}{$_[0]};
}
sub variables {
my ($self) = shift;
return keys %{$self->{_variables}};
}
sub param {
@_=@_;
my ($self) = shift;
$self->{_params}{$_[0]} = trim($_[1]) if exists $_[1];
return $self->{_params}{$_[0]};
}
sub params {
my ($self) = shift;
return keys %{$self->{_params}};
}
sub cookie {
@_=@_;
my ($self) = shift;
$self->{_cookies}{$_[0]} = $_[1] if exists $_[1];
return $self->{_cookies}{$_[0]};
}
sub cookies {
my ($self) = shift;
return keys %{$self->{_cookies}};
}
sub country_code {
my ($self, $key, $value) = @_;
$self->{country_codes}{$key} = $value if $value;
if (exists $self->{country_codes}{$key}) {
return $self->{country_codes}{$key};
}
$self->set_error($self->lang(14, $key));
die; #break, uma configuracao é essencial para o sistema
}
sub country_codes {
my ($self) = shift;
return sort keys %{$self->{country_codes}};
}
sub setting {
my ($self, $key, $value) = @_;
$self->{settings}{$key} = $value if defined $value;
if (exists $self->{settings}{$key}) {
return $self->{settings}{$key};
}
$self->set_error($self->lang(2, $key));
die $key if $self->connected; #break, uma configuracao é essencial para o sistema
}
sub settings {
my ($self) = @_;
return keys %{$self->{settings}};
}
sub skin {
my ($self, $key) = @_;
if (exists $self->{'skin'}{$key}) {
return $self->{'skin'}{$key};
}
$self->set_error($self->lang(4, $key, $self->{'skin'}{'name'}));
die; #break, uma configuracao é essencial para o sistema
}
sub skins {
my $self = shift;
my $sth = $self->select_sql(qq|SELECT DISTINCT `name` FROM `skins`|);
my @skins = map {@{$_}} @{ $sth->fetchall_arrayref() };
$self->finish;
return @skins;
}
sub gonext {
my $self = @_;
$self->{'_next'} = 1;
return 1;
}
sub golast {
my $self = @_;
$self->{'_last'} = 1;
return 1;
}
sub next {
my $self = @_;
if ($self->{'_next'} == 1) {
$self->{'_next'} = undef;
next;
}
if ($self->{'_last'} == 1) {
$self->{'_last'} = undef;
last;
}
}
sub list_langs {
my $self = shift;
my @mods;
my $base = $self->setting('app') .'/lang/';
opendir(F, $base ) || return undef;
my @list = readdir(F);
closedir F;
foreach my $item (@list) {
if (-d $base.$item) {
push (@dirs, $item) if (-e $base.$item.'/lang.inc');
}
}
@{ $self->{list_langs} } = sort {lc($a) cmp lc($b)} @dirs;
iUnique( $self->{list_langs} );
return @{ $self->{list_langs} };
}
sub list_modules {
my $self = shift;
my @mods;
my $match = sub {
if ($File::Find::name =~ /\.pm$/) {
open(F, $File::Find::name) || return undef;
my $is_module;
while(<F>) {
$is_module = 1 if /^# Use: Module/;
if ($is_module == 1 && /^ *package +(([^\s:]+(::)?){4}([^\s:]+){0,1});/) {
push (@mods, $1);
last;
}
}
close(F);
}
};
find( $match, $self->setting('data').'/sistema/'.$self->setting('modules'), $self->setting('app').'/modules');
@{ $self->{list_modules} } = sort {lc($a) cmp lc($b)} @mods;
iUnique( $self->{list_modules} );
return @{ $self->{list_modules} };
}
sub DESTROY {
my $self = @_;
#warn 'Controller was closed';
}
sub traceback { #TODO enviar trace pra admin e die_nice pro usuário
my $self = shift;
my $err = shift;
my @trace; #FIXME: empty list?
# Skip the first frame [0], because it's the call to dotb.
# Skip the second frame [1], because it's the call to die, with redirection
my $frame = 2;
my $tab = 1;
while (my ($package, $filename, $line, $sub) = caller($frame++)) {
if ($package eq 'main') {
$sub =~ s/main:://;
push(@trace, trim("$sub() called from $filename on line $line"));
} else {
return undef if $sub eq '(eval)'; #O Pacote tem direito de chamar um eval para fazer seu próprio handle de erro #CASO: cPanel::PublicAPI.pm eval { require $module; } if ( !$@ ) { };
push(@trace, trim("$package::$sub() called from $filename on line $line\n"));
}
}
#print STDERR "Content-type: text/plain\n\n" unless $mod_perl;
my $mess .= "Traceback (most recent call last):\n";
$mess .= join("\n", map { " "x$tab++ . $_ } reverse(@trace) )."\n";
$mess .= "Package error: ".$self->error()."\n";
$mess .= "Error: $err"; #already has \n at end
my $mod_perl = exists $ENV{MOD_PERL};
if ($mod_perl) {
my $r;
if ($ENV{MOD_PERL_API_VERSION} && $ENV{MOD_PERL_API_VERSION} == 2) {
$mod_perl = 2;
require Apache2::RequestRec;
require Apache2::RequestIO;
require Apache2::RequestUtil;
require APR::Pool;
require ModPerl::Util;
require Apache2::Response;
$r = Apache2::RequestUtil->request;
} else {
$r = Apache->request;
}
# If bytes have already been sent, then
# we print the message out directly.
# Otherwise we make a custom error
# handler to produce the doc for us.
if ($r->bytes_sent) {
$r->print($mess);
$mod_perl == 2 ? ModPerl::Util::exit(0) : $r->exit;
} else {
# MSIE won't display a custom 500 response unless it is >512 bytes!
if ($ENV{HTTP_USER_AGENT} =~ /MSIE/) {
$mess = "<!-- " . (' ' x 513) . " -->\n$mess";
}
$r->custom_response(500,$mess);
}
} else {
# my $bytes_written = eval{tell STDERR};
# if (defined $bytes_written && $bytes_written > 0) {
# print STDERR $mess;
# }
# else {
# print STDERR "Status: 500\n";
# print STDERR "Content-type: text/plain\n\n";
# print STDERR $mess;
# }
}
$self->logevent($mess);
#send message to cron lock
$self->logcron($err) if $self->connected;
#send a nice message to user
$self->script_error($err);
}
sub script_error {
my ($self) = shift;
my $error = "@_";
$error ||= $self->error;
#TODO estudar se o script_error pode ficar em um arquivo html
print "Content-type: text/html\n\n";
print qq~<html><head><title>Erro</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head><body bgcolor="#FFFFFF"><p> </p><table width="600" border="0" cellspacing="0" cellpadding="0" align="center"><tr><td colspan="3"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b>Controller:
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><font color="#990000">Erro de </font></b></font><font color="#990000">Script </font></b></font></td></tr><tr> <td> </td><td> </td><td> </td></tr><tr>
<td colspan="3"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Controller não pode ser rodado pelos seguintes erros:</font></td>
</tr><tr><td colspan="3" height="40"><font face="Courier New, Courier, mono" size="2"><br>$error<br></td></tr></table><p align="center"> </p></body></html>
~;
exit(1);
}
__END__;
Diagnostics
Find @ISA:
use Class::ISA;
print "Food::Fishstick path is:\n ",
join(", ", Class::ISA::super_path($class)),
"\n";
1; | milhomem/controller | backend/src/sistema/include/mods/Controller.pm | Perl | gpl-2.0 | 73,414 |
core:import( "CoreMissionScriptElement" )
ElementPlayerSpawner = ElementPlayerSpawner or class( CoreMissionScriptElement.MissionScriptElement )
function ElementPlayerSpawner:init( ... )
ElementPlayerSpawner.super.init( self, ... )
managers.player:preload()
end
-- Returns a value
function ElementPlayerSpawner:value( name )
return self._values[ name ]
end
function ElementPlayerSpawner:client_on_executed( ... )
if not self._values.enabled then
return
end
managers.player:set_player_state( self._values.state or managers.player:default_player_state() )
end
function ElementPlayerSpawner:on_executed( instigator )
if not self._values.enabled then
return
end
managers.player:set_player_state( self._values.state or managers.player:default_player_state() )
managers.groupai:state():on_player_spawn_state_set( self._values.state or managers.player:default_player_state() )
managers.network:register_spawn_point( self._id, { position = self._values.position, rotation = self._values.rotation } )
ElementPlayerSpawner.super.on_executed( self, self._unit or instigator )
end
| zjohn4/PD2-lua-src | lib/managers/mission/elementplayerspawner.lua | Lua | gpl-2.0 | 1,095 |
#ifndef __CODEC_COM_ETSI_OP_H__
#define __CODEC_COM_ETSI_OP_H__
/*****************************************************************************
1 ÆäËûÍ·Îļþ°üº¬
*****************************************************************************/
#ifndef _MED_C89_
#include "codec_op_etsi_hifi.h"
#endif
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
/*****************************************************************************
2 Êý¾ÝÀàÐͶ¨Òå
*****************************************************************************/
/* ±ê×¼Cƽ̨¶¨Òå */
#ifdef _MED_C89_
/* »ù±¾Êý¾ÝÀàÐͶ¨Òå */
typedef char Char;
typedef signed char Word8;
typedef unsigned char UWord8;
typedef short Word16;
typedef unsigned short UWord16;
typedef long Word32;
typedef unsigned long UWord32;
typedef int Flag;
#endif
/*****************************************************************************
3 ºê¶¨Òå
*****************************************************************************/
#define MAX_32 ((Word32)0x7fffffffL) /*×î´óµÄ32λÊý*/
#define MIN_32 ((Word32)0x80000000L) /*×îСµÄ32λÊý*/
#define MAX_16 ((Word16)0x7fff) /*×î´óµÄ16λÊý*/
#define MIN_16 ((Word16)0x8000) /*×îСµÄ16λÊý*/
/* ±ê×¼Cƽ̨¶¨Òå */
#ifdef _MED_C89_
#define CODEC_OpSetOverflow(swFlag) (Overflow = swFlag)
#define CODEC_OpGetOverflow() (Overflow)
#define CODEC_OpSetCarry(swFlag) (Carry = swFlag)
#define CODEC_OpGetCarry() (Carry)
#define XT_INLINE static
#endif
/*****************************************************************************
4 ö¾Ù¶¨Òå
*****************************************************************************/
/*****************************************************************************
5 ÏûϢͷ¶¨Òå
*****************************************************************************/
/*****************************************************************************
6 ÏûÏ¢¶¨Òå
*****************************************************************************/
/*****************************************************************************
7 STRUCT¶¨Òå
*****************************************************************************/
/*****************************************************************************
8 UNION¶¨Òå
*****************************************************************************/
/*****************************************************************************
9 OTHERS¶¨Òå
*****************************************************************************/
#define round(L_var1) round_etsi(L_var1)
/*****************************************************************************
10 È«¾Ö±äÁ¿ÉùÃ÷
*****************************************************************************/
/* ±ê×¼Cƽ̨¶¨Òå */
#ifdef _MED_C89_
extern Flag Overflow;
extern Flag Carry;
#endif
/*****************************************************************************
11 º¯ÊýÉùÃ÷
*****************************************************************************/
#ifdef _MED_C89_
/* ETSI : basic_op.h */
extern Word16 saturate (Word32 swVar); /* 32bit->16bit */
extern Word16 add(Word16 shwVar1, Word16 shwVar2); /* Short add */
extern Word16 sub(Word16 shwVar1, Word16 shwVar2); /* Short sub */
extern Word16 abs_s(Word16 shwVar1); /* Short abs */
extern Word16 shl(Word16 shwVar1, Word16 shwVar2); /* Short shift left */
extern Word16 shr(Word16 shwVar1, Word16 shwVar2); /* Short shift right*/
extern Word16 mult(Word16 shwVar1, Word16 shwVar2); /* Short mult */
extern Word32 L_mult(Word16 shwVar1, Word16 shwVar2); /* Long mult */
extern Word16 negate(Word16 shwVar1); /* Short negate */
extern Word16 extract_h(Word32 swVar1); /* Extract high */
extern Word16 extract_l(Word32 swVar1); /* Extract low */
extern Word16 round_etsi(Word32 swVar1); /* Round */
extern Word32 L_mac(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac */
extern Word32 L_msu(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu */
extern Word32 L_macNs(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac without sat */
extern Word32 L_msuNs(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu without sat */
extern Word32 L_add(Word32 swVar1, Word32 swVar2); /* Long add */
extern Word32 L_sub(Word32 swVar1, Word32 swVar2); /* Long sub */
extern Word32 L_add_c(Word32 swVar1, Word32 swVar2); /* Long add with c */
extern Word32 L_sub_c(Word32 swVar1, Word32 swVar2); /* Long sub with c */
extern Word32 L_negate(Word32 swVar1); /* Long negate */
extern Word16 mult_r(Word16 shwVar1, Word16 shwVar2); /* Mult with round */
extern Word32 L_shl(Word32 swVar1, Word16 shwVar2); /* Long shift left */
extern Word32 L_shr(Word32 swVar1, Word16 shwVar2); /* Long shift right */
extern Word16 shr_r(Word16 shwVar1, Word16 shwVar2); /* Shift right with round */
extern Word16 mac_r(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Mac with rounding */
extern Word16 msu_r(Word32 swVar3, Word16 shwVar1, Word16 shwVar2); /* Msu with rounding */
extern Word32 L_deposit_h(Word16 shwVar1); /* 16 bit shwVar1 -> MSB */
extern Word32 L_deposit_l(Word16 shwVar1); /* 16 bit shwVar1 -> LSB */
extern Word32 L_shr_r(Word32 swVar1, Word16 shwVar2); /* Long shift right with round */
extern Word32 L_abs(Word32 swVar1); /* Long abs */
extern Word32 L_sat(Word32 swVar1); /* Long saturation */
extern Word16 norm_s(Word16 shwVar1); /* Short norm */
extern Word16 div_s(Word16 shwVar1, Word16 shwVar2); /* Short division */
extern Word16 norm_l(Word32 swVar1); /* Long norm */
/* ETSI : oper_32b.h */
/* Extract from a 32 bit integer two 16 bit DPF */
extern void L_Extract(Word32 swVar32, Word16 *pshwHi, Word16 *pshwLo);
/* Compose from two 16 bit DPF a 32 bit integer */
extern Word32 L_Comp(Word16 shwHi, Word16 shwLo);
/* Multiply two 32 bit integers (DPF). The result is divided by 2**31 */
extern Word32 Mpy_32(Word16 shwHi1, Word16 shwLo1, Word16 shwHi2, Word16 shwLo2);
/* Multiply a 16 bit integer by a 32 bit (DPF). The result is divided by 2**15 */
extern Word32 Mpy_32_16(Word16 shwHi, Word16 shwLo, Word16 shwN);
/* Fractional integer division of two 32 bit numbers */
extern Word32 Div_32(Word32 swNum, Word16 denom_hi, Word16 denom_lo);
/* ETSI : mac_32.h */
/* Multiply two 32 bit integers (DPF) and accumulate with (normal) 32 bit integer.
The multiplication result is divided by 2**31 */
extern Word32 Mac_32(Word32 swVar32, Word16 shwHi1, Word16 shwLo1, Word16 shwHi2, Word16 shwLo2);
/* Multiply a 16 bit integer by a 32 bit (DPF) and accumulate with (normal)32 bit integer.
The multiplication result is divided by 2**15 */
extern Word32 Mac_32_16(Word32 swVar32, Word16 shwHi, Word16 shwLo, Word16 shwN);
#endif /* ifdef _MED_C89_ */
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif /* end of med_com_etsi_op.h */
| gabry3795/android_kernel_huawei_mt7_l09 | drivers/vendor/hisi/modem/med/common/inc/codec/codec_op_etsi.h | C | gpl-2.0 | 8,235 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ext.flac;
import android.os.Handler;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.audio.AudioProcessor;
import com.google.android.exoplayer2.audio.AudioRendererEventListener;
import com.google.android.exoplayer2.audio.SimpleDecoderAudioRenderer;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.ExoMediaCrypto;
import com.google.android.exoplayer2.util.MimeTypes;
/**
* Decodes and renders audio using the native Flac decoder.
*/
public class LibflacAudioRenderer extends SimpleDecoderAudioRenderer {
private static final int NUM_BUFFERS = 16;
public LibflacAudioRenderer() {
this(null, null);
}
/**
* @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
* null if delivery of events is not required.
* @param eventListener A listener of events. May be null if delivery of events is not required.
* @param audioProcessors Optional {@link AudioProcessor}s that will process audio before output.
*/
public LibflacAudioRenderer(
Handler eventHandler,
AudioRendererEventListener eventListener,
AudioProcessor... audioProcessors) {
super(eventHandler, eventListener, audioProcessors);
}
@Override
protected int supportsFormatInternal(DrmSessionManager<ExoMediaCrypto> drmSessionManager,
Format format) {
if (!MimeTypes.AUDIO_FLAC.equalsIgnoreCase(format.sampleMimeType)) {
return FORMAT_UNSUPPORTED_TYPE;
} else if (!supportsOutput(format.channelCount, C.ENCODING_PCM_16BIT)) {
return FORMAT_UNSUPPORTED_SUBTYPE;
} else if (!supportsFormatDrm(drmSessionManager, format.drmInitData)) {
return FORMAT_UNSUPPORTED_DRM;
} else {
return FORMAT_HANDLED;
}
}
@Override
protected FlacDecoder createDecoder(Format format, ExoMediaCrypto mediaCrypto)
throws FlacDecoderException {
return new FlacDecoder(
NUM_BUFFERS, NUM_BUFFERS, format.maxInputSize, format.initializationData);
}
}
| CzBiX/Telegram | TMessagesProj/src/main/java/com/google/android/exoplayer2/ext/flac/LibflacAudioRenderer.java | Java | gpl-2.0 | 2,743 |
/*
* Compiler error handler
* Copyright
* (C) 1992 Joseph H. Allen
*
* This file is part of JOE (Joe's Own Editor)
*/
#include "types.h"
/* Error database */
typedef struct error ERROR;
struct error {
LINK(ERROR) link; /* Linked list of errors */
long line; /* Target line number */
long org; /* Original target line number */
unsigned char *file; /* Target file name */
long src; /* Error-file line number */
unsigned char *msg; /* The message */
} errors = { { &errors, &errors} };
ERROR *errptr = &errors; /* Current error row */
B *errbuf = NULL; /* Buffer with error messages */
/* Function which allows stepping through all error buffers,
for multi-file search and replace. Give it a buffer. It finds next
buffer in error list. Look at 'berror' for error information. */
/* This is made to work like bafter: it does not increment refcount of buffer */
B *beafter(B *b)
{
struct error *e;
unsigned char *name = b->name;
if (!name) name = USTR "";
for (e = errors.link.next; e != &errors; e = e->link.next)
if (!zcmp(name, e->file))
break;
if (e == &errors) {
/* Given buffer is not in list? Return first buffer in list. */
e = errors.link.next;
}
while (e != &errors && !zcmp(name, e->file))
e = e->link.next;
berror = 0;
if (e != &errors) {
B *b = bfind(e->file);
/* bfind bumps refcount, so we have to unbump it */
if (b->count == 1)
b->orphan = 1; /* Oops */
else
--b->count;
return b;
}
return 0;
}
/* Insert and delete notices */
void inserr(unsigned char *name, long int where, long int n, int bol)
{
ERROR *e;
if (!n)
return;
if (name) {
for (e = errors.link.next; e != &errors; e = e->link.next) {
if (!zcmp(e->file, name)) {
if (e->line > where)
e->line += n;
else if (e->line == where && bol)
e->line += n;
}
}
}
}
void delerr(unsigned char *name, long int where, long int n)
{
ERROR *e;
if (!n)
return;
if (name) {
for (e = errors.link.next; e != &errors; e = e->link.next) {
if (!zcmp(e->file, name)) {
if (e->line > where + n)
e->line -= n;
else if (e->line > where)
e->line = where;
}
}
}
}
/* Abort notice */
void abrerr(unsigned char *name)
{
ERROR *e;
if (name)
for (e = errors.link.next; e != &errors; e = e->link.next)
if (!zcmp(e->file, name))
e->line = e->org;
}
/* Save notice */
void saverr(unsigned char *name)
{
ERROR *e;
if (name)
for (e = errors.link.next; e != &errors; e = e->link.next)
if (!zcmp(e->file, name))
e->org = e->line;
}
/* Pool of free error nodes */
ERROR errnodes = { {&errnodes, &errnodes} };
/* Free an error node */
static void freeerr(ERROR *n)
{
vsrm(n->file);
vsrm(n->msg);
enquef(ERROR, link, &errnodes, n);
}
/* Free all errors */
static int freeall(void)
{
int count = 0;
while (!qempty(ERROR, link, &errors)) {
freeerr(deque_f(ERROR, link, errors.link.next));
++count;
}
errptr = &errors;
return count;
}
/* Parse error messages into database */
/* From joe's joe 2.9 */
/* First word (allowing ., /, _ and -) with a . is the file name. Next number
is line number. Then there should be a ':' */
static void parseone(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line)
{
int x, y, flg;
unsigned char *name = NULL;
long line = -1;
y=0;
flg=0;
if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':')
goto bye;
do {
/* Skip to first word */
for (x = y; s[x] && !(joe_isalnum_(map,s[x]) || s[x] == '.' || s[x] == '/'); ++x) ;
/* Skip to end of first word */
for (y = x; joe_isalnum_(map,s[y]) || s[y] == '.' || s[y] == '/' || s[y]=='-'; ++y)
if (s[y] == '.')
flg = 1;
} while (!flg && x!=y);
/* Save file name */
if (x != y)
name = vsncpy(NULL, 0, s + x, y - x);
/* Skip to first number */
for (x = y; s[x] && (s[x] < '0' || s[x] > '9'); ++x) ;
/* Skip to end of first number */
for (y = x; s[y] >= '0' && s[y] <= '9'; ++y) ;
/* Save line number */
if (x != y)
sscanf((char *)(s + x), "%ld", &line);
if (line != -1)
--line;
/* Look for ':' */
flg = 0;
while (s[y]) {
/* Allow : anywhere on line: works for MIPS C compiler */
/*
for (y = 0; s[y];)
*/
if (s[y]==':') {
flg = 1;
break;
}
++y;
}
bye:
if (!flg)
line = -1;
*rtn_name = name;
*rtn_line = line;
}
/* Parser for file name lists from grep, find and ls.
*
* filename
* filename:*
* filename:line-number:*
*/
void parseone_grep(struct charmap *map,unsigned char *s,unsigned char **rtn_name,long *rtn_line)
{
int y;
unsigned char *name = NULL;
long line = -1;
if (s[0] == 'J' && s[1] == 'O' && s[2] == 'E' && s[3] == ':')
goto bye;
/* Skip to first : or end of line */
for (y = 0;s[y] && s[y] != ':';++y);
if (y) {
/* This should be the file name */
name = vsncpy(NULL,0,s,y);
line = 0;
if (s[y] == ':') {
/* Maybe there's a line number */
++y;
while (s[y] >= '0' && s[y] <= '9')
line = line * 10 + (s[y++] - '0');
--line;
if (line < 0 || s[y] != ':') {
/* Line number is only valid if there's a second : */
line = 0;
}
}
}
bye:
*rtn_name = name;
*rtn_line = line;
}
static int parseit(struct charmap *map,unsigned char *s, long int row,
void (*parseone)(struct charmap *map, unsigned char *s, unsigned char **rtn_name, long *rtn_line), unsigned char *current_dir)
{
unsigned char *name = NULL;
long line = -1;
ERROR *err;
parseone(map,s,&name,&line);
if (name) {
if (line != -1) {
/* We have an error */
err = (ERROR *) alitem(&errnodes, sizeof(ERROR));
err->file = name;
if (current_dir) {
err->file = vsncpy(NULL, 0, sv(current_dir));
err->file = vsncpy(sv(err->file), sv(name));
err->file = canonical(err->file);
vsrm(name);
} else {
err->file = name;
}
err->org = err->line = line;
err->src = row;
err->msg = vsncpy(NULL, 0, sc("\\i"));
err->msg = vsncpy(sv(err->msg), sv(s));
enqueb(ERROR, link, &errors, err);
return 1;
} else
vsrm(name);
}
return 0;
}
/* Parse the error output contained in a buffer */
void kill_ansi(unsigned char *s);
static long parserr(B *b)
{
if (markv(1)) {
P *p = pdup(markb, USTR "parserr1");
P *q = pdup(markb, USTR "parserr2");
long nerrs = 0;
errbuf = markb->b;
freeall();
p_goto_bol(p);
do {
unsigned char *s;
pset(q, p);
p_goto_eol(p);
s = brvs(q, (int) (p->byte - q->byte));
if (s) {
kill_ansi(s);
nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone),q->b->current_dir);
vsrm(s);
}
pgetc(p);
} while (p->byte < markk->byte);
prm(p);
prm(q);
return nerrs;
} else {
P *p = pdup(b->bof, USTR "parserr3");
P *q = pdup(p, USTR "parserr4");
long nerrs = 0;
errbuf = b;
freeall();
do {
unsigned char *s;
pset(q, p);
p_goto_eol(p);
s = brvs(q, (int) (p->byte - q->byte));
if (s) {
kill_ansi(s);
nerrs += parseit(q->b->o.charmap, s, q->line, (q->b->parseone ? q->b->parseone : parseone), q->b->current_dir);
vsrm(s);
}
} while (pgetc(p) != NO_MORE_DATA);
prm(p);
prm(q);
return nerrs;
}
}
BW *find_a_good_bw(B *b)
{
W *w;
BW *bw = 0;
/* Find lowest window with buffer */
if ((w = maint->topwin) != NULL) {
do {
if ((w->watom->what&TYPETW) && ((BW *)w->object)->b==b && w->y>=0)
bw = (BW *)w->object;
w = w->link.next;
} while (w != maint->topwin);
}
if (bw)
return bw;
/* Otherwise just find lowest window */
if ((w = maint->topwin) != NULL) {
do {
if ((w->watom->what&TYPETW) && w->y>=0)
bw = (BW *)w->object;
w = w->link.next;
} while (w != maint->topwin);
}
return bw;
}
int parserrb(B *b)
{
BW *bw;
int n;
freeall();
bw = find_a_good_bw(b);
unmark(bw);
n = parserr(b);
if (n)
joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n);
else
joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found")));
msgnw(bw->parent, msgbuf);
return 0;
}
int urelease(BW *bw)
{
bw->b->parseone = 0;
if (qempty(ERROR, link, &errors) && !errbuf) {
joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages")));
} else {
int count = freeall();
errbuf = NULL;
joe_snprintf_1(msgbuf, sizeof(msgbuf), joe_gettext(_("%d messages cleared")), count);
}
msgnw(bw->parent, msgbuf);
updall();
return 0;
}
int uparserr(BW *bw)
{
int n;
freeall();
bw->b->parseone = parseone;
n = parserr(bw->b);
if (n)
joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n);
else
joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found")));
msgnw(bw->parent, msgbuf);
return 0;
}
int ugparse(BW *bw)
{
int n;
freeall();
bw->b->parseone = parseone_grep;
n = parserr(bw->b);
if (n)
joe_snprintf_1(msgbuf, JOE_MSGBUFSIZE, joe_gettext(_("%d messages found")), n);
else
joe_snprintf_0(msgbuf, sizeof(msgbuf), joe_gettext(_("No messages found")));
msgnw(bw->parent, msgbuf);
return 0;
}
int jump_to_file_line(BW *bw,unsigned char *file,int line,unsigned char *msg)
{
int omid;
if (!bw->b->name || zcmp(file, bw->b->name)) {
if (doswitch(bw, vsdup(file), NULL, NULL))
return -1;
bw = (BW *) maint->curwin->object;
}
omid = mid;
mid = 1;
pline(bw->cursor, line);
dofollows();
mid = omid;
bw->cursor->xcol = piscol(bw->cursor);
msgnw(bw->parent, msg);
return 0;
}
/* Show current message */
int ucurrent_msg(BW *bw)
{
if (errptr != &errors) {
msgnw(bw->parent, errptr->msg);
return 0;
} else {
msgnw(bw->parent, joe_gettext(_("No messages")));
return -1;
}
}
/* Find line in error database: return pointer to message */
ERROR *srcherr(BW *bw,unsigned char *file,long line)
{
ERROR *p;
for (p = errors.link.next; p != &errors; p=p->link.next)
if (!zcmp(p->file,file) && p->org == line) {
errptr = p;
setline(errbuf, errptr->src);
return errptr;
}
return 0;
}
/* Delete ansi formatting */
void kill_ansi(unsigned char *s)
{
unsigned char *d = s;
while (*s)
if (*s == 27) {
while (*s && (*s == 27 || *s == '[' || (*s >= '0' && *s <= '9') || *s == ';'))
++s;
if (*s)
++s;
} else
*d++ = *s++;
*d = 0;
}
int ujump(BW *bw)
{
int rtn = -1;
P *p = pdup(bw->cursor, USTR "ujump");
P *q = pdup(p, USTR "ujump");
unsigned char *s;
p_goto_bol(p);
p_goto_eol(q);
s = brvs(p, (int) (q->byte - p->byte));
kill_ansi(s);
prm(p);
prm(q);
if (s) {
unsigned char *name = NULL;
unsigned char *fullname = NULL;
unsigned char *curd = get_cd(bw->parent);
long line = -1;
if (bw->b->parseone)
bw->b->parseone(bw->b->o.charmap,s,&name,&line);
else
parseone_grep(bw->b->o.charmap,s,&name,&line);
/* Prepend current directory.. */
fullname = vsncpy(NULL, 0, sv(curd));
fullname = vsncpy(sv(fullname), sv(name));
vsrm(name);
name = canonical(fullname);
if (name && line != -1) {
ERROR *p = srcherr(bw, name, line);
uprevw((BASE *)bw);
/* Check that we made it to a tw */
if (p)
rtn = jump_to_file_line(maint->curwin->object,name,p->line,NULL /* p->msg */);
else
rtn = jump_to_file_line(maint->curwin->object,name,line,NULL);
vsrm(name);
}
vsrm(s);
}
return rtn;
}
int unxterr(BW *bw)
{
if (errptr->link.next == &errors) {
msgnw(bw->parent, joe_gettext(_("No more errors")));
return -1;
}
errptr = errptr->link.next;
setline(errbuf, errptr->src);
return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */);
}
int uprverr(BW *bw)
{
if (errptr->link.prev == &errors) {
msgnw(bw->parent, joe_gettext(_("No more errors")));
return -1;
}
errptr = errptr->link.prev;
setline(errbuf, errptr->src);
return jump_to_file_line(bw,errptr->file,errptr->line,NULL /* errptr->msg */);
}
| jhallen/joe-editor | joe/uerror.c | C | gpl-2.0 | 11,705 |
<HTML>
<HEAD>
<META HTTP-EQUIV="content-type" CONTENT="text/html;charset=iso-8859-1">
<TITLE>Using mission packs by dragging them onto the Quake II application icon</TITLE>
<META NAME="copyright" CONTENT="Copyright 2002 Fruitz Of Dojo. All Rights Reserved.">
<META NAME="description" CONTENT="Learn how to use mission packs with Quake II via drag'n'drop.">
</HEAD>
<BODY BGCOLOR="#ffffff"><A NAME="itns1003"></A><A NAME="xicnitn"></A>
<DIV ALIGN="left">
<TABLE WIDTH="352" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR ALIGN="left" VALIGN="top" HEIGHT="20">
<TD ALIGN="left" VALIGN="top" WIDTH="7" HEIGHT="20">
</TD>
<TD ALIGN="left" VALIGN="top" WIDTH="22" HEIGHT="20">
<IMG SRC="../gfx/quake2.gif" ALT="Quake II" HEIGHT="16" WIDTH="16">
</TD>
<TD ALIGN="left" VALIGN="top" WIDTH="308" HEIGHT="20">
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
<A HREF="../Quake%20II%20Help.html">
Quake II Help
</A>
</FONT>
</TD>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR HEIGHT="40">
<TD VALIGN="middle" WIDTH="7" HEIGHT="40">
</TD>
<TD WIDTH="100%" HEIGHT="40">
<FONT SIZE="4" FACE="Lucida Grande,Helvetica,Arial">
<B>Using mission packs by dragging them onto the Quake II application icon</B>
</FONT>
</TD>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7">
<TR>
<TD>
<P>
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
Please follow this steps to use mission packs or mods via drag'n'drop:
</FONT>
</P>
</TD>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7" BGCOLOR="#ffffcc">
<TR VALIGN="top" BGCOLOR="#ffffcc">
<TD BGCOLOR="#ffffcc" WIDTH="98%">
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3">
<TR VALIGN="top">
<TD WIDTH="16">
<FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial">
<B>1</B>
</FONT>
</TD>
<TD>
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
Quit Quake II.
</FONT>
</TD>
</TR>
</TABLE>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3">
<TR VALIGN="top">
<TD WIDTH="16">
<FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial">
<B>2</B>
</FONT>
</TD>
<TD>
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
Copy the folder of the mission pack to your "Quake II" folder. The "Quake II" folder is the folder that holds the "baseq2" folder.
</FONT>
</TD>
</TR>
</TABLE>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="3">
<TR VALIGN="top">
<TD WIDTH="16">
<FONT SIZE="2" FACE="Lucida Grande,Helvetica,Arial">
<B>3</B>
</FONT>
</TD>
<TD>
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
Drag the folder which contains the mission pack onto the Quake II application icon.
</FONT>
</TD>
</TR>
</TABLE>
</FONT>
</TD>
</TR>
</TABLE>
<FONT SIZE="1"> </FONT>
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="7">
<TR VALIGN="top">
<TD ALIGN="left">
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
</FONT>
</TD>
<TD ALIGN="right">
<FONT SIZE="2" FACE="Lucida Grande,Geneva,Arial">
<A HREF="help:search='using mission packs' bookID=Quake%20II%20Help">
Tell me more
</A>
</FONT>
</TD>
</TR>
</TABLE>
</DIV>
</BODY>
</HTML> | davepkennedy/quake2_py | quake2-3.21/macosx/Help/English/pgs/201.html | HTML | gpl-2.0 | 4,565 |
# PryGitHub
Proyecto para usa desde Github
| guti0630/PryGitHub | README.md | Markdown | gpl-2.0 | 43 |
<?php
/**
* @package Windwalker.Framework
* @subpackage class
*
* @copyright Copyright (C) 2012 Asikart. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Generated by AKHelper - http://asikart.com
*/
// no direct access
defined('_JEXEC') or die;
/**
* AKGrid class to dynamically generate HTML tables
*
* @package Windwalker.Framework
* @subpackage class
* @since 11.3
*/
class AKGrid
{
/**
* Array of columns
* @var array
* @since 11.3
*/
protected $columns = array();
/**
* Current active row
* @var int
* @since 11.3
*/
protected $activeRow = 0;
/**
* Rows of the table (including header and footer rows)
* @var array
* @since 11.3
*/
protected $rows = array();
/**
* Header and Footer row-IDs
* @var array
* @since 11.3
*/
protected $specialRows = array('header' => array(), 'footer' => array());
/**
* Associative array of attributes for the table-tag
* @var array
* @since 11.3
*/
protected $options;
/**
* Constructor for a AKGrid object
*
* @param array $options Associative array of attributes for the table-tag
*
* @since 11.3
*/
public function __construct($options = array())
{
$this->setTableOptions($options, true);
}
/**
* Magic function to render this object as a table.
*
* @return string
*
* @since 11.3
*/
public function __toString()
{
return $this->toString();
}
/**
* Method to set the attributes for a table-tag
*
* @param array $options Associative array of attributes for the table-tag
* @param bool $replace Replace possibly existing attributes
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function setTableOptions($options = array(), $replace = false)
{
if ($replace)
{
$this->options = $options;
}
else
{
$this->options = array_merge($this->options, $options);
}
return $this;
}
/**
* Get the Attributes of the current table
*
* @return array Associative array of attributes
*
* @since 11.3
*/
public function getTableOptions()
{
return $this->options;
}
/**
* Add new column name to process
*
* @param string $name Internal column name
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function addColumn($name)
{
$this->columns[] = $name;
return $this;
}
/**
* Returns the list of internal columns
*
* @return array List of internal columns
*
* @since 11.3
*/
public function getColumns()
{
return $this->columns;
}
/**
* Delete column by name
*
* @param string $name Name of the column to be deleted
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function deleteColumn($name)
{
$index = array_search($name, $this->columns);
if ($index !== false)
{
unset($this->columns[$index]);
$this->columns = array_values($this->columns);
}
return $this;
}
/**
* Method to set a whole range of columns at once
* This can be used to re-order the columns, too
*
* @param array $columns List of internal column names
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function setColumns($columns)
{
$this->columns = array_values($columns);
return $this;
}
/**
* Adds a row to the table and sets the currently
* active row to the new row
*
* @param array $options Associative array of attributes for the row
* @param int $special 1 for a new row in the header, 2 for a new row in the footer
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function addRow($options = array(), $special = false)
{
$this->rows[]['_row'] = $options;
$this->activeRow = count($this->rows) - 1;
if ($special)
{
if ($special === 1)
{
$this->specialRows['header'][] = $this->activeRow;
}
else
{
$this->specialRows['footer'][] = $this->activeRow;
}
}
return $this;
}
/**
* Method to get the attributes of the currently active row
*
* @return array Associative array of attributes
*
* @since 11.3
*/
public function getRowOptions()
{
return $this->rows[$this->activeRow]['_row'];
}
/**
* Method to set the attributes of the currently active row
*
* @param array $options Associative array of attributes
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function setRowOptions($options)
{
$this->rows[$this->activeRow]['_row'] = $options;
return $this;
}
/**
* Get the currently active row ID
*
* @return int ID of the currently active row
*
* @since 11.3
*/
public function getActiveRow()
{
return $this->activeRow;
}
/**
* Set the currently active row
*
* @param int $id ID of the row to be set to current
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function setActiveRow($id)
{
$this->activeRow = (int) $id;
return $this;
}
/**
* Set cell content for a specific column for the
* currently active row
*
* @param string $name Name of the column
* @param string $content Content for the cell
* @param array $option Associative array of attributes for the td-element
* @param bool $replace If false, the content is appended to the current content of the cell
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function setRowCell($name, $content, $option = array(), $replace = true)
{
if ($replace || !isset($this->rows[$this->activeRow][$name]))
{
$cell = new stdClass;
$cell->options = $option;
$cell->content = $content;
$this->rows[$this->activeRow][$name] = $cell;
}
else
{
$this->rows[$this->activeRow][$name]->content .= $content;
$this->rows[$this->activeRow][$name]->options = $option;
}
return $this;
}
/**
* Get all data for a row
*
* @param int $id ID of the row to return
*
* @return array Array of columns of a table row
*
* @since 11.3
*/
public function getRow($id = false)
{
if ($id === false)
{
$id = $this->activeRow;
}
if (isset($this->rows[(int) $id]))
{
return $this->rows[(int) $id];
}
else
{
return false;
}
}
/**
* Get the IDs of all rows in the table
*
* @param int $special false for the standard rows, 1 for the header rows, 2 for the footer rows
*
* @return array Array of IDs
*
* @since 11.3
*/
public function getRows($special = false)
{
if ($special)
{
if ($special === 1)
{
return $this->specialRows['header'];
}
else
{
return $this->specialRows['footer'];
}
}
return array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer']));
}
/**
* Delete a row from the object
*
* @param int $id ID of the row to be deleted
*
* @return AKGrid This object for chaining
*
* @since 11.3
*/
public function deleteRow($id)
{
unset($this->rows[$id]);
if (in_array($id, $this->specialRows['header']))
{
unset($this->specialRows['header'][array_search($id, $this->specialRows['header'])]);
}
if (in_array($id, $this->specialRows['footer']))
{
unset($this->specialRows['footer'][array_search($id, $this->specialRows['footer'])]);
}
if ($this->activeRow == $id)
{
end($this->rows);
$this->activeRow = key($this->rows);
}
return $this;
}
/**
* Render the HTML table
*
* @return string The rendered HTML table
*
* @since 11.3
*/
public function toString()
{
$output = array();
$output[] = '<table' . $this->renderAttributes($this->getTableOptions()) . '>';
if (count($this->specialRows['header']))
{
$output[] = $this->renderArea($this->specialRows['header'], 'thead', 'th');
}
if (count($this->specialRows['footer']))
{
$output[] = $this->renderArea($this->specialRows['footer'], 'tfoot');
}
$ids = array_diff(array_keys($this->rows), array_merge($this->specialRows['header'], $this->specialRows['footer']));
if (count($ids))
{
$output[] = $this->renderArea($ids);
}
$output[] = '</table>';
return implode('', $output);
}
/**
* Render an area of the table
*
* @param array $ids IDs of the rows to render
* @param string $area Name of the area to render. Valid: tbody, tfoot, thead
* @param string $cell Name of the cell to render. Valid: td, th
*
* @return string The rendered table area
*
* @since 11.3
*/
protected function renderArea($ids, $area = 'tbody', $cell = 'td')
{
$output = array();
$output[] = '<' . $area . ">\n";
foreach ($ids as $id)
{
$output[] = "\t<tr" . $this->renderAttributes($this->rows[$id]['_row']) . ">\n";
foreach ($this->getColumns() as $name)
{
if (isset($this->rows[$id][$name]))
{
$column = $this->rows[$id][$name];
$output[] = "\t\t<" . $cell . $this->renderAttributes($column->options) . '>' . $column->content . '</' . $cell . ">\n";
}
}
$output[] = "\t</tr>\n";
}
$output[] = '</' . $area . '>';
return implode('', $output);
}
/**
* Renders an HTML attribute from an associative array
*
* @param array $attributes Associative array of attributes
*
* @return string The HTML attribute string
*
* @since 11.3
*/
protected function renderAttributes($attributes)
{
if (count((array) $attributes) == 0)
{
return '';
}
$return = array();
foreach ($attributes as $key => $option)
{
$return[] = $key . '="' . $option . '"';
}
return ' ' . implode(' ', $return);
}
}
| ForAEdesWeb/AEW32 | administrator/components/com_quickcontent/windwalker/html/grid.php | PHP | gpl-2.0 | 9,645 |
<?php
class Metabox
{
public static $boxes = array();
/**
* @static
* @param $type
* @param $options
* @return Metabox
*/
public static function factory($type, $options = null) {
$parts = explode('_', $type);
array_walk(
$parts,
function(&$item){
$item = ucfirst($item);
}
);
$class = 'Metabox_'.implode('_', $parts);
if(class_exists($class)) {
if( ! isset($options['type']) ) {
$options['type'] = $type;
}
return new $class($options);
}
return false;
}
/**
* @static
* @param $key
* @return Metabox
*/
public static function get($key) {
return (isset(self::$boxes[$key]) ? self::$boxes[$key] : null);
}
public static function attr($box, $attr) {
return (isset(self::$boxes[$box]->$attr) ? self::$boxes[$box]->$attr : null);
}
} | vladcazacu/Wordpress-HMVC | wp-content/themes/hmvc/core/classes/metabox.php | PHP | gpl-2.0 | 805 |
/*
* tseries.h
*
* specific parts for B&R T-Series Motherboard
*
* Copyright (C) 2013 Hannes Schmelzer <[email protected]> -
* Bernecker & Rainer Industrieelektronik GmbH - http://www.br-automation.com
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __CONFIG_TSERIES_H__
#define __CONFIG_TSERIES_H__
#include <configs/bur_cfg_common.h>
#include <configs/bur_am335x_common.h>
/* ------------------------------------------------------------------------- */
#define CONFIG_AM335X_LCD
#define CONFIG_LCD
#define CONFIG_LCD_ROTATION
#define CONFIG_LCD_DT_SIMPLEFB
#define CONFIG_SYS_WHITE_ON_BLACK
#define LCD_BPP LCD_COLOR32
#define CONFIG_HW_WATCHDOG
#define CONFIG_OMAP_WATCHDOG
#define CONFIG_SPL_WATCHDOG_SUPPORT
#define CONFIG_SPL_GPIO_SUPPORT
/* Bootcount using the RTC block */
#define CONFIG_SYS_BOOTCOUNT_ADDR 0x44E3E000
#define CONFIG_BOOTCOUNT_LIMIT
#define CONFIG_BOOTCOUNT_AM33XX
/* memory */
#define CONFIG_SYS_MALLOC_LEN (5 * 1024 * 1024)
/* Clock Defines */
#define V_OSCK 26000000 /* Clock output from T2 */
#define V_SCLK (V_OSCK)
#define CONFIG_POWER_TPS65217
/* Support both device trees and ATAGs. */
#define CONFIG_OF_LIBFDT
#define CONFIG_USE_FDT /* use fdt within board code */
#define CONFIG_OF_BOARD_SETUP
#define CONFIG_CMDLINE_TAG
#define CONFIG_SETUP_MEMORY_TAGS
#define CONFIG_INITRD_TAG
#define CONFIG_CMD_BOOTZ
/*#define CONFIG_MACH_TYPE 3589*/
#define CONFIG_MACH_TYPE 0xFFFFFFFF /* TODO: check with kernel*/
/* MMC/SD IP block */
#if defined(CONFIG_EMMC_BOOT)
#define CONFIG_MMC
#define CONFIG_GENERIC_MMC
#define CONFIG_OMAP_HSMMC
#define CONFIG_CMD_MMC
#define CONFIG_SUPPORT_EMMC_BOOT
/* RAW SD card / eMMC locations. */
#define CONFIG_SYS_MMCSD_RAW_MODE_U_BOOT_SECTOR 0x300 /*addr. 0x60000 */
#define CONFIG_SYS_U_BOOT_MAX_SIZE_SECTORS 0x200 /* 256 KB */
#define CONFIG_SPL_MMC_SUPPORT
#endif /* CONFIG_EMMC_BOOT */
/*
* When we have SPI or NAND flash we expect to be making use of mtdparts,
* both for ease of use in U-Boot and for passing information on to
* the Linux kernel.
*/
#if defined(CONFIG_SPI_BOOT) || defined(CONFIG_NAND)
#define CONFIG_MTD_DEVICE /* Required for mtdparts */
#define CONFIG_CMD_MTDPARTS
#endif /* CONFIG_SPI_BOOT, ... */
#undef CONFIG_SPL_OS_BOOT
#ifdef CONFIG_SPL_OS_BOOT
#define CONFIG_SYS_SPL_ARGS_ADDR 0x80F80000
/* RAW SD card / eMMC */
#define CONFIG_SYS_MMCSD_RAW_MODE_KERNEL_SECTOR 0x900 /* address 0x120000 */
#define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTOR 0x80 /* address 0x10000 */
#define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTORS 0x80 /* 64KiB */
/* NAND */
#ifdef CONFIG_NAND
#define CONFIG_CMD_SPL_NAND_OFS 0x080000 /* end of u-boot */
#define CONFIG_SYS_NAND_SPL_KERNEL_OFFS 0x140000
#define CONFIG_CMD_SPL_WRITE_SIZE 0x2000
#endif /* CONFIG_NAND */
#endif /* CONFIG_SPL_OS_BOOT */
#ifdef CONFIG_NAND
#define CONFIG_SPL_NAND_AM33XX_BCH /* OMAP4 and later ELM support */
#define CONFIG_SPL_NAND_SUPPORT
#define CONFIG_SPL_NAND_BASE
#define CONFIG_SPL_NAND_DRIVERS
#define CONFIG_SPL_NAND_ECC
#define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_TEXT_BASE
#define CONFIG_SYS_NAND_U_BOOT_OFFS 0x80000
#endif /* CONFIG_NAND */
/* Always 64 KiB env size */
#define CONFIG_ENV_SIZE (64 << 10)
#ifdef CONFIG_NAND
#define NANDARGS \
"mtdids=" MTDIDS_DEFAULT "\0" \
"mtdparts=" MTDPARTS_DEFAULT "\0" \
"nandargs=setenv bootargs console=${console} " \
"${optargs} " \
"${optargs_rot} " \
"root=mtd6 " \
"rootfstype=jffs2\0" \
"kernelsize=0x400000\0" \
"nandboot=echo booting from nand ...; " \
"run nandargs; " \
"nand read ${loadaddr} kernel ${kernelsize}; " \
"bootz ${loadaddr} - ${dtbaddr}\0" \
"defboot=run nandboot\0" \
"bootlimit=1\0" \
"simplefb=1\0 " \
"altbootcmd=run usbscript\0"
#else
#define NANDARGS ""
#endif /* CONFIG_NAND */
#ifdef CONFIG_MMC
#define MMCARGS \
"dtbdev=mmc\0" \
"dtbpart=0:1\0" \
"mmcroot0=setenv bootargs ${optargs_rot} ${optargs} console=${console}\0" \
"mmcroot1=setenv bootargs ${optargs_rot} ${optargs} console=${console} " \
"root=/dev/mmcblk0p2 rootfstype=ext4\0" \
"mmcboot0=echo booting Updatesystem from mmc (ext4-fs) ...; " \
"setenv simplefb 1; " \
"ext4load mmc 0:1 ${loadaddr} /${kernel}; " \
"ext4load mmc 0:1 ${ramaddr} /${ramdisk}; " \
"run mmcroot0; bootz ${loadaddr} ${ramaddr} ${dtbaddr};\0" \
"mmcboot1=echo booting PPT-OS from mmc (ext4-fs) ...; " \
"setenv simplefb 0; " \
"ext4load mmc 0:2 ${loadaddr} /boot/${kernel}; " \
"run mmcroot1; bootz ${loadaddr} - ${dtbaddr};\0" \
"defboot=ext4load mmc 0:2 ${loadaddr} /boot/PPTImage.md5 && run mmcboot1; " \
"ext4load mmc 0:1 ${dtbaddr} /$dtb && run mmcboot0; " \
"run ramboot; run usbscript;\0" \
"bootlimit=1\0" \
"altbootcmd=run mmcboot0;\0" \
"upduboot=dhcp; " \
"tftp ${loadaddr} MLO && mmc write ${loadaddr} 100 100; " \
"tftp ${loadaddr} u-boot.img && mmc write ${loadaddr} 300 400;\0"
#else
#define MMCARGS ""
#endif /* CONFIG_MMC */
#ifndef CONFIG_SPL_BUILD
#define CONFIG_EXTRA_ENV_SETTINGS \
BUR_COMMON_ENV \
"verify=no\0" \
"autoload=0\0" \
"dtb=bur-ppt-ts30.dtb\0" \
"dtbaddr=0x80100000\0" \
"loadaddr=0x80200000\0" \
"ramaddr=0x80A00000\0" \
"kernel=zImage\0" \
"ramdisk=rootfs.cpio.uboot\0" \
"console=ttyO0,115200n8\0" \
"optargs=consoleblank=0 quiet panic=2\0" \
"nfsroot=/tftpboot/tseries/rootfs-small\0" \
"nfsopts=nolock\0" \
"ramargs=setenv bootargs ${optargs} console=${console} root=/dev/ram0\0" \
"netargs=setenv bootargs console=${console} " \
"${optargs} " \
"root=/dev/nfs " \
"nfsroot=${serverip}:${nfsroot},${nfsopts} rw " \
"ip=dhcp\0" \
"netboot=echo Booting from network ...; " \
"dhcp; " \
"tftp ${loadaddr} ${kernel}; " \
"tftp ${dtbaddr} ${dtb}; " \
"run netargs; " \
"bootz ${loadaddr} - ${dtbaddr}\0" \
"ramboot=echo Booting from network into RAM ...; "\
"if dhcp; then; " \
"tftp ${loadaddr} ${kernel}; " \
"tftp ${ramaddr} ${ramdisk}; " \
"if ext4load ${dtbdev} ${dtbpart} ${dtbaddr} /${dtb}; " \
"then; else tftp ${dtbaddr} ${dtb}; fi;" \
"run mmcroot0; " \
"bootz ${loadaddr} ${ramaddr} ${dtbaddr}; fi;\0" \
"netupdate=echo Updating UBOOT from Network (TFTP) ...; " \
"setenv autoload 0; " \
"dhcp && tftp 0x80000000 updateUBOOT.img && source;\0" \
NANDARGS \
MMCARGS
#endif /* !CONFIG_SPL_BUILD*/
#define CONFIG_BOOTCOMMAND \
"run defboot;"
#define CONFIG_BOOTDELAY 0
#ifdef CONFIG_NAND
/*
* GPMC block. We support 1 device and the physical address to
* access CS0 at is 0x8000000.
*/
#define CONFIG_SYS_MAX_NAND_DEVICE 1
#define CONFIG_SYS_NAND_BASE 0x8000000
#define CONFIG_NAND_OMAP_GPMC
/* don't change OMAP_ELM, ECCSCHEME. ROM code only supports this */
#define CONFIG_NAND_OMAP_ELM
#define CONFIG_NAND_OMAP_ECCSCHEME OMAP_ECC_BCH8_CODE_HW
#define CONFIG_SYS_NAND_5_ADDR_CYCLE
#define CONFIG_SYS_NAND_BLOCK_SIZE (128*1024)
#define CONFIG_SYS_NAND_PAGE_SIZE 2048
#define CONFIG_SYS_NAND_PAGE_COUNT (CONFIG_SYS_NAND_BLOCK_SIZE / \
CONFIG_SYS_NAND_PAGE_SIZE)
#define CONFIG_SYS_NAND_OOBSIZE 64
#define CONFIG_SYS_NAND_BAD_BLOCK_POS NAND_LARGE_BADBLOCK_POS
#define CONFIG_SYS_NAND_ECCPOS {2, 3, 4, 5, 6, 7, 8, 9, \
10, 11, 12, 13, 14, 15, 16, 17, \
18, 19, 20, 21, 22, 23, 24, 25, \
26, 27, 28, 29, 30, 31, 32, 33, \
34, 35, 36, 37, 38, 39, 40, 41, \
42, 43, 44, 45, 46, 47, 48, 49, \
50, 51, 52, 53, 54, 55, 56, 57, }
#define CONFIG_SYS_NAND_ECCSIZE 512
#define CONFIG_SYS_NAND_ECCBYTES 14
#define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_TEXT_BASE
#define CONFIG_SYS_NAND_U_BOOT_OFFS 0x80000
#define MTDIDS_DEFAULT "nand0=omap2-nand.0"
#define MTDPARTS_DEFAULT "mtdparts=omap2-nand.0:" \
"128k(MLO)," \
"128k(MLO.backup)," \
"128k(dtb)," \
"128k(u-boot-env)," \
"512k(u-boot)," \
"4m(kernel),"\
"128m(rootfs),"\
"-(user)"
#define CONFIG_NAND_OMAP_GPMC_WSCFG 1
#endif /* CONFIG_NAND */
/* USB configuration */
#define CONFIG_USB_MUSB_DSPS
#define CONFIG_ARCH_MISC_INIT
#define CONFIG_USB_MUSB_PIO_ONLY
#define CONFIG_USB_MUSB_DISABLE_BULK_COMBINE_SPLIT
/* attention! not only for gadget, enables also highspeed in hostmode */
#define CONFIG_USB_GADGET_DUALSPEED
#define CONFIG_AM335X_USB0
#define CONFIG_AM335X_USB0_MODE MUSB_HOST
#define CONFIG_AM335X_USB1
#define CONFIG_AM335X_USB1_MODE MUSB_HOST
#if defined(CONFIG_SPI_BOOT)
/* McSPI IP block */
#define CONFIG_SPI
#define CONFIG_OMAP3_SPI
#define CONFIG_SF_DEFAULT_SPEED 24000000
#define CONFIG_SPL_SPI_SUPPORT
#define CONFIG_SPL_SPI_FLASH_SUPPORT
#define CONFIG_SPL_SPI_LOAD
#define CONFIG_SYS_SPI_U_BOOT_OFFS 0x20000
#undef CONFIG_ENV_IS_NOWHERE
#define CONFIG_ENV_IS_IN_SPI_FLASH
#define CONFIG_SYS_REDUNDAND_ENVIRONMENT
#define CONFIG_ENV_SPI_MAX_HZ CONFIG_SF_DEFAULT_SPEED
#define CONFIG_ENV_SECT_SIZE (4 << 10) /* 4 KB sectors */
#define CONFIG_ENV_OFFSET (768 << 10) /* 768 KiB in */
#define CONFIG_ENV_OFFSET_REDUND (896 << 10) /* 896 KiB in */
#elif defined(CONFIG_EMMC_BOOT)
#undef CONFIG_ENV_IS_NOWHERE
#define CONFIG_ENV_IS_IN_MMC
#define CONFIG_SYS_MMC_ENV_DEV 0
#define CONFIG_SYS_MMC_ENV_PART 2
#define CONFIG_ENV_OFFSET 0x40000 /* TODO: Adresse definieren */
#define CONFIG_ENV_OFFSET_REDUND (CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE)
#define CONFIG_SYS_REDUNDAND_ENVIRONMENT
#elif defined(CONFIG_NAND)
/* No NAND env support in SPL */
#ifdef CONFIG_SPL_BUILD
#define CONFIG_ENV_IS_NOWHERE
#else
#define CONFIG_ENV_IS_IN_NAND
#endif
#define CONFIG_ENV_OFFSET 0x60000
#define CONFIG_SYS_ENV_SECT_SIZE CONFIG_ENV_SIZE
#else
#error "no storage for Environment defined!"
#endif
/*
* Common filesystems support. When we have removable storage we
* enabled a number of useful commands and support.
*/
#if defined(CONFIG_MMC) || defined(CONFIG_USB_STORAGE)
#define CONFIG_DOS_PARTITION
#define CONFIG_CMD_FAT
#define CONFIG_FAT_WRITE
#define CONFIG_FS_EXT4
#define CONFIG_EXT4_WRITE
#define CONFIG_CMD_EXT4
#define CONFIG_CMD_EXT4_WRITE
#define CONFIG_CMD_FS_GENERIC
#endif /* CONFIG_MMC, ... */
#endif /* ! __CONFIG_TSERIES_H__ */
| cosino/u-boot-enigma | include/configs/tseries.h | C | gpl-2.0 | 9,931 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_25) on Sun Oct 26 12:20:02 GMT+02:00 2014 -->
<title>Item</title>
<meta name="date" content="2014-10-26">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Item";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":9,"i10":10,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10,"i17":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Item.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?eshop/entity/Item.html" target="_top">Frames</a></li>
<li><a href="Item.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">eshop.entity</div>
<h2 title="Class Item" class="title">Class Item</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>eshop.entity.Item</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">Item</span>
extends java.lang.Object</pre>
<div class="block">Item class models a stock item in eShop program.
Items can be interactively produced using
<a href="../../eshop/parser/Parser.html#inputItem--"><code>eshop.parser.Parser#inputItem() factory method</code></a></div>
<dl>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>0.1</dd>
<dt><span class="simpleTagLabel">Version:</span></dt>
<dd>0.1</dd>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Trayan Iliev, http://iproduct.org</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../eshop/parser/Parser.html" title="class in eshop.parser"><code>Parser</code></a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item--">Item</a></span>()</code>
<div class="block">No argument constructor</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item-long-java.lang.String-java.lang.String-">Item</a></span>(long id,
java.lang.String name,
java.lang.String manufacturer)</code>
<div class="block">Constructor with mandatory arguments</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#Item-long-java.lang.String-java.lang.String-java.lang.String-java.lang.String-double-int-">Item</a></span>(long id,
java.lang.String name,
java.lang.String manufacturer,
java.lang.String category,
java.lang.String description,
double price,
int stockQuantity)</code>
<div class="block">Full constructor</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object obj)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getCategory--">getCategory</a></span>()</code>
<div class="block">Return item category.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getDescription--">getDescription</a></span>()</code>
<div class="block">Return item description</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>long</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getId--">getId</a></span>()</code>
<div class="block">Returns item id</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getManufacturer--">getManufacturer</a></span>()</code>
<div class="block">Return item manufacturer</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getName--">getName</a></span>()</code>
<div class="block">Returns item name</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getPrice--">getPrice</a></span>()</code>
<div class="block">Return item price in default currency</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#getStockQuantity--">getStockQuantity</a></span>()</code>
<div class="block">Returns stock quantity available for the item</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#hashCode--">hashCode</a></span>()</code> </td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#main-java.lang.String:A-">main</a></span>(java.lang.String[] args)</code> </td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setCategory-java.lang.String-">setCategory</a></span>(java.lang.String category)</code>
<div class="block">Sets item category from a predefined list of categories.</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setDescription-java.lang.String-">setDescription</a></span>(java.lang.String description)</code>
<div class="block">Sets item description</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setId-long-">setId</a></span>(long id)</code>
<div class="block">Sets item id</div>
</td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setManufacturer-java.lang.String-">setManufacturer</a></span>(java.lang.String manufacturer)</code>
<div class="block">Sets item manufacturer</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setName-java.lang.String-">setName</a></span>(java.lang.String name)</code>
<div class="block">Sets item name</div>
</td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setPrice-double-">setPrice</a></span>(double price)</code>
<div class="block">Sets item price in default currency</div>
</td>
</tr>
<tr id="i16" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#setStockQuantity-int-">setStockQuantity</a></span>(int stockQuantity)</code>
<div class="block">Modifies the stock quantity available for the item</div>
</td>
</tr>
<tr id="i17" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../eshop/entity/Item.html#toString--">toString</a></span>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Item--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>Item</h4>
<pre>public Item()</pre>
<div class="block">No argument constructor</div>
</li>
</ul>
<a name="Item-long-java.lang.String-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>Item</h4>
<pre>public Item(long id,
java.lang.String name,
java.lang.String manufacturer)</pre>
<div class="block">Constructor with mandatory arguments</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>id</code> - item it</dd>
<dd><code>name</code> - item name</dd>
<dd><code>manufacturer</code> - item manufacturer</dd>
</dl>
</li>
</ul>
<a name="Item-long-java.lang.String-java.lang.String-java.lang.String-java.lang.String-double-int-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Item</h4>
<pre>public Item(long id,
java.lang.String name,
java.lang.String manufacturer,
java.lang.String category,
java.lang.String description,
double price,
int stockQuantity)</pre>
<div class="block">Full constructor</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>@param</code> - id item it</dd>
<dd><code>name</code> - item name</dd>
<dd><code>manufacturer</code> - item manufacturer</dd>
<dd><code>category</code> - category name from a predefined list of categories</dd>
<dd><code>description</code> - optional item description</dd>
<dd><code>price</code> - optional standard price for the item</dd>
<dd><code>stockQuantity</code> - optional available stock quantity for the item</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getId--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getId</h4>
<pre>public long getId()</pre>
<div class="block">Returns item id</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the id</dd>
</dl>
</li>
</ul>
<a name="setId-long-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setId</h4>
<pre>public void setId(long id)</pre>
<div class="block">Sets item id</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>id</code> - the id to set</dd>
</dl>
</li>
</ul>
<a name="getName--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>public java.lang.String getName()</pre>
<div class="block">Returns item name</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the name</dd>
</dl>
</li>
</ul>
<a name="setName-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setName</h4>
<pre>public void setName(java.lang.String name)</pre>
<div class="block">Sets item name</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name to set</dd>
</dl>
</li>
</ul>
<a name="getManufacturer--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getManufacturer</h4>
<pre>public java.lang.String getManufacturer()</pre>
<div class="block">Return item manufacturer</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the manufacturer</dd>
</dl>
</li>
</ul>
<a name="setManufacturer-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setManufacturer</h4>
<pre>public void setManufacturer(java.lang.String manufacturer)</pre>
<div class="block">Sets item manufacturer</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>manufacturer</code> - the manufacturer to set</dd>
</dl>
</li>
</ul>
<a name="getCategory--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCategory</h4>
<pre>public java.lang.String getCategory()</pre>
<div class="block">Return item category.
See <a href="../../eshop/entity/Item.html#setCategory-java.lang.String-"><code>examples in #setCategory(String)</code></a></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the category</dd>
</dl>
</li>
</ul>
<a name="setCategory-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setCategory</h4>
<pre>public void setCategory(java.lang.String category)</pre>
<div class="block">Sets item category from a predefined list of categories. Example:
<ul>
<li>Processors</li>
<li>Moteherboards</li>
<li>Accessories</li>
<li>etc.</li>
</ul></div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>category</code> - the category to set</dd>
</dl>
</li>
</ul>
<a name="getDescription--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDescription</h4>
<pre>public java.lang.String getDescription()</pre>
<div class="block">Return item description</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the description</dd>
</dl>
</li>
</ul>
<a name="setDescription-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setDescription</h4>
<pre>public void setDescription(java.lang.String description)</pre>
<div class="block">Sets item description</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>description</code> - the description to set</dd>
</dl>
</li>
</ul>
<a name="getPrice--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPrice</h4>
<pre>public double getPrice()</pre>
<div class="block">Return item price in default currency</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the price</dd>
</dl>
</li>
</ul>
<a name="setPrice-double-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPrice</h4>
<pre>public void setPrice(double price)</pre>
<div class="block">Sets item price in default currency</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>price</code> - the price to set</dd>
</dl>
</li>
</ul>
<a name="getStockQuantity--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getStockQuantity</h4>
<pre>public int getStockQuantity()</pre>
<div class="block">Returns stock quantity available for the item</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the stockQuantity</dd>
</dl>
</li>
</ul>
<a name="setStockQuantity-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setStockQuantity</h4>
<pre>public void setStockQuantity(int stockQuantity)</pre>
<div class="block">Modifies the stock quantity available for the item</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>stockQuantity</code> - the stockQuantity to set</dd>
</dl>
</li>
</ul>
<a name="hashCode--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public int hashCode()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>hashCode</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="equals-java.lang.Object-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public boolean equals(java.lang.Object obj)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="toString--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="main-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] args)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/Item.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?eshop/entity/Item.html" target="_top">Frames</a></li>
<li><a href="Item.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| iproduct/IPT-Course-Java-8 | IPT-Course-Java-29ed/eShop/doc/eshop/entity/Item.html | HTML | gpl-2.0 | 22,609 |
<!DOCTYPE html>
<html>
<head>
<title>Asterisk Project : Asterisk 12 ManagerEvent_ConfbridgeEnd</title>
<link rel="stylesheet" href="styles/site.css" type="text/css" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body class="theme-default aui-theme-default">
<div id="page">
<div id="main" class="aui-page-panel">
<div id="main-header">
<div id="breadcrumb-section">
<ol id="breadcrumbs">
<li class="first">
<span><a href="index.html">Asterisk Project</a></span>
</li>
<li>
<span><a href="Asterisk-12-Documentation_25919697.html">Asterisk 12 Documentation</a></span>
</li>
<li>
<span><a href="Asterisk-12-Command-Reference_26476688.html">Asterisk 12 Command Reference</a></span>
</li>
<li>
<span><a href="Asterisk-12-AMI-Events_26476694.html">Asterisk 12 AMI Events</a></span>
</li>
</ol>
</div>
<h1 id="title-heading" class="pagetitle">
<span id="title-text">
Asterisk Project : Asterisk 12 ManagerEvent_ConfbridgeEnd
</span>
</h1>
</div>
<div id="content" class="view">
<div class="page-metadata">
Added by wikibot , edited by wikibot on Dec 18, 2013
</div>
<div id="main-content" class="wiki-content group">
<h1 id="Asterisk12ManagerEvent_ConfbridgeEnd-ConfbridgeEnd">ConfbridgeEnd</h1>
<h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Synopsis">Synopsis</h3>
<p>Raised when a conference ends.</p>
<h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Description">Description</h3>
<h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-Syntax">Syntax</h3>
<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
<pre>Action:
Conference: <value>
BridgeUniqueid: <value>
BridgeType: <value>
BridgeTechnology: <value>
BridgeCreator: <value>
BridgeName: <value>
BridgeNumChannels: <value>
</pre>
</div></div>
<h5 id="Asterisk12ManagerEvent_ConfbridgeEnd-Arguments">Arguments</h5>
<ul>
<li><code>Conference</code> - The name of the Confbridge conference.</li>
<li><code>BridgeUniqueid</code></li>
<li><code>BridgeType</code> - The type of bridge</li>
<li><code>BridgeTechnology</code> - Technology in use by the bridge</li>
<li><code>BridgeCreator</code> - Entity that created the bridge if applicable</li>
<li><code>BridgeName</code> - Name used to refer to the bridge by its BridgeCreator if applicable</li>
<li><code>BridgeNumChannels</code> - Number of channels in the bridge</li>
</ul>
<h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-SeeAlso">See Also</h3>
<ul>
<li><a href="Asterisk-12-ManagerEvent_ConfbridgeStart_26478095.html">Asterisk 12 ManagerEvent_ConfbridgeStart</a></li>
<li><a href="Asterisk-12-Application_ConfBridge_26476812.html">Asterisk 12 Application_ConfBridge</a></li>
</ul>
<h3 id="Asterisk12ManagerEvent_ConfbridgeEnd-ImportVersion">Import Version</h3>
<p>This documentation was imported from Asterisk Version SVN-branch-12-r404099</p>
</div>
</div> </div>
<div id="footer">
<section class="footer-body">
<p>Document generated by Confluence on Dec 20, 2013 14:14</p>
</section>
</div>
</div> </body>
</html>
| truongduy134/asterisk | doc/Asterisk-Admin-Guide/Asterisk-12-ManagerEvent_ConfbridgeEnd_26478094.html | HTML | gpl-2.0 | 4,182 |
<?php
/**
* General API for generating and formatting diffs - the differences between
* two sequences of strings.
*
* The original PHP version of this code was written by Geoffrey T. Dairiki
* <[email protected]>, and is used/adapted with his permission.
*
* Copyright 2004 Geoffrey T. Dairiki <[email protected]>
* Copyright 2004-2010 The Horde Project (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you did
* not receive this file, see http://opensource.org/licenses/lgpl-license.php.
*
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*/
class Text_Diff {
/**
* Array of changes.
*
* @var array
*/
var $_edits;
/**
* Computes diffs between sequences of strings.
*
* @param string $engine Name of the diffing engine to use. 'auto'
* will automatically select the best.
* @param array $params Parameters to pass to the diffing engine.
* Normally an array of two arrays, each
* containing the lines from a file.
*/
function Text_Diff($engine, $params) {
// Backward compatibility workaround.
if (!is_string($engine)) {
$params = array($engine, $params);
$engine = 'auto';
}
if ($engine == 'auto') {
$engine = extension_loaded('xdiff') ? 'xdiff' : 'native';
} else {
$engine = basename($engine);
}
// WP #7391
require_once dirname(__FILE__) . '/Diff/Engine/' . $engine . '.php';
$class = 'Text_Diff_Engine_' . $engine;
$diff_engine = new $class();
$this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params);
}
/**
* Returns the array of differences.
*/
function getDiff() {
return $this->_edits;
}
/**
* returns the number of new (added) lines in a given diff.
*
* @since Text_Diff 1.1.0
*
* @return integer The number of new lines
*/
function countAddedLines() {
$count = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_add') || is_a($edit, 'Text_Diff_Op_change')) {
$count += $edit->nfinal();
}
}
return $count;
}
/**
* Returns the number of deleted (removed) lines in a given diff.
*
* @since Text_Diff 1.1.0
*
* @return integer The number of deleted lines
*/
function countDeletedLines() {
$count = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_delete') || is_a($edit, 'Text_Diff_Op_change')) {
$count += $edit->norig();
}
}
return $count;
}
/**
* Computes a reversed diff.
*
* Example:
* <code>
* $diff = new Text_Diff($lines1, $lines2);
* $rev = $diff->reverse();
* </code>
*
* @return Text_Diff A Diff object representing the inverse of the
* original diff. Note that we purposely don't return a
* reference here, since this essentially is a clone()
* method.
*/
function reverse() {
if (version_compare(zend_version(), '2', '>')) {
$rev = clone($this);
} else {
$rev = $this;
}
$rev->_edits = array();
foreach ($this->_edits as $edit) {
$rev->_edits[] = $edit->reverse();
}
return $rev;
}
/**
* Checks for an empty diff.
*
* @return boolean True if two sequences were identical.
*/
function isEmpty() {
foreach ($this->_edits as $edit) {
if (!is_a($edit, 'Text_Diff_Op_copy')) {
return false;
}
}
return true;
}
/**
* Computes the length of the Longest Common Subsequence (LCS).
*
* This is mostly for diagnostic purposes.
*
* @return integer The length of the LCS.
*/
function lcs() {
$lcs = 0;
foreach ($this->_edits as $edit) {
if (is_a($edit, 'Text_Diff_Op_copy')) {
$lcs += count($edit->orig);
}
}
return $lcs;
}
/**
* Gets the original set of lines.
*
* This reconstructs the $from_lines parameter passed to the constructor.
*
* @return array The original sequence of strings.
*/
function getOriginal() {
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->orig) {
array_splice($lines, count($lines), 0, $edit->orig);
}
}
return $lines;
}
/**
* Gets the final set of lines.
*
* This reconstructs the $to_lines parameter passed to the constructor.
*
* @return array The sequence of strings.
*/
function getFinal() {
$lines = array();
foreach ($this->_edits as $edit) {
if ($edit->final) {
array_splice($lines, count($lines), 0, $edit->final);
}
}
return $lines;
}
/**
* Removes trailing newlines from a line of text. This is meant to be used
* with array_walk().
*
* @param string $line The line to trim.
* @param integer $key The index of the line in the array. Not used.
*/
static function trimNewlines(&$line, $key) {
$line = str_replace(array("\n", "\r"), '', $line);
}
/**
* Determines the location of the system temporary directory.
*
* @static
*
* @access protected
*
* @return string A directory name which can be used for temp files.
* Returns false if one could not be found.
*/
function _getTempDir() {
$tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', 'c:\windows\temp', 'c:\winnt\temp');
/* Try PHP's upload_tmp_dir directive. */
$tmp = ini_get('upload_tmp_dir');
/* Otherwise, try to determine the TMPDIR environment variable. */
if (!strlen($tmp)) {
$tmp = getenv('TMPDIR');
}
/* If we still cannot determine a value, then cycle through a list of
* preset possibilities. */
while (!strlen($tmp) && count($tmp_locations)) {
$tmp_check = array_shift($tmp_locations);
if (@is_dir($tmp_check)) {
$tmp = $tmp_check;
}
}
/* If it is still empty, we have failed, so return false; otherwise
* return the directory determined. */
return strlen($tmp) ? $tmp : false;
}
/**
* Checks a diff for validity.
*
* This is here only for debugging purposes.
*/
function _check($from_lines, $to_lines) {
if (serialize($from_lines) != serialize($this->getOriginal())) {
trigger_error("Reconstructed original doesn't match", E_USER_ERROR);
}
if (serialize($to_lines) != serialize($this->getFinal())) {
trigger_error("Reconstructed final doesn't match", E_USER_ERROR);
}
$rev = $this->reverse();
if (serialize($to_lines) != serialize($rev->getOriginal())) {
trigger_error("Reversed original doesn't match", E_USER_ERROR);
}
if (serialize($from_lines) != serialize($rev->getFinal())) {
trigger_error("Reversed final doesn't match", E_USER_ERROR);
}
$prevtype = null;
foreach ($this->_edits as $edit) {
if ($prevtype == get_class($edit)) {
trigger_error("Edit sequence is non-optimal", E_USER_ERROR);
}
$prevtype = get_class($edit);
}
return true;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*/
class Text_MappedDiff extends Text_Diff {
/**
* Computes a diff between sequences of strings.
*
* This can be used to compute things like case-insensitve diffs, or diffs
* which ignore changes in white-space.
*
* @param array $from_lines An array of strings.
* @param array $to_lines An array of strings.
* @param array $mapped_from_lines This array should have the same size
* number of elements as $from_lines. The
* elements in $mapped_from_lines and
* $mapped_to_lines are what is actually
* compared when computing the diff.
* @param array $mapped_to_lines This array should have the same number
* of elements as $to_lines.
*/
function Text_MappedDiff($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) {
assert(count($from_lines) == count($mapped_from_lines));
assert(count($to_lines) == count($mapped_to_lines));
parent::Text_Diff($mapped_from_lines, $mapped_to_lines);
$xi = $yi = 0;
for ($i = 0; $i < count($this->_edits); $i++) {
$orig = &$this->_edits[$i]->orig;
if (is_array($orig)) {
$orig = array_slice($from_lines, $xi, count($orig));
$xi += count($orig);
}
$final = &$this->_edits[$i]->final;
if (is_array($final)) {
$final = array_slice($to_lines, $yi, count($final));
$yi += count($final);
}
}
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*
* @access private
*/
class Text_Diff_Op {
var $orig;
var $final;
function &reverse() {
trigger_error('Abstract method', E_USER_ERROR);
}
function norig() {
return $this->orig ? count($this->orig) : 0;
}
function nfinal() {
return $this->final ? count($this->final) : 0;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*
* @access private
*/
class Text_Diff_Op_copy extends Text_Diff_Op {
function Text_Diff_Op_copy($orig, $final = false) {
if (!is_array($final)) {
$final = $orig;
}
$this->orig = $orig;
$this->final = $final;
}
function &reverse() {
$reverse = new Text_Diff_Op_copy($this->final, $this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*
* @access private
*/
class Text_Diff_Op_delete extends Text_Diff_Op {
function Text_Diff_Op_delete($lines) {
$this->orig = $lines;
$this->final = false;
}
function &reverse() {
$reverse = new Text_Diff_Op_add($this->orig);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*
* @access private
*/
class Text_Diff_Op_add extends Text_Diff_Op {
function Text_Diff_Op_add($lines) {
$this->final = $lines;
$this->orig = false;
}
function &reverse() {
$reverse = new Text_Diff_Op_delete($this->final);
return $reverse;
}
}
/**
* @package Text_Diff
* @author Geoffrey T. Dairiki <[email protected]>
*
* @access private
*/
class Text_Diff_Op_change extends Text_Diff_Op {
function Text_Diff_Op_change($orig, $final) {
$this->orig = $orig;
$this->final = $final;
}
function &reverse() {
$reverse = new Text_Diff_Op_change($this->final, $this->orig);
return $reverse;
}
}
| ajspencer/NCSSM-SG-WordPress | wp-includes/Text/Diff.php | PHP | gpl-2.0 | 11,727 |
/*
Stuart Bowman 2016
This class contains the graph nodes themselves, as well as helper functions for use by the generation class
to better facilitate evaluation and breeding. It also contains the class definition for the nodes themselves,
as well as the A* search implementation used by the genetic algorithm to check if a path can be traced between
two given points on the maze.
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Graph
{
public Dictionary<int, Node> nodes;
float AStarPathSuccess = 0.0f;//fraction of samples that could be maped to nodes and completed with AStar
float AStarAvgPathLength = 0.0f;//average path length of successful paths
public float getAStarPathSuccess() { return AStarPathSuccess; }
public float getAStarAvgPathLength() { return AStarAvgPathLength; }
public float getCompositeScore() { return AStarPathSuccess; }//a weighted, composite score of all evaluated attributes of this graph
public int newNodeStartingID = 0;
public Graph(int startingID)
{
newNodeStartingID = startingID;
nodes = new Dictionary<int, Node>();
}
public Graph(List<GameObject> floors, List<GameObject> walls, int initNumNodes = 20)
{
nodes = new Dictionary<int, Node>();
for (int i = 0; i < initNumNodes; i++)
{
int rndTile = Random.Range(0, floors.Count);
//get the 2d bounding area for any floor tile
MeshCollider mc = floors[rndTile].GetComponent<MeshCollider>();
Vector2 xyWorldSpaceBoundsBottomLeft = new Vector2(mc.bounds.center.x - mc.bounds.size.x/2, mc.bounds.center.z - mc.bounds.size.z/2);
Vector2 rndPosInTile = new Vector2(Random.Range(0, mc.bounds.size.x), Random.Range(0, mc.bounds.size.z));
Vector2 rndWorldPos = xyWorldSpaceBoundsBottomLeft + rndPosInTile;
Node n = addNewNode(rndWorldPos);
}
connectAllNodes();
}
public Graph(Graph g)//deep copy constructor
{
nodes = new Dictionary<int, Node>();
//deep copy
foreach (KeyValuePair<int, Node> entry in g.nodes)
{
//deep copy the node with the best score
bool inherited = entry.Value.isNodeInheritedFromParent();
Node currentNode = new Node(new Vector2(entry.Value.pos.x, entry.Value.pos.y), entry.Value.ID, inherited);
//don't bother copying the A* and heuristic stuff for each node, it's just going to be re-crunched later
nodes.Add(currentNode.ID, currentNode);
}
AStarPathSuccess = g.getAStarPathSuccess();
AStarAvgPathLength = g.getAStarAvgPathLength();
}
public static float normDistRand(float mean, float stdDev)
{
float u1 = Random.Range(0, 1.0f);
float u2 = Random.Range(0, 1.0f);
float randStdNormal = Mathf.Sqrt(-2.0f * Mathf.Log(u1) * Mathf.Sin(2.0f * 3.14159f * u2));
return mean + stdDev * randStdNormal;
}
public string getSummary()
{
string result = "";
result += nodes.Count + "\tNodes\t(" + getNumOfNewlyAddedNodes() + " new)\n";
result += getAStarPathSuccess() * 100 + "%\tA* Satisfaction\n";
result += getAStarAvgPathLength() + "\tUnit avg. A* Path\n";
return result;
}
int getNumOfNewlyAddedNodes()
{
int result = 0;
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (entry.Value.isNodeInheritedFromParent() == false)
result++;
}
return result;
}
public void connectAllNodes()
{
foreach (KeyValuePair<int,Node> entry in nodes)
{
foreach (KeyValuePair<int, Node> entry2 in nodes)
{
if (entry.Value != entry2.Value)
{
if (!Physics.Linecast(new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y), new Vector3(entry2.Value.pos.x, 2, entry2.Value.pos.y)))
{
entry.Value.connectTo(entry2.Value);
}
}
}
}
}
public int getFirstUnusedID()
{
for (int i = 0; i < nodes.Count; i++)
{
if (!nodes.ContainsKey(i))
return i;
}
return nodes.Count;
}
public int getMaxID()
{
int temp = 0;
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (entry.Value.ID > temp) temp = entry.Value.ID;
}
if (temp < newNodeStartingID)
return newNodeStartingID;
return temp;
}
public class Node
{
public int ID;
public Vector2 pos;
public List<Node> connectedNodes;
bool inheritedFromParent;
public Node Ancestor;//used in A*
public float g, h;//public values for temporary use during searching and heuristic analysis
public float f
{
get {return g + h; }
private set { }
}
public bool isNodeInheritedFromParent()
{
return inheritedFromParent;
}
public Node(Vector2 position, int id, bool inherited)
{
connectedNodes = new List<Node>();
pos = position;
ID = id;
inheritedFromParent = inherited;
}
public void connectTo(Node node)
{
if (!connectedNodes.Contains(node))
{
connectedNodes.Add(node);
if (!node.connectedNodes.Contains(this))
{
node.connectedNodes.Add(this);
}
}
}
public void disconnectFrom(Node n)
{
for (int i = 0; i < connectedNodes.Count; i++)
{
if (connectedNodes[i] == n)
n.connectedNodes.Remove(this);
}
connectedNodes.Remove(n);
}
}
public Node addNewNode(Vector2 pos)
{
int newID = this.getMaxID()+1;//get the new id from the maxID property
Node tempNode = new Node(pos, newID, false);
nodes.Add(newID, tempNode);
return tempNode;
}
public Node addNewNode(Vector2 pos, int ID)
{
Node tempNode = new Node(pos, ID, false);
nodes.Add(ID, tempNode);
return tempNode;
}
public Node addNewNode(Vector2 pos, int ID, bool inherited)
{
Node tempNode = new Node(pos, ID, inherited);
nodes.Add(ID, tempNode);
return tempNode;
}
public void removeNode(int ID)
{
Node nodeToRemove = nodes[ID];
foreach (Node n in nodeToRemove.connectedNodes)
{
//remove symmetrical connections
n.connectedNodes.Remove(nodeToRemove);
}
nodes.Remove(ID);//delete the actual node
}
public void printAdjMatrix()
{
foreach (KeyValuePair<int, Node> entry in nodes)
{
string connNodes = "Node: " + entry.Value.ID + "\nConn: ";
foreach (Node n2 in entry.Value.connectedNodes)
{
connNodes += n2.ID + ", ";
}
Debug.Log(connNodes);
}
}
public List<Node> AStar(int startingNodeKey, int endingNodeKey)
{
List<Node> ClosedSet = new List<Node>();
List<Node> OpenSet = new List<Node>();
foreach(KeyValuePair<int, Node> entry in nodes)
{
entry.Value.g = 99999;//set all g values to infinity
entry.Value.Ancestor = null;//set all node ancestors to null
}
nodes[startingNodeKey].g = 0;
nodes[startingNodeKey].h = Vector2.Distance(nodes[startingNodeKey].pos, nodes[endingNodeKey].pos);
OpenSet.Add(nodes[startingNodeKey]);
while (OpenSet.Count > 0 )
{
float minscore = 99999;
int minIndex = 0;
for(int i = 0;i<OpenSet.Count;i++)
{
if (OpenSet[i].f < minscore)
{
minscore = OpenSet[i].f;
minIndex = i;
}
}
//deep copy the node with the best score
Node currentNode = new Node(new Vector2(OpenSet[minIndex].pos.x, OpenSet[minIndex].pos.y), OpenSet[minIndex].ID, false);
currentNode.g = OpenSet[minIndex].g;
currentNode.h = OpenSet[minIndex].h;
currentNode.Ancestor = OpenSet[minIndex].Ancestor;
if (currentNode.ID == endingNodeKey)
{
//build the path list
List<Node> fullPath = new List<Node>();
Node temp = currentNode;
while (temp != null)
{
fullPath.Add(temp);
temp = temp.Ancestor;
}
return fullPath;
}
//remove this node from the open set
OpenSet.RemoveAt(minIndex);
ClosedSet.Add(currentNode);
//go through the list of nodes that are connected to the current node
foreach(Node n in nodes[currentNode.ID].connectedNodes)
{
bool isInClosedSet = false;
//check if it's already in the closed set
for (int i = 0; i < ClosedSet.Count; i++)
{
if (ClosedSet[i].ID == n.ID)
{
isInClosedSet = true;
break;
}
}
if (isInClosedSet)
continue;
float tenativeG = currentNode.g + Vector2.Distance(n.pos, currentNode.pos);
bool isInOpenSet = false;
for (int i = 0; i < OpenSet.Count; i++)
{
if (OpenSet[i].ID == n.ID)
isInOpenSet = true;
}
if (!isInOpenSet)
OpenSet.Add(n);
else if (tenativeG >= n.g)
continue;
n.Ancestor = currentNode;
n.g = tenativeG;
n.h = Vector2.Distance(n.pos, nodes[endingNodeKey].pos);
}
}
//didn't find a path
return new List<Node>();
}
public void generateAStarSatisfaction(List<Vector2> startingPoint, List<Vector2> endingPoint)
{
int successfulPaths = 0;
float avgPathLen = 0.0f;
for (int i = 0; i < startingPoint.Count; i++)
{
Node startingNode = closestNodeToPoint(startingPoint[i]);
if (startingNode == null)
continue;//skip to next iteration if no starting node can be found
Node endingNode = closestNodeToPoint(endingPoint[i]);
if (endingNode == null)
continue;//skip to next iteration if no ending node can be found
List<Node> path = AStar(startingNode.ID, endingNode.ID);
if (path.Count != 0)//if the path was successful
{
successfulPaths++;
avgPathLen += path[path.Count - 1].g +
Vector2.Distance(startingPoint[i], startingNode.pos) + Vector2.Distance(endingPoint[i], endingNode.pos);
}
}
avgPathLen /= successfulPaths;
//store results
AStarAvgPathLength = avgPathLen;
AStarPathSuccess = successfulPaths / (float)startingPoint.Count;
}
Node closestNodeToPoint(Vector2 point)
{
//find closest node to the given starting point
List<Node> lineOfSightNodes = new List<Node>();
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (!Physics.Linecast(new Vector3(point.x, 2, point.y), new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y)))
{
lineOfSightNodes.Add(entry.Value);
}
}
float minDist = 999999;
int minIndex = 0;
if (lineOfSightNodes.Count == 0)
return null;//no nodes are line of sight to this point
for (int j = 0; j < lineOfSightNodes.Count; j++)
{
float dist = Vector2.Distance(point, lineOfSightNodes[j].pos);
if (dist < minDist)
{
minDist = dist;
minIndex = j;
}
}
return lineOfSightNodes[minIndex];
}
}
| stuartsoft/gngindiestudy | Assets/Scripts/Graph.cs | C# | gpl-2.0 | 12,517 |
<?php
function migrate_blog() {
/*
* $tabRub[0] = "Annonces";
$tabRub[1] = "Partenariat";
$tabRub[2] = "Vie d'Anciela";
$tabRub[3] = "Autres";
* */
$categories = array('annonces','partenariat','anciela','autres');
$categoryNames = array('annonces'=>"Annonces",'partenariat'=>'Partenariats','anciela'=>"Vie d'anciela",'autres'=>'Autres');
foreach($categoryNames as $categorySlug => $categoryName) {
wp_insert_term($categoryName, 'category', array('slug'=>$categorySlug));
}
$db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($link));
// Setup the author, slug, and title for the post
$author_id = 1;
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
);
$attachments = get_posts($args);
$db->query('set names utf8');
$db->query("SET character_set_connection = 'UTF8'");
$db->query("SET character_set_client = 'UTF8'");
$db->query("SET character_set_results = 'UTF8'");
$result = $db->query("select * from `anc_info_blog`");
while($row = $result->fetch_array()) {
$categoryIntId = ($row["rub_blog"]-1);
$category = $categories[$categoryIntId];
$category = get_category_by_slug($category);
if ($category) {
$category = $category->term_id;
}
$title = stripslashes($row["titre_blog"]);
$date = $row["date_pub_deb_blog"];
$content = stripslashes($row['texte_blog']);
$img = $row['image_blog'];
$align = $row['image_pos_blog'] == 0 ? 'center' : 'right';
if ($img) {
foreach ($attachments as $post) {
setup_postdata($post);
the_title();
$mediaTitle = $post->post_title;
$img = explode('.', $img)[0];
if ($mediaTitle == $img) {
$id = $post->ID;
$content = '[image id="'.$id.'" align="'.$align.'"]<br/>'.$content;
}
/*$dataToSave = array(
'ID' => $post->ID,
'post_title' =>
);
wp_update_post($dataToSave);*/
}
}
if (null == get_page_by_title($title, null, 'post')) {
wp_insert_post(
array(
'comment_status' => 'open',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'post',
'post_category' => array($category),
'post_date' => $date . ' 12:00:00',
'post_content' => $content
)
);
}
}
mysqli_close($db);
} // end migrate_blog
//migrate_blog();
function migrate_events() {
global $wpdb;
$db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($db));
// Setup the author, slug, and title for the post
$author_id = 1;
$db->query('set names utf8');
$db->query("SET character_set_connection = 'UTF8'");
$db->query("SET character_set_client = 'UTF8'");
$db->query("SET character_set_results = 'UTF8'");
$result = $db->query("select * from `anc_info_even_renc`");
$querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%location%'";
$locationKey = $wpdb->get_results($querystr, OBJECT);
if ($locationKey[0]) {
$locationKey = $locationKey[0]->meta_key;
}
$querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%beginDate%'";
$beginDateKey = $wpdb->get_results($querystr, OBJECT);
if ($beginDateKey[0]) {
$beginDateKey = $beginDateKey[0]->meta_key;
}
$querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%endDate%'";
$endDateKey = $wpdb->get_results($querystr, OBJECT);
if ($endDateKey[0]) {
$endDateKey = $endDateKey[0]->meta_key;
}
$querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%beginTime%'";
$beginTimeKey = $wpdb->get_results($querystr, OBJECT);
if ($beginTimeKey[0]) {
$beginTimeKey = $beginTimeKey[0]->meta_key;
}
$querystr = "SELECT meta_key FROM $wpdb->postmeta WHERE meta_value LIKE '%endTime%'";
$endTimeKey = $wpdb->get_results($querystr, OBJECT);
if ($endTimeKey[0]) {
$endTimeKey = $endTimeKey[0]->meta_key;
}
while ($row = $result->fetch_array()) {
$title = stripslashes($row["titre_even_renc"]);
$content = stripslashes($row['texte_even_renc'].'<br /><br />Intervenants : '.$row['intervenants_even_renc']);
$location = stripslashes($row['lieu_even_renc']);
$beginDate = $row['date_pub_deb_even_renc'];
$endDate = $row['date_pub_fin_even_renc'];
$timeStr = $row['horaire_even_renc'];
$time = str_replace('h', ':', $timeStr);
$time = explode(' ', $time);
$beginTime = $time[0];
if (strlen($beginTime) == 3) {
$beginTime = $beginTime . '00';
}
$endTime = $time[2];
if (strlen($endTime) == 3) {
$endTime = $endTime . '00';
}
if (null == get_page_by_title($title, null, 'event')) {
$postId = wp_insert_post(
array(
'comment_status' => 'open',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'event',
'post_date' => $row['date_crea_even_renc'],
'post_content' => $content,
)
);
$beginDate = str_replace('-','',$beginDate);
$endDate = str_replace('-','',$endDate);
if ($endDate == '00000000') {
$endDate = $beginDate;
}
$acf = array(
$locationKey => array('address' => $location),
$beginTimeKey => $beginTime,
$endTimeKey => $endTime,
$beginDateKey => $beginDate,
$endDateKey => $endDate
);
foreach($acf as $k => $v ) {
$f = apply_filters('acf/load_field', false, $k );
do_action('acf/update_value', $v, $postId, $f );
}
}
}
mysqli_close($db);
} // end migrate_events
//migrate_events();
function image_shortcode($atts, $content = null) {
extract( shortcode_atts( array(
'id' => '',
'align' => 'center',
), $atts ) );
if (isset($id)) {
$url = wp_get_attachment_image_src($id, 'large')[0];
if ($align == 'center') {
$output = '<p style="text-align:center;"><a href="'.$url.'""><img style="max-width:100%;" src="'.$url.'" /></a></p>';
} else {
$output = '<a href="'.$url.'""><img style="max-width:100%;float:right;margin-left:20px;" src="'.$url.'" /></a>';
}
return $output;
}
trigger_error($id." image not found", E_USER_WARNING);
return '';
}
add_shortcode('image','image_shortcode');
function setupPages() {
$pages = array(
"Découvrir Anciela",
"Agenda des activités",
"Blog",
"Contact",
"Anciela : Nos objectifs",
"Anciela : Notre équipe",
"Anciela : Devenir Bénévole",
"Anciela : Nous soutenir",
"Anciela : Actualités d'Anciela",
"Démarches participatives : Collégiens et lycéens éco-citoyens",
"Démarches participatives : Étudiants éco-citoyens",
"Démarches participatives : Territoires de vie",
"Démarches participatives : Animations ponctuelles",
"Pépinière d'initiatives citoyennes : La démarche",
"Pépinière d'initiatives citoyennes : Les cycles d'activités",
"Pépinière d'initiatives citoyennes : Les initiatives accompagnées",
"Pépinière d'initiatives citoyennes : Participez !",
"Projets numériques : democratie-durable.info",
"Projets numériques : ressources-ecologistes.org",
"Projets internationaux : Notre démarche",
"Projets internationaux : Jeunesse francophone pour un monde écologique et solidaire",
"Projets internationaux : Nos partenaires",
"Projets internationaux : Construire des projets avec nous ?",
"Recherche : Esprit de la recherche",
"Recherche : Partages et publications",
"Recherche : Participez à la recherche !",
"Recherche : Le Conseil scientifique",
"Formations : Esprit des formations",
"Formations : Formations ouvertes",
"Formations : Service civique",
"Formations : Formation et accompagnement des structures",
"Nous rejoindre",
"Réseaux, agréments et partenaires",
"Ils parlent de nous",
"Communiqués et logos",
"Nos rapports d’activités",
"Mentions légales",
"Faire un don : pourquoi ? Comment ?",
"Newsletter",
"J'ai une idée !"
);
foreach($pages as $pageTitle) {
if (null == get_page_by_title($pageTitle, null, 'page')) {
wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => '1',
'post_title' => $pageTitle,
'post_status' => 'publish',
'post_type' => 'page'
)
);
}
}
} // end setupPages
//setupPages();
function setup_header_menu() {
$menuName = 'header';
$exists = wp_get_nav_menu_object($menuName);
if(!$exists){
$menuId = wp_update_nav_menu_object(0, array(
'menu-name' => $menuName,
'theme-location' => 'header'
));
$entries = array(
'Découvrir Anciela' => '',
'Agenda des activités' => 'Agenda',
'Blog' => '',
'Contact' => ''
);
foreach ($entries as $pageName => $linkTitle) {
$page = get_page_by_title($pageName, null, 'page');
if (empty($linkTitle)) {
$linkTitle = $pageName;
}
wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $linkTitle,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-status' => 'publish'));
}
}
}
//setup_header_menu();
function setup_home_menu() {
$menuName = 'home';
$exists = wp_get_nav_menu_object($menuName);
if(!$exists){
$menuId = wp_update_nav_menu_object(0, array(
'menu-name' => $menuName,
'theme-location' => $menuName
));
$entries = array(
'Anciela : Devenir Bénévole' => 'Devenir Bénévole',
'Faire un don : pourquoi ? Comment ?' => 'Dons citoyens',
'Newsletter' => '',
"J'ai une idée" => "J'ai une idée !"
);
foreach ($entries as $pageName => $linkTitle) {
$page = get_page_by_title($pageName, null, 'page');
if (empty($linkTitle)) {
$linkTitle = $pageName;
}
wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $linkTitle,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-status' => 'publish'));
}
}
}
//setup_home_menu();
function setup_footer_menu() {
$menuName = 'footer';
$exists = wp_get_nav_menu_object($menuName);
if(!$exists){
$menuId = wp_update_nav_menu_object(0, array(
'menu-name' => $menuName,
'theme-location' => 'footer'
));
$entries = array(
'Anciela : Notre équipe' => 'Notre équipe',
'Nous rejoindre' => '',
"Réseaux, agréments et partenaires" => '',
'Ils parlent de nous' => '',
"Communiqués et logos" => 'Communiqués & logos',
"Nos rapports d’activités" => '',
'Mentions légales' => ''
);
foreach ($entries as $pageName => $linkTitle) {
$page = get_page_by_title($pageName, null, 'page');
if (empty($linkTitle)) {
$linkTitle = $pageName;
}
wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $linkTitle,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-status' => 'publish'));
}
}
}
//setup_footer_menu();
function setup_side_menu() {
$menuName = 'side';
//wp_delete_nav_menu($menuName);
$exists = wp_get_nav_menu_object($menuName);
if(!$exists){
$menuId = wp_update_nav_menu_object(0, array(
'menu-name' => $menuName,
'theme-location' => $menuName
));
$entries = array(
'Anciela' => array(
'Anciela : Nos objectifs' => 'Nos objectifs',
'Anciela : Notre équipe' => 'Notre équipe',
'Anciela : Devenir bénévole' => 'Devenir bénévole',
'Anciela : Nous soutenir' => 'Nous soutenir',
'Anciela : Actualités d\'Anciela' => 'Actualités d\'Anciela'
),
'Démarches participatives' => array(
'Démarches participatives : Collégiens et lycéens éco-citoyens' => 'Jeunes éco-citoyens',
'Démarches participatives : Étudiants éco-citoyens' => 'Étudiants éco-citoyens',
'Démarches participatives : Territoires de vie' => 'Territoires de vie',
'Démarches participatives : Animations ponctuelles' => 'Animations ponctuelles'
),
'Pépinière d\'initiatives' => array(
'Pépinière d\'initiatives citoyennes : La démarche' => 'La démarche',
"Pépinière d'initiatives citoyennes : Les cycles d'activités" => "Les cycles d'activités",
"Pépinière d'initiatives citoyennes : Les initiatives accompagnées" => 'Les initiatives',
'Pépinière d\'initiatives citoyennes : Participez !' => 'Participez !'
),
'Projets numériques' => array(
'Projets numériques : democratie-durable.info' => 'Démocratie Durable',
'Projets numériques : ressources-ecologistes.org' => 'Ressources écologistes'
),
'Projets internationaux' => array(
"Projets internationaux : Notre démarche" => "Notre démarche",
"Projets internationaux : Jeunesse francophone pour un monde écologique et solidaire" => "Jeunesse francophone",
"Projets internationaux : Nos partenaires" => "Nos partenaires",
"Projets internationaux : Construire des projets avec nous ?" => "Construire des projets<br/>avec nous ?"
),
'Recherche' => array(
"Recherche : Esprit de la recherche" => "Esprit de la recherche",
"Recherche : Partages et publications" => "Partages et publications",
"Recherche : Participez à la recherche !" => "Participez à la recherche !",
"Recherche : Le Conseil scientifique" => "Le Conseil scientifique"
),
'Formations' => array(
'Formations : Esprit des formations' => 'Esprit des formations',
'Formations : Formations ouvertes' => 'Formations ouvertes',
'Formations : Service civique' => 'Service civique',
'Formations : Formation et accompagnement des structures' => 'Formation et accompagnement<br/>des structures'
)
);
foreach ($entries as $pageName => $data) {
if (is_array($data)) {
$parentItemId = wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $pageName,
'menu-item-url' => '',
'menu-item-status' => 'publish'));
foreach($data as $childPageName => $childPageTitle) {
$page = get_page_by_title($childPageName, null, 'page');
wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $childPageTitle,
'menu-item-parent-id' => $parentItemId,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-status' => 'publish'));
}
} else {
$page = get_page_by_title($pageName, null, 'page');
wp_update_nav_menu_item($menuId, 0, array(
'menu-item-title' => $pageName,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-status' => 'publish'));
}
}
}
}
//setup_side_menu();
function setup_menu_locations() {
$headerMenu = wp_get_nav_menu_object('header');
$footerMenu = wp_get_nav_menu_object('footer');
$sideMenu = wp_get_nav_menu_object('side');
$homeMenu = wp_get_nav_menu_object('home');
set_theme_mod('nav_menu_locations', array(
'header' => $headerMenu->term_id,
'side' => $sideMenu->term_id,
'footer' => $footerMenu->term_id,
'home' => $homeMenu->term_id
));
}
//setup_menu_locations();
update_option('timezone_string', 'Europe/Paris');
function add_custom_taxonomies() {
// Add new "Locations" taxonomy to Posts
$taxonomy = 'articles';
if (!taxonomy_exists($taxonomy)) {
register_taxonomy($taxonomy, 'post', array(
'hierarchical' => false,
// This array of options controls the labels displayed in the WordPress Admin UI
'labels' => array(
'name' => _x('Types', 'taxonomy general name'),
'singular_name' => _x('Type d\'articles', 'taxonomy singular name'),
'search_items' => __('Chercher un type d\'articles'),
'all_items' => __('Tous les types d\'articles'),
'edit_item' => __('Modifier ce type d\'articles'),
'update_item' => __('Modifier ce type d\'articles'),
'add_new_item' => __('Ajouter un nouveau type d\'articles'),
'new_item_name' => __('Nouveau type d\'articles'),
'menu_name' => __('Types'),
),
// Control the slugs used for this taxonomy
'rewrite' => array(
'with_front' => false, // Don't display the category base before "/locations/"
'hierarchical' => false // This will allow URL's like "/locations/boston/cambridge/"
),
));
$array = array('Blog', 'Jeunes Éco-citoyens', 'Étudiants Éco-citoyens', 'Territoires de vie', 'Pépinière (démarche)', 'Démocratie Durable',
'Recherche', 'Formations', 'Projets internationaux', 'Projets numériques');
foreach($array as $page) {
wp_insert_term($page, $taxonomy);
}
}
}
//add_custom_taxonomies();
function renameMedia() {
$db = mysqli_connect("localhost","root","","db161162332") or die("Error " . mysqli_error($db));
// Setup the author, slug, and title for the post
$author_id = 1;
$db->query('set names utf8');
$db->query("SET character_set_connection = 'UTF8'");
$db->query("SET character_set_client = 'UTF8'");
$db->query("SET character_set_results = 'UTF8'");
$files = array();
$result = $db->query("select * from `anc_info_fichier`");
while ($row = $result->fetch_array()) {
$fileId = strtolower(current(explode(".", $row['nom_file'])));
$files[$fileId] = $row['libelle_file'];
}
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $post) {
the_title();
wp_update_post(array('ID'=>$post->ID, 'post_title'=>$files[$post->post_name]));
}
}
$db->close();
}
//renameMedia();
function my_excerpt_length($length) {
return 50;
}
add_filter('excerpt_length', 'my_excerpt_length');
if(!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', get_template_directory_uri() . '/lib/jquery/dist/jquery.min.js', array(), null, true);
wp_register_script('momentjs-core', get_template_directory_uri() . '/lib/momentjs/min/moment.min.js', array(), null, true);
wp_register_script('momentjs', get_template_directory_uri() . '/lib/momentjs/lang/fr.js', array('momentjs-core'), null, true);
wp_register_script('underscorejs', get_template_directory_uri() . '/lib/underscore/underscore.js', array(), null, true);
wp_register_script('clndr', get_template_directory_uri() . '/lib/clndr/clndr.min.js', array('jquery', 'momentjs', 'underscorejs'), null, true);
wp_register_script('tooltipster', get_template_directory_uri() . '/lib/tooltipster/js/jquery.tooltipster.min.js', array(), null, true);
wp_register_style('anciela-style', get_template_directory_uri() . '/style.css', array(), null);
wp_register_style('tooltipster-style', get_template_directory_uri() . '/lib/tooltipster/css/tooltipster.css', array('anciela-style'), null);
}
wp_register_style('fontawesome', 'http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css', array('anciela-style'), null);
| Anciela/anciela.info | wp-content/themes/anciela/inc/anciela-setup.php | PHP | gpl-2.0 | 22,406 |
Experimental IRC-like chat
==========================
This is experimental project as an attempt to crete IRC like (channels and users) chat server and client.
DIRECTORY STRUCTURE
-------------------
assets/ contains assets definition
commands/ contains console commands (controllers)
config/ contains application configurations
controllers/ contains Web controller classes
mail/ contains view files for e-mails
models/ contains model classes
runtime/ contains files generated during runtime
tests/ contains various tests for the basic application
vendor/ contains dependent 3rd-party packages
views/ contains view files for the Web application
web/ contains the entry script and Web resources
REQUIREMENTS
------------
The minimum requirement by this application template that your Web server supports PHP 5.5.0.
INSTALLATION
------------
### Install via Composer
If you do not have [Composer](http://getcomposer.org/), you may install it by following the instructions
at [getcomposer.org](http://getcomposer.org/doc/00-intro.md#installation-nix).
You can then install this project template using the following command:
~~~
php composer.phar global require "fxp/composer-asset-plugin:~1.0.0"
php composer.phar create-project --prefer-dist Deele/experimental-irc-like-chat experimental-irc-like-chat
~~~
Now you should be able to access the application through the following URL, assuming `experimental-irc-like-chat` is the directory
directly under the Web root.
~~~
http://localhost/experimental-irc-like-chat/web/
~~~ | Deele/experimental-irc-like-chat | README.md | Markdown | gpl-2.0 | 1,732 |
#include "Input.h"
#include "Core.h"
#include "Memory.h"
#include "Cpu.h"
//Gameboy keys:
//[Up][Left][Right][Down][A][B][Start][Select]
//Mapped to standard keyboard keys:
//[Up][Left][Right][Down][Z][X][Enter][RShift]
//Mapped to standard Xbox controller buttons:
//[Up][Left][Right][Down][A][X][Start][Select]
// or
// [B]
Input::Input(QObject *parent, Memory& memory, Cpu& cpu)
: QObject(parent), memory(memory), cpu(cpu)
{
QObject::connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent,
this, &Input::gamepadButtonPressed);
QObject::connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent,
this, &Input::gamepadButtonReleased);
}
void Input::gamepadButtonPressed(int id, QGamepadManager::GamepadButton button, double value) {
switch(button) {
case QGamepadManager::ButtonA:
padA = true;
break;
case QGamepadManager::ButtonB:
case QGamepadManager::ButtonX:
padB = true;
break;
case QGamepadManager::ButtonStart:
padStart = true;
break;
case QGamepadManager::ButtonSelect:
padSelect = false;
break;
case QGamepadManager::ButtonLeft:
padLeft = true;
break;
case QGamepadManager::ButtonRight:
padRight = true;
break;
case QGamepadManager::ButtonUp:
padUp = true;
break;
case QGamepadManager::ButtonDown:
padDown = true;
break;
}
}
void Input::gamepadButtonReleased(int id, QGamepadManager::GamepadButton button) {
switch(button) {
case QGamepadManager::ButtonA:
padA = false;
break;
case QGamepadManager::ButtonB:
case QGamepadManager::ButtonX:
padB = false;
break;
case QGamepadManager::ButtonStart:
padStart = false;
break;
case QGamepadManager::ButtonSelect:
padSelect = false;
break;
case QGamepadManager::ButtonLeft:
padLeft = false;
break;
case QGamepadManager::ButtonRight:
padRight = false;
break;
case QGamepadManager::ButtonUp:
padUp = false;
break;
case QGamepadManager::ButtonDown:
padDown = false;
break;
}
}
Input::~Input() {
QObject::disconnect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent,
this, &Input::gamepadButtonPressed);
QObject::disconnect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent,
this, &Input::gamepadButtonReleased);
}
unsigned char Input::getKeyInput()
{
return memory.readMemory(0xFF00);
}
bool Input::isAnyKeyPressed()
{
return keyUp || keyDown || keyLeft || keyRight || keyStart || keySelect || keyA || keyB ||
padUp || padDown || padLeft || padRight || padStart || padSelect || padA || padB;
}
void Input::readInput()
{
unsigned char keyInput = getKeyInput();
bool interrupt = false;
cpu.setStop(false);
if (((keyInput & 0x10) >> 4) == 1)
{
if (keyA || padA) { //Z //A
keyInput &= 0xFE;
interrupt = true;
}
else
{
keyInput |= 0x01;
}
if (keyB || padB) { //X //B
keyInput &= 0xFD;
interrupt = true;
}
else
{
keyInput |= 0x02;
}
if (keySelect || padSelect) { //Control //Select
keyInput &= 0xFB;
interrupt = true;
}
else
{
keyInput |= 0x04;
}
if (keyStart || padStart) { //Enter //Start
keyInput &= 0xF7;
interrupt = true;
}
else
{
keyInput |= 0x08;
}
}
else if (((keyInput & 0x20) >> 5) == 1)//(keyInput == 0x20)
{
if (!((keyRight || padRight) && (keyLeft || padLeft))) //Detect if both inputs are NOT enabled at once
{
if (keyRight || padRight)
{
keyInput &= 0xFE;
interrupt = true;
}
else
{
keyInput |= 0x01;
}
if (keyLeft || padLeft)
{
keyInput &= 0xFD;
interrupt = true;
}
else
{
keyInput |= 0x02;
}
}
else //To solve issue of multiple key input on one axis we will ignore input when both left and right are pressed at the same time.
{
keyInput |= 0x01;
keyInput |= 0x02;
}
if (!((keyUp || padUp) && (keyDown || padDown))) //Detect if both inputs are NOT enabled at once
{
if (keyUp || padUp)
{
keyInput &= 0xFB;
interrupt = true;
}
else
{
keyInput |= 0x04;
}
if (keyDown || padDown)
{
keyInput &= 0xF7;
interrupt = true;
}
else
{
keyInput |= 0x08;
}
}
else //To solve issue of multiple key input on one axis we will ignore input when both left and right are pressed at the same time.
{
keyInput |= 0x04;
keyInput |= 0x08;
}
}
else
{
keyInput |= 0x01;
keyInput |= 0x02;
keyInput |= 0x04;
keyInput |= 0x08;
}
//Bit 7 and 6 are always 1
keyInput |= 0x80; //Bit 7
keyInput |= 0x40; //Bit 6
if (interrupt)
{
memory.writeMemory(0xFF0F, (unsigned char)(memory.readMemory(0xFF0F) | 0x10));
}
memory.writeMemory(0xFF00, keyInput);
}
void Input::setKeyInput(int keyCode, bool enabled)
{
cpu.setStop(false);
switch (keyCode)
{
case 0:
{
keyUp = enabled;
break;
}
case 1:
{
keyDown = enabled;
break;
}
case 2:
{
keyLeft = enabled;
break;
}
case 3:
{
keyRight = enabled;
break;
}
case 4:
{
keyStart = enabled;
break;
}
case 5:
{
keySelect = enabled;
break;
}
case 6:
{
keyA = enabled;
break;
}
case 7:
{
keyB = enabled;
break;
}
}
}
bool Input::eventFilter(QObject *obj, QEvent *event) {
bool keyPressed = event->type() == QEvent::KeyPress;
bool keyReleased = event->type() == QEvent::KeyRelease;
if (keyPressed || keyReleased) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
int key = keyEvent->key();
if (key == Qt::Key_Z) {
setKeyInput(6, keyPressed);
}
if (key == Qt::Key_X) {
setKeyInput(7, keyPressed);
}
if (key == Qt::Key_Return) {
setKeyInput(4, keyPressed);
}
if (key == Qt::Key_Shift) {
setKeyInput(5, keyPressed);
}
if (key == Qt::Key_Right) {
setKeyInput(3, keyPressed);
}
if (key == Qt::Key_Left) {
setKeyInput(2, keyPressed);
}
if (key == Qt::Key_Up) {
setKeyInput(0, keyPressed);
}
if (key == Qt::Key_Down) {
setKeyInput(1, keyPressed);
}
if (key == Qt::Key_F1 && keyReleased) {
memory.createSaveFile(true);
}
}
return QObject::eventFilter(obj, event);
}
void Input::resetInput() {
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = false;
keySelect = false;
keyStart = false;
keyA = false;
keyB = false;
padRight = false;
padLeft = false;
padUp = false;
padDown = false;
padSelect = false;
padStart = false;
padA = false;
padB = false;
}
| Daniel-McCarthy/GameBeak | GameBeak/src/Input.cpp | C++ | gpl-2.0 | 8,311 |
{% spaceless %}
{% load django_tables2 %}
{% load i18n %}
{% if table.page %}
<div class="table-container">
{% endif %}
{% block table %}
<table {% if table.attrs %} {{ table.attrs.as_html }}{% endif %}>
{% block table.thead %}
<thead>
<tr>
{% for column in table.columns %}
{% if column.orderable %}
<th {{ column.attrs.th.as_html }}><a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a></th>
{% else %}
<th {{ column.attrs.th.as_html }}>{{ column.header }}</th>
{% endif %}
{% endfor %}
</tr>
</thead>
{% endblock table.thead %}
{% block table.tbody %}
<tbody>
{% for row in table.page.object_list|default:table.rows %} {# support pagination #}
{% block table.tbody.row %}
<tr class="{{ forloop.counter|divisibleby:2|yesno:"even,odd" }} {{row.style}}"> {# avoid cycle for Django 1.2-1.6 compatibility #}
{% for column, cell in row.items %}
<td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
{% endfor %}
</tr>
{% endblock table.tbody.row %}
{% empty %}
{% if table.empty_text %}
{% block table.tbody.empty_text %}
<tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
{% endblock table.tbody.empty_text %}
{% endif %}
{% endfor %}
</tbody>
{% endblock table.tbody %}
{% block table.tfoot %}
<tfoot></tfoot>
{% endblock table.tfoot %}
</table>
{% endblock table %}
{% if table.page %}
{% with table.page.paginator.count as total %}
{% with table.page.object_list|length as count %}
{% comment %}
{% block pagination %}
<ul class="pagination">
<li><a href="{% querystring table.prefixed_page_field=1 %}">«</a></li>
{% if table.page.has_previous %}
{% nospaceless %}{% block pagination.previous %}<li class="previous"><a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}">‹</li>{% endblock pagination.previous %}{% endnospaceless %}
{% endif %}
{% if table.page.has_previous or table.page.has_next %}
{% nospaceless %}{% block pagination.current %}<li class="active">{% blocktrans with table.page.number as current and table.paginator.num_pages as total %}Page {{ current }} of {{ total }}{% endblocktrans %}</li>{% endblock pagination.current %}{% endnospaceless %}
{% endif %}
{% nospaceless %}{% block pagination.cardinality %}<li class="cardinality">{% if total != count %}{% blocktrans %}{{ count }} of {{ total }}{% endblocktrans %}{% else %}{{ total }}{% endif %} {% if total == 1 %}{{ table.data.verbose_name }}{% else %}{{ table.data.verbose_name_plural }}{% endif %}</li>{% endblock pagination.cardinality %}{% endnospaceless %}
{% if table.page.has_next %}
{% nospaceless %}{% block pagination.next %}<li class="next"><a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}">›</a></li>{% endblock pagination.next %}{% endnospaceless %}
{% endif %}
<li><a href="{% querystring table.prefixed_page_field=table.page.paginator.num_pages %}">»</a></li>
</ul>
{% endblock pagination %}
{% endcomment %}
{% endwith %}
{% endwith %}
</div>
{% endif %}
{% endspaceless %}
| maglab/naked-mole-rat-portal | genomeportal/templates/custom_table.html | HTML | gpl-2.0 | 3,496 |
<?php
/**
* Interactive image shortcode template
*/
?>
<div class="mkd-interactive-image <?php echo esc_attr($classes)?>">
<?php if($params['link'] != '') { ?>
<a href="<?php echo esc_url($params['link'])?>"></a>
<?php } ?>
<?php echo wp_get_attachment_image($image,'full'); ?>
<?php if($params['add_checkmark'] == 'yes') { ?>
<div class="tick" <?php libero_mikado_inline_style($checkmark_position); ?>></div>
<?php } ?>
</div>
| peerapat-pongnipakorn/somphoblaws | wp-content/themes/libero/framework/modules/shortcodes/interactive-image/templates/interactive-image-template.php | PHP | gpl-2.0 | 443 |
/* This file is part of the KDE project
* Copyright (C) 2010 Carlos Licea <[email protected]>
*
* 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; either
* version 2 of the License, or (at your option) any later version.
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef MSOOXMLDRAWINGTABLESTYLEREADER_H
#define MSOOXMLDRAWINGTABLESTYLEREADER_H
#include <MsooXmlCommonReader.h>
#include <MsooXmlThemesReader.h>
class KOdfGenericStyles;
#include <QtGui/QPen>
#include <QtCore/QString>
/**
* The following classes deal with the table styles part, specifically
* we deal with the elements that start at the a:tblStyleLst §20.1.4.2.27,
* you can find its part definition at Table Styles Part §14.2.9
*/
namespace MSOOXML
{
class MSOOXML_EXPORT Border {
public:
Border();
~Border();
enum Side {
NoSide,
Bottom,
Left,
Right,
// TopLeftToBottomRight,
Top,
// TopRightToBottomLeft
};
Side side() const;
void setSide(Side side);
QColor color() const;
void setColor(const QColor& color);
QString odfBorderName() const;
enum Style {
None,
Solid,
Dashed,
Dotted,
DashDot,
DashDotDot
};
void setStyle(Style style);
Style style() const;
QString odfStyleName() const;
void setWidth(qreal width);
qreal width() const;
QString odfStyleProperties() const;
private:
QColor m_color;
Side m_side;
qreal m_width;
Style m_style;
};
class MSOOXML_EXPORT TableStyleProperties
{
public:
TableStyleProperties();
~TableStyleProperties();
enum Type {
NoType,
FirstRow,
FirstCol,
LastCol,
LastRow,
NeCell,
NwCell,
SeCell,
SwCell,
Band1Horizontal,
Band2Horizontal,
Band1Vertical,
Band2Vertical,
WholeTbl
};
Type type() const;
void setType(Type type);
Border borderForSide(Border::Side side) const;
void addBorder(Border border);
/**
* @brief Save the style, note that the type of the style depends on the type
* of this styleProperties
* @return the name of the saved style
*/
QString saveStyle(KOdfGenericStyles& styles);
static Type typeFromString(const QString& string);
static QString stringFromType(Type type);
private:
//TODO see if we can take care of InsideH InsideV and how
QMap<Border::Side, Border> m_borders;
Type m_type;
};
class MSOOXML_EXPORT TableStyle
{
public:
TableStyle();
~TableStyle();
QString id() const;
void setId(const QString& id);
TableStyleProperties propertiesForType(TableStyleProperties::Type type) const;
void addProperties(TableStyleProperties properties);
private:
QString m_id;
//TODO handle the table background stored in the element TblBg
QMap<TableStyleProperties::Type, TableStyleProperties> m_properties;
};
class MSOOXML_EXPORT TableStyleList
{
public:
TableStyleList();
~TableStyleList();
TableStyle tableStyle(const QString& id) const;
void insertStyle(QString id, MSOOXML::TableStyle style);
private:
QMap<QString, TableStyle> m_styles;
};
class MsooXmlImport;
class MSOOXML_EXPORT MsooXmlDrawingTableStyleContext : public MSOOXML::MsooXmlReaderContext
{
public:
MsooXmlDrawingTableStyleContext(MSOOXML::MsooXmlImport* _import, const QString& _path, const QString& _file, MSOOXML::DrawingMLTheme* _themes, MSOOXML::TableStyleList* _styleList);
virtual ~MsooXmlDrawingTableStyleContext();
TableStyleList* styleList;
//Those members are used by some methods included
MsooXmlImport* import;
QString path;
QString file;
MSOOXML::DrawingMLTheme* themes;
};
class MSOOXML_EXPORT MsooXmlDrawingTableStyleReader : public MsooXmlCommonReader
{
public:
MsooXmlDrawingTableStyleReader(KoOdfWriters* writers);
virtual ~MsooXmlDrawingTableStyleReader();
virtual KoFilter::ConversionStatus read(MsooXmlReaderContext* context = 0);
protected:
KoFilter::ConversionStatus read_tblStyleLst();
KoFilter::ConversionStatus read_tblStyle();
KoFilter::ConversionStatus read_wholeTbl();
KoFilter::ConversionStatus read_tcStyle();
KoFilter::ConversionStatus read_tcTxStyle();
KoFilter::ConversionStatus read_bottom();
KoFilter::ConversionStatus read_left();
KoFilter::ConversionStatus read_right();
KoFilter::ConversionStatus read_top();
// KoFilter::ConversionStatus read_insideV();
// KoFilter::ConversionStatus read_insideH();
// KoFilter::ConversionStatus read_tl2br();
// KoFilter::ConversionStatus read_tr2bl();
KoFilter::ConversionStatus read_tcBdr();
//get read_ln and friends, it's a shame I have to get a lot of crap alongside
#include <MsooXmlCommonReaderMethods.h>
#include <MsooXmlCommonReaderDrawingMLMethods.h>
private:
MsooXmlDrawingTableStyleContext* m_context;
TableStyleProperties m_currentStyleProperties;
TableStyle m_currentStyle;
};
}
#endif // MSOOXMLDRAWINGTABLESTYLEREADER_H
| KDE/koffice | filters/libmsooxml/MsooXmlDrawingTableStyleReader.h | C | gpl-2.0 | 5,705 |
/* This file is part of the KDE project
* Copyright (C) 2009 Elvis Stansvik <[email protected]>
*
* 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; either
* version 2 of the License, or (at your option) any later version.
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef KTABLEFORMAT_H
#define KTABLEFORMAT_H
#include "kodftext_export.h"
#include <QSharedDataPointer>
#include <QMap>
class KTableFormatPrivate;
class QVariant;
class QString;
class QBrush;
/**
* The KTableFormat class describes a format for a table component such
* as a row or a column. It is the base class for KoTableColumnFormat and
* KoTableRowFormat.
*
* It is not a style, but a format. Very much like the implicitly shared
* QTextFormat in Qt.
*
* \sa KoTableColumnFormat, KoTableRowFormat
*/
class KODFTEXT_EXPORT KTableFormat
{
public:
/// Creates a new format of type \c InvalidFormat.
KTableFormat();
/// Creates a format with the same attributes as \a rhs.
KTableFormat(const KTableFormat &rhs);
/// Assigns \a rhs to this format and returns a reference to this format.
KTableFormat& operator=(const KTableFormat &rhs);
/// Destroys this format.
~KTableFormat();
/// Get property \a propertyId as a QVariant.
QVariant property(int propertyId) const;
/// Set property \a propertyId to \a value.
void setProperty(int propertyId, const QVariant &value);
/// Clear property \a propertyId.
void clearProperty(int propertyId);
/// Returns true if this format has property \a propertyId, otherwise false.
bool hasProperty(int propertyId) const;
/// Returns a map with all properties of this format.
QMap<int, QVariant> properties() const;
/// Get bool property \a propertyId.
bool boolProperty(int propertyId) const;
/// Get int property \a propertyId.
int intProperty(int propertyId) const;
/// Get double property \a propertyId.
qreal doubleProperty(int propertyId) const;
/// Get string property \a propertyId.
QString stringProperty(int propertyId) const;
/// Get brush property \a propertyId.
QBrush brushProperty(int propertyId) const;
private:
QSharedDataPointer<KTableFormatPrivate> d; // Shared data pointer.
};
#endif // KOTABLEFORMAT_H
| KDE/koffice | libs/kotext/styles/KTableFormat.h | C | gpl-2.0 | 2,868 |
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
/*
* 1 Header File Including
*/
#include <linux/module.h>
#include <linux/netdevice.h>
#include "hwifi_tps.h"
#include "cfg80211_stru.h"
#include "hwifi_cfg80211.h"
#include "hwifi_wpa_ioctl.h" /* for wl_pwrm_set */
#include "hwifi_wl_config_ioctl.h"
#include <net/cfg80211.h> /* wdev_priv */
#include <linux/etherdevice.h> /* eth_type_trans */
#include "hwifi_utils.h"
#include "hwifi_hcc.h"
#include "hwifi_netdev.h"
#include "hwifi_cfgapi.h"
/*
* 2 Global Variable Definition
*/
/*
* 3 Function Definition
*/
/*****************************************************************************
º¯ Êý Ãû : hwifi_test_freq_set
¹¦ÄÜÃèÊö : ÉèÖÃwifiƵ¶Î
ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_test_freq_set(struct cfg_struct *cfg, int32 freq)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *wid_freq;
uint16 msg_size;
int32 ret;
if(IS_CONNECTED(cfg))
{
HWIFI_WARNING("Current connected status not support wifreq param setting.");
return -EFAIL;
}
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
wid_freq = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(wid_freq, WID_PRIMARY_CHANNEL , freq);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("Failed to send wifi freq set msg!");
return -EFAIL;
}
cfg->ap_info.curr_channel=freq;
HWIFI_DEBUG("Succeed to set wifreq: %d", freq);
return SUCC;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_test_userpow_set
¹¦ÄÜÃèÊö : ÉèÖÃWIFI¹¦ÂÊ
ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_test_userpow_set(struct cfg_struct *cfg, int32 userpow)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *wid_userpow;
uint16 msg_size;
int32 ret;
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
wid_userpow = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(wid_userpow, WID_USER_CONTROL_ON_TX_POWER , (uint8)userpow);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("Failed to send wifi userpow set msg!");
return -EFAIL;
}
cfg->hi110x_dev->tps->userpow=userpow;
HWIFI_DEBUG("succeed to set wiuserpow: %d", userpow);
return SUCC;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_test_userpow_get
¹¦ÄÜÃèÊö : »ñÈ¡WIFI¹¦ÂÊ
ÊäÈë²ÎÊý : struct cfg_struct *cfg
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWS160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_test_userpow_get(struct cfg_struct *cfg)
{
return cfg->hi110x_dev->tps->userpow;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_test_pow_set
¹¦ÄÜÃèÊö : É趨WIFIÖ¸¶¨¹¦ÂÊ·¢ËÍ
ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_test_pow_set(struct cfg_struct *cfg, int32 pow)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *wid_pow;
uint16 msg_size;
int32 ret;
int32 n_channels_2G = 1;
int32 n_channels_5G = 0;
if (HWIFI_CONNECTED == cfg->conn.status)
{
if (cfg->conn.bss.freq <= HWIFI_AT_TEST_MAX_FREQ_2G)
{
HWIFI_INFO("scan: 2.4G connected scan, only scan 2.4G");
n_channels_5G = 0;
n_channels_2G = 1;
}
else
{
HWIFI_INFO("scan: 5G connected scan, only scan 5G");
n_channels_5G = 1;
n_channels_2G = 0;
}
}
else if(IS_AP(cfg))
{
if(cfg->ap_info.channel_info & HWIFI_AT_TEST_5G_BAND)
{
HWIFI_INFO("ap operation on 5G, only scan 5G");
n_channels_5G = 1;
n_channels_2G = 0;
}
else
{
HWIFI_INFO("ap operation on 2.4G, only scan 2.4G");
n_channels_5G = 0;
n_channels_2G = 1;
}
}
if(n_channels_5G > 0)
{
if(pow > 180 || pow <0)
{
HWIFI_WARNING("can not set the pow value %d",pow);
return -EFAIL;
}
}
else if(n_channels_2G > 0)
{
if(pow > 200 || pow <0)
{
HWIFI_WARNING("can not set the pow value %d",pow);
return -EFAIL;
}
}
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
wid_pow = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(wid_pow, WID_CURRENT_TX_POW , (uint16)pow);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("fail to send wifi pow set msg");
return -EFAIL;
}
cfg->hi110x_dev->tps->pow=pow;
HWIFI_INFO("succeed to send wifi pow set msg %d",pow);
return SUCC;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_test_pow_get
¹¦ÄÜÃèÊö : »ñÈ¡WIFIÖ¸¶¨¹¦ÂÊ
ÊäÈë²ÎÊý :struct cfg_struct *cfg
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_test_pow_get(struct cfg_struct *cfg)
{
return cfg->hi110x_dev->tps->pow;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_oltpc_active_set
¹¦ÄÜÃèÊö : ÉèÖÃWiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁȡָÁî
ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_oltpc_active_set(struct cfg_struct *cfg, int32 enabled)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *wid_oltpc;
uint16 msg_size;
int32 ret;
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
wid_oltpc = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(wid_oltpc, WID_OLTPC_ACTIVE , (uint8)enabled);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("fail to send wifi oltpc active set msg");
return -EFAIL;
}
cfg->hi110x_dev->tps->oltpc_active=enabled;
HWIFI_DEBUG("succeed to send wifi oltpc active set msg");
return SUCC;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_oltpc_active_get
¹¦ÄÜÃèÊö : »ñÈ¡WiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁȡָÁî
ÊäÈë²ÎÊý :struct cfg_struct *cfg
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_oltpc_active_get(struct cfg_struct *cfg)
{
return cfg->hi110x_dev->tps->oltpc_active;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_oltpc_switch_set
¹¦ÄÜÃèÊö : ÉèÖÃWiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁȡָÁî
ÊäÈë²ÎÊý : struct cfg_struct *cfg, uint8 enabled
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_oltpc_switch_set(struct cfg_struct *cfg, int32 enabled)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *wid_oltpc;
uint16 msg_size;
int32 ret;
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
wid_oltpc = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(wid_oltpc, WID_OLTPC_SWITCH , (uint8)enabled);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("Failed to send wifi olptc active set msg!");
return -EFAIL;
}
cfg->hi110x_dev->tps->oltpc_switch=enabled;
HWIFI_DEBUG("succeed to send wifi oltpc switch set msg");
return SUCC;
}
/*****************************************************************************
º¯ Êý Ãû : hwifi_oltpc_switch_get
¹¦ÄÜÃèÊö : »ñÈ¡WiFi µ±Ç°µÄ¹¦Âʵ÷ÕûÐÅÏ¢¶ÁȡָÁî
ÊäÈë²ÎÊý :struct cfg_struct *cfg
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ :
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2013Äê3ÔÂ12ÈÕ
×÷ Õß : hWX160629
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
int32 hwifi_oltpc_switch_get(struct cfg_struct *cfg)
{
return cfg->hi110x_dev->tps->oltpc_switch;
}
/*
* Prototype : hwifi_test_mode_set
* Description : set burst rx/tx mode
* Input : struct cfg_struct *cfg, uint8 enabled
* Output : None
* Return Value :
* Calls :
* Called By :
*
* History :
* 1.Date : 2013/5/3
* Author : hWX160629
* Modification : Created function
*
*/
int32 hwifi_test_mode_set(struct cfg_struct *cfg, uint8 mode)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *test_mode;
uint16 msg_size;
int32 ret;
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
if(!IS_STA(cfg) && !IS_AP(cfg))
{
HWIFI_WARNING("Current status can not support burst tx/rx mode set.");
dev_kfree_skb_any(skb);
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_MODE, msg_size);
/* fill ps mode */
test_mode = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(test_mode, WID_MODE_CHANGE, mode);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("Failed to send mode set msg!");
return -EFAIL;
}
cfg->hi110x_dev->tps->mode=mode;
HWIFI_DEBUG("Succeed to set mode param :%d", mode);
return SUCC;
}
/*
* Prototype : hwifi_test_mode_get
* Description : get the setting of mode param
* Input : struct cfg_struct *cfg
* Output : None
* Return Value :
* Calls :
* Called By :
*
* History :
* 1.Date : 2013/5/3
* Author : hWX160629
* Modification : Created function
*
*/
int32 hwifi_test_mode_get(struct cfg_struct *cfg)
{
return cfg->hi110x_dev->tps->mode;
}
/*
* Prototype : hwifi_test_datarate_set
* Description : set rate
* Input : struct cfg_struct *cfg,
* uint8 enabled
* Output : None
* Return Value : int32
* Calls :
* Called By :
*
* History :
* 1.Date : 2012/2/19
* Author : hWX160629
* Modification : Created function
*
*/
int32 hwifi_test_datarate_set(struct cfg_struct *cfg, uint8 rate)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *rate_set;
uint16 msg_size;
int32 ret;
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
rate_set = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(rate_set, WID_CURRENT_TX_RATE, rate);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("fail to send rate set msg");
return -EFAIL;
}
HWIFI_INFO("succeed to send rate set msg %d",rate);
return SUCC;
}
/*
* Prototype : hwifi_band_set
* Description : enable/disable support for 40MHz operation
* Input : struct cfg_struct *cfg,uint8 enabled
* Output : None
* Return Value : int32
* Calls :
* Called By :
*
* History :
* 1.Date : 2013/4/26
* Author : hWX160629
* Modification : Created function
*
*/
int32 hwifi_band_set(struct cfg_struct *cfg,uint8 band)
{
int32 ret;
ret = hwifi_sta_2040_enable_ctrl_set(cfg,band);
if (SUCC != ret)
{
HWIFI_WARNING("Failed to send band param set msg!");
return -EFAIL;
}
HWIFI_INFO("Succeed to set band param:%d", band);
return SUCC;
}
/*
* Prototype : wifitest_protocol_gmode_set
* Description : set 11g operating mode
* Input : struct cfg_struct *cfg,uint8 enabled
* Output : None
* Return Value : int32
* Calls :
* Called By :
*
* History :
* 1.Date : 2013/4/26
* Author : hWX160629
* Modification : Created function
*
*/
int32 wifitest_protocol_gmode_set(struct cfg_struct *cfg,uint8 mode)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *gmode;
uint16 msg_size;
int32 ret;
if(IS_CONNECTED(cfg)||(IS_P2P_ON(cfg)))
{
HWIFI_WARNING("current status can not support protocol gmode set.");
return -EFAIL;
}
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill gmode */
gmode = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(gmode, WID_11G_OPERATING_MODE, mode);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("fail to send protocol gmode set msg");
return -EFAIL;
}
cfg->sta_info.gmode= mode;
HWIFI_INFO("succeed to set protocol gmode:%d", mode);
return SUCC;
}
/*
* Prototype : wifitest_protocol_nmode_set
* Description : set ht capability enabled
* Input : struct cfg_struct *cfg,uint8 enabled
* uint8 enabled
* Output : None
* Return Value : int32
* Calls :
* Called By :
*
* History :
* 1.Date : 2012/2/19
* Author : hWX160629
* Modification : Created function
*
*/
int32 wifitest_protocol_nmode_set(struct cfg_struct *cfg,uint8 mode)
{
struct sk_buff *skb;
struct hwifi_msg_header *msghdr;
struct char_wid *ht;
uint16 msg_size;
int32 ret;
if (IS_CONNECTED(cfg) || IS_AP(cfg))
{
HWIFI_WARNING("current status can not support 11n mode set.");
return -EFAIL;
}
msg_size = sizeof(struct hwifi_msg_header) + sizeof(struct char_wid);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
/* fill the msg header */
msghdr = (struct hwifi_msg_header*)skb_put(skb, sizeof(struct hwifi_msg_header));
hwifi_fill_msg_hdr(msghdr, HOST_CMD_CONFIG, msg_size);
/* fill ps mode */
ht = (struct char_wid *)skb_put(skb, sizeof(struct char_wid));
hwifi_fill_char_wid(ht, WID_11N_ENABLE, mode);
ret = hwifi_send_cmd(cfg, skb);
if (SUCC != ret)
{
HWIFI_WARNING("fail to send 11n mode set msg");
return -EFAIL;
}
HWIFI_INFO("succeed to send 11n mode set msg %d",mode);
return SUCC;
}
/*
* Prototype : hwifi_dbb_get
* Description : get dbb of wifi
* Input : struct cfg_struct *cfg
* Output : None
* Return Value : int
* Calls :
* Called By :
*
* History :
* 1.Date : 2013/11/9
* Author : hWX160629
* Modification : Created function
*
*/
int32 hwifi_dbb_get(struct cfg_struct *cfg,int8 *dbb)
{
int32 ret;
if (NULL == cfg)
{
HWIFI_WARNING("Invalid NULL cfg!");
return -EFAIL;
}
cfg->hi110x_dev->tps->dbb_ver_got = 0xFF;
ret = wl_get_dbb_info(cfg);
if(SUCC != ret)
{
HWIFI_WARNING("Failed to get DBB number!");
return -EFAIL;
}
ret = wait_event_interruptible_timeout(cfg->wait_queue, (0xFF != cfg->hi110x_dev->tps->dbb_ver_got), 5 * HZ);
if (0 == ret)
{
HWIFI_WARNING("wait for dbb version message time out(5s)!");
return -EFAIL;
}
else if (ret < 0)
{
HWIFI_WARNING("wait for dbb version message error!");
return -EFAIL;
}
strncpy(dbb,cfg->hi110x_dev->tps->dbb,HISI_WIFI_DBB_LEN);
HWIFI_DEBUG("DBB number is %s",cfg->hi110x_dev->tps->dbb);
return SUCC;
}
int32 hwifi_upc_get(struct cfg_struct *cfg)
{
int32 ret;
if (NULL == cfg)
{
HWIFI_WARNING("Invalid NULL cfg!");
return -EFAIL;
}
cfg->hi110x_dev->tps->check_upc_ctrl = -EFAIL;
ret = wl_get_upc_info(cfg);
if(SUCC != ret)
{
HWIFI_WARNING("Failed to get upc!");
return -EFAIL;
}
ret = wait_event_interruptible_timeout(cfg->wait_queue, (-EFAIL != cfg->hi110x_dev->tps->check_upc_ctrl), 5 * HZ);
if (0 == ret)
{
HWIFI_WARNING("wait for upc info message time out(5s)!");
return -EFAIL;
}
else if (ret < 0)
{
HWIFI_WARNING("wait for upc info message error!");
return -EFAIL;
}
HWIFI_DEBUG("report upc info is %d",cfg->hi110x_dev->tps->check_upc_flag);
return cfg->hi110x_dev->tps->check_upc_flag;
}
int32 hwifi_gen_cw_single_tone_set(struct cfg_struct *cfg)
{
int32 ret;
uint16 msg_size;
struct sk_buff *skb;
struct hwifi_gen_cw_single_tone_msg *msg;
HWIFI_ASSERT((NULL != cfg));
msg_size = sizeof(struct hwifi_gen_cw_single_tone_msg);
skb = hwifi_alloc_skb_for_cmd(msg_size);
if (NULL == skb)
{
return -EFAIL;
}
msg = (struct hwifi_gen_cw_single_tone_msg *)skb_put(skb, msg_size);
/* set the msg header */
hwifi_fill_msg_hdr(&msg->msg_hdr, HOST_CMD_CONFIG, msg_size);
hwifi_fill_char_wid(&msg->phy_active_reg_1, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_1);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_1, WID_11N_PHY_ACTIVE_REG_VAL, WID_SIGNAL_TONE_ACTIVE_REG_VAL_1);
hwifi_fill_char_wid(&msg->phy_active_reg_2, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_2);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_2,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_2);
hwifi_fill_char_wid(&msg->phy_active_reg_3, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_3);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_3,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_3);
hwifi_fill_char_wid(&msg->phy_active_reg_4, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_4);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_4,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_4);
hwifi_fill_char_wid(&msg->phy_active_reg_5, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_5);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_5,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_5);
hwifi_fill_char_wid(&msg->phy_active_reg_6, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_6);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_6,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_6);
hwifi_fill_char_wid(&msg->phy_active_reg_7, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_7);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_7,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_7);
hwifi_fill_char_wid(&msg->phy_active_reg_8, WID_PHY_ACTIVE_REG, WID_SIGNAL_TONE_PHY_ACTIVE_REG_8);
hwifi_fill_int_wid(&msg->hw_11n_phy_active_reg_val_8,WID_11N_PHY_ACTIVE_REG_VAL,WID_SIGNAL_TONE_ACTIVE_REG_VAL_8);
hwifi_fill_int_wid(&msg->rf_reg_info, WID_RF_REG_VAL, WID_SIGNAL_TONE_RF_REG_INFO);
ret = hwifi_send_cmd(cfg, skb);
PRINT_SEND_CMD_RET("connect status,gen_cw_single_tone param set success", ret);
return ret;
}
int32 hwifi_tps_ioctl_cmd(struct hi110x_device* hi110x_dev, struct ifreq *ifr, int32 cmd)
{
wifi_ioctl_test_data_struct ioctl_data;
int32 ret = SUCC;
if ((NULL == hi110x_dev) || (NULL == ifr) || (NULL == ifr->ifr_data))
{
HWIFI_WARNING("Invalid NULL params!");
return -EFAIL;
}
HWIFI_PRINT_ONCE(INFO, "sizeof wifi_ioctl_test_data_struct is %zu", sizeof(wifi_ioctl_test_data_struct));
if(copy_from_user(&ioctl_data,ifr->ifr_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ifr->ifr_data from user!");
return -EFAIL;
}
if(ioctl_data.verify != VERIFY_CODE)
{
HWIFI_WARNING("ioctl verify failed,verify code is:%d(not equal %d)", ioctl_data.verify, VERIFY_CODE);
return -EFAIL;
}
switch(ioctl_data.cmd)
{
case HWIFI_IOCTL_CMD_WI_FREQ_SET:
ret = hwifi_test_freq_set(hi110x_dev->cfg,ioctl_data.pri_data.freq);
break;
case HWIFI_IOCTL_CMD_WI_USERPOW_SET:
ret = hwifi_test_userpow_set(hi110x_dev->cfg,ioctl_data.pri_data.userpow);
break;
case HWIFI_IOCTL_CMD_WI_USERPOW_GET:
ioctl_data.pri_data.userpow = hwifi_test_userpow_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_CMD_WI_POWER_SET:
ret = hwifi_test_pow_set(hi110x_dev->cfg,ioctl_data.pri_data.pow);
break;
case HWIFI_IOCTL_CMD_WI_POWER_GET:
ioctl_data.pri_data.pow = hwifi_test_pow_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_OLTPC_ACTIVE_SET:
ret = hwifi_oltpc_active_set(hi110x_dev->cfg,ioctl_data.pri_data.oltpc_active);
break;
case HWIFI_IOCTL_OLTPC_SWITCH_SET:
ret = hwifi_oltpc_switch_set(hi110x_dev->cfg,ioctl_data.pri_data.oltpc_switch);
break;
case HWIFI_IOCTL_OLTPC_ACTIVE_GET:
ioctl_data.pri_data.oltpc_active=hwifi_oltpc_active_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_OLTPC_SWITCH_GET:
ioctl_data.pri_data.oltpc_switch=hwifi_oltpc_switch_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("copy_to_user failed");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_CMD_MODE_SET:
ret = hwifi_test_mode_set(hi110x_dev->cfg,ioctl_data.pri_data.mode);
break;
case HWIFI_IOCTL_CMD_MODE_GET:
ioctl_data.pri_data.mode=hwifi_test_mode_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_CMD_DATARATE_SET:
ret = hwifi_test_datarate_set(hi110x_dev->cfg,(uint8)ioctl_data.pri_data.datarate);
break;
case HWIFI_IOCTL_CMD_BAND_SET:
ret = hwifi_band_set(hi110x_dev->cfg,ioctl_data.pri_data.band);
break;
case HWIFI_IOCTL_CMD_PROTOCOL_GMODE_SET:
ret = wifitest_protocol_gmode_set(hi110x_dev->cfg,ioctl_data.pri_data.protocol_gmode);
break;
case HWIFI_IOCTL_CMD_PROTOCOL_NMODE_SET:
ret = wifitest_protocol_nmode_set(hi110x_dev->cfg,ioctl_data.pri_data.protocol_nmode);
break;
case HWIFI_IOCTL_CMD_DBB_GET:
ret = hwifi_dbb_get(hi110x_dev->cfg,ioctl_data.pri_data.dbb);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_CMD_UPC_GET:
ioctl_data.pri_data.check_upc_flag = hwifi_upc_get(hi110x_dev->cfg);
if(copy_to_user(ifr->ifr_data,&ioctl_data,sizeof(wifi_ioctl_test_data_struct)))
{
HWIFI_WARNING("Failed to copy ioctl_data to user !");
ret = -EFAIL;
}
break;
case HWIFI_IOCTL_CMD_GEN_CW_SINGLE_TONE_SET:
ret = hwifi_gen_cw_single_tone_set(hi110x_dev->cfg);
break;
default:
HWIFI_WARNING("Invalid not support ioctl_data.cmd(%d)",ioctl_data.cmd);
ret = -EFAIL;
break;
}
return ret;
}
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
| gabry3795/android_kernel_huawei_mt7_l09 | drivers/huawei_platform/connectivity/hisi/hisiwifi/hwifi_tps.c | C | gpl-2.0 | 28,729 |
from models import Connection
from django import forms
class ConnectionForm(forms.ModelForm):
class Meta:
model = Connection
exclude = ('d_object_id',)
| CIGNo-project/CIGNo | cigno/mdtools/forms.py | Python | gpl-3.0 | 173 |
# pedalo | scandaglio/pedalo | README.md | Markdown | gpl-3.0 | 8 |
// created on 13/12/2002 at 22:07
using System;
namespace xServer.Core.NAudio.Mixer
{
/// <summary>
/// Custom Mixer control
/// </summary>
public class CustomMixerControl : MixerControl
{
internal CustomMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
{
this.mixerControl = mixerControl;
this.mixerHandle = mixerHandle;
this.mixerHandleType = mixerHandleType;
this.nChannels = nChannels;
this.mixerControlDetails = new MixerInterop.MIXERCONTROLDETAILS();
GetControlDetails();
}
/// <summary>
/// Get the data for this custom control
/// </summary>
/// <param name="pDetails">pointer to memory to receive data</param>
protected override void GetDetails(IntPtr pDetails)
{
}
// TODO: provide a way of getting / setting data
}
}
| mirkoBastianini/Quasar-RAT | Server/Core/NAudio/Mixer/CustomMixerControl.cs | C# | gpl-3.0 | 873 |
package org.mivotocuenta.client.service;
import org.mivotocuenta.server.beans.Conteo;
import org.mivotocuenta.shared.UnknownException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("servicegestionconteo")
public interface ServiceGestionConteo extends RemoteService {
Boolean insertarVoto(Conteo bean) throws UnknownException;
}
| jofrantoba/mivotocuenta | src/org/mivotocuenta/client/service/ServiceGestionConteo.java | Java | gpl-3.0 | 431 |
<div class="tablist-content">I am ajax tab content i was pulled in from ajax-content.html </div>
| gitubo/watchnwater | www/js/demos/tabs/ajax-content.html | HTML | gpl-3.0 | 98 |
# -*- coding: utf-8 -*-
# pylint: disable=too-many-lines,too-complex,too-many-branches
# pylint: disable=too-many-statements,arguments-differ
# needs refactoring, but I don't have the energy for anything
# more than a superficial cleanup.
#-------------------------------------------------------------------------------
# Name: midi/__init__.py
# Purpose: Access to MIDI library / music21 classes for dealing with midi data
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
# (Will Ware -- see docs)
#
# Copyright: Copyright © 2011-2013 Michael Scott Cuthbert and the music21 Project
# Some parts of this module are in the Public Domain, see details.
# License: LGPL or BSD, see license.txt
#-------------------------------------------------------------------------------
'''
Objects and tools for processing MIDI data. Converts from MIDI files to
:class:`~MidiEvent`, :class:`~MidiTrack`, and
:class:`~MidiFile` objects, and vice-versa.
This module uses routines from Will Ware's public domain midi.py library from 2001
see http://groups.google.com/group/alt.sources/msg/0c5fc523e050c35e
'''
import struct
import sys
import unicodedata # @UnresolvedImport
# good midi reference:
# http://www.sonicspot.com/guide/midifiles.html
def is_num(usr_data):
'''
check if usr_data is a number (float, int, long, Decimal),
return boolean
unlike `isinstance(usr_data, Number)` does not return True for `True, False`.
Does not use `isinstance(usr_data, Number)` which is 6 times slower
than calling this function (except in the case of Fraction, when
it's 6 times faster, but that's rarer)
Runs by adding 0 to the "number" -- so anything that implements
add to a scalar works
>>> is_num(3.0)
True
>>> is_num(3)
True
>>> is_num('three')
False
>>> is_num([2, 3, 4])
False
True and False are NOT numbers:
>>> is_num(True)
False
>>> is_num(False)
False
>>> is_num(None)
False
:rtype: bool
'''
try:
dummy = usr_data + 0
# pylint: disable=simplifiable-if-statement
if usr_data is not True and usr_data is not False:
return True
else:
return False
except Exception: # pylint: disable=broad-except
return False
# pylint: disable=missing-docstring
#-------------------------------------------------------------------------------
class EnumerationException(Exception):
pass
class MidiException(Exception):
pass
#-------------------------------------------------------------------------------
def char_to_binary(char):
'''
Convert a char into its binary representation. Useful for debugging.
>>> char_to_binary('a')
'01100001'
'''
ascii_value = ord(char)
binary_digits = []
while ascii_value > 0:
if (ascii_value & 1) == 1:
binary_digits.append("1")
else:
binary_digits.append("0")
ascii_value = ascii_value >> 1
binary_digits.reverse()
binary = ''.join(binary_digits)
zerofix = (8 - len(binary)) * '0'
return zerofix + binary
def ints_to_hex_string(int_list):
'''
Convert a list of integers into a hex string, suitable for testing MIDI encoding.
>>> # note on, middle c, 120 velocity
>>> ints_to_hex_string([144, 60, 120])
b'\\x90<x'
'''
# note off are 128 to 143
# note on messages are decimal 144 to 159
post = b''
for i in int_list:
# B is an unsigned char
# this forces values between 0 and 255
# the same as chr(int)
post += struct.pack(">B", i)
return post
def get_number(midi_str, length):
'''
Return the value of a string byte or bytes if length > 1
from an 8-bit string or (PY3) bytes object
Then, return the remaining string or bytes object
The `length` is the number of chars to read.
This will sum a length greater than 1 if desired.
Note that MIDI uses big-endian for everything.
This is the inverse of Python's chr() function.
>>> get_number('test', 0)
(0, 'test')
>>> get_number('test', 2)
(29797, 'st')
>>> get_number('test', 4)
(1952805748, '')
'''
summation = 0
if not is_num(midi_str):
for i in range(length):
midi_str_or_num = midi_str[i]
if is_num(midi_str_or_num):
summation = (summation << 8) + midi_str_or_num
else:
summation = (summation << 8) + ord(midi_str_or_num)
return summation, midi_str[length:]
else:
mid_num = midi_str
summation = mid_num - ((mid_num >> (8*length)) << (8*length))
big_bytes = mid_num - summation
return summation, big_bytes
def get_variable_length_number(midi_str):
r'''
Given a string of data, strip off a the first character, or all high-byte characters
terminating with one whose ord() function is < 0x80. Thus a variable number of bytes
might be read.
After finding the appropriate termination,
return the remaining string.
This is necessary as DeltaTime times are given with variable size,
and thus may be if different numbers of characters are used.
(The ellipses below are just to make the doctests work on both Python 2 and
Python 3 (where the output is in bytes).)
>>> get_variable_length_number('A-u')
(65, ...'-u')
>>> get_variable_length_number('-u')
(45, ...'u')
>>> get_variable_length_number('u')
(117, ...'')
>>> get_variable_length_number('test')
(116, ...'est')
>>> get_variable_length_number('E@-E')
(69, ...'@-E')
>>> get_variable_length_number('@-E')
(64, ...'-E')
>>> get_variable_length_number('-E')
(45, ...'E')
>>> get_variable_length_number('E')
(69, ...'')
Test that variable length characters work:
>>> get_variable_length_number(b'\xff\x7f')
(16383, ...'')
>>> get_variable_length_number('中xy')
(210638584, ...'y')
If no low-byte character is encoded, raises an IndexError
>>> get_variable_length_number('中国')
Traceback (most recent call last):
MidiException: did not find the end of the number!
'''
# from http://faydoc.tripod.com/formats/mid.htm
# This allows the number to be read one byte at a time, and when you see
# a msb of 0, you know that it was the last (least significant) byte of the number.
summation = 0
if isinstance(midi_str, str):
midi_str = midi_str.encode('utf-8')
for i, byte in enumerate(midi_str):
if not is_num(byte):
byte = ord(byte)
summation = (summation << 7) + (byte & 0x7F)
if not byte & 0x80:
try:
return summation, midi_str[i+1:]
except IndexError:
break
raise MidiException('did not find the end of the number!')
def get_numbers_as_list(midi_str):
'''
Translate each char into a number, return in a list.
Used for reading data messages where each byte encodes
a different discrete value.
>>> get_numbers_as_list('\\x00\\x00\\x00\\x03')
[0, 0, 0, 3]
'''
post = []
for item in midi_str:
if is_num(item):
post.append(item)
else:
post.append(ord(item))
return post
def put_number(num, length):
'''
Put a single number as a hex number at the end of a string `length` bytes long.
>>> put_number(3, 4)
b'\\x00\\x00\\x00\\x03'
>>> put_number(0, 1)
b'\\x00'
'''
lst = bytearray()
for i in range(length):
shift_bits = 8 * (length - 1 - i)
this_num = (num >> shift_bits) & 0xFF
lst.append(this_num)
return bytes(lst)
def put_variable_length_number(num):
'''
>>> put_variable_length_number(4)
b'\\x04'
>>> put_variable_length_number(127)
b'\\x7f'
>>> put_variable_length_number(0)
b'\\x00'
>>> put_variable_length_number(1024)
b'\\x88\\x00'
>>> put_variable_length_number(8192)
b'\\xc0\\x00'
>>> put_variable_length_number(16383)
b'\\xff\\x7f'
>>> put_variable_length_number(-1)
Traceback (most recent call last):
MidiException: cannot put_variable_length_number() when number is negative: -1
'''
if num < 0:
raise MidiException(
'cannot put_variable_length_number() when number is negative: %s' % num)
lst = bytearray()
while True:
result, num = num & 0x7F, num >> 7
lst.append(result + 0x80)
if num == 0:
break
lst.reverse()
lst[-1] = lst[-1] & 0x7f
return bytes(lst)
def put_numbers_as_list(num_list):
'''
Translate a list of numbers (0-255) into a bytestring.
Used for encoding data messages where each byte encodes a different discrete value.
>>> put_numbers_as_list([0, 0, 0, 3])
b'\\x00\\x00\\x00\\x03'
If a number is < 0 then it wraps around from the top.
>>> put_numbers_as_list([0, 0, 0, -3])
b'\\x00\\x00\\x00\\xfd'
>>> put_numbers_as_list([0, 0, 0, -1])
b'\\x00\\x00\\x00\\xff'
A number > 255 is an exception:
>>> put_numbers_as_list([256])
Traceback (most recent call last):
MidiException: Cannot place a number > 255 in a list: 256
'''
post = bytearray()
for num in num_list:
if num < 0:
num = num % 256 # -1 will be 255
if num >= 256:
raise MidiException("Cannot place a number > 255 in a list: %d" % num)
post.append(num)
return bytes(post)
#-------------------------------------------------------------------------------
class Enumeration(object):
'''
Utility object for defining binary MIDI message constants.
'''
def __init__(self, enum_list=None):
if enum_list is None:
enum_list = []
lookup = {}
reverse_lookup = {}
num = 0
unique_names = []
unique_values = []
for enum in enum_list:
if isinstance(enum, tuple):
enum, num = enum
if not isinstance(enum, str):
raise EnumerationException("enum name is not a string: " + enum)
if not isinstance(num, int):
raise EnumerationException("enum value is not an integer: " + num)
if enum in unique_names:
raise EnumerationException("enum name is not unique: " + enum)
if num in unique_values:
raise EnumerationException("enum value is not unique for " + enum)
unique_names.append(enum)
unique_values.append(num)
lookup[enum] = num
reverse_lookup[num] = enum
num = num + 1
self.lookup = lookup
self.reverse_lookup = reverse_lookup
def __add__(self, other):
lst = []
for k in self.lookup:
lst.append((k, self.lookup[k]))
for k in other.lookup:
lst.append((k, other.lookup[k]))
return Enumeration(lst)
def hasattr(self, attr):
if attr in self.lookup:
return True
return False
def has_value(self, attr):
if attr in self.reverse_lookup:
return True
return False
def __getattr__(self, attr):
if attr not in self.lookup:
raise AttributeError
return self.lookup[attr]
def whatis(self, value):
post = self.reverse_lookup[value]
return post
CHANNEL_VOICE_MESSAGES = Enumeration([
("NOTE_OFF", 0x80),
("NOTE_ON", 0x90),
("POLYPHONIC_KEY_PRESSURE", 0xA0),
("CONTROLLER_CHANGE", 0xB0),
("PROGRAM_CHANGE", 0xC0),
("CHANNEL_KEY_PRESSURE", 0xD0),
("PITCH_BEND", 0xE0)])
CHANNEL_MODE_MESSAGES = Enumeration([
("ALL_SOUND_OFF", 0x78),
("RESET_ALL_CONTROLLERS", 0x79),
("LOCAL_CONTROL", 0x7A),
("ALL_NOTES_OFF", 0x7B),
("OMNI_MODE_OFF", 0x7C),
("OMNI_MODE_ON", 0x7D),
("MONO_MODE_ON", 0x7E),
("POLY_MODE_ON", 0x7F)])
META_EVENTS = Enumeration([
("SEQUENCE_NUMBER", 0x00),
("TEXT_EVENT", 0x01),
("COPYRIGHT_NOTICE", 0x02),
("SEQUENCE_TRACK_NAME", 0x03),
("INSTRUMENT_NAME", 0x04),
("LYRIC", 0x05),
("MARKER", 0x06),
("CUE_POINT", 0x07),
("PROGRAM_NAME", 0x08),
# optional event is used to embed the
# patch/program name that is called up by the immediately
# subsequent Bank Select and Program Change messages.
# It serves to aid the end user in making an intelligent
# program choice when using different hardware.
("SOUND_SET_UNSUPPORTED", 0x09),
("MIDI_CHANNEL_PREFIX", 0x20),
("MIDI_PORT", 0x21),
("END_OF_TRACK", 0x2F),
("SET_TEMPO", 0x51),
("SMTPE_OFFSET", 0x54),
("TIME_SIGNATURE", 0x58),
("KEY_SIGNATURE", 0x59),
("SEQUENCER_SPECIFIC_META_EVENT", 0x7F)])
#-------------------------------------------------------------------------------
class MidiEvent(object):
'''
A model of a MIDI event, including note-on, note-off, program change,
controller change, any many others.
MidiEvent objects are paired (preceded) by :class:`~base.DeltaTime`
objects in the list of events in a MidiTrack object.
The `track` argument must be a :class:`~base.MidiTrack` object.
The `type_` attribute is a string representation of a Midi event from the CHANNEL_VOICE_MESSAGES
or META_EVENTS definitions.
The `channel` attribute is an integer channel id, from 1 to 16.
The `time` attribute is an integer duration of the event in ticks. This value
can be zero. This value is not essential, as ultimate time positioning is
determined by :class:`~base.DeltaTime` objects.
The `pitch` attribute is only defined for note-on and note-off messages.
The attribute stores an integer representation (0-127, with 60 = middle C).
The `velocity` attribute is only defined for note-on and note-off messages.
The attribute stores an integer representation (0-127). A note-on message with
velocity 0 is generally assumed to be the same as a note-off message.
The `data` attribute is used for storing other messages,
such as SEQUENCE_TRACK_NAME string values.
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> me1.type_ = "NOTE_ON"
>>> me1.channel = 3
>>> me1.time = 200
>>> me1.pitch = 60
>>> me1.velocity = 120
>>> me1
<MidiEvent NOTE_ON, t=200, track=1, channel=3, pitch=60, velocity=120>
>>> me2 = MidiEvent(mt)
>>> me2.type_ = "SEQUENCE_TRACK_NAME"
>>> me2.time = 0
>>> me2.data = 'guitar'
>>> me2
<MidiEvent SEQUENCE_TRACK_NAME, t=0, track=1, channel=None, data=b'guitar'>
'''
def __init__(self, track, type_=None, time=None, channel=None):
self.track = track
self.type_ = type_
self.time = time
self.channel = channel
self._parameter1 = None # pitch or first data value
self._parameter2 = None # velocity or second data value
# data is a property...
# if this is a Note on/off, need to store original
# pitch space value in order to determine if this is has a microtone
self.cent_shift = None
# store a reference to a corresponding event
# if a noteOn, store the note off, and vice versa
# NTODO: We should make sure that we garbage collect this -- otherwise it's a memory
# leak from a circular reference.
# note: that's what weak references are for
# unimplemented
self.corresponding_event = None
# store and pass on a running status if found
self.last_status_byte = None
self.sort_order = 0
self.update_sort_order()
def update_sort_order(self):
if self.type_ == 'PITCH_BEND':
self.sort_order = -10
if self.type_ == 'NOTE_OFF':
self.sort_order = -20
def __repr__(self):
if self.track is None:
track_index = None
else:
track_index = self.track.index
return_str = ("<MidiEvent %s, t=%s, track=%s, channel=%s" %
(self.type_, repr(self.time), track_index,
repr(self.channel)))
if self.type_ in ['NOTE_ON', 'NOTE_OFF']:
attr_list = ["pitch", "velocity"]
else:
if self._parameter2 is None:
attr_list = ['data']
else:
attr_list = ['_parameter1', '_parameter2']
for attrib in attr_list:
if getattr(self, attrib) is not None:
return_str = return_str + ", " + attrib + "=" + repr(getattr(self, attrib))
return return_str + ">"
def _set_pitch(self, value):
self._parameter1 = value
def _get_pitch(self):
if self.type_ in ['NOTE_ON', 'NOTE_OFF']:
return self._parameter1
else:
return None
pitch = property(_get_pitch, _set_pitch)
def _set_velocity(self, value):
self._parameter2 = value
def _get_velocity(self):
return self._parameter2
velocity = property(_get_velocity, _set_velocity)
def _set_data(self, value):
if value is not None and not isinstance(value, bytes):
if isinstance(value, str):
value = value.encode('utf-8')
self._parameter1 = value
def _get_data(self):
return self._parameter1
data = property(_get_data, _set_data)
def set_pitch_bend(self, cents, bend_range=2):
'''
Treat this event as a pitch bend value, and set the ._parameter1 and
._parameter2 fields appropriately given a specified bend value in cents.
The `bend_range` parameter gives the number of half steps in the bend range.
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> me1.set_pitch_bend(50)
>>> me1._parameter1, me1._parameter2
(0, 80)
>>> me1.set_pitch_bend(100)
>>> me1._parameter1, me1._parameter2
(0, 96)
>>> me1.set_pitch_bend(200)
>>> me1._parameter1, me1._parameter2
(127, 127)
>>> me1.set_pitch_bend(-50)
>>> me1._parameter1, me1._parameter2
(0, 48)
>>> me1.set_pitch_bend(-100)
>>> me1._parameter1, me1._parameter2
(0, 32)
'''
# value range is 0, 16383
# center should be 8192
cent_range = bend_range * 100
center = 8192
top_span = 16383 - center
bottom_span = center
if cents > 0:
shift_scalar = cents / float(cent_range)
shift = int(round(shift_scalar * top_span))
elif cents < 0:
shift_scalar = cents / float(cent_range) # will be negative
shift = int(round(shift_scalar * bottom_span)) # will be negative
else:
shift = 0
target = center + shift
# produce a two-char value
char_value = put_variable_length_number(target)
data1, _ = get_number(char_value[0], 1)
# need to convert from 8 bit to 7, so using & 0x7F
data1 = data1 & 0x7F
if len(char_value) > 1:
data2, _ = get_number(char_value[1], 1)
data2 = data2 & 0x7F
else:
data2 = 0
self._parameter1 = data2
self._parameter2 = data1 # data1 is msb here
def _parse_channel_voice_message(self, midi_str):
'''
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> remainder = me1._parse_channel_voice_message(ints_to_hex_string([144, 60, 120]))
>>> me1.channel
1
>>> remainder = me1._parse_channel_voice_message(ints_to_hex_string([145, 60, 120]))
>>> me1.channel
2
>>> me1.type_
'NOTE_ON'
>>> me1.pitch
60
>>> me1.velocity
120
'''
# first_byte, channel_number, and second_byte define
# characteristics of the first two chars
# for first_byte: The left nybble (4 bits) contains the actual command, and the right nibble
# contains the midi channel number on which the command will be executed.
if is_num(midi_str[0]):
first_byte = midi_str[0]
else:
first_byte = ord(midi_str[0])
channel_number = first_byte & 0xF0
if is_num(midi_str[1]):
second_byte = midi_str[1]
else:
second_byte = ord(midi_str[1])
if is_num(midi_str[2]):
third_byte = midi_str[2]
else:
third_byte = ord(midi_str[2])
self.channel = (first_byte & 0x0F) + 1
self.type_ = CHANNEL_VOICE_MESSAGES.whatis(channel_number)
if (self.type_ == "PROGRAM_CHANGE" or
self.type_ == "CHANNEL_KEY_PRESSURE"):
self.data = second_byte
return midi_str[2:]
elif self.type_ == "CONTROLLER_CHANGE":
# for now, do nothing with this data
# for a note, str[2] is velocity; here, it is the control value
self.pitch = second_byte # this is the controller id
self.velocity = third_byte # this is the controller value
return midi_str[3:]
else:
self.pitch = second_byte
self.velocity = third_byte
return midi_str[3:]
def read(self, time, midi_str):
'''
Parse the string that is given and take the beginning
section and convert it into data for this event and return the
now truncated string.
The `time` value is the number of ticks into the Track
at which this event happens. This is derived from reading
data the level of the track.
TODO: These instructions are inadequate.
>>> # all note-on messages (144-159) can be found
>>> 145 & 0xF0 # testing message type_ extraction
144
>>> 146 & 0xF0 # testing message type_ extraction
144
>>> (144 & 0x0F) + 1 # getting the channel
1
>>> (159 & 0x0F) + 1 # getting the channel
16
'''
if len(midi_str) < 2:
# often what we have here are null events:
# the string is simply: 0x00
print(
'MidiEvent.read(): got bad data string',
'time',
time,
'str',
repr(midi_str))
return ''
# first_byte, message_type, and second_byte define
# characteristics of the first two chars
# for first_byte: The left nybble (4 bits) contains the
# actual command, and the right nibble
# contains the midi channel number on which the command will
# be executed.
if is_num(midi_str[0]):
first_byte = midi_str[0]
else:
first_byte = ord(midi_str[0])
# detect running status: if the status byte is less than 128, its
# not a status byte, but a data byte
if first_byte < 128:
if self.last_status_byte is not None:
rsb = self.last_status_byte
if is_num(rsb):
rsb = bytes([rsb])
else:
rsb = bytes([0x90])
# add the running status byte to the front of the string
# and process as before
midi_str = rsb + midi_str
if is_num(midi_str[0]):
first_byte = midi_str[0]
else:
first_byte = ord(midi_str[0])
else:
self.last_status_byte = midi_str[0]
message_type = first_byte & 0xF0
if is_num(midi_str[1]):
second_byte = midi_str[1]
else:
second_byte = ord(midi_str[1])
if CHANNEL_VOICE_MESSAGES.has_value(message_type):
return self._parse_channel_voice_message(midi_str)
elif message_type == 0xB0 and CHANNEL_MODE_MESSAGES.has_value(second_byte):
self.channel = (first_byte & 0x0F) + 1
self.type_ = CHANNEL_MODE_MESSAGES.whatis(second_byte)
if self.type_ == "LOCAL_CONTROL":
self.data = (ord(midi_str[2]) == 0x7F)
elif self.type_ == "MONO_MODE_ON":
self.data = ord(midi_str[2])
else:
print('unhandled message:', midi_str[2])
return midi_str[3:]
elif first_byte == 0xF0 or first_byte == 0xF7:
self.type_ = {0xF0: "F0_SYSEX_EVENT",
0xF7: "F7_SYSEX_EVENT"}[first_byte]
length, midi_str = get_variable_length_number(midi_str[1:])
self.data = midi_str[:length]
return midi_str[length:]
# SEQUENCE_TRACK_NAME and other MetaEvents are here
elif first_byte == 0xFF:
if not META_EVENTS.has_value(second_byte):
print("unknown meta event: FF %02X" % second_byte)
sys.stdout.flush()
raise MidiException("Unknown midi event type_: %r, %r" % (first_byte, second_byte))
self.type_ = META_EVENTS.whatis(second_byte)
length, midi_str = get_variable_length_number(midi_str[2:])
self.data = midi_str[:length]
return midi_str[length:]
else:
# an uncaught message
print(
'got unknown midi event type_',
repr(first_byte),
'char_to_binary(midi_str[0])',
char_to_binary(midi_str[0]),
'char_to_binary(midi_str[1])',
char_to_binary(midi_str[1]))
raise MidiException("Unknown midi event type_")
def get_bytes(self):
'''
Return a set of bytes for this MIDI event.
'''
sysex_event_dict = {"F0_SYSEX_EVENT": 0xF0,
"F7_SYSEX_EVENT": 0xF7}
if CHANNEL_VOICE_MESSAGES.hasattr(self.type_):
return_bytes = chr((self.channel - 1) +
getattr(CHANNEL_VOICE_MESSAGES, self.type_))
# for writing note-on/note-off
if self.type_ not in [
'PROGRAM_CHANGE', 'CHANNEL_KEY_PRESSURE']:
# this results in a two-part string, like '\x00\x00'
try:
data = chr(self._parameter1) + chr(self._parameter2)
except ValueError:
raise MidiException(
"Problem with representing either %d or %d" % (
self._parameter1, self._parameter2))
elif self.type_ in ['PROGRAM_CHANGE']:
try:
data = chr(self.data)
except TypeError:
raise MidiException(
"Got incorrect data for %return_bytes in .data: %return_bytes," %
(self, self.data) + "cannot parse Program Change")
else:
try:
data = chr(self.data)
except TypeError:
raise MidiException(
("Got incorrect data for %return_bytes in "
".data: %return_bytes, ") % (self, self.data) +
"cannot parse Miscellaneous Message")
return return_bytes + data
elif CHANNEL_MODE_MESSAGES.hasattr(self.type_):
return_bytes = getattr(CHANNEL_MODE_MESSAGES, self.type_)
return_bytes = (chr(0xB0 + (self.channel - 1)) +
chr(return_bytes) +
chr(self.data))
return return_bytes
elif self.type_ in sysex_event_dict:
return_bytes = bytes([sysex_event_dict[self.type_]])
return_bytes = return_bytes + put_variable_length_number(len(self.data))
return return_bytes + self.data
elif META_EVENTS.hasattr(self.type_):
return_bytes = bytes([0xFF]) + bytes([getattr(META_EVENTS, self.type_)])
return_bytes = return_bytes + put_variable_length_number(len(self.data))
try:
return return_bytes + self.data
except (UnicodeDecodeError, TypeError):
return return_bytes + unicodedata.normalize(
'NFKD', self.data).encode('ascii', 'ignore')
else:
raise MidiException("unknown midi event type_: %return_bytes" % self.type_)
#---------------------------------------------------------------------------
def is_note_on(self):
'''
return a boolean if this is a NOTE_ON message and velocity is not zero_
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> me1.type_ = "NOTE_ON"
>>> me1.velocity = 120
>>> me1.is_note_on()
True
>>> me1.is_note_off()
False
'''
return self.type_ == "NOTE_ON" and self.velocity != 0
def is_note_off(self):
'''
Return a boolean if this is should be interpreted as a note-off message,
either as a real note-off or as a note-on with zero velocity.
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> me1.type_ = "NOTE_OFF"
>>> me1.is_note_on()
False
>>> me1.is_note_off()
True
>>> me2 = MidiEvent(mt)
>>> me2.type_ = "NOTE_ON"
>>> me2.velocity = 0
>>> me2.is_note_on()
False
>>> me2.is_note_off()
True
'''
if self.type_ == "NOTE_OFF":
return True
elif self.type_ == "NOTE_ON" and self.velocity == 0:
return True
return False
def is_delta_time(self):
'''
Return a boolean if this is a DeltaTime subclass.
>>> mt = MidiTrack(1)
>>> dt = DeltaTime(mt)
>>> dt.is_delta_time()
True
'''
if self.type_ == "DeltaTime":
return True
return False
def matched_note_off(self, other):
'''
Returns True if `other` is a MIDI event that specifies
a note-off message for this message. That is, this event
is a NOTE_ON message, and the other is a NOTE_OFF message
for this pitch on this channel. Otherwise returns False
>>> mt = MidiTrack(1)
>>> me1 = MidiEvent(mt)
>>> me1.type_ = "NOTE_ON"
>>> me1.velocity = 120
>>> me1.pitch = 60
>>> me2 = MidiEvent(mt)
>>> me2.type_ = "NOTE_ON"
>>> me2.velocity = 0
>>> me2.pitch = 60
>>> me1.matched_note_off(me2)
True
>>> me2.pitch = 61
>>> me1.matched_note_off(me2)
False
>>> me2.type_ = "NOTE_OFF"
>>> me1.matched_note_off(me2)
False
>>> me2.pitch = 60
>>> me1.matched_note_off(me2)
True
>>> me2.channel = 12
>>> me1.matched_note_off(me2)
False
'''
if other.is_note_off:
# might check velocity here too?
if self.pitch == other.pitch and self.channel == other.channel:
return True
return False
class DeltaTime(MidiEvent):
'''
A :class:`~base.MidiEvent` subclass that stores the
time change (in ticks) since the start or since the last MidiEvent.
Pairs of DeltaTime and MidiEvent objects are the basic presentation of temporal data.
The `track` argument must be a :class:`~base.MidiTrack` object.
Time values are in integers, representing ticks.
The `channel` attribute, inherited from MidiEvent is not used and set to None
unless overridden (don't!).
>>> mt = MidiTrack(1)
>>> dt = DeltaTime(mt)
>>> dt.time = 380
>>> dt
<MidiEvent DeltaTime, t=380, track=1, channel=None>
'''
def __init__(self, track, time=None, channel=None):
MidiEvent.__init__(self, track, time=time, channel=channel)
self.type_ = "DeltaTime"
def read(self, oldstr):
self.time, newstr = get_variable_length_number(oldstr)
return self.time, newstr
def get_bytes(self):
midi_str = put_variable_length_number(self.time)
return midi_str
class MidiTrack(object):
'''
A MIDI Track. Each track contains a list of
:class:`~base.MidiChannel` objects, one for each channel.
All events are stored in the `events` list, in order.
An `index` is an integer identifier for this object.
TODO: Better Docs
>>> mt = MidiTrack(0)
'''
def __init__(self, index):
self.index = index
self.events = []
self.length = 0 #the data length; only used on read()
def read(self, midi_str):
'''
Read as much of the string (representing midi data) as necessary;
return the remaining string for reassignment and further processing.
The string should begin with `MTrk`, specifying a Midi Track
Creates and stores :class:`~base.DeltaTime`
and :class:`~base.MidiEvent` objects.
'''
time = 0 # a running counter of ticks
if not midi_str[:4] == b"MTrk":
raise MidiException('badly formed midi string: missing leading MTrk')
# get the 4 chars after the MTrk encoding
length, midi_str = get_number(midi_str[4:], 4)
self.length = length
# all event data is in the track str
track_str = midi_str[:length]
remainder = midi_str[length:]
e_previous = None
while track_str:
# shave off the time stamp from the event
delta_t = DeltaTime(self)
# return extracted time, as well as remaining string
d_time, track_str_candidate = delta_t.read(track_str)
# this is the offset that this event happens at, in ticks
time_candidate = time + d_time
# pass self to event, set this MidiTrack as the track for this event
event = MidiEvent(self)
if e_previous is not None: # set the last status byte
event.last_status_byte = e_previous.last_status_byte
# some midi events may raise errors; simply skip for now
try:
track_str_candidate = event.read(time_candidate, track_str_candidate)
except MidiException:
# assume that track_str, after delta extraction, is still correct
# set to result after taking delta time
track_str = track_str_candidate
continue
# only set after trying to read, which may raise exception
time = time_candidate
track_str = track_str_candidate # remainder string
# only append if we get this far
self.events.append(delta_t)
self.events.append(event)
e_previous = event
return remainder # remainder string after extracting track data
def get_bytes(self):
'''
returns a string of midi-data from the `.events` in the object.
'''
# build str using MidiEvents
midi_str = b""
for event in self.events:
# this writes both delta time and message events
try:
event_bytes = event.get_bytes()
int_array = []
for byte in event_bytes:
if is_num(byte):
int_array.append(byte)
else:
int_array.append(ord(byte))
event_bytes = bytes(bytearray(int_array))
midi_str = midi_str + event_bytes
except MidiException as err:
print("Conversion error for %s: %s; ignored." % (event, err))
return b"MTrk" + put_number(len(midi_str), 4) + midi_str
def __repr__(self):
return_str = "<MidiTrack %d -- %d events\n" % (self.index, len(self.events))
for event in self.events:
return_str = return_str + " " + event.__repr__() + "\n"
return return_str + " >"
#---------------------------------------------------------------------------
def update_events(self):
'''
We may attach events to this track before setting their `track` parameter.
This method will move through all events and set their track to this track.
'''
for event in self.events:
event.track = self
def has_notes(self):
'''Return True/False if this track has any note-on/note-off pairs defined.
'''
for event in self.events:
if event.is_note_on():
return True
return False
def set_channel(self, value):
'''Set the channel of all events in this Track.
'''
if value not in range(1, 17):
raise MidiException('bad channel value: %s' % value)
for event in self.events:
event.channel = value
def get_channels(self):
'''Get all channels used in this Track.
'''
post = []
for event in self.events:
if event.channel not in post:
post.append(event.channel)
return post
def get_program_changes(self):
'''Get all unique program changes used in this Track, sorted.
'''
post = []
for event in self.events:
if event.type_ == 'PROGRAM_CHANGE':
if event.data not in post:
post.append(event.data)
return post
class MidiFile(object):
'''
Low-level MIDI file writing, emulating methods from normal Python files.
The `ticks_per_quarter_note` attribute must be set before writing. 1024 is a common value.
This object is returned by some properties for directly writing files of midi representations.
'''
def __init__(self):
self.file = None
self.format = 1
self.tracks = []
self.ticks_per_quarter_note = 1024
self.ticks_per_second = None
def open(self, filename, attrib="rb"):
'''
Open a MIDI file path for reading or writing.
For writing to a MIDI file, `attrib` should be "wb".
'''
if attrib not in ['rb', 'wb']:
raise MidiException('cannot read or write unless in binary mode, not:', attrib)
self.file = open(filename, attrib)
def open_file_like(self, file_like):
'''Assign a file-like object, such as those provided by StringIO, as an open file object.
>>> from io import StringIO
>>> fileLikeOpen = StringIO()
>>> mf = MidiFile()
>>> mf.open_file_like(fileLikeOpen)
>>> mf.close()
'''
self.file = file_like
def __repr__(self):
return_str = "<MidiFile %d tracks\n" % len(self.tracks)
for track in self.tracks:
return_str = return_str + " " + track.__repr__() + "\n"
return return_str + ">"
def close(self):
'''
Close the file.
'''
self.file.close()
def read(self):
'''
Read and parse MIDI data stored in a file.
'''
self.readstr(self.file.read())
def readstr(self, midi_str):
'''
Read and parse MIDI data as a string, putting the
data in `.ticks_per_quarter_note` and a list of
`MidiTrack` objects in the attribute `.tracks`.
'''
if not midi_str[:4] == b"MThd":
raise MidiException('badly formated midi string, got: %s' % midi_str[:20])
# we step through the str src, chopping off characters as we go
# and reassigning to str
length, midi_str = get_number(midi_str[4:], 4)
if length != 6:
raise MidiException('badly formated midi string')
midi_format_type, midi_str = get_number(midi_str, 2)
self.format = midi_format_type
if midi_format_type not in (0, 1):
raise MidiException('cannot handle midi file format: %s' % format)
num_tracks, midi_str = get_number(midi_str, 2)
division, midi_str = get_number(midi_str, 2)
# very few midi files seem to define ticks_per_second
if division & 0x8000:
frames_per_second = -((division >> 8) | -128)
ticks_per_frame = division & 0xFF
if ticks_per_frame not in [24, 25, 29, 30]:
raise MidiException('cannot handle ticks per frame: %s' % ticks_per_frame)
if ticks_per_frame == 29:
ticks_per_frame = 30 # drop frame
self.ticks_per_second = ticks_per_frame * frames_per_second
else:
self.ticks_per_quarter_note = division & 0x7FFF
for i in range(num_tracks):
trk = MidiTrack(i) # sets the MidiTrack index parameters
midi_str = trk.read(midi_str) # pass all the remaining string, reassing
self.tracks.append(trk)
def write(self):
'''
Write MIDI data as a file to the file opened with `.open()`.
'''
self.file.write(self.writestr())
def writestr(self):
'''
generate the midi data header and convert the list of
midi_track objects in self_tracks into midi data and return it as a string_
'''
midi_str = self.write_m_thd_str()
for trk in self.tracks:
midi_str = midi_str + trk.get_bytes()
return midi_str
def write_m_thd_str(self):
'''
convert the information in self_ticks_per_quarter_note
into midi data header and return it as a string_'''
division = self.ticks_per_quarter_note
# Don't handle ticks_per_second yet, too confusing
if (division & 0x8000) != 0:
raise MidiException(
'Cannot write midi string unless self.ticks_per_quarter_note is a multiple of 1024')
midi_str = b"MThd" + put_number(6, 4) + put_number(self.format, 2)
midi_str = midi_str + put_number(len(self.tracks), 2)
midi_str = midi_str + put_number(division, 2)
return midi_str
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
| nihlaeth/voicetrainer | voicetrainer/midi.py | Python | gpl-3.0 | 42,017 |
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Storage/1.3.1/ApplicationDir.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Storage{struct ApplicationDir__WriteClosure;}}}
namespace g{
namespace Fuse{
namespace Storage{
// private sealed class ApplicationDir.WriteClosure :91
// {
uType* ApplicationDir__WriteClosure_typeof();
void ApplicationDir__WriteClosure__ctor__fn(ApplicationDir__WriteClosure* __this, uString* filename, uString* value);
void ApplicationDir__WriteClosure__Invoke_fn(ApplicationDir__WriteClosure* __this, bool* __retval);
void ApplicationDir__WriteClosure__New1_fn(uString* filename, uString* value, ApplicationDir__WriteClosure** __retval);
struct ApplicationDir__WriteClosure : uObject
{
uStrong<uString*> _filename;
uStrong<uString*> _value;
void ctor_(uString* filename, uString* value);
bool Invoke();
static ApplicationDir__WriteClosure* New1(uString* filename, uString* value);
};
// }
}}} // ::g::Fuse::Storage
| gncvalente/18app | dist/ios/include/Fuse.Storage.ApplicationDir.WriteClosure.h | C | gpl-3.0 | 1,089 |
---
title: Bagaimana jika seseorang berubah pikiran mengenai lisensi yang digunakan?
date: 2011-10-13 18:38:00 +07:00
published: false
categories:
- Kajian
tags:
- Lisensi Creative Commons
- Pergantian Lisensi
author: nita
comments: true
img: "/assets/img/favicon.png"
---
Lisensi CC tidak dapat dibatalkan. Setelah karya ini diumumkan di bawah lisensi CC, pemberi lisensi dapat terus menggunakan ciptaan sesuai dengan persyaratan lisensi selama jangka waktu perlindungan hak cipta. Walau demikian, lisensi CC tidak melarang pemberi lisensi untuk menghentikan pengumuman ciptaannya pada setiap saat. Selain itu, lisensi CC menyediakan [mekanisme](http://creativecommons.or.id/faq/#Bagaimana_jika_saya_tidak_suka_cara_seseorang_menggunakan_ciptaan_berlisensi_Creative_Commons_saya.3F) bagi pemberi lisensi dan pemilik hak cipta untuk meminta orang lain menggunakan ciptaan mereka untuk menghapus kredit kepada mereka walau dinyatakan lain oleh lisensi. Anda harus [berpikir secara hati-hati sebelum memilih lisensi Creative Commons](http://wiki.creativecommons.org/Before_Licensing).
| CreativeCommonsIndonesia/CCID | _posts/2011-10-13-bagaimana-kalau-saya-berubah-pikiran.markdown | Markdown | gpl-3.0 | 1,084 |
AddCSLuaFile()
SWEP.HoldType = "ar2"
if CLIENT then
SWEP.PrintName = "AUG"
SWEP.Slot = 2
SWEP.ViewModelFlip = false
SWEP.ViewModelFOV = 54
SWEP.Icon = "vgui/ttt/icon_aug.png"
SWEP.IconLetter = "l"
end
SWEP.Base = "weapon_tttbase"
SWEP.Kind = WEAPON_HEAVY
SWEP.Primary.Damage = 19
SWEP.Primary.Delay = 0.12
SWEP.Primary.DelayZoom = 0.22
SWEP.Primary.Cone = 0.03
SWEP.Primary.ClipSize = 20
SWEP.Primary.ClipMax = 60
SWEP.Primary.DefaultClip = 20
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "pistol"
SWEP.Primary.Recoil = 0.9
SWEP.Primary.Sound = Sound( "Weapon_Aug.Single" )
SWEP.Secondary.Sound = Sound("Default.Zoom")
SWEP.AutoSpawnable = true
SWEP.AmmoEnt = "item_ammo_pistol_ttt"
SWEP.UseHands = true
SWEP.ViewModel = "models/weapons/cstrike/c_rif_aug.mdl"
SWEP.WorldModel = "models/weapons/w_rif_aug.mdl"
SWEP.IronSightsPos = Vector( -6.55, -5, 2.4 )
SWEP.IronSightsAng = Vector( 2.2, -0.1, 0 )
SWEP.DeploySpeed = 1
function SWEP:SetZoom(state)
if IsValid(self.Owner) and self.Owner:IsPlayer() then
if state then
self.Primary.Cone = 0
if SERVER then
self.Owner:DrawViewModel(false)
self.Owner:SetFOV(20, 0.3)
end
else
self.Primary.Cone = 0.03
if SERVER then
self.Owner:DrawViewModel(true)
self.Owner:SetFOV(0, 0.2)
end
end
end
end
function SWEP:PrimaryAttack( worldsnd )
self.BaseClass.PrimaryAttack( self.Weapon, worldsnd )
if self:GetIronsights() then
self:SetNextPrimaryFire(CurTime() + self.Primary.DelayZoom)
else
self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
end
self:SetNextSecondaryFire( CurTime() + 0.1 )
end
-- Add some zoom to ironsights for this gun
function SWEP:SecondaryAttack()
if not self.IronSightsPos then return end
if self:GetNextSecondaryFire() > CurTime() then return end
local bIronsights = not self:GetIronsights()
self:SetIronsights( bIronsights )
if SERVER then
self:SetZoom(bIronsights)
else
self:EmitSound(self.Secondary.Sound)
end
self:SetNextSecondaryFire( CurTime() + 0.3)
end
function SWEP:PreDrop()
self:SetZoom(false)
self:SetIronsights(false)
return self.BaseClass.PreDrop(self)
end
function SWEP:Reload()
if ( self:Clip1() == self.Primary.ClipSize or self.Owner:GetAmmoCount( self.Primary.Ammo ) <= 0 ) then return end
self:DefaultReload( ACT_VM_RELOAD )
self:SetIronsights( false )
self:SetZoom( false )
end
function SWEP:Holster()
self:SetIronsights(false)
self:SetZoom(false)
return true
end
if CLIENT then
local scope = surface.GetTextureID("sprites/scope")
function SWEP:DrawHUD()
if self:GetIronsights() then
surface.SetDrawColor( 0, 0, 0, 255 )
local scrW = ScrW()
local scrH = ScrH()
local x = scrW / 2.0
local y = scrH / 2.0
local scope_size = scrH
-- crosshair
local gap = 80
local length = scope_size
surface.DrawLine( x - length, y, x - gap, y )
surface.DrawLine( x + length, y, x + gap, y )
surface.DrawLine( x, y - length, x, y - gap )
surface.DrawLine( x, y + length, x, y + gap )
gap = 0
length = 50
surface.DrawLine( x - length, y, x - gap, y )
surface.DrawLine( x + length, y, x + gap, y )
surface.DrawLine( x, y - length, x, y - gap )
surface.DrawLine( x, y + length, x, y + gap )
-- cover edges
local sh = scope_size / 2
local w = (x - sh) + 2
surface.DrawRect(0, 0, w, scope_size)
surface.DrawRect(x + sh - 2, 0, w, scope_size)
-- cover gaps on top and bottom of screen
surface.DrawLine( 0, 0, scrW, 0 )
surface.DrawLine( 0, scrH - 1, scrW, scrH - 1 )
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawLine(x, y, x + 1, y + 1)
-- scope
surface.SetTexture(scope)
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawTexturedRectRotated(x, y, scope_size, scope_size, 0)
else
return self.BaseClass.DrawHUD(self)
end
end
function SWEP:AdjustMouseSensitivity()
return (self:GetIronsights() and 0.2) or nil
end
end
| SirFrancisBillard/stupid-ttt | stupid-ttt/lua/weapons/weapon_ttt_aug.lua | Lua | gpl-3.0 | 4,457 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import testtools
import openstack.cloud
from openstack.cloud import meta
from openstack.tests import fakes
from openstack.tests.unit import base
class TestVolume(base.TestCase):
def test_attach_volume(self):
server = dict(id='server001')
vol = {'id': 'volume001', 'status': 'available',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
rattach = {'server_id': server['id'], 'device': 'device001',
'volumeId': volume['id'], 'id': 'attachmentId'}
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments']),
json={'volumeAttachment': rattach},
validate=dict(json={
'volumeAttachment': {
'volumeId': vol['id']}})
)])
ret = self.cloud.attach_volume(server, volume, wait=False)
self.assertEqual(rattach, ret)
self.assert_calls()
def test_attach_volume_exception(self):
server = dict(id='server001')
vol = {'id': 'volume001', 'status': 'available',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments']),
status_code=404,
validate=dict(json={
'volumeAttachment': {
'volumeId': vol['id']}})
)])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudURINotFound,
"Error attaching volume %s to server %s" % (
volume['id'], server['id'])
):
self.cloud.attach_volume(server, volume, wait=False)
self.assert_calls()
def test_attach_volume_wait(self):
server = dict(id='server001')
vol = {'id': 'volume001', 'status': 'available',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
vol['attachments'] = [{'server_id': server['id'],
'device': 'device001'}]
vol['status'] = 'attached'
attached_volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
rattach = {'server_id': server['id'], 'device': 'device001',
'volumeId': volume['id'], 'id': 'attachmentId'}
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments']),
json={'volumeAttachment': rattach},
validate=dict(json={
'volumeAttachment': {
'volumeId': vol['id']}})),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [attached_volume]})])
# defaults to wait=True
ret = self.cloud.attach_volume(server, volume)
self.assertEqual(rattach, ret)
self.assert_calls()
def test_attach_volume_wait_error(self):
server = dict(id='server001')
vol = {'id': 'volume001', 'status': 'available',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
vol['status'] = 'error'
errored_volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
rattach = {'server_id': server['id'], 'device': 'device001',
'volumeId': volume['id'], 'id': 'attachmentId'}
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments']),
json={'volumeAttachment': rattach},
validate=dict(json={
'volumeAttachment': {
'volumeId': vol['id']}})),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [errored_volume]})])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException,
"Error in attaching volume %s" % errored_volume['id']
):
self.cloud.attach_volume(server, volume)
self.assert_calls()
def test_attach_volume_not_available(self):
server = dict(id='server001')
volume = dict(id='volume001', status='error', attachments=[])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException,
"Volume %s is not available. Status is '%s'" % (
volume['id'], volume['status'])
):
self.cloud.attach_volume(server, volume)
self.assertEqual(0, len(self.adapter.request_history))
def test_attach_volume_already_attached(self):
device_id = 'device001'
server = dict(id='server001')
volume = dict(id='volume001',
attachments=[
{'server_id': 'server001', 'device': device_id}
])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException,
"Volume %s already attached to server %s on device %s" % (
volume['id'], server['id'], device_id)
):
self.cloud.attach_volume(server, volume)
self.assertEqual(0, len(self.adapter.request_history))
def test_detach_volume(self):
server = dict(id='server001')
volume = dict(id='volume001',
attachments=[
{'server_id': 'server001', 'device': 'device001'}
])
self.register_uris([
dict(method='DELETE',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments', volume['id']]))])
self.cloud.detach_volume(server, volume, wait=False)
self.assert_calls()
def test_detach_volume_exception(self):
server = dict(id='server001')
volume = dict(id='volume001',
attachments=[
{'server_id': 'server001', 'device': 'device001'}
])
self.register_uris([
dict(method='DELETE',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments', volume['id']]),
status_code=404)])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudURINotFound,
"Error detaching volume %s from server %s" % (
volume['id'], server['id'])
):
self.cloud.detach_volume(server, volume, wait=False)
self.assert_calls()
def test_detach_volume_wait(self):
server = dict(id='server001')
attachments = [{'server_id': 'server001', 'device': 'device001'}]
vol = {'id': 'volume001', 'status': 'attached', 'name': '',
'attachments': attachments}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
vol['status'] = 'available'
vol['attachments'] = []
avail_volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='DELETE',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments', volume.id])),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [avail_volume]})])
self.cloud.detach_volume(server, volume)
self.assert_calls()
def test_detach_volume_wait_error(self):
server = dict(id='server001')
attachments = [{'server_id': 'server001', 'device': 'device001'}]
vol = {'id': 'volume001', 'status': 'attached', 'name': '',
'attachments': attachments}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
vol['status'] = 'error'
vol['attachments'] = []
errored_volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='DELETE',
uri=self.get_mock_url(
'compute', 'public',
append=['servers', server['id'],
'os-volume_attachments', volume.id])),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [errored_volume]})])
with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException,
"Error in detaching volume %s" % errored_volume['id']
):
self.cloud.detach_volume(server, volume)
self.assert_calls()
def test_delete_volume_deletes(self):
vol = {'id': 'volume001', 'status': 'attached',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='DELETE',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', volume.id])),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': []})])
self.assertTrue(self.cloud.delete_volume(volume['id']))
self.assert_calls()
def test_delete_volume_gone_away(self):
vol = {'id': 'volume001', 'status': 'attached',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='DELETE',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', volume.id]),
status_code=404)])
self.assertFalse(self.cloud.delete_volume(volume['id']))
self.assert_calls()
def test_delete_volume_force(self):
vol = {'id': 'volume001', 'status': 'attached',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', volume.id, 'action']),
validate=dict(
json={'os-force_delete': None})),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': []})])
self.assertTrue(self.cloud.delete_volume(volume['id'], force=True))
self.assert_calls()
def test_set_volume_bootable(self):
vol = {'id': 'volume001', 'status': 'attached',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', volume.id, 'action']),
json={'os-set_bootable': {'bootable': True}}),
])
self.cloud.set_volume_bootable(volume['id'])
self.assert_calls()
def test_set_volume_bootable_false(self):
vol = {'id': 'volume001', 'status': 'attached',
'name': '', 'attachments': []}
volume = meta.obj_to_munch(fakes.FakeVolume(**vol))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes', 'detail']),
json={'volumes': [volume]}),
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', volume.id, 'action']),
json={'os-set_bootable': {'bootable': False}}),
])
self.cloud.set_volume_bootable(volume['id'])
self.assert_calls()
def test_list_volumes_with_pagination(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
vol2 = meta.obj_to_munch(fakes.FakeVolume('02', 'available', 'vol2'))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={
'volumes': [vol1],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
json={
'volumes': [vol2],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=02']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=02']),
json={'volumes': []})])
self.assertEqual(
[self.cloud._normalize_volume(vol1),
self.cloud._normalize_volume(vol2)],
self.cloud.list_volumes())
self.assert_calls()
def test_list_volumes_with_pagination_next_link_fails_once(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
vol2 = meta.obj_to_munch(fakes.FakeVolume('02', 'available', 'vol2'))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={
'volumes': [vol1],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
status_code=404),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={
'volumes': [vol1],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
json={
'volumes': [vol2],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=02']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=02']),
json={'volumes': []})])
self.assertEqual(
[self.cloud._normalize_volume(vol1),
self.cloud._normalize_volume(vol2)],
self.cloud.list_volumes())
self.assert_calls()
def test_list_volumes_with_pagination_next_link_fails_all_attempts(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
uris = []
attempts = 5
for i in range(attempts):
uris.extend([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={
'volumes': [vol1],
'volumes_links': [
{'href': self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
'rel': 'next'}]}),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail'],
qs_elements=['marker=01']),
status_code=404)])
self.register_uris(uris)
# Check that found volumes are returned even if pagination didn't
# complete because call to get next link 404'ed for all the allowed
# attempts
self.assertEqual(
[self.cloud._normalize_volume(vol1)],
self.cloud.list_volumes())
self.assert_calls()
def test_get_volume_by_id(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
self.register_uris([
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', '01']),
json={'volume': vol1}
)
])
self.assertEqual(
self.cloud._normalize_volume(vol1),
self.cloud.get_volume_by_id('01'))
self.assert_calls()
def test_create_volume(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes']),
json={'volume': vol1},
validate=dict(json={
'volume': {
'size': 50,
'name': 'vol1',
}})),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={'volumes': [vol1]}),
])
self.cloud.create_volume(50, name='vol1')
self.assert_calls()
def test_create_bootable_volume(self):
vol1 = meta.obj_to_munch(fakes.FakeVolume('01', 'available', 'vol1'))
self.register_uris([
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public', append=['volumes']),
json={'volume': vol1},
validate=dict(json={
'volume': {
'size': 50,
'name': 'vol1',
}})),
dict(method='GET',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', 'detail']),
json={'volumes': [vol1]}),
dict(method='POST',
uri=self.get_mock_url(
'volumev2', 'public',
append=['volumes', '01', 'action']),
validate=dict(
json={'os-set_bootable': {'bootable': True}})),
])
self.cloud.create_volume(50, name='vol1', bootable=True)
self.assert_calls()
| ctrlaltdel/neutrinator | vendor/openstack/tests/unit/cloud/test_volume.py | Python | gpl-3.0 | 22,754 |
# frozen_string_literal: true
module ActiveJob
# Returns the version of the currently loaded Active Job as a <tt>Gem::Version</tt>
def self.gem_version
Gem::Version.new VERSION::STRING
end
module VERSION
MAJOR = 5
MINOR = 2
TINY = 6
PRE = nil
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
end
| BeGe78/esood | vendor/bundle/ruby/3.0.0/gems/activejob-5.2.6/lib/active_job/gem_version.rb | Ruby | gpl-3.0 | 344 |
# Stuff to add
- Add the parallel code
- Add a chunksize parameter
- ipython notebook demonstrating:
- graphs of the general scaling with boundlen, number of objects
- variation of these when querying within a tile and outside
- cuts on magnitude and redshift
- Fixed focal plane (different chunk-size, different numbers of threads)
| rbiswas4/BenchmarkInstanceCatalogs | doc/TODO_LIST.md | Markdown | gpl-3.0 | 347 |
<?php
// HTTP
define('HTTP_SERVER', 'http://localhost/opencart/upload/');
// HTTPS
define('HTTPS_SERVER', 'http://localhost/opencart/upload/');
// DIR
define('DIR_APPLICATION', 'F:\git\OC\OC\upload\/catalog/');
define('DIR_SYSTEM', 'F:\git\OC\OC\upload\/system/');
define('DIR_DATABASE', 'F:\git\OC\OC\upload\/system/database/');
define('DIR_LANGUAGE', 'F:\git\OC\OC\upload\/catalog/language/');
define('DIR_TEMPLATE', 'F:\git\OC\OC\upload\/catalog/view/theme/');
define('DIR_CONFIG', 'F:\git\OC\OC\upload\/system/config/');
define('DIR_IMAGE', 'F:\git\OC\OC\upload\/image/');
define('DIR_CACHE', 'F:\git\OC\OC\upload\/system/cache/');
define('DIR_DOWNLOAD', 'F:\git\OC\OC\upload\/download/');
define('DIR_LOGS', 'F:\git\OC\OC\upload\/system/logs/');
// DB
define('DB_DRIVER', 'mysql');
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'opencart');
define('DB_PREFIX', 'oc_');
?> | tianhua/opencart | OC/upload/config.php | PHP | gpl-3.0 | 949 |
require 'y_support/all'
# Places are basically glorified variables, with current contents (marking), and
# default contents (default_marking).
#
class Place
attr_reader :name, :default_marking
attr_accessor :marking
def initialize name, default_marking=0
@name, @default_marking = name, default_marking
end
def reset!; @marking = default_marking end
end
# Transitions specify how marking changes when the transition "fires" (activates).
# "Arcs" attribute is a hash of { place => change } pairs.
#
class Transition
attr_reader :name, :arcs
def initialize( name, arcs: {} )
@name, @arcs = name, arcs
end
def fire!
arcs.each { |place, change| place.marking = place.marking + change }
end
end
A, B, C = Place.new( "A" ), Place.new( "B" ), Place.new( "C" )
# Marking of A is incremented by 1
AddA = Transition.new( "AddA", arcs: { A => 1 } )
# 1 piece of A dissociates into 1 piece of B and 1 piece of C
DissocA = Transition.new( "DissocA", arcs: { A => -1, B => +1, C => +1 } )
[ A, B, C ].each &:reset!
[ A, B, C ].map &:marking #=> [0, 0, 0]
AddA.fire!
[ A, B, C ].map &:marking #=> [1, 0, 0]
DissocA.fire!
[ A, B, C ].map &:marking #=> [0, 1, 1]
require 'yaml'
class Place
def to_yaml
YAML.dump( { name: name, default_marking: default_marking } )
end
def to_ruby
"Place( name: #{name}, default_marking: #{default_marking} )\n"
end
end
puts A.to_yaml
puts B.to_yaml
puts C.to_yaml
puts A.to_ruby
puts B.to_ruby
puts C.to_ruby
class Transition
def to_yaml
YAML.dump( { name: name, arcs: arcs.modify { |k, v| [k.name, v] } } )
end
def to_ruby
"Transition( name: #{name}, default_marking: #{arcs.modify { |k, v| [k.name.to_sym, v] }} )\n"
end
end
puts AddA.to_yaml
puts DissocA.to_yaml
puts AddA.to_ruby
puts DissocA.to_ruby
# Now save that to a file
# and use
Place.from_yaml YAML.load( yaml_place_string )
Transition.from_yaml YAML.load( yaml_transition_string )
# or
YNelson::Manipulator.load( yaml: YAML.load( system_definition ) )
# then decorate #to_yaml and #to_ruby methods with Zz-structure-specific parts.
class Zz
def to_yaml
super + "\n" +
YAML.dump( { along: dump_connectivity() } )
end
def to_ruby
super + "\n" +
"#{name}.along( #{dimension} ).posward #{along( dimension ).posward.name}\n" +
"#{name}.along( #{dimension} ).negward #{along( dimension ).negward.name}"
end
end
# etc.
| boris-s/y_nelson | test/mongoid_example.rb | Ruby | gpl-3.0 | 2,409 |
using System;
using System.Runtime.InteropServices;
namespace ABC.PInvoke
{
/// <summary>
/// Class through which user32.dll calls can be accessed for which the .NET framework offers no alternative.
/// TODO: Clean up remaining original documentation, converting it to the wrapper's equivalents.
/// </summary>
public static partial class User32
{
const string Dll = "user32.dll";
#region Window Functions.
/// <summary>
/// Calls the default window procedure to provide default processing for any window messages that an application does not process. This function ensures that every message is processed. DefWindowProc is called with the same parameters received by the window procedure.
/// </summary>
/// <param name="handle">A handle to the window procedure that received the message.</param>
/// <param name="message">The message.</param>
/// <param name="wParam">Additional message information. The content of this parameter depends on the value of the Msg parameter.</param>
/// <param name="lParam">Additional message information. The content of this parameter depends on the value of the Msg parameter</param>
/// <returns>The return value is the result of the message processing and depends on the message.</returns>
[DllImport( Dll )]
public static extern IntPtr DefWindowProc( IntPtr handle, uint message, IntPtr wParam, IntPtr lParam );
/// <summary>
/// Registers a specified Shell window to receive certain messages for events or notifications that are useful to Shell applications.
/// </summary>
/// <param name="hwnd">A handle to the window to register for Shell hook messages.</param>
/// <returns>TRUE if the function succeeds; otherwise, FALSE.</returns>
[DllImport( Dll, CharSet = CharSet.Auto, SetLastError = true )]
public static extern bool RegisterShellHookWindow( IntPtr hwnd );
/// <summary>
/// Changes an attribute of the specified window. The function also sets the 32-bit (long) value at the specified offset into the extra window memory. Note: this function has been superseded by the SetWindowLongPtr function. To write code that is compatible with both 32-bit and 64-bit versions of Windows, use the SetWindowLongPtr function.
/// </summary>
/// <param name="windowHandle">A handle to the window and, indirectly, the class to which the window belongs.</param>
/// <param name="index">The zero-based offset to the value to be set. Valid values are in the range zero through the number of bytes of extra window memory, minus the size of an integer. To set any other value, specify one of the following values.</param>
/// <param name="dwNewLong">The replacement value.</param>
/// <returns>If the function succeeds, the return value is the previous value of the specified 32-bit integer. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
public static IntPtr SetWindowLongPtr( IntPtr windowHandle, int index, uint dwNewLong )
{
// GetWindowLongPtr is only supported by Win64. By checking the pointer size the correct function can be called.
return IntPtr.Size == 8
? SetWindowLongPtr64( windowHandle, index, dwNewLong )
: SetWindowLongPtr32( windowHandle, index, dwNewLong );
}
[DllImport( Dll, EntryPoint = "SetWindowLong", SetLastError = true )]
static extern IntPtr SetWindowLongPtr32( IntPtr windowHandle, int index, uint dwNewLong );
[DllImport( Dll, EntryPoint = "SetWindowLongPtr", SetLastError = true )]
static extern IntPtr SetWindowLongPtr64( IntPtr windowHandle, int index, uint dwNewLong );
#endregion // Window Functions.
}
} | Whathecode/ABC | ABC/ABC.PInvoke/User32.cs | C# | gpl-3.0 | 3,655 |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - KNIGHT, Mary</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>KNIGHT, Mary<sup><small></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
KNIGHT, Mary
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I19227</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">female</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/3/e/d15f60afe5835e44ab117c610e3.html" title="Birth">
Birth
<span class="grampsid"> [E19800]</span>
</a>
</td>
<td class="ColumnDate">about 1824</td>
<td class="ColumnPlace">
<a href="../../../plc/8/a/d15f60afe152a1c9f65946dd0a8.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1a">1a</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/d/c/d15f60afe71b41083012d24cd.html" title="Baptism">
Baptism
<span class="grampsid"> [E19801]</span>
</a>
</td>
<td class="ColumnDate">1824-11-07</td>
<td class="ColumnPlace">
<a href="../../../plc/5/d/d15f60afe793ace2da21ce058d5.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1b">1b</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/0/3/d15f60afe923d72183f129bee30.html" title="Census">
Census
<span class="grampsid"> [E19802]</span>
</a>
</td>
<td class="ColumnDate">1841</td>
<td class="ColumnPlace">
<a href="../../../plc/9/1/d15f60afceb68dd41ed5a144c19.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1c">1c</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/c/c/d15f60afeaa282365fa78ee33cc.html" title="Census">
Census
<span class="grampsid"> [E19803]</span>
</a>
</td>
<td class="ColumnDate">1861</td>
<td class="ColumnPlace">
<a href="../../../plc/2/b/d15f60afd2a1bb84c99a9e83eb2.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1d">1d</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/3/9/d15f60afec24bd07bd21f48093.html" title="Census">
Census
<span class="grampsid"> [E19804]</span>
</a>
</td>
<td class="ColumnDate">1881</td>
<td class="ColumnPlace">
<a href="../../../plc/9/2/d15f60af9a67ecbe34abbbae929.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1e">1e</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/5/f/d15f60afed91b3473a9efe9c2f5.html" title="Census">
Census
<span class="grampsid"> [E19805]</span>
</a>
</td>
<td class="ColumnDate">1891</td>
<td class="ColumnPlace">
<a href="../../../plc/d/b/d15f60afee11372b2e80b488abd.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1f">1f</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/f/d/d15f60afefe378c6f74354d91df.html" title="Occupation">
Occupation
<span class="grampsid"> [E19806]</span>
</a>
</td>
<td class="ColumnDate">1891</td>
<td class="ColumnPlace"> </td>
<td class="ColumnDescription">
Farmer
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1g">1g</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="../../../fam/0/5/d15f60afa006aefe9adcd6ee650.html" title="Family of GAMMON, George and KNIGHT, Mary">Family of GAMMON, George and KNIGHT, Mary<span class="grampsid"> [F6830]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Husband</td>
<td class="ColumnValue">
<a href="../../../ppl/4/c/d15f60afc536ab74cc257cf6dc4.html">GAMMON, George<span class="grampsid"> [I19225]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/c/e/d15f60e295b180744c545f33ec.html" title="Marriage">
Marriage
<span class="grampsid"> [E26544]</span>
</a>
</td>
<td class="ColumnDate">1840-10-21</td>
<td class="ColumnPlace">
<a href="../../../plc/9/b/d15f60afcb472ddf963e0b51ab9.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1h">1h</a>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Children</td>
<td class="ColumnValue">
<ol>
<li>
<a href="../../../ppl/4/6/d15f60b00e47ddcf57183c51764.html">GAMMON, Sophia<span class="grampsid"> [I19232]</span></a>
</li>
<li>
<a href="../../../ppl/b/0/d15f60b01651f191a2579cecd0b.html">GAMMON, Mary Ann<span class="grampsid"> [I19233]</span></a>
</li>
<li>
<a href="../../../ppl/d/5/d15f60b01f146d923826dcc125d.html">GAMMON, Emma<span class="grampsid"> [I19234]</span></a>
</li>
<li>
<a href="../../../ppl/f/6/d15f60b02915ca61a8d46cb7d6f.html">GAMMON, Sarah Ann<span class="grampsid"> [I19235]</span></a>
</li>
<li>
<a href="../../../ppl/8/1/d15f60b036076af576d215e6f18.html">GAMMON, John<span class="grampsid"> [I19237]</span></a>
</li>
<li>
<a href="../../../ppl/a/a/d15f60b040746cece74746f61aa.html">GAMMON, Jane<span class="grampsid"> [I19238]</span></a>
</li>
<li>
<a href="../../../ppl/9/c/d15f60b048e7c87cb33728253c9.html">GAMMON, Eliza<span class="grampsid"> [I19239]</span></a>
</li>
<li>
<a href="../../../ppl/0/6/d15f60b04fe17d864d27c836760.html">GAMMON, Lizzie<span class="grampsid"> [I19240]</span></a>
</li>
<li>
<a href="../../../ppl/5/4/d15f60b058366bf83401c5ba345.html">GAMMON, Hannah<span class="grampsid"> [I19241]</span></a>
</li>
</ol>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Attributes</td>
<td class="ColumnValue">
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">225125EEFFE1874C99ADB8B3C4A2FBF23DBC</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="attributes">
<h4>Attributes</h4>
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">54C74CCB51F45645BF85BA5842B3936555CC</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<ol>
<li class="thisperson">
KNIGHT, Mary
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/4/c/d15f60afc536ab74cc257cf6dc4.html">GAMMON, George<span class="grampsid"> [I19225]</span></a>
<ol>
<li>
<a href="../../../ppl/4/6/d15f60b00e47ddcf57183c51764.html">GAMMON, Sophia<span class="grampsid"> [I19232]</span></a>
</li>
<li>
<a href="../../../ppl/b/0/d15f60b01651f191a2579cecd0b.html">GAMMON, Mary Ann<span class="grampsid"> [I19233]</span></a>
</li>
<li>
<a href="../../../ppl/d/5/d15f60b01f146d923826dcc125d.html">GAMMON, Emma<span class="grampsid"> [I19234]</span></a>
</li>
<li>
<a href="../../../ppl/f/6/d15f60b02915ca61a8d46cb7d6f.html">GAMMON, Sarah Ann<span class="grampsid"> [I19235]</span></a>
</li>
<li>
<a href="../../../ppl/8/1/d15f60b036076af576d215e6f18.html">GAMMON, John<span class="grampsid"> [I19237]</span></a>
</li>
<li>
<a href="../../../ppl/a/a/d15f60b040746cece74746f61aa.html">GAMMON, Jane<span class="grampsid"> [I19238]</span></a>
</li>
<li>
<a href="../../../ppl/9/c/d15f60b048e7c87cb33728253c9.html">GAMMON, Eliza<span class="grampsid"> [I19239]</span></a>
</li>
<li>
<a href="../../../ppl/0/6/d15f60b04fe17d864d27c836760.html">GAMMON, Lizzie<span class="grampsid"> [I19240]</span></a>
</li>
<li>
<a href="../../../ppl/5/4/d15f60b058366bf83401c5ba345.html">GAMMON, Hannah<span class="grampsid"> [I19241]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/3/6/d15f60af1bd7c37ad5f1470b463.html" title="Faded Genes Website 1/3/09" name ="sref1">
Faded Genes Website 1/3/09
<span class="grampsid"> [S0435]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1b">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1c">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1d">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1e">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1f">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1g">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1h">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:39<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| RossGammon/the-gammons.net | RossFamilyTree/ppl/4/1/d15f60afe5345ed3452e575a014.html | HTML | gpl-3.0 | 15,201 |
#!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger = getLogger(__name__)
#-----------------------------------------------------------------------------
@csrf_exempt
def list(request, nick = None):
template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nick
form_target = reverse(list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
else: # 'leave' in request.POST
presence.person_left(request.POST['nick'], context)
# tell the browser to reload the page, but with GET request
return django.shortcuts.redirect(request.path)
context = RequestContext(request, {
'form_target': form_target,
'form': form,
'present': presence.list_people(),
'sensors': presence.list_simple_sensors(),
'complex_sensors': presence.list_complex_sensors(),
})
return HttpResponse(template.render(context))
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker
| HackerspaceWroclaw/wlokalu | wlokalu/views.py | Python | gpl-3.0 | 1,663 |
/* Test Octagonal_Shape::generalized_affine_image().
Copyright (C) 2001-2009 Roberto Bagnara <[email protected]>
This file is part of the Parma Polyhedra Library (PPL).
The PPL 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.
The PPL 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 02111-1307, USA.
For the most up-to-date information see the Parma Polyhedra Library
site: http://www.cs.unipr.it/ppl/ . */
#include "ppl_test.hh"
namespace {
bool
test01() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2);
oct.add_constraint(A >= 0);
oct.add_constraint(A <= 4);
oct.add_constraint(B <= 5);
oct.add_constraint(A <= B);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(2);
known_result.add_constraint(A >= 0);
known_result.add_constraint(A <= 4);
known_result.add_constraint(B - A >= 2);
oct.generalized_affine_image(B, GREATER_OR_EQUAL, A+2);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(B, "
"GREATER_OR_EQUAL, A+2) ***");
return ok;
}
bool
test02() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2);
oct.add_constraint(B >= 0);
oct.add_constraint(A - B >= 0);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(oct);
oct.generalized_affine_image(A, EQUAL, A + 2);
known_result.affine_image(A, A + 2);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image"
"(A, EQUAL, A + 2) ***");
return ok;
}
bool
test03() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2, EMPTY);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(2, EMPTY);
oct.generalized_affine_image(A, LESS_OR_EQUAL, B + 1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image"
"(A, LESS_OR_EQUAL, B + 1) ***");
return ok;
}
bool
test04() {
Variable x(0);
Variable y(1);
Variable z(2);
TOctagonal_Shape oct(3);
oct.add_constraint(x >= 2);
oct.add_constraint(x - y <= 3);
oct.add_constraint(y <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(x >= 1);
known_result.add_constraint(y <= 2);
known_result.add_constraint(- y <= 1);
oct.generalized_affine_image(x, GREATER_OR_EQUAL, 2*x - 2, 2);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(x,"
"GREATER_OR_EQUAL, 2*x - 2, 2) ***");
return ok;
}
bool
test05() {
Variable x(0);
Variable y(1);
TOctagonal_Shape oct(3);
oct.add_constraint(x >= 2);
oct.add_constraint(x - y <= 3);
oct.add_constraint(y <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(x >= 2);
known_result.add_constraint(x <= 5);
known_result.add_constraint(x - y <= 1);
oct.generalized_affine_image(y, GREATER_OR_EQUAL, 2*x - 2, 2);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(y, "
"GREATER_OR_EQUAL, 2*x - 2, 2) ***");
return ok;
}
bool
test06() {
Variable x(0);
Variable y(1);
TOctagonal_Shape oct(2);
oct.add_constraint(x >= 4);
oct.add_constraint(x <= -6);
oct.add_constraint(y == 0);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(2 , EMPTY);
oct.generalized_affine_image(y, LESS_OR_EQUAL, Linear_Expression(2));
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(y, "
"LESS_OR_EQUAL, 2) ***");
return ok;
}
bool
test07() {
Variable x(0);
// Variable y(1);
TOctagonal_Shape oct(2, EMPTY);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(oct);
oct.generalized_affine_image(x, EQUAL, Linear_Expression(6));
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(x, EQUAL, 6) ***");
return ok;
}
bool
test08() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2);
oct.add_constraint(A >= 0);
oct.add_constraint(B >= 0);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(2);
known_result.add_constraint(B >= 0);
known_result.add_constraint(A <= 3);
oct.generalized_affine_image(A, LESS_OR_EQUAL, Linear_Expression(3));
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(A, "
"LESS_OR_EQUAL, 3) ***");
return ok;
}
bool
test09() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2);
oct.add_constraint(A == 0);
oct.add_constraint(B >= 1);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(oct);
known_result.affine_image(B, Linear_Expression(5));
oct.generalized_affine_image(B, EQUAL, Linear_Expression(5));
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(B, EQUAL, 5) ***");
return ok;
}
bool
test10() {
Variable A(0);
Variable B(1);
TOctagonal_Shape oct(2);
oct.add_constraint(A + B == 0);
oct.add_constraint(B <= 1);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(2);
known_result.add_constraint(A >= 2);
known_result.add_constraint(B <= 1);
oct.generalized_affine_image(A, GREATER_OR_EQUAL, Linear_Expression(2));
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(A, "
"GREATER_OR_EQUAL, 2) ***");
return ok;
}
bool
test11() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A - B == 0);
oct.add_constraint(B <= 1);
oct.add_constraint(C + A <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A - B == 0);
known_result.add_constraint(B <= 1);
known_result.add_constraint(C + A <= 3);
known_result.add_constraint(C + B <= 3);
oct.generalized_affine_image(C, LESS_OR_EQUAL, C + 1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(C, "
"LESS_OR_EQUAL, C + 1) ***");
return ok;
}
bool
test12() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A - B == 0);
oct.add_constraint(B <= 1);
oct.add_constraint(C + A <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(oct);
known_result.affine_image(C, C + 1);
oct.generalized_affine_image(C, EQUAL, C + 1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(C, "
"EQUAL, C+1) ***");
return ok;
}
bool
test13() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A - B == 0);
oct.add_constraint(B <= 1);
oct.add_constraint(C + A <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(B - A >= -2);
known_result.add_constraint(A <= 1);
known_result.add_constraint(C + A <= 2);
oct.generalized_affine_image(B, GREATER_OR_EQUAL, B - 2);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(B, "
"GREATER_OR_EQUAL, B - 2) ***");
return ok;
}
bool
test14() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A - B == 0);
oct.add_constraint(B <= 1);
oct.add_constraint(C + A <= 2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(B <= C + 3);
known_result.add_constraint(A <= 1);
known_result.add_constraint(C + A <= 2);
oct.generalized_affine_image(B, LESS_OR_EQUAL, C + 3);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct, "*** oct.generalized_affine_image(B, "
"LESS_OR_EQUAL, C + 3) ***");
return ok;
}
bool
test15() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A - B == 0);
oct.add_constraint(B <= 1);
oct.add_constraint(C + A <=2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(oct);
known_result.affine_image(B, C + 3);
oct.generalized_affine_image(B, EQUAL, C + 3);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, EQUAL, C+3) ***");
return ok;
}
bool
test16() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A <= 21);
oct.add_constraint(B <= 1);
oct.add_constraint(C <= 2);
oct.add_constraint(A >= 2);
oct.add_constraint(B >= -1);
oct.add_constraint(C >= -2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A <= 21);
known_result.add_constraint(A >= 2);
known_result.add_constraint(C <= 2);
known_result.add_constraint(C >= -2);
known_result.add_constraint(B <= 4);
oct.generalized_affine_image(B, LESS_OR_EQUAL, B + 3);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, "
"LESS_OR_EQUAL, B + 3) ***");
return ok;
}
bool
test17() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A <= 21);
oct.add_constraint(B <= 1);
oct.add_constraint(C <= 2);
oct.add_constraint(A >= 2);
oct.add_constraint(B >= -1);
oct.add_constraint(C >= -2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A <= 21);
known_result.add_constraint(A >= 2);
known_result.add_constraint(C <= 2);
known_result.add_constraint(C >= -2);
known_result.add_constraint(B + C <= -3);
oct.generalized_affine_image(B, LESS_OR_EQUAL, C + 3, -1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, "
"LESS_OR_EQUAL, C + 3, -1) ***");
return ok;
}
bool
test18() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A <= 21);
oct.add_constraint(B <= 1);
oct.add_constraint(C <= 2);
oct.add_constraint(A >= 2);
oct.add_constraint(B >= -1);
oct.add_constraint(C >= -2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A <= 21);
known_result.add_constraint(A >= 2);
known_result.add_constraint(C <= 2);
known_result.add_constraint(C >= -2);
known_result.add_constraint(A + B <= -3);
oct.generalized_affine_image(B, LESS_OR_EQUAL, A + 3, -1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, "
"LESS_OR_EQUAL, A + 3, -1) ***");
return ok;
}
bool
test19() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A <= 21);
oct.add_constraint(B <= 1);
oct.add_constraint(C <= 2);
oct.add_constraint(A >= 2);
oct.add_constraint(B >= -1);
oct.add_constraint(C >= -2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A <= 21);
known_result.add_constraint(A >= 2);
known_result.add_constraint(C <= 2);
known_result.add_constraint(C >= -2);
known_result.add_constraint(B - A >= 3);
oct.generalized_affine_image(B, GREATER_OR_EQUAL, A + 3);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, "
"GREATER_OR_EQUAL, A + 3) ***");
return ok;
}
bool
test20() {
Variable A(0);
Variable B(1);
Variable C(2);
TOctagonal_Shape oct(3);
oct.add_constraint(A <= 21);
oct.add_constraint(B <= 1);
oct.add_constraint(C <= 2);
oct.add_constraint(A >= 2);
oct.add_constraint(B >= -1);
oct.add_constraint(C >= -2);
print_constraints(oct, "*** oct ***");
Octagonal_Shape<mpq_class> known_result(3);
known_result.add_constraint(A <= 21);
known_result.add_constraint(A >= 2);
known_result.add_constraint(C <= 2);
known_result.add_constraint(C >= -2);
known_result.add_constraint(A + B >= -3);
oct.generalized_affine_image(B, GREATER_OR_EQUAL, A + 3, -1);
bool ok = (Octagonal_Shape<mpq_class>(oct) == known_result);
print_constraints(oct,
"*** oct.generalized_affine_image(B, "
"GREATER_OR_EQUAL, A + 3, -1) ***");
return ok;
}
} // namespace
BEGIN_MAIN
DO_TEST(test01);
DO_TEST(test02);
DO_TEST(test03);
DO_TEST(test04);
DO_TEST(test05);
DO_TEST(test06);
DO_TEST(test07);
DO_TEST(test08);
DO_TEST(test09);
DO_TEST(test10);
DO_TEST(test11);
DO_TEST(test12);
DO_TEST(test13);
DO_TEST(test14);
DO_TEST(test15);
DO_TEST(test16);
DO_TEST(test17);
DO_TEST(test18);
DO_TEST(test19);
DO_TEST(test20);
END_MAIN
| OpenInkpot-archive/iplinux-ppl | tests/Octagonal_Shape/generalizedaffineimage1.cc | C++ | gpl-3.0 | 14,365 |
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace xServer.Core.Build
{
public static class IconInjector
{
// Basically, you can change icons with the UpdateResource api call.
// When you make the call you say "I'm updating an icon", and you send the icon data.
// The main problem is that ICO files store the icons in one set of structures, and exe/dll files store them in
// another set of structures. So you have to translate between the two -- you can't just load the ICO file as
// bytes and send them with the UpdateResource api call.
[SuppressUnmanagedCodeSecurity()]
private class NativeMethods
{
[DllImport("kernel32")]
public static extern IntPtr BeginUpdateResource(string fileName, [MarshalAs(UnmanagedType.Bool)]bool deleteExistingResources);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UpdateResource(IntPtr hUpdate, IntPtr type, IntPtr name, short language, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)]byte[] data, int dataSize);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EndUpdateResource(IntPtr hUpdate, [MarshalAs(UnmanagedType.Bool)]bool discard);
}
// The first structure in an ICO file lets us know how many images are in the file.
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIR
{
// Reserved, must be 0
public ushort Reserved;
// Resource type, 1 for icons.
public ushort Type;
// How many images.
public ushort Count;
// The native structure has an array of ICONDIRENTRYs as a final field.
}
// Each ICONDIRENTRY describes one icon stored in the ico file. The offset says where the icon image data
// starts in the file. The other fields give the information required to turn that image data into a valid
// bitmap.
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIRENTRY
{
// Width, in pixels, of the image
public byte Width;
// Height, in pixels, of the image
public byte Height;
// Number of colors in image (0 if >=8bpp)
public byte ColorCount;
// Reserved ( must be 0)
public byte Reserved;
// Color Planes
public ushort Planes;
// Bits per pixel
public ushort BitCount;
// Length in bytes of the pixel data
public int BytesInRes;
// Offset in the file where the pixel data starts.
public int ImageOffset;
}
// Each image is stored in the file as an ICONIMAGE structure:
//typdef struct
//{
// BITMAPINFOHEADER icHeader; // DIB header
// RGBQUAD icColors[1]; // Color table
// BYTE icXOR[1]; // DIB bits for XOR mask
// BYTE icAND[1]; // DIB bits for AND mask
//} ICONIMAGE, *LPICONIMAGE;
[StructLayout(LayoutKind.Sequential)]
private struct BITMAPINFOHEADER
{
public uint Size;
public int Width;
public int Height;
public ushort Planes;
public ushort BitCount;
public uint Compression;
public uint SizeImage;
public int XPelsPerMeter;
public int YPelsPerMeter;
public uint ClrUsed;
public uint ClrImportant;
}
// The icon in an exe/dll file is stored in a very similar structure:
[StructLayout(LayoutKind.Sequential, Pack = 2)]
private struct GRPICONDIRENTRY
{
public byte Width;
public byte Height;
public byte ColorCount;
public byte Reserved;
public ushort Planes;
public ushort BitCount;
public int BytesInRes;
public ushort ID;
}
public static void InjectIcon(string exeFileName, string iconFileName)
{
InjectIcon(exeFileName, iconFileName, 1, 1);
}
public static void InjectIcon(string exeFileName, string iconFileName, uint iconGroupID, uint iconBaseID)
{
const uint RT_ICON = 3u;
const uint RT_GROUP_ICON = 14u;
IconFile iconFile = IconFile.FromFile(iconFileName);
var hUpdate = NativeMethods.BeginUpdateResource(exeFileName, false);
var data = iconFile.CreateIconGroupData(iconBaseID);
NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_GROUP_ICON), new IntPtr(iconGroupID), 0, data, data.Length);
for (int i = 0; i <= iconFile.ImageCount - 1; i++)
{
var image = iconFile.ImageData(i);
NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_ICON), new IntPtr(iconBaseID + i), 0, image, image.Length);
}
NativeMethods.EndUpdateResource(hUpdate, false);
}
private class IconFile
{
private ICONDIR iconDir = new ICONDIR();
private ICONDIRENTRY[] iconEntry;
private byte[][] iconImage;
public int ImageCount
{
get { return iconDir.Count; }
}
public byte[] ImageData (int index)
{
return iconImage[index];
}
public static IconFile FromFile(string filename)
{
IconFile instance = new IconFile();
// Read all the bytes from the file.
byte[] fileBytes = System.IO.File.ReadAllBytes(filename);
// First struct is an ICONDIR
// Pin the bytes from the file in memory so that we can read them.
// If we didn't pin them then they could move around (e.g. when the
// garbage collector compacts the heap)
GCHandle pinnedBytes = GCHandle.Alloc(fileBytes, GCHandleType.Pinned);
// Read the ICONDIR
instance.iconDir = (ICONDIR)Marshal.PtrToStructure(pinnedBytes.AddrOfPinnedObject(), typeof(ICONDIR));
// which tells us how many images are in the ico file. For each image, there's a ICONDIRENTRY, and associated pixel data.
instance.iconEntry = new ICONDIRENTRY[instance.iconDir.Count];
instance.iconImage = new byte[instance.iconDir.Count][];
// The first ICONDIRENTRY will be immediately after the ICONDIR, so the offset to it is the size of ICONDIR
int offset = Marshal.SizeOf(instance.iconDir);
// After reading an ICONDIRENTRY we step forward by the size of an ICONDIRENTRY
var iconDirEntryType = typeof(ICONDIRENTRY);
var size = Marshal.SizeOf(iconDirEntryType);
for (int i = 0; i <= instance.iconDir.Count - 1; i++)
{
// Grab the structure.
var entry = (ICONDIRENTRY)Marshal.PtrToStructure(new IntPtr(pinnedBytes.AddrOfPinnedObject().ToInt64() + offset), iconDirEntryType);
instance.iconEntry[i] = entry;
// Grab the associated pixel data.
instance.iconImage[i] = new byte[entry.BytesInRes];
Buffer.BlockCopy(fileBytes, entry.ImageOffset, instance.iconImage[i], 0, entry.BytesInRes);
offset += size;
}
pinnedBytes.Free();
return instance;
}
public byte[] CreateIconGroupData(uint iconBaseID)
{
// This will store the memory version of the icon.
int sizeOfIconGroupData = Marshal.SizeOf(typeof(ICONDIR)) + Marshal.SizeOf(typeof(GRPICONDIRENTRY)) * ImageCount;
byte[] data = new byte[sizeOfIconGroupData];
var pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(iconDir, pinnedData.AddrOfPinnedObject(), false);
var offset = Marshal.SizeOf(iconDir);
for (int i = 0; i <= ImageCount - 1; i++)
{
GRPICONDIRENTRY grpEntry = new GRPICONDIRENTRY();
BITMAPINFOHEADER bitmapheader = new BITMAPINFOHEADER();
var pinnedBitmapInfoHeader = GCHandle.Alloc(bitmapheader, GCHandleType.Pinned);
Marshal.Copy(ImageData(i), 0, pinnedBitmapInfoHeader.AddrOfPinnedObject(), Marshal.SizeOf(typeof(BITMAPINFOHEADER)));
pinnedBitmapInfoHeader.Free();
grpEntry.Width = iconEntry[i].Width;
grpEntry.Height = iconEntry[i].Height;
grpEntry.ColorCount = iconEntry[i].ColorCount;
grpEntry.Reserved = iconEntry[i].Reserved;
grpEntry.Planes = bitmapheader.Planes;
grpEntry.BitCount = bitmapheader.BitCount;
grpEntry.BytesInRes = iconEntry[i].BytesInRes;
grpEntry.ID = Convert.ToUInt16(iconBaseID + i);
Marshal.StructureToPtr(grpEntry, new IntPtr(pinnedData.AddrOfPinnedObject().ToInt64() + offset), false);
offset += Marshal.SizeOf(typeof(GRPICONDIRENTRY));
}
pinnedData.Free();
return data;
}
}
}
}
| 1ookup/xRAT | Server/Core/Build/IconInjector.cs | C# | gpl-3.0 | 9,721 |
/**
* Copyright (C) 2007-2012 Hypertable, Inc.
*
* This file is part of Hypertable.
*
* Hypertable 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 any later version.
*
* Hypertable 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.
*/
package org.hypertable.examples.PerformanceTest;
import java.nio.ByteBuffer;
import org.hypertable.AsyncComm.Serialization;
public class Result {
public int encodedLength() {
return 48;
}
public void encode(ByteBuffer buf) {
buf.putLong(itemsSubmitted);
buf.putLong(itemsReturned);
buf.putLong(requestCount);
buf.putLong(valueBytesReturned);
buf.putLong(elapsedMillis);
buf.putLong(cumulativeLatency);
}
public void decode(ByteBuffer buf) {
itemsSubmitted = buf.getLong();
itemsReturned = buf.getLong();
requestCount = buf.getLong();
valueBytesReturned = buf.getLong();
elapsedMillis = buf.getLong();
cumulativeLatency = buf.getLong();
}
public String toString() {
return new String("(items-submitted=" + itemsSubmitted + ", items-returned=" + itemsReturned +
"requestCount=" + requestCount + "value-bytes-returned=" + valueBytesReturned +
", elapsed-millis=" + elapsedMillis + ", cumulativeLatency=" + cumulativeLatency + ")");
}
public long itemsSubmitted = 0;
public long itemsReturned = 0;
public long requestCount = 0;
public long valueBytesReturned = 0;
public long elapsedMillis = 0;
public long cumulativeLatency = 0;
}
| deniskin82/hypertable | examples/java/org/hypertable/examples/PerformanceTest/Result.java | Java | gpl-3.0 | 2,057 |
<!doctype html>
<html>
<head>
<title>Sudoku Client</title>
<script src="js/snappyjs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="js/realTimeChartMulti.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-UQiGfs9ICog+LwheBSRCt1o5cbyKIHbwjWscjemyBMT9YCUMZffs6UqUTd0hObXD" crossorigin="anonymous">
<link rel="stylesheet" href="jsclient.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="myApp">
<p>
<form class="pure-form">
<a id="btnRegister" class="pure-button pure-button-primary" href="#">Register as GUI</a>
<a id="btnUnregister" class="pure-button pure-button-primary" href="#">Unregister</a>
<a id="btnPing" class="pure-button pure-button-primary" href="#">Ping</a>
<a id="btnSolve" class="pure-button pure-button-primary" href="#">Solve</a>
<a id="btnGenerate" class="pure-button pure-button-primary" href="#">Generate</a>
<input id="sudokuSize" class="pure-input-rounded" style="text-align: center;" size=3/>
<input id="sudokuDiff" class="pure-input-rounded" style="text-align: center;" size=1/>
<a id="btnCreateSudoku" class="pure-button pure-button-primary" href="#">Create Sudoku</a>
<a id="btnRndSudoku" class="pure-button pure-button-primary" href="#">Randomize Sudoku</a>
</form>
</p>
<hr>
<p>
<form class="pure-form">
<a id="btnShowSolve" class="pure-button button-error" href="#">Show Solve Messages</a>
<a id="btnShowLog" class="pure-button button-error" href="#">Show Log Messages</a>
</form>
</p>
<hr>
<div id="sudoku"></div>
<hr>
<div id="viewDiv"></div>
<hr>
<div id="myConsole"></div>
</div>
<script src="js/app.js"></script>
</body>
</html>
| jaschaknack/ct_ws1617_project | JSClient/index.html | HTML | gpl-3.0 | 1,910 |
#!/usr/bin/env bash
# This file is part of RetroPie.
#
# (c) Copyright 2012-2015 Florian Müller ([email protected])
#
# See the LICENSE.md file at the top-level directory of this distribution and
# at https://raw.githubusercontent.com/petrockblog/RetroPie-Setup/master/LICENSE.md.
#
rp_module_id="disabletimeouts"
rp_module_desc="Disable system timeouts"
rp_module_menus="2+"
rp_module_flags="nobin"
function install_disabletimeouts() {
sed -i 's/BLANK_TIME=30/BLANK_TIME=0/g' /etc/kbd/config
sed -i 's/POWERDOWN_TIME=30/POWERDOWN_TIME=0/g' /etc/kbd/config
}
| free5ty1e/RetroPie-Setup | scriptmodules/supplementary/disabletimeouts.sh | Shell | gpl-3.0 | 582 |
#ifndef JME_RpcHandler_h__
#define JME_RpcHandler_h__
#include <string>
#include <map>
#include "boost/shared_ptr.hpp"
#include "boost/function.hpp"
#include "google/protobuf/message.h"
#include "log/JME_GLog.h"
using namespace std;
namespace JMEngine
{
namespace rpc
{
class RpcHandlerInterface
{
public:
typedef boost::shared_ptr<RpcHandlerInterface> RpcHandlerInterfacePtr;
//rpc´¦Àíº¯Êýº¯Êý ¸ºÔð·ÖÅä ·µ»ØMessage, rpc·þÎñ²à¸ºÔðÊÍ·ÅMessage
typedef boost::function<google::protobuf::Message*(const string& params)> RpcHandler;
public:
static RpcHandlerInterface::RpcHandlerInterfacePtr create();
static void regRpcHandler(const char* method, RpcHandler handler);
static google::protobuf::Message* execRpcHandler(const string& method, const string& params);
private:
static map<string, RpcHandlerInterface::RpcHandler>& getRpcHandler();
};
}
}
#endif // JME_RpcHandler_h__
| jimmy0313/JMEngine | include/rpc/JME_RpcHandler.h | C | gpl-3.0 | 950 |
////////////////////////////////////////////////////////////////////////////////
// Filename: TrackingCameraScript.h
////////////////////////////////////////////////////////////////////////////////
#pragma once
//////////////
// INCLUDES //
//////////////
///////////////////////
// MY CLASS INCLUDES //
///////////////////////
#include "Script.h"
#include "Camera.h"
#include "Transform.h"
////////////////
// NAMESPACES //
////////////////
using namespace dg;
class TrackingCameraScript : public Script {
public:
TrackingCameraScript(SceneObject* target, float distanceToTarget = 20.0f)
: Script("TrackingCameraScript") {
m_Target = target;
m_Camera = Camera::ActiveCamera();
m_DistanceToTarget = distanceToTarget;
}
virtual void OnActivate() {
m_TargetTransform = GetComponentType(m_Target, Transform);
}
virtual void Update() {
vec3 newPosition = m_TargetTransform->GetPosition();
newPosition.z -= m_DistanceToTarget;
newPosition.y += 5.0f;
m_Camera->SetPosition(newPosition);
}
private:
SceneObject* m_Target;
Transform* m_TargetTransform;
Camera* m_Camera;
float m_DistanceToTarget;
};
| Aloisius92/DgEngine | DgEngine/Source/TrackingCameraScript.h | C | gpl-3.0 | 1,134 |
<?php
/**
* @package Projectlog.Administrator
* @subpackage com_projectlog
*
* @copyright Copyright (C) 2009 - 2016 The Thinkery, LLC. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined( '_JEXEC' ) or die( 'Restricted access');
jimport('joomla.application.component.controller');
jimport('joomla.log.log');
class ProjectlogControllerAjax extends JControllerLegacy
{
/**
* Get json encoded list of DB values
*
* @param string $field DB field to filter *
* @param string $token Joomla token
*
* @return json_encoded list of values
*/
public function autoComplete()
{
// Check for request forgeries
JSession::checkToken('get') or die( 'Invalid Token');
$field = JRequest::getString('field');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('DISTINCT '.$db->quoteName($field))
->from('#__projectlog_projects')
->groupby($db->quoteName($field));
$db->setQuery($query);
$data = $db->loadColumn();
echo new JResponseJson($data);
}
/**
* Add a new log via the project logs tab
*
* @return JResponseJson result of ajax request
*/
public function addLog()
{
// Check for request forgeries
JSession::checkToken('get') or die( 'Invalid Token');
$app = JFactory::getApplication();
$data = JRequest::get('post');
$user = JFactory::getUser();
$clientmodel = (JFactory::getApplication()->getName() == 'site') ? 'Logform' : 'Log';
$model = $this->getModel($clientmodel);
$currdate = JFactory::getDate()->toSql();
$gravatar = projectlogHtml::getGravatar($user->get('email'));
$data['associations'] = array();
$data['published'] = 1;
$data['created_by'] = $user->get('id');
$data['language'] = JFactory::getLanguage()->getTag();
if(!$data['language']) $data['language'] = '*';
try
{
$result = false;
if($model->save($data)){
$new_log =
'<div class="plitem-cnt">
'.$gravatar["image"].'
<div class="theplitem">
<h5>'.$data['title'].'</h5>
<br/>
<p>'.$data['description'].'</p>
<p data-utime="1371248446" class="small plitem-dt">
'.$user->get('name').' - '.JHtml::date($currdate, JText::_('DATE_FORMAT_LC2')).'
</p>
</div>
</div>';
//$app->enqueueMessage(JText::_('COM_PROJECTLOG_SUCCESS'));
echo new JResponseJson($new_log);
return;
}
echo new JResponseJson($result, $model->getError());
return;
}
catch(Exception $e)
{
echo new JResponseJson($e);
}
}
/**
* Delete a log via the project logs tab
*
* @return JResponseJson result of ajax request
*/
public function deleteLog()
{
// Check for request forgeries
JSession::checkToken('get') or die( 'Invalid Token');
$data = JRequest::get('post');
$log_id = (int)$data['log_id'];
$clientmodel = (JFactory::getApplication()->getName() == 'site') ? 'Logform' : 'Log';
$model = $this->getModel($clientmodel);
try{
$result = false;
if($model->delete($log_id)){
echo new JResponseJson($log_id);
}
else
{
echo new JResponseJson($result, $model->getError());
}
}
catch(Exception $e)
{
echo new JResponseJson($e);
}
}
/**
* Delete a document via the project docs tab
*
* @return JResponseJson result of ajax request
*/
public function deleteDoc()
{
// Check for request forgeries
JSession::checkToken('get') or die( 'Invalid Token');
$data = JRequest::get('post');
$doc_id = (int)$data['doc_id'];
$clientmodel = (JFactory::getApplication()->getName() == 'site') ? 'Docform' : 'Doc';
$model = $this->getModel($clientmodel);
try{
$result = false;
if($model->delete($doc_id)){
echo new JResponseJson($doc_id);
}
else
{
echo new JResponseJson($result, $model->getError());
}
}
catch(Exception $e)
{
echo new JResponseJson($e);
}
}
}
?>
| thinkerytim/ProjectLog | admin/controllers/ajax.json.php | PHP | gpl-3.0 | 5,016 |
$('.attach_detach').on('click', function(){
var device_id = $(this).attr('device_id');
$('#device_id').val(device_id);
});
$('.detach_customer').on('click', function(){
//get the attached customer name
var customer_name = $(this).attr('cust_name');
if(confirm('Are you sure you want to detach('+customer_name+') from the device?')){
return true;
}else{
return false;
}
}); | toxicaliens/rental | src/js/allocate_devices.js | JavaScript | gpl-3.0 | 399 |
#include <psp2/display.h>
#include <psp2/io/fcntl.h>
#include <psp2/kernel/processmgr.h>
#include <stdio.h> // sprintf()
#include <psp2/ctrl.h> // sceCtrl*()
#include "graphics.h"
#define VER_MAJOR 0
#define VER_MINOR 9
#define VER_BUILD ""
#define VAL_LENGTH 0x10
#define VAL_PUBLIC 0x0A
#define VAL_PRIVATE 0x06
#define printf psvDebugScreenPrintf
int _vshSblAimgrGetConsoleId(char CID[32]);
/*
Model: Proto, SKU: DEM-3000, MoBo: IRT-001/IRT-002;
Model: FatWF, SKU: PCH-1000, MoBo: IRS-002/IRS-1001;
Model: Fat3G, SKU: PCH-1100, MoBo: IRS-002/IRS-1001;
Model: Slim, SKU: PCH-2000, MoBo: USS-1001/USS-1002;
Model: TV, SKU: VTE-1000, MoBo: DOL-1001/DOL-1002.
No diff between FatWF and Fat3G.
No diff between Vita TV (Asian) and PSTV (Western).
*/
SceCtrlData pad;
void ExitCross(char*text)
{
printf("%s, press X to exit...\n", text);
do
{
sceCtrlReadBufferPositive(0, &pad, 1);
sceKernelDelayThread(0.05*1000*1000);
}
while(!(pad.buttons & SCE_CTRL_CROSS));
sceKernelExitProcess(0);
}
void ExitError(char*text, int delay, int error)
{
printf(text, error);
sceKernelDelayThread(delay*1000*1000);
sceKernelExitProcess(0);
}
int WriteFile(char*file, void*buf, int size)
{
sceIoRemove(file);
SceUID fd = sceIoOpen(file, SCE_O_WRONLY | SCE_O_CREAT | SCE_O_TRUNC, 0777);
if (fd < 0)
return fd;
int written = sceIoWrite(fd, buf, size);
sceIoClose(fd);
return written;
}
int main(int argc, char *argv[])
{
int i = 0;
int paranoid = 0;
char idps_buffer[16];
unsigned char idps_text_char_tmp[1];
unsigned char idps_text_char_1st[1];
unsigned char idps_text_char_2nd[1];
char idps_text_buffer[32] = "";
for (i = 0; i < 1000; i++) {
sceCtrlReadBufferPositive(0, &pad, 1);
if (pad.buttons & SCE_CTRL_LTRIGGER)
paranoid = 1;
sceKernelDelayThread(1000);
}
psvDebugScreenInit();
psvDebugScreenClear(0);
printf("PSV IDPS Dumper v%i.%i%s by Yoti\n\n", VER_MAJOR, VER_MINOR, VER_BUILD);
#if (VAL_PUBLIC + VAL_PRIVATE != 0x10)
#error IDPS Lenght must be 16 bytes long!
#endif
_vshSblAimgrGetConsoleId(idps_buffer);
printf(" Your IDPS is: ");
for (i=0; i<VAL_PUBLIC; i++)
{
if (i == 0x04)
psvDebugScreenSetFgColor(0xFF0000FF); // red #1
else if (i == 0x05)
psvDebugScreenSetFgColor(0xFFFF0000); // blue #2
else if (i == 0x06)
psvDebugScreenSetFgColor(0xFF0000FF); // red #3
else if (i == 0x07)
psvDebugScreenSetFgColor(0xFF00FF00); // green #4
else
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
printf("%02X", (u8)idps_buffer[i]);
}
if (paranoid == 1)
{
for (i=0; i<VAL_PRIVATE; i++)
{
psvDebugScreenSetFgColor(0xFF777777); // gray
printf("XX");
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
}
}
else
{
for (i=0; i<VAL_PRIVATE; i++)
{
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
printf("%02X", (u8)idps_buffer[VAL_PUBLIC+i]);
}
}
printf("\n\n");
printf(" It seems that you are using ");
psvDebugScreenSetFgColor(0xFF0000FF); // red
if (idps_buffer[0x04] == 0x00)
printf("PlayStation Portable");
else if (idps_buffer[0x04] == 0x01) // psv, vtv/pstv
{
if (idps_buffer[0x06] == 0x00)
printf("PlayStation Vita"); // fatWF/fat3G, slim
else if (idps_buffer[0x06] == 0x02)
printf("PlayStation/Vita TV"); // vtv, pstv
else if (idps_buffer[0x06] == 0x06)
printf("PlayStation/Vita TV"); // vtv, pstv (testkit)
else
printf("Unknown Vita 0x%02X", idps_buffer[0x06]);
}
else
printf("Unknown PS 0x%02X", idps_buffer[0x04]);
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
printf("\n");
printf(" Your motherboard is ");
psvDebugScreenSetFgColor(0xFF00FF00); // green
if (idps_buffer[0x06] == 0x00) // portable
{
switch(idps_buffer[0x07])
{
case 0x01:
printf("TA-079/081 (PSP-1000)");
break;
case 0x02:
printf("TA-082/086 (PSP-1000)");
break;
case 0x03:
printf("TA-085/088 (PSP-2000)");
break;
case 0x04:
printf("TA-090/092 (PSP-3000)");
break;
case 0x05:
printf("TA-091 (PSP-N1000)");
break;
case 0x06:
printf("TA-093 (PSP-3000)");
break;
//case 0x07:
// printf("TA-094 (PSP-N1000)");
// break;
case 0x08:
printf("TA-095 (PSP-3000)");
break;
case 0x09:
printf("TA-096/097 (PSP-E1000)");
break;
case 0x10:
printf("IRS-002 (PCH-1000/1100)");
break;
case 0x11: // 3G?
case 0x12: // WF?
printf("IRS-1001 (PCH-1000/1100)");
break;
case 0x14:
printf("USS-1001 (PCH-2000)");
break;
case 0x18:
printf("USS-1002 (PCH-2000)");
break;
default:
printf("Unknown MoBo 0x%02X", idps_buffer[0x07]);
break;
}
}
else if ((idps_buffer[0x06] == 0x02) || (idps_buffer[0x06] == 0x06)) // home system
{
switch(idps_buffer[0x07])
{
case 0x01:
printf("DOL-1001 (VTE-1000)");
break;
case 0x02:
printf("DOL-1002 (VTE-1000)");
break;
default:
printf("Unknown MoBo 0x%02X", idps_buffer[0x07]);
break;
}
}
else
printf("Unknown type 0x%02X", idps_buffer[0x06]);
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
printf("\n");
printf(" And your region is ");
psvDebugScreenSetFgColor(0xFFFF0000); // blue
switch(idps_buffer[0x05])
{
case 0x00:
printf("Proto");
break;
case 0x01:
printf("DevKit");
break;
case 0x02:
printf("TestKit");
break;
case 0x03:
printf("Japan");
break;
case 0x04:
printf("North America");
break;
case 0x05:
printf("Europe/East/Africa");
break;
case 0x06:
printf("Korea");
break;
case 0x07: // PCH-xx03 VTE-1016
printf("Great Britain/United Kingdom");
break;
case 0x08:
printf("Mexica/Latin America");
break;
case 0x09:
printf("Australia/New Zeland");
break;
case 0x0A:
printf("Hong Kong/Singapore");
break;
case 0x0B:
printf("Taiwan");
break;
case 0x0C:
printf("Russia");
break;
case 0x0D:
printf("China");
break;
default:
printf("Unknown region 0x%02X", idps_buffer[0x05]);
break;
}
psvDebugScreenSetFgColor(0xFFFFFFFF); // white
printf("\n\n");
// binary
printf(" Saving as ux0:data/idps.bin... ");
if (WriteFile("ux0:data/idps.bin", idps_buffer, 16) > 0)
printf("OK");
else
printf("NG");
printf("\n");
// text
for (i=0; i<0x10; i++)
{
idps_text_char_tmp[1]=idps_buffer[i];
idps_text_char_1st[1]=(idps_text_char_tmp[1] & 0xf0) >> 4;
idps_text_char_2nd[1]=(idps_text_char_tmp[1] & 0x0f);
// 1st half of byte
if (idps_text_char_1st[1] < 0xA) // digit
sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_1st[1]+0x30);
else // char
sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_1st[1]+0x37);
// 2nd half of byte
if (idps_text_char_2nd[1] < 0xA) // digit
sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_2nd[1]+0x30);
else // char
sprintf(idps_text_buffer, "%s%c", idps_text_buffer, idps_text_char_2nd[1]+0x37);
}
printf(" Saving as ux0:data/idps.txt... ");
if (WriteFile("ux0:data/idps.txt", idps_text_buffer, 32) > 0)
printf("OK");
else
printf("NG");
printf("\n\n");
printf(" https://github.com/yoti/psv_idpsdump/\n");
ExitCross("\nDone");
return 0;
}
| Yoti/psv_idpsdump | main.c | C | gpl-3.0 | 7,135 |
var gulp = require('gulp')
var mocha = require('gulp-mocha')
var nodemon = require('gulp-nodemon')
var env = require('gulp-env');
gulp.task('API-Server', (cb) => {
let started = false
env({
vars: {
httpPort: 8080
}
});
return nodemon({
script: 'index.js'
})
.on('start', () => {
if (!started) {
started = true
return cb()
}
})
.on('restart', () => {
console.log('restarting')
})
})
gulp.task('test', ['API-Server'], function() {
return gulp.src('./test/index.js')
.pipe(mocha())
.once('error', function() {
process.exit(1)
})
.once('end', function() {
process.exit()
})
})
| HeyYZU/HeyYZU-server | gulpfile.js | JavaScript | gpl-3.0 | 690 |
#region License, Terms and Conditions
//
// Jayrock - A JSON-RPC implementation for the Microsoft .NET Framework
// Written by Atif Aziz (www.raboof.com)
// Copyright (c) Atif Aziz. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option)
// any later version.
//
// 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 Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace Jayrock
{
#region Imports
using System;
using System.Reflection;
using Jayrock.Tests;
using NUnit.Framework;
#endregion
[ TestFixture ]
public class TestTypeResolution : TestUtilityBase
{
private TypeResolutionHandler _initialCurrent;
[ SetUp ]
public void Init()
{
_initialCurrent = TypeResolution.Current;
}
[ TearDown ]
public void Dispose()
{
TypeResolution.Current = _initialCurrent;
}
[ Test ]
public void Default()
{
Assert.IsNotNull(TypeResolution.Default);
}
[ Test ]
public void Current()
{
Assert.IsNotNull(TypeResolution.Current);
Assert.AreSame(TypeResolution.Default, TypeResolution.Current);
}
[ Test, ExpectedException(typeof(ArgumentNullException)) ]
public void CannotSetCurrentToNull()
{
TypeResolution.Current = null;
}
[ Test ]
public void SetCurrent()
{
TypeResolutionHandler handler = new TypeResolutionHandler(DummyGetType);
TypeResolution.Current = handler;
Assert.AreSame(handler, TypeResolution.Current);
}
[ Test ]
public void FindTypeResolution()
{
TestTypeResolver resolver = new TestTypeResolver(typeof(object));
TypeResolution.Current = new TypeResolutionHandler(resolver.Resolve);
Assert.AreSame(typeof(object), TypeResolution.FindType("obj"));
Assert.AreEqual("obj", resolver.LastTypeName, "typeName");
Assert.AreEqual(false, resolver.LastThrowOnError, "throwOnError");
Assert.AreEqual(false, resolver.LastIgnoreCase, "ignoreCase");
}
[ Test ]
public void GetTypeResolution()
{
TestTypeResolver resolver = new TestTypeResolver(typeof(object));
TypeResolution.Current = new TypeResolutionHandler(resolver.Resolve);
Assert.AreSame(typeof(object), TypeResolution.GetType("obj"));
Assert.AreEqual("obj", resolver.LastTypeName, "typeName");
Assert.AreEqual(true, resolver.LastThrowOnError, "throwOnError");
Assert.AreEqual(false, resolver.LastIgnoreCase, "ignoreCase");
}
private static Type DummyGetType(string typeName, bool throwOnError, bool ignoreCase)
{
throw new NotImplementedException();
}
private sealed class TestTypeResolver
{
public string LastTypeName;
public bool LastThrowOnError;
public bool LastIgnoreCase;
public Type NextResult;
public TestTypeResolver(Type nextResult)
{
NextResult = nextResult;
}
public Type Resolve(string typeName, bool throwOnError, bool ignoreCase)
{
LastTypeName = typeName;
LastThrowOnError = throwOnError;
LastIgnoreCase = ignoreCase;
return NextResult;
}
}
}
} | atifaziz/Jayrock | tests/Jayrock/TestTypeResolution.cs | C# | gpl-3.0 | 4,130 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 13.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V14
65536
65548
65549
65575
65576
65595
65596
65598
65599
65614
65616
65630
65664
65787
END
| Ascoware/get-iplayer-automator | Binaries/get_iplayer/perl/lib/5.32.0/unicore/lib/Sc/Linb.pl | Perl | gpl-3.0 | 575 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2015 Leslie Zhai <[email protected]>
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <glib.h>
#include <glib/gstdio.h>
int main(int argc, char *argv[])
{
char *path = argv[1];
struct stat buf;
if (lstat(path, &buf) == -1) {
printf("ERROR: failed to get %s lstat\n", path);
return 0;
}
switch (buf.st_mode & S_IFMT) {
case S_IFDIR:
printf("DEBUG: line %d %s is directory\n", __LINE__, path);
break;
case S_IFLNK:
printf("DEBUG: line %d %s is symbolic link\n", __LINE__, path);
break;
case S_IFREG:
printf("DEBUG: line %d %s is regular file\n", __LINE__, path);
break;
default:
break;
}
if (g_file_test(path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_SYMLINK))
printf("DEBUG: line %d %s is symbolic link\n", __LINE__, path);
return 0;
}
| LeetcodeCN/leetcodecn.github.io | src/stat/hello-stat.c | C | gpl-3.0 | 1,716 |
<!DOCTYPE HTML PUBLIC "
-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>023</title>
<meta http-equiv="CONTENT-LANGUAGE" CONTENT="PL">
<meta http-equiv="content-type" CONTENT="text/html; CHARSET=iso-8859-2">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head><body><script>
document.write("<h1>023</h1>");
liczba=10
while(liczba!=0) {
document.write(liczba)
document.write("<br>")
liczba--
}
</script></body></html> | slawomirszwan/slawomirszwan.github.io | javascript/ebook/javascript-i-jquery-131-praktycznych-skryptow-witold-wrotek/023d.html | HTML | gpl-3.0 | 483 |
//# ShapeletCoherence.h: Spatial coherence function of a source modelled as a
//# shapelet basis expansion.
//#
//# Copyright (C) 2008
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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.
//#
//# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id: ShapeletCoherence.h 14789 2010-01-13 12:39:15Z zwieten $
#ifndef LOFAR_BBSKERNEL_EXPR_SHAPELETCOHERENCE_H
#define LOFAR_BBSKERNEL_EXPR_SHAPELETCOHERENCE_H
// \file
// Spatial coherence function of a source modelled as a shapelet basis
// expansion.
#include <BBSKernel/Expr/BasicExpr.h>
#include <Common/lofar_complex.h>
#include <casacore/casa/Arrays.h>
namespace LOFAR
{
namespace BBS
{
// \addtogroup Expr
// @{
class ShapeletCoherence: public BasicTernaryExpr<Vector<4>, Vector<3>,
Vector<3>, JonesMatrix>
{
public:
typedef shared_ptr<ShapeletCoherence> Ptr;
typedef shared_ptr<const ShapeletCoherence> ConstPtr;
ShapeletCoherence(const Expr<Vector<4> >::ConstPtr stokes, double scaleI,
const casacore::Array<double> &coeffI,
const Expr<Vector<3> >::ConstPtr &uvwA,
const Expr<Vector<3> >::ConstPtr &uvwB);
protected:
virtual const JonesMatrix::View evaluateImpl(const Grid &grid,
const Vector<4>::View &stokes, const Vector<3>::View &uvwA,
const Vector<3>::View &uvwB) const;
virtual const JonesMatrix::View evaluateImplI(const Grid &grid,
const Vector<4>::View &stokes, double scaleI,
const casacore::Array<double> &coeffI, const Vector<3>::View &uvwA,
const Vector<3>::View &uvwB) const;
double itsShapeletScaleI_;
casacore::Array<double> itsShapeletCoeffI_;
};
// @}
} // namespace BBS
} // namespace LOFAR
#endif
| kernsuite-debian/lofar | CEP/Calibration/BBSKernel/include/BBSKernel/Expr/ShapeletCoherence.h | C | gpl-3.0 | 2,451 |
MODX Evolution 1.1 = 07452b3a1b6754a6861e6c36f1cd3e62
| gohdan/DFC | known_files/hashes/assets/plugins/managermanager/widgets/ddfillmenuindex/ddfillmenuindex.php | PHP | gpl-3.0 | 54 |
Bitrix 16.5 Business Demo = b10b46488015710ddcf5f4d0217eea77
| gohdan/DFC | known_files/hashes/bitrix/modules/main/interface/settings_admin_list.php | PHP | gpl-3.0 | 61 |
<?php
/*
This file is part of Vosbox.
Vosbox 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.
Vosbox 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 Vosbox. If not, see <http://www.gnu.org/licenses/>.
Vosbox copyright Callan Bryant 2011-2012 <[email protected]> http://callanbryant.co.uk/
*/
/*
produces an abject containing metadata of an mp3 file
define ('GETID3_INCLUDEPATH', ROOT_DIR.'/getid3/');
*/
require_once __DIR__.'/constants.php';
require_once __DIR__.'/VSE/keyStore.class.php';
require_once GETID3_INCLUDEPATH.'/getid3.php';
class audioFile
{
public $title,$artist,$album,$year,$genre,$id,$time;
protected $path;
// id of blob in keystore in namespace 'albumArt'
// for album cover art, if any
public $albumArtId = null;
public $count = 0;
// output from getid3 (removed after use)
private $analysis;
private $dir;
// ... for compariston purposes when multiple songs exist
// integer
protected $quality = 0;
public function __construct($filepath)
{
// force string on filename (when using recursive file iterator,
// objects are returned)
$filepath = (string)$filepath;
if (!extension_loaded('Imagick'))
throw new Exception("Imagic extension required. Not loaded");
if (!file_exists($filepath))
throw new Exception("$filepath not found");
if (!is_readable($filepath))
throw new Exception("permission denied reading $filepath");
$this->path = $filepath;
$this->dir = dirname($filepath).'/';
$getID3 = new getID3();
$this->analysis = $getID3->analyze($filepath);
if (@isset($this->analysis['error']) )
throw new Exception( $this->analysis['error'][0] );
if (!isset($this->analysis['id3v1']) and !isset($this->analysis['id3v2']) )
throw new Exception("no ID3v1 or ID3v2 tags in $filepath");
// aggregate both tag formats (clobbering other metadata)
getid3_lib::CopyTagsToComments($this->analysis);
@$this->title = $this->analysis['comments']['title'][0];
@$this->artist = $this->analysis['comments']['artist'][0];
@$this->year = $this->analysis['comments']['year'][0];
@$this->genre = $this->analysis['comments']['genre'][0];
@$this->album = $this->analysis['comments']['album'][0];
@$seconds = ceil($this->analysis['playtime_seconds']);
@$this->time = floor($seconds/60).':'.str_pad($seconds%60, 2, "0", STR_PAD_LEFT);
if (!$this->title)
throw new Exception("No title found in $filepath");
if (!$this->album)
$this->album = 'Various artists';
$this->assignAlbumArt();
// set an ID relative to metadata
$this->id = md5($this->artist.$this->album.$this->title);
// let's guess quality is proportional to bitrate
@$this->quality = floor($this->analysis['audio']['bitrate']/1000);
// remove the getID3 analysis -- it's massive. It should not be indexed!
unset ($this->analysis);
}
// get and save album art from the best source possible
// then resize it to 128x128 JPG format
private function assignAlbumArt()
{
$k = new keyStore('albumArt');
// generate a potential ID corresponding to this album/artist combination
$id = md5($this->album.$this->artist);
// check for existing art from the same album
// if there, then assign this song that albumn ID
if ($k->get($id))
return $this->albumArtId = $id;
// get an instance of the ImageMagick class to manipulate
// the album art image
$im = new Imagick();
$blob = null;
// look in the ID3v2 tag
if (isset($this->analysis['id3v2']['APIC'][0]['data']))
$blob = &$this->analysis['id3v2']['APIC'][0]['data'];
elseif (isset($this->analysis['id3v2']['PIC'][0]['data']))
$blob = &$this->analysis['id3v2']['PIC'][0]['data'];
// look in containing folder for images
elseif($images = glob($this->dir.'*.{jpg,png}',GLOB_BRACE) )
{
// use file pointers instead of file_get_contents
// to fix a memory leak due to failed re-use of allocated memory
// when loading successivle bigger files
@$h = fopen($images[0], 'rb');
$size = filesize($images[0]);
if ($h === false)
throw new Exception("Could not open cover art: $images[0]");
if (!$size)
// invalid or no image
//throw new Exception("Could not open cover art: $images[0]");
// assign no art
return;
$blob = fread($h,$size);
fclose($h);
}
else
// no albumn art available, assign none
return;
// TODO, if necessary: try amazon web services
// standardise the album art to 128x128 jpg
$im->readImageBlob($blob);
$im->thumbnailImage(128,128);
$im->setImageFormat('jpeg');
$im->setImageCompressionQuality(90);
$blob = $im->getImageBlob();
// save the album art under the generated ID
$k->set($id,$blob);
// assign this song that albumn art ID
$this->albumArtId = $id;
}
public function getPath()
{
return $this->path;
}
public function getQuality()
{
return $this->quality;
}
}
| naggie/vosbox | audioFile.class.php | PHP | gpl-3.0 | 5,333 |
/*
* Created by CSSCatcher plugin for Crawljax
* CSS file is for Crawljax DOM state http://www.employeesolutions.com
* CSS file was contained in index * Downloaded from http://www.employeesolutions.com/assets/template/css/source/helpers/jquery.fancybox-thumbs.css?v=1.0.6
*/
#fancybox-thumbs {
position: fixed;
left: 0;
width: 100%;
overflow: hidden;
z-index: 8050;
}
#fancybox-thumbs.bottom {
bottom: 2px;
}
#fancybox-thumbs.top {
top: 2px;
}
#fancybox-thumbs ul {
position: relative;
list-style: none;
margin: 0;
padding: 0;
}
#fancybox-thumbs ul li {
float: left;
padding: 1px;
opacity: 0.5;
}
#fancybox-thumbs ul li.active {
opacity: 0.75;
padding: 0;
border: 1px solid #fff;
}
#fancybox-thumbs ul li:hover {
opacity: 1;
}
#fancybox-thumbs ul li a {
display: block;
position: relative;
overflow: hidden;
border: 1px solid #222;
background: #111;
outline: none;
}
#fancybox-thumbs ul li img {
display: block;
position: relative;
border: 0;
padding: 0;
} | paNjii/summerschoolOnCompilers | Day1/CSS/src/suites/8b6cc12cdf0ae92cf3e741347de9b1708868bf97.css | CSS | gpl-3.0 | 998 |
<div class= "parametre">
<a href = "parametre.php" onclick="">mon compte</a>
</div>
<div style = "background-color:blue; border:2px solid white; border-radius:25px; padding:1%; font-size:1.5em;" >
<a href = "./deconnect.php">deconnection</a>
</div>
| mysteriou13/protonet | view/divmembre.php | PHP | gpl-3.0 | 258 |
from urllib.request import urlopen
from urllib.parse import urlparse, parse_qs
from socket import error as SocketError
import errno
from bs4 import BeautifulSoup
MAX_PAGES_TO_SEARCH = 3
def parse_news(item):
'''Parse news item
return is a tuple(id, title, url)
'''
url = 'http://www.spa.gov.sa' + item['href']
url_parsed = urlparse(url)
qs = parse_qs(url_parsed[4])
id = qs['newsid'][0]
title = item.h2.contents[0]
title = " ".join(title.split())
item_parsed = (id, title, url)
return item_parsed
def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1):
'''Retrieve news for person or royal
person 1= king, 2= crown prince and 3= deputy crown prince
if royal is = 1 news will be retriveved
if last_id not definend it will return the max
return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url)...]
'''
all_news = []
found = False
page = 1
while (page <= MAX_PAGES_TO_SEARCH and not found):
url = ("http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"
"t={}&royal={}&lang=ar&pg={}".format(person, cabinet, royal, page))
try:
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
news = soup.find_all("a", class_="aNewsTitle")
for item in news:
item_parsed = parse_news(item)
if item_parsed[0] <= str(last_id):
found = True
break
all_news.append(item_parsed)
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise
pass
page = page + 1
return all_news
def retrieve_detail(item):
'''Retrive detaill for news item
return is tuple (id, title, url, text)
'''
url = item[2]
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
detail = soup.find(class_='divNewsDetailsText')
detail = detail.get_text()
_list = list(item)
_list.insert(3, detail)
item = tuple(_list)
return item
def royal_order(last_id=-1):
'''Retrive royal orders
if last_id not defiend it will return the max
return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
orders = []
_news = retrieve_news(royal=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
orders.append(_detail)
return orders
def cabinet_decision(last_id=-1):
'''Retrive cabinet decisions
if last_id not defiend it will return the max
return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10)
[(id, title, url, text)...]
'''
decisions = []
_news = retrieve_news(cabinet=1, last_id=last_id)
for item in _news:
_detail = retrieve_detail(item)
decisions.append(_detail)
return decisions
def arrival_news(person, last_id=-1):
'''Retrive only arrival news for person
if last_id not defiend it will return the max
return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, location)...]
'''
arrival_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يصل إلى' in item[1]:
_list = list(item)
_list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0])
item = tuple(_list)
arrival_news.append(item)
return arrival_news
def leave_news(person, last_id=-1):
'''Retrive only leave news for person
if last_id not defiend it will return the max
return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news)
[(id, title, url, locationFromTo)...]
'''
leave_news = []
all_news = retrieve_news(person=person, last_id= last_id)
for item in all_news:
if 'يغادر' in item[1]:
_list = list(item)
_list.insert(3, item[1].split('يغادر')[1])
item = tuple(_list)
leave_news.append(item)
return leave_news
if __name__ == "__main__":
# just for testing
news = cabinet_decision()
print(news)
| saudisproject/saudi-bots | bots/spa.py | Python | gpl-3.0 | 4,254 |
<?php
/*
* +----------------------------------------------------------------------+
* | PHP Version 4 |
* +----------------------------------------------------------------------+
* | Copyright (c) 2002-2005 Heinrich Stamerjohanns |
* | |
* | getrecord.php -- Utilities for the OAI Data Provider |
* | |
* | This 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 software 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 software; if not, write to the Free Software Foundation, |
* | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
* | |
* +----------------------------------------------------------------------+
* | Derived from work by U. Mόller, HUB Berlin, 2002 |
* | |
* | Written by Heinrich Stamerjohanns, May 2002 |
* | [email protected] |
* +----------------------------------------------------------------------+
*/
//
// $Id: getrecord.php,v 1.02 2003/04/08 14:22:07 stamer Exp $
//
// parse and check arguments
foreach($args as $key => $val) {
switch ($key) {
case 'identifier':
$identifier = $val;
if (!is_valid_uri($identifier)) {
$errors .= oai_error('badArgument', $key, $val);
}
break;
case 'metadataPrefix':
if (is_array($METADATAFORMATS[$val])
&& isset($METADATAFORMATS[$val]['myhandler'])) {
$metadataPrefix = $val;
$inc_record = $METADATAFORMATS[$val]['myhandler'];
} else {
$errors .= oai_error('cannotDisseminateFormat', $key, $val);
}
break;
default:
$errors .= oai_error('badArgument', $key, $val);
}
}
if (!isset($args['identifier'])) {
$errors .= oai_error('missingArgument', 'identifier');
}
if (!isset($args['metadataPrefix'])) {
$errors .= oai_error('missingArgument', 'metadataPrefix');
}
// remove the OAI part to get the identifier
if (empty($errors)) {
$id = str_replace($oaiprefix, '', $identifier);
if ($id == '') {
$errors .= oai_error('idDoesNotExist', '', $identifier);
}
$query = selectallQuery($id);
$res = $db->query($query);
if (DB::isError($res)) {
if ($SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE."<br />";
echo "Query: $query<br />\n";
die($db->errorNative());
} else {
$errors .= oai_error('idDoesNotExist', '', $identifier);
}
} elseif (!$res->numRows()) {
$errors .= oai_error('idDoesNotExist', '', $identifier);
}
}
// break and clean up on error
if ($errors != '') {
oai_exit();
}
$output .= " <GetRecord>\n";
$num_rows = $res->numRows();
if (DB::isError($num_rows)) {
if ($SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE."<br />";
echo "Query: $query<br />\n";
die($db->errorNative());
}
}
if ($num_rows) {
$record = $res->fetchRow();
if (DB::isError($record)) {
if ($SHOW_QUERY_ERROR) {
echo __FILE__.','.__LINE."<br />";
die($db->errorNative());
}
}
$identifier = $oaiprefix.$record[$SQL['identifier']];;
$datestamp = formatDatestamp($record[$SQL['datestamp']]);
if (isset($record[$SQL['deleted']]) && ($record[$SQL['deleted']] == 'true') &&
($deletedRecord == 'transient' || $deletedRecord == 'persistent')) {
$status_deleted = TRUE;
} else {
$status_deleted = FALSE;
}
// print Header
$output .=
' <record>'."\n";
$output .=
' <header';
if ($status_deleted) {
$output .= ' status="deleted"';
}
$output .='>'."\n";
// use xmlrecord since we include stuff from database;
$output .= xmlrecord($identifier, 'identifier', '', 3);
$output .= xmlformat($datestamp, 'datestamp', '', 3);
if (!$status_deleted)
$output .= xmlrecord($record[$SQL['set']], 'setSpec', '', 3);
$output .=
' </header>'."\n";
// return the metadata record itself
if (!$status_deleted)
include('lib/'.$inc_record);
$output .=
' </record>'."\n";
}
else {
// we should never get here
oai_error('idDoesNotExist');
}
// End GetRecord
$output .=
' </GetRecord>'."\n";
$output = utf8_decode($output);
?> | agroknow/agrimoodle | blocks/oai_target/target/lib/getrecord.php | PHP | gpl-3.0 | 5,027 |
SUBROUTINE CHR_ITOC( IVALUE, STRING, NCHAR )
*+
* Name:
* CHR_ITOC
* Purpose:
* Encode an INTEGER value as a string.
* Language:
* Starlink Fortran 77
* Invocation:
* CALL CHR_ITOC( IVALUE, STRING, NCHAR )
* Description:
* Encode an integer value as a (decimal) character string, using as
* concise a format as possible, and return the number of characters
* used. In the event of an error, '*'s will be written into to the
* string.
* Arguments:
* IVALUE = INTEGER (Given)
* The value to be encoded.
* STRING = CHARACTER * ( * ) (Returned)
* The string into which the integer value is encoded.
* NCHAR = INTEGER (Returned)
* The field width used in encoding the value.
* Copyright:
* Copyright (C) 1983, 1984, 1988, 1989, 1994 Science & Engineering Research Council.
* All Rights Reserved.
* Licence:
* 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., 51 Franklin Street,Fifth Floor, Boston, MA
* 02110-1301, USA
* Authors:
* JRG: Jack Giddings (UCL)
* ACD: A.C. Davenhall (ROE)
* AJC: A.J. Chipperfield (STARLINK)
* PCTR: P.C.T. Rees (STARLINK)
* ACC: A.C. Charles (STARLINK)
* {enter_new_authors_here}
* History:
* 3-JAN-1983 (JRG):
* Original version.
* 16-NOV-1984 (ACD):
* Documentation improved.
* 1-SEP-1988 (AJC):
* Use LEN instead of CHR_SIZE.
* 3-OCT-1988 (AJC):
* Remove termination to declared length of STRING.
* Improve documentation.
* 14-JUN-1989 (AJC):
* Use field of minimum size/precision and CHR_LDBLK not RMBLK.
* 10-MAR-1994 (ACC for PCTR):
* Modifications to prologue.
* {enter_further_changes_here}
* Bugs:
* {note_any_bugs_here}
*-
* Type Definitions:
IMPLICIT NONE ! No implicit typing
* Arguments Given:
INTEGER IVALUE
* Arguments Returned:
CHARACTER STRING * ( * )
INTEGER NCHAR
* External References:
INTEGER CHR_LEN ! String length (ignoring trailing blanks)
* Local Constants:
INTEGER MXPREC ! Maximum number of digits in integer
PARAMETER ( MXPREC = 11 )
* Local Variables:
INTEGER IOSTAT ! Local status
INTEGER FIELD ! Character count
INTEGER SIZE ! Declared length of the returned string
CHARACTER FORMAT * 10 ! Fortran 77 format string
*.
* Get the declared length of the returned string.
SIZE = LEN( STRING )
* Calculate the field size for the internal write statement.
FIELD = MIN( SIZE, MXPREC )
* Construct the FORMAT statement for the internal WRITE.
WRITE ( FORMAT, '(''(I'',I3,'')'')', IOSTAT=IOSTAT ) FIELD
* Trap errors.
IF ( IOSTAT .EQ. 0 ) THEN
* Perform the internal WRITE.
WRITE ( STRING, FORMAT, IOSTAT=IOSTAT ) IVALUE
* Trap errors.
IF ( IOSTAT .EQ. 0 ) THEN
* Remove the leading spaces - the remainder was cleared by the
* WRITE statement.
CALL CHR_LDBLK( STRING( 1 : FIELD ) )
NCHAR = CHR_LEN( STRING( 1 : FIELD ) )
ELSE
* On error, fill the returned string with '*'s.
CALL CHR_FILL( '*', STRING )
NCHAR = SIZE
END IF
ELSE
* On error, fill the returned string with '*'s.
CALL CHR_FILL( '*', STRING )
NCHAR = SIZE
END IF
END
| timj/starlink-pyndf | chr/chr_itoc.f | FORTRAN | gpl-3.0 | 4,075 |
# ScreenTrooper
Remote Configurable Slideshow
| tedr56/ScreenTrooper | README.md | Markdown | gpl-3.0 | 46 |
import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Allows user to enter commands '''
def __init__(self,prompt='[$] '):
self._prompt = prompt
self._at = ''
def poll(self,wait_s=None,uid=None):
try:
prompt = str(self._at)+str(self._prompt)
msg = raw_input(prompt)
if msg == '':
self._at = ''
return []
if msg[0] == '@':
self._at = msg.split()[0]+' '
else:
msg = self._at+msg
return [msg]
except Exception as e:
print(repr(e))
return []
def subscribe(self,*uids):
pass
class Script:
''' Runs a script passed as a list, default frequency = 1000Hz '''
def __init__(self,msgs):
self._msgs = msgs
self._index = 0
self._period = 0.001
self._pid = 'SCRIPT'
def poll(self,wait_s=None,uid=None):
period = self._period if wait_s is None else wait_s
time.sleep(period)
try:
msg = self._msgs[self._index]
print(self._pid+' SEND > '+msg)
self._index += 1
return [msg]
except IndexError:
return []
def subscribe(self,*uids):
for uid in uids:
if uid is not None:
if uid[0] is '@': assert uid[1:] in get_attr(Uid)
else: assert uid in get_attr(Uid)
return self
def load(self,msg_array):
self._msgs += msg_array
return self
def set_period(self,period):
self._period = period
return self
def run(self):
t = threading.current_thread()
self._pid = str(t.ident)+' '+str(t.name)
while len(self.poll()) > 0: pass
def run_async(self):
Thread(target=self.run).start()
if __name__ == '__main__':
Printer('A simple printer: ').send('Just printing a msg to current_thread')
script = [
'@other_uid topic data',
'@other_uid topic',
'uid topic data',
'uid topic'
]
async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]]
async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]]
Script(script).set_period(1).run()
Script(async).set_period(0.15).run_async()
Script(async2).set_period(0.2).run_async() | WritingTechForJarrod/app | src/wtfj/connectors_local.py | Python | gpl-3.0 | 2,202 |
// Copyright (c) 2016 Tristan Colgate-McFarlane
//
// This file is part of hugot.
//
// hugot 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.
//
// hugot 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 hugot. If not, see <http://www.gnu.org/licenses/>.
// Package hugot provides a simple interface for building extensible
// chat bots in an idiomatic go style. It is heavily influenced by
// net/http, and uses an internal message format that is compatible
// with Slack messages.
//
// Note: This package requires go1.7
//
// Adapters
//
// Adapters are used to integrate with external chat systems. Currently
// the following adapters exist:
// slack - github.com/tcolgate/hugot/adapters/slack - for https://slack.com/
// mattermost - github.com/tcolgate/hugot/adapters/mattermost - for https://www.mattermost.org/
// irc - github.com/tcolgate/hugot/adapters/irc - simple irc adapter
// shell - github.com/tcolgate/hugot/adapters/shell - simple readline based adapter
// ssh - github.com/tcolgate/hugot/adapters/ssh - Toy implementation of unauth'd ssh interface
//
// Examples of using these adapters can be found in github.com/tcolgate/hugot/cmd
//
// Handlers
//
// Handlers process messages. There are a several built in handler types:
//
// - Plain Handlers will execute for every message sent to them.
//
// - Background handlers, are started when a bot is started. They do not
// receive messages but can send them. They are intended to implement long
// lived background tasks that react to external inputs.
//
// - WebHook handlers can be used to implement web hooks by adding the bot to a
// http.ServeMux. A URL is built from the name of the handler.
//
// In addition to these basic handlers some more complex handlers are supplied.
//
// - Hears Handlers will execute for any message which matches a given regular
// expression.
//
// - Command Handlers act as command line tools. Message are attempted to be
// processed as a command line. Quoted text is handle as a single argument. The
// passed message can be used as a flag.FlagSet.
//
// - A Mux. The Mux will multiplex message across a set of handlers. In addition,
// a top level "help" Command handler is added to provide help on usage of the
// various handlers added to the Mux.
//
// WARNING: The API is still subject to change.
package hugot
| tcolgate/hugot | doc.go | GO | gpl-3.0 | 2,788 |
#include "shader.h"
#include <iostream>
Shader::Shader(GLuint shader_id)
: shader_id(shader_id) {}
void Shader::use()
{
glUseProgram(shader_id);
}
void Shader::send_cam_pos(glm::vec3 cam_pos)
{
this->cam_pos = cam_pos;
}
void Shader::set_VP(glm::mat4 V, glm::mat4 P)
{
this->V = V;
this->P = P;
}
void Shader::send_mesh_model(glm::mat4 mesh_model)
{
this->mesh_model = mesh_model;
}
void Shader::set_material(Material m) {}
void Shader::draw(Geometry *g, glm::mat4 to_world) {} | jytang/greed_island | src/shader.cpp | C++ | gpl-3.0 | 503 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.