code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
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];
}
}
| Java |
<?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);
| Java |
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/
~~~ | Java |
#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;
}
| Java |
{% 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 %}
| Java |
<?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>
| Java |
/* This file is part of the KDE project
* Copyright (C) 2010 Carlos Licea <carlos@kdab.com>
*
* 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
| Java |
/* This file is part of the KDE project
* Copyright (C) 2009 Elvis Stansvik <elvstone@gmail.com>
*
* 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
| Java |
#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
| Java |
from models import Connection
from django import forms
class ConnectionForm(forms.ModelForm):
class Meta:
model = Connection
exclude = ('d_object_id',)
| Java |
# pedalo | Java |
// 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
}
}
| Java |
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;
}
| Java |
<div class="tablist-content">I am ajax tab content i was pulled in from ajax-content.html </div>
| Java |
# -*- 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)
| Java |
// 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
| Java |
---
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).
| Java |
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
| Java |
# 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()
| Java |
# 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
| Java |
# 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)
| Java |
<?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_');
?> | Java |
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.
| Java |
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.
}
} | Java |
<!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>
| Java |
#!/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
| Java |
/* Test Octagonal_Shape::generalized_affine_image().
Copyright (C) 2001-2009 Roberto Bagnara <bagnara@cs.unipr.it>
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
| Java |
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;
}
}
}
}
| Java |
/**
* 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;
}
| Java |
<!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/purecss@0.6.2/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>
| Java |
#!/usr/bin/env bash
# This file is part of RetroPie.
#
# (c) Copyright 2012-2015 Florian Müller (contact@petrockblock.com)
#
# 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
}
| Java |
#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__
| Java |
////////////////////////////////////////////////////////////////////////////////
// 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;
};
| Java |
<?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);
}
}
}
?>
| Java |
$('.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;
}
}); | Java |
#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;
}
| Java |
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()
})
})
| Java |
#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;
}
}
}
} | Java |
# !!!!!!! 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
| Java |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2015 Leslie Zhai <xiang.zhai@i-soft.com.cn>
*
* 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;
}
| Java |
<!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> | Java |
//# 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
| Java |
MODX Evolution 1.1 = 07452b3a1b6754a6861e6c36f1cd3e62
| Java |
Bitrix 16.5 Business Demo = b10b46488015710ddcf5f4d0217eea77
| Java |
<?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 <callan.bryant@gmail.com> 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;
}
}
| Java |
/*
* 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;
} | Java |
<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>
| Java |
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)
| Java |
<?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 |
* | stamer@uni-oldenburg.de |
* +----------------------------------------------------------------------+
*/
//
// $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);
?> | Java |
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
| Java |
# ScreenTrooper
Remote Configurable Slideshow
| Java |
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() | Java |
// 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
| Java |
#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) {} | Java |
/*
Playdar - music content resolver
Copyright (C) 2009 Richard Jones
Copyright (C) 2009 Last.fm Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __RESOLVED_ITEM_BUILDER_H__
#define __RESOLVED_ITEM_BUILDER_H__
#include "playdar/resolved_item.h"
#include "library.h"
using namespace json_spirit;
namespace playdar {
/*
Builds a ResolvedItem describing something (a song) that can be played.
*/
class ResolvedItemBuilder
{
public:
static void createFromFid(Library& lib, int fid, json_spirit::Object& out)
{
createFromFid( lib.db(), fid, out );
}
static void createFromFid( sqlite3pp::database& db, int fid, Object& out)
{
LibraryFile_ptr file( Library::file_from_fid(db, fid) );
out.push_back( Pair("mimetype", file->mimetype) );
out.push_back( Pair("size", file->size) );
out.push_back( Pair("duration", file->duration) );
out.push_back( Pair("bitrate", file->bitrate) );
artist_ptr artobj = Library::load_artist( db, file->piartid);
track_ptr trkobj = Library::load_track( db, file->pitrkid);
out.push_back( Pair("artist", artobj->name()) );
out.push_back( Pair("track", trkobj->name()) );
// album metadata kinda optional for now
if (file->pialbid) {
album_ptr albobj = Library::load_album(db, file->pialbid);
out.push_back( Pair("album", albobj->name()) );
}
out.push_back( Pair("url", file->url) );
}
};
} // ns
#endif //__RESOLVED_ITEM_BUILDER_H__
| Java |
#region License
//
// GroupableTest.cs
//
// Copyright (C) 2009-2013 Alex Taylor. All Rights Reserved.
//
// This file is part of Digitalis.LDTools.DOM.UnitTests.dll
//
// Digitalis.LDTools.DOM.UnitTests.dll 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.
//
// Digitalis.LDTools.DOM.UnitTests.dll 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 Digitalis.LDTools.DOM.UnitTests.dll. If not, see <http://www.gnu.org/licenses/>.
//
#endregion License
namespace UnitTests
{
#region Usings
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Digitalis.LDTools.DOM;
using Digitalis.LDTools.DOM.API;
#endregion Usings
[TestClass]
public sealed class GroupableTest : IGroupableTest
{
#region Infrastructure
protected override Type TestClassType { get { return typeof(Groupable); } }
protected override IGroupable CreateTestGroupable()
{
return new MockGroupable();
}
#endregion Infrastructure
#region Definition Test
[TestMethod]
public override void DefinitionTest()
{
Assert.IsTrue(TestClassType.IsAbstract);
Assert.IsFalse(TestClassType.IsSealed);
base.DefinitionTest();
}
#endregion Definition Test
#region Disposal
[TestMethod]
public override void DisposeTest()
{
LDStep step = new LDStep();
MockGroupable groupable = new MockGroupable();
MLCadGroup group = new MLCadGroup();
step.Add(group);
Assert.AreEqual(1, step.PathToDocumentChangedSubscribers);
Assert.AreEqual(0, group.PathToDocumentChangedSubscribers);
step.Add(groupable);
groupable.Group = group;
// the Groupable should subscribe to its step's PathToDocumentChanged event...
Assert.AreEqual(3, step.PathToDocumentChangedSubscribers); // adds two subscribers: Groupable and its superclass Element
// ...and to its group's PathToDocumentChanged event
Assert.AreEqual(1, group.PathToDocumentChangedSubscribers);
groupable.Dispose();
Assert.AreEqual(1, step.PathToDocumentChangedSubscribers);
Assert.AreEqual(0, group.PathToDocumentChangedSubscribers);
base.DisposeTest();
}
#endregion Disposal
#region Grouping
[TestMethod]
public override void GroupTest()
{
IGroupable groupable = CreateTestGroupable();
IStep step = new LDStep();
MLCadGroup group = new MLCadGroup();
step.Add(groupable);
step.Add(group);
Assert.AreEqual(0, group.PathToDocumentChangedSubscribers);
groupable.Group = group;
Assert.AreEqual(1, group.PathToDocumentChangedSubscribers);
groupable.Group = null;
Assert.AreEqual(0, group.PathToDocumentChangedSubscribers);
base.GroupTest();
}
#endregion Grouping
}
}
| Java |
use std::collections::HashMap;
use std::rc::Rc;
use serde::de::{Deserialize, Deserializer};
use serde_derive::Deserialize;
use toml::value;
use crate::errors;
use crate::icons::Icons;
use crate::protocol::i3bar_event::MouseButton;
use crate::themes::Theme;
#[derive(Debug)]
pub struct SharedConfig {
pub theme: Rc<Theme>,
icons: Rc<Icons>,
icons_format: String,
pub scrolling: Scrolling,
}
impl SharedConfig {
pub fn new(config: &Config) -> Self {
Self {
theme: Rc::new(config.theme.clone()),
icons: Rc::new(config.icons.clone()),
icons_format: config.icons_format.clone(),
scrolling: config.scrolling,
}
}
pub fn icons_format_override(&mut self, icons_format: String) {
self.icons_format = icons_format;
}
pub fn theme_override(&mut self, overrides: &HashMap<String, String>) -> errors::Result<()> {
let mut theme = self.theme.as_ref().clone();
theme.apply_overrides(overrides)?;
self.theme = Rc::new(theme);
Ok(())
}
pub fn icons_override(&mut self, overrides: HashMap<String, String>) {
let mut icons = self.icons.as_ref().clone();
icons.0.extend(overrides);
self.icons = Rc::new(icons);
}
pub fn get_icon(&self, icon: &str) -> crate::errors::Result<String> {
use crate::errors::OptionExt;
Ok(self.icons_format.clone().replace(
"{icon}",
self.icons
.0
.get(icon)
.internal_error("get_icon()", &format!("icon '{}' not found in your icons file. If you recently upgraded to v0.2 please check NEWS.md.", icon))?,
))
}
}
impl Default for SharedConfig {
fn default() -> Self {
Self {
theme: Rc::new(Theme::default()),
icons: Rc::new(Icons::default()),
icons_format: " {icon} ".to_string(),
scrolling: Scrolling::default(),
}
}
}
impl Clone for SharedConfig {
fn clone(&self) -> Self {
Self {
theme: Rc::clone(&self.theme),
icons: Rc::clone(&self.icons),
icons_format: self.icons_format.clone(),
scrolling: self.scrolling,
}
}
}
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
#[serde(default)]
pub icons: Icons,
#[serde(default)]
pub theme: Theme,
#[serde(default = "Config::default_icons_format")]
pub icons_format: String,
/// Direction of scrolling, "natural" or "reverse".
///
/// Configuring natural scrolling on input devices changes the way i3status-rust
/// processes mouse wheel events: pushing the wheen away now is interpreted as downward
/// motion which is undesired for sliders. Use "natural" to invert this.
#[serde(default)]
pub scrolling: Scrolling,
#[serde(rename = "block", deserialize_with = "deserialize_blocks")]
pub blocks: Vec<(String, value::Value)>,
}
impl Config {
fn default_icons_format() -> String {
" {icon} ".to_string()
}
}
impl Default for Config {
fn default() -> Self {
Config {
icons: Icons::default(),
theme: Theme::default(),
icons_format: Config::default_icons_format(),
scrolling: Scrolling::default(),
blocks: Vec::new(),
}
}
}
#[derive(Deserialize, Copy, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum Scrolling {
Reverse,
Natural,
}
#[derive(Copy, Clone, Debug)]
pub enum LogicalDirection {
Up,
Down,
}
impl Scrolling {
pub fn to_logical_direction(self, button: MouseButton) -> Option<LogicalDirection> {
use LogicalDirection::*;
use MouseButton::*;
use Scrolling::*;
match (self, button) {
(Reverse, WheelUp) | (Natural, WheelDown) => Some(Up),
(Reverse, WheelDown) | (Natural, WheelUp) => Some(Down),
_ => None,
}
}
}
impl Default for Scrolling {
fn default() -> Self {
Scrolling::Reverse
}
}
fn deserialize_blocks<'de, D>(deserializer: D) -> Result<Vec<(String, value::Value)>, D::Error>
where
D: Deserializer<'de>,
{
let mut blocks: Vec<(String, value::Value)> = Vec::new();
let raw_blocks: Vec<value::Table> = Deserialize::deserialize(deserializer)?;
for mut entry in raw_blocks {
if let Some(name) = entry.remove("block") {
if let Some(name) = name.as_str() {
blocks.push((name.to_owned(), value::Value::Table(entry)))
}
}
}
Ok(blocks)
}
| Java |
/*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2016 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* JoinDirective.java
*
* Created on 25. lokakuuta 2007, 11:38
*
*/
package org.wandora.query;
import org.wandora.topicmap.*;
import java.util.*;
/**
* @deprecated
*
* @author olli
*/
public class JoinDirective implements Directive {
private Directive query;
private Locator joinContext;
private Directive joinQuery;
/** Creates a new instance of JoinDirective */
public JoinDirective(Directive query,Directive joinQuery) {
this(query,(Locator)null,joinQuery);
}
public JoinDirective(Directive query,Locator joinContext,Directive joinQuery) {
this.query=query;
this.joinContext=joinContext;
this.joinQuery=joinQuery;
}
public JoinDirective(Directive query,String joinContext,Directive joinQuery) {
this(query,new Locator(joinContext),joinQuery);
}
public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException {
return query(context,null,null);
}
public ArrayList<ResultRow> query(QueryContext context,FilterDirective filter,Object filterParam) throws TopicMapException {
Topic contextTopic=context.getContextTopic();
TopicMap tm=contextTopic.getTopicMap();
ArrayList<ResultRow> inner=query.query(context);
ArrayList<ResultRow> res=new ArrayList<ResultRow>();
ArrayList<ResultRow> cachedJoin=null;
boolean useCache=!joinQuery.isContextSensitive();
for(ResultRow row : inner){
Topic t=null;
if(joinContext!=null){
Locator c=row.getPlayer(joinContext);
if(c==null) continue;
t=tm.getTopic(c);
}
else t=context.getContextTopic();
if(t==null) continue;
ArrayList<ResultRow> joinRes;
if(!useCache || cachedJoin==null){
joinRes=joinQuery.query(context.makeNewWithTopic(t));
if(useCache) cachedJoin=joinRes;
}
else joinRes=cachedJoin;
for(ResultRow joinRow : joinRes){
ResultRow joined=ResultRow.joinRows(row,joinRow);
if(filter!=null && !filter.includeRow(joined, contextTopic, tm, filterParam)) continue;
res.add(joined);
}
}
return res;
}
public boolean isContextSensitive(){
return query.isContextSensitive();
// note joinQuery gets context from query so it's sensitivity is same
// as that of query
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.transition.AutoTransition
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY>
<!-- Start of nav bar -->
<a name="top"></a>
<div id="header" style="margin-bottom:0;padding-bottom:0;">
<div id="headerLeft">
<a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
</div>
<div id="headerRight">
<div id="headerLinks">
<!-- <img src="/assets/images/icon_world.jpg" alt="" /> -->
<span class="text">
<!-- <a href="#">English</a> | -->
<nobr><a href="//developer.android.com" target="_top">Android Developers</a> | <a href="//www.android.com" target="_top">Android.com</a></nobr>
</span>
</div>
<div class="and-diff-id" style="margin-top:6px;margin-right:8px;">
<table class="diffspectable">
<tr>
<td colspan="2" class="diffspechead">API Diff Specification</td>
</tr>
<tr>
<td class="diffspec" style="padding-top:.25em">To Level:</td>
<td class="diffvaluenew" style="padding-top:.25em">21</td>
</tr>
<tr>
<td class="diffspec">From Level:</td>
<td class="diffvalueold">l-preview</td>
</tr>
<tr>
<td class="diffspec">Generated</td>
<td class="diffvalue">2014.10.15 14:58</td>
</tr>
</table>
</div><!-- End and-diff-id -->
<div class="and-diff-id" style="margin-right:8px;">
<table class="diffspectable">
<tr>
<td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a>
</tr>
</table>
</div> <!-- End and-diff-id -->
</div> <!-- End headerRight -->
</div> <!-- End header -->
<div id="body-content" xstyle="padding:12px;padding-right:18px;">
<div id="doc-content" style="position:relative;">
<div id="mainBodyFluid">
<H2>
Class android.transition.<A HREF="../../../../reference/android/transition/AutoTransition.html" target="_top"><font size="+2"><code>AutoTransition</code></font></A>
</H2>
<a NAME="constructors"></a>
<p>
<a NAME="Added"></a>
<TABLE summary="Added Constructors" WIDTH="100%">
<TR>
<TH VALIGN="TOP" COLSPAN=2>Added Constructors</FONT></TD>
</TH>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.transition.AutoTransition.ctor_added(android.content.Context, android.util.AttributeSet)"></A>
<nobr><A HREF="../../../../reference/android/transition/AutoTransition.html#AutoTransition(android.content.Context, android.util.AttributeSet)" target="_top"><code>AutoTransition</code></A>(<code>Context,</nobr> AttributeSet<nobr><nobr></code>)</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="methods"></a>
<a NAME="fields"></a>
</div>
<div id="footer">
<div id="copyright">
Except as noted, this content is licensed under
<a href="//creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>.
For details and restrictions, see the <a href="/license.html">Content License</a>.
</div>
<div id="footerlinks">
<p>
<a href="//www.android.com/terms.html">Site Terms of Service</a> -
<a href="//www.android.com/privacy.html">Privacy Policy</a> -
<a href="//www.android.com/branding.html">Brand Guidelines</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| Java |
<?php
// Heading
$_['heading_title'] = 'Εγγραφή';
// Text
$_['text_account'] = 'Λογαριασμός';
$_['text_register'] = 'Εγγραφή';
$_['text_account_already'] = 'Εάν έχετε ήδη λογαριασμό, εισέλθετε από <a href="%s">εδώ</a>.';
$_['text_your_details'] = 'Προσωπικά Στοιχεία';
$_['text_your_address'] = 'Διεύθυνση';
$_['text_newsletter'] = 'Ενημερώσεις';
$_['text_your_password'] = 'Ο Κωδικός σας';
$_['text_agree'] = 'Αποδέχομαι τους <a class="fancybox" href="%s" alt="%s"><b>%s</b></a>';
// Entry
$_['entry_firstname'] = 'Όνομα:';
$_['entry_lastname'] = 'Επίθετο:';
$_['entry_email'] = 'E-Mail:';
$_['entry_telephone'] = 'Τηλέφωνο:';
$_['entry_fax'] = 'Fax:';
$_['entry_company'] = 'Εταιρία:';
$_['entry_customer_group'] = 'Είδος Εταιρίας:';
$_['entry_company_id'] = 'Αναγνωριστικό (ID) Εταιρίας:';
$_['entry_tax_id'] = 'ΑΦΜ:';
$_['entry_address_1'] = 'Διεύθυνση 1:';
$_['entry_address_2'] = 'Διεύθυνση 2:';
$_['entry_postcode'] = 'Ταχυδρομικός Κώδικας:';
$_['entry_city'] = 'Πόλη:';
$_['entry_country'] = 'Χώρα:';
$_['entry_zone'] = 'Περιοχή:';
$_['entry_newsletter'] = 'Συνδρομή:';
$_['entry_password'] = 'Κωδικός:';
$_['entry_confirm'] = 'Επαλήθευση Κωδικού:';
// Error
$_['error_exists'] = 'Προειδοποίηση: Η διεύθυνση E-Mail είναι ήδη καταχωρημένη!';
$_['error_firstname'] = 'Το Όνομα πρέπει να είναι από 1 έως 32 χαρακτήρες!';
$_['error_lastname'] = 'Το Επίθετο πρέπει να είναι από 1 έως 32 χαρακτήρες!';
$_['error_email'] = 'Η διεύθυνση E-Mail φαίνεται να μην είναι έγκυρη!';
$_['error_telephone'] = 'Το Τηλέφωνο πρέπει να είναι από 3 έως 32 χαρακτήρες!';
$_['error_password'] = 'Ο Κωδικός πρέπει να είναι από 4 έως 20 χαρακτήρες!';
$_['error_confirm'] = 'Η Επαλήθευση Κωδικού δεν ταιριάζει με τον αρχικό Κωδικό!';
$_['error_company_id'] = 'Απαιτείται η εισαγωγή του Αναγνωριστικού (ID) Εταιρίας!';
$_['error_tax_id'] = 'Απαιτείται η εισαγωγή ΑΦΜ!';
$_['error_vat'] = 'Ο ΦΠΑ είναι λανθασμένος!';
$_['error_address_1'] = 'Η Διεύθυνση 1 πρέπει να είναι από 3 έως 128 χαρακτήρες!';
$_['error_city'] = 'Η Πόλη πρέπει να είναι από 2 έως 128 χαρακτήρες!';
$_['error_postcode'] = 'Ο Ταχυδρομικός Κώδικας πρέπει να είναι από 2 έως 10 χαρακτήρες!';
$_['error_country'] = 'Εισάγετε Χώρα!';
$_['error_zone'] = 'Εισάγετε Περιοχή!';
$_['error_agree'] = 'Προειδοποίηση: Πρέπει να συμφωνήσετε με %s!';
?>
| Java |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-03 08:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('snapventure', '0004_auto_20161102_2043'),
]
operations = [
migrations.CreateModel(
name='Inscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('created', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('journey', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Journey')),
],
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bio', models.TextField(blank=True, max_length=500)),
('location', models.CharField(blank=True, max_length=30)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='inscription',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Profile'),
),
migrations.AddField(
model_name='journey',
name='inscriptions',
field=models.ManyToManyField(through='snapventure.Inscription', to='snapventure.Profile'),
),
]
| Java |
//
// CreditsViewController.h
// P5P
//
// Created by CNPP on 25.2.2011.
// Copyright Beat Raess 2011. All rights reserved.
//
// This file is part of P5P.
//
// P5P 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.
//
// P5P 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 P5P. If not, see www.gnu.org/licenses/.
#import <UIKit/UIKit.h>
#import "CellLink.h"
// Sections
enum {
SectionCreditsReferences,
SectionCreditsFrameworks,
SectionCreditsComponents,
SectionCreditsAssets
} P5PCreditsSections;
/**
* Credit.
*/
@interface Credit : NSObject {
}
// Properties
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *meta;
@property (nonatomic, retain) NSString *url;
// Initializer
- (id)initWithName:(NSString*)n meta:(NSString*)m url:(NSString*)u;
@end
/**
* CreditsViewController.
*/
@interface CreditsViewController : UITableViewController <CellLinkDelegate> {
// data
NSMutableArray *references;
NSMutableArray *frameworks;
NSMutableArray *components;
NSMutableArray *assets;
}
@end
| Java |
#ifndef CONFIGURATION_H
#define CONFIGURATION_H
#include <QObject>
#include <qsettings.h>
class Configuration
{
public:
Configuration();
QString Hostname;
QString Username;
QString AutoLogin;
QString SaveDir;
int ConcurrentDownloads;
bool UseSSL;
QSettings *settings;
void Load();
void Save();
};
#endif // CONFIGURATION_H
| Java |
Note: This is not the [authoritative source](https://www.comlaw.gov.au/Details/C2012C00832) for this act, and likely contains errors
# Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011
##### Act No. 56 of 2011 as amended
##### This compilation was prepared on 20 November 2012
##### taking into account amendments up to Act No. 136 of 2012
##### The text of any of those amendments not in force
##### on that date is appended in the Notes section
##### The operation of amendments that have been incorporated may be
##### affected by application provisions that are set out in the Notes section
##### Prepared by the Office of Parliamentary Counsel, Canberra
##
## Contents
* "1-9" \t "ActHead 1,2,ActHead 2,2,ActHead 3,3,ActHead 4,4,ActHead 5,5, Schedule,2, Schedule Text,3, NotesSection,6" 1 Short title [_see_ Note 1]
* 2 Commencement
* 3 Schedule(s)
* 4 Review of operation of AUSTRAC cost recovery levy
* **Schedule 1--Amendment of the Anti-Money Laundering and Counter-Terrorism Financing Act 2006 **
* Schedule 2--Infringement notice provisions **
* **Part 1--Amendments
* _Anti-Money Laundering and Counter-Terrorism Financing Act 2006 _
* _Part 2--Transitional provision
* **Notes **
### **
### An Act to deal with consequential matters relating to the enactment of the Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011, and for related purposes
* 1** Short title **[_see_ Note 1]
* This Act may be cited as the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_.
##### 2 Commencement
* (1) Each provision of this Act specified in column 1 of the table commences, or is taken to have commenced, in accordance with column 2 of the table. Any other statement in column 2 has effect according to its terms.
**Commencement information**
Column 1**
Column 2**
Column 3**
Provision(s)**
Commencement**
Date/Details**
**1. Sections 1 to 3 and anything in this Act not elsewhere covered by this table
The day this Act receives the Royal Assent.
28 June 2011
2. Schedule 1
A single day to be fixed by Proclamation.
However, if any of the provision(s) do not commence within the period of 6 months beginning on the day this Act receives the Royal Assent, they commence on the day after the end of that period.
1 November 2011
(_see_ F2011L02035)
3. Schedule 2, Part 1
The later of:
* (a) the commencement of item 31 of Schedule 1 to the _Combating the Financing of People Smuggling and Other Measures Act 2011_; and
* (b) immediately after the commencement of the provision(s) covered by table item 2.
However, the provision(s) do not commence at all unless both of the events mentioned in paragraphs (a) and (b) occur.
1 November 2011
4. Schedule 2, Part 2
Immediately after the commencement of the provision(s) covered by table item 2.
1 November 2011
* Note: This table relates only to the provisions of this Act as originally enacted. It will not be amended to deal with any later amendments of this Act.
* (2) Any information in column 3 of the table is not part of this Act. Information may be inserted in this column, or information in it may be edited, in any published version of this Act.
##### 3 Schedule(s)
* Each Act that is specified in a Schedule to this Act is amended or repealed as set out in the applicable items in the Schedule concerned, and any other item in a Schedule to this Act has effect according to its terms.
##### 4 Review of operation of AUSTRAC cost recovery levy
* (1) The Minister must cause an independent review of the operation of the levy imposed by the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_ to be undertaken as soon as possible after the second anniversary of the commencement of section 3 of that Act.
* (2) The person who undertakes the review must give the Minister a written report of the review within 6 months after the second anniversary of the commencement of section 3 of the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_.
* (3) The Minister must cause a copy of the report of the review to be tabled in each House of Parliament within 15 sitting days of receiving it.
* (4) A report prepared under subsection (1) must include but is not limited to:
* (a) a review of the levy calculation methodology; and
* (b) consultation with industry participants including small and micro businesses about the impact of the levy and the costs of complying with the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_.
###
### Schedule 1--Amendment of the Anti-Money Laundering and Counter-Terrorism Financing Act 2006
##### 1 Section 5
* Insert:
* **_enrolment details_**, in relation to a person, means such information relating to the person as is specified in the AML/CTF Rules.
##### 2 After Part 3
* Insert:
### Part 3A--Reporting Entities Roll
##### 51A Simplified outline
* The following is a simplified outline of this Part:
* Providers of designated services must be entered on the Reporting Entities Roll.
##### 51B Reporting entities must enrol
* (1) If a person's name is not entered on the Reporting Entities Roll, the person must:
* (a) if the person provided a designated service during the period of 28 days before the commencement of this section--apply in writing to the AUSTRAC CEO under subsection 51E(1) within 28 days after the commencement of this section; or
* (b) if the person commences to provide a designated service after the commencement of this section--apply in writing to the AUSTRAC CEO under subsection 51E(1) within 28 days after commencing to provide the designated service.
* (2) Subsection (1) does not apply if the person:
* (a) has applied under subsection 51E(1) in relation to the provision of another designated service; and
* (b) has not since requested under section 51G that the AUSTRAC CEO remove the person's name and enrolment details from the Reporting Entities Roll.
* _Civil penalty_
* _ (3) Subsection (1) is a civil penalty provision.
##### 51C Reporting Entities Roll
* (1) The AUSTRAC CEO must maintain a roll for the purposes of this Part, to be known as the Reporting Entities Roll.
* (2) The AUSTRAC CEO may maintain the Reporting Entities Roll by electronic means.
* (3) The Reporting Entities Roll is not a legislative instrument.
* (4) The AML/CTF Rules may make provision for and in relation to either or both of the following:
* (a) the correction of entries in the Reporting Entities Roll;
* (b) any other matter relating to the administration or operation of the Reporting Entities Roll, including the removal of names and enrolment details from the Reporting Entities Roll.
##### 51D Enrolment
* If a person applies to the AUSTRAC CEO under subsection 51E(1) and the person's name is not already entered on the Reporting Entities Roll, the AUSTRAC CEO must enter on the Reporting Entities Roll:
* (a) the person's name; and
* (b) the person's enrolment details.
##### 51E Applications for enrolment
* (1) A person may apply in writing to the AUSTRAC CEO for enrolment as a reporting entity.
* (2) The application must:
* (a) be in accordance with the approved form, or in a manner specified in the AML/CTF Rules; and
* (b) contain the information required by the AML/CTF Rules.
##### 51F Enrolled persons to advise of change in enrolment details
* (1) A person who is enrolled under this Part must advise the AUSTRAC CEO, in accordance with subsection (2), of any change in the person's enrolment details that is of a kind specified in the AML/CTF Rules.
* (2) A person who is required by subsection (1) to advise the AUSTRAC CEO of a change in enrolment details must do so:
* (a) within 14 days of the change arising; and
* (b) in accordance with the approved form, or in a manner specified in the AML/CTF Rules.
* _Civil penalty_
* _ (3) Subsection (1) is a civil penalty provision.
##### 51G Removal of entries from the Reporting Entities Roll
* (1) A person may, in writing, request the AUSTRAC CEO to remove the person's name and enrolment details from the Reporting Entities Roll.
* (2) The request must:
* (a) be in the approved form; and
* (b) contain the information required by the AML/CTF Rules.
* (3) The AUSTRAC CEO must consider the request and remove the person's name and enrolment details from the Reporting Entities Roll if the AUSTRAC CEO is satisfied that it is appropriate to do so, having regard to:
* (a) whether the person has ceased to provide designated services; and
* (b) the likelihood of the person providing a designated service in the financial year beginning after the request is given; and
* (c) any outstanding obligations the person has (if any) to provide a report under any of the following provisions:
* (i) section 43 (threshold transaction reports);
* (ii) section 45 (international funds transfer instruction reports);
* (iii) section 47 (AML/CTF compliance reports).
### Schedule 2--Infringement notice provisions
##### Part 1--Amendments
#### Anti-Money Laundering and Counter-Terrorism Financing Act 2006
##### 1 Before paragraph 184(1A)(a)
* Insert:
* (aaa) subsection 51B(1) (which deals with the requirement for reporting entities to enrol on the Reporting Entities Roll);
* (aa) subsection 51F(1) (which deals with reporting entities notifying changes of their enrolment details);
##### 2 Subsection 186A(1)
* Before "by a body corporate", insert "or subsection 51B(1) or 51F(1) (a **_Part 3A infringement notice provision_**)".
* Note: The heading to section 186A is altered by adding at the end "**or Part 3A**".
##### 3 Subsection 186A(2)
* After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision".
##### 4 Paragraphs 186A(3)(a) and (4)(a)
* After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision".
##### 5 Paragraph 186A(4)(b)
* After "Part 6 infringement notice provisions", insert "or Part 3A infringement notice provisions".
##### 6 Paragraph 186A(4)(b)
* After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision".
##### Part 2--Transitional provision
##### 7 Transitional
* (1) If this item commences before the commencement of Part 1 of this Schedule, Division 3 of Part 15 of the _Anti-Money Laundering and Counter-Terrorism Financing Act 2006 _applies with the modifications set out in this item for the period:
* (a) beginning immediately after the commencement of this item; and
* (b) ending just before the commencement of Part 1 of this Schedule.
* (2) Treat a reference in that Division to "subsection 53(3) or 59(4)" as a reference to "subsection 51B(1), 51F(1), 53(3) or 59(4)".
* (3) Assume the following subsection was added at the end of section 185 of that Act:
* (2) An infringement notice may specify more than one alleged contravention of one or more of the provisions referred to in subsection 184(1). If it does so, the infringement notice must set out the details referred to in paragraph (1)(c) in relation to each alleged contravention.
* (4) Assume that the following section was inserted after section 186 of that Act:
##### 186A Amount of penalty--breaches of certain provisions of Part 3A
* The penalty to be specified in an infringement notice for an alleged contravention of subsection 51B(1) or 51F(1) must be:
* (a) for an alleged contravention by a body corporate--a pecuniary penalty equal to 60 penalty units; and
* (b) for an alleged contravention by a person other than a body corporate--12 penalty units.
#####
##### Notes to the \* MERGEFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011
##### Note 1
The _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _as shown in this compilation comprises Act No. 56, 2011 amended as indicated in the Tables below.
##### Table of Acts
Act
Number
and year
Date
of Assent
Date of commencement
Application, saving or transitional provisions
_Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_56, 2011
28 June 2011
_See_ s. 2(1)
_Statute Law Revision Act 2012_
_136, 2012
22 Sept 2012
Schedule 2 (item 1): Royal Assent
--
*
* **Table of Amendments**
**ad. = added or inserted am. = amended rep. = repealed rs. = repealed and substituted
Provision affected
How affected
S. 4
am. No. 136, 2012
_PAGE iii \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _
\* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE iii_
\* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE iii_
Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 Act No. 56 of 2011 as amended PAGE iii_
FILENAME \p K:\Consolidated Acts\- A -\AustTransRepAnalyCentSuperCostRecLevyConseqAmend2011\2011A056_20121116_2012A136_Conversion_A\AustTranRepAnalCenSupCostRecLevyConAmend2011.doc TIME \@ "d/M/yyyy h:mm AM/PM" 20/11/2012 8:58 AM_
_** **
**
**
_PAGE 2 \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _
\* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 9_
_
_ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 1_
_** Schedule 2** Infringement notice provisions
** Part 1** Amendments
Infringement notice provisions ** Schedule 2**
** Transitional provision ** Part 2**
**_PAGE 8 \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _
_ STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_**Table of Acts**
** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_**Table of Acts**
** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_**Table of Acts**
**_ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 11_
_ STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments**
** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments**
** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_
_** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments**
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace SO.SilList.Manager.Models.ValueObjects
{
[Table("JobType", Schema = "app" )]
[Serializable]
public class JobTypeVo
{
[DisplayName("job Type Id")]
[Required]
[Key]
public int jobTypeId { get; set; }
[DisplayName("name")]
[StringLength(50)]
public string name { get; set; }
[DisplayName("description")]
public string description { get; set; }
[DisplayName("created")]
public Nullable<DateTime> created { get; set; }
[DisplayName("modified")]
public Nullable<DateTime> modified { get; set; }
[DisplayName("created By")]
public Nullable<int> createdBy { get; set; }
[DisplayName("modified By")]
public Nullable<int> modifiedBy { get; set; }
[DisplayName("is Active")]
[Required]
public bool isActive { get; set; }
[Association("JobType_Job", "jobTypeId", "jobTypeId")]
public List<JobVo> jobses { get; set; }
public JobTypeVo()
{
this.isActive = true;
}
}
}
| Java |
/****************************************************************************
**
** Copyright (C) 2014-2015 Dinu SV.
** (contact: mail@dinusv.com)
** This file is part of C++ Snippet Assist application.
**
** GNU General Public License Usage
**
** This file may be used under the terms of the GNU General Public License
** version 3.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
**
****************************************************************************/
#ifndef QSOURCELOCATION_HPP
#define QSOURCELOCATION_HPP
#include "QCSAGlobal.hpp"
#include <QString>
#include <QObject>
namespace csa{
class Q_CSA_EXPORT QSourceLocation : public QObject{
Q_OBJECT
public:
QSourceLocation(
const QString& file,
unsigned int line,
unsigned int column,
unsigned int offset,
QObject* parent = 0);
QSourceLocation(
const char* file,
unsigned int line,
unsigned int column,
unsigned int offset,
QObject* parent = 0);
QSourceLocation(
const QSourceLocation& other,
QObject* parent = 0);
~QSourceLocation();
void assign(const QSourceLocation& other);
QSourceLocation& operator =(const QSourceLocation& other);
public slots:
unsigned int line() const;
unsigned int column() const;
unsigned int offset() const;
QString filePath() const;
QString fileName() const;
QString toString() const;
private:
QString m_filePath;
unsigned int m_line;
unsigned int m_column;
unsigned int m_offset;
};
inline unsigned int QSourceLocation::line() const{
return m_line;
}
inline unsigned int QSourceLocation::column() const{
return m_column;
}
inline unsigned int QSourceLocation::offset() const{
return m_offset;
}
inline QString QSourceLocation::filePath() const{
return m_filePath;
}
}// namespace
Q_DECLARE_METATYPE(csa::QSourceLocation*)
#endif // QSOURCELOCATION_HPP
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CentralAirportSupervision.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute( )]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute( "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0" )]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ( (Settings)( global::System.Configuration.ApplicationSettingsBase.Synchronized( new Settings( ) ) ) );
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| Java |
{% load fiber_tags imagekit %}
<div>
{% thumbnail '150x150' product.image %}
<div>
{{ product.text|safe }}
<span class="product-name">
{{ product.name }}
</span>
</div>
<div class="paypal-button">
{{ product.paypal_button|safe }}
</div>
</div>
{% if 'change_product' in perms %}
<a href="{% url "admin:products_product_change" product.pk %}" class="no-ajax">
edit
</a>
{% endif %}
| Java |
package cat.foixench.test.parcelable;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | Java |
package com.acgmodcrew.kip.tileentity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
/**
* Created by Malec on 05/03/2015.
*/
public class TileEntityRepositry extends TileEntity implements IInventory
{
private ItemStack[] inventory = new ItemStack[4];
@Override
public int getSizeInventory()
{
return 4;
}
@Override
public ItemStack getStackInSlot(int slot)
{
return inventory[slot];
}
@Override
public ItemStack decrStackSize(int slot, int p_70298_2_)
{
if (this.inventory[slot] != null)
{
ItemStack itemstack;
if (this.inventory[slot].stackSize <= p_70298_2_)
{
itemstack = this.inventory[slot];
this.inventory[slot] = null;
this.markDirty();
return itemstack;
}
else
{
itemstack = this.inventory[slot].splitStack(p_70298_2_);
if (this.inventory[slot].stackSize == 0)
{
this.inventory[slot] = null;
}
this.markDirty();
return itemstack;
}
}
else
{
return null;
}
}
@Override
public ItemStack getStackInSlotOnClosing(int p_70304_1_)
{
return null;
}
@Override
public void setInventorySlotContents(int slot, ItemStack itemStack)
{
inventory[slot] = itemStack;
}
@Override
public String getInventoryName()
{
return "Repository";
}
@Override
public boolean hasCustomInventoryName()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer)
{
if (worldObj == null)
{
return true;
}
if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
return false;
}
return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D;
}
@Override
public void openInventory()
{
}
@Override
public void closeInventory()
{
}
@Override
public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_)
{
return false;
}
}
| Java |
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="report.css" type="text/css"/>
<title></title>
<script type="text/javascript" src="report.js"></script>
<script type="text/javascript" src="link_popup.js"></script>
<script type="text/javascript" src="tooltip.js"></script>
</head>
<body style="margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px;">
<div style="position:absolute; z-index:21; visibility:hidden" id="vplink">
<table border="1" cellpadding="0" cellspacing="0" bordercolor="#A9BFD3">
<tr>
<td>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr style="background:#DDDDDD">
<td style="font-size: 12px;" align="left">
<select onchange="vpLinkToggleName()" id="vplink-linkType">
<option value="Project Link">Project Link</option>
<option value="Page URL">Page URL</option>
</select>
</td>
<td style="font-size: 12px;" align="right">
<input onclick="javascript: vpLinkToggleName()" id="vplink-checkbox" type="checkbox" />
<label for="vplink-checkbox">with Name</label> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<textarea id="vplink-text" style="width: 348px; height: 60px; border-color: #7EADD9; outline: none;"></textarea> </td>
</tr>
</table>
</div>
<div class="HeaderText">
<span>
discovery </span>
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="HeaderLine1">
</td>
</tr>
<tr>
<td class="HeaderLine2">
</td>
</tr>
<tr>
<td class="HeaderLine3">
</td>
</tr>
</table>
<p>
<a href="ProjectFormat_LjXSTsKAUChCqADJ.html" class="PageParentTitle">
ProjectFormat : ProjectFormat</a>
</p>
<p class="PageTitle">
ProjectFillColorModel - <a onclick="javascript: showVpLink('discovery.vpp://modelelement/5TXSTsKAUChCqAHD', '\ndiscovery.vpp://modelelement/5TXSTsKAUChCqAHD', '', this); return false;" style="padding-left: 16px; font-size: 12px" href="#">
<img src="../images/icons/link.png" border="0"> Lien</a>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Propriétés </td>
</tr>
<tr>
<td class="TableCellSpaceHolder5PxTall">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="TableCellSpaceHolder10Px">
</td>
<td width="25%">
<span class="TableHeaderText">Nom</span> </td>
<td class="TableCellSpaceHolder20Px">
</td>
<td>
<span class="TableHeaderText">Valeur</span> </td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Base Type</span> </td>
<td>
</td>
<td>
<span class="TableContent">ArchiMateDriver</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Type</span> </td>
<td>
</td>
<td>
<span class="TableContent">Solid</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Fill Color Gradient Style</span> </td>
<td>
</td>
<td>
<span class="TableContent">S-N</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Transparency</span> </td>
<td>
</td>
<td>
<span class="TableContent">0</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Fill Color Color1</span> </td>
<td>
</td>
<td>
<span class="TableContent">-2380289</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Fill Color Color2</span> </td>
<td>
</td>
<td>
<span class="TableContent">0</span> </td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="TableCellSpaceHolder1PxTall">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<p>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Diagrammes Occupés </td>
</tr>
<tr>
<td class="TableCellSpaceHolder5PxTall">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="TableCellSpaceHolder10Px">
</td>
<td>
<span class="TableHeaderText">Diagramme</span> </td>
</tr>
<tr>
<td colSpan="2" class="TableHeaderLine2">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="TableCellSpaceHolder1PxTall">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<div style="height: 20px;">
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="FooterLine">
</td>
</tr>
</table>
<div class="HeaderText">
discovery </div>
</body>
</html>
| Java |
import os
import re
import subprocess
# Copied from Trojita
"""Fetch the .po files from KDE's SVN for GCompris
Run me from GCompris's top-level directory.
"""
SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/"
SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po"
OUTPUT_PO_PATH = "./po/"
OUTPUT_PO_PATTERN = "gcompris_%s.po"
fixer = re.compile(r'^#~\| ', re.MULTILINE)
re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE)
re_empty_line = re.compile('^$', re.MULTILINE)
re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n')
if not os.path.exists(OUTPUT_PO_PATH):
os.mkdir(OUTPUT_PO_PATH)
all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'],
stderr=subprocess.STDOUT)
all_languages = [x.strip() for x in all_languages.split("\n") if len(x)]
all_languages.remove("x-test")
for lang in all_languages:
try:
raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH],
stderr=subprocess.PIPE)
(transformed, subs) = fixer.subn('# ~| ', raw_data)
pos1 = re_empty_msgid.search(transformed).start()
pos2 = re_empty_line.search(transformed).start()
if re_has_qt_contexts.search(transformed, pos1, pos2) is None:
transformed = transformed[:pos2] + \
'"X-Qt-Contexts: true\\n"\n' + \
transformed[pos2:]
subs = subs + 1
if (subs > 0):
print "Fetched %s (and performed %d cleanups)" % (lang, subs)
else:
print "Fetched %s" % lang
file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed)
except subprocess.CalledProcessError:
print "No data for %s" % lang
# Inform qmake about the updated file list
#os.utime("CMakeLists.txt", None)
| Java |
#include <includes.h>
#include <utils.h>
#include <methnum.h>
#include "s_param.h"
#include "integral.h"
double Ivac ( Param * P , double m )
{
double m2 = m*m ;
double LE = sqrt ( m2 + P->L2 );
return 0.5 * ONE_OVER_8PI_2 * ( P->L * LE * ( m2 + 2*P->L ) + m2*m2 * log ( m/(P->L + LE) ) ) ;
}
double dm_Ivac ( Param * P , double m )
{
double m2 = m*m ;
double LE = sqrt ( m2 + P->L2 );
return m * ONE_OVER_4PI_2 * ( P->L * LE + m2 * log ( m/(P->L + LE) ) );
}
double dm2_Ivac ( Param * P , double m )
{
double m2 = m*m ;
double LE = sqrt ( m2 + P->L2 );
return ONE_OVER_4PI_2 * ( P->L*(3*m2 + P->L2)/LE + 3*m2 * log ( m / (P->L + LE) ) ) ;
}
double dm3_Ivac ( Param * P , double m )
{
double m2 = m*m ;
double LE2 = m2 + P->L2 ;
double LE = sqrt( LE2 );
return 3 * m * ONE_OVER_2PI_2 * ( P->L*( 3*m2 + 4*P->L2 )/(3*LE2*LE) + log ( m / (P->L + LE) ) );
}
double Imed ( Param * P , double m , double T , double mu )
{
double m2 = m*m ;
double b = 1./T ;
double integ ( double p )
{
double p2 = p*p ;
double E2 = p2 + m2 ;
double E = sqrt ( E2 );
double x = -(E - mu) * b ;
double y = -(E + mu) * b ;
double a = log ( 1 + exp ( x ) ) ;
double b = log ( 1 + exp ( y ) ) ;
return p2 * ( a + b );
}
double I = ONE_OVER_2PI_2 * integ_dp ( integ , 0. , P->L , cutoff );
return I ;
}
double dm_Imed ( Param * P , double m , double T , double mu )
{
double m2 = m*m ;
double b = 1./T ;
double integ ( double p )
{
double p2 = p*p ;
double E2 = p2 + m2 ;
double E = sqrt ( E2 );
double x = (E - mu) * b ;
double y = (E + mu) * b ;
double ex = exp ( x ) ;
double ey = exp ( y );
double f = 1. / ( 1 + ex );
double fb = 1. / ( 1 + ey );
return p2 * ( - f - fb ) / E ;
}
double I = integ_dp ( integ , 0. , P->L , cutoff );
return m * I ;
}
double dT_Imed ( Param * P , double m , double T , double mu )
{
}
double dmu_Imed ( Param * P , double m , double T , double mu );
/* double dm2_Imed ( Param * P , double m , double T , double mu ); */
/* double dmT_Imed ( Param * P , double m , double T , double mu ); */
/* double dmmu_Imed ( Param * P , double m , double T , double mu ); */
/* double dT2_Imed ( Param * P , double m , double T , double mu ); */
/* double dTmu_Imed ( Param * P , double m , double T , double mu ); */
/* double dmu2_Imed ( Param * P , double m , double T , double mu ); */
| Java |
#include "Scene.h"
#include "Screen.h"
Scene::Scene()
{
}
void Scene::Update()
{
Object::AddPreparedObjects();
for (Object* obj : Object::objects)
{
if (obj->IsActive())
obj->Update();
}
for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++)
{
if (!(*iter)->IsActive())
{
Object::DeleteObject(*iter);
break;
}
}
}
void Scene::Render()
{
SDL_SetRenderDrawColor(Screen::GetRenderer(), 0, 0, 0, 255);
SDL_RenderClear(Screen::GetRenderer());
for (Object* obj : Object::objects)
{
if(obj->IsActive())
obj->Render();
}
SDL_RenderPresent(Screen::GetRenderer());
}
Object* Scene::FindObject(string name)
{
return Object::FindObject(name);
}
void Scene::OnOpened()
{
}
void Scene::OnClosed()
{
Object::ClearObjects();
}
Object** Scene::GetObjectsOfName(string name, int* count)
{
*count = 0;
for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++)
{
if (!(*iter)->IsActive())
continue;
Object* obj = *iter;
if (obj->GetObjectName() == name)
(*count)++;
}
Object** objs = new Object*[*count];
int index = 0;
for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++)
{
if (!(*iter)->IsActive())
continue;
Object* obj = *iter;
if (obj->GetObjectName() == name)
{
objs[index] = obj;
index++;
}
}
return objs;
} | Java |
package com.simplecity.amp_library.playback;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.RemoteControlClient;
import android.os.Bundle;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import com.annimon.stream.Stream;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.cantrowitz.rxbroadcast.RxBroadcast;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.ShuttleApplication;
import com.simplecity.amp_library.androidauto.CarHelper;
import com.simplecity.amp_library.androidauto.MediaIdHelper;
import com.simplecity.amp_library.data.Repository;
import com.simplecity.amp_library.model.Song;
import com.simplecity.amp_library.playback.constants.InternalIntents;
import com.simplecity.amp_library.ui.screens.queue.QueueItem;
import com.simplecity.amp_library.ui.screens.queue.QueueItemKt;
import com.simplecity.amp_library.utils.LogUtils;
import com.simplecity.amp_library.utils.MediaButtonIntentReceiver;
import com.simplecity.amp_library.utils.SettingsManager;
import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import java.util.List;
import kotlin.Unit;
class MediaSessionManager {
private static final String TAG = "MediaSessionManager";
private Context context;
private MediaSessionCompat mediaSession;
private QueueManager queueManager;
private PlaybackManager playbackManager;
private PlaybackSettingsManager playbackSettingsManager;
private SettingsManager settingsManager;
private CompositeDisposable disposables = new CompositeDisposable();
private MediaIdHelper mediaIdHelper;
private static String SHUFFLE_ACTION = "ACTION_SHUFFLE";
MediaSessionManager(
Context context,
QueueManager queueManager,
PlaybackManager playbackManager,
PlaybackSettingsManager playbackSettingsManager,
SettingsManager settingsManager,
Repository.SongsRepository songsRepository,
Repository.AlbumsRepository albumsRepository,
Repository.AlbumArtistsRepository albumArtistsRepository,
Repository.GenresRepository genresRepository,
Repository.PlaylistsRepository playlistsRepository
) {
this.context = context.getApplicationContext();
this.queueManager = queueManager;
this.playbackManager = playbackManager;
this.settingsManager = settingsManager;
this.playbackSettingsManager = playbackSettingsManager;
mediaIdHelper = new MediaIdHelper((ShuttleApplication) context.getApplicationContext(), songsRepository, albumsRepository, albumArtistsRepository, genresRepository, playlistsRepository);
ComponentName mediaButtonReceiverComponent = new ComponentName(context.getPackageName(), MediaButtonIntentReceiver.class.getName());
mediaSession = new MediaSessionCompat(context, "Shuttle", mediaButtonReceiverComponent, null);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPause() {
playbackManager.pause(true);
}
@Override
public void onPlay() {
playbackManager.play();
}
@Override
public void onSeekTo(long pos) {
playbackManager.seekTo(pos);
}
@Override
public void onSkipToNext() {
playbackManager.next(true);
}
@Override
public void onSkipToPrevious() {
playbackManager.previous(false);
}
@Override
public void onSkipToQueueItem(long id) {
List<QueueItem> queueItems = queueManager.getCurrentPlaylist();
QueueItem queueItem = Stream.of(queueItems)
.filter(aQueueItem -> (long) aQueueItem.hashCode() == id)
.findFirst()
.orElse(null);
if (queueItem != null) {
playbackManager.setQueuePosition(queueItems.indexOf(queueItem));
}
}
@Override
public void onStop() {
playbackManager.stop(true);
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.e("MediaButtonReceiver", "OnMediaButtonEvent called");
MediaButtonIntentReceiver.handleIntent(context, mediaButtonEvent, playbackSettingsManager);
return true;
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
mediaIdHelper.getSongListForMediaId(mediaId, (songs, position) -> {
playbackManager.load((List<Song>) songs, position, true, 0);
return Unit.INSTANCE;
});
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("CheckResult")
@Override
public void onPlayFromSearch(String query, Bundle extras) {
if (TextUtils.isEmpty(query)) {
playbackManager.play();
} else {
mediaIdHelper.handlePlayFromSearch(query, extras)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
pair -> {
if (!pair.getFirst().isEmpty()) {
playbackManager.load(pair.getFirst(), pair.getSecond(), true, 0);
} else {
playbackManager.pause(false);
}
},
error -> LogUtils.logException(TAG, "Failed to gather songs from search. Query: " + query, error)
);
}
}
@Override
public void onCustomAction(String action, Bundle extras) {
if (action.equals(SHUFFLE_ACTION)) {
queueManager.setShuffleMode(queueManager.shuffleMode == QueueManager.ShuffleMode.ON ? QueueManager.ShuffleMode.OFF : QueueManager.ShuffleMode.ON);
}
updateMediaSession(action);
}
});
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
//For some reason, MediaSessionCompat doesn't seem to pass all of the available 'actions' on as
//transport control flags for the RCC, so we do that manually
RemoteControlClient remoteControlClient = (RemoteControlClient) mediaSession.getRemoteControlClient();
if (remoteControlClient != null) {
remoteControlClient.setTransportControlFlags(
RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_STOP);
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(InternalIntents.QUEUE_CHANGED);
intentFilter.addAction(InternalIntents.META_CHANGED);
intentFilter.addAction(InternalIntents.PLAY_STATE_CHANGED);
intentFilter.addAction(InternalIntents.POSITION_CHANGED);
disposables.add(RxBroadcast.fromBroadcast(context, intentFilter).subscribe(intent -> {
String action = intent.getAction();
if (action != null) {
updateMediaSession(intent.getAction());
}
}));
}
private void updateMediaSession(final String action) {
int playState = playbackManager.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
long playbackActions = getMediaSessionActions();
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder();
builder.setActions(playbackActions);
switch (queueManager.shuffleMode) {
case QueueManager.ShuffleMode.OFF:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_on), R.drawable.ic_shuffle_off_circled).build());
break;
case QueueManager.ShuffleMode.ON:
builder.addCustomAction(
new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_off), R.drawable.ic_shuffle_on_circled).build());
break;
}
builder.setState(playState, playbackManager.getSeekPosition(), 1.0f);
if (currentQueueItem != null) {
builder.setActiveQueueItemId((long) currentQueueItem.hashCode());
}
PlaybackStateCompat playbackState = builder.build();
if (action.equals(InternalIntents.PLAY_STATE_CHANGED) || action.equals(InternalIntents.POSITION_CHANGED) || action.equals(SHUFFLE_ACTION)) {
mediaSession.setPlaybackState(playbackState);
} else if (action.equals(InternalIntents.META_CHANGED) || action.equals(InternalIntents.QUEUE_CHANGED)) {
if (currentQueueItem != null) {
MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, String.valueOf(currentQueueItem.getSong().id))
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentQueueItem.getSong().artistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, currentQueueItem.getSong().albumArtistName)
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentQueueItem.getSong().albumName)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentQueueItem.getSong().name)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentQueueItem.getSong().duration)
.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (long) (queueManager.queuePosition + 1))
//Getting the genre is expensive.. let's not bother for now.
//.putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null)
.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, (long) (queueManager.getCurrentPlaylist().size()));
// If we're in car mode, don't wait for the artwork to load before setting session metadata.
if (CarHelper.isCarUiMode(context)) {
mediaSession.setMetadata(metaData.build());
}
mediaSession.setPlaybackState(playbackState);
mediaSession.setQueue(QueueItemKt.toMediaSessionQueueItems(queueManager.getCurrentPlaylist()));
mediaSession.setQueueTitle(context.getString(R.string.menu_queue));
if (settingsManager.showLockscreenArtwork() || CarHelper.isCarUiMode(context)) {
updateMediaSessionArtwork(metaData);
} else {
mediaSession.setMetadata(metaData.build());
}
}
}
}
private void updateMediaSessionArtwork(MediaMetadataCompat.Builder metaData) {
QueueItem currentQueueItem = queueManager.getCurrentQueueItem();
if (currentQueueItem != null) {
disposables.add(Completable.defer(() -> Completable.fromAction(() ->
Glide.with(context)
.load(currentQueueItem.getSong().getAlbum())
.asBitmap()
.override(1024, 1024)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
if (bitmap != null) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap);
}
try {
mediaSession.setMetadata(metaData.build());
} catch (NullPointerException e) {
metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null);
mediaSession.setMetadata(metaData.build());
}
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
mediaSession.setMetadata(metaData.build());
}
})
))
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe()
);
}
}
private long getMediaSessionActions() {
return PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_PLAY_PAUSE
| PlaybackStateCompat.ACTION_SKIP_TO_NEXT
| PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
| PlaybackStateCompat.ACTION_STOP
| PlaybackStateCompat.ACTION_SEEK_TO
| PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
| PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
| PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM;
}
MediaSessionCompat.Token getSessionToken() {
return mediaSession.getSessionToken();
}
void setActive(boolean active) {
mediaSession.setActive(active);
}
void destroy() {
disposables.clear();
mediaSession.release();
}
} | Java |
#!/usr/bin/env perl
use strict;
use warnings;
@ARGV >= 1 or die "Usage: \n\tperl $0 event1 event2 ... eventn\n\tperl $0 events.info\n";
my @events;
if (@ARGV == 1 and -f $ARGV[0]) {
open(IN, "< $ARGV[0]");
foreach (<IN>) {
my ($event) = split /\s+/;
push @events, $event;
}
close(IN);
} else {
@events = @ARGV;
}
foreach my $event (@events) {
system "perl rdseed.pl $event";
system "perl eventinfo.pl $event";
system "perl marktime.pl $event";
system "perl transfer.pl $event";
system "perl rotate.pl $event";
system "perl resample.pl $event";
}
| Java |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(){var l={_attachScript:function(e,c){var d=new CKEDITOR.dom.element("script");d.setAttribute("src",e);d.on("error",c);CKEDITOR.document.getBody().append(d);return d},sendRequest:function(e,c,d,a){function b(){g&&(g.remove(),delete CKEDITOR._.jsonpCallbacks[h],g=null)}var k={};c=c||{};var h=CKEDITOR.tools.getNextNumber(),g;c.callback="CKEDITOR._.jsonpCallbacks["+h+"]";CKEDITOR._.jsonpCallbacks[h]=function(a){setTimeout(function(){b();d(a)})};g=this._attachScript(e.output(c),function(){b();
a&&a()});k.cancel=b;return k}};CKEDITOR.plugins.add("embedbase",{lang:"az,ca,cs,da,de,de-ch,en,eo,es,es-mx,eu,fr,gl,hr,hu,id,it,ja,ko,ku,nb,nl,oc,pl,pt,pt-br,ru,sk,sv,tr,ug,uk,zh,zh-cn",requires:"dialog,widget,notificationaggregator",onLoad:function(){CKEDITOR._.jsonpCallbacks={}},init:function(){CKEDITOR.dialog.add("embedBase",this.path+"dialogs/embedbase.js")}});CKEDITOR.plugins.embedBase={createWidgetBaseDefinition:function(e){var c,d=e.lang.embedbase;return{mask:!0,template:"\x3cdiv\x3e\x3c/div\x3e",
pathName:d.pathName,_cache:{},urlRegExp:/^((https?:)?\/\/|www\.)/i,init:function(){this.on("sendRequest",function(a){this._sendRequest(a.data)},this,null,999);this.on("dialog",function(a){a.data.widget=this},this);this.on("handleResponse",function(a){if(!a.data.html){var b=this._responseToHtml(a.data.url,a.data.response);null!==b?a.data.html=b:(a.data.errorMessage="unsupportedUrl",a.cancel())}},this,null,999)},loadContent:function(a,b){function c(e){f.response=e;d.editor.widgets.instances[d.id]?d._handleResponse(f)&&
(d._cacheResponse(a,e),b.callback&&b.callback()):(CKEDITOR.warn("embedbase-widget-invalid"),f.task&&f.task.done())}b=b||{};var d=this,e=this._getCachedResponse(a),f={noNotifications:b.noNotifications,url:a,callback:c,errorCallback:function(a){d._handleError(f,a);b.errorCallback&&b.errorCallback(a)}};if(e)setTimeout(function(){c(e)});else return b.noNotifications||(f.task=this._createTask()),this.fire("sendRequest",f),f},isUrlValid:function(a){return this.urlRegExp.test(a)&&!1!==this.fire("validateUrl",
a)},getErrorMessage:function(a,b,c){(c=e.lang.embedbase[a+(c||"")])||(c=a);return(new CKEDITOR.template(c)).output({url:b||""})},_sendRequest:function(a){var b=this,c=l.sendRequest(this.providerUrl,{url:encodeURIComponent(a.url)},a.callback,function(){a.errorCallback("fetchingFailed")});a.cancel=function(){c.cancel();b.fire("requestCanceled",a)}},_handleResponse:function(a){var b={url:a.url,html:"",response:a.response};if(!1!==this.fire("handleResponse",b))return a.task&&a.task.done(),this._setContent(a.url,
b.html),!0;a.errorCallback(b.errorMessage);return!1},_handleError:function(a,b){a.task&&(a.task.cancel(),a.noNotifications||e.showNotification(this.getErrorMessage(b,a.url),"warning"))},_responseToHtml:function(a,b){return"photo"==b.type?'\x3cimg src\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.url)+'" alt\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.title||"")+'" style\x3d"max-width:100%;height:auto" /\x3e':"video"==b.type||"rich"==b.type?(b.html=b.html.replace(/<iframe/g,'\x3ciframe tabindex\x3d"-1"'),b.html):
null},_setContent:function(a,b){this.setData("url",a);this.element.setHtml(b)},_createTask:function(){if(!c||c.isFinished())c=new CKEDITOR.plugins.notificationAggregator(e,d.fetchingMany,d.fetchingOne),c.on("finished",function(){c.notification.hide()});return c.createTask()},_cacheResponse:function(a,b){this._cache[a]=b},_getCachedResponse:function(a){return this._cache[a]}}},_jsonp:l}})(); | Java |
<?php require_once 'header.php';?>
<div class="page-header">
<h1><?=APP_NAME ?></h1>
</div>
<a href="auth">auth</a>
<!--echo "role=".<?=$role ?>; -->
<?php
$app = \Slim\Slim::getInstance();
// echo "user->role=".$app->user->role;
?>
<?php require_once 'footer.php';?> | Java |
/**
* Copyright 2017 Kaloyan Raev
*
* This file is part of chitanka4kindle.
*
* chitanka4kindle 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.
*
* chitanka4kindle 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 chitanka4kindle. If not, see <http://www.gnu.org/licenses/>.
*/
package name.raev.kaloyan.kindle.chitanka.model.search.label;
public class Label {
private String slug;
private String name;
private int nrOfTexts;
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfTexts() {
return nrOfTexts;
}
public void setNumberOfTexts(int nrOfTexts) {
this.nrOfTexts = nrOfTexts;
}
}
| Java |
export class GameId {
constructor(
public game_id: string) {
}
}
| Java |
namespace Net.Demandware.Ocapi.Resources.Data
{
class Coupons
{
}
}
| Java |
/** File errors.cc author Vladislav Tcendrovskii
* Copyright (c) 2013
* This source subjected to the Gnu General Public License v3 or later (see LICENSE)
* All other rights reserved
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY
* OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
* */
#include "errors.h"
std::string error_str(int errnum)
{
std::string ans;
switch(errnum)
{
case ENO:
ans = "No error";
break;
case EZERO:
ans = "Division by zero";
break;
case EDIM:
ans = "Dimension mismatch";
break;
case EMEM:
ans = "Memory allocation fail";
break;
case ETYPE:
ans = "Wrong object type/form";
break;
case EIND:
ans = "Index out of range";
break;
default:
ans = "Error number " + errnum;
break;
}
return ans;
} | Java |
#! /usr/bin/python
from xml.sax.saxutils import escape
import re
def ConvertDiagnosticLineToSonqarqube(item):
try:
id, line, message, source_file = GetDiagnosticFieldsFromDiagnosticLine(item)
WriteDiagnosticFieldsToFile(id, line, message, source_file)
except:
print 'Cant parse line {}'.format(item)
def GetDiagnosticFieldsFromDiagnosticLine(item):
source_file = re.search('\/(.*?):', item).group(0).replace(':', '')
line = re.search(':\d*:', item).group(0).replace(':', '')
id = re.search('\[.*\]', item).group(0).replace('[', '').replace(']', '') + '-clang-compiler'
message = re.search('warning: (.*)\[', item).group(0).replace('[', '').replace('warning: ', '')
return id, line, message, source_file
def WriteDiagnosticFieldsToFile(id, line, message, source_file):
clang_sonar_report.write(" <error file=\"" + str(source_file) +
"\" line=\"" + str(line) +
"\" id=\"" + str(id) +
"\" msg=\"" + escape(str(message)) + "\"/>\n")
def CreateOutputFile():
file_to_write = open('clang_compiler_report.xml', 'w')
file_to_write.write('<?xml version="1.0" encoding="UTF-8"?>\n')
file_to_write.write('<results>\n')
return file_to_write
def ReadCompilerReportFile():
file = open('clang_compiler_report_formatted', 'r')
messages_xml = file.readlines()
return messages_xml
def CloseOutputFile():
clang_sonar_report.write('</results>\n')
clang_sonar_report.close()
def WriteSonarRulesToOutputFile():
item_list = clang_compiler_report
for item in item_list:
ConvertDiagnosticLineToSonqarqube(item)
if __name__ == '__main__':
clang_sonar_report = CreateOutputFile()
clang_compiler_report = ReadCompilerReportFile()
WriteSonarRulesToOutputFile()
CloseOutputFile()
| Java |
/* Coolors Exported Palette - coolors.co/393d3f-437f97-f2bb05-ff8552-071e22
*
* Black Olive
* rgba(57, 61, 63, 1)
* Queen Blue
* rgba(67, 127, 151, 1)
* Selective Yellow
* rgba(242, 187, 5, 1)
* Coral
* rgba(255, 133, 82, 1)
* Dark Jungle Green
* rgba(7, 30, 34, 1)
*
*/
html {
background: url(../img/6794800763_72896eacd3_o.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
.main {
background: rgba(255, 255, 255, 0.75);
padding: 2em;
margin-top: 2em;
margin-bottom: 2em;
border-radius: 2px;
}
i {
color: rgba(242, 187, 5, 1);
}
h1, h2, h3, h4, h5, h6 {
color: rgba(7, 30, 34, 1));
}
| Java |
#!/usr/bin/env python
import os
import tempfile
import pipes
import subprocess
import time
import random
import shutil
try:
from wand.image import Image
from wand.display import display
except ImportError as e:
# cd /usr/lib/
# ln -s libMagickWand-6.Q16.so libMagickWand.so
print("Couldn't import Wand package.")
print("Please refer to #http://dahlia.kr/wand/ to install it.")
import traceback; traceback.print_exc()
raise e
try:
import magic
mime = magic.Magic()
except ImportError:
mime = None
#https://github.com/ahupp/python-magic
try:
from docopt import docopt
except ImportError:
print("Couldn't import Docopt package.")
print("Please refer to#https://github.com/docopt/docopt to install it.")
print("/!\\ Option parsing not possible, defaulting to hardcoded values/!\\")
def to_bool(val):
if val is None:
return false
return val == 1
def to_int(val):
return int(val)
def to_str(val):
return val
def to_path(val):
return val
OPT_TO_KEY = {
'--do-wrap' : ("DO_WRAP", to_bool),
'--line-height': ("LINE_HEIGHT", to_int),
'--nb-lines' : ('LINES', to_int),
'--no-caption' : ("WANT_NO_CAPTION", to_bool),
'--force-no-vfs': ("FORCE_VFS", to_bool),
'--force-vfs' : ("FORCE_NO_VFS", to_bool),
'--pick-random': ("PICK_RANDOM", to_bool),
'--put-random' : ("PUT_RANDOM", to_bool),
'--resize' : ("DO_RESIZE", to_bool),
'--sleep' : ('SLEEP_TIME', to_int),
'--width' : ('WIDTH', to_int),
'--no-switch-to-mini': ("NO_SWITCH_TO_MINI", to_bool),
'<path>' : ('PATH', to_path),
'<target>' : ('TARGET', to_path),
'--polaroid' : ("DO_POLAROID", to_bool),
'--format' : ("IMG_FORMAT_SUFFIX", to_str),
'--crop-size' : ("CROP_SIZE", to_int),
'~~use-vfs' : ("USE_VFS", to_bool),
'--help' : ("HELP", to_bool)
}
KEY_TO_OPT = dict([(key, (opt, ttype)) for opt, (key, ttype) in OPT_TO_KEY.items()])
PARAMS = {
"PATH" : "/home/kevin/mount/first",
"TARGET" : "/tmp/final.png",
#define the size of the picture
"WIDTH" : 2000,
#define how many lines do we want
"LINES": 2,
"LINE_HEIGHT": 200,
#minimum width of cropped image. Below that, we black it out
#only for POLAROID
"CROP_SIZE": 1000,
"IMG_FORMAT_SUFFIX": ".png",
# False if PATH is a normal directory, True if it is WebAlbums-FS
"USE_VFS": False,
"FORCE_VFS": False,
"FORCE_NO_VFS": False,
# True if end-of-line photos are wrapped to the next line
"DO_WRAP": False,
# True if we want a black background and white frame, plus details
"DO_POLAROID": True,
"WANT_NO_CAPTION": True,
# False if we want to add pictures randomly
"PUT_RANDOM": False,
"DO_RESIZE": False,
### VFS options ###
"NO_SWITCH_TO_MINI": False,
### Directory options ###
# False if we pick directory images sequentially, false if we take them randomly
"PICK_RANDOM": False, #not implemented yet
## Random wall options ##
"SLEEP_TIME": 0,
"HELP": False
}
DEFAULTS = dict([(key, value) for key, value in PARAMS.items()])
DEFAULTS_docstr = dict([(KEY_TO_OPT[key][0], value) for key, value in PARAMS.items()])
usage = """Photo Wall for WebAlbums 3.
Usage:
photowall.py <path> <target> [options]
Arguments:
<path> The path where photos are picked up from. [default: %(<path>)s]
<target> The path where the target photo is written. Except in POLAROID+RANDOM mode, the image will be blanked out first. [default: %(<target>)s]
Options:
--polaroid Use polaroid-like images for the wall
--width <width> Set final image width. [default: %(--width)d]
--nb-lines <nb> Number on lines of the target image. [default: %(--nb-lines)d]
--resize Resize images before putting in the wall. [default: %(--resize)s]
--line-height <height> Set the height of a single image. [default: %(--line-height)d]
--do-wrap If not POLAROID, finish images on the next line. [default: %(--do-wrap)s]
--help Display this message
Polaroid mode options:
--crop-size <crop> Minimum size to allow cropping an image. [default: %(--crop-size)s]
--no-caption Disable caption. [default: %(--no-caption)s]
--put-random Put images randomly instead of linearily. [default: %(--put-random)s]
--sleep <time> If --put-random, time (in seconds) to go asleep before adding a new image. [default: %(--sleep)d]
Filesystem options:
--force-vfs Treat <path> as a VFS filesystem. [default: %(--force-vfs)s]
--force-no-vfs Treat <path> as a normal filesystem. [default: %(--force-no-vfs)s]
--no-switch-to-mini If VFS, don't switch from the normal image to the miniature. [default: %(--no-switch-to-mini)s]
--pick-random If not VFS, pick images randomly in the <path> folder. [default: %(--pick-random)s]
""" % DEFAULTS_docstr
class UpdateCallback:
def newExec(self):
pass
def newImage(self, row=0, col=0, filename=""):
print("%d.%d > %s" % (row, col, filename))
def updLine(self, row, tmpLine):
#print("--- %d ---" % row)
pass
def newFinal(self, name):
pass
def finished(self, name):
print("==========")
def stopRequested(self):
return False
def checkPause(self):
pass
updateCB = UpdateCallback()
if __name__ == "__main__":
arguments = docopt(usage, version="3.5-dev")
if arguments["--help"]:
print(usage)
exit()
param_args = dict([(OPT_TO_KEY[opt][0], OPT_TO_KEY[opt][1](value)) for opt, value in arguments.items()])
PARAMS = dict(PARAMS, **param_args)
###########################################
###########################################
previous = None
def get_next_file_vfs():
global previous
if previous is not None:
try:
os.unlink(previous)
except OSerror:
pass
files = os.listdir(PARAMS["PATH"])
for filename in files:
if not "By Years" in filename:
previous = PARAMS["PATH"]+filename
if "gpx" in previous:
return get_next_file()
to_return = previous
try:
to_return = os.readlink(to_return)
except OSError:
pass
if not PARAMS["NO_SWITCH_TO_MINI"]:
to_return = to_return.replace("/images/", "/miniatures/") + ".png"
return to_return
def get_file_details(filename):
try:
link = filename
try:
link = os.readlink(filename)
except OSError:
pass
link = pipes.quote(link)
names = link[link.index("/miniatures/" if not PARAMS["NO_SWITCH_TO_MINI"] else "/images"):].split("/")[2:]
theme, year, album, fname = names
return "%s (%s)" % (album, theme)
except Exception as e:
#print("Cannot get details from {}: {}".format(filename, e))
fname = get_file_details_dir(filename)
fname = fname.rpartition(".")[0]
fname = fname.replace("_", "\n")
return fname
###########################################
class GetFileDir:
def __init__(self, randomize):
self.idx = 0
self.files = os.listdir(PARAMS["PATH"])
if len(self.files) == 0:
raise EnvironmentError("No file available")
self.files.sort()
if randomize:
print("RANDOMIZE")
random.shuffle(self.files)
def get_next_file(self):
to_return = self.files[self.idx]
self.idx += 1
self.idx %= len(self.files)
return PARAMS["PATH"]+to_return
def get_file_details_dir(filename):
return filename[filename.rindex("/")+1:]
###########################################
###########################################
def do_append(first, second, underneath=False):
sign = "-" if underneath else "+"
background = "-background black" if PARAMS["DO_POLAROID"] else ""
command = "convert -gravity center %s %sappend %s %s %s" % (background, sign, first, second, first)
ret = subprocess.call(command, shell=True)
if ret != 0:
raise Exception("Command failed: ", command)
def do_polaroid (image, filename=None, background="black", suffix=None):
if suffix is None:
suffix = PARAMS["IMG_FORMAT_SUFFIX"]
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
tmp.close()
image.save(filename=tmp.name)
if not(PARAMS["WANT_NO_CAPTION"]) and filename:
details = get_file_details(filename)
caption = """-caption "%s" """ % details.replace("'", "\\'")
else:
caption = ""
command = "convert -bordercolor snow -background %(bg)s -gravity center %(caption)s +polaroid %(name)s %(name)s" % {"bg" : background, "name":tmp.name, "caption":caption}
ret = subprocess.call(command, shell=True)
if ret != 0:
raise Exception("Command failed: "+ command)
img = Image(filename=tmp.name).clone()
os.unlink(tmp.name)
img.resize(width=image.width, height=image.height)
return img
def do_blank_image(height, width, filename, color="black"):
command = "convert -size %dx%d xc:%s %s" % (width, height, color, filename)
ret = subprocess.call(command, shell=True)
if ret != 0:
raise Exception("Command failed: "+ command)
def do_polaroid_and_random_composite(target_filename, target, image, filename):
PERCENT_IN = 100
image = do_polaroid(image, filename, background="transparent", suffix=".png")
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"])
image.save(filename=tmp.name)
height = random.randint(0, target.height - image.height) - target.height/2
width = random.randint(0, target.width - image.width) - target.width/2
geometry = ("+" if height >= 0 else "") + str(height) + ("+" if width >= 0 else "") + str(width)
command = "composite -geometry %s -compose Over -gravity center %s %s %s" % (geometry, tmp.name, target_filename, target_filename)
ret = os.system(command)
os.unlink(tmp.name)
if ret != 0:
raise object("failed")
def photowall(name):
output_final = None
previous_filename = None
#for all the rows,
for row in range(PARAMS["LINES"]):
output_row = None
row_width = 0
#concatenate until the image width is reached
img_count = 0
while row_width < PARAMS["WIDTH"]:
# get a new file, or the end of the previous one, if it was split
filename = get_next_file() if previous_filename is None else previous_filename
mimetype = None
previous_filename = None
# get a real image
if mime is not None:
mimetype = mime.from_file(filename)
if "symbolic link" in mimetype:
filename = os.readlink(filename)
mimetype = mime.from_file(filename)
if not "image" in mimetype:
continue
else:
try:
filename = os.readlink(filename)
except OSError:
pass
updateCB.newImage(row, img_count, filename)
img_count += 1
# resize the image
image = Image(filename=filename)
with image.clone() as clone:
factor = float(PARAMS["LINE_HEIGHT"])/clone.height
clone.resize(height=PARAMS["LINE_HEIGHT"], width=int(clone.width*factor))
#if the new image makes an overflow
if row_width + clone.width > PARAMS["WIDTH"]:
#compute how many pixels will overflow
overflow = row_width + clone.width - PARAMS["WIDTH"]
will_fit = clone.width - overflow
if PARAMS["DO_POLAROID"] and will_fit < PARAMS["CROP_SIZE"]:
row_width = PARAMS["WIDTH"]
previous_filename = filename
print("Doesn't fit")
continue
if PARAMS["DO_WRAP"]:
with clone.clone() as next_img:
next_img.crop(will_fit+1, 0, width=overflow, height=PARAMS["LINE_HEIGHT"])
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"])
tmp.close()
next_img.save(filename=tmp.name)
previous_filename = tmp.name
clone.crop(0, 0, width=will_fit, height=PARAMS["LINE_HEIGHT"])
if PARAMS["DO_POLAROID"]:
clone = do_polaroid(clone, filename)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"])
tmp.close()
clone.save(filename=tmp.name)
row_width += clone.width
if output_row is not None:
do_append(output_row.name, tmp.name)
os.unlink(tmp.name)
else:
output_row = tmp
updateCB.updLine(row, output_row.name)
updateCB.checkPause()
if updateCB.stopRequested():
break
else:
if output_final is not None:
do_append(output_final.name, output_row.name, underneath=True)
os.unlink(output_row.name)
else:
output_final = output_row
updateCB.newFinal(output_final.name)
if output_final is not None:
shutil.move(output_final.name, name)
updateCB.finished(name)
else:
updateCB.finished(None)
return name
def random_wall(real_target_filename):
name = real_target_filename
filename = name[name.rindex("/"):]
name = filename[:filename.index(".")]
ext = filename[filename.index("."):]
target_filename = tempfile.gettempdir()+"/"+name+".2"+ext
try:
#remove any existing tmp file
os.unlink(target_filename)
except:
pass
try:
#if source already exist, build up on it
os.system("cp %s %s" % (target_filename, real_target_filename))
except:
pass
print("Target file is %s" % real_target_filename )
target = None
if mime is not None:
try:
mimetype = mime.from_file(target_filename)
if "symbolic link" in mimetype:
filename = os.readlink(target_filename)
mimetype = mime.from_file(target_filename)
if "image" in mimetype:
target = Image(filename=target_filename)
except IOError:
pass
if target is None:
height = PARAMS["LINES"] * PARAMS["LINE_HEIGHT"]
do_blank_image(height, PARAMS["WIDTH"], target_filename)
target = Image(filename=target_filename)
cnt = 0
while True:
updateCB.checkPause()
if updateCB.stopRequested():
break
filename = get_next_file()
print(filename)
img = Image(filename=filename)
with img.clone() as clone:
if PARAMS["DO_RESIZE"]:
factor = float(PARAMS["LINE_HEIGHT"])/clone.height
clone.resize(width=int(clone.width*factor), height=int(clone.height*factor))
do_polaroid_and_random_composite(target_filename, target, clone, filename)
updateCB.checkPause()
if updateCB.stopRequested():
break
updateCB.newImage(row=cnt, filename=filename)
updateCB.newFinal(target_filename)
os.system("cp %s %s" % (target_filename, real_target_filename))
cnt += 1
updateCB.checkPause()
if updateCB.stopRequested():
break
time.sleep(PARAMS["SLEEP_TIME"])
updateCB.checkPause()
if updateCB.stopRequested():
break
get_next_file = None
def path_is_jnetfs(path):
#check if PATH is VFS or not
df_output_lines = os.popen("df -Ph '%s'" % path).read().splitlines()
return df_output_lines and "JnetFS" in df_output_lines[1]
def fix_args():
global get_next_file
if PARAMS["PATH"][-1] != "/":
PARAMS["PATH"] += "/"
if PARAMS["FORCE_NO_VFS"]:
PARAMS["USE_VFS"]
elif PARAMS["FORCE_NO_VFS"]:
PARAMS["USE_VFS"]
else:
PARAMS["USE_VFS"] = path_is_jnetfs(PARAMS["PATH"])
if not PARAMS["USE_VFS"]:
get_next_file = GetFileDir(PARAMS["PICK_RANDOM"]).get_next_file
else:
get_next_file = get_next_file_vfs
def do_main():
fix_args()
updateCB.newExec()
target = PARAMS["TARGET"]
if not(PARAMS["PUT_RANDOM"]):
photowall(target)
else:
random_wall(target)
if __name__== "__main__":
do_main()
| Java |
/*
* Copyright (C) 2019 phramusca ( https://github.com/phramusca/ )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jamuz.process.book;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author phramusca ( https://github.com/phramusca/ )
*/
public class TableModelBookTest {
/**
*
*/
public TableModelBookTest() {
}
/**
*
*/
@BeforeClass
public static void setUpClass() {
}
/**
*
*/
@AfterClass
public static void tearDownClass() {
}
/**
*
*/
@Before
public void setUp() {
}
/**
*
*/
@After
public void tearDown() {
}
/**
* Test of isCellEditable method, of class TableModelBook.
*/
@Test
public void testIsCellEditable() {
System.out.println("isCellEditable");
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
boolean expResult = false;
boolean result = instance.isCellEditable(row, col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of isCellEnabled method, of class TableModelBook.
*/
@Test
public void testIsCellEnabled() {
System.out.println("isCellEnabled");
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
boolean expResult = false;
boolean result = instance.isCellEnabled(row, col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getBooks method, of class TableModelBook.
*/
@Test
public void testGetBooks() {
System.out.println("getBooks");
TableModelBook instance = new TableModelBook();
List<Book> expResult = null;
List<Book> result = instance.getBooks();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getFile method, of class TableModelBook.
*/
@Test
public void testGetFile() {
System.out.println("getFile");
int index = 0;
TableModelBook instance = new TableModelBook();
Book expResult = null;
Book result = instance.getFile(index);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getLengthAll method, of class TableModelBook.
*/
@Test
public void testGetLengthAll() {
System.out.println("getLengthAll");
TableModelBook instance = new TableModelBook();
long expResult = 0L;
long result = instance.getLengthAll();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getNbSelected method, of class TableModelBook.
*/
@Test
public void testGetNbSelected() {
System.out.println("getNbSelected");
TableModelBook instance = new TableModelBook();
int expResult = 0;
int result = instance.getNbSelected();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getRowCount method, of class TableModelBook.
*/
@Test
public void testGetRowCount() {
System.out.println("getRowCount");
TableModelBook instance = new TableModelBook();
int expResult = 0;
int result = instance.getRowCount();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getValueAt method, of class TableModelBook.
*/
@Test
public void testGetValueAt() {
System.out.println("getValueAt");
int rowIndex = 0;
int columnIndex = 0;
TableModelBook instance = new TableModelBook();
Object expResult = null;
Object result = instance.getValueAt(rowIndex, columnIndex);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setValueAt method, of class TableModelBook.
*/
@Test
public void testSetValueAt() {
System.out.println("setValueAt");
Object value = null;
int row = 0;
int col = 0;
TableModelBook instance = new TableModelBook();
instance.setValueAt(value, row, col);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of select method, of class TableModelBook.
*/
@Test
public void testSelect() {
System.out.println("select");
Book book = null;
boolean selected = false;
TableModelBook instance = new TableModelBook();
instance.select(book, selected);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getLengthSelected method, of class TableModelBook.
*/
@Test
public void testGetLengthSelected() {
System.out.println("getLengthSelected");
TableModelBook instance = new TableModelBook();
long expResult = 0L;
long result = instance.getLengthSelected();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getColumnClass method, of class TableModelBook.
*/
@Test
public void testGetColumnClass() {
System.out.println("getColumnClass");
int col = 0;
TableModelBook instance = new TableModelBook();
Class expResult = null;
Class result = instance.getColumnClass(col);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of clear method, of class TableModelBook.
*/
@Test
public void testClear() {
System.out.println("clear");
TableModelBook instance = new TableModelBook();
instance.clear();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of addRow method, of class TableModelBook.
*/
@Test
public void testAddRow() {
System.out.println("addRow");
Book file = null;
TableModelBook instance = new TableModelBook();
instance.addRow(file);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of removeRow method, of class TableModelBook.
*/
@Test
public void testRemoveRow() {
System.out.println("removeRow");
Book file = null;
TableModelBook instance = new TableModelBook();
instance.removeRow(file);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of loadThumbnails method, of class TableModelBook.
*/
@Test
public void testLoadThumbnails() {
System.out.println("loadThumbnails");
TableModelBook instance = new TableModelBook();
instance.loadThumbnails();
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table.head, table.foot { width: 100%; }
td.head-rtitle, td.foot-os { text-align: right; }
td.head-vol { text-align: center; }
table.foot td { width: 50%; }
table.head td { width: 33%; }
div.spacer { margin: 1em 0; }
</style>
<title>
LNSTAT(8)</title>
</head>
<body>
<div class="mandoc">
<table class="head">
<tbody>
<tr>
<td class="head-ltitle">
LNSTAT(8)</td>
<td class="head-vol">
System Manager's Manual</td>
<td class="head-rtitle">
LNSTAT(8)</td>
</tr>
</tbody>
</table>
<div class="section">
<h1>NAME</h1> lnstat - unified linux network statistics</div>
<div class="section">
<h1>SYNOPSIS</h1> <b>lnstat</b> [<i>options</i>]</div>
<div class="section">
<h1>DESCRIPTION</h1> This manual page documents briefly the <b>lnstat</b> command.<div class="spacer">
</div>
<b>lnstat</b> is a generalized and more feature-complete replacement for the old rtstat program. In addition to routing cache statistics, it supports any kind of statistics the linux kernel exports via a file in /proc/net/stat/.</div>
<div class="section">
<h1>OPTIONS</h1> lnstat supports the following options.<dl>
<dt>
<b>-h, --help</b></dt>
<dd>
Show summary of options.</dd>
</dl>
<dl>
<dt>
<b>-V, --version</b></dt>
<dd>
Show version of program.</dd>
</dl>
<dl>
<dt>
<b>-c, --count <count></b></dt>
<dd>
Print <count> number of intervals.</dd>
</dl>
<dl>
<dt>
<b>-d, --dump</b></dt>
<dd>
Dump list of available files/keys.</dd>
</dl>
<dl>
<dt>
<b>-f, --file <file></b></dt>
<dd>
Statistics file to use.</dd>
</dl>
<dl>
<dt>
<b>-i, --interval <intv></b></dt>
<dd>
Set interval to 'intv' seconds.</dd>
</dl>
<dl>
<dt>
<b>-j, --json</b></dt>
<dd>
Display results in JSON format</dd>
</dl>
<dl>
<dt>
<b>-k, --keys k,k,k,...</b></dt>
<dd>
Display only keys specified.</dd>
</dl>
<dl>
<dt>
<b>-s, --subject [0-2]</b></dt>
<dd>
Specify display of subject/header. '0' means no header at all, '1' prints a header only at start of the program and '2' prints a header every 20 lines.</dd>
</dl>
<dl>
<dt>
<b>-w, --width n,n,n,...</b></dt>
<dd>
Width for each field.</dd>
</dl>
</div>
<div class="section">
<h1>USAGE EXAMPLES</h1><dl>
<dt>
<b># lnstat -d</b></dt>
<dd>
Get a list of supported statistics files.</dd>
</dl>
<dl>
<dt>
<b># lnstat -k arp_cache:entries,rt_cache:in_hit,arp_cache:destroys</b></dt>
<dd>
Select the specified files and keys.</dd>
</dl>
<dl>
<dt>
<b># lnstat -i 10</b></dt>
<dd>
Use an interval of 10 seconds.</dd>
</dl>
<dl>
<dt>
<b># lnstat -f ip_conntrack</b></dt>
<dd>
Use only the specified file for statistics.</dd>
</dl>
<dl>
<dt>
<b># lnstat -s 0</b></dt>
<dd>
Do not print a header at all.</dd>
</dl>
<dl>
<dt>
<b># lnstat -s 20</b></dt>
<dd>
Print a header at start and every 20 lines.</dd>
</dl>
<dl>
<dt>
<b># lnstat -c -1 -i 1 -f rt_cache -k entries,in_hit,in_slow_tot</b></dt>
<dd>
Display statistics for keys entries, in_hit and in_slow_tot of field rt_cache every second.</dd>
</dl>
</div>
<div class="section">
<h1>SEE ALSO</h1> <b>ip</b>(8), and /usr/share/doc/iproute-doc/README.lnstat (package iproute-doc on Debian)<div style="height: 0.00em;">
 </div>
</div>
<div class="section">
<h1>AUTHOR</h1> lnstat was written by Harald Welte <laforge@gnumonks.org>.<div class="spacer">
</div>
This manual page was written by Michael Prokop <mika@grml.org> for the Debian project (but may be used by others).</div>
<table class="foot">
<tr>
<td class="foot-date">
</td>
<td class="foot-os">
</td>
</tr>
</table>
</div>
</body>
</html>
| Java |
#!/bin/sh
#
# Build and test mocpy in a 32-bit environment with python3
#
# Usage:
# testing_py3_ubuntu32.sh
#
# Update packages to the latest available versions
linux32 --32bit i386 sh -c '
apt update > /dev/null &&
apt install -y curl pkg-config libfreetype6-dev \
python3 python3-pip >/dev/null &&
# Symbolic link so that pyO3 points to the
# python3 version
ln -s /usr/bin/python3 /usr/bin/python
' &&
# Run the tests
linux32 --32bit i386 sh -c '
pip3 install -U pip &&
# Download the dependencies for compiling cdshealpix
pip install -r requirements/contributing.txt &&
pip install setuptools_rust &&
# Install Rust compiler
curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain nightly -y &&
export PATH="$HOME/.cargo/bin:$PATH" &&
# Build the rust dynamic library
python3 setup.py build_rust &&
# Move the dynamic lib to the python package folder
find build/ -name "*.so" -type f -exec cp {} ./mocpy \; &&
python3 -m pytest -v mocpy
'
| Java |
<?PHP
class ftp {
/**
* @var string FTP Host
*/
private $_host;
/**
* @var string FTP Port
*/
private $_port;
/**
* @var string FTP User
*/
private $_user;
/**
* @var string FTP Passwort
*/
private $_password;
/**
* @var ressource FTP Verbindung
*/
private $_connection;
/**
* @var bool befindet man sich im Lito Ordner (Root)
*/
public $lito_root = false; //Wenn true, kann der Paketmanager diese Verbindung verwenden
/**
* @var bool Steht die Verbindung?
*/
public $connected = false;
/**
* @var string PHP or FTP
*/
private $_method = 'PHP';
/**
* Daten angeben um eine Verbindung herzustellen
* @param string host
* @param string user
* @param string password
* @param string rootdir Verzeichniss auf dem Server
* @param int port
*/
/**
* @var string rootdir for phpmode
*/
private $rootdir = './';
public function ftp($host = '', $user = '', $password = '', $rootdir = './', $port = 21) {
if(defined('C_FTP_METHOD')){
$this->_method = C_FTP_METHOD;
}
if($this->_method == 'PHP'){
$rootdir=LITO_ROOT_PATH;
if(!is_dir($rootdir))
return false;
$this->rootdir = preg_replace('!\/$!', '', $rootdir);
$this->connected = true;
$this->lito_root = true;
//echo 'Useing PHP as a workaround!';
} else {
$this->_host = $host;
$this->_port = $port;
$this->_user = $user;
$this->_password = $password;
if (!@ $this->_connection = ftp_connect($this->_host, $this->_port))
return false;
if (!@ ftp_login($this->_connection, $this->_user, $this->_password))
return false;
$this->connected = true;
ftp_chdir($this->_connection, $rootdir);
//if ($this->exists('litotex.php'))
$this->lito_root = true;
}
}
/**
* Erstellt ein Verzeichniss
* @param string dir Verzeichnissname
*/
public function mk_dir($dir) {
if (!$this->connected)
return false;
if ($this->exists($dir)){
return true;
}
if($this->_method == 'PHP')
return mkdir($this->rootdir.'/'.$dir);
else
return @ ftp_mkdir($this->_connection, $dir);
}
/**
* L�scht ein Verzeichniss
* @param string dir Verzeichnissname
*/
public function rm_dir($dir) {
$dir = preg_replace('!^\/!', '', $dir);
if (!$this->connected)
return false;
if (!$this->exists($dir))
return false;
if($this->_method == 'PHP'){
$this->_php_all_delete($this->_rootdir.'/'.$dir);
} else {
$list = $this->list_files($dir);
if (is_array($list)) {
foreach ($list as $file) {
if (!is_array($this->list_files($file)) || in_array($file, $this->list_files($file))) {
$this->rm_file($file);
} else {
$this->rm_dir($file);
}
}
}
return @ ftp_rmdir($this->_connection, $dir);
}
}
/**
* Verschiebt ein Verzeichniss oder eine Datei
* @param string file Verzeichnissname/Dateiname
* @param string dest Ziel
*/
public function mv($file, $dest) {
if (!$this->connected)
return false;
if (!$this->exists($file))
return false;
if($this->_method == 'PHP'){
return @ rename($this->rootdir.'/'.$file, $this->rootdir.'/'.$dest);
} else
return @ftp_rename($this->_connection, $file, $dest);
}
/**
* Listet den Inhalt eines Verzeichnisses auf
* @param string dir Verzeichnissname
*/
public function list_files($dir = './') {
if (!$this->connected)
return false;
if($this->_method == 'PHP'){
if(!is_dir($this->rootdir.'/'.$dir))
return false;
$dir = opendir($this->rootdir.'/'.$dir);
$return = array();
while($file = readdir($dir)){
if($file == '.' || $file == '..')
continue;
$return[] = $file;
}
return $return;
} else {
$dir = preg_replace('!^\/!', '', $dir);
$return = @ ftp_nlist($this->_connection, './'.$dir);
if(!is_array($return))
return false;
foreach($return as $i => $param){
$return[$i] = preg_replace('!^'.str_replace("/", "\\/", $dir).'\\/!', '', $param);
}
return $return;
}
}
/**
* L�scht eine Datei
* @param string file Dateiname
*/
public function rm_file($file) {
if (!$this->connected)
return false;
if (!$this->exists($file))
return true;
if($file == '.' || $file == '..')
return false;
if($this->_method == 'PHP'){
if(!is_file($this->rootdir.'/'.$file))
return false;
return @unlink($this->rootdir.'/'.$file);
} else
return @ftp_delete($this->_connection, $file);
}
/**
* Setzt Berechtigungen
* @param string ch Berechtigungen
* @param string file Dateiname
*/
public function chown_perm($ch, $file) {
if (!$this->connected)
return false;
if (!$this->exists($file)){
return false;
}
if($this->_method == 'PHP'){
return @chmod($this->rootdir.'/'.$file, $ch);
} else
return @ftp_chmod($this->_connection, $ch, $file);
}
/**
* Gibt den Inhalt einer Datei zur�ck
* @param string file Dateiname
*/
public function get_contents($file) {
if (!$this->connected)
return false;
if (!$this->exists($file))
return false;
if($this->_method == 'PHP'){
if(!is_file($this->rootdir.'/'.$file))
return false;
return file_get_contents($this->rootdir.'/'.$file);
} else {
$time = time();
$local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'w');
ftp_fget($this->_connection, $local_cache, $file, FTP_BINARY);
$return = file_get_contents(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time);
fclose($local_cache);
unlink(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time);
return $return;
}
}
/**
* Schreibt in eine Datei
* @param string file Dateiname
* @param string new Neuer Inhalt
*/
public function write_contents($file, $new, $overwrite = true) {
if (!$this->connected)
return false;
if ($overwrite && $this->exists($file))
return false;
if($this->_method == 'PHP'){
$file_h = fopen($this->rootdir.'/'.$file, 'w');
fwrite($file_h, $new);
return @fclose($file_h);
} else {
$time = time();
$local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'w');
fwrite($local_cache, $new);
fclose($local_cache);
$local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'r');
@$return = ftp_fput($this->_connection, $file, $local_cache, FTP_BINARY);
fclose($local_cache);
unlink(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time);
return $return;
}
}
/**
* Kopiert dateien per FTP
* @param string file Zu kopierende Datei
* @param string dest Ziel
*/
public function copy_file($file, $dest){
$file_c = $this->get_contents($file);
$this->write_contents($dest, $file_c);
}
/**
* Kopiert Dateien und Ordner rekursiv per FTP
* @param string source Zu kopierendes Verzeichniss
* @param string dest Ziel
*/
public function copy_req($source, $dest){
$source = preg_replace("!\/$!", '', $source);
if(!$this->list_files($source))
return false;
if(!$this->exists($dest))
if(!$this->mk_dir($dest))
return false;
$source_files = $this->list_files($source);
foreach($source_files as $file){
if($file == '.' || $file == '..' || $file == $source.'/.' || $file == $source.'/..')
continue;
if(!preg_match('!'.preg_replace('!^\/!', '', $source).'!', $file))
$file = $source.'/'.$file;
if($this->isdir($file))
$this->copy_req($file, str_replace($source, $dest, $file));
else{
$this->copy_file($file, str_replace($source, $dest, $file));
}
}
}
/**
* Löscht ein Verzeichniss rekursiv
* @param string dir Verzeichniss
*/
public function req_remove($dir){
$dir = preg_replace('!\/$!', '', $dir);
if(!$this->exists($dir)){
return true;
}
if($dir == '.' || $dir == '..')
return false;
if(!$this->isdir($dir)){
return $this->rm_file($dir);
}
if($this->_method == 'PHP'){
$this->_php_all_delete($this->rootdir.'/'.$dir);
} else {
$files = $this->list_files($dir);
foreach($files as $file){
if($file == '.' || $file == '..')
continue;
$file = $dir.'/'.$file;
$this->req_remove($file);
}
$this->rm_dir($dir);
}
}
public function isdir($file){
if(!$this->exists($file))
return false;
if($this->_method == 'PHP'){
return is_dir($this->rootdir.'/'.$file);
} else {
if(ftp_size($this->_connection, $file) == -1)
return true;
return false;
}
}
/**
* Schließt die FTP Verbindung
*/
public function disconnect() {
if($this->_method == 'PHP')
$this->connected = false;
else{
if (!$this->connected)
return false;
ftp_close($this->_connection);
$this->connected = false;
}
}
/**
* �berpr�ft ob die angegebene Datei/das Verzeichniss existiert
* @param string file
* @return bool
*/
public function exists($file) {
if($this->_method == 'PHP'){
return file_exists($this->rootdir.'/'.$file);
} else {
$dir = dirname($file);
$file = basename($file);
if($dir == '.')
$dir = '';
if($dir == '' && count($this->list_files($dir)) == 0)
$dir = '.';
if (@ in_array($file, @ $this->list_files($dir), '/'))
return true;
else
return false;
}
}
/**
* Deletes a Directory recursivly
* @param $verz Direcotory
* @param $folder foldersarray (ignore!)
* @return array, deletet folders
*/
private function _php_dir_delete($verz, $folder = array())
{
$folder[] = $verz;
$fp = opendir($verz);
while ($dir_file = readdir($fp))
{
if (($dir_file == '.') || ($dir_file == '..'))
continue;
$neu_file = $verz . '/' . $dir_file;
if (is_dir($neu_file))
$folder = $this->_php_dir_delete($neu_file, $folder);
else
unlink($neu_file);
}
closedir($fp);
return $folder;
}
/**
* Deletes all (dirs and files)
* @param $dir_file dir or file to delete
* @return bool
*/
private function _php_all_delete($dir_file)
{
if (is_dir($dir_file))
{
$array = $this->_php_dir_delete($dir_file);
$array = array_reverse($array);
foreach ($array as $elem)
rmdir($elem);
}
elseif (is_file($dir_file))
unlink($dir_file);
else
return false;
}
}
?> | Java |
<head><title>Popular Baby Names</title>
<meta name="dc.language" scheme="ISO639-2" content="eng">
<meta name="dc.creator" content="OACT">
<meta name="lead_content_manager" content="JeffK">
<meta name="coder" content="JeffK">
<meta name="dc.date.reviewed" scheme="ISO8601" content="2005-12-30">
<link rel="stylesheet" href="../OACT/templatefiles/master.css" type="text/css" media="screen">
<link rel="stylesheet" href="../OACT/templatefiles/custom.css" type="text/css" media="screen">
<link rel="stylesheet" href="../OACT/templatefiles/print.css" type="text/css" media="print">
</head>
<body bgcolor="#ffffff" text="#000000" topmargin="1" leftmargin="0">
<table width="100%" border="0" cellspacing="0" cellpadding="4">
<tbody>
<tr>
<td class="sstop" valign="bottom" align="left" width="25%">
Social Security Online
</td>
<td valign="bottom" class="titletext">
<!-- sitetitle -->Popular Baby Names
</td>
</tr>
<tr bgcolor="#333366"><td colspan="2" height="2"></td></tr>
<tr>
<td class="graystars" width="25%" valign="top"> </td>
<td valign="top">
<a href="http://www.ssa.gov/"><img src="/templateimages/tinylogo.gif"
width="52" height="47" align="left"
alt="SSA logo: link to Social Security home page" border="0"></a><a name="content"></a>
<h1>Popular Names by State</h1>August 31, 2007</td>
</tr>
<tr bgcolor="#333366"><td colspan="2" height="1"></td></tr>
</tbody></table>
<table width="100%" border="0" cellspacing="0" cellpadding="4" summary="formatting">
<tbody>
<tr align="left" valign="top">
<td width="25%" class="whiteruled2-td">
<table width="92%" border="0" cellpadding="4" class="ninetypercent">
<tr>
<td class="whiteruled-td"><a href="../OACT/babynames/index.html">Popular
Baby Names</a></td>
</tr>
<tr>
<td class="whiteruled-td"><a href="../OACT/babynames/background.html">
Background information</a></td>
</tr>
<tr>
<td class="whiteruled2-td"><a href="../OACT/babynames/USbirthsNumident.html">Number
of U. S. births</a> based on Social Security card applications</td>
</tr>
</table>
<p>
Make another selection?<br />
<form method="post" action="/cgi-bin/namesbystate.cgi">
<label for="state">Select State</label><br />
<select name="state" size="1" id="state">
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="AR" selected>Arkansas</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DC">District of Columbia</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="IA">Iowa</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="MA">Massachusetts</option>
<option value="MD">Maryland</option>
<option value="ME">Maine</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MO">Missouri</option>
<option value="MS">Mississippi</option>
<option value="MT">Montana</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="NE">Nebraska</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NV">Nevada</option>
<option value="NY">New York</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VA">Virginia</option>
<option value="VT">Vermont</option>
<option value="WA">Washington</option>
<option value="WI">Wisconsin</option>
<option value="WV">West Virginia</option>
<option value="WY">Wyoming</option>
</select><p>
<label for="year">Enter a year between<br /> 1960-2004:</label>
<input type="text" name="year" size="4" maxlength="4" id="year" value="1981">
<p> <input type="submit" value=" Go ">
</form>
</p>
</td>
<td class="greyruled-td">
<p>
The following table shows the 100 most frequent given names for
male and female births in 1981 in Arkansas. The number to
the right of each name is the number of occurrences in the data.
The source is a 100% sample based on Social Security card application data.
See the <a href="../OACT/babynames/background.html">limitations</a> of this data source.
<p align="center">
<table width="72%" border="1" bordercolor="#aaabbb"
cellpadding="1" cellspacing="0">
<caption><b>Popularity for top 100 names in Arkansas for births in 1981</b>
</caption>
<tr align="center" valign="bottom">
<th scope="col" width="12%" bgcolor="#efefef">Rank</th>
<th scope="col" width="22%" bgcolor="#99ccff">Male name</th>
<th scope="col" width="22%" bgcolor="#99ccff">Number of<br /> males</th>
<th scope="col" width="22%" bgcolor="pink">Female name</th>
<th scope="col" width="22%" bgcolor="pink">Number of<br /> females</th></tr>
<tr align="right"><td>1</td>
<td align="center">Joshua</td>
<td>519</td>
<td align="center">Amanda</td>
<td>517</td></tr>
<tr align="right"><td>2</td>
<td align="center">Michael</td>
<td>512</td>
<td align="center">Jennifer</td>
<td>508</td></tr>
<tr align="right"><td>3</td>
<td align="center">James</td>
<td>499</td>
<td align="center">Jessica</td>
<td>354</td></tr>
<tr align="right"><td>4</td>
<td align="center">Christopher</td>
<td>478</td>
<td align="center">Crystal</td>
<td>268</td></tr>
<tr align="right"><td>5</td>
<td align="center">Jason</td>
<td>430</td>
<td align="center">Sarah</td>
<td>241</td></tr>
<tr align="right"><td>6</td>
<td align="center">John</td>
<td>392</td>
<td align="center">Amber</td>
<td>233</td></tr>
<tr align="right"><td>7</td>
<td align="center">Matthew</td>
<td>351</td>
<td align="center">Ashley</td>
<td>223</td></tr>
<tr align="right"><td>8</td>
<td align="center">David</td>
<td>331</td>
<td align="center">Amy</td>
<td>204</td></tr>
<tr align="right"><td>9</td>
<td align="center">Brandon</td>
<td>328</td>
<td align="center">Kimberly</td>
<td>202</td></tr>
<tr align="right"><td>10</td>
<td align="center">Justin</td>
<td>317</td>
<td align="center">Melissa</td>
<td>200</td></tr>
<tr align="right"><td>11</td>
<td align="center">Robert</td>
<td>312</td>
<td align="center">Tiffany</td>
<td>198</td></tr>
<tr align="right"><td>12</td>
<td align="center">Jeremy</td>
<td>300</td>
<td align="center">Angela</td>
<td>188</td></tr>
<tr align="right"><td>13</td>
<td align="center">William</td>
<td>285</td>
<td align="center">Stephanie</td>
<td>185</td></tr>
<tr align="right"><td>14</td>
<td align="center">Jonathan</td>
<td>265</td>
<td align="center">April</td>
<td>183</td></tr>
<tr align="right"><td>15</td>
<td align="center">Joseph</td>
<td>245</td>
<td align="center">Heather</td>
<td>177</td></tr>
<tr align="right"><td>16</td>
<td align="center">Brian</td>
<td>204</td>
<td align="center">Brandy</td>
<td>165</td></tr>
<tr align="right"><td>17</td>
<td align="center">Daniel</td>
<td>194</td>
<td align="center">Rebecca</td>
<td>159</td></tr>
<tr align="right"><td>18</td>
<td align="center">Charles</td>
<td>174</td>
<td align="center">Rachel</td>
<td>157</td></tr>
<tr align="right"><td>19</td>
<td align="center">Kevin</td>
<td>171</td>
<td align="center">Mary</td>
<td>132</td></tr>
<tr align="right"><td>20</td>
<td align="center">Steven</td>
<td>167</td>
<td align="center">Elizabeth</td>
<td>131</td></tr>
<tr align="right"><td>21</td>
<td align="center">Timothy</td>
<td>162</td>
<td align="center">Jamie</td>
<td>125</td></tr>
<tr align="right"><td>22</td>
<td align="center">Eric</td>
<td>158</td>
<td align="center">Andrea</td>
<td>119</td></tr>
<tr align="right"><td>23</td>
<td align="center">Nicholas</td>
<td>155</td>
<td align="center">Brandi</td>
<td>117</td></tr>
<tr align="right"><td>24</td>
<td align="center">Aaron</td>
<td>154</td>
<td align="center">Laura</td>
<td>116</td></tr>
<tr align="right"><td>25</td>
<td align="center">Adam</td>
<td>151</td>
<td align="center">Lisa</td>
<td>116</td></tr>
<tr align="right"><td>26</td>
<td align="center">Dustin</td>
<td>148</td>
<td align="center">Misty</td>
<td>116</td></tr>
<tr align="right"><td>27</td>
<td align="center">Richard</td>
<td>136</td>
<td align="center">Leslie</td>
<td>86</td></tr>
<tr align="right"><td>28</td>
<td align="center">Anthony</td>
<td>133</td>
<td align="center">Courtney</td>
<td>85</td></tr>
<tr align="right"><td>29</td>
<td align="center">Ryan</td>
<td>133</td>
<td align="center">Michelle</td>
<td>85</td></tr>
<tr align="right"><td>30</td>
<td align="center">Thomas</td>
<td>131</td>
<td align="center">Erin</td>
<td>84</td></tr>
<tr align="right"><td>31</td>
<td align="center">Benjamin</td>
<td>114</td>
<td align="center">Christina</td>
<td>82</td></tr>
<tr align="right"><td>32</td>
<td align="center">Nathan</td>
<td>113</td>
<td align="center">Erica</td>
<td>77</td></tr>
<tr align="right"><td>33</td>
<td align="center">Stephen</td>
<td>109</td>
<td align="center">Sara</td>
<td>77</td></tr>
<tr align="right"><td>34</td>
<td align="center">Travis</td>
<td>109</td>
<td align="center">Julie</td>
<td>76</td></tr>
<tr align="right"><td>35</td>
<td align="center">Bradley</td>
<td>106</td>
<td align="center">Shannon</td>
<td>76</td></tr>
<tr align="right"><td>36</td>
<td align="center">Chad</td>
<td>106</td>
<td align="center">Emily</td>
<td>73</td></tr>
<tr align="right"><td>37</td>
<td align="center">Andrew</td>
<td>101</td>
<td align="center">Latoya</td>
<td>70</td></tr>
<tr align="right"><td>38</td>
<td align="center">Marcus</td>
<td>96</td>
<td align="center">Samantha</td>
<td>70</td></tr>
<tr align="right"><td>39</td>
<td align="center">Jacob</td>
<td>95</td>
<td align="center">Kelly</td>
<td>69</td></tr>
<tr align="right"><td>40</td>
<td align="center">Jeffrey</td>
<td>94</td>
<td align="center">Tara</td>
<td>66</td></tr>
<tr align="right"><td>41</td>
<td align="center">Mark</td>
<td>93</td>
<td align="center">Carrie</td>
<td>65</td></tr>
<tr align="right"><td>42</td>
<td align="center">Patrick</td>
<td>88</td>
<td align="center">Holly</td>
<td>64</td></tr>
<tr align="right"><td>43</td>
<td align="center">Kenneth</td>
<td>82</td>
<td align="center">Lindsey</td>
<td>58</td></tr>
<tr align="right"><td>44</td>
<td align="center">Jesse</td>
<td>78</td>
<td align="center">Natalie</td>
<td>58</td></tr>
<tr align="right"><td>45</td>
<td align="center">Billy</td>
<td>77</td>
<td align="center">Natasha</td>
<td>58</td></tr>
<tr align="right"><td>46</td>
<td align="center">Bobby</td>
<td>77</td>
<td align="center">Alicia</td>
<td>57</td></tr>
<tr align="right"><td>47</td>
<td align="center">Paul</td>
<td>77</td>
<td align="center">Katherine</td>
<td>57</td></tr>
<tr align="right"><td>48</td>
<td align="center">Larry</td>
<td>75</td>
<td align="center">Christy</td>
<td>56</td></tr>
<tr align="right"><td>49</td>
<td align="center">Gary</td>
<td>74</td>
<td align="center">Patricia</td>
<td>56</td></tr>
<tr align="right"><td>50</td>
<td align="center">Derrick</td>
<td>73</td>
<td align="center">Brooke</td>
<td>55</td></tr>
<tr align="right"><td>51</td>
<td align="center">Jared</td>
<td>73</td>
<td align="center">Lauren</td>
<td>54</td></tr>
<tr align="right"><td>52</td>
<td align="center">Jimmy</td>
<td>70</td>
<td align="center">Kristin</td>
<td>53</td></tr>
<tr align="right"><td>53</td>
<td align="center">Jeffery</td>
<td>69</td>
<td align="center">Kristen</td>
<td>52</td></tr>
<tr align="right"><td>54</td>
<td align="center">Keith</td>
<td>68</td>
<td align="center">Nicole</td>
<td>52</td></tr>
<tr align="right"><td>55</td>
<td align="center">Scott</td>
<td>67</td>
<td align="center">Cynthia</td>
<td>51</td></tr>
<tr align="right"><td>56</td>
<td align="center">Antonio</td>
<td>64</td>
<td align="center">Leah</td>
<td>51</td></tr>
<tr align="right"><td>57</td>
<td align="center">Phillip</td>
<td>64</td>
<td align="center">Dana</td>
<td>50</td></tr>
<tr align="right"><td>58</td>
<td align="center">Shawn</td>
<td>63</td>
<td align="center">Tonya</td>
<td>50</td></tr>
<tr align="right"><td>59</td>
<td align="center">Jerry</td>
<td>61</td>
<td align="center">Pamela</td>
<td>49</td></tr>
<tr align="right"><td>60</td>
<td align="center">Terry</td>
<td>59</td>
<td align="center">Katrina</td>
<td>48</td></tr>
<tr align="right"><td>61</td>
<td align="center">Gregory</td>
<td>58</td>
<td align="center">Tina</td>
<td>48</td></tr>
<tr align="right"><td>62</td>
<td align="center">Kyle</td>
<td>58</td>
<td align="center">Candace</td>
<td>46</td></tr>
<tr align="right"><td>63</td>
<td align="center">Zachary</td>
<td>57</td>
<td align="center">Candice</td>
<td>45</td></tr>
<tr align="right"><td>64</td>
<td align="center">Cody</td>
<td>56</td>
<td align="center">Kristy</td>
<td>44</td></tr>
<tr align="right"><td>65</td>
<td align="center">Brent</td>
<td>55</td>
<td align="center">Lori</td>
<td>44</td></tr>
<tr align="right"><td>66</td>
<td align="center">Wesley</td>
<td>53</td>
<td align="center">Megan</td>
<td>44</td></tr>
<tr align="right"><td>67</td>
<td align="center">Bryan</td>
<td>52</td>
<td align="center">Miranda</td>
<td>44</td></tr>
<tr align="right"><td>68</td>
<td align="center">Corey</td>
<td>52</td>
<td align="center">Stacy</td>
<td>44</td></tr>
<tr align="right"><td>69</td>
<td align="center">Derek</td>
<td>51</td>
<td align="center">Casey</td>
<td>41</td></tr>
<tr align="right"><td>70</td>
<td align="center">Ricky</td>
<td>51</td>
<td align="center">Krystal</td>
<td>41</td></tr>
<tr align="right"><td>71</td>
<td align="center">Casey</td>
<td>50</td>
<td align="center">Monica</td>
<td>40</td></tr>
<tr align="right"><td>72</td>
<td align="center">Ronald</td>
<td>50</td>
<td align="center">Robin</td>
<td>40</td></tr>
<tr align="right"><td>73</td>
<td align="center">Donald</td>
<td>49</td>
<td align="center">Anna</td>
<td>39</td></tr>
<tr align="right"><td>74</td>
<td align="center">Edward</td>
<td>48</td>
<td align="center">Latasha</td>
<td>38</td></tr>
<tr align="right"><td>75</td>
<td align="center">Randy</td>
<td>45</td>
<td align="center">Tasha</td>
<td>38</td></tr>
<tr align="right"><td>76</td>
<td align="center">Samuel</td>
<td>45</td>
<td align="center">Susan</td>
<td>37</td></tr>
<tr align="right"><td>77</td>
<td align="center">Johnny</td>
<td>44</td>
<td align="center">Felicia</td>
<td>35</td></tr>
<tr align="right"><td>78</td>
<td align="center">Danny</td>
<td>43</td>
<td align="center">Lindsay</td>
<td>35</td></tr>
<tr align="right"><td>79</td>
<td align="center">Jeremiah</td>
<td>40</td>
<td align="center">Mandy</td>
<td>35</td></tr>
<tr align="right"><td>80</td>
<td align="center">Raymond</td>
<td>39</td>
<td align="center">Melanie</td>
<td>35</td></tr>
<tr align="right"><td>81</td>
<td align="center">Sean</td>
<td>39</td>
<td align="center">Tracy</td>
<td>35</td></tr>
<tr align="right"><td>82</td>
<td align="center">Clinton</td>
<td>38</td>
<td align="center">Alisha</td>
<td>34</td></tr>
<tr align="right"><td>83</td>
<td align="center">Blake</td>
<td>37</td>
<td align="center">Linda</td>
<td>34</td></tr>
<tr align="right"><td>84</td>
<td align="center">Douglas</td>
<td>36</td>
<td align="center">Bethany</td>
<td>33</td></tr>
<tr align="right"><td>85</td>
<td align="center">Johnathan</td>
<td>36</td>
<td align="center">Cassandra</td>
<td>33</td></tr>
<tr align="right"><td>86</td>
<td align="center">Nathaniel</td>
<td>36</td>
<td align="center">Danielle</td>
<td>33</td></tr>
<tr align="right"><td>87</td>
<td align="center">Tony</td>
<td>36</td>
<td align="center">Julia</td>
<td>33</td></tr>
<tr align="right"><td>88</td>
<td align="center">Jessie</td>
<td>35</td>
<td align="center">Summer</td>
<td>33</td></tr>
<tr align="right"><td>89</td>
<td align="center">Lucas</td>
<td>35</td>
<td align="center">Tammy</td>
<td>33</td></tr>
<tr align="right"><td>90</td>
<td align="center">Ronnie</td>
<td>35</td>
<td align="center">Allison</td>
<td>32</td></tr>
<tr align="right"><td>91</td>
<td align="center">Tommy</td>
<td>35</td>
<td align="center">Brittany</td>
<td>32</td></tr>
<tr align="right"><td>92</td>
<td align="center">Clayton</td>
<td>34</td>
<td align="center">Rebekah</td>
<td>32</td></tr>
<tr align="right"><td>93</td>
<td align="center">George</td>
<td>34</td>
<td align="center">Sherry</td>
<td>32</td></tr>
<tr align="right"><td>94</td>
<td align="center">Joe</td>
<td>34</td>
<td align="center">Jenny</td>
<td>31</td></tr>
<tr align="right"><td>95</td>
<td align="center">Rodney</td>
<td>34</td>
<td align="center">Katie</td>
<td>31</td></tr>
<tr align="right"><td>96</td>
<td align="center">Adrian</td>
<td>33</td>
<td align="center">Regina</td>
<td>31</td></tr>
<tr align="right"><td>97</td>
<td align="center">Micheal</td>
<td>33</td>
<td align="center">Rhonda</td>
<td>31</td></tr>
<tr align="right"><td>98</td>
<td align="center">Randall</td>
<td>33</td>
<td align="center">Stacey</td>
<td>31</td></tr>
<tr align="right"><td>99</td>
<td align="center">Lee</td>
<td>32</td>
<td align="center">Tabitha</td>
<td>31</td></tr>
<tr align="right"><td>100</td>
<td align="center">Shane</td>
<td>32</td>
<td align="center">Whitney</td>
<td>31</td></tr>
</table></td></tr></table>
<table class="printhide" width="100%" border="0" cellpadding="1" cellspacing="0">
<tr bgcolor="#333366"><td height="1" valign="top" height="1" colspan="3"></td></tr>
<tr>
<td width="26%" valign="middle"> <a href="http://www.firstgov.gov"><img
src="/templateimages/firstgov3.gif" width="72" height="15"
alt="Link to FirstGov.gov: U.S. Government portal" border="0"></a></td>
<td valign="top" class="seventypercent">
<a href="http://www.ssa.gov/privacy.html">Privacy Policy</a>
| <a href="http://www.ssa.gov/websitepolicies.htm">Website Policies
& Other Important Information</a>
| <a href="http://www.ssa.gov/sitemap.htm">Site Map</a></td>
</tr>
</table>
</body></html>
| Java |
#ifndef RESIDUAL_H
#define RESIDUAL_H
#include "base.h"
#include "peak_detection.h"
#include "partial_tracking.h"
#include "synthesis.h"
extern "C" {
#include "sms.h"
}
using namespace std;
namespace simpl
{
// ---------------------------------------------------------------------------
// Residual
//
// Calculate a residual signal
// ---------------------------------------------------------------------------
class Residual {
protected:
int _frame_size;
int _hop_size;
int _sampling_rate;
Frames _frames;
void clear();
public:
Residual();
~Residual();
virtual void reset();
int frame_size();
virtual void frame_size(int new_frame_size);
int hop_size();
virtual void hop_size(int new_hop_size);
int sampling_rate();
void sampling_rate(int new_sampling_rate);
virtual void residual_frame(Frame* frame);
virtual void find_residual(int synth_size, sample* synth,
int original_size, sample* original,
int residual_size, sample* residual);
virtual void synth_frame(Frame* frame);
virtual Frames synth(Frames& frames);
virtual Frames synth(int original_size, sample* original);
};
// ---------------------------------------------------------------------------
// SMSResidual
// ---------------------------------------------------------------------------
class SMSResidual : public Residual {
private:
SMSResidualParams _residual_params;
SMSPeakDetection _pd;
SMSPartialTracking _pt;
SMSSynthesis _synth;
public:
SMSResidual();
~SMSResidual();
void reset();
void frame_size(int new_frame_size);
void hop_size(int new_hop_size);
int num_stochastic_coeffs();
void num_stochastic_coeffs(int new_num_stochastic_coeffs);
void residual_frame(Frame* frame);
void synth_frame(Frame* frame);
};
} // end of namespace Simpl
#endif
| Java |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>ndnSIM for iCenS: /home/network/NSOL/ndnSIM-dev/ns-3/src/ndnSIM/model/cs/custom-policies Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">ndnSIM for iCenS
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,'Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_3f14f6767c31cb4a1d22c13c18cc6fc3.html">model</a></li><li class="navelem"><a class="el" href="dir_b8559f3e867009595f1342820a7715ba.html">cs</a></li><li class="navelem"><a class="el" href="dir_5d6f6271b0ce2ddab294170ccac04363.html">custom-policies</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">custom-policies Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.12
</small></address>
</body>
</html>
| Java |
/*
* This file is part of EchoPet.
*
* EchoPet 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.
*
* EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type;
import com.dsh105.echopet.compat.api.entity.EntityPetType;
import com.dsh105.echopet.compat.api.entity.EntitySize;
import com.dsh105.echopet.compat.api.entity.IPet;
import com.dsh105.echopet.compat.api.entity.PetType;
import com.dsh105.echopet.compat.api.entity.SizeCategory;
import com.dsh105.echopet.compat.api.entity.type.nms.IEntityGiantPet;
import net.minecraft.server.v1_14_R1.EntityTypes;
import net.minecraft.server.v1_14_R1.World;
@EntitySize(width = 5.5F, height = 5.5F)
@EntityPetType(petType = PetType.GIANT)
public class EntityGiantPet extends EntityZombiePet implements IEntityGiantPet{
public EntityGiantPet(World world){
super(EntityTypes.GIANT, world);
}
public EntityGiantPet(World world, IPet pet){
super(EntityTypes.GIANT, world, pet);
}
@Override
public SizeCategory getSizeCategory(){
return SizeCategory.OVERSIZE;
}
}
| Java |
<?php
namespace GO\Base\Fs;
class MemoryFile extends File{
private $_data;
public function __construct($filename, $data) {
$this->_data = $data;
return parent::__construct($filename);
}
public function getContents() {
return $this->_data;
}
public function contents() {
return $this->_data;
}
public function putContents($data, $flags = null, $context = null) {
if($flags = FILE_APPEND){
$this->_data .= $data;
}else
{
$this->_data = $data;
}
}
public function size() {
return strlen($this->_data);
}
public function mtime() {
return time();
}
public function ctime() {
return time();
}
public function exists() {
return true;
}
public function move(Base $destinationFolder, $newFileName = false, $isUploadedFile = false, $appendNumberToNameIfDestinationExists = false) {
throw Exception("move not implemented for memory file");
}
public function copy(Folder $destinationFolder, $newFileName = false) {
throw Exception("copy not implemented for memory file");
}
public function parent() {
return false;
}
public function child($filename) {
throw Exception("child not possible for memory file");
}
public function createChild($filename, $isFile = true) {
throw Exception("createChild not possible for memory file");
}
/**
* Check if the file or folder is writable for the webserver user.
*
* @return boolean
*/
public function isWritable(){
return true;
}
/**
* Change owner
* @param StringHelper $user
* @return boolean
*/
public function chown($user){
return false;
}
/**
* Change group
*
* @param StringHelper $group
* @return boolean
*/
public function chgrp($group){
return false;
}
/**
*
* @param int $permissionsMode <p>
* Note that mode is not automatically
* assumed to be an octal value, so strings (such as "g+w") will
* not work properly. To ensure the expected operation,
* you need to prefix mode with a zero (0):
* </p>
*
* @return boolean
*/
public function chmod($permissionsMode){
return false;
}
/**
* Delete the file
*
* @return boolean
*/
public function delete(){
return false;
}
public function isFolder() {
return false;
}
/**
* Check if this object is a file.
*
* @return boolean
*/
public function isFile(){
return true;
}
public function rename($name){
$this->path=$name;
}
public function appendNumberToNameIfExists() {
return $this->path;
}
public function output() {
echo $this->_data;
}
public function setDefaultPermissions() {
}
public function md5Hash(){
return md5($this->_data);
}
}
| Java |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>My Project: SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">My Project
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespace_sample_hospital_model.html">SampleHospitalModel</a></li><li class="navelem"><a class="el" href="namespace_sample_hospital_model_1_1_visualization.html">Visualization</a></li><li class="navelem"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html">WPFVisualizationEngineOutpatientDepartment</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#properties">Properties</a> |
<a href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Additional visualization for outpatient control units, with extra visualization of waiting list numbers: Number of patients waiting for a slot to be assigned Number of patients waiting for slots
<a href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#details">More...</a></p>
<div class="dynheader">
Inheritance diagram for SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment:</div>
<div class="dyncontent">
<div class="center">
<img src="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.png" usemap="#SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map" alt=""/>
<map id="SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map" name="SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map">
<area href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html" alt="SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit< OutpatientActionTypeClass >" shape="rect" coords="0,0,715,24"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#a50cbb97ee541ebb20c7ce54fb48960ed">WPFVisualizationEngineOutpatientDepartment</a> (<a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a> drawingSystem, Point position, <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a> size, double personSize)</td></tr>
<tr class="memdesc:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="mdescLeft"> </td><td class="mdescRight">Basic constructor, just calls base constructor <a href="#a50cbb97ee541ebb20c7ce54fb48960ed">More...</a><br /></td></tr>
<tr class="separator:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="memItemLeft" align="right" valign="top">override void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#af8be5c28237bb4fc3261b13bcdb5aa45">AdditionalStaticVisualization</a> (DateTime initializationTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit)</td></tr>
<tr class="memdesc:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="mdescLeft"> </td><td class="mdescRight">Calls base class method and additiona visualization for string captions <a href="#af8be5c28237bb4fc3261b13bcdb5aa45">More...</a><br /></td></tr>
<tr class="separator:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="memItemLeft" align="right" valign="top">override void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#ab14586d925c0fcb7c6d77394fe4c8d65">AdditionalDynamicVisualization</a> (DateTime currentTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit, IEnumerable< <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> > currentEvents)</td></tr>
<tr class="memdesc:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="mdescLeft"> </td><td class="mdescRight">Additionally to event handling methods for visualization, the number of patients waiting for a slot to be assigned or waiting for a slot are showed. <a href="#ab14586d925c0fcb7c6d77394fe4c8d65">More...</a><br /></td></tr>
<tr class="separator:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit')"><img src="closed.png" alt="-"/> Public Member Functions inherited from <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html">SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit< OutpatientActionTypeClass ></a></td></tr>
<tr class="memitem:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a897a51338edd7243dcf4dfda927be6b6">WPFVisualizationEngineHealthCareDepartmentControlUnit</a> (<a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a> drawingSystem, Point position, <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a> size, double personSize)</td></tr>
<tr class="memdesc:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Basic constructor, assigns visualization methods to dictionaries for event and activity types <a href="#a897a51338edd7243dcf4dfda927be6b6">More...</a><br /></td></tr>
<tr class="separator:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a3571407fd3c83321bab8ccdae3baac0e">CreatePatient</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a patient drawing object <a href="#a3571407fd3c83321bab8ccdae3baac0e">More...</a><br /></td></tr>
<tr class="separator:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ab39da1d23eebe1d8fe34c03b137e877f">CreateDoctor</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a doctor drawing object <a href="#ab39da1d23eebe1d8fe34c03b137e877f">More...</a><br /></td></tr>
<tr class="separator:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a650fbd7d7bb218e7e719a4dcac3d4a3f">CreateNurse</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a nurse drawing object <a href="#a650fbd7d7bb218e7e719a4dcac3d4a3f">More...</a><br /></td></tr>
<tr class="separator:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#aa97bfcd681045655d1d5e43d77a1722a">CreateTreatmentFacility</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a treatment facility drawing object, different objects for different skill types of treatment facilities are generated, e.g. CT or MRI <a href="#aa97bfcd681045655d1d5e43d77a1722a">More...</a><br /></td></tr>
<tr class="separator:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a88c622beb3aaa3efa3e10e9cf9a3ce24">CreateMultiplePatientTreatmentFacility</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a multiple patient treatment facility drawing object <a href="#a88c622beb3aaa3efa3e10e9cf9a3ce24">More...</a><br /></td></tr>
<tr class="separator:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae89366f9a28ea6a3ac75891fca0f50a9"></a>
<a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ae89366f9a28ea6a3ac75891fca0f50a9">CreateWaitingRoom</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr>
<tr class="memdesc:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates a waiting room drawing object </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">entity</td><td>Treatment facility entity</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>A drawing object visualizing a waiting room</dd></dl>
<br /></td></tr>
<tr class="separator:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a0d4ef8176bd2251ff53971e7ddfad3f3">DrawHoldingEntity</a> (<a class="el" href="interface_simulation_core_1_1_h_c_c_m_elements_1_1_i_dynamic_holding_entity.html">IDynamicHoldingEntity</a> holdingEntity)</td></tr>
<tr class="memdesc:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Draws a holding entity, if size is sufficient for all entities holded, they are visualized in a grid form, if they do not fit they are all visualized in the middle and a string representing the count of holded entities is visualized <a href="#a0d4ef8176bd2251ff53971e7ddfad3f3">More...</a><br /></td></tr>
<tr class="separator:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">override void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#aa57efb82b63494b349a5977073019c43">AdditionalStaticVisualization</a> (DateTime initializationTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit)</td></tr>
<tr class="memdesc:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Creates the static visualization, draws all treatment facilities, waiting rooms and multiple patient treatment facilities for each structural area <a href="#aa57efb82b63494b349a5977073019c43">More...</a><br /></td></tr>
<tr class="separator:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a780a15d08281938df5c17a0b24584d2d">HealthCareActionEnd</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr>
<tr class="memdesc:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Method that visualized the end of a health care action, patient is removed from the drawing system <a href="#a780a15d08281938df5c17a0b24584d2d">More...</a><br /></td></tr>
<tr class="separator:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a3394a6e0359fa0246fff89c9313965d4">HealthCareActionStart</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr>
<tr class="memdesc:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Method that visualized the start of a health care action, patient is added to the drawing system and all entities (staff and patient) are set to the corresponding positions in the treatment facility (if it is not a multiple patient treatment facility). <a href="#a3394a6e0359fa0246fff89c9313965d4">More...</a><br /></td></tr>
<tr class="separator:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#adfff669d5726f33626b88c1a72b8ab96">WaitInFacilityEnd</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr>
<tr class="memdesc:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Method that visualized the end of a wait in facility activity, patient is removed from the drawing system <a href="#adfff669d5726f33626b88c1a72b8ab96">More...</a><br /></td></tr>
<tr class="separator:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ad09159950ba3f4c77bda340214bcce44">WaitInFacilityStart</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr>
<tr class="memdesc:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Method that visualized the start of a wait in facility action, patient is added to the drawing system and set to the corresponding positions in the treatment facility (if it is not a multiple patient treatment facility). <a href="#ad09159950ba3f4c77bda340214bcce44">More...</a><br /></td></tr>
<tr class="separator:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ae7b7553c4abb3871ccadbd93a336cf69">EventPatientLeave</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> ev)</td></tr>
<tr class="memdesc:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Upon patient leave events the drawing object is removed from the system <a href="#ae7b7553c4abb3871ccadbd93a336cf69">More...</a><br /></td></tr>
<tr class="separator:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a64759dc8379a68dd03c80d7fde9b2b71">EventLeavingStaff</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> ev)</td></tr>
<tr class="memdesc:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Upon staff leave events the drawing object is removed from the system <a href="#a64759dc8379a68dd03c80d7fde9b2b71">More...</a><br /></td></tr>
<tr class="separator:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a>
Properties</h2></td></tr>
<tr class="memitem:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#a992d490ed94e38c9a9cf1b1f2ddff207">NumberSlotWaitString</a><code> [get]</code></td></tr>
<tr class="memdesc:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="mdescLeft"> </td><td class="mdescRight">Drawing object for the string representing the number of patients waiting for a slot <a href="#a992d490ed94e38c9a9cf1b1f2ddff207">More...</a><br /></td></tr>
<tr class="separator:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af57ab2efb02c541b204a377740f69906"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#af57ab2efb02c541b204a377740f69906">NumberSlotAssignString</a><code> [get]</code></td></tr>
<tr class="memdesc:af57ab2efb02c541b204a377740f69906"><td class="mdescLeft"> </td><td class="mdescRight">Drawing object for the string representing the number of patients waiting for a slot to be assigned <a href="#af57ab2efb02c541b204a377740f69906">More...</a><br /></td></tr>
<tr class="separator:af57ab2efb02c541b204a377740f69906"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="inherit_header properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td colspan="2" onclick="javascript:toggleInherit('properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit')"><img src="closed.png" alt="-"/> Properties inherited from <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html">SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit< OutpatientActionTypeClass ></a></td></tr>
<tr class="memitem:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">Point </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a7af7fadd903ca4aa578ceb80cf4747dd">Position</a><code> [get]</code></td></tr>
<tr class="memdesc:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Position of control unit visualization on drawing system <a href="#a7af7fadd903ca4aa578ceb80cf4747dd">More...</a><br /></td></tr>
<tr class="separator:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">Size </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a><code> [get]</code></td></tr>
<tr class="memdesc:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Size of control unit visualization on drawing system <a href="#abe4ba0d78d527ff6c4cdde7dd27943fc">More...</a><br /></td></tr>
<tr class="separator:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">double </td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a53651357a0075b021a5ebad63112fc1a">PersonSize</a><code> [get]</code></td></tr>
<tr class="memdesc:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft"> </td><td class="mdescRight">Size in which persons are visualized <a href="#a53651357a0075b021a5ebad63112fc1a">More...</a><br /></td></tr>
<tr class="separator:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Additional visualization for outpatient control units, with extra visualization of waiting list numbers: Number of patients waiting for a slot to be assigned Number of patients waiting for slots </p>
</div><h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a class="anchor" id="a50cbb97ee541ebb20c7ce54fb48960ed"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.WPFVisualizationEngineOutpatientDepartment </td>
<td>(</td>
<td class="paramtype"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a> </td>
<td class="paramname"><em>drawingSystem</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">Point </td>
<td class="paramname"><em>position</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a> </td>
<td class="paramname"><em>size</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double </td>
<td class="paramname"><em>personSize</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Basic constructor, just calls base constructor </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">drawingSystem</td><td>Drawing system used for visualization</td></tr>
<tr><td class="paramname">position</td><td>Position of control unit visualization on drawing system</td></tr>
<tr><td class="paramname">size</td><td>Size of control unit visualization on drawing system</td></tr>
<tr><td class="paramname">personSize</td><td>Size in which persons are visualized</td></tr>
</table>
</dd>
</dl>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="ab14586d925c0fcb7c6d77394fe4c8d65"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">override void SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.AdditionalDynamicVisualization </td>
<td>(</td>
<td class="paramtype">DateTime </td>
<td class="paramname"><em>currentTime</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> </td>
<td class="paramname"><em>simModel</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> </td>
<td class="paramname"><em>parentControlUnit</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">IEnumerable< <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> > </td>
<td class="paramname"><em>currentEvents</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Additionally to event handling methods for visualization, the number of patients waiting for a slot to be assigned or waiting for a slot are showed. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">currentTime</td><td>Time for additional dynamic visualization</td></tr>
<tr><td class="paramname">simModel</td><td>Simulation model to be visualized</td></tr>
<tr><td class="paramname">parentControlUnit</td><td>Control to be visualized</td></tr>
<tr><td class="paramname">currentEvents</td><td>Events that have been triggered at current time</td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a class="anchor" id="af8be5c28237bb4fc3261b13bcdb5aa45"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">override void SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.AdditionalStaticVisualization </td>
<td>(</td>
<td class="paramtype">DateTime </td>
<td class="paramname"><em>initializationTime</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> </td>
<td class="paramname"><em>simModel</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> </td>
<td class="paramname"><em>parentControlUnit</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Calls base class method and additiona visualization for string captions </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">initializationTime</td><td>Time at which static visualization is generated</td></tr>
<tr><td class="paramname">simModel</td><td>Simulation model for which the visuslization is generated</td></tr>
<tr><td class="paramname">parentControlUnit</td><td>Control unit that is visualized</td></tr>
</table>
</dd>
</dl>
</div>
</div>
<h2 class="groupheader">Property Documentation</h2>
<a class="anchor" id="af57ab2efb02c541b204a377740f69906"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.NumberSlotAssignString</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">get</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Drawing object for the string representing the number of patients waiting for a slot to be assigned </p>
</div>
</div>
<a class="anchor" id="a992d490ed94e38c9a9cf1b1f2ddff207"></a>
<div class="memitem">
<div class="memproto">
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.NumberSlotWaitString</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">get</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Drawing object for the string representing the number of patients waiting for a slot </p>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| Java |
<?PHP
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
if($fgmembersite->RegisterUser())
{
require_once("config.php");
mkdir($dataDir);
mkdir($dataDir."CLASSTéléversés");
$fgmembersite->RedirectToURL("thank-you.html");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Register</title>
<link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" />
<script type='text/javascript' src='scripts/gen_validatorv31.js'></script>
<link rel="STYLESHEET" type="text/css" href="style/pwdwidget.css" />
<script src="scripts/pwdwidget.js" type="text/javascript"></script>
</head>
<body>
<!-- Form Code Start -->
<div id='fg_membersite'>
<form id='register' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Register</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class='short_explanation'>* required fields</div>
<input type='text' class='spmhidip' name='<?php echo $fgmembersite->GetSpamTrapInputName(); ?>' />
<div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='name' >Your Full Name*: </label><br/>
<input type='text' name='name' id='name' value='<?php echo $fgmembersite->SafeDisplay('name') ?>' maxlength="50" /><br/>
<span id='register_name_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='email' >Email Address*:</label><br/>
<input type='text' name='email' id='email' value='<?php echo $fgmembersite->SafeDisplay('email') ?>' maxlength="50" /><br/>
<span id='register_email_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='username' >UserName*:</label><br/>
<input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
<div class='container' style='height:80px;'>
<label for='password' >Password*:</label><br/>
<div class='pwdwidgetdiv' id='thepwddiv' ></div>
<noscript>
<input type='password' name='password' id='password' maxlength="50" />
</noscript>
<div id='register_password_errorloc' class='error' style='clear:both'></div>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Submit' />
</div>
</fieldset>
</form>
<!-- client-side Form Validations:
Uses the excellent form validation script from JavaScript-coder.com-->
<script type='text/javascript'>
// <![CDATA[
var pwdwidget = new PasswordWidget('thepwddiv','password');
pwdwidget.MakePWDWidget();
var frmvalidator = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("username","req","Please provide a username");
frmvalidator.addValidation("password","req","Please provide a password");
// ]]>
</script>
<!--
Form Code End (see html-form-guide.com for more info.)
-->
</body>
</html> | Java |
/*
* Copyright (C) 2006-2008 Alfresco Software Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 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.
* As a special exception to the terms and conditions of version 2.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* and Open Source Software ("FLOSS") applications as described in Alfresco's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* http://www.alfresco.com/legal/licensing"
*/
package org.alfresco.jlan.server.filesys;
import org.alfresco.jlan.server.SrvSession;
/**
* Transactional Filesystem Interface
*
* <p>Optional interface that a filesystem driver can implement to add support for transactions around filesystem calls.
*
* @author gkspencer
*/
public interface TransactionalFilesystemInterface {
/**
* Begin a read-only transaction
*
* @param sess SrvSession
*/
public void beginReadTransaction(SrvSession sess);
/**
* Begin a writeable transaction
*
* @param sess SrvSession
*/
public void beginWriteTransaction(SrvSession sess);
/**
* End an active transaction
*
* @param sess SrvSession
* @param tx Object
*/
public void endTransaction(SrvSession sess, Object tx);
}
| Java |
//
// ECCardView.h
// Beacon
//
// Created by 段昊宇 on 2017/5/29.
// Copyright © 2017年 Echo. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CCDraggableCardView.h"
#import "ECReturningVideo.h"
@interface ECCardView : CCDraggableCardView
- (void)initialData:(ECReturningVideo *)video;
- (void)addLiked;
- (void)delLiked;
@end
| Java |
-- >> INVENTORY <<
DROP TABLE Items CASCADE;
DROP TABLE contient;
DROP TRIGGER IF EXISTS delcharacter ON Characterr;
CREATE TABLE public.Items(
id_inventory INT,
item_name VARCHAR(100),
qte INT CONSTRAINT item_qte_null NOT NULL CONSTRAINT item_qte_check CHECK (qte > 0) ,
weight FLOAT CONSTRAINT item_weight_null NOT NULL CONSTRAINT item_weight_check CHECK (weight > 0),
CONSTRAINT prk_constraint_item PRIMARY KEY (id_inventory,item_name)
)WITHOUT OIDS;
ALTER TABLE public.Items ADD CONSTRAINT FK_items_inventory FOREIGN KEY (id_inventory) REFERENCES public.Inventaire(id_inventory);
-- Reimplementation of broken features
CREATE OR REPLACE FUNCTION delCharacter () RETURNS TRIGGER AS $delCharacter$
BEGIN
DELETE FROM items
WHERE id_inventory = old.id_inventory;
DELETE FROM inventaire
WHERE id_inventory = old.id_inventory;
RETURN old;
END;
$delCharacter$ LANGUAGE plpgsql;
CREATE TRIGGER delCharacter
AFTER DELETE ON Characterr
FOR EACH ROW
EXECUTE PROCEDURE delCharacter();
CREATE OR REPLACE FUNCTION inventory_Manager () RETURNS TRIGGER AS $inventory_Manager$
DECLARE
poids ITEMS.WEIGHT%TYPE;
poids_max ITEMS.WEIGHT%TYPE;
BEGIN
IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN
SELECT size_ INTO poids FROM inventaire
WHERE id_inventory = old.id_inventory;
poids := poids - (old.qte * old.weight);
UPDATE inventaire
SET size_ = poids
WHERE id_inventory = old.id_inventory;
END IF;
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
SELECT size_ INTO poids FROM inventaire
WHERE id_inventory = new.id_inventory;
poids := poids + (new.qte * new.weight);
SELECT size_max INTO poids_max FROM inventaire
WHERE id_inventory = new.id_inventory;
--IF poids > poids_max THEN
--RAISE EXCEPTION 'Inventory size exceeded';
--ELSE
UPDATE inventaire
SET size_ = poids
WHERE id_inventory = new.id_inventory;
--END IF;
END IF;
IF TG_OP = 'DELETE' THEN
RETURN old;
ELSE
RETURN new;
END IF;
END;
$inventory_Manager$ LANGUAGE plpgsql;
CREATE TRIGGER inventory_Manager
BEFORE INSERT OR UPDATE OR DELETE ON Items
FOR EACH ROW
EXECUTE PROCEDURE inventory_Manager();
CREATE OR REPLACE FUNCTION additem
(
dbkey Characterr.charkey%TYPE,
idserv JDR.id_server%TYPE,
idchan JDR.id_channel%TYPE,
itname Items.item_name%TYPE,
quantite INT,
poids Items.weight%TYPE
) RETURNS void AS $$
DECLARE
inv Inventaire.id_inventory%TYPE;
nbr INT;
BEGIN
SELECT id_inventory INTO inv FROM Characterr
WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan);
SELECT COUNT(*) INTO nbr FROM Items
WHERE (item_name LIKE LOWER(itname) AND id_inventory = inv);
IF nbr = 0 THEN
INSERT INTO Items
VALUES (inv,itname,quantite,poids);
ELSE
UPDATE Items
SET qte = qte + quantite
WHERE (item_name = itname AND id_inventory = inv);
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION removeitem
(
dbkey Characterr.charkey%TYPE,
idserv JDR.id_server%TYPE,
idchan JDR.id_channel%TYPE,
itname Items.item_name%TYPE,
quantite INT
) RETURNS void AS $$
DECLARE
inv Inventaire.id_inventory%TYPE;
nbr INT;
BEGIN
SELECT id_inventory INTO inv FROM Characterr
WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan);
SELECT qte INTO nbr FROM Items
WHERE (id_inventory = inv AND item_name = itname);
nbr := nbr - quantite;
IF nbr <= 0 THEN
DELETE FROM Items
WHERE (item_name = itname AND id_inventory = inv);
ELSE
UPDATE Items
SET qte = nbr
WHERE (item_name = itname AND id_inventory = inv);
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION forceinvcalc () RETURNS void AS $$
DECLARE
poids INVENTAIRE.SIZE_%TYPE;
inv RECORD;
item RECORD;
po Characterr.argent%TYPE;
BEGIN
FOR inv IN (SELECT id_inventory FROM inventaire) LOOP
SELECT argent INTO po FROM characterr WHERE id_inventory = inv.id_inventory;
poids := CEIL(po/5000);
FOR item IN (SELECT item_name,qte,weight FROM Items WHERE id_inventory = inv.id_inventory) LOOP
poids := poids + (item.qte * item.weight);
END LOOP;
UPDATE inventaire
SET size_ = poids
WHERE id_inventory = inv.id_inventory;
END LOOP;
END;
$$ LANGUAGE plpgsql;
-- >> XP <<
ALTER TABLE public.Characterr ADD COLUMN xp INT;
-- Perform update of characterr
DO $$
<<xpupdate>>
BEGIN
UPDATE Characterr
SET xp = 0;
END xpupdate $$;
-- Update old fonctions
CREATE OR REPLACE FUNCTION charcreate
(
dbkey Characterr.charkey%TYPE,
idserv JDR.id_server%TYPE,
idchan JDR.id_channel%TYPE,
cl Classe.id_classe%TYPE
) RETURNS void AS $$
DECLARE
inv inventaire.id_inventory%TYPE;
BEGIN
INSERT INTO inventaire (charkey)
VALUES (dbkey);
SELECT MAX(id_inventory) INTO inv FROM inventaire
WHERE charkey = dbkey;
--update here
INSERT INTO Characterr
VALUES (dbkey, dbkey, '', 1, 1, 1, 1, 1, 50, 50, 50, 50, 0, 0, 0, 1, 1, 3, 100, 0, 0, 0, 0, 0, 0, 0, idserv, idchan, 'O', 'O', inv, 'NULL',false,cl,false,0);
--end of update
END;
$$ LANGUAGE plpgsql;
-- new fonctions
CREATE OR REPLACE FUNCTION charxp
(
dbkey Characterr.charkey%TYPE,
idserv JDR.id_server%TYPE,
idchan JDR.id_channel%TYPE,
amount Characterr.xp%TYPE,
allowlevelup BOOL
) RETURNS INT AS $$
DECLARE
earnedlvl INT;
curxp Characterr.xp%TYPE;
BEGIN
earnedlvl := 0;
IF allowlevelup THEN
SELECT xp INTO curxp FROM Characterr
WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan);
earnedlvl := FLOOR((curxp + amount) / 100);
amount := curxp + amount - (earnedlvl * 100);
UPDATE Characterr
SET xp = amount
WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan);
ELSE
UPDATE Characterr
SET xp = xp + amount
WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan);
END IF;
RETURN earnedlvl;
END;
$$ LANGUAGE plpgsql;
| Java |
#PASTOR: Code generated by XML::Pastor/1.0.4 at 'Sun Jun 28 20:44:47 2015'
use utf8;
use strict;
use warnings;
no warnings qw(uninitialized);
use XML::Pastor;
#================================================================
package SAN::Cat::Type::catRecord;
use SAN::Cat::Type::catRecordBody;
use SAN::Cat::Type::catRecordHeader;
our @ISA=qw(XML::Pastor::ComplexType);
SAN::Cat::Type::catRecord->mk_accessors( qw(catRecordHeader catRecordBody));
SAN::Cat::Type::catRecord->XmlSchemaType( bless( {
'attributeInfo' => {},
'attributePrefix' => '_',
'attributes' => [],
'baseClasses' => [
'XML::Pastor::ComplexType'
],
'class' => 'SAN::Cat::Type::catRecord',
'contentType' => 'complex',
'elementInfo' => {
'catRecordBody' => bless( {
'class' => 'SAN::Cat::Type::catRecordBody',
'metaClass' => 'SAN::Cat::Pastor::Meta',
'minOccurs' => '0',
'name' => 'catRecordBody',
'scope' => 'local',
'targetNamespace' => 'http://san.mibac.it/cat-import',
'type' => 'catRecordBody|http://san.mibac.it/cat-import'
}, 'XML::Pastor::Schema::Element' ),
'catRecordHeader' => bless( {
'class' => 'SAN::Cat::Type::catRecordHeader',
'maxOccurs' => '1',
'metaClass' => 'SAN::Cat::Pastor::Meta',
'minOccurs' => '1',
'name' => 'catRecordHeader',
'scope' => 'local',
'targetNamespace' => 'http://san.mibac.it/cat-import',
'type' => 'catRecordHeader|http://san.mibac.it/cat-import'
}, 'XML::Pastor::Schema::Element' )
},
'elements' => [
'catRecordHeader',
'catRecordBody'
],
'isRedefinable' => 1,
'metaClass' => 'SAN::Cat::Pastor::Meta',
'name' => 'catRecord',
'scope' => 'global',
'targetNamespace' => 'http://san.mibac.it/cat-import'
}, 'XML::Pastor::Schema::ComplexType' ) );
1;
__END__
=head1 NAME
B<SAN::Cat::Type::catRecord> - A class generated by L<XML::Pastor> .
=head1 ISA
This class descends from L<XML::Pastor::ComplexType>.
=head1 CODE GENERATION
This module was automatically generated by L<XML::Pastor> version 1.0.4 at 'Sun Jun 28 20:44:47 2015'
=head1 CHILD ELEMENT ACCESSORS
=over
=item B<catRecordBody>() - See L<SAN::Cat::Type::catRecordBody>.
=item B<catRecordHeader>() - See L<SAN::Cat::Type::catRecordHeader>.
=back
=head1 SEE ALSO
L<XML::Pastor::ComplexType>, L<XML::Pastor>, L<XML::Pastor::Type>, L<XML::Pastor::ComplexType>, L<XML::Pastor::SimpleType>
=cut
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.