answer
stringlengths 15
1.25M
|
|---|
// .NAME <API key>
// .SECTION Description
// <API key> is a specialization of vtkPVAnimationCue that uses
// the <API key> as the manipulator.
#ifndef <API key>
#define <API key>
#include "vtkPVAnimationCue.h"
class vtkPVKeyFrame;
class <API key>;
class <API key> <API key> : public vtkPVAnimationCue
{
public:
vtkTypeMacro(<API key>, vtkPVAnimationCue);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Forwarded to the internal <API key>.
int AddKeyFrame (vtkPVKeyFrame* keyframe);
int <API key>();
void RemoveKeyFrame(vtkPVKeyFrame*);
void RemoveAllKeyFrames();
//BTX
protected:
<API key>();
~<API key>();
<API key>* <API key>();
private:
<API key>(const <API key>&); // Not implemented
void operator=(const <API key>&); // Not implemented
//ETX
};
#endif
|
// Decompiled with JetBrains decompiler
// Type: System.Web.UI.WebControls.WebParts.<API key>
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKey<API key>
// MVID: <API key>
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing.Design;
using System.Runtime;
namespace System.Web.UI.WebControls.WebParts
{
<summary>
Contains a collection of static <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects, which is used when the connections are declared in content pages and the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartManager"/> control is declared in a master page. This class cannot be inherited.
</summary>
[Editor("System.ComponentModel.Design.CollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKey<API key>, typeof (UITypeEditor))]
public sealed class <API key> : CollectionBase
{
private WebPartManager _webPartManager;
<summary>
Gets a value indicating whether <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects can be added to the collection.
</summary>
<returns>
true if connection objects cannot be added to the collection; otherwise, false.
</returns>
public bool IsReadOnly
{
get
{
if (this._webPartManager != null)
return this._webPartManager.StaticConnections.IsReadOnly;
return false;
}
}
<summary>
Gets or sets a connection item within the collection, based on an index number indicating the item's location in the collection.
</summary>
<returns>
A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> at the specified index in the collection.
</returns>
<param name="index">An integer that indicates the index of a member of the collection. </param>
public WebPartConnection this[int index]
{
get
{
return (WebPartConnection) this.List[index];
}
set
{
this.List[index] = (object) value;
}
}
<summary>
Returns a specific member of the collection according to a unique identifier.
</summary>
<returns>
The first <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> whose ID matches the value of the <paramref name="id"/> parameter. Returns null if no match is found.
</returns>
<param name="id">A string that contains the ID of a particular connection in the collection. </param>
public WebPartConnection this[string id]
{
get
{
foreach (WebPartConnection webPartConnection in (IEnumerable) this.List)
{
if (webPartConnection != null && string.Equals(webPartConnection.ID, id, StringComparison.OrdinalIgnoreCase))
return webPartConnection;
}
return (WebPartConnection) null;
}
}
<summary>
Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.WebParts.<API key>"/> class.
</summary>
[<API key>("Performance critical to inline this type of method across NGen image boundaries")]
public <API key>()
{
}
<summary>
Adds a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object to the collection.
</summary>
<returns>
An integer value that indicates where the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> was inserted into the collection.
</returns>
<param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to add to the collection. </param>
public int Add(WebPartConnection value)
{
return this.List.Add((object) value);
}
<summary>
Returns a value indicating whether a particular <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object exists in the collection.
</summary>
<returns>
true if <paramref name="value"/> exists in the collection; otherwise, false.
</returns>
<param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> being checked for its existence in a collection. </param>
public bool Contains(WebPartConnection value)
{
return this.List.Contains((object) value);
}
<summary>
Copies the collection to an array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects.
</summary>
<param name="array">An array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects to contain the copied collection. </param><param name="index">An integer that indicates the starting point in the array at which to place the collection contents. </param>
public void CopyTo(WebPartConnection[] array, int index)
{
this.List.CopyTo((Array) array, index);
}
<summary>
Returns the position of a particular member of the collection.
</summary>
<returns>
An integer that indicates the position of a particular object in the collection.
</returns>
<param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> that is a member of the collection. </param>
public int IndexOf(WebPartConnection value)
{
return this.List.IndexOf((object) value);
}
<summary>
Inserts a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object into the collection at the specified index.
</summary>
<param name="index">An integer indicating the ordinal position in the collection at which a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> should be inserted. </param><param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to insert into the collection. </param>
public void Insert(int index, WebPartConnection value)
{
this.List.Insert(index, (object) value);
}
protected override void OnClear()
{
this.CheckReadOnly();
if (this._webPartManager != null)
{
foreach (WebPartConnection webPartConnection in (CollectionBase) this)
this._webPartManager.StaticConnections.Remove(webPartConnection);
}
base.OnClear();
}
protected override void OnInsert(int index, object value)
{
this.CheckReadOnly();
if (this._webPartManager != null)
this._webPartManager.StaticConnections.Insert(index, (WebPartConnection) value);
base.OnInsert(index, value);
}
protected override void OnRemove(int index, object value)
{
this.CheckReadOnly();
if (this._webPartManager != null)
this._webPartManager.StaticConnections.Remove((WebPartConnection) value);
base.OnRemove(index, value);
}
protected override void OnSet(int index, object oldValue, object newValue)
{
this.CheckReadOnly();
if (this._webPartManager != null)
this._webPartManager.StaticConnections[this._webPartManager.StaticConnections.IndexOf((WebPartConnection) oldValue)] = (WebPartConnection) newValue;
base.OnSet(index, oldValue, newValue);
}
protected override void OnValidate(object value)
{
base.OnValidate(value);
if (value == null)
throw new <API key>("value", System.Web.SR.GetString("<API key>"));
if (!(value is WebPartConnection))
throw new ArgumentException(System.Web.SR.GetString("<API key>", new object[1]
{
(object) "WebPartConnection"
}));
}
<summary>
Removes the specified <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object from the collection.
</summary>
<param name="value">The <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to be removed. </param>
public void Remove(WebPartConnection value)
{
this.List.Remove((object) value);
}
internal void SetWebPartManager(WebPartManager webPartManager)
{
this._webPartManager = webPartManager;
foreach (WebPartConnection webPartConnection in (CollectionBase) this)
this._webPartManager.StaticConnections.Add(webPartConnection);
}
private void CheckReadOnly()
{
if (this.IsReadOnly)
throw new <API key>(System.Web.SR.GetString("<API key>"));
}
}
}
|
<!DOCTYPE html PUBLIC "-
<html>
<!-- This file redirects to the location of a node or anchor -->
<head>
<title>GNU Octave: XREFbicgstab</title>
<meta name="description" content="GNU Octave: XREFbicgstab">
<meta name="keywords" content="GNU Octave: XREFbicgstab">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
</style>
<meta http-equiv="Refresh" content="0; url=Specialized-Solvers.html#XREFbicgstab">
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<p>The node you are looking for is at <a href="Specialized-Solvers.html#XREFbicgstab">XREFbicgstab</a>.</p>
</body>
|
// This file is part of the Research Data Management Platform (RDMP).
using System.Windows.Forms;
using <API key>;
namespace Rdmp.UI.Refreshing
{
<summary>
<see cref="<API key>"/> for <see cref="Control"/> classes which want their lifetime to be linked to a single
<see cref="<API key>"/> object. This grants notifications of publish events about the object and ensures
your <see cref="Control"/> is closed when/if the object is deleted.
<para>See <see cref="RefreshBus.<API key>"/></para>
</summary>
public interface ILifetimeSubscriber:IContainerControl,<API key>
{
}
}
|
import sys, os, urllib, time, socket, mt, ssl
from dlmanager.NZB import NZBParser
from dlmanager.NZB.nntplib2 import NNTP_SSL,NNTPError,NNTP, NNTPReplyError
from dlmanager.NZB.Decoder import ArticleDecoder
class StatusReport(object):
def __init__(self):
self.message = "Downloading.."
self.total_bytes = 0
self.current_bytes = 0
self.completed = False
self.error_occured = False
self.start_time = 0
self.file_name = ""
self.kbps = 0
self.assembly = False
self.assembly_percent = 0
class NZBClient():
def __init__(self, nzbFile, save_to, nntpServer, nntpPort, nntpUser=None, nntpPassword=None, nntpSSL=False, nntpConnections=5, cache_path=""):
# Settings
self.save_to = save_to
self.nntpServer = nntpServer
self.nntpUser = nntpUser
self.nntpPort = nntpPort
self.nntpPassword = nntpPassword
self.nntpSSL = nntpSSL
self.nntpConnections = nntpConnections
self.threads = []
self.running = False
# setup our cache folder.
self.cache_path = cache_path
if ( self.cache_path == "" ): self.cache_path = "packages/dlmanager/cache/"
self.clearCache()
# ensure both directorys exist
mt.utils.mkdir(self.save_to)
mt.utils.mkdir(self.cache_path)
# Open the NZB, get this show started.
realFile = urllib.urlopen(nzbFile)
self.nzb = NZBParser.parse(realFile)
self.all_decoded = False
self.connection_count = 0
# used to track status.
self.status = StatusReport()
self.status.file_name = nzbFile
self.status.total_bytes = self.nzb.size
# Segment tracking.
self.cache = []
self.segment_list = []
self.segments_finished = []
self.segments_aborted = []
# Queues.
self.segment_queue = []
self.failed_queue = []
# Used to track the speed.
self.speedTime = 0
self.speedCounter = 0
def start(self):
# keep track of running time.
self.status.start_time = time.time()
self.running = True
# Generate a list of segments and build our queue.
for file in self.nzb.files:
for seg in file.segments:
self.segment_list.append(seg.msgid)
self.segment_queue.append(seg)
# start the connections.
for a in range(0, self.nntpConnections):
thread = NNTPConnection(a,
self.nntpServer,
self.nntpPort,
self.nntpUser,
self.nntpPassword,
self.nntpSSL,
self.nextSeg,
self.segComplete,
self.segFailed,
self.threadStopped)
self.threads.append(thread)
self.connection_count += 1
thread.start()
# start the article decoder.
self.articleDecoder = ArticleDecoder(self.decodeNextSeg,
self.save_to,
self.cache_path,
self.decodeFinished,
self.decodeSuccess,
self.decodeFailed,
self.assemblyStatus)
self.articleDecoder.start()
def getStatus(self):
return self.status
# Article Decoder - Next segment.
def decodeNextSeg(self):
# if we're not running send an instant kill switch.
if ( not self.running ): return -1
# try to grab a segment from the cache to decode.
seg = None
try:
seg = self.cache.pop()
except:
pass
if ( seg == None ) and ( self.all_decoded ):
return -1
return seg
# Article Decoder - Decoded all segments.
def decodeFinished(self):
self.status.completed = True
# Article Decoder - Decode success.
def decodeSuccess(self, seg):
self.status.current_bytes += seg.size
self.segments_finished.append(seg.msgid)
if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ):
self.all_decoded = True
# Article Decoder - Decode failed.
def decodeFailed(self, seg):
if ( seg == None ): return
mt.log.debug("Segment failed to decode: " + seg.msgid)
self.segFailed(seg)
# Article Decoder - Assembly Status.
def assemblyStatus(self, percent):
self.status.assembly = True
self.status.assembly_percent = percent
# NNTP Connection - Thread stopped.
def threadStopped(self, thread_num):
self.connection_count -= 1
# NNTP Connection - Segment completed.
def segComplete(self, seg):
if ( seg == None ): return
if ( seg.data ):
data_size = len("".join(seg.data))
current_time = time.time()
if ( (current_time - self.speedTime) > 1 ):
self.status.kbps = self.speedCounter
self.speedCounter = 0
self.speedTime = current_time
else:
self.speedCounter += (data_size/1024)
self.cache.append(seg)
#mt.log.debug("Segment Complete: " + seg.msgid)
# NNTP Connection - Download of segment failed.
def segFailed(self, seg):
if ( seg == None ): return
if ( seg.aborted() ):
mt.log.error("Segment Aborted: " + seg.msgid + " after " + str(seg.retries) + " attempts.")
self.segments_aborted.append(seg.msgid)
seg.data = []
if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ):
self.all_decoded = True
return
seg.retries += 1
mt.log.error("Segment Failed: " + seg.msgid + " Attempt #" + str(seg.retries) + ".")
self.failed_queue.append(seg)
# NNTP Connection - Next Segment
def nextSeg(self):
# if we're not running send an instant kill switch.
if ( not self.running ): return -1
# try to get a segment from main queue or failed queue.
queue_empty = False
seg = None
try:
seg = self.segment_queue.pop()
except:
try:
seg = self.failed_queue.pop()
except:
queue_empty = True
pass
pass
# We're all outta segments, if they're done decoding, kill the threads.
if ( queue_empty ) and ( self.all_decoded ):
return -1
return seg
# empty the cache of any files.
def clearCache(self):
mt.utils.rmdir(self.cache_path)
def stop(self):
self.running = False
self.articleDecoder.stop()
for thread in self.threads:
thread.stop()
self.clearCache()
class NNTPConnection(mt.threads.Thread):
def __init__(self, connection_number, server, port, username, password, ssl, nextSegFunc, onSegComplete = None, onSegFailed = None, onThreadStop = None):
mt.threads.Thread.__init__(self)
# Settings
self.connection = None
self.connection_number = connection_number
self.server = server
self.port = port
self.username = username
self.password = password
self.ssl = ssl
# Events.
self.nextSegFunc = nextSegFunc
self.onSegComplete = onSegComplete
self.onSegFailed = onSegFailed
self.onThreadStop = onThreadStop
def connect(self):
# Open either an SSL or regular NNTP connection.
try:
if ( self.ssl ):
self.connection = NNTP_SSL(self.server, self.port, self.username, self.password, False, True, timeout=15)
else:
self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15)
except:
pass
if ( self.connection ): return True
return False
def disconnect(self):
if ( self.connection ):
try:
self.connection.quit()
except:
pass
self.connection = None
def run(self):
connection = None
seg = None
# Thread has started.
mt.log.debug("Thread " + str(self.connection_number) + " started.")
start_time = time.time()
while(self.running):
seg = None
connected = self.connect()
if ( connected ):
while(self.running):
seg = self.nextSegFunc()
# Out of segments, sleep for a bit and see if we get anymore.
if ( seg == None ):
self.sleep(0.1)
continue
# Download complete, bail.
if ( seg == -1 ):
self.running = False
seg = None
break
# Attempt to grab a segment.
try:
resp, nr, id, data = self.connection.body("<%s>" % seg.msgid)
if resp[0] == "2":
seg.data = data
if ( self.onSegComplete ): self.onSegComplete(seg)
seg = None
except ssl.SSLError:
break
except NNTPError as e:
mt.log.error("Error getting segment: " + e.response)
pass
except:
mt.log.error("Error getting segment.")
pass
if ( seg and self.onSegFailed ):
self.onSegFailed(seg)
seg = None
# Disconnect when we're finished.
if ( seg and self.onSegFailed ): self.onSegFailed(seg)
self.disconnect()
else:
mt.log.error("Connection error. Reconnecting in 3 seconds.")
self.sleep(3)
# Thread has ended.
self.disconnect() # just to be safe.
end_time = time.time()
mt.log.debug("Thread " + str(self.connection_number) + " stopped after " + str(end_time-start_time) + " seconds.")
if ( self.onThreadStop ): self.onThreadStop(self.connection_number)
|
"""Tests for `fix.with_fixture`."""
from __future__ import with_statement
import os
import shutil
import tempfile
from types import FunctionType
from fix import with_fixture
def test_exists():
"""`fix.with_fixture` function exists"""
assert isinstance(with_fixture, FunctionType)
def test_setup_only():
"""`setup_only` fixture works as expected"""
def setup_only(context):
"""A fixture with no `teardown()`."""
def setup():
"""Add something to the context."""
assert context == {}
context.squee = "kapow"
return setup
@with_fixture(setup_only)
def case(context):
"""Check that the context has been set up."""
assert context == {"squee": "kapow"}
case() # pylint: disable=E1120
def test_setup_teardown():
"""`setup_teardown` fixture works as expected"""
def setup_teardown(context):
"""A fixture with both `setup()` and `teardown()`."""
def setup():
"""Add something to the context."""
assert context == {}
context.squee = "kapow"
def teardown():
"""Check that `context.squee` has changed."""
assert context == {"squee": "boing"}
return setup, teardown
@with_fixture(setup_teardown)
def case(context):
"""Alter the context."""
assert context == {"squee": "kapow"}
context.squee = "boing"
case() # pylint: disable=E1120
def <API key>():
"""`multiple` fixture creates a fresh context each invocation"""
def multiple(context):
"""A fixture to be invoked multiple times."""
def setup():
"""Add something to the context."""
assert context == {}
context.squee = "kapow"
def teardown():
"""Check that `context.squee` has changed."""
assert context == {"squee": "kapow", "boing": "thunk"}
return setup, teardown
@with_fixture(multiple)
def case(context):
"""Add to the context."""
assert context == {"squee": "kapow"}
context.boing = "thunk"
for _ in range(3):
case() # pylint: disable=E1120
def test_external():
"""`external` fixture interacts as expected with the 'real world'."""
def external(context, files=3):
"""A fixture to manipulate temporary files and directories."""
def setup():
"""Create some temporary files."""
context.temp_dir = tempfile.mkdtemp()
context.filenames = ["file_%03d" % i for i in range(files)]
for filename in context.filenames:
with open(os.path.join(context.temp_dir, filename), "w") as f:
f.write("This is the file %r.\n" % filename)
def teardown():
"""Delete the temporary files created in `setup()`."""
shutil.rmtree(context.temp_dir)
return setup, teardown
@with_fixture(external, files=5)
def check_files(context):
"""Return the number of present and absent files."""
present = 0
absent = 0
for filename in context.filenames:
if os.path.exists(os.path.join(context.temp_dir, filename)):
present += 1
else:
absent += 1
return context.temp_dir, present, absent
temp_dir, present, absent = check_files() # pylint: disable=E1120
assert not os.path.exists(temp_dir)
assert present == 5
assert absent == 0
|
# @author Peter Kappelt
# @author Clemens Bergmann
# @version 1.16.dev-cf.9
package main;
use strict;
use warnings;
use Data::Dumper;
use JSON;
use TradfriUtils;
sub <API key>($) {
my ($hash) = @_;
$hash->{DefFn} = 'Tradfri_Define';
$hash->{UndefFn} = 'Tradfri_Undef';
$hash->{SetFn} = 'Tradfri_Set';
$hash->{GetFn} = 'Tradfri_Get';
$hash->{AttrFn} = 'Tradfri_Attr';
$hash->{ReadFn} = 'Tradfri_Read';
$hash->{ParseFn} = 'TradfriGroup_Parse';
$hash->{Match} = '(^<API key>::)|(^moodList::)';
$hash->{AttrList} =
"usePercentDimming:1,0 "
. $readingFnAttributes;
}
#messages look like this: (without newlines)
# <API key>::group-id::{
# "createdAt":1494088484,
# "mood":198884,
# "groupid":173540,
# "members":[
# "name":"Fenster Links",
# "deviceid":65537
# "deviceid":65536
# "name":"Fenster Rechts",
# "deviceid":65538
# "name":"Wohnzimmer",
# "dimvalue":200,
# "onoff":0
sub TradfriGroup_Parse($$){
my ($io_hash, $message) = @_;
my @parts = split('::', $message);
if(int(@parts) < 3){
#expecting at least three parts
return undef;
}
my $messageID = $parts[1];
#check if group with the id exists
if(my $hash = $modules{'TradfriGroup'}{defptr}{$messageID})
{
#parse the JSON data
my $jsonData = eval{ JSON->new->utf8->decode($parts[2]) };
if($@){
return undef; #the string was probably not valid JSON
}
if('<API key>' eq $parts[0]){
my $createdAt = FmtDateTimeRFC1123($jsonData->{'createdAt'} || '');
my $name = $jsonData->{'name'} || '';
my $members = JSON->new->pretty->encode($jsonData->{'members'});
#dimvalue is in range 0 - 254
my $dimvalue = $jsonData->{'dimvalue'} || '0';
#dimpercent is always in range 0 - 100
my $dimpercent = int($dimvalue / 2.54 + 0.5);
$dimpercent = 1 if($dimvalue == 1);
$dimvalue = $dimpercent if (AttrVal($hash->{name}, 'usePercentDimming', 0) == 1);
my $state = 'off';
if($jsonData->{'onoff'} eq '0'){
$dimpercent = 0;
}else{
$state = Tradfri_stateString($dimpercent);
}
my $onoff = ($jsonData->{'onoff'} || '0') ? 'on':'off';
readingsBeginUpdate($hash);
<API key>($hash, 'createdAt', $createdAt, 1);
<API key>($hash, 'name', $name, 1);
<API key>($hash, 'members', $members, 1);
<API key>($hash, 'dimvalue', $dimvalue, 1);
<API key>($hash, 'pct', $dimpercent, 1);
<API key>($hash, 'onoff', $onoff, 1) ;
<API key>($hash, 'state', $state, 1);
readingsEndUpdate($hash, 1);
}elsif('moodList' eq $parts[0]){
#update of mood list
<API key>($hash, 'moods', JSON->new->pretty->encode($jsonData), 1);
$hash->{helper}{moods} = undef;
foreach (@{$jsonData}){
$hash->{helper}{moods}->{$_->{name}} = $_;
}
}
#$attr{$hash->{NAME}}{webCmd} = 'pct:toggle:on:off';
#$attr{$hash->{NAME}}{devStateIcon} = '{(<API key>($name),"toggle")}' if( !defined( $attr{$hash->{name}}{devStateIcon} ) );
#return the appropriate group's name
return $hash->{NAME};
}
return undef;
}
1;
=pod
=item device
=item summary controls an IKEA Trådfri lighting group
=item summary_DE steuert eine IKEA Trådfri Beleuchtungsgruppe
=begin html
<a name="TradfriGroup"></a>
<h3>TradfriGroup</h3>
<ul>
<i>TradfriGroup</i> is a module for controlling an IKEA Trådfri lighting group. You currently need a gateway for the connection.
See TradfriGateway.
<br><br>
<a name="TradfriGroupdefine"></a>
<b>Define</b>
<ul>
<code>define <name> TradfriGroup <group-address></code>
<br><br>
Example: <code>define trGroupOne TradfriGroup 193768</code>
<br><br>
You can get the ID of the lighting groups by calling "get TradfriGW groupList" on the gateway device
</ul>
<br>
<a name="TradfriGroupset"></a>
<b>Set</b><br>
<ul>
<code>set <name> <option> [<value>]</code>
<br><br>
You can set the following options. See <a href="http://fhem.de/commandref.html#set">commandref#set</a>
for more info about the set command.
<br><br>
Options:
<ul>
<li><i>on</i><br>
Turns all devices in the group on.<br>The brightness is the one, before the devices were turned off</li>
<li><i>off</i><br>
Turn all devices in the group off.</li>
<li><i>dimvalue</i><br>
Set the brightness of all devices in the group.<br>
You need to specify the brightness value as an integer between 0 and 100/254.<br>
The largest value depends on the attribute "usePercentDimming".<br>
If this attribute is set, the largest value will be 100.<br>
By default, it isn't set, so the largest value is 254.<br>
A brightness value of 0 turns the devices off.<br>
If the devices are off, and you set a value greater than 0, they'll turn on.</li>
<li><i>mood</i><br>
Set the mood of the group.<br>
Moods are preconfigured color temperatures, brightnesses and states for each device of the group<br>
In order to set the mood, you need a mood ID or the mood's name.<br>
You can list the moods that are available for this group by running "get moods".<br>
Note, that the mood's name isn't necessarily the same that you've defined in the IKEA app.
This module is currently unable to handle whitespaces in mood names, so whitespaces get removed internally.
Check the reading "moods" after running "get moods" in order to get the names, that you may use with this module.<br>
Mood names are case-sensitive. Mood names, that are only made out of numbers are not supported.</li>
</ul>
</ul>
<br>
<a name="TradfriGroupget"></a>
<b>Get</b><br>
<ul>
<code>get <name> <option></code>
<br><br>
You can get the following information about the group. See
<a href="http://fhem.de/commandref.html#get">commandref#get</a> for more info about
the get command.
<br><br>
Options:
<ul>
<li><i>moods</i><br>
Get all moods (their name and their ID) that are configured for this group<br>
The JSON-formatted result is stored in the Reading "moods"</br>
Please note, that the mood IDs may differ between different groups (though they are the same moods) -> check them for each group</li>
</ul>
</ul>
<br>
<a name="<API key>"></a>
<b>Readings</b><br>
<ul>
The following readings are displayed for a group. Once there is a change and the connection to the gateway is made, they get updated automatically.
<br><br>
Readings:
<ul>
<li><i>createdAt</i><br>
A timestamp string, like "Sat, 15 Apr 2017 18:29:24 GMT", that indicates, when the group was created in the gateway.</li>
<li><i>dimvalue</i><br>
The brightness that is set for this group. It is a integer in the range of 0 to 100/ 254.<br>
The greatest dimvalue depends on the attribute "usePercentDimming", see below.</li>
<li><i>pct</i><br>
The brightness that is set for this device in percent.</li>
<li><i>members</i><br>
JSON-String that contains all member-IDs and their names.</li>
<li><i>moods</i><br>
JSON info of all moods and their names, e.g.:<br>
[ { "groupid" : 173540, "moodid" : 198884, "name" : "EVERYDAY" }, { "moodid" : 213983, "name" : "RELAX", "groupid" : 173540 }, { "groupid" : 173540, "name" : "FOCUS", "moodid" : 206399 } ]<br>
This reading isn't updated automatically, you've to call "get moods" in order to refresh them.</li>
<li><i>name</i><br>
The name of the group that you've set in the app.</li>
<li><i>onoff</i><br>
Indicates whether the device is on or off, can be the strings 'on' or 'off'</li>
<li><i>state</i><br>
Indicates, whether the group is on or off. Thus, the reading's value is either "on" or "off", too.</li>
</ul>
</ul>
<br>
<a name="TradfriGroupattr"></a>
<b>Attributes</b>
<ul>
<code>attr <name> <attribute> <value></code>
<br><br>
See <a href="http://fhem.de/commandref.html#attr">commandref#attr</a> for more info about
the attr command.
<br><br>
Attributes:
<ul>
<li><i>usePercentDimming</i> 0/1<br>
If this attribute is one, the largest value for "set dimvalue" will be 100.<br>
Otherwise, the largest value is 254.<br>
This attribute is useful, if you need to control the brightness in percent (0-100%)<br>
For backward compatibility, it is disabled by default, so the largest dimvalue is 254 by default.
</li>
</ul>
</ul>
</ul>
=end html
=cut
|
#include "demandmodel.h"
#include "Elements/junction.h"
#include <cmath>
#include <algorithm>
using namespace std;
// Parent constructor and destructor
DemandModel::DemandModel() : expon(0.0)
{}
DemandModel::DemandModel(double expon_) : expon(expon_)
{}
DemandModel::~DemandModel()
{}
// Demand model factory
DemandModel* DemandModel::factory(const string model, const double expon_)
{
if ( model == "FIXED" ) return new FixedDemandModel();
else if ( model == "CONSTRAINED" ) return new <API key>();
else if ( model == "POWER" ) return new PowerDemandModel(expon_);
else if ( model == "LOGISTIC" ) return new LogisticDemandModel(expon_);
else return nullptr;
}
// Default functions
double DemandModel::findDemand(Junction* junc, double p, double& dqdh)
{
dqdh = 0.0;
return junc->fullDemand;
}
Fixed Demand Model
FixedDemandModel::FixedDemandModel()
{}
Constrained Demand Model
<API key>::<API key>()
{}
bool <API key>::isPressureDeficient(Junction* junc)
{
//if ( junc->fixedGrade ||
// ... return false if normal full demand is non-positive
if (junc->fullDemand <= 0.0 ) return false;
double hMin = junc->elev + junc->pMin;
if ( junc->head < hMin )
{
junc->fixedGrade = true;
junc->head = hMin;
return true;
}
return false;
}
double <API key>::findDemand(Junction* junc, double p, double& dqdh)
{
dqdh = 0.0;
return junc->actualDemand;
}
Power Demand Model
PowerDemandModel::PowerDemandModel(double expon_) : DemandModel(expon_)
{}
double PowerDemandModel::findDemand(Junction* junc, double p, double& dqdh)
{
// ... initialize demand and demand derivative
double qFull = junc->fullDemand;
double q = qFull;
dqdh = 0.0;
// ... check for positive demand and pressure range
double pRange = junc->pFull - junc->pMin;
if ( qFull > 0.0 && pRange > 0.0)
{
// ... find fraction of full pressure met (f)
double factor = 0.0;
double f = (p - junc->pMin) / pRange;
// ... apply power function
if (f <= 0.0) factor = 0.0;
else if (f >= 1.0) factor = 1.0;
else
{
factor = pow(f, expon);
dqdh = expon / pRange * factor / f;
}
// ... update total demand and its derivative
q = qFull * factor;
dqdh = qFull * dqdh;
}
return q;
}
Logistic Demand Model
LogisticDemandModel::LogisticDemandModel(double expon_) :
DemandModel(expon_),
a(0.0),
b(0.0)
{}
double LogisticDemandModel::findDemand(Junction* junc, double p, double& dqdh)
{
double f = 1.0; // fraction of full demand
double q = junc->fullDemand; // demand flow (cfs)
double arg; // argument of exponential term
double dfdh; // gradient of f w.r.t. pressure head
// ... initialize derivative
dqdh = 0.0;
// ... check for positive demand and pressure range
if ( junc->fullDemand > 0.0 && junc->pFull > junc->pMin )
{
// ... find logistic function coeffs. a & b
setCoeffs(junc->pMin, junc->pFull);
// ... prevent against numerical over/underflow
arg = a + b*p;
if (arg < -100.) arg = -100.0;
else if (arg > 100.0) arg = 100.0;
// ... find fraction of full demand (f) and its derivative (dfdh)
f = exp(arg);
f = f / (1.0 + f);
f = max(0.0, min(1.0, f));
dfdh = b * f * (1.0 - f);
// ... evaluate demand and its derivative
q = junc->fullDemand * f;
dqdh = junc->fullDemand * dfdh;
}
return q;
}
void LogisticDemandModel::setCoeffs(double pMin, double pFull)
{
// ... computes logistic function coefficients
// assuming 99.9% of full demand at full pressure
// and 1% of full demand at minimum pressure.
double pRange = pFull - pMin;
a = (-4.595 * pFull - 6.907 * pMin) / pRange;
b = 11.502 / pRange;
}
|
// <<API key>>
// This file is part of Osiris Serverless Portal System.
// Osiris Serverless Portal System is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Osiris Serverless Portal System is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// </<API key>>
#ifndef <API key>
#define <API key>
#include "ideportalcontrol.h"
#include "idepickerselect.h"
#include "entitiesentities.h"
OS_NAMESPACE_BEGIN()
class <API key>;
class EngineExport IdePickerComponent : public IdePickerSelect
{
typedef IdePickerSelect ControlBase;
// Construction
public:
IdePickerComponent();
virtual ~IdePickerComponent();
// Attributes
public:
// Events
private:
// Operations
private:
void addComponent(shared_ptr<<API key>> component);
// IControl interface
public:
virtual void onLoad();
virtual void onPreRender();
protected:
};
OS_NAMESPACE_END()
#endif // <API key>
|
var <API key> =
[
[ "allowsContinuation", "d3/d89/<API key>.html#<API key>", null ],
[ "bestContinuations", "d3/d89/<API key>.html#<API key>", null ],
[ "bestLaneOffset", "d3/d89/<API key>.html#<API key>", null ],
[ "lane", "d3/d89/<API key>.html#<API key>", null ],
[ "length", "d3/d89/<API key>.html#<API key>", null ],
[ "nextOccupation", "d3/d89/<API key>.html#<API key>", null ],
[ "occupation", "d3/d89/<API key>.html#<API key>", null ]
];
|
# Build global options
# NOTE: Can be overridden externally.
# Compiler options here.
ifeq ($(USE_OPT),)
USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16
endif
# C specific options here (added to USE_OPT).
ifeq ($(USE_COPT),)
USE_COPT =
endif
# C++ specific options here (added to USE_OPT).
ifeq ($(USE_CPPOPT),)
USE_CPPOPT = -fno-rtti
endif
# Enable this if you want the linker to remove unused code and data
ifeq ($(USE_LINK_GC),)
USE_LINK_GC = yes
endif
# Linker extra options here.
ifeq ($(USE_LDOPT),)
USE_LDOPT =
endif
# Enable this if you want link time optimizations (LTO)
ifeq ($(USE_LTO),)
USE_LTO = yes
endif
# If enabled, this option allows to compile the application in THUMB mode.
ifeq ($(USE_THUMB),)
USE_THUMB = yes
endif
# Enable this if you want to see the full log while compiling.
ifeq ($(USE_VERBOSE_COMPILE),)
USE_VERBOSE_COMPILE = no
endif
# If enabled, this option makes the build process faster by not compiling
# modules not used in the current configuration.
ifeq ($(USE_SMART_BUILD),)
USE_SMART_BUILD = yes
endif
# Build global options
# Architecture or project specific options
# Stack size to be allocated to the Cortex-M process stack. This stack is
# the stack used by the main() thread.
ifeq ($(<API key>),)
<API key> = 0x400
endif
# Stack size to the allocated to the Cortex-M main/exceptions stack. This
# stack is used for processing interrupts and exceptions.
ifeq ($(<API key>),)
<API key> = 0x400
endif
# Enables the use of FPU (no, softfp, hard).
ifeq ($(USE_FPU),)
USE_FPU = no
endif
# Architecture or project specific options
# Project, sources and paths
# Define project name here
PROJECT = ch
# Imported source files and paths
CHIBIOS = ../../../..
# Startup files.
include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f3xx.mk
# HAL-OSAL files (optional).
include $(CHIBIOS)/os/hal/hal.mk
include $(CHIBIOS)/os/hal/ports/STM32/STM32F37x/platform.mk
include $(CHIBIOS)/os/hal/boards/ST_STM32373C_EVAL/board.mk
include $(CHIBIOS)/os/hal/osal/rt/osal.mk
# RTOS files (optional).
include $(CHIBIOS)/os/rt/rt.mk
include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/port_v7m.mk
# Other files (optional).
include $(CHIBIOS)/test/lib/test.mk
include $(CHIBIOS)/test/rt/rt_test.mk
include $(CHIBIOS)/test/oslib/oslib_test.mk
include $(CHIBIOS)/os/hal/lib/streams/streams.mk
include $(CHIBIOS)/os/various/shell/shell.mk
# Define linker script file here
LDSCRIPT= $(STARTUPLD)/STM32F373xC.ld
# C sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CSRC = $(STARTUPSRC) \
$(KERNSRC) \
$(PORTSRC) \
$(OSALSRC) \
$(HALSRC) \
$(PLATFORMSRC) \
$(BOARDSRC) \
$(TESTSRC) \
$(STREAMSSRC) \
$(SHELLSRC) \
usbcfg.c main.c
# C++ sources that can be compiled in ARM or THUMB mode depending on the global
# setting.
CPPSRC =
# C sources to be compiled in ARM mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
ACSRC =
# C++ sources to be compiled in ARM mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
ACPPSRC =
# C sources to be compiled in THUMB mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
TCSRC =
# C sources to be compiled in THUMB mode regardless of the global setting.
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
# option that results in lower performance and larger code size.
TCPPSRC =
# List ASM source files here
ASMSRC =
ASMXSRC = $(STARTUPASM) $(PORTASM) $(OSALASM)
INCDIR = $(CHIBIOS)/os/license \
$(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \
$(HALINC) $(PLATFORMINC) $(BOARDINC) $(TESTINC) \
$(STREAMSINC) $(SHELLINC)
# Project, sources and paths
# Compiler settings
MCU = cortex-m4
#TRGT = arm-elf-
TRGT = arm-none-eabi-
CC = $(TRGT)gcc
CPPC = $(TRGT)g++
# Enable loading with g++ only if you need C++ runtime support.
# NOTE: You can use C++ even without C++ support if you are careful. C++
# runtime support makes code size explode.
LD = $(TRGT)gcc
#LD = $(TRGT)g++
CP = $(TRGT)objcopy
AS = $(TRGT)gcc -x assembler-with-cpp
AR = $(TRGT)ar
OD = $(TRGT)objdump
SZ = $(TRGT)size
HEX = $(CP) -O ihex
BIN = $(CP) -O binary
# ARM-specific options here
AOPT =
# THUMB-specific options here
TOPT = -mthumb -DTHUMB
# Define C warning options here
CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes
# Define C++ warning options here
CPPWARN = -Wall -Wextra -Wundef
# Compiler settings
# Start of user section
# List all user C define here, like -D_DEBUG=1
UDEFS =
# Define ASM defines here
UADEFS =
# List all user directories here
UINCDIR =
# List the user directory to look for the libraries here
ULIBDIR =
# List all user libraries here
ULIBS =
# End of user defines
RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC
include $(RULESPATH)/rules.mk
|
#include "postgres.h"
#include "funcapi.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "tsearch/ts_cache.h"
#include "tsearch/ts_utils.h"
#include "utils/builtins.h"
#include "utils/jsonapi.h"
#include "utils/varlena.h"
typedef struct
{
int cur;
LexDescr *list;
} TSTokenTypeStorage;
/* state for ts_headline_json_* */
typedef struct HeadlineJsonState
{
HeadlineParsedText *prs;
TSConfigCacheEntry *cfg;
TSParserCacheEntry *prsobj;
TSQuery query;
List *prsoptions;
bool transformed;
} HeadlineJsonState;
static text *headline_json_value(void *_state, char *elem_value, int elem_len);
static void
tt_setup_firstcall(FuncCallContext *funcctx, Oid prsid)
{
TupleDesc tupdesc;
MemoryContext oldcontext;
TSTokenTypeStorage *st;
TSParserCacheEntry *prs = <API key>(prsid);
if (!OidIsValid(prs->lextypeOid))
elog(ERROR, "method lextype isn't defined for text search parser %u",
prsid);
oldcontext = <API key>(funcctx-><API key>);
st = (TSTokenTypeStorage *) palloc(sizeof(TSTokenTypeStorage));
st->cur = 0;
/* lextype takes one dummy argument */
st->list = (LexDescr *) DatumGetPointer(OidFunctionCall1(prs->lextypeOid,
(Datum) 0));
funcctx->user_fctx = (void *) st;
tupdesc = <API key>(3, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "alias",
TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description",
TEXTOID, -1, 0);
funcctx->attinmeta = <API key>(tupdesc);
<API key>(oldcontext);
}
static Datum
tt_process_call(FuncCallContext *funcctx)
{
TSTokenTypeStorage *st;
st = (TSTokenTypeStorage *) funcctx->user_fctx;
if (st->list && st->list[st->cur].lexid)
{
Datum result;
char *values[3];
char txtid[16];
HeapTuple tuple;
sprintf(txtid, "%d", st->list[st->cur].lexid);
values[0] = txtid;
values[1] = st->list[st->cur].alias;
values[2] = st->list[st->cur].descr;
tuple = <API key>(funcctx->attinmeta, values);
result = HeapTupleGetDatum(tuple);
pfree(values[1]);
pfree(values[2]);
st->cur++;
return result;
}
if (st->list)
pfree(st->list);
pfree(st);
return (Datum) 0;
}
Datum
ts_token_type_byid(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
tt_setup_firstcall(funcctx, PG_GETARG_OID(0));
}
funcctx = SRF_PERCALL_SETUP();
if ((result = tt_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *prsname = PG_GETARG_TEXT_PP(0);
Oid prsId;
funcctx = SRF_FIRSTCALL_INIT();
prsId = get_ts_parser_oid(<API key>(prsname), false);
tt_setup_firstcall(funcctx, prsId);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = tt_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
typedef struct
{
int type;
char *lexeme;
} LexemeEntry;
typedef struct
{
int cur;
int len;
LexemeEntry *list;
} PrsStorage;
static void
prs_setup_firstcall(FuncCallContext *funcctx, Oid prsid, text *txt)
{
TupleDesc tupdesc;
MemoryContext oldcontext;
PrsStorage *st;
TSParserCacheEntry *prs = <API key>(prsid);
char *lex = NULL;
int llen = 0,
type = 0;
void *prsdata;
oldcontext = <API key>(funcctx-><API key>);
st = (PrsStorage *) palloc(sizeof(PrsStorage));
st->cur = 0;
st->len = 16;
st->list = (LexemeEntry *) palloc(sizeof(LexemeEntry) * st->len);
prsdata = (void *) DatumGetPointer(FunctionCall2(&prs->prsstart,
PointerGetDatum(VARDATA_ANY(txt)),
Int32GetDatum(VARSIZE_ANY_EXHDR(txt))));
while ((type = DatumGetInt32(FunctionCall3(&prs->prstoken,
PointerGetDatum(prsdata),
PointerGetDatum(&lex),
PointerGetDatum(&llen)))) != 0)
{
if (st->cur >= st->len)
{
st->len = 2 * st->len;
st->list = (LexemeEntry *) repalloc(st->list, sizeof(LexemeEntry) * st->len);
}
st->list[st->cur].lexeme = palloc(llen + 1);
memcpy(st->list[st->cur].lexeme, lex, llen);
st->list[st->cur].lexeme[llen] = '\0';
st->list[st->cur].type = type;
st->cur++;
}
FunctionCall1(&prs->prsend, PointerGetDatum(prsdata));
st->len = st->cur;
st->cur = 0;
funcctx->user_fctx = (void *) st;
tupdesc = <API key>(2, false);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid",
INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "token",
TEXTOID, -1, 0);
funcctx->attinmeta = <API key>(tupdesc);
<API key>(oldcontext);
}
static Datum
prs_process_call(FuncCallContext *funcctx)
{
PrsStorage *st;
st = (PrsStorage *) funcctx->user_fctx;
if (st->cur < st->len)
{
Datum result;
char *values[2];
char tid[16];
HeapTuple tuple;
values[0] = tid;
sprintf(tid, "%d", st->list[st->cur].type);
values[1] = st->list[st->cur].lexeme;
tuple = <API key>(funcctx->attinmeta, values);
result = HeapTupleGetDatum(tuple);
pfree(values[1]);
st->cur++;
return result;
}
else
{
if (st->list)
pfree(st->list);
pfree(st);
}
return (Datum) 0;
}
Datum
ts_parse_byid(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *txt = PG_GETARG_TEXT_PP(1);
funcctx = SRF_FIRSTCALL_INIT();
prs_setup_firstcall(funcctx, PG_GETARG_OID(0), txt);
PG_FREE_IF_COPY(txt, 1);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = prs_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
ts_parse_byname(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
Datum result;
if (SRF_IS_FIRSTCALL())
{
text *prsname = PG_GETARG_TEXT_PP(0);
text *txt = PG_GETARG_TEXT_PP(1);
Oid prsId;
funcctx = SRF_FIRSTCALL_INIT();
prsId = get_ts_parser_oid(<API key>(prsname), false);
prs_setup_firstcall(funcctx, prsId, txt);
}
funcctx = SRF_PERCALL_SETUP();
if ((result = prs_process_call(funcctx)) != (Datum) 0)
SRF_RETURN_NEXT(funcctx, result);
SRF_RETURN_DONE(funcctx);
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
text *in = PG_GETARG_TEXT_PP(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_PP(3) : NULL;
HeadlineParsedText prs;
List *prsoptions;
text *out;
TSConfigCacheEntry *cfg;
TSParserCacheEntry *prsobj;
cfg = <API key>(tsconfig);
prsobj = <API key>(cfg->prsId);
if (!OidIsValid(prsobj->headlineOid))
ereport(ERROR,
(errcode(<API key>),
errmsg("text search parser does not support headline creation")));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
hlparsetext(cfg->cfgId, &prs, query,
VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in));
if (opt)
prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
prsoptions = NIL;
FunctionCall3(&(prsobj->prsheadline),
PointerGetDatum(&prs),
PointerGetDatum(prsoptions),
PointerGetDatum(query));
out = generateHeadline(&prs);
PG_FREE_IF_COPY(in, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
pfree(prs.startsel);
pfree(prs.stopsel);
PG_RETURN_POINTER(out);
}
Datum
ts_headline_byid(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
ts_headline(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
ts_headline_opt(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
Jsonb *jb = PG_GETARG_JSONB_P(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL;
Jsonb *out;
<API key> action = (<API key>) headline_json_value;
HeadlineParsedText prs;
HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
state->prs = &prs;
state->cfg = <API key>(tsconfig);
state->prsobj = <API key>(state->cfg->prsId);
state->query = query;
if (opt)
state->prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
state->prsoptions = NIL;
if (!OidIsValid(state->prsobj->headlineOid))
ereport(ERROR,
(errcode(<API key>),
errmsg("text search parser does not support headline creation")));
out = <API key>(jb, state, action);
PG_FREE_IF_COPY(jb, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
if (state->transformed)
{
pfree(prs.startsel);
pfree(prs.stopsel);
}
PG_RETURN_JSONB_P(out);
}
Datum
ts_headline_jsonb(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
Oid tsconfig = PG_GETARG_OID(0);
text *json = PG_GETARG_TEXT_P(1);
TSQuery query = PG_GETARG_TSQUERY(2);
text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL;
text *out;
<API key> action = (<API key>) headline_json_value;
HeadlineParsedText prs;
HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState));
memset(&prs, 0, sizeof(HeadlineParsedText));
prs.lenwords = 32;
prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords);
state->prs = &prs;
state->cfg = <API key>(tsconfig);
state->prsobj = <API key>(state->cfg->prsId);
state->query = query;
if (opt)
state->prsoptions = deserialize_deflist(PointerGetDatum(opt));
else
state->prsoptions = NIL;
if (!OidIsValid(state->prsobj->headlineOid))
ereport(ERROR,
(errcode(<API key>),
errmsg("text search parser does not support headline creation")));
out = <API key>(json, state, action);
PG_FREE_IF_COPY(json, 1);
PG_FREE_IF_COPY(query, 2);
if (opt)
PG_FREE_IF_COPY(opt, 3);
pfree(prs.words);
if (state->transformed)
{
pfree(prs.startsel);
pfree(prs.stopsel);
}
PG_RETURN_TEXT_P(out);
}
Datum
ts_headline_json(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall3(<API key>,
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
Datum
<API key>(PG_FUNCTION_ARGS)
{
PG_RETURN_DATUM(DirectFunctionCall4(<API key>,
ObjectIdGetDatum(getTSCurrentConfig(true)),
PG_GETARG_DATUM(0),
PG_GETARG_DATUM(1),
PG_GETARG_DATUM(2)));
}
/*
* Return headline in text from, generated from a json(b) element
*/
static text *
headline_json_value(void *_state, char *elem_value, int elem_len)
{
HeadlineJsonState *state = (HeadlineJsonState *) _state;
HeadlineParsedText *prs = state->prs;
TSConfigCacheEntry *cfg = state->cfg;
TSParserCacheEntry *prsobj = state->prsobj;
TSQuery query = state->query;
List *prsoptions = state->prsoptions;
prs->curwords = 0;
hlparsetext(cfg->cfgId, prs, query, elem_value, elem_len);
FunctionCall3(&(prsobj->prsheadline),
PointerGetDatum(prs),
PointerGetDatum(prsoptions),
PointerGetDatum(query));
state->transformed = true;
return generateHeadline(prs);
}
|
package org.luolamies.jgcgen.text;
import java.io.File;
import java.io.FileInputStream;
import java.io.<API key>;
import java.io.IOException;
import java.io.InputStream;
import org.luolamies.jgcgen.RenderException;
public class Fonts {
private final File workdir;
public Fonts(File workdir) {
this.workdir = workdir;
}
public Font get(String name) {
String type;
if(name.endsWith(".jhf"))
type = "Hershey";
else
throw new RenderException("Can't figure out font type from filename! Use $fonts.get(\"file\", \"type\")");
return get(name, type);
}
@SuppressWarnings("unchecked")
public Font get(String name, String type) {
Class<? extends Font> fclass;
try {
fclass = (Class<? extends Font>) Class.forName(getClass().getPackage().getName() + "." + type + "Font");
} catch (<API key> e1) {
throw new RenderException("Font type \"" + type + "\" not supported!");
}
InputStream in;
File file = new File(workdir, name);
if(file.isFile()) {
try {
in = new FileInputStream(file);
} catch (<API key> e) {
in = null;
}
} else
in = getClass().getResourceAsStream("/fonts/" + name);
if(in==null)
throw new RenderException("Can't find font: " + name);
try {
return fclass.getConstructor(InputStream.class).newInstance(in);
} catch(Exception e) {
throw new RenderException("Error while trying to construct handler for font \"" + type + "\": " + e.getMessage(), e);
} finally {
try { in.close(); } catch (IOException e) { }
}
}
}
|
#!/bin/bash -f
# Vivado (TM) v2015.4.2 (64-bit)
# Filename : design_TEST.sh
# Simulator : Cadence Incisive Enterprise Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
# The script will automatically create the design libraries sub-directories in the run
# directory, add the library logical mappings in the simulator setup file, create default
# 'do/prj' file, execute compilation, elaboration and simulation steps.
# Generated by Vivado on Thu Sep 01 17:23:17 +0200 2016
# IP Build 1491208 on Wed Feb 24 03:25:39 MST 2016
# usage: design_TEST.sh [-help]
# usage: design_TEST.sh [-lib_map_path]
# usage: design_TEST.sh [-noclean_files]
# usage: design_TEST.sh [-reset_run]
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
# You can also point to the simulation libraries by either replacing the <<API key>> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'design_TEST.sh -help' for more information.
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
# Script info
echo -e "design_TEST.sh - Script generated by export_simulation (Vivado v2015.4.2 (64-bit)-id)\n"
# Script usage
usage()
{
msg="Usage: design_TEST.sh [-help]\n\
Usage: design_TEST.sh [-lib_map_path]\n\
Usage: design_TEST.sh [-reset_run]\n\
Usage: design_TEST.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
echo -e $msg
exit 1
}
if [[ ($# == 1 ) && ($1 != "-lib_map_path" && $1 != "-noclean_files" && $1 != "-reset_run" && $1 != "-help" && $1 != "-h") ]]; then
echo -e "ERROR: Unknown option specified '$1' (type \"./design_TEST.sh -help\" for more information)\n"
exit 1
fi
if [[ ($1 == "-help" || $1 == "-h") ]]; then
usage
fi
# STEP: setup
setup()
{
case $1 in
"-lib_map_path" )
if [[ ($2 == "") ]]; then
echo -e "ERROR: Simulation library directory path not specified (type \"./design_TEST.sh -help\" for more information)\n"
exit 1
fi
# precompiled simulation library directory path
create_lib_mappings $2
touch hdl.var
;;
"-reset_run" )
reset_run
echo -e "INFO: Simulation run files deleted.\n"
exit 0
;;
"-noclean_files" )
# do not remove previous data
;;
* )
create_lib_mappings $2
touch hdl.var
esac
# Add any setup/initialization commands here:-
# <user specific commands>
}
# Remove generated data from the previous run and re-create setup files/library mappings
reset_run()
{
files_to_remove=(ncsim.key irun.key ncvlog.log ncvhdl.log compile.log elaborate.log simulate.log run.log waves.shm INCA_libs)
for (( i=0; i<${#files_to_remove[*]}; i++ )); do
file="${files_to_remove[i]}"
if [[ -e $file ]]; then
rm -rf $file
fi
done
}
# Main steps
run()
{
setup $1 $2
compile
elaborate
simulate
}
# Create design library directory paths and define design library mappings in cds.lib
create_lib_mappings()
{
libs=(xil_defaultlib lib_pkg_v1_0_2 <API key> lib_fifo_v1_0_4 lib_srl_fifo_v1_0_2 lib_cdc_v1_0_2 <API key> axi_sg_v4_1_2 axi_dma_v7_1_8 <API key> <API key> <API key> <API key> <API key> axi_crossbar_v2_1_8 <API key>)
file="cds.lib"
dir="ies"
if [[ -e $file ]]; then
rm -f $file
fi
if [[ -e $dir ]]; then
rm -rf $dir
fi
touch $file
lib_map_path="<<API key>>"
if [[ ($1 != "" && -e $1) ]]; then
lib_map_path="$1"
else
echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n"
fi
incl_ref="INCLUDE $lib_map_path/cds.lib"
echo $incl_ref >> $file
for (( i=0; i<${#libs[*]}; i++ )); do
lib="${libs[i]}"
lib_dir="$dir/$lib"
if [[ ! -e $lib_dir ]]; then
mkdir -p $lib_dir
mapping="DEFINE $lib $dir/$lib"
echo $mapping >> $file
fi
done
}
# RUN_STEP: <compile>
compile()
{
# Directory path for design sources and include directories (if any) wrt this path
ref_dir="."
# Command line options
opts_ver="-64bit -messages -logfile ncvlog.log -append_log"
opts_vhd="-64bit -V93 -RELAX -logfile ncvhdl.log -append_log"
# Compile design files
ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.v" \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.v" \
ncvhdl -work lib_pkg_v1_0_2 $opts_vhd \
"$ref_dir/../../../ipstatic/lib_pkg_v1_0/hdl/src/vhdl/lib_pkg.vhd" \
ncvhdl -work <API key> $opts_vhd \
"$ref_dir/../../../ipstatic/<API key>/simulation/<API key>.vhd" \
"$ref_dir/../../../ipstatic/<API key>/hdl/<API key>.vhd" \
ncvhdl -work lib_fifo_v1_0_4 $opts_vhd \
"$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/async_fifo_fg.vhd" \
"$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/sync_fifo_fg.vhd" \
ncvhdl -work lib_srl_fifo_v1_0_2 $opts_vhd \
"$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/dynshreg_f.vhd" \
"$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_rbu_f.vhd" \
"$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_f.vhd" \
ncvhdl -work lib_cdc_v1_0_2 $opts_vhd \
"$ref_dir/../../../ipstatic/lib_cdc_v1_0/hdl/src/vhdl/cdc_sync.vhd" \
ncvhdl -work <API key> $opts_vhd \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_reset.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_fifo.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_scc.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_pcc.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rdmux.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rd_sf.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_sf.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_slice.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover.vhd" \
ncvhdl -work axi_sg_v4_1_2 $opts_vhd \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_pkg.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_reset.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_sfifo_autord.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_afifo_autord.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_fifo.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cmd_status.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rdmux.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_addr_cntl.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rddata_cntl.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wr_demux.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc_wr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid2mm_buf.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wrdata_cntl.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid_buf.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_datamover.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_sm.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_pntr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cntrl_strm.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_queue.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_noqueue.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_q_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_sm.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_queue.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_noqueue.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_q_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_intrpt.vhd" \
"$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg.vhd" \
ncvhdl -work axi_dma_v7_1_8 $opts_vhd \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_pkg.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reset.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_rst_module.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_lite_if.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_register.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reg_module.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_skid_buf.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_sofeof_gen.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_smple_sm.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sg_if.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sm.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sg_if.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sm.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/<API key>.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_mngr.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_cmd_split.vhd" \
"$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma.vhd" \
ncvhdl -work xil_defaultlib $opts_vhd \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.vhd" \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.vhd" \
ncvhdl -work <API key> $opts_vhd \
"$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/upcnt_n.vhd" \
"$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/sequence_psr.vhd" \
"$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/lpf.vhd" \
"$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/proc_sys_reset.vhd" \
ncvhdl -work xil_defaultlib $opts_vhd \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.vhd" \
ncvlog -work <API key> $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
ncvlog -work <API key> $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
ncvlog -work <API key> $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
ncvlog -work <API key> $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/<API key>.v" \
ncvlog -work axi_crossbar_v2_1_8 $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/<API key>.v" \
ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_0/sim/design_TEST_xbar_0.v" \
"$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_1/sim/design_TEST_xbar_1.v" \
ncvlog -work <API key> $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
"$ref_dir/../../../ipstatic/<API key>/hdl/verilog/<API key>.v" \
ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/<API key>/hdl" \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.v" \
"$ref_dir/../../../bd/design_TEST/ip/<API key>/sim/<API key>.v" \
ncvhdl -work xil_defaultlib $opts_vhd \
"$ref_dir/../../../bd/design_TEST/hdl/design_TEST.vhd" \
ncvlog $opts_ver -work xil_defaultlib \
"glbl.v"
}
# RUN_STEP: <elaborate>
elaborate()
{
opts="-loadvpi "C:/Xilinx/Vivado/2015.4/lib/win64.o/libxil_ncsim.dll:<API key>" -64bit -relax -access +rwc -messages -logfile elaborate.log -timescale 1ps/1ps"
libs="-libname unisims_ver -libname unimacro_ver -libname secureip -libname xil_defaultlib -libname lib_pkg_v1_0_2 -libname <API key> -libname lib_fifo_v1_0_4 -libname lib_srl_fifo_v1_0_2 -libname lib_cdc_v1_0_2 -libname <API key> -libname axi_sg_v4_1_2 -libname axi_dma_v7_1_8 -libname <API key> -libname <API key> -libname <API key> -libname <API key> -libname <API key> -libname axi_crossbar_v2_1_8 -libname <API key>"
ncelab $opts xil_defaultlib.design_TEST xil_defaultlib.glbl $libs
}
# RUN_STEP: <simulate>
simulate()
{
opts="-64bit -logfile simulate.log"
ncsim $opts xil_defaultlib.design_TEST -input simulate.do
}
# Script usage
usage()
{
msg="Usage: design_TEST.sh [-help]\n\
Usage: design_TEST.sh [-lib_map_path]\n\
Usage: design_TEST.sh [-reset_run]\n\
Usage: design_TEST.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
echo -e $msg
exit 1
}
# Launch script
run $1 $2
|
\subsection{Instruction Working Set Signature}
An instruction working set (IWS)~\cite{Dhodapkar:2002:MMH} is the set of instructions touched over a fixed interval of time. The relative working set distance between intervals $i$ and $i-1$ is defined as
\begin{center}
$\delta_{i,i-1} = \frac{||W_i \bigcup W_{i-1}||-||W_i \bigcap W_{i-1}||}{||W_i \bigcup W_{i-1}||}$
\end{center}
where $W_i$ is the working set for interval $i$.
A working set signature is a lossy-compressed representation of a working set. The program counter is sampled over a fixed interval of instructions. A hashing function is applied to the sample to set a bit in an $n$-bit vector, which represents the signature (See Figure~\ref{fig:signature}). Phase changes are detected by computing the relative signature distance between intervals and comparing the distance against some pre-determined threshold. The hardware complexity of this technique is dependent on the working set size.
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=0.60\columnwidth]{figs/workingsetsignature}
\end{center}
\caption{Generating the working set signature.}
\label{fig:signature}
\end{figure}
|
// -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
// vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et:
using System;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Reflection;
namespace XSpect.MetaTweet.Objects
{
public class <API key>
: ObjectContext
{
public const String ContainerName = "<API key>";
private ObjectSet<Account> _accounts;
private ObjectSet<Activity> _activities;
private ObjectSet<Advertisement> _advertisements;
public <API key>(String connectionString)
: base(connectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
this.ContextOptions.<API key> = false;
}
public <API key>(EntityConnection connection)
: base(connection, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
this.ContextOptions.<API key> = false;
}
public ObjectSet<Account> Accounts
{
get
{
return this._accounts ?? (this._accounts = this.CreateObjectSet<Account>("Accounts"));
}
}
public ObjectSet<Activity> Activities
{
get
{
return this._activities ?? (this._activities = this.CreateObjectSet<Activity>("Activities"));
}
}
public ObjectSet<Advertisement> Advertisements
{
get
{
return this._advertisements ?? (this._advertisements = this.CreateObjectSet<Advertisement>("Advertisements"));
}
}
public Boolean IsDisposed
{
get
{
// HACK: Depends on internal structure, accessing non-public field
return typeof(ObjectContext)
.GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(this) == null;
}
}
public ObjectSet<TObject> GetObjectSet<TObject>()
where TObject : StorageObject
{
return (ObjectSet<TObject>) (typeof(TObject) == typeof(Account)
? (Object) this.Accounts
: typeof(TObject) == typeof(Activity)
? (Object) this.Activities
: this.Advertisements
);
}
public String GetEntitySetName<TObject>()
where TObject : StorageObject
{
return typeof(TObject) == typeof(Account)
? ContainerName + ".Accounts"
: typeof(TObject) == typeof(Activity)
? ContainerName + ".Activities"
: ContainerName + ".Advertisements";
}
public String GetEntitySetName(StorageObject obj)
{
return obj is Account
? ContainerName + ".Accounts"
: obj is Activity
? ContainerName + ".Activities"
: ContainerName + ".Advertisements";
}
}
}
|
# -*- coding: utf-8 -*-
from django.conf.urls import include, url, patterns
from django.contrib import admin
from Workinout import views
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*)
]
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
else:
urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}),
)
|
#region using directives
using POGOProtos.Enums;
using POGOProtos.Settings.Master.Pokemon;
#endregion
namespace PoGo.PokeMobBot.Logic.Event.Pokemon
{
public class BaseNewPokemonEvent : IEvent
{
public int Cp;
public ulong Uid;
public PokemonId Id;
public double Perfection;
public PokemonFamilyId Family;
public int Candy;
public double Level;
public PokemonMove Move1;
public PokemonMove Move2;
public PokemonType Type1;
public PokemonType Type2;
public StatsAttributes Stats;
public int MaxCp;
public int Stamina;
public int IvSta;
public int PossibleCp;
public int CandyToEvolve;
public int IvAtk;
public int IvDef;
public float Cpm;
public float Weight;
public int StaminaMax;
public PokemonId[] Evolutions;
public double Latitude;
public double Longitude;
}
}
|
#!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import poplib, email, re, sys, xmlConfigs, utils;
class ReferenceNode :
def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")):
self.node = node
self.children = dict(children)
self.references = references[:]
self.slotted = slotted
self.emailMessage = emailMessage
def get_node(self):
return self.node
def get_children(self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
def __repr__(self):
return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n"
def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, <API key>):
for reference in referencesToCheck[:] :
if reference in referenceNodeNow.get_children() :
referencesToCheck.remove(reference)
return <API key>[reference]
if len(referencesToCheck) == 0 :
referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction
def makeChildren(<API key>) :
ref_keys = <API key>.keys()
ref_keys.sort()
for messageId in ref_keys:
referenceNode = <API key>[messageId]
utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node())
referenceIds = referenceNode.get_references()
referenceIdsClone = referenceIds[:]
utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone)
if len(referenceIds) > 0 :
nextNode = <API key>[referenceIdsClone[0]]
referenceIdsClone.remove(referenceIdsClone[0])
while nextNode != None :
utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node())
utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node())
utils.verboseOutput(verbose, "REF: ", referenceIdsClone)
nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, <API key>)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument == "--verbose" :
verbose = "true"
pseudoArgs.remove(argument)
utils.verboseOutput(verbose, "Checking POP3 for gmail")
try:
emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml")
myPop = emailConfig.get_pop3_connection()
numMessages = len(myPop.list()[1])
patchMessages = dict()
for i in range(numMessages):
utils.verboseOutput(verbose, "Index: ", i)
totalContent = ""
for content in myPop.retr(i+1)[1]:
totalContent += content + '\n'
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", subject)
if subjectMatch == None :
continue
else :
continue
messageId = ""
if 'message-id' in msg:
messageId = re.search("<(.*)>", msg['message-id']).group(1)
utils.verboseOutput(verbose, 'Message-ID:', messageId)
referenceIds = []
if 'references' in msg:
references = msg['references']
referenceIds = re.findall("<(.*)>", references)
utils.verboseOutput(verbose, "References: ", referenceIds)
currentNode = ReferenceNode(messageId, msg, referenceIds)
patchMessages[messageId] = currentNode
currentNode.set_slotted(bool("false"))
utils.verboseOutput(verbose, "**************Make Children**************")
makeChildren(patchMessages)
utils.verboseOutput(verbose, "
utils.verboseOutput(verbose, patchMessages)
except:
utils.verboseOutput(verbose, "Error: ", sys.exc_info())
|
// modified for NAudio
// milligan22963 - updated to include audio session manager
using System;
using NAudio.CoreAudioApi.Interfaces;
using System.Runtime.InteropServices;
namespace NAudio.CoreAudioApi
{
<summary>
MM Device
</summary>
public class MMDevice : IDisposable
{
#region Variables
private readonly IMMDevice deviceInterface;
private PropertyStore propertyStore;
private <API key> <API key>;
private AudioEndpointVolume audioEndpointVolume;
private AudioSessionManager audioSessionManager;
#endregion
#region Guids
private static Guid <API key> = new Guid("<API key>");
private static Guid <API key> = new Guid("<API key>");
private static Guid IID_IAudioClient = new Guid("<API key>");
private static Guid <API key> = new Guid("<API key>");
#endregion
#region Init
<summary>
Initializes the device's property store.
</summary>
<param name="stgmAccess">The storage-access mode to open store for.</param>
<remarks>Administrative client is required for Write and ReadWrite modes.</remarks>
public void <API key>(StorageAccessMode stgmAccess = StorageAccessMode.Read)
{
IPropertyStore propstore;
Marshal.ThrowExceptionForHR(deviceInterface.OpenPropertyStore(stgmAccess, out propstore));
propertyStore = new PropertyStore(propstore);
}
private AudioClient GetAudioClient()
{
object result;
Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero,
out result));
return new AudioClient(result as IAudioClient);
}
private void <API key>()
{
object result;
Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref <API key>, ClsCtx.ALL,
IntPtr.Zero, out result));
<API key> = new <API key>(result as <API key>);
}
private void <API key>()
{
object result;
Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref <API key>, ClsCtx.ALL, IntPtr.Zero,
out result));
audioEndpointVolume = new AudioEndpointVolume(result as <API key>);
}
private void <API key>()
{
object result;
Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref <API key>, ClsCtx.ALL, IntPtr.Zero,
out result));
audioSessionManager = new AudioSessionManager(result as <API key>);
}
#endregion
#region Properties
<summary>
Audio Client
</summary>
public AudioClient AudioClient
{
get
{
// now makes a new one each call to allow caller to manage when to dispose
// n.b. should probably not be a property anymore
return GetAudioClient();
}
}
<summary>
Audio Meter Information
</summary>
public <API key> <API key>
{
get
{
if (<API key> == null)
<API key>();
return <API key>;
}
}
<summary>
Audio Endpoint Volume
</summary>
public AudioEndpointVolume AudioEndpointVolume
{
get
{
if (audioEndpointVolume == null)
<API key>();
return audioEndpointVolume;
}
}
<summary>
AudioSessionManager instance
</summary>
public AudioSessionManager AudioSessionManager
{
get
{
if (audioSessionManager == null)
{
<API key>();
}
return audioSessionManager;
}
}
<summary>
Properties
</summary>
public PropertyStore Properties
{
get
{
if (propertyStore == null)
<API key>();
return propertyStore;
}
}
<summary>
Friendly name for the endpoint
</summary>
public string FriendlyName
{
get
{
if (propertyStore == null)
{
<API key>();
}
if (propertyStore.Contains(PropertyKeys.<API key>))
{
return (string) propertyStore[PropertyKeys.<API key>].Value;
}
else
return "Unknown";
}
}
<summary>
Friendly name of device
</summary>
public string DeviceFriendlyName
{
get
{
if (propertyStore == null)
{
<API key>();
}
if (propertyStore.Contains(PropertyKeys.<API key>))
{
return (string) propertyStore[PropertyKeys.<API key>].Value;
}
else
{
return "Unknown";
}
}
}
<summary>
Icon path of device
</summary>
public string IconPath
{
get
{
if (propertyStore == null)
{
<API key>();
}
if (propertyStore.Contains(PropertyKeys.<API key>))
{
return (string) propertyStore[PropertyKeys.<API key>].Value;
}
else
return "Unknown";
}
}
<summary>
Device ID
</summary>
public string ID
{
get
{
string result;
Marshal.ThrowExceptionForHR(deviceInterface.GetId(out result));
return result;
}
}
<summary>
Data Flow
</summary>
public DataFlow DataFlow
{
get
{
DataFlow result;
var ep = deviceInterface as IMMEndpoint;
ep.GetDataFlow(out result);
return result;
}
}
<summary>
Device State
</summary>
public DeviceState State
{
get
{
DeviceState result;
Marshal.ThrowExceptionForHR(deviceInterface.GetState(out result));
return result;
}
}
#endregion
#region Constructor
internal MMDevice(IMMDevice realDevice)
{
deviceInterface = realDevice;
}
#endregion
<summary>
To string
</summary>
public override string ToString()
{
return FriendlyName;
}
<summary>
Dispose
</summary>
public void Dispose()
{
this.audioEndpointVolume?.Dispose();
this.audioSessionManager?.Dispose();
GC.SuppressFinalize(this);
}
<summary>
Finalizer
</summary>
~MMDevice()
{
Dispose();
}
}
}
|
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <opencv2/imgproc.hpp>
#include <vector>
#include "filter.h"
#include "filterwidget.h"
#include <imgproc/types.h>
#include <imgproc/thresholding.h>
#include <imgproc/util.h>
Filter::Filter() :
mThresholdMode(0),
mColorMode(0)
{
for (int i = 0; i < 5; i++)
mAffectedChannel[i] = false;
}
Filter::~Filter()
{
}
ImageFilter *Filter::clone()
{
Filter * f = new Filter();
f->mThresholdMode = mThresholdMode;
f->mColorMode = mColorMode;
for (int i = 0; i < 5; i++)
f->mAffectedChannel[i] = mAffectedChannel[i];
return f;
}
extern "C" QHash<QString, QString> getIBPPluginInfo();
QHash<QString, QString> Filter::info()
{
return getIBPPluginInfo();
}
QImage Filter::process(const QImage &inputImage)
{
if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32)
return inputImage;
QImage i = inputImage.copy();
cv::Mat dstMat(i.height(), i.width(), CV_8UC4, i.bits(), i.bytesPerLine());
const int radius = 10;
const int windowSize = radius * 2 + 1;
const double k = .05;
if (mColorMode == 0)
{
if (!mAffectedChannel[0] && !mAffectedChannel[4])
return i;
if (mAffectedChannel[0])
{
register BGRA * bitsSrc = (BGRA *)inputImage.bits();
register BGRA * bitsDst = (BGRA *)i.bits();
register int totalPixels = i.width() * i.height();
while (totalPixels
{
bitsDst->b = IBP_pixelIntensity4(bitsSrc->r, bitsSrc->g, bitsSrc->b);
bitsSrc++;
bitsDst++;
}
}
cv::Mat mSrcGray, mSrcAlpha;
if (mAffectedChannel[0])
{
mSrcGray = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 0,0 };
cv::mixChannels(&dstMat, 1, &mSrcGray, 1, from_to, 1);
}
if (mAffectedChannel[4])
{
mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 3,0 };
cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1);
}
if (mThresholdMode == 0)
{
if (mAffectedChannel[0])
cv::threshold(mSrcGray, mSrcGray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (mAffectedChannel[4])
cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
}
else
{
if (mAffectedChannel[0])
<API key>(mSrcGray, mSrcGray, windowSize, k);
if (mAffectedChannel[4])
<API key>(mSrcAlpha, mSrcAlpha, windowSize, k);
}
if (mAffectedChannel[0])
{
int from_to[] = { 0,0, 0,1, 0,2 };
cv::mixChannels(&mSrcGray, 1, &dstMat, 1, from_to, 3);
}
if (mAffectedChannel[4])
{
int from_to[] = { 0,3 };
cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1);
}
}
else
{
if (!mAffectedChannel[1] && !mAffectedChannel[2] &&
!mAffectedChannel[3] && !mAffectedChannel[4])
return i;
cv::Mat mSrcRed, mSrcGreen, mSrcBlue, mSrcAlpha;
if (mAffectedChannel[1])
{
mSrcBlue = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 0,0 };
cv::mixChannels(&dstMat, 1, &mSrcBlue, 1, from_to, 1);
}
if (mAffectedChannel[2])
{
mSrcGreen = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 1,0 };
cv::mixChannels(&dstMat, 1, &mSrcGreen, 1, from_to, 1);
}
if (mAffectedChannel[3])
{
mSrcRed = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 2,0 };
cv::mixChannels(&dstMat, 1, &mSrcRed, 1, from_to, 1);
}
if (mAffectedChannel[4])
{
mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1);
int from_to[] = { 3,0 };
cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1);
}
if (mThresholdMode == 0)
{
if (mAffectedChannel[1])
cv::threshold(mSrcBlue, mSrcBlue, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (mAffectedChannel[2])
cv::threshold(mSrcGreen, mSrcGreen, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (mAffectedChannel[3])
cv::threshold(mSrcRed, mSrcRed, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
if (mAffectedChannel[4])
cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
}
else
{
if (mAffectedChannel[1])
<API key>(mSrcBlue, mSrcBlue, windowSize, k);
if (mAffectedChannel[2])
<API key>(mSrcGreen, mSrcGreen, windowSize, k);
if (mAffectedChannel[3])
<API key>(mSrcRed, mSrcRed, windowSize, k);
if (mAffectedChannel[4])
<API key>(mSrcAlpha, mSrcAlpha, windowSize, k);
}
if (mAffectedChannel[1])
{
int from_to[] = { 0,0 };
cv::mixChannels(&mSrcBlue, 1, &dstMat, 1, from_to, 1);
}
if (mAffectedChannel[2])
{
int from_to[] = { 0,1 };
cv::mixChannels(&mSrcGreen, 1, &dstMat, 1, from_to, 1);
}
if (mAffectedChannel[3])
{
int from_to[] = { 0,2 };
cv::mixChannels(&mSrcRed, 1, &dstMat, 1, from_to, 1);
}
if (mAffectedChannel[4])
{
int from_to[] = { 0,3 };
cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1);
}
}
return i;
}
bool Filter::loadParameters(QSettings &s)
{
QString thresholdModeStr, colorModeStr, affectedChannelStr;
int thresholdMode, colorMode;
QStringList affectedChannelList;
bool affectedChannel[5] = { false };
thresholdModeStr = s.value("thresholdmode", "global").toString();
if (thresholdModeStr == "global")
thresholdMode = 0;
else if (thresholdModeStr == "local")
thresholdMode = 1;
else
return false;
colorModeStr = s.value("colormode", "luma").toString();
if (colorModeStr == "luma")
colorMode = 0;
else if (colorModeStr == "rgb")
colorMode = 1;
else
return false;
affectedChannelStr = s.value("affectedchannels", "").toString();
affectedChannelList = affectedChannelStr.split(" ", QString::SkipEmptyParts);
for (int i = 0; i < affectedChannelList.size(); i++)
{
affectedChannelStr = affectedChannelList.at(i);
if (affectedChannelList.at(i) == "luma")
affectedChannel[0] = true;
else if (affectedChannelList.at(i) == "red")
affectedChannel[1] = true;
else if (affectedChannelList.at(i) == "green")
affectedChannel[2] = true;
else if (affectedChannelList.at(i) == "blue")
affectedChannel[3] = true;
else if (affectedChannelList.at(i) == "alpha")
affectedChannel[4] = true;
else
return false;
}
setThresholdMode(thresholdMode);
setColorMode(colorMode);
for (int i = 0; i < 5; i++)
setAffectedChannel(i, affectedChannel[i]);
return true;
}
bool Filter::saveParameters(QSettings &s)
{
s.setValue("thresholdmode", mThresholdMode == 0 ? "global" : "local");
s.setValue("colormode", mColorMode == 0 ? "luma" : "rgb");
QStringList affectedChannelList;
if (mAffectedChannel[0])
affectedChannelList.append("luma");
if (mAffectedChannel[1])
affectedChannelList.append("red");
if (mAffectedChannel[2])
affectedChannelList.append("green");
if (mAffectedChannel[3])
affectedChannelList.append("blue");
if (mAffectedChannel[4])
affectedChannelList.append("alpha");
s.setValue("affectedchannels", affectedChannelList.join(" "));
return true;
}
QWidget *Filter::widget(QWidget *parent)
{
FilterWidget * fw = new FilterWidget(parent);
fw->setThresholdMode(mThresholdMode);
fw->setColorMode(mColorMode);
for (int i = 0; i < 5; i++)
fw->setAffectedChannel(i, mAffectedChannel[i]);
connect(this, SIGNAL(<API key>(int)), fw, SLOT(setThresholdMode(int)));
connect(this, SIGNAL(colorModeChanged(int)), fw, SLOT(setColorMode(int)));
connect(this, SIGNAL(<API key>(int,bool)), fw, SLOT(setAffectedChannel(int,bool)));
connect(fw, SIGNAL(<API key>(int)), this, SLOT(setThresholdMode(int)));
connect(fw, SIGNAL(colorModeChanged(int)), this, SLOT(setColorMode(int)));
connect(fw, SIGNAL(<API key>(int,bool)), this, SLOT(setAffectedChannel(int,bool)));
return fw;
}
void Filter::setThresholdMode(int m)
{
if (m == mThresholdMode)
return;
mThresholdMode = m;
emit <API key>(m);
emit parametersChanged();
}
void Filter::setColorMode(int m)
{
if (m == mColorMode)
return;
mColorMode = m;
emit colorModeChanged(m);
emit parametersChanged();
}
void Filter::setAffectedChannel(int c, bool a)
{
if (a == mAffectedChannel[c])
return;
mAffectedChannel[c] = a;
emit <API key>(c, a);
emit parametersChanged();
}
|
<!DOCTYPE html>
<html>
<head>
<title>SenseNet : modul Senzory</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./SenseNet_Files/over.css">
<link rel="stylesheet" href="https:
<link rel="stylesheet" href="./SenseNet_Files/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Arvo' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>
<link rel="icon" href="./SenseNet_Files/favicon.ico">
<meta name="author" content="labka.cz" />
<meta name="description" content="SenseNet platform which is able to measure, parse, and predict data about air polution in industrial region Ostrava" />
<meta name="keywords" content="SenseNet, SensoricNet, Sense Net, Sensoric Net, AI, platform, prediction, parser, neural network, hackerspace, labka.cz, labka, ostrava, hackerspaces, polution, air, environmental, environment"/>
</head>
<body>
<!-- Imported floating menu -->
<div class="obal">
<div class="menu">
<iframe src="menu.html" seamless></iframe>
</div>
</div>
<div class="celek">
<img class="obrR" src="./SenseNet_Files/pavel_s.png" width="350px">
<h2>Modul NET : infrastruktura </h2>
<div>
Mezi moduly Smysly [Sense] a Mozek [Brain] musí samozřejmě existovat nějaké spojení, tak jako jsou jím v lidském těle nervy.br />
V našem případě je takových spojení potřeba několik. Budou se budou vzájemně překrývat, protože komunikace je zásadní pro každý projekt a proto je potřebné mít oněch pomyslných nervových soustav několik a na několika různých vrstvách.<br />
<br />
Cílem projektu je vytvoření rozhraní mezi senzory a servery, na kterých se budou data zpracovávat, a to tak, aby bylo možné projekt zveřejnit jak pod OpenSource licencemi, jako kompletní, preprodukovatelné řešení, tak aby na druhou stranu bylo možné enterprise nasazení za pomoci patentovaných technologií a garantovaných vysílacích pásem.<br />
<h3>NB-IoT</h3>
NB-IoT je experimentální standardizovaná techologie bezdrátového přenosu malých množtví dat pomocí existující bezdrátové telefonní a datové sítě.<br />
<br />
Technologie NB-IoT je založena na standardech Low Power Wide Area (LPWA) a díky její nízké spotřebě a vysoké propustnosti se Internet věcí může masivně rozšířit. Podporuje řešení jak v průmyslu (např. v energetice, automobilovém průmyslu, strojírenství, zemědělství, atd.), zdravotnictví a v projektech chytrých měst, tak i v oblasti běžného života (monitorování a zabezpečení domácností, vozidel, domácích mazlíčků atd.). Mezi největší výhody patří výborná prostupnost signálu překážkami, signál se tak dostane i do sklepů nebo garáží, dále provoz na licencovaném frekvenčním pásmu zajišťujícím uživatelům spolehlivější a bezpečnější komunikaci, roaming, nízká spotřeba energie koncovými zařízeními (výdrž baterie až 10 – 15 let) a také jejich nízká cena. <br />
<br />
Našemu týmu se podařilo okolo testovacícho čipu vybudovat celou hardwarovou platformu tak, že tato může být připojena k senzorickému modulu, a bude možné testovat její stabilitu, pokrytí a náročnost na napájení.<br />
Tato část projektu je již téměř dokončena a nachází se ve stádiu pre-produkčního testování.<br />
<br />
Díky tomu, že se jedná o technologii patentovanou a ke své fuknci využívající produkční komerční frekvence vlastněné společností Vodafone, nebude tato část modulu zařazena v OpenSource verzi projektu SenseNet<br />
<h3>LoraWan</h3>
Nekomerční, OpenSource obdoba NB-IoT sestávající z open hardware i open software, která využívá nekomerční, ale také negarantovaná vysílací pásma pro rádiový přenos.<br />
Modul bude zařazen do OpenSource dokumentace SenseNet a měl by být plně schopen nahradit komerční, patentované řešení.<br />
V součastné době ještě neproběhlo testování v Labce, nicméně hardware senzorů je pro LoraWan nasazení připraven.<br />
<h3>Interní síťová infrastruktura</h3>
Interně bude pro síťování projektu použita standarndní implementace IPv4 a do budoucna IPv6.<br />
Tato část projektu je již hotová v pre-produkčním stadiu, bude vytvořena ještě dokumentace pro jiné než testovací a laboratorní použití.
</body>
</html>
|
#ifndef <API key>
#define <API key>
#include "sudoku_types.h"
#include "cell_listener_if.h"
namespace sudoku_systemc
{
template<unsigned int SIZE>
class <API key>
{
public:
<API key>(const unsigned int & p_sub_x,const unsigned int & p_sub_y,const unsigned int & p_initial_value, cell_listener_if & p_listener);
<API key>(const <API key><SIZE> & p_initial_state,const unsigned int & p_hypothesis_level);
unsigned int get_real_value(const typename sudoku_types<SIZE>::t_data_type & p_value)const;
void <API key>(const typename sudoku_types<SIZE>::t_data_type & p_value);
void <API key>(const typename sudoku_types<SIZE>::t_data_type & p_value);
void <API key>(const typename sudoku_types<SIZE>::t_data_type & p_value);
void <API key>(const typename sudoku_types<SIZE>::t_data_type & p_value);
const typename sudoku_types<SIZE>::<API key> & <API key>(void)const;
const typename sudoku_types<SIZE>::t_data_type make_hypothesis(void);
const typename sudoku_types<SIZE>::t_available_values & <API key>(void)const;
const typename sudoku_types<SIZE>::t_data_type get_remaining_value(void);
// Value management
inline const typename sudoku_types<SIZE>::t_data_type & get_value(void)const;
inline const bool is_value_set(void)const;
void set_value(const typename sudoku_types<SIZE>::t_data_type & p_value);
const unsigned int & <API key>(void)const;
bool is_modified(void)const ;
void notify_listener(void);
private:
void <API key>(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value);
void <API key>(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value);
void <API key>(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value);
void set_available_value(const unsigned int & p_index, bool p_value);
void set_release_value(const unsigned int & p_index, bool p_value);
cell_listener_if & m_listener;
typename sudoku_types<SIZE>::t_group_candidate <API key>[<API key><SIZE>::m_nb_value];
typename sudoku_types<SIZE>::t_group_candidate <API key>[<API key><SIZE>::m_nb_value];
typename sudoku_types<SIZE>::t_group_candidate m_square_candidates[<API key><SIZE>::m_nb_value];
typename sudoku_types<SIZE>::t_available_values m_available_values;
typename sudoku_types<SIZE>::<API key> <API key>;
typename sudoku_types<SIZE>::t_available_values m_values_to_release;
typename sudoku_types<SIZE>::t_data_type m_value;
bool m_value_set;
unsigned int m_hypothesis_level;
bool m_modified;
};
}
#include "<API key>.hpp"
#endif // <API key>
//EOF
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-20 22:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('erudit', '<API key>'),
]
operations = [
migrations.AddField(
model_name='issue',
name='force_free_access',
field=models.BooleanField(default=False, verbose_name='Contraindre en libre accès'),
),
]
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Modules.InstantAction.Views
{
<summary>
InstantActionPage.xaml
</summary>
public partial class InstantActionPage : UserControl
{
public InstantActionPage()
{
InitializeComponent();
}
}
public class <API key> : <API key>
{
public DataTemplate EmptyTemplate { get; set; }
public DataTemplate FileSelectTemplate { get; set; }
public DataTemplate <API key> { get; set; }
public DataTemplate FinishingTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item == null)
{
return EmptyTemplate;
}
else if (item is ViewModels.<API key>)
{
return FileSelectTemplate;
}
else if (item is ViewModels.<API key>)
{
return <API key>;
}
else if (item is ViewModels.<API key>)
{
return FinishingTemplate;
}
return base.SelectTemplate(item, container);
}
}
}
|
package bartburg.nl.backbaseweather.provision.remote.controller;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import bartburg.nl.backbaseweather.AppConstants;
import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController;
import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil;
import static bartburg.nl.backbaseweather.AppConstants.<API key>;
import static bartburg.nl.backbaseweather.AppConstants.<API key>;
public abstract class BaseApiController {
/**
* Do the actual work of requesting data from the server. Note, should not run on main thread.
*
* @param parameters Parameters that will be added to the query string.
* @param onErrorListener Listener that will get called when status code is not 200
* @return The result string or *null* when failed.
*/
@Nullable
public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) {
return get(parameters, onErrorListener, null);
}
/**
* Do the actual work of requesting data from the server. Note, should not run on main thread.
*
* @param parameters Parameters that will be added to the query string.
* @param onErrorListener Listener that will get called when status code is not 200
* @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation).
* @return The result string or *null* when failed.
*/
@Nullable
public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) {
try {
parameters.put("appid", AppConstants.<API key>);
URL url = new URL(<API key> + <API key> + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
if (responseCode != 200 && onErrorListener != null) {
onErrorListener.onError(responseCode, responseMessage);
} else {
return readInputStream(urlConnection);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@NonNull
private String readInputStream(HttpURLConnection urlConnection) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
return sb.toString();
}
public interface OnErrorListener {
void onError(int responseCode, String responseMessage);
}
private String getRelativePath(String customRelativePath) {
if (customRelativePath != null) {
return customRelativePath;
}
Class<? extends BaseApiController> aClass = getClass();
if (aClass.isAnnotationPresent(ApiController.class)) {
Annotation annotation = aClass.getAnnotation(ApiController.class);
ApiController apiController = (ApiController) annotation;
return apiController.relativePath();
}
return "";
}
}
|
package org.cgiar.ccafs.ap.data.dao.mysql;
import org.cgiar.ccafs.ap.data.dao.<API key>;
import org.cgiar.ccafs.utils.db.DAOManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class <API key> implements <API key> {
// Logger
private static Logger LOG = LoggerFactory.getLogger(<API key>.class);
private DAOManager databaseManager;
@Inject
public <API key>(DAOManager databaseManager) {
this.databaseManager = databaseManager;
}
@Override
public Map<String, String> <API key>(int <API key>) {
Map<String, String> <API key> = new HashMap<String, String>();
LOG.debug(">> <API key>( <API key> = {} )", <API key>);
StringBuilder query = new StringBuilder();
query.append("SELECT ipo.* ");
query.append("FROM <API key> as ipo ");
query.append("WHERE ipo.id= ");
query.append(<API key>);
try (Connection con = databaseManager.getConnection()) {
ResultSet rs = databaseManager.makeQuery(query.toString(), con);
if (rs.next()) {
<API key>.put("id", rs.getString("id"));
<API key>.put("project_id", rs.getString("project_id"));
<API key>.put("contribution", rs.getString("contribution"));
<API key>.put("<API key>", rs.getString("<API key>"));
<API key>.put("<API key>", rs.getString("<API key>"));
}
con.close();
} catch (SQLException e) {
LOG.error("Exception arised getting the IP Other Contribution {}.", <API key>, e);
}
LOG.debug("-- <API key>() > Calling method executeQuery to get the results");
return <API key>;
}
@Override
public Map<String, String> <API key>(int projectID) {
LOG.debug(">> <API key> (projectID = {} )", projectID);
Map<String, String> <API key> = new HashMap<String, String>();
StringBuilder query = new StringBuilder();
query.append("SELECT ipo.* ");
query.append("FROM <API key> as ipo ");
query.append("INNER JOIN projects p ON ipo.project_id = p.id ");
query.append("WHERE ipo.project_id= ");
query.append(projectID);
try (Connection con = databaseManager.getConnection()) {
ResultSet rs = databaseManager.makeQuery(query.toString(), con);
if (rs.next()) {
<API key>.put("id", rs.getString("id"));
<API key>.put("project_id", rs.getString("project_id"));
<API key>.put("contribution", rs.getString("contribution"));
<API key>.put("<API key>", rs.getString("<API key>"));
<API key>.put("<API key>", rs.getString("<API key>"));
}
con.close();
} catch (SQLException e) {
LOG.error("Exception arised getting the IP Other Contribution by the projectID {}.", projectID, e);
}
LOG.debug("-- <API key>() : {}", <API key>);
return <API key>;
}
@Override
public int <API key>(int projectID, Map<String, Object> <API key>) {
LOG.debug(">> <API key>(<API key>={})", <API key>);
StringBuilder query = new StringBuilder();
int result = -1;
Object[] values;
if (<API key>.get("id") == null) {
// Insert new IP Other Contribution record
query.append("INSERT INTO <API key> (project_id, contribution, <API key>, ");
query.append("<API key>, created_by, modified_by, <API key>) ");
query.append("VALUES (?,?,?,?,?,?,?) ");
values = new Object[7];
values[0] = projectID;
values[1] = <API key>.get("contribution");
values[2] = <API key>.get("<API key>");
values[3] = <API key>.get("<API key>");
values[4] = <API key>.get("user_id");
values[5] = <API key>.get("user_id");
values[6] = <API key>.get("justification");
result = databaseManager.saveData(query.toString(), values);
if (result <= 0) {
LOG.error("A problem happened trying to add a new IP Other Contribution with project id={}", projectID);
return -1;
}
} else {
// update IP Other Contribution record
query.append("UPDATE <API key> SET project_id = ?, contribution = ?, ");
query.append("<API key> = ?, <API key> = ?, modified_by = ?, ");
query.append("<API key> = ? WHERE id = ? ");
values = new Object[7];
values[0] = projectID;
values[1] = <API key>.get("contribution");
values[2] = <API key>.get("<API key>");
values[3] = <API key>.get("<API key>");
values[4] = <API key>.get("user_id");
values[5] = <API key>.get("justification");
values[6] = <API key>.get("id");
result = databaseManager.saveData(query.toString(), values);
if (result == -1) {
LOG.error("A problem happened trying to update the IP Other Contribution identified with the id = {}",
<API key>.get("id"));
return -1;
}
}
LOG.debug("<< <API key>():{}", result);
return result;
}
}
|
// ReSharper disable CheckNamespace
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var people = new Dictionary<string, Person>();
string input;
while ((input = Console.ReadLine()) != "End")
{
var split = input.Split();
string name = split[0];
if (!people.ContainsKey(name))
{
people.Add(name, new Person());
}
Person person = people[name];
string infoType = split[1];
if (infoType == "company")
{
person.Company = new Company(split[2], split[3], double.Parse(split[4]));
}
else if (infoType == "pokemon")
{
person.Pokemon.Add(new Pokemon(split[2], split[3]));
}
else if (infoType == "parents")
{
person.Parents.Add(new Parent(split[2], split[3]));
}
else if (infoType == "children")
{
person.Children.Add(new Child(split[2], split[3]));
}
else if (infoType == "car")
{
person.Car = new Car(split[2], int.Parse(split[3]));
}
}
string nameToPrint = Console.ReadLine();
Console.WriteLine(nameToPrint);
people[nameToPrint].PrintInformation();
}
}
|
<?php
/** Zend_Form_Exception */
require_once 'Zend/Form/Exception.php';
class <API key> extends Zend_Form_Exception
{
}
|
// +build linux
package subsystem
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
)
type PlatformHeader LinuxHeader
func NewPlatformHeader() *LinuxHeader {
header := new(LinuxHeader)
header.Devices = make(map[string]LinuxDevice)
header.getDevsParts()
return header
}
func (header *LinuxHeader) getDevsParts() {
f, err := os.Open("/proc/diskstats")
if err != nil {
panic(err)
}
defer f.Close()
scan := bufio.NewScanner(f)
for scan.Scan() {
var major, minor int
var name string
c, err := fmt.Sscanf(scan.Text(), "%d %d %s", &major, &minor, &name)
if err != nil {
panic(err)
}
if c != 3 {
continue
}
header.DevsParts = append(header.DevsParts, name)
if isDevice(name) {
header.Devices[name] = LinuxDevice{
name, getPartitions(name),
}
}
}
}
func isDevice(name string) bool {
stat, err := os.Stat(fmt.Sprintf("/sys/block/%s", name))
if err == nil && stat.IsDir() {
return true
}
return false
}
func getPartitions(name string) []string {
var dir *os.File
var fis []os.FileInfo
var err error
var parts = []string{}
dir, err = os.Open(fmt.Sprintf("/sys/block/%s", name))
if err != nil {
panic(err)
}
fis, err = dir.Readdir(0)
if err != nil {
panic(err)
}
for _, fi := range fis {
_, err := os.Stat(fmt.Sprintf("/sys/block/%s/%s/stat", name, fi.Name()))
if err == nil {
// partition exists
parts = append(parts, fi.Name())
}
}
return parts
}
func ReadCpuStat(record *StatRecord) error {
f, ferr := os.Open("/proc/stat")
if ferr != nil {
return ferr
}
defer f.Close()
if record.Cpu == nil {
num_core := 0
out, err := exec.Command("nproc", "--all").Output()
out_str := strings.TrimSpace(string(out))
if err == nil {
num_core, err = strconv.Atoi(out_str)
if err != nil {
num_core = 0
}
}
if num_core == 0 {
num_core = runtime.NumCPU()
}
record.Cpu = NewCpuStat(num_core)
} else {
record.Cpu.Clear()
}
if record.Proc == nil {
record.Proc = NewProcStat()
} else {
record.Proc.Clear()
}
scan := bufio.NewScanner(f)
for scan.Scan() {
var err error
var cpu string
line := scan.Text()
if line[0:4] == "cpu " {
// Linux 2.6.33 or later
_, err = fmt.Sscanf(line,
"%s %d %d %d %d %d %d %d %d %d %d",
&cpu,
&record.Cpu.All.User,
&record.Cpu.All.Nice,
&record.Cpu.All.Sys,
&record.Cpu.All.Idle,
&record.Cpu.All.Iowait,
&record.Cpu.All.Hardirq,
&record.Cpu.All.Softirq,
&record.Cpu.All.Steal,
&record.Cpu.All.Guest,
&record.Cpu.All.GuestNice)
if err == io.EOF {
// Linux 2.6.24 or later
_, err = fmt.Sscanf(line,
"%s %d %d %d %d %d %d %d %d %d",
&cpu,
&record.Cpu.All.User,
&record.Cpu.All.Nice,
&record.Cpu.All.Sys,
&record.Cpu.All.Idle,
&record.Cpu.All.Iowait,
&record.Cpu.All.Hardirq,
&record.Cpu.All.Softirq,
&record.Cpu.All.Steal,
&record.Cpu.All.Guest)
record.Cpu.All.GuestNice = 0
}
if err != nil {
panic(err)
}
} else if line[0:3] == "cpu" {
var n_core int
var core_stat *CpuCoreStat
// assume n_core < 10000
_, err = fmt.Sscanf(line[3:7], "%d", &n_core)
if err != nil {
panic(err)
}
core_stat = &record.Cpu.CoreStats[n_core]
// Linux 2.6.33 or later
_, err = fmt.Sscanf(line,
"%s %d %d %d %d %d %d %d %d %d %d",
&cpu,
&core_stat.User,
&core_stat.Nice,
&core_stat.Sys,
&core_stat.Idle,
&core_stat.Iowait,
&core_stat.Hardirq,
&core_stat.Softirq,
&core_stat.Steal,
&core_stat.Guest,
&core_stat.GuestNice)
if err == io.EOF {
// Linux 2.6.24 or later
_, err = fmt.Sscanf(line,
"%s %d %d %d %d %d %d %d %d %d",
&cpu,
&core_stat.User,
&core_stat.Nice,
&core_stat.Sys,
&core_stat.Idle,
&core_stat.Iowait,
&core_stat.Hardirq,
&core_stat.Softirq,
&core_stat.Steal,
&core_stat.Guest)
}
if err != nil {
panic(err)
}
} else if line[0:5] == "ctxt " {
_, err = fmt.Sscanf(line[4:], "%d", &record.Proc.ContextSwitch)
if err != nil {
panic(err)
}
} else if line[0:10] == "processes " {
_, err = fmt.Sscanf(line[10:], "%d", &record.Proc.Fork)
if err != nil {
panic(err)
}
}
}
return nil
}
func <API key>(line string, num_core int) (*InterruptStatEntry, error) {
entry := new(InterruptStatEntry)
entry.NumCore = num_core
entry.IntrCounts = make([]int, num_core)
tokens := strings.Fields(line)
idx := 0
tok := tokens[0]
tok = strings.TrimRight(tok, ":")
if irqno, err := strconv.Atoi(tok); err == nil {
entry.IrqNo = irqno
entry.IrqType = ""
} else {
entry.IrqNo = -1
entry.IrqType = tok
}
for idx := 1; idx < num_core+1; idx += 1 {
var c int
var err error
if idx >= len(tokens) {
break
}
tok = tokens[idx]
if c, err = strconv.Atoi(tok); err != nil {
return nil, errors.New("Invalid string for IntrCounts element: " + tok)
}
entry.IntrCounts[idx-1] = c
}
idx = num_core + 1
if idx < len(tokens) {
entry.Descr = strings.Join(tokens[idx:], " ")
} else {
entry.Descr = ""
}
return entry, nil
}
func ReadInterruptStat(record *StatRecord) error {
intr_stat := NewInterruptStat()
if record == nil {
return errors.New("Valid *StatRecord is required.")
}
f, err := os.Open("/proc/interrupts")
if err != nil {
panic(err)
}
defer f.Close()
scan := bufio.NewScanner(f)
if !scan.Scan() {
return errors.New("/proc/interrupts seems to be empty")
}
cores := strings.Fields(scan.Text())
num_core := len(cores)
for scan.Scan() {
entry, err := <API key>(scan.Text(), num_core)
if err != nil {
return err
}
intr_stat.Entries = append(intr_stat.Entries, entry)
intr_stat.NumEntries += 1
}
record.Interrupt = intr_stat
return nil
}
func ReadDiskStats(record *StatRecord, targets *map[string]bool) error {
if record == nil {
return errors.New("Valid *StatRecord is required.")
}
f, ferr := os.Open("/proc/diskstats")
if ferr != nil {
panic(ferr)
}
defer f.Close()
if record.Disk == nil {
record.Disk = NewDiskStat()
} else {
record.Disk.Clear()
}
scan := bufio.NewScanner(f)
var num_items int
var err error
for scan.Scan() {
var rdmerge_or_rdsec int64
var rdsec_or_wrios int64
var rdticks_or_wrsec int64
line := scan.Text()
entry := NewDiskStatEntry()
num_items, err = fmt.Sscanf(line,
"%d %d %s %d %d %d %d %d %d %d %d %d %d %d",
&entry.Major, &entry.Minor, &entry.Name,
&entry.RdIos, &rdmerge_or_rdsec, &rdsec_or_wrios, &rdticks_or_wrsec,
&entry.WrIos, &entry.WrMerges, &entry.WrSectors, &entry.WrTicks,
&entry.IosPgr, &entry.TotalTicks, &entry.ReqTicks)
if err != nil {
return err
}
if num_items == 14 {
entry.RdMerges = rdmerge_or_rdsec
entry.RdSectors = rdsec_or_wrios
entry.RdTicks = rdticks_or_wrsec
} else if num_items == 7 {
entry.RdSectors = rdmerge_or_rdsec
entry.WrIos = rdsec_or_wrios
entry.WrSectors = rdticks_or_wrsec
} else {
continue
}
if entry.RdIos == 0 && entry.WrIos == 0 {
continue
}
if targets != nil {
if _, ok := (*targets)[entry.Name]; !ok {
// device not in targets
continue
}
} else {
if !isDevice(entry.Name) {
continue
}
}
record.Disk.Entries = append(record.Disk.Entries, entry)
}
return nil
}
func ReadNetStat(record *StatRecord) error {
if record == nil {
return errors.New("Valid *StatRecord is required.")
}
net_stat := NewNetStat()
f, err := os.Open("/proc/net/dev")
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
switch {
case line[0:7] == "Inter-|":
continue
case line[0:7] == " face |":
continue
}
line = strings.Replace(line, ":", " ", -1)
e := NewNetStatEntry()
var devname string
n, err := fmt.Sscanf(line,
"%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &devname,
&e.RxBytes, &e.RxPackets, &e.RxErrors, &e.RxDrops,
&e.RxFifo, &e.RxFrame, &e.RxCompressed, &e.RxMulticast,
&e.TxBytes, &e.TxPackets, &e.TxErrors, &e.TxDrops,
&e.TxFifo, &e.TxFrame, &e.TxCompressed, &e.TxMulticast)
if err == io.EOF {
break
} else if err != nil {
return err
}
if n != 17 {
continue
}
// trim trailing ":" from devname
if devname[len(devname)-1] == ':' {
devname = devname[0 : len(devname)-1]
}
e.Name = devname
net_stat.Entries = append(net_stat.Entries, e)
}
record.Net = net_stat
return nil
}
func ReadMemStat(record *StatRecord) error {
if record == nil {
return errors.New("Valid *StatRecord is required.")
}
mem_stat := NewMemStat()
f, err := os.Open("/proc/meminfo")
if err != nil {
return err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
var key string
var val int64
line := scanner.Text()
n, err := fmt.Sscanf(line, "%s %d", &key, &val)
if err == io.EOF {
break
} else if err != nil {
return err
}
if n != 2 {
continue
}
switch key {
case "HugePages_Surp:":
mem_stat.HugePages_Surp = val
case "HugePages_Rsvd:":
mem_stat.HugePages_Rsvd = val
case "HugePages_Free:":
mem_stat.HugePages_Free = val
case "HugePages_Total:":
mem_stat.HugePages_Total = val
case "Hugepagesize:":
mem_stat.Hugepagesize = val
case "AnonHugePages:":
mem_stat.AnonHugePages = val
case "Committed_AS:":
mem_stat.Committed_AS = val
case "CommitLimit:":
mem_stat.CommitLimit = val
case "Bounce:":
mem_stat.Bounce = val
case "NFS_Unstable:":
mem_stat.NFS_Unstable = val
case "Shmem:":
mem_stat.Shmem = val
case "Slab:":
mem_stat.Slab = val
case "SReclaimable:":
mem_stat.SReclaimable = val
case "SUnreclaim:":
mem_stat.SUnreclaim = val
case "KernelStack:":
mem_stat.KernelStack = val
case "PageTables:":
mem_stat.PageTables = val
case "Mapped:":
mem_stat.Mapped = val
case "AnonPages:":
mem_stat.AnonPages = val
case "Writeback:":
mem_stat.Writeback = val
case "Dirty:":
mem_stat.Dirty = val
case "SwapFree:":
mem_stat.SwapFree = val
case "SwapTotal:":
mem_stat.SwapTotal = val
case "Inactive:":
mem_stat.Inactive = val
case "Active:":
mem_stat.Active = val
case "SwapCached:":
mem_stat.SwapCached = val
case "Cached:":
mem_stat.Cached = val
case "Buffers:":
mem_stat.Buffers = val
case "MemFree:":
mem_stat.MemFree = val
case "MemTotal:":
mem_stat.MemTotal = val
}
}
record.Mem = mem_stat
return nil
}
|
#ifndef _TCA6416_KEYS_H
#define _TCA6416_KEYS_H
#include <linux/types.h>
struct tca6416_button
{
/* Configuration parameters */
int code; /* input event code (KEY_*, SW_*) */
int active_low;
int type; /* input event type (EV_KEY, EV_SW) */
};
struct <API key>
{
struct tca6416_button *buttons;
int nbuttons;
unsigned int rep: 1; /* enable input subsystem auto repeat */
uint16_t pinmask;
uint16_t invert;
int irq_is_gpio;
int use_polling; /* use polling if Interrupt is not connected*/
};
#endif
|
// item //
datablock ItemData(YoyoItem)
{
category = "Weapon"; // Mission editor category
className = "Weapon"; // For inventory system
// Basic Item Properties
shapeFile = "./Yoyo.dts";
rotate = false;
mass = 1;
density = 0.2;
elasticity = 0.2;
friction = 0.6;
emap = true;
//gui stuff
uiName = "Yo-yo";
iconName = "./icon_Yoyo";
doColorShift = true;
colorShiftColor = "0 1 1 1.000";
// Dynamic properties defined by the scripts
image = YoyoImage;
canDrop = true;
};
//weapon image//
datablock ShapeBaseImageData(YoyoImage)
{
// Basic Item properties
shapeFile = "./Yoyo.dts";
emap = true;
// Specify mount point & offset for 3rd person, and eye offset
// for first person rendering.
mountPoint = 0;
offset = "0 0 0";
eyeOffset = 0; //"0.7 1.2 -0.5";
rotation = eulerToMatrix( "0 0 0" );
// When firing from a point offset from the eye, muzzle correction
// will adjust the muzzle vector to point to the eye LOS point.
// Since this weapon doesn't actually fire from the muzzle point,
// we need to turn this off.
correctMuzzleVector = true;
// Add the WeaponImage namespace as a parent, WeaponImage namespace
// provides some hooks into the inventory system.
className = "WeaponImage";
// Projectile && Ammo.
item = YoyoItem;
projectile = emptyProjectile;
projectileType = Projectile;
ammo = " ";
//melee particles shoot from eye node for consistancy
melee = false;
//raise your arm up or not
armReady = true;
doColorShift = true;
colorShiftColor = YoyoItem.colorShiftColor;//"0.400 0.196 0 1.000";
//casing = " ";
// Images have a state system which controls how the animations
// are run, which sounds are played, script callbacks, etc. This
// state system is downloaded to the client so that clients can
// predict state changes and animate accordingly. The following
// system supports basic ready->fire->reload transitions as
// well as a no-ammo->dryfire idle state.
// Initial start up state
stateName[0] = "Activate";
stateTimeoutValue[0] = 0.15;
<API key>[0] = "Ready";
stateSound[0] = weaponSwitchSound;
stateName[1] = "Ready";
<API key>[1] = "Fire";
<API key>[1] = true;
stateSequence[1] = "Ready";
stateName[2] = "Fire";
stateTimeoutValue[2] = 1.1;
<API key>[2] = "Reload";
stateSequence[2] = "fire";
stateScript[2] = "OnFire";
stateName[3] = "Reload";
stateSequence[3] = "Reload";
<API key>[3] = "Ready";
stateSequence[3] = "Ready";
};
|
#include "services/video_capture/<API key>.h"
#include "services/video_capture/<API key>.h"
namespace video_capture {
<API key>::<API key>(
mojom::MockMediaDevicePtr* device)
: device_(device) {}
<API key>::~<API key>() = default;
void <API key>::AllocateAndStart(
const media::VideoCaptureParams& params,
std::unique_ptr<Client> client) {
mojom::MockDeviceClientPtr client_proxy;
auto client_request = mojo::GetProxy(&client_proxy);
mojo::MakeStrongBinding(
base::MakeUnique<<API key>>(std::move(client)),
std::move(client_request));
(*device_)->AllocateAndStart(std::move(client_proxy));
}
void <API key>::RequestRefreshFrame() {}
void <API key>::StopAndDeAllocate() {
(*device_)->StopAndDeAllocate();
}
void <API key>::<API key>(
<API key> callback) {}
void <API key>::SetPhotoOptions(
media::mojom::PhotoSettingsPtr settings,
<API key> callback) {}
void <API key>::TakePhoto(TakePhotoCallback callback) {}
} // namespace video_capture
|
package com.ocams.andre;
import javax.swing.table.DefaultTableModel;
public class MasterJurnal extends javax.swing.JFrame {
public MasterJurnal() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jTextField4 = new javax.swing.JTextField();
<API key>(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Kode:");
jLabel2.setText("Perkiraan:");
jLabel3.setText("Nomor Referensi:");
jLabel4.setText("Posisi:");
jLabel5.setText("Harga:");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
<API key>(evt);
}
});
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("Debit");
buttonGroup1.add(jRadioButton2);
jRadioButton2.setText("Kredit");
jLabel6.setText("User:");
jLabel7.setText("NamaUser");
jButton1.setText("Logout");
jButton2.setText("Insert");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
<API key>(evt);
}
});
jButton3.setText("Update");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
<API key>(evt);
}
});
jButton4.setText("Delete");
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
<API key>(evt);
}
});
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Kode", "Perkiraan", "No. Ref.", "Posisi", "Harga"
}
));
jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable2MouseClicked(evt);
}
});
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.<API key>()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7))
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)))
.addGroup(layout.<API key>()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.<API key>()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.<API key>()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton2))
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(jLabel7))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void <API key>(java.awt.event.MouseEvent evt) {//GEN-FIRST:<API key>
String kode = jTextField1.getText();
String perkiraan = jTextField2.getText();
String noref = jTextField3.getText();
String posisi = "";
if (jRadioButton1.isSelected() == true){
posisi = "Debit";
}else if (jRadioButton2.isSelected() == true){
posisi = "Kredit";
}
String harga = jTextField4.getText();
Object[] row = {kode,perkiraan,noref,posisi,harga};
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.addRow(row);
}//GEN-LAST:<API key>
private void <API key>(java.awt.event.MouseEvent evt) {//GEN-FIRST:<API key>
int baris = jTable2.rowAtPoint(evt.getPoint());
String kode = jTextField1.getText();
String perkiraan = jTextField2.getText();
String noref = jTextField3.getText();
String posisi = "";
if (jRadioButton1.isSelected() == true){
posisi = "Debit";
}else if (jRadioButton2.isSelected() == true){
posisi = "Kredit";
}
String harga = jTextField4.getText();
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.setValueAt(kode, baris, 0);
model.setValueAt(perkiraan, baris, 1);
model.setValueAt(noref, baris, 2);
model.setValueAt(posisi, baris, 3);
model.setValueAt(harga, baris, 4);
}//GEN-LAST:<API key>
private void <API key>(java.awt.event.MouseEvent evt) {//GEN-FIRST:<API key>
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.removeRow(jTable2.rowAtPoint(evt.getPoint()));
}//GEN-LAST:<API key>
private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:<API key>
int baris = jTable2.rowAtPoint(evt.getPoint());
jTextField1.setText(String.valueOf(jTable2.getValueAt(baris, 0)));
jTextField2.setText(String.valueOf(jTable2.getValueAt(baris, 1)));
jTextField3.setText(String.valueOf(jTable2.getValueAt(baris,2)));
String posisi = String.valueOf(jTable2.getValueAt(baris, 3));
if ("debit".equalsIgnoreCase(posisi)){
jRadioButton1.setSelected(true);
}else if ("kredit".equalsIgnoreCase(posisi)){
jRadioButton2.setSelected(true);
}
jTextField4.setText(String.valueOf(jTable2.getValueAt(baris, 4)));
}//GEN-LAST:<API key>
private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key>
// TODO add your handling code here:
}//GEN-LAST:<API key>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.<API key>()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.<API key> ex) {
java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MasterJurnal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables
}
|
// For more information, see LICENCE in the main folder
#ifndef _DUEL_H_
#define _DUEL_H_
struct duel
{
int members_count;
int invites_count;
int max_players_limit;
};
#define MAX_DUEL 1024
extern struct duel duel_list[MAX_DUEL];
extern int duel_count;
//Duel functions // [LuzZza]
int duel_create (struct map_session_data *sd, const unsigned int maxpl);
int duel_invite (const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd);
int duel_accept (const unsigned int did, struct map_session_data *sd);
int duel_reject (const unsigned int did, struct map_session_data *sd);
int duel_leave (const unsigned int did, struct map_session_data *sd);
int duel_showinfo (const unsigned int did, struct map_session_data *sd);
int duel_checktime (struct map_session_data *sd);
int do_init_duel (void);
void do_final_duel (void);
#endif /* _DUEL_H_ */
|
/*
* generated by Xtext
*/
package org.eclectic.frontend.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.eclectic.frontend.services.TaoGrammarAccess;
public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private TaoGrammarAccess grammarAccess;
@Override
protected void <API key>(XtextTokenStream tokenStream) {
tokenStream.<API key>("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) {
return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "TaoTransformation";
}
public TaoGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(TaoGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
|
<?php
require "common.inc.php";
verifica_seguranca($_SESSION[PAP_RESP_MUTIRAO]);
top();
?>
<?php
$action = request_get("action",-1);
if($action==-1) $action=ACAO_EXIBIR_LEITURA;
$est_cha=request_get("est_cha",-1);
if($est_cha==-1)
{
if(isset($_SESSION['cha_id_pref']))
{
$est_cha=$_SESSION['cha_id_pref'];
}
}
$_SESSION['cha_id_pref']=$est_cha;
if ($est_cha<>-1)
{
$sql = "SELECT prodt_nome, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega, cha_taxa_percentual, ((<API key> is null) OR (<API key> > now() ) ) as cha_dentro_prazo, date_format(<API key>,'%d/%m/%Y %H:%i') <API key> ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE cha_id = " . prep_para_bd($est_cha);
$res = executa_sql($sql);
if ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
$prodt_nome = $row["prodt_nome"];
$cha_dt_entrega = $row["cha_dt_entrega"];
$cha_taxa_percentual = $row["cha_taxa_percentual"];
$<API key> = $row["<API key>"];
$cha_dentro_prazo = $row["cha_dentro_prazo"];
}
}
if ($action == ACAO_SALVAR)
{
// salva disponibilidade de produtos
$n = isset($_REQUEST['est_prod']) ? sizeof($_REQUEST['est_prod']) : 0;
for($i=0;$i<$n;$i++)
{
$est_cha_bd = prep_para_bd($est_cha);
$qtde_antes_bd = $_REQUEST['est_prod_qtde_antes'][$i] <>"" ? prep_para_bd(<API key>($_REQUEST['est_prod_qtde_antes'][$i])) : 'NULL';
$obs_antes_bd = $_REQUEST['est_obs_antes'][$i] <>"" ? prep_para_bd($_REQUEST['est_obs_antes'][$i]) : 'NULL';
$sql = "INSERT INTO estoque (est_cha, est_prod, est_prod_qtde_antes, est_obs_antes ) ";
$sql.= "VALUES ( " . $est_cha_bd . " ," . prep_para_bd($_REQUEST['est_prod'][$i]) . ", ";
$sql.= $qtde_antes_bd . ", " . $obs_antes_bd . ") ";
$sql.= "ON DUPLICATE KEY UPDATE ";
$sql.= " est_prod_qtde_antes = " . $qtde_antes_bd . ", ";
$sql.= " est_obs_antes = " . $obs_antes_bd . " ";
$res = executa_sql($sql);
}
if($res)
{
$action=ACAO_EXIBIR_LEITURA;
<API key>(MSG_TIPO_SUCESSO,"As informações de estoque relacionado à chamada " . $cha_dt_entrega . " foram salvas com sucesso.");
}
else
{
<API key>(MSG_TIPO_ERRO,"Erro ao tentar salvar informações de estoque da chamada para o dia " . $cha_dt_entrega . ".");
}
<API key>();
}
if ($action == ACAO_EXIBIR_LEITURA || $action == ACAO_EXIBIR_EDICAO )
{
}
?>
<ul class="nav nav-tabs">
<li><a href="mutirao.php">Mutirão</a></li>
<li class="active"><a href="
<li><a href="recebimento.php"><i class="glyphicon glyphicon-road"></i> Recebimento</a></li>
<li><a href="<API key>.php"><i class="glyphicon <API key>"></i> Distribuição</a></li>
<li><a href="estoque_pos.php"><i class="glyphicon glyphicon-bed"></i> Estoque Pós-Mutirão</a></li>
<li><a href="<API key>.php"><i class="glyphicon glyphicon-eye-open"></i> Divergências</a></li>
</ul>
<br>
<div class="panel panel-default">
<div class="panel-heading">
<strong>Estoque Pré-Mutirão</strong>
</div>
<?php
if($action==ACAO_EXIBIR_LEITURA)
{
?>
<div class="panel-body">
<form class="form-inline" method="get" name="frm_filtro" id="frm_filtro">
<?php
?>
<fieldset>
<div class="form-group">
<label for="est_cha">Chamada: </label>
<select name="est_cha" id="est_cha" onchange="javascript:frm_filtro.submit();" class="form-control">
<option value="-1">SELECIONE</option>
<?php
$sql = "SELECT cha_id, prodt_nome, cha_dt_entrega <API key>, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE prodt_mutirao = '1' ";
$sql.= "ORDER BY <API key> DESC LIMIT 10";
$res = executa_sql($sql);
if($res)
{
$achou=false;
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
echo("<option value='" . $row['cha_id'] . "'");
if($row['cha_id']==$est_cha)
{
echo(" selected");
$achou=true;
}
echo (">" . $row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>");
}
if($est_cha!=-1 && !$achou)
{
$sql = "SELECT cha_id, prodt_nome, cha_dt_entrega <API key>, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE cha_id = " . prep_para_bd($est_cha);
$res2 = executa_sql($sql);
$row = mysqli_fetch_array($res2,MYSQLI_ASSOC);
if($row)
{
echo("<option value='" . $row['cha_id'] . "' selected>");
echo ($row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>");
}
}
}
?>
</select>
<?php
if($est_cha!=-1)
{
?>
<label for="<API key>">Prazo para Edição: </label> <?php echo($<API key>?$<API key>:"ainda não configurado"); ?>
<?php
if(!$cha_dentro_prazo)
{
echo("<span class='alert alert-danger'>(encerrado)</span>");
}
}
?>
</div>
</fieldset>
</form>
</div>
<?php
if($est_cha!=-1)
{
$sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes <API key>, ";
$sql.= "estoque.est_obs_antes est_atual_obs_antes, ";
$sql.= "estoque_anterior.<API key> <API key>, prod_unidade, ";
$sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos ";
$sql.= "LEFT JOIN produtos on chaprod_prod = prod_id ";
$sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id ";
$sql.= "LEFT JOIN fornecedores on prod_forn = forn_id ";
$sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod ";
$sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(<API key>($est_cha)) . " ";
$sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() ";
$sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND <API key> > 0 ";
$sql.= " AND (estoque.est_prod_qtde_antes >0 OR estoque_anterior.<API key> > 0 OR estoque.est_obs_antes IS NOT NULL ) ";
$sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade ";
$res = executa_sql($sql);
if($res && mysqli_num_rows($res)==0)
{
?>
<div class="panel-body">
<!
<button type="button" class="btn btn-default btn-enviando" data-loading-text="importando..." onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA);?>&est_cha=<?php echo($est_cha); ?>&importar=sim'">
<i class="icon glyphicon <API key>"></i> importar estoque do último mutirão
</button>
<br /><div class='well'> Sem produtos em estoque. Se de fato houver, clique em editar para registrar. </div><br />
</div>
<?php
}
else if($res)
{
?>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th colspan="3">Informações de Estoque Pré-Mutirão da Entrega de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?></th>
<th colspan="2">
<?php
if($cha_dentro_prazo)
{
?>
<a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&cha_id=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit"></i> editar</a>
<?php
}
else
{
echo(" ");
}
?>
</th>
</tr>
</thead>
<tbody>
<?php
$ultimo_forn = "";
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
if($row["forn_nome_curto"]!=$ultimo_forn)
{
$ultimo_forn = $row["forn_nome_curto"];
?>
<tr>
<th>
<?php echo($row["forn_nome_curto"]);
<API key>("",$row["forn_nome_completo"]);
?>
</th>
<th>Unidade</th>
<th>Estoque Pré-Mutirão Esperado<?php <API key>("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th>
<th>Estoque Pré-Mutirão Real</th>
<th>Observação</th>
</tr>
<?php
}
?>
<tr>
<td><?php echo($row["prod_nome"]);?></td>
<td><?php echo($row["prod_unidade"]); ?></td>
<td>
<?php if($row["<API key>"]) <API key>($row["<API key>"]); else echo(" "); ?>
</td>
<td <?php if($row["<API key>"] != $row["<API key>"]) echo(" class='" . (($row["est_atual_obs_antes"]) ? "info" : "danger") . "'");?>>
<?php if($row["<API key>"]) <API key>($row["<API key>"]); else echo(" "); ?>
</td>
<td>
<?php echo( ($row["est_atual_obs_antes"]) ? $row["est_atual_obs_antes"] : " ") ; ?>
</td>
</tr>
<?php
}
echo("</tbody></table>");
}
?>
</div>
<?php
if($est_cha!=-1 && $cha_dentro_prazo)
{
?>
<div align="right">
<a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&est_cha=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit glyphicon-white"></i> editar</a>
</div>
<?php
}
} // fim if est_cha !=-1
?>
<?php
}
else
{
?>
<form class="form-horizontal" method="post">
<div class="panel-body">
<div align="right">
<button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque...">
<i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button>
<button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button>
</div>
</div>
<fieldset>
<input type="hidden" name="est_cha" value="<?php echo($est_cha); ?>" />
<input type="hidden" name="action" value="<?php echo(ACAO_SALVAR); ?>" />
<div class="form-group">
<div class="container">
<?php
$sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes <API key>, ";
$sql.= "estoque.est_obs_antes est_atual_obs_antes, ";
$sql.= "estoque_anterior.<API key> <API key>, prod_unidade, ";
$sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos ";
$sql.= "LEFT JOIN produtos on chaprod_prod = prod_id ";
$sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id ";
$sql.= "LEFT JOIN fornecedores on prod_forn = forn_id ";
$sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod ";
$sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(<API key>($est_cha)) . " ";
$sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() ";
$sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND <API key> > 0 ";
$sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade ";
$res = executa_sql($sql);
if($res)
{
?>
<table class='table table-striped table-bordered table-condensed table-hover'>
<thead>
<tr>
<th colspan="5">
Informações de Estoque Pré-Mutirão relacionado à chamada de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?>
</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td><td> </td>
<td colspan="2">
<button type="button" class="btn btn-info" name="<API key>" id="<API key>" onclick="javascript:replicaDados('replica-origem','replica-destino');">
<i class="glyphicon glyphicon-paste"></i> replicar do estoque esperado
</button>
</td>
<td> </td>
</tr>
<?php
$ultimo_forn = "";
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
if($row["forn_nome_curto"]!=$ultimo_forn)
{
$ultimo_forn = $row["forn_nome_curto"];
?>
<tr>
<th>
<?php echo($row["forn_nome_curto"]);
<API key>("",$row["forn_nome_completo"]);
?>
</th>
<th>Unidade</th>
<th>Estoque Pré-Mutirão Esperado<?php <API key>("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th>
<th>Estoque Pré-Mutirão Real</th>
<th>Observação</th>
</tr>
<?php
}
?>
<tr>
<input type="hidden" name="est_prod[]" value="<?php echo($row["prod_id"]); ?>"/>
<td><?php echo($row["prod_nome"]);?></td>
<td><?php echo($row["prod_unidade"]); ?></td>
<td style="text-align:center">
<input type="hidden" name="<API key>[]" class="replica-origem" value="<?php if($row["<API key>"]) <API key>($row["<API key>"]); ?>">
<?php if($row["<API key>"]) <API key>($row["<API key>"],"0"); ?>
</td>
<td>
<input type="text" class="replica-destino form-control propaga-colar numero-positivo" style="font-size:18px; text-align:center;" value="<?php if($row["<API key>"]) <API key>($row["<API key>"],"0"); ?>" name="est_prod_qtde_antes[]" id="<API key><?php echo($row["prod_id"]); ?>"/>
</td>
<td>
<input type="text" class="form-control" value="<?php if($row["est_atual_obs_antes"]) echo($row["est_atual_obs_antes"]); ?>" name="est_obs_antes[]" id="est_obs_antes_<?php echo($row["prod_id"]); ?>"/>
</td>
</tr>
<?php
}
echo("</tbody></table>");
}
?>
</div>
</div>
<div align="right">
<button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque...">
<i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button>
<button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button>
</div>
</fieldset>
</form>
<?php
}
footer();
?>
|
jQuery(document).ready(function($) {
$('#slide-left').flexslider({
animation: "slide",
controlNav: "thumbnails",
start: function(slider) {
$('ol.flex-control-thumbs li img.flex-active').parent('li').addClass('active');
}
});
});
jQuery(document).ready(function($) {
$('#slide').flexslider({
animation: "slide",
controlNav: false,
directionNav: true
});
});
|
#include "converter_sosi2tsv.h"
void sosicon::ConverterSosi2tsv::
run( bool* ) {
}
|
use crate::cube::Cube;
use glium;
use glium::{Display, Program, Surface, implement_vertex};
use glium::index::{IndexBuffer, PrimitiveType};
use std::rc::Rc;
pub fn solid_fill_program(display: &Display) -> Program {
let vertex_shader_src = include_str!("shaders/solid.vert");
let fragment_shader_src = include_str!("shaders/solid.frag");
Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap()
}
#[derive(Copy, Clone)]
struct Vertex { position: [f32; 3] }
implement_vertex!(Vertex, position);
pub struct BoundingBox {
vertexes: glium::VertexBuffer<Vertex>,
program: Rc<Program>,
indices: IndexBuffer<u16>,
}
impl BoundingBox {
pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox {
let vertex_data = [
Vertex { position: [c.xmin, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymin, c.zmax] },
Vertex { position: [c.xmax, c.ymin, c.zmax] },
Vertex { position: [c.xmax, c.ymax, c.zmax] },
Vertex { position: [c.xmin, c.ymax, c.zmax] },
];
const INDICES: &[u16] = &[0, 1, 1, 2, 2, 3, 3, 0, // front
4, 5, 5, 6, 6, 7, 7, 4, // back
0, 4, 1, 5, 2, 6, 3, 7]; // sides
BoundingBox {
vertexes: glium::VertexBuffer::new(display, &vertex_data).unwrap(),
program: program,
indices: IndexBuffer::new(display, PrimitiveType::LinesList, INDICES).unwrap(),
}
}
pub fn draw<U>(&self, frame: &mut glium::Frame,
uniforms: &U) where U: glium::uniforms::Uniforms {
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
..Default::default()
},
blend: glium::Blend::alpha_blending(),
..Default::default()
};
frame.draw(&self.vertexes, &self.indices, &self.program, uniforms, ¶ms).unwrap();
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace DrakSolz.Projectiles {
public class ChickenEgg : ModProjectile {
public override string Texture { get { return "Terraria/Projectile_318"; } }
public override void SetStaticDefaults() {
DisplayName.SetDefault("Chicken Egg");
}
public override void SetDefaults() {
projectile.CloneDefaults(ProjectileID.RottenEgg);
projectile.aiStyle = 2;
projectile.friendly = false;
projectile.hostile = true;
projectile.penetrate = -1;
projectile.timeLeft = 600;
}
public override bool TileCollideStyle(ref int width, ref int height, ref bool fallThrough) {
width = 5;
height = 5;
return true;
}
public override void Kill(int timeLeft) {
Utils.PoofOfSmoke(projectile.Center);
NPC.NewNPC((int) projectile.Center.X, (int) projectile.Center.Y, ModContent.NPCType<NPCs.Enemy.PreHardMode.EvilChicken>());
}
}
}
|
date: 2020-01-07T17:53:33+0000
title: "Hazy State"
authors: "Collective Arts Brewing"
rating: 3.5
drink_of: https://untappd.com/b/<API key>/3104704
checkin:
title: The Griffin
lat: 51.525
long: -0.082
weather:
summary: Overcast
temperature: 11.5
badges:
- title: I Believe in IPA! (Level 9)
id: 619792722
posting_method: https://ownyour.beer
|
# Example implementing 5 layer encoder
# Original code taken from
# The model trained here is restored in load.py
from __future__ import division, print_function, absolute_import
# Import MNIST data
# from tensorflow.examples.tutorials.mnist import input_data
# data_set = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Import libraries
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import sys
import scipy.io as sio
sys.path.insert(0, '../..') # Add path to where TF_Model.py is, if not in the same dir
from TF_Model import *
from utils import *
# 01 thumb
# 10 pinky
action_map = {}
action_map[1] = [0,1]
action_map[2] = [1,0]
# thumb up
mat_contents_t0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_0.mat')
mat_contents_t1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_1.mat')
mat_contents_test0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_jan5_2.mat')
data_t0 = mat_contents_t0['EMGdata']
data_t1 = mat_contents_t1['EMGdata']
data_test0 = mat_contents_test0['EMGdata']
batch_y_t0, batch_x_t0 = <API key>(data_t0, action_map, [0])
batch_y_t1, batch_x_t1 = <API key>(data_t1, action_map, [0])
batch_y_test0, batch_x_test0 = <API key>(data_test0, action_map, [0])
# pinky up
mat_contents_p0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_0.mat')
mat_contents_p1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_1.mat')
mat_contents_test1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_2.mat')
data_p0 = mat_contents_p0['EMGdata']
data_p1 = mat_contents_p1['EMGdata']
data_test1 = mat_contents_test1['EMGdata']
batch_y_p0, batch_x_p0 = <API key>(data_p0, action_map, [0])
batch_y_p1, batch_x_p1 = <API key>(data_p1, action_map, [0])
batch_y_test1, batch_x_test1 = <API key>(data_test1, action_map, [0])
print("done reading data")
# Create TF_Model, a wrapper for models created using tensorflow
# Note that the configuration file 'config.txt' must be present in the directory
model = TF_Model('model')
# Parameters
learning_rate = 0.05
training_epochs = 200
batch_size = 256
display_step = 1
examples_to_show = 10
# total_batch = int(data_set.train.num_examples/batch_size)
dropout = tf.placeholder(tf.float32)
# Create variables for inputs, outputs and predictions
x = tf.placeholder(tf.float32, [None, 1000])
y = tf.placeholder(tf.float32, [None, 2])
y_true = y
y_pred = model.predict(x)
# Cost function
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.<API key>()
sess = tf.Session()
sess.run(init)
model_output = model.predict(x)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(model_output), reduction_indices=[1]))
train_step = tf.train.<API key>(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(model_output,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Train
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1})
# Display logs per epoch step
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c))
print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0}))
print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1}))
print("===final===")
print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0}))
print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1}))
# Save
model.save(sess, 'example_3')
|
package com.github.mdsimmo.pixeldungeon.levels.painters;
import com.github.mdsimmo.pixeldungeon.items.Gold;
import com.github.mdsimmo.pixeldungeon.items.Heap;
import com.github.mdsimmo.pixeldungeon.items.keys.IronKey;
import com.github.mdsimmo.pixeldungeon.levels.Level;
import com.github.mdsimmo.pixeldungeon.levels.Room;
import com.github.mdsimmo.pixeldungeon.levels.Terrain;
import com.github.mdsimmo.utils.Random;
public class TreasuryPainter extends Painter {
public static void paint( Level level, Room room ) {
fill( level, room, Terrain.WALL );
fill( level, room, 1, Terrain.EMPTY );
set( level, room.center(), Terrain.STATUE );
Heap.Type heapType = Random.Int( 2 ) == 0 ? Heap.Type.CHEST : Heap.Type.HEAP;
int n = Random.IntRange( 2, 3 );
for ( int i = 0; i < n; i++ ) {
int pos;
do {
pos = room.random();
} while ( level.map[pos] != Terrain.EMPTY || level.heaps.get( pos ) != null );
level.drop( new Gold().random(), pos ).type = (i == 0 && heapType == Heap.Type.CHEST ? Heap.Type.MIMIC : heapType);
}
if ( heapType == Heap.Type.HEAP ) {
for ( int i = 0; i < 6; i++ ) {
int pos;
do {
pos = room.random();
} while ( level.map[pos] != Terrain.EMPTY );
level.drop( new Gold( Random.IntRange( 1, 3 ) ), pos );
}
}
room.entrance().set( Room.Door.Type.LOCKED );
level.addItemToSpawn( new IronKey() );
}
}
|
/**
* Universal hash array object
*
* @package bsp::libbsp-core
* @author Dr.NP <np@bsgroup.org>
* @update 05/21/2013
* @changelog
* [06/11/2012] - Creation
* [08/14/2012] - Float / Double byte order
* [09/28/2012] - Array support
* [05/21/2013] - Remove float / double byte-order reverse
* [12/17/2013] - Lightuserdata supported
* [08/05/2014] - Rebuild
*/
#include "bsp.h"
/* Set values */
/*
void set_item_int8(BSP_VALUE *val, const int8_t value)
{
if (val)
{
set_int8(value, val->lval);
val->type = BSP_VAL_INT8;
}
return;
}
void set_item_int16(BSP_VALUE *val, const int16_t value)
{
if (val)
{
set_int16(value, val->lval);
val->type = BSP_VAL_INT16;
}
return;
}
void set_item_int32(BSP_VALUE *val, const int32_t value)
{
if (val)
{
set_int32(value, val->lval);
val->type = BSP_VAL_INT32;
}
return;
}
void set_item_int64(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_int64(value, val->lval);
item->value.type = BSP_VAL_INT64;
}
return;
}
*/
// Set value to value
void value_set_int(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_vint(value, val->lval);
val->type = BSP_VAL_INT;
}
}
void value_set_float(BSP_VALUE *val, const float value)
{
if (val)
{
set_float(value, val->lval);
val->type = BSP_VAL_FLOAT;
}
return;
}
void value_set_double(BSP_VALUE *val, const double value)
{
if (val)
{
set_double(value, val->lval);
val->type = BSP_VAL_DOUBLE;
}
return;
}
void <API key>(BSP_VALUE *val)
{
if (val)
{
set_vint(1, val->lval);
val->type = <API key>;
}
return;
}
void <API key>(BSP_VALUE *val)
{
if (val)
{
set_vint(0, val->lval);
val->type = <API key>;
}
return;
}
void value_set_pointer(BSP_VALUE *val, const void *p)
{
if (val)
{
val->rval = (void *) p;
val->type = BSP_VAL_POINTER;
}
return;
}
void value_set_string(BSP_VALUE *val, BSP_STRING *str)
{
if (val && str)
{
val->rval = (void *) str;
val->type = BSP_VAL_STRING;
}
return;
}
void value_set_object(BSP_VALUE *val, BSP_OBJECT *obj)
{
if (val && obj)
{
val->rval = (void *) obj;
val->type = BSP_VAL_OBJECT;
}
return;
}
void value_set_null(BSP_VALUE *val)
{
if (val)
{
val->type = BSP_VAL_NULL;
}
return;
}
// Get value from value
int64_t value_get_int(BSP_VALUE *val)
{
int64_t ret = 0;
if (val)
{
if (BSP_VAL_INT == val->type)
{
// int64
ret = get_vint(val->lval, NULL);
}
else if (BSP_VAL_INT29 == val->type)
{
// int29
ret = get_vint29(val->lval, NULL);
}
}
return ret;
}
int value_get_boolean(BSP_VALUE *val)
{
int ret = BSP_BOOLEAN_FALSE;
if (val && <API key> == val->type)
{
ret = BSP_BOOLEAN_TRUE;
}
return ret;
}
float value_get_float(BSP_VALUE *val)
{
float ret = 0.0;
if (val && BSP_VAL_FLOAT == val->type)
{
ret = get_float(val->rval);
}
return ret;
}
double value_get_double(BSP_VALUE *val)
{
double ret = 0.0;
if (val && BSP_VAL_DOUBLE == val->type)
{
ret = get_double(val->rval);
}
return ret;
}
void * value_get_pointer(BSP_VALUE *val)
{
void *ret = NULL;
if (val && BSP_VAL_POINTER == val->type)
{
ret = val->rval;
}
return ret;
}
BSP_STRING * value_get_string(BSP_VALUE *val)
{
BSP_STRING *ret = NULL;
if (val && BSP_VAL_STRING == val->type)
{
ret = (BSP_STRING *) val->rval;
}
return ret;
}
BSP_OBJECT * value_get_object(BSP_VALUE *val)
{
BSP_OBJECT *ret = NULL;
if (val && BSP_VAL_OBJECT == val->type)
{
ret = (BSP_OBJECT *) val->rval;
}
return ret;
}
/* Object & Value */
BSP_OBJECT * new_object(char type)
{
BSP_OBJECT *obj = bsp_calloc(1, sizeof(BSP_OBJECT));
if (obj)
{
obj->type = type;
bsp_spin_init(&obj->lock);
}
return obj;
}
void del_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
BSP_VALUE *val = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
struct bsp_hash_item_t *item = NULL, *old = NULL;
size_t idx, bucket, seq;
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
val = (BSP_VALUE *) obj->node;
del_value(val);
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
bucket = (idx / ARRAY_BUCKET_SIZE);
seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
del_value(val);
}
}
bsp_free(array);
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
item = hash->head;
while (item)
{
del_string(item->key);
del_value(item->value);
old = item;
item = old->lnext;
bsp_free(old);
}
bsp_free(hash);
}
break;
case <API key> :
default :
break;
}
bsp_spin_unlock(&obj->lock);
bsp_free(obj);
return;
}
BSP_VALUE * new_value()
{
return (BSP_VALUE *) bsp_calloc(1, sizeof(BSP_VALUE));
}
void del_value(BSP_VALUE *val)
{
if (val)
{
if (BSP_VAL_POINTER == val->type)
{
// Just ignore, we cannot determine what you are
}
else if (BSP_VAL_STRING == val->type)
{
del_string((BSP_STRING *) val->rval);
}
else if (BSP_VAL_OBJECT == val->type)
{
del_object((BSP_OBJECT *) val->rval);
}
else
{
// Local value, Just free
}
}
return bsp_free(val);
}
/* Item cursor operates */
// TODO : Not thread-safe, but maybe not neccessery
BSP_VALUE * curr_item(BSP_OBJECT *obj)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *curr = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
curr = (BSP_VALUE *) obj->node;
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
size_t bucket = (array->curr / ARRAY_BUCKET_SIZE);
if (array->curr < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
curr = array->items[bucket][array->curr % ARRAY_BUCKET_SIZE];
}
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
// Just value
// You can get current key with curr_item_key()
curr = hash->curr->value;
}
break;
default :
curr = NULL;
break;
}
return curr;
}
// Current array index
size_t curr_array_index(BSP_OBJECT *obj)
{
size_t idx = 0;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (array)
{
idx = array->curr;
}
}
return idx;
}
// Current hash key
BSP_STRING * curr_hash_key(BSP_OBJECT *obj)
{
BSP_STRING *key = NULL;
if (obj && OBJECT_TYPE_HASH == obj->type)
{
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
key = hash->curr->key;
}
}
return key;
}
size_t object_size(BSP_OBJECT *obj)
{
size_t ret = 0;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
if (obj)
{
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
if (obj->node)
{
ret = 1;
}
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
ret = array->nitems;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
ret = hash->nitems;
}
break;
default :
break;
}
}
return ret;
}
void reset_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
array->curr = 0;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
hash->curr = hash->head;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to do
break;
}
return;
}
void next_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr < array->nitems)
{
array->curr ++;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lnext;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to NEXT
break;
}
return;
}
void prev_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr > 0)
{
array->curr
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lprev;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to PREV
break;
}
}
/* Sort */
/*
inline static int __sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
register int is_d1 = 1, is_d2 = 1;
if (v1_int == 0)
{
if (0 != strcmp(v1, "0"))
{
is_d1 = 0;
}
}
if (v2_int == 0)
{
if (0 != strcmp(v2, "0"))
{
is_d2 = 0;
}
}
if (is_d1 && is_d2)
{
if (v1_int > v2_int)
{
return 1;
}
else
{
return -1;
}
}
if (!is_d1 && !is_d2)
{
// Strings
if (v1_len > v2_len)
{
return memcmp(v1, v2, v2_len);
}
else
{
return memcmp(v1, v2, v1_len);
}
}
return (is_d1 > is_d2) ? -1 : 1;
}
inline static int _sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
return (v1_len > v2_len) ? memcmp(v1, v2, v2_len) : memcmp(v1, v2, v1_len);
}
inline static void _sort_qsort(BSP_OBJECT_ITEM **list, size_t nitems)
{
int64_t begin_stack[256];
int64_t end_stack[256];
register int64_t begin;
register int64_t end;
register int64_t middle;
register int64_t pivot;
register int64_t seg1;
register int64_t seg2;
register int loop, c1, c2, c3;
register BSP_OBJECT_ITEM *tmp;
begin_stack[0] = 0;
end_stack[0] = nitems - 1;
for (loop = 0; loop >= 0; loop --)
{
begin = begin_stack[loop];
end = end_stack[loop];
while (begin < end)
{
// Find pivot
middle = (end - begin) >> 1;
c1 = _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int);
c2 = _sort_compare(
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int,
list[end]->key,
list[end]->key_len,
list[end]->key_int);
c3 = _sort_compare(
list[end]->key,
list[end]->key_len,
list[end]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int);
if (c1 >= 0)
{
pivot = (c2 >= 0) ? middle : ((c3 >= 0) ? begin : end);
}
else
{
pivot = (c2 < 0) ? middle : ((c3 < 0) ? begin : end);
}
if (pivot != begin)
{
// Swap pivot & begin
tmp = list[begin]; list[begin] = list[pivot]; list[pivot] = tmp;
}
seg1 = begin + 1;
seg2 = end;
while (1)
{
for (
;
seg1 < seg2 && _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[seg1]->key,
list[seg1]->key_len,
list[seg1]->key_int) > 0;
seg1 ++);
for (
;
seg2 >= seg1 && _sort_compare(
list[seg2]->key,
list[seg2]->key_len,
list[seg2]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int) > 0;
seg2 --);
if (seg1 >= seg2)
{
break;
}
tmp = list[seg1]; list[seg1] = list[seg2]; list[seg2] = tmp;
seg1 ++;
seg2 --;
}
// Swap begin & seg2
tmp = list[begin]; list[begin] = list[seg2]; list[seg2] = tmp;
if ((seg2 - begin) <= (end - seg2))
{
if ((seg2 + 1) < end)
{
begin_stack[loop] = seg2 + 1;
end_stack[loop ++] = end;
}
end = seg2 - 1;
}
else
{
if ((seg2 - 1) > begin)
{
begin_stack[loop] = begin;
end_stack[loop ++] = seg2 - 1;
}
begin = seg2 + 1;
}
}
}
return;
}
// Quicksort
int sort_object(BSP_OBJECT *obj)
{
if (!obj || 2 > obj->nitems )
{
return <API key>;
}
// Make a copy of item link
BSP_OBJECT_ITEM **list = bsp_calloc(obj->nitems, sizeof(BSP_OBJECT_ITEM *));
if (!list)
{
return <API key>;
}
bsp_spin_lock(&obj->obj_lock);
BSP_OBJECT_ITEM *curr = NULL;
int i = 0;
reset_object(obj);
curr = curr_item(obj);
while (curr)
{
if (i > obj->nitems - 1)
{
break;
}
list[i ++] = curr;
next_item(obj);
curr = curr_item(obj);
}
_sort_qsort(list, obj->nitems);
// Relink item link
for (i = 1; i < obj->nitems - 1; i ++)
{
list[i]->lnext = list[i + 1];
list[i]->lprev = list[i - 1];
}
list[0]->lnext = list[1];
list[0]->lprev = NULL;
obj->head = list[0];
list[obj->nitems - 1]->lnext = NULL;
list[obj->nitems - 1]->lprev = list[obj->nitems - 2];
obj->tail = list[obj->nitems - 1];
bsp_spin_unlock(&obj->obj_lock);
bsp_free(list);
return BSP_RTN_SUCCESS;
}
*/
// Find item from hash
static inline struct bsp_hash_item_t * _find_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (STR_IS_EQUAL(key, curr->key))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
static inline struct bsp_hash_item_t * _find_hash_str(struct bsp_hash_t *hash, const char *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (0 == strncmp(key, STR_STR(curr->key), STR_LEN(curr->key)))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
// Remove item from hash
static inline int _remove_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
static inline int _remove_hash_str(struct bsp_hash_t *hash, const char *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
// Insert an item into hash
static int _insert_hash(struct bsp_hash_t *hash, BSP_STRING *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = key;
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
static int _insert_hash_str(struct bsp_hash_t *hash, const char *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = new_string(key, -1);
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
// Enlarge hash table, rebuild hash link
static void _rebuild_hash(struct bsp_hash_t *hash, size_t new_hash_size)
{
if (hash && new_hash_size)
{
if (new_hash_size == hash->hash_size)
{
return;
}
if (hash->hash_table)
{
bsp_free(hash->hash_table);
}
hash->hash_table = bsp_calloc(new_hash_size, sizeof(struct bsp_hash_item_t));
hash->hash_size = new_hash_size;
// Insert every item from link
struct bsp_hash_item_t *curr = hash->head;
struct bsp_hash_item_t *bucket;
uint32_t hash_key;
while (curr && curr->key)
{
hash_key = bsp_hash(STR_STR(curr->key), STR_LEN(curr->key));
bucket = &hash->hash_table[hash_key % hash->hash_size];
curr->next = bucket->next;
curr->prev = bucket;
bucket->next = curr;
curr = curr->lnext;
}
}
return;
}
// Evalute a single (Number / String / Boolean etc) to a object
void object_set_single(BSP_OBJECT *obj, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
if (obj->node)
{
BSP_VALUE *old = (BSP_VALUE *) obj->node;
del_value(old);
}
obj->node = (BSP_VALUE *) val;
bsp_spin_unlock(&obj->lock);
}
return;
}
// Add an item into array
void object_set_array(BSP_OBJECT *obj, ssize_t idx, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (!array)
{
// Make a new array
array = bsp_calloc(1, sizeof(struct bsp_array_t));
obj->node = (void *) array;
}
if (idx < 0)
{
idx = array->nitems;
}
size_t bucket = (idx / ARRAY_BUCKET_SIZE);
size_t seq = idx % ARRAY_BUCKET_SIZE;
size_t nbuckets = array->nbuckets;
if (bucket >= nbuckets)
{
// Enlarge buckets
nbuckets = 2 << (int) (log2(bucket + 1));
array->items = bsp_realloc(array->items, nbuckets * sizeof(struct BSP_VAL **));
size_t i;
for (i = array->nbuckets; i < nbuckets; i ++)
{
array->items[i] = NULL;
}
array->nbuckets = nbuckets;
}
if (!array->items[bucket])
{
// New bucket
array->items[bucket] = bsp_calloc(ARRAY_BUCKET_SIZE, sizeof(struct BSP_VAL *));
}
if (array->items[bucket][seq])
{
// Remove old value
del_value(array->items[bucket][seq]);
}
array->items[bucket][seq] = val;
if (idx >= array->nitems)
{
array->nitems = idx + 1;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Insert / Remove an item into / from a hash
void object_set_hash(BSP_OBJECT *obj, BSP_STRING *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
void object_set_hash_str(BSP_OBJECT *obj, const char *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash_str(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash_str(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Get single value from object
BSP_VALUE * object_get_single(BSP_OBJECT *obj)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
ret = (BSP_VALUE *) obj->node;
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from array by given index
BSP_VALUE * object_get_array(BSP_OBJECT *obj, size_t idx)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (array && idx < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
ret = array->items[bucket][seq];
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from hash table
BSP_VALUE * object_get_hash(BSP_OBJECT *obj, BSP_STRING *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
BSP_VALUE * object_get_hash_str(BSP_OBJECT *obj, const char *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
/* Magic path */
BSP_VALUE * object_get_value(BSP_OBJECT *obj, const char *path)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *ret = NULL;
BSP_VALUE *curr_val = NULL;
BSP_OBJECT *curr_obj = obj;
BSP_STRING *key = NULL;
size_t idx = 0;
size_t i;
ssize_t start = -1;
int invalid = 0;
unsigned char c;
char *endptr = NULL;
if (OBJECT_TYPE_SINGLE == obj->type)
{
// Return full
ret = object_get_single(obj);
}
else
{
if (!path || 0 == strlen(path))
{
// No path
}
else
{
// Parse path normally
for (i = 0; i <= strlen(path); i ++)
{
c = (unsigned char) path[i];
if ('.' == c || '\0' == c)
{
// Hash seg
if (start < i && start >= 0 && curr_obj)
{
if (OBJECT_TYPE_HASH == curr_obj->type)
{
key = new_string_const(path + start, (i - start));
curr_val = object_get_hash(curr_obj, key);
del_string(key);
if (!curr_val)
{
// False
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else if (OBJECT_TYPE_ARRAY == curr_obj->type)
{
idx = (size_t) strtoull(path + start, &endptr, 0);
if (!idx && (path + start) == endptr)
{
// No digital
invalid = 1;
break;
}
curr_val = object_get_array(curr_obj, idx);
if (!curr_val)
{
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else
{
// False
curr_val = object_get_single(curr_obj);
break;
}
}
else
{
invalid = 1;
break;
}
}
else
{
// Normal char
if (start < 0)
{
start = i;
}
}
}
if (!invalid)
{
ret = curr_val;
}
}
}
return ret;
}
/* Serializer & Unserializer */
static void _pack_key(BSP_STRING *str, BSP_STRING *key);
static void _pack_value(BSP_STRING *str, BSP_VALUE *val);
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj);
static void _pack_key(BSP_STRING *str, BSP_STRING *key)
{
if (str)
{
char buf[9];
if (key)
{
string_append(str, buf, set_vint(STR_LEN(key), buf));
string_append(str, STR_STR(key), STR_LEN(key));
}
else
{
string_append(str, buf, set_vint(strlen(NO_HASH_KEY), buf));
string_append(str, NO_HASH_KEY, -1);
}
}
return;
}
static void _pack_value(BSP_STRING *str, BSP_VALUE *val)
{
char tmp[9];
int tmp_len;
BSP_STRING *sub_str = NULL;
BSP_OBJECT *sub_obj = NULL;
if (val && str)
{
string_append(str, &val->type, 1);
switch (val->type)
{
case BSP_VAL_INT :
string_append(str, val->lval, vintlen(val->lval, -1));
break;
case BSP_VAL_FLOAT :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_DOUBLE :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_STRING :
sub_str = (BSP_STRING *) val->rval;
if (sub_str)
{
tmp_len = set_vint(STR_LEN(sub_str), tmp);
string_append(str, tmp, tmp_len);
string_append(str, STR_STR(sub_str), STR_LEN(sub_str));
}
else
{
tmp[0] = 0;
string_append(str, tmp, 1);
}
break;
case BSP_VAL_POINTER :
set_pointer(val->rval, tmp);
string_append(str, tmp, sizeof(void *));
break;
case BSP_VAL_OBJECT :
sub_obj = (BSP_OBJECT *) val->rval;
if (sub_obj)
{
_pack_object(str, sub_obj);
}
break;
case <API key> :
case <API key> :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// No value
break;
}
}
return;
}
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj)
{
char value_type[1];
BSP_VALUE *val = NULL;
if (obj && str)
{
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// A single value
value_type[0] = <API key>;
string_append(str, value_type, 1);
// Push value
val = (BSP_VALUE *) obj->node;
_pack_value(str, val);
value_type[0] = <API key>;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_ARRAY :
// Array
value_type[0] = <API key>;
string_append(str, value_type, 1);
// Every item
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx, bucket, seq;
if (array)
{
for (idx = 9; idx < array->nitems; idx ++)
{
bucket = idx / ARRAY_BUCKET_SIZE;
seq = idx % ARRAY_BUCKET_SIZE;
val = NULL;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
_pack_value(str, val);
}
else
{
// Empty
value_type[0] = BSP_VAL_NULL;
string_append(str, value_type, 1);
}
}
}
value_type[0] = <API key>;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_HASH :
// Dict
value_type[0] = BSP_VAL_OBJECT_HASH;
string_append(str, value_type, 1);
// Traverse items
BSP_STRING *key;
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
// Set key and value
_pack_key(str, key);
_pack_value(str, val);
next_item(obj);
val = curr_item(obj);
}
value_type[0] = <API key>;
string_append(str, value_type, 1);
break;
case <API key> :
default :
// Yaaaahhh~~~?
break;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
BSP_STRING * object_serialize(BSP_OBJECT *obj)
{
BSP_STRING * ret = new_string(NULL, 0);
if (obj && ret)
{
_pack_object(ret, obj);
}
return ret;
}
static BSP_STRING * _unpack_key(BSP_STRING *str);
static BSP_VALUE * _unpack_value(BSP_STRING *str);
static BSP_OBJECT * _unpack_object(BSP_STRING *str);
static BSP_STRING * _unpack_key(BSP_STRING *str)
{
BSP_STRING *ret = NULL;
char *data;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
if (left > 0)
{
data = STR_STR(str);
vlen = vintlen(data, left);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret = new_string(data + vlen, str_len);
vlen += str_len;
}
}
}
str->cursor += vlen;
}
return ret;
}
static BSP_VALUE * _unpack_value(BSP_STRING *str)
{
BSP_VALUE *ret = NULL;
char *data;
char type;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
BSP_OBJECT *obj = NULL;
if (left > 0)
{
// 1st byte : Type
type = STR_STR(str)[str->cursor];
data = STR_STR(str) + 1;
ret = new_value();
ret->type = type;
switch (type)
{
case BSP_VAL_INT :
vlen = vintlen(data, left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_FLOAT :
vlen = (left > sizeof(float)) ? sizeof(float) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_DOUBLE :
vlen = (left > sizeof(double)) ? sizeof(double) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_STRING :
vlen = vintlen(data, left - 1);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret->rval = (void *) new_string(data + vlen, str_len);
vlen += str_len;
}
}
break;
case BSP_VAL_POINTER :
vlen = (left > sizeof(void *)) ? sizeof(void *) : (left - 1);
memcpy(&ret->rval, data, vlen);
break;
case BSP_VAL_OBJECT :
obj = _unpack_object(str);
ret->rval = (void *) obj;
break;
case <API key> :
case <API key> :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// Single values
break;
}
str->cursor += vlen + 1;
}
}
return ret;
}
static BSP_OBJECT * _unpack_object(BSP_STRING *str)
{
BSP_OBJECT *obj = NULL;
if (str)
{
bsp_spin_lock(&str->lock);
if (str->cursor < STR_LEN(str))
{
// Read first
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
char type = STR_STR(str)[str->cursor];
obj = new_object(type);
str->cursor ++;
switch (type)
{
case <API key> :
val = _unpack_value(str);
object_set_single(obj, val);
// Pass endding
str->cursor ++;
break;
case <API key> :
while (1)
{
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && <API key> == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_array(obj, -1, val);
}
break;
case BSP_VAL_OBJECT_HASH :
while (1)
{
// Read key first
key = _unpack_key(str);
if (!key)
{
break;
}
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && <API key> == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_hash(obj, key, val);
}
break;
default :
break;
}
}
bsp_spin_unlock(&str->lock);
}
return obj;
}
BSP_OBJECT * object_unserialize(BSP_STRING *str)
{
BSP_OBJECT * ret = NULL;
if (str)
{
str->cursor = 0;
ret = _unpack_object(str);
}
return ret;
}
/* Object <-> LUA stack */
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val);
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj);
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val)
{
if (!s)
{
return;
}
if (!val)
{
lua_pushnil(s);
return;
}
int v_intlen = 0;
uint64_t v_int = 0;
float v_float = 0.0;
double v_double = 0.0;
BSP_STRING *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (val->type)
{
case BSP_VAL_INT :
v_int = get_vint(val->lval, &v_intlen);
lua_pushinteger(s, (lua_Integer) v_int);
break;
case BSP_VAL_FLOAT :
v_float = get_float(val->lval);
lua_pushnumber(s, (lua_Number) v_float);
break;
case BSP_VAL_DOUBLE :
v_double = get_double(val->lval);
lua_pushnumber(s, (lua_Number) v_double);
break;
case <API key> :
lua_pushboolean(s, BSP_BOOLEAN_TRUE);
break;
case <API key> :
lua_pushboolean(s, BSP_BOOLEAN_FALSE);
break;
case BSP_VAL_STRING :
v_str = (BSP_STRING *) val->rval;
lua_pushlstring(s, STR_STR(v_str), STR_LEN(v_str));
break;
case BSP_VAL_POINTER :
v_ptr = val->rval;
<API key>(s, v_ptr);
break;
case BSP_VAL_OBJECT :
v_obj = (BSP_OBJECT *) val->rval;
_push_object_to_lua(s, v_obj);
break;
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
lua_pushnil(s);
break;
}
return;
}
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj)
{
if (!s)
{
return;
}
if (!obj)
{
lua_pushnil(s);
return;
}
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
bsp_spin_lock(&obj->lock);
lua_checkstack(s, 1);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// Single value
val = (BSP_VALUE *) obj->node;
_push_value_to_lua(s, val);
break;
case OBJECT_TYPE_ARRAY :
// Array
lua_newtable(s);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
if (val)
{
lua_checkstack(s, 2);
lua_pushinteger(s, (lua_Integer) idx + 1);
_push_value_to_lua(s, val);
lua_settable(s, -3);
}
}
}
}
break;
case OBJECT_TYPE_HASH :
// Hash
lua_newtable(s);
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
if (key)
{
lua_checkstack(s, 2);
lua_pushlstring(s, STR_STR(key), STR_LEN(key));
_push_value_to_lua(s, val);
if (lua_istable(s, -3))
{
lua_settable(s, -3);
}
}
next_item(obj);
val = curr_item(obj);
}
break;
case <API key> :
default :
lua_pushnil(s);
break;
}
bsp_spin_unlock(&obj->lock);
return;
}
void object_to_lua_stack(lua_State *s, BSP_OBJECT *obj)
{
if (!obj || !s)
{
return;
}
_push_object_to_lua(s, obj);
return;
}
static BSP_VALUE * _lua_value_to_value(lua_State *s);
static BSP_OBJECT * <API key>(lua_State *s);
static BSP_VALUE * _lua_value_to_value(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_VALUE *ret = new_value();
if (ret)
{
lua_Number v_number = 0;
int v_boolean = 0;
size_t str_len = 0;
const char *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (lua_type(s, -1))
{
case LUA_TNIL :
value_set_null(ret);
break;
case LUA_TNUMBER :
v_number = lua_tonumber(s, -1);
if (v_number == (lua_Number)(int64_t) v_number)
{
// Integer
value_set_int(ret, (const int64_t) v_number);
}
else
{
// Double / Float
value_set_double(ret, (const double) v_number);
}
break;
case LUA_TBOOLEAN :
v_boolean = lua_toboolean(s, -1);
if (BSP_BOOLEAN_FALSE == v_boolean)
{
<API key>(ret);
}
else
{
<API key>(ret);
}
break;
case LUA_TSTRING :
v_str = lua_tolstring(s, -1, &str_len);
value_set_string(ret, new_string(v_str, str_len));
break;
case LUA_TUSERDATA :
v_ptr = lua_touserdata(s, -1);
value_set_pointer(ret, (const void *) v_ptr);
break;
case LUA_TTABLE :
v_obj = <API key>(s);
value_set_object(ret, v_obj);
break;
default :
value_set_null(ret);
break;
}
}
return ret;
}
static BSP_OBJECT * <API key>(lua_State *s)
{
if (!s || !lua_istable(s, -1))
{
return NULL;
}
BSP_OBJECT *ret = NULL;
BSP_VALUE *val = NULL;
// Is array or hash?
if (luaL_len(s, -1) == lua_table_size(s, -1))
{
// Array
ret = new_object(OBJECT_TYPE_ARRAY);
size_t idx;
for (idx = 1; idx <= luaL_len(s, -1); idx ++)
{
lua_rawgeti(s, -1, idx);
val = _lua_value_to_value(s);
object_set_array(ret, idx - 1, val);
}
}
else
{
// Hash
ret = new_object(OBJECT_TYPE_HASH);
const char *key_str = NULL;
size_t key_len = 0;
BSP_STRING *key = NULL;
lua_checkstack(s, 2);
lua_pushnil(s);
while (0 != lua_next(s, -2))
{
// Key
key_str = lua_tolstring(s, -2, &key_len);
key = new_string(key_str, key_len);
// Value
val = _lua_value_to_value(s);
object_set_hash(ret, key, val);
lua_pop(s, 1);
}
}
return ret;
}
BSP_OBJECT * lua_stack_to_object(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_OBJECT *ret = NULL;
if (lua_istable(s, -1))
{
// Array or hash
ret = <API key>(s);
}
else
{
// Single
ret = new_object(OBJECT_TYPE_SINGLE);
object_set_single(ret, _lua_value_to_value(s));
}
return ret;
}
|
/* Defines the layout of the location structure */
#ifndef <API key>
#define <API key>
#include <glib.h>
#include <string.h>
#define <API key> "Location"
#define <API key> strlen(<API key>)
/* LocationInfo struct definition */
typedef struct
{
gchar * alias_;
gchar * city_;
gchar * state_;
gchar * country_;
gchar * woeid_;
gchar units_;
guint interval_;
gboolean enabled_;
} LocationInfo;
/* Configuration helpers */
typedef enum
{
ALIAS = 0,
CITY,
STATE,
COUNTRY,
WOEID,
UNITS,
INTERVAL,
ENABLED,
<API key>
} LocationInfoField;
/* Defined in the .c file - specifies the array of field names */
extern const gchar * <API key>[];
/**
* Provides the mechanism to free any data associated with
* the LocationInfo structure
*
* @param location Location entry to free.
*
*/
void
location_free(gpointer location);
/**
* Prints the contents of the supplied entry to stdout
*
* @param locatrion Location entry contents of which to print.
*
*/
void
location_print(gpointer location);
/**
* Sets the given property for the location
*
* @param location Pointer to the location to modify.
* @param property Name of the property to set.
* @param value Value to assign to the property.
* @param len Length of the value to assign to the property (think strlen())
*/
void
<API key>(gpointer location,
const gchar * property,
const gchar * value,
gsize len);
/**
* Copies a location entry.
*
* @param dst Address of the pointer to the location to set.
* @param src Pointer to the location to use/copy.
*
* @note Destination is first freed, if non-NULL, otherwise a new allocation
* is made. Both source and destination locations must be released by
* the caller.
*/
void
location_copy(gpointer * dst, gpointer src);
#endif
|
#include "util.h"
#include <math.h>
/* Geometry helper functions */
double distance(int x1, int y1, int x2, int y2)
{
int dx = x1 - x2;
int dy = y1 - y2;
return sqrt(dx * dx + dy * dy);
}
void each_actor(struct engine *engine, TCOD_list_t lst,
void (*action)(struct engine *engine,
struct actor *actor))
{
struct actor **iterator;
for (iterator = (struct actor **) TCOD_list_begin(engine->actors);
iterator != (struct actor **) TCOD_list_end(engine->actors);
iterator++)
action(engine, *iterator);
}
const char *generate_name(const char *filename)
{
TCOD_namegen_parse(filename, <API key>());
return <API key>("Celtic male", false);
}
void free_name_generator(void)
{
<API key>();
}
|
{% extends "userspace/journal/base.html" %}
{% load i18n rules %}
{% block title %}{{ block.super }}{% endblock title %}
{% block breadcrumb %}{{ block.super }}
<li><a href="{% url 'userspace:journal:subscription:list' <API key>.pk %}">{% trans "Abonnements" %}</a></li>
{% endblock breadcrumb %}
{% block section_title %}
{% trans "Abonnements" %}
{% endblock %}
{% block content_main %}
<ul class="tabs">
{% has_perm 'subscription.<API key>' request.user <API key> as <API key> %}
{% has_perm 'subscription.<API key>' request.user <API key> as <API key> %}
{% if <API key> %}
<li class="tabs__item{% if view.is_org_view %} tabs__item_active{% endif %}">
<a href="{% url 'userspace:journal:subscription:org_list' <API key>.pk %}">{% trans "Institutionnels" %}</a>
</li>
{% endif %}
{% if <API key> %}
<li class="tabs__item{% if not view.is_org_view %} tabs__item_active{% endif %}">
<a href="{% url 'userspace:journal:subscription:list' <API key>.pk %}">{% trans "Individuels" %}</a>
</li>
{% endif %}
</ul>
{% endblock content_main %}
|
// This file is part of the go-krypton library.
// The go-krypton library is free software: you can redistribute it and/or modify
// (at your option) any later version.
// The go-krypton library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// Package trie implements Merkle Patricia Tries.
package trie
import (
"bytes"
"errors"
"fmt"
"hash"
"github.com/krypton/go-krypton/common"
"github.com/krypton/go-krypton/crypto"
"github.com/krypton/go-krypton/crypto/sha3"
"github.com/krypton/go-krypton/logger"
"github.com/krypton/go-krypton/logger/glog"
"github.com/krypton/go-krypton/rlp"
)
const <API key> = 800
var (
// The global cache stores decoded trie nodes by hash as they get loaded.
globalCache = newARC(<API key>)
// This is the known root hash of an empty trie.
emptyRoot = common.HexToHash("<SHA256-like>")
// This is the known hash of an empty state trie entry.
emptyState = crypto.Sha3Hash(nil)
)
var ErrMissingRoot = errors.New("missing root node")
// Database must be implemented by backing stores for the trie.
type Database interface {
DatabaseWriter
// Get returns the value for key from the database.
Get(key []byte) (value []byte, err error)
}
// DatabaseWriter wraps the Put method of a backing store for the trie.
type DatabaseWriter interface {
// Put stores the mapping key->value in the database.
// Implementations must not hold onto the value bytes, the trie
// will reuse the slice across calls to Put.
Put(key, value []byte) error
}
// Trie is a Merkle Patricia Trie.
// The zero value is an empty trie with no database.
// Use New to create a trie that sits on top of a database.
// Trie is not safe for concurrent use.
type Trie struct {
root node
db Database
*hasher
}
// New creates a trie with an existing root node from db.
// If root is the zero hash or the sha3 hash of an empty string, the
// trie is initially empty and does not require a database. Otherwise,
// New will panics if db is nil or root does not exist in the
// database. Accessing the trie loads nodes from db on demand.
func New(root common.Hash, db Database) (*Trie, error) {
trie := &Trie{db: db}
if (root != common.Hash{}) && root != emptyRoot {
if db == nil {
panic("trie.New: cannot use existing root without a database")
}
if v, _ := trie.db.Get(root[:]); len(v) == 0 {
return nil, ErrMissingRoot
}
trie.root = hashNode(root.Bytes())
}
return trie, nil
}
// Iterator returns an iterator over all mappings in the trie.
func (t *Trie) Iterator() *Iterator {
return NewIterator(t)
}
// Get returns the value for key stored in the trie.
func (t *Trie) Get(key []byte) []byte {
key = compactHexDecode(key)
tn := t.root
for len(key) > 0 {
switch n := tn.(type) {
case shortNode:
if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
return nil
}
tn = n.Val
key = key[len(n.Key):]
case fullNode:
tn = n[key[0]]
key = key[1:]
case nil:
return nil
case hashNode:
tn = t.resolveHash(n)
default:
panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
}
}
return tn.(valueNode)
}
// Update associates key with value in the trie. Subsequent calls to
// Get will return value. If value has length zero, any existing value
// is deleted from the trie and calls to Get will return nil.
// stored in the trie.
func (t *Trie) Update(key, value []byte) {
k := compactHexDecode(key)
if len(value) != 0 {
t.root = t.insert(t.root, k, valueNode(value))
} else {
t.root = t.delete(t.root, k)
}
}
func (t *Trie) insert(n node, key []byte, value node) node {
if len(key) == 0 {
return value
}
switch n := n.(type) {
case shortNode:
matchlen := prefixLen(key, n.Key)
// If the whole key matches, keep this short node as is
// and only update the value.
if matchlen == len(n.Key) {
return shortNode{n.Key, t.insert(n.Val, key[matchlen:], value)}
}
// Otherwise branch out at the index where they differ.
var branch fullNode
branch[n.Key[matchlen]] = t.insert(nil, n.Key[matchlen+1:], n.Val)
branch[key[matchlen]] = t.insert(nil, key[matchlen+1:], value)
// Replace this shortNode with the branch if it occurs at index 0.
if matchlen == 0 {
return branch
}
// Otherwise, replace it with a short node leading up to the branch.
return shortNode{key[:matchlen], branch}
case fullNode:
n[key[0]] = t.insert(n[key[0]], key[1:], value)
return n
case nil:
return shortNode{key, value}
case hashNode:
// We've hit a part of the trie that isn't loaded yet. Load
// the node and insert into it. This leaves all child nodes on
// the path to the value in the trie.
// TODO: track whkrypton insertion changed the value and keep
// n as a hash node if it didn't.
return t.insert(t.resolveHash(n), key, value)
default:
panic(fmt.Sprintf("%T: invalid node: %v", n, n))
}
}
// Delete removes any existing value for key from the trie.
func (t *Trie) Delete(key []byte) {
k := compactHexDecode(key)
t.root = t.delete(t.root, k)
}
// delete returns the new root of the trie with key deleted.
// It reduces the trie to minimal form by simplifying
// nodes on the way up after deleting recursively.
func (t *Trie) delete(n node, key []byte) node {
switch n := n.(type) {
case shortNode:
matchlen := prefixLen(key, n.Key)
if matchlen < len(n.Key) {
return n // don't replace n on mismatch
}
if matchlen == len(key) {
return nil // remove n entirely for whole matches
}
// The key is longer than n.Key. Remove the remaining suffix
// from the subtrie. Child can never be nil here since the
// subtrie must contain at least two other values with keys
// longer than n.Key.
child := t.delete(n.Val, key[len(n.Key):])
switch child := child.(type) {
case shortNode:
// Deleting from the subtrie reduced it to another
// short node. Merge the nodes to avoid creating a
// shortNode{..., shortNode{...}}. Use concat (which
// always creates a new slice) instead of append to
// avoid modifying n.Key since it might be shared with
// other nodes.
return shortNode{concat(n.Key, child.Key...), child.Val}
default:
return shortNode{n.Key, child}
}
case fullNode:
n[key[0]] = t.delete(n[key[0]], key[1:])
// Check how many non-nil entries are left after deleting and
// reduce the full node to a short node if only one entry is
// left. Since n must've contained at least two children
// before deletion (otherwise it would not be a full node) n
// can never be reduced to nil.
// When the loop is done, pos contains the index of the single
// value that is left in n or -2 if n contains at least two
// values.
pos := -1
for i, cld := range n {
if cld != nil {
if pos == -1 {
pos = i
} else {
pos = -2
break
}
}
}
if pos >= 0 {
if pos != 16 {
// If the remaining entry is a short node, it replaces
// n and its key gets the missing nibble tacked to the
// front. This avoids creating an invalid
// shortNode{..., shortNode{...}}. Since the entry
// might not be loaded yet, resolve it just for this
// check.
cnode := t.resolve(n[pos])
if cnode, ok := cnode.(shortNode); ok {
k := append([]byte{byte(pos)}, cnode.Key...)
return shortNode{k, cnode.Val}
}
}
// Otherwise, n is replaced by a one-nibble short node
// containing the child.
return shortNode{[]byte{byte(pos)}, n[pos]}
}
// n still contains at least two values and cannot be reduced.
return n
case nil:
return nil
case hashNode:
// We've hit a part of the trie that isn't loaded yet. Load
// the node and delete from it. This leaves all child nodes on
// the path to the value in the trie.
// TODO: track whkrypton deletion actually hit a key and keep
// n as a hash node if it didn't.
return t.delete(t.resolveHash(n), key)
default:
panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
}
}
func concat(s1 []byte, s2 ...byte) []byte {
r := make([]byte, len(s1)+len(s2))
copy(r, s1)
copy(r[len(s1):], s2)
return r
}
func (t *Trie) resolve(n node) node {
if n, ok := n.(hashNode); ok {
return t.resolveHash(n)
}
return n
}
func (t *Trie) resolveHash(n hashNode) node {
if v, ok := globalCache.Get(n); ok {
return v
}
enc, err := t.db.Get(n)
if err != nil || enc == nil {
// TODO: This needs to be improved to properly distinguish errors.
// Disk I/O errors shouldn't produce nil (and cause a
// consensus failure or weird crash), but it is unclear how
// they could be handled because the entire stack above the trie isn't
// prepared to cope with missing state nodes.
if glog.V(logger.Error) {
glog.Errorf("Dangling hash node ref %x: %v", n, err)
}
return nil
}
dec := mustDecodeNode(n, enc)
if dec != nil {
globalCache.Put(n, dec)
}
return dec
}
// Root returns the root hash of the trie.
// Deprecated: use Hash instead.
func (t *Trie) Root() []byte { return t.Hash().Bytes() }
// Hash returns the root hash of the trie. It does not write to the
// database and can be used even if the trie doesn't have one.
func (t *Trie) Hash() common.Hash {
root, _ := t.hashRoot(nil)
return common.BytesToHash(root.(hashNode))
}
// Commit writes all nodes to the trie's database.
// Nodes are stored with their sha3 hash as the key.
// Committing flushes nodes from memory.
// Subsequent Get calls will load nodes from the database.
func (t *Trie) Commit() (root common.Hash, err error) {
if t.db == nil {
panic("Commit called on trie with nil database")
}
return t.CommitTo(t.db)
}
// CommitTo writes all nodes to the given database.
// Nodes are stored with their sha3 hash as the key.
// Committing flushes nodes from memory. Subsequent Get calls will
// load nodes from the trie's database. Calling code must ensure that
// the changes made to db are written back to the trie's attached
// database before using the trie.
func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
n, err := t.hashRoot(db)
if err != nil {
return (common.Hash{}), err
}
t.root = n
return common.BytesToHash(n.(hashNode)), nil
}
func (t *Trie) hashRoot(db DatabaseWriter) (node, error) {
if t.root == nil {
return hashNode(emptyRoot.Bytes()), nil
}
if t.hasher == nil {
t.hasher = newHasher()
}
return t.hasher.hash(t.root, db, true)
}
type hasher struct {
tmp *bytes.Buffer
sha hash.Hash
}
func newHasher() *hasher {
return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()}
}
func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, error) {
hashed, err := h.replaceChildren(n, db)
if err != nil {
return hashNode{}, err
}
if n, err = h.store(hashed, db, force); err != nil {
return hashNode{}, err
}
return n, nil
}
// hashChildren replaces child nodes of n with their hashes if the encoded
// size of the child is larger than a hash.
func (h *hasher) replaceChildren(n node, db DatabaseWriter) (node, error) {
var err error
switch n := n.(type) {
case shortNode:
n.Key = compactEncode(n.Key)
if _, ok := n.Val.(valueNode); !ok {
if n.Val, err = h.hash(n.Val, db, false); err != nil {
return n, err
}
}
if n.Val == nil {
// Ensure that nil children are encoded as empty strings.
n.Val = valueNode(nil)
}
return n, nil
case fullNode:
for i := 0; i < 16; i++ {
if n[i] != nil {
if n[i], err = h.hash(n[i], db, false); err != nil {
return n, err
}
} else {
// Ensure that nil children are encoded as empty strings.
n[i] = valueNode(nil)
}
}
if n[16] == nil {
n[16] = valueNode(nil)
}
return n, nil
default:
return n, nil
}
}
func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) {
// Don't store hashes or empty nodes.
if _, isHash := n.(hashNode); n == nil || isHash {
return n, nil
}
h.tmp.Reset()
if err := rlp.Encode(h.tmp, n); err != nil {
panic("encode error: " + err.Error())
}
if h.tmp.Len() < 32 && !force {
// Nodes smaller than 32 bytes are stored inside their parent.
return n, nil
}
// Larger nodes are replaced by their hash and stored in the database.
h.sha.Reset()
h.sha.Write(h.tmp.Bytes())
key := hashNode(h.sha.Sum(nil))
if db != nil {
err := db.Put(key, h.tmp.Bytes())
return key, err
}
return key, nil
}
|
#!/bin/csh
# Script to Read in a new substructure file to the database
#set verbose on
if ( $#argv != 1 ) then
echo "Usage: $0 FileRoot"
echo " FileROOT : The substructure information file (rootname without sdf extension)"
echo " The file is assumed to be in the current directory"
exit(1)
endif
# Set up inputs, files and program
# The program and the input file pattern
set CHEMPROG = $REACTROOT/bin/runchem.sh
set REFERENCE = $REACTROOT/programs/inputs/ReadSubsFromFile.inp
# The current input file and the standard (established) input file
set NEWFILE = $1
# The combined input file (all the substructures are formed again)
set STANDARDSUBFILE = standard
set STANDARD = $REACTROOT/data/mol/subs/standard.sdf
set TEMPDIR = $REACTROOT/tmp
set TEMPFILE = $REACTROOT/tmp/read.prg
set TEMPOUTFILE = $REACTROOT/tmp/read.out
set INFILE = $NEWFILE.sdf
# Modify program and merge input data files
sed "s/XXXXX/$NEWFILE/g"\
$REFERENCE >! $TEMPFILE
cat $INFILE > $STANDARD
# Put Substructures in Database
pushd $TEMPDIR
$CHEMPROG read < read.prg
rm $TEMPFILE
popd
mv $TEMPOUTFILE $NEWFILE.out
|
class Solution {
public:
string addBinary(string a, string b) {
string sum = "";
int carry = 0;
for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i
int m = (i >= 0 && a[i] == '1');
int n = (j >= 0 && b[j] == '1');
sum += to_string((m + n + carry) & 0x1); // &0x1 only get the last binary digit
//It's better to avoid pattern string = char + string in loop. Use s[i] to alter string.
//just directly writing the output string and reversing it at last.
carry = (m + n + carry) >> 1; // >>1 is /2
}
reverse(sum.begin(), sum.end());
if(carry) sum = '1' + sum;
else sum = '0' + sum; //in case of two null input string
size_t i=0;
while(sum[i] == '0' && i < sum.length()-1) i++;
sum = sum.substr(i);
return sum;
}
};
|
title: "कांग्रेस का नया नारा 'अब होगा NYAY', चुनावी कैम्पेन लांच"
layout: item
category: ["politics"]
date: 2019-04-07T08:05:44.259Z
image: <API key>.jpg
<p>नई दिल्ली: कांग्रेस लोकसभा चुनाव के लिए रविवार को अपने प्रचार अभियान की औपचारिक रूप से शुरुआत की। इस अभियान के तहत पार्टी ने प्रिंट, इलेक्ट्रॉनिक और डिजिटल मीडिया माध्यमों पर दिए जाने वाले पार्टी के प्रचार अभियान का ब्यौरा पेश किया। कांग्रेस के वरिष्ठ नेता आनंद शर्मा की अध्यक्षता वाली प्रचार अभियान की समिति ने प्रचार अभियान का पूरा ब्यौरा देते हुए स्लोगन लॉन्च किया। स्लोगन की टैगलाइन है- अब होगा न्याय। न्याय कैम्पेन वीडियो के लिए लिरिक्स जावेद अख्तर ने लिखे हैं। निखिल अडवाणी ने इसे निर्देशित किया है।</p>
<div class="tw-container"><div class="tweet" data-tweet="1114790612199333888"></div></div>
<p>आनंद शर्मा ने कहा कि मोदी सरकार ने लोगों को सपने दिखाकर चकनाचूर किया। उन्होंने बताया कि &
<div class="tw-container"><div class="tweet" data-tweet="1114798893240209408"></div></div>
<p>कांग्रेस अपने प्रचार अभियान में रोजगार, नौजवान, किसान और महिलाओं पर मुख्य रूप से केंद्रित रखेगी तथा विभिन्न मुद्दों को लेकर मोदी सरकार को घेरने पर भी जोर दिया।</p>
<div class="tw-container"><div class="tweet" data-tweet="1114797055937892352"></div></div>
|
{-# LANGUAGE FlexibleContexts, CPP, JavaScriptFFI #-}
module Carnap.GHCJS.Action.TreeDeductionCheck (<API key>) where
import Lib hiding (content)
import Data.Tree
import Data.Either
import Data.Map as M (lookup,Map, toList)
import Data.IORef (IORef, readIORef, newIORef, writeIORef)
import Data.Typeable (Typeable)
import Data.Aeson.Types
import Data.Text (pack)
import qualified Text.Parsec as P (parse)
import Control.Monad.State (modify,get,execState,State)
import Control.Lens
import Control.Concurrent
import Control.Monad (mplus, (>=>))
import Control.Monad.IO.Class (liftIO)
import Carnap.Core.Unification.Unification (MonadVar,FirstOrder, applySub)
import Carnap.Core.Unification.ACUI (ACUI)
import Carnap.Core.Data.Types
import Carnap.Core.Data.Classes
import Carnap.Core.Data.Optics
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.Util.LanguageClasses
import Carnap.Calculi.Util
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Checker
import Carnap.Calculi.Tableau.Data
import Carnap.Languages.PurePropositional.Logic (ofPropTreeSys)
import Carnap.Languages.PureFirstOrder.Logic (ofFOLTreeSys)
import Carnap.GHCJS.Util.ProofJS
import Carnap.GHCJS.SharedTypes
import GHCJS.DOM.HTMLElement (getInnerText, castToHTMLElement)
import GHCJS.DOM.Element (setInnerHTML, click, keyDown, input, setAttribute )
import GHCJS.DOM.Node (appendChild, removeChild, getParentNode, insertBefore, getParentElement)
import GHCJS.DOM.Types (Element, Document, IsElement)
import GHCJS.DOM.Document (createElement, getActiveElement)
import GHCJS.DOM.KeyboardEvent
import GHCJS.DOM.EventM
import GHCJS.DOM
import GHCJS.Types
<API key> :: IO ()
<API key> =
do initializeCallback "checkProofTreeInfo" njCheck
initElements getCheckers activateChecker
return ()
where njCheck = maybe (error "can't find PropNJ") id $ (\calc -> checkProofTree calc Nothing >=> return . fst) `ofPropTreeSys` "PropNJ"
getCheckers :: IsElement self => Document -> self -> IO [Maybe (Element, Element, Map String String)]
getCheckers w = genInOutElts w "div" "div" "<API key>"
activateChecker :: Document -> Maybe (Element, Element, Map String String) -> IO ()
activateChecker _ Nothing = return ()
activateChecker w (Just (i, o, opts)) = case (setupWith `ofPropTreeSys` sys)
`mplus` (setupWith `ofFOLTreeSys` sys)
of Just io -> io
Nothing -> error $ "couldn't parse tree system: " ++ sys
where sys = case M.lookup "system" opts of
Just s -> s
Nothing -> "propNK"
setupWith calc = do
mgoal <- parseGoal calc
let content = M.lookup "content" opts
root <- case (content >>= decodeJSON, mgoal) of
(Just val,_) -> let Just c = content in initRoot c o
(_, Just seq) | "prepopulate" `inOpts` opts ->
initRoot ("{\"label\": \"" ++ show (view rhs seq)
++ "\", \"rule\":\"\", \"forest\": []}") o
_ -> initRoot "{\"label\": \"\", \"rule\":\"\", \"forest\": []}" o
memo <- newIORef mempty
threadRef <- newIORef (Nothing :: Maybe ThreadId)
bw <- createButtonWrapper w o
let submit = submitTree w memo opts calc root mgoal
btStatus <- createSubmitButton w bw submit opts
if "displayJSON" `inOpts` opts
then do
Just displayDiv <- createElement w (Just "div")
setAttribute displayDiv "class" "jsonDisplay"
setAttribute displayDiv "contenteditable" "true"
val <- toCleanVal root
setInnerHTML displayDiv . Just $ toJSONString val
toggleDisplay <- newListener $ do
kbe <- event
isCtrl <- getCtrlKey kbe
code <- liftIO $ keyString kbe
liftIO $ print code
if isCtrl && code == "?"
then do
preventDefault
mparent <- getParentNode displayDiv
case mparent of
Just p -> removeChild o (Just displayDiv)
_ -> appendChild o (Just displayDiv)
return ()
else return ()
addListener o keyDown toggleDisplay False
updateRoot <- newListener $ liftIO $ do
Just json <- getInnerText (castToHTMLElement displayDiv)
replaceRoot root json
addListener displayDiv input updateRoot False
root `onChange` (\_ -> do
mfocus <- getActiveElement w
--don't update when the display is
--focussed, to avoid cursor jumping
if Just displayDiv /= mfocus then do
val <- toCleanVal root
setInnerHTML displayDiv . Just $ toJSONString val
else return ())
return ()
else return ()
initialCheck <- newListener $ liftIO $ do
forkIO $ do
threadDelay 500000
mr <- toCleanVal root
case mr of
Just r -> do (info,mseq) <- checkProofTree calc (Just memo) r
decorate root info
Just wrap <- getParentElement i
updateInfo calc mgoal mseq wrap
Nothing -> return ()
return ()
addListener i initialize initialCheck False --initial check in case we preload a tableau
doOnce i mutate False $ liftIO $ btStatus Edited
case M.lookup "init" opts of Just "now" -> dispatchCustom w i "initialize"; _ -> return ()
root `onChange` (\_ -> dispatchCustom w i "mutate")
root `onChange` (\_ -> checkOnChange memo threadRef calc mgoal i root)
parseGoal calc = do
let seqParse = parseSeqOver $ tbParseForm calc
case M.lookup "goal" opts of
Just s -> case P.parse seqParse "" s of
Left e -> do setInnerHTML i (Just $ "Couldn't Parse This Goal:" ++ s)
error "couldn't parse goal"
Right seq -> do setInnerHTML i (Just . tbNotation calc . show $ seq)
return $ Just seq
Nothing -> do setInnerHTML i (Just "Awaiting a proof")
return Nothing
updateInfo _ (Just goal) (Just seq) wrap | seq `seqSubsetUnify` goal = setAttribute wrap "class" "success"
updateInfo _ (Just goal) (Just seq) wrap = setAttribute wrap "class" "failure"
updateInfo calc Nothing (Just seq) wrap = setInnerHTML wrap (Just . tbNotation calc . show $ seq)
updateInfo _ Nothing Nothing wrap = setInnerHTML wrap (Just "Awaiting a proof")
updateInfo _ _ _ wrap = setAttribute wrap "class" ""
submitTree w memo opts calc root (Just seq) l =
do Just val <- liftIO $ toCleanVal root
case parse parseTreeJSON val of
Error s -> message $ "Something has gone wrong. Here's the error:" ++ s
Success tree -> case toProofTree calc tree of
Left _ | "exam" `inOpts` opts -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) False
Left _ -> message "Something is wrong with the proof... Try again?"
Right prooftree -> do
validation <- liftIO $ <API key> memo (<API key> prooftree) prooftree
case validation of
Right seq' | "exam" `inOpts` opts || (seq' `seqSubsetUnify` seq)
-> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) (seq' `seqSubsetUnify` seq)
_ -> message "Something is wrong with the proof... Try again?"
checkOnChange :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (<API key> lex)
, ACUI (<API key> lex)
, MonadVar (<API key> lex) (State Int)
, StaticVar (<API key> lex)
, Schematizable (lex (<API key> lex))
, CopulaSchema (<API key> lex)
, Typeable sem
, Show rule
, <API key> lex
, FirstOrderLex (lex (<API key> lex))
, StructuralOverride rule (ProofTree rule lex sem)
, StructuralInference rule lex (ProofTree rule lex sem)
) => ProofMemoRef lex sem rule -> IORef (Maybe ThreadId) -> TableauCalc lex sem rule
-> Maybe (<API key> lex (Sequent sem)) -> Element -> JSVal -> IO ()
checkOnChange memo threadRef calc mgoal i root = do
mt <- readIORef threadRef
case mt of Just t -> killThread t
Nothing -> return ()
t' <- forkIO $ do
threadDelay 500000
Just changedVal <- toCleanVal root
(theInfo, mseq) <- checkProofTree calc (Just memo) changedVal
decorate root theInfo
Just wrap <- getParentElement i
updateInfo calc mgoal mseq wrap
writeIORef threadRef (Just t')
toProofTree :: ( Typeable sem
, ReLex lex
, Sequentable lex
, StructuralOverride rule (ProofTree rule lex sem)
, Inference rule lex sem
) => TableauCalc lex sem rule -> Tree (String,String) -> Either (TreeFeedback lex) (ProofTree rule lex sem)
toProofTree calc (Node (l,r) f)
| all isRight parsedForest && isRight newNode = handleOverride <$> (Node <$> newNode <*> sequence parsedForest)
| isRight newNode = Left $ Node Waiting (map cleanTree parsedForest)
| Left n <- newNode = Left n
where parsedLabel = (SS . liftToSequent) <$> P.parse (tbParseForm calc) "" l
parsedRules = P.parse (tbParseRule calc) "" r
parsedForest = map (toProofTree calc) f
cleanTree (Left fs) = fs
cleanTree (Right fs) = fmap (const Waiting) fs
newNode = case ProofLine 0 <$> parsedLabel <*> parsedRules of
Right l -> Right l
Left e -> Left (Node (ProofError $ NoParse e 0) (map cleanTree parsedForest))
handleOverride f@(Node l fs) = case structuralOverride f (head (rule l)) of
Nothing -> f
Just rs -> Node (l {rule = rs}) fs
checkProofTree :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (<API key> lex)
, ACUI (<API key> lex)
, MonadVar (<API key> lex) (State Int)
, StaticVar (<API key> lex)
, Schematizable (lex (<API key> lex))
, CopulaSchema (<API key> lex)
, Typeable sem
, Show rule
, StructuralOverride rule (ProofTree rule lex sem)
, StructuralInference rule lex (ProofTree rule lex sem)
) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) -> Value -> IO (Value, Maybe (<API key> lex (Sequent sem)))
checkProofTree calc mmemo v = case parse parseTreeJSON v of
Success t -> case toProofTree calc t of
Left feedback -> return (toInfo feedback, Nothing)
Right tree -> do (val,mseq) <- validateProofTree calc mmemo tree
return (toInfo val, mseq)
Error s -> do print (show v)
error s
validateProofTree :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (<API key> lex)
, ACUI (<API key> lex)
, MonadVar (<API key> lex) (State Int)
, StaticVar (<API key> lex)
, Schematizable (lex (<API key> lex))
, CopulaSchema (<API key> lex)
, Typeable sem
, Show rule
, StructuralInference rule lex (ProofTree rule lex sem)
) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule)
-> ProofTree rule lex sem -> IO (TreeFeedback lex, Maybe (<API key> lex (Sequent sem)))
validateProofTree calc mmemo t@(Node _ fs) = do rslt <- case mmemo of
Nothing -> return $ hoReduceProofTree (<API key> t) t
Just memo -> <API key> memo (<API key> t) t
case rslt of
Left msg -> (,) <$> (Node <$> pure (ProofError msg) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs)
<*> pure Nothing
Right seq -> (,) <$> (Node <$> pure (ProofData (tbNotation calc . show $ seq)) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs)
<*> pure (Just seq)
|
#ifndef <API key>
#define <API key>
#include "Platform/Define.h"
#include "Policies/Singleton.h"
#include <ace/Thread_Mutex.h>
#include "Utilities/UnorderedMap.h"
#include "Policies/ThreadingModel.h"
#include "ByteBuffer.h"
#include "UpdateData.h"
#include "GridDefines.h"
#include "Object.h"
#include "Player.h"
#include <set>
class Creature;
class Corpse;
class Unit;
class GameObject;
class DynamicObject;
class WorldObject;
class Map;
template <class T>
class HashMapHolder
{
public:
typedef UNORDERED_MAP<uint64, T*> MapType;
typedef ACE_Thread_Mutex LockType;
typedef BlizzLike::GeneralLock<LockType > Guard;
static void Insert(T* o)
{
Guard guard(i_lock);
m_objectMap[o->GetGUID()] = o;
}
static void Remove(T* o)
{
Guard guard(i_lock);
m_objectMap.erase(o->GetGUID());
}
static T* Find(uint64 guid)
{
Guard guard(i_lock);
typename MapType::iterator itr = m_objectMap.find(guid);
return (itr != m_objectMap.end()) ? itr->second : NULL;
}
static MapType& GetContainer() { return m_objectMap; }
static LockType* GetLock() { return &i_lock; }
private:
//Non instanceable only static
HashMapHolder() {}
static LockType i_lock;
static MapType m_objectMap;
};
class ObjectAccessor : public BlizzLike::Singleton<ObjectAccessor, BlizzLike::ClassLevelLockable<ObjectAccessor, ACE_Thread_Mutex> >
{
friend class BlizzLike::OperatorNew<ObjectAccessor>;
ObjectAccessor();
~ObjectAccessor();
ObjectAccessor(const ObjectAccessor&);
ObjectAccessor& operator=(const ObjectAccessor&);
public:
typedef UNORDERED_MAP<uint64, Corpse*> <API key>;
typedef UNORDERED_MAP<Player*, UpdateData>::value_type UpdateDataValueType;
// returns object if is in world
template<class T> static T* GetObjectInWorld(uint64 guid, T* /*typeSpecifier*/)
{
return HashMapHolder<T>::Find(guid);
}
// Player may be not in world while in ObjectAccessor
static Player* GetObjectInWorld(uint64 guid, Player* /*typeSpecifier*/)
{
Player* player = HashMapHolder<Player>::Find(guid);
if (player && player->IsInWorld())
return player;
return NULL;
}
static Unit* GetObjectInWorld(uint64 guid, Unit* /*typeSpecifier*/)
{
if (IS_PLAYER_GUID(guid))
return (Unit*)GetObjectInWorld(guid, (Player*)NULL);
if (IS_PET_GUID(guid))
return (Unit*)GetObjectInWorld(guid, (Pet*)NULL);
return (Unit*)GetObjectInWorld(guid, (Creature*)NULL);
}
// returns object if is in map
template<class T> static T* GetObjectInMap(uint64 guid, Map * map, T* /*typeSpecifier*/)
{
assert(map);
if (T * obj = GetObjectInWorld(guid, (T*)NULL))
if (obj->GetMap() == map)
return obj;
return NULL;
}
template<class T> static T* GetObjectInWorld(uint32 mapid, float x, float y, uint64 guid, T* /*fake*/)
{
T* obj = HashMapHolder<T>::Find(guid);
if (!obj || obj->GetMapId() != mapid)
return NULL;
CellPair p = BlizzLike::ComputeCellPair(x, y);
if (p.x_coord >= <API key> || p.y_coord >= <API key>)
{
sLog.outError("ObjectAccessor::GetObjectInWorld: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord);
return NULL;
}
CellPair q = BlizzLike::ComputeCellPair(obj->GetPositionX(),obj->GetPositionY());
if (q.x_coord >= <API key> || q.y_coord >= <API key>)
{
sLog.outError("ObjectAccessor::GetObjecInWorld: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), q.x_coord, q.y_coord);
return NULL;
}
int32 dx = int32(p.x_coord) - int32(q.x_coord);
int32 dy = int32(p.y_coord) - int32(q.y_coord);
if (dx > -2 && dx < 2 && dy > -2 && dy < 2)
return obj;
else
return NULL;
}
// these functions return objects only if in map of specified object
static Object* GetObjectByTypeMask(WorldObject const&, uint64, uint32 typemask);
static Corpse* GetCorpse(WorldObject const& u, uint64 guid);
static GameObject* GetGameObject(WorldObject const& u, uint64 guid);
static DynamicObject* GetDynamicObject(WorldObject const& u, uint64 guid);
static Unit* GetUnit(WorldObject const&, uint64 guid);
static Creature* GetCreature(WorldObject const& u, uint64 guid);
static Pet* GetPet(WorldObject const&, uint64 guid);
static Player* GetPlayer(WorldObject const&, uint64 guid);
static Creature* GetCreatureOrPet(WorldObject const&, uint64);
// these functions return objects if found in whole world
// ACCESS LIKE THAT IS NOT THREAD SAFE
static Pet* FindPet(uint64);
static Player* FindPlayer(uint64);
static Unit* FindUnit(uint64);
Player* FindPlayerByName(const char* name);
// when using this, you must use the hashmapholder's lock
HashMapHolder<Player>::MapType& GetPlayers()
{
return HashMapHolder<Player>::GetContainer();
}
template<class T> void AddObject(T* object)
{
HashMapHolder<T>::Insert(object);
}
template<class T> void RemoveObject(T* object)
{
HashMapHolder<T>::Remove(object);
}
void RemoveObject(Player* pl)
{
HashMapHolder<Player>::Remove(pl);
RemoveUpdateObject((Object*)pl);
}
void SaveAllPlayers();
void AddUpdateObject(Object* obj)
{
Guard guard(i_updateGuard);
i_objects.insert(obj);
}
void RemoveUpdateObject(Object* obj)
{
Guard guard(i_updateGuard);
i_objects.erase(obj);
}
void Update(uint32 diff);
Corpse* <API key>(uint64 guid);
void RemoveCorpse(Corpse* corpse);
void AddCorpse(Corpse* corpse);
void AddCorpsesToGrid(GridPair const& gridpair, GridType& grid, Map* map);
Corpse* <API key>(uint64 player_guid, bool insignia = false);
void RemoveOldCorpses();
typedef ACE_Thread_Mutex LockType;
typedef BlizzLike::GeneralLock<LockType> Guard;
private:
<API key> i_player2corpse;
static void <API key>(WorldObject*, UpdateDataMapType&);
static void _buildPacket(Player*, Object*, UpdateDataMapType&);
void _update();
std::set<Object*> i_objects;
LockType i_updateGuard;
LockType i_corpseGuard;
};
#endif
|
#include "stdafx.h"
#include <gtest/gtest.h>
#include "<API key>.h"
namespace PacMan
{
namespace Logic
{
namespace Tests
{
using namespace Logic;
void <API key> (
Row monster_row,
Column monster_column,
Row pacman_row,
Column pacman_column,
Heading expected )
{
// Arrange
<API key> sut{};
sut.monster_row = monster_row;
sut.monster_column = monster_column;
sut.pacman_row = pacman_row;
sut.pacman_column = pacman_column;
// Act
sut.calculate();
// Assert
Heading actual = sut.get_heading();
EXPECT_EQ(expected, actual);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{0},
Column{0},
Row{1},
Column{1},
Heading_Down);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{0},
Column{1},
Row{1},
Column{1},
Heading_Down);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{0},
Column{2},
Row{1},
Column{1},
Heading_Down);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{1},
Column{0},
Row{1},
Column{1},
Heading_Right);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{1},
Column{1},
Row{1},
Column{1},
Heading_Unknown);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{1},
Column{2},
Row{1},
Column{1},
Heading_Left);
}
TEST(<API key>, <API key>)
{
using namespace Logic;
<API key>(
Row{2},
Column{0},
Row{1},
Column{1},
Heading_Up);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{2},
Column{1},
Row{1},
Column{1},
Heading_Up);
}
TEST(<API key>, <API key>)
{
<API key>(
Row{2},
Column{2},
Row{1},
Column{1},
Heading_Up);
}
};
};
};
|
/** Created at: 4/30/2012 12:07:26 AM **/
#include<stdio.h>
int main()
{
int i,j,k,p,m,n,t;
while(scanf("%d",&t)==1)
{
for(i=1;i<=t;i++)
{
scanf("%d",&p);
if(p==2||p==3||p==5||p==7||p==13||p==17)
printf("Yes\n");
else
printf("No\n");
getchar();
}
}
return 0;
}
|
"""
Tests for closeness centrality.
"""
import pytest
import networkx as nx
from networkx.testing import almost_equal
class <API key>:
@classmethod
def setup_class(cls):
cls.K = nx.<API key>()
cls.P3 = nx.path_graph(3)
cls.P4 = nx.path_graph(4)
cls.K5 = nx.complete_graph(5)
cls.C4 = nx.cycle_graph(4)
cls.T = nx.balanced_tree(r=2, h=2)
cls.Gb = nx.Graph()
cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
F = nx.<API key>()
cls.F = F
cls.LM = nx.<API key>()
# Create random undirected, unweighted graph for testing incremental version
cls.undirected_G = nx.<API key>(n=100, p=0.6, seed=123)
cls.undirected_G_cc = nx.<API key>(cls.undirected_G)
def test_wf_improved(self):
G = nx.union(self.P4, nx.path_graph([4, 5, 6]))
c = nx.<API key>(G)
cwf = nx.<API key>(G, wf_improved=False)
res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222}
wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667}
for n in G:
assert almost_equal(c[n], res[n], places=3)
assert almost_equal(cwf[n], wf_res[n], places=3)
def test_digraph(self):
G = nx.path_graph(3, create_using=nx.DiGraph())
c = nx.<API key>(G)
cr = nx.<API key>(G.reverse())
d = {0: 0.0, 1: 0.500, 2: 0.667}
dr = {0: 0.667, 1: 0.500, 2: 0.0}
for n in sorted(self.P3):
assert almost_equal(c[n], d[n], places=3)
assert almost_equal(cr[n], dr[n], places=3)
def test_k5_closeness(self):
c = nx.<API key>(self.K5)
d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000}
for n in sorted(self.K5):
assert almost_equal(c[n], d[n], places=3)
def test_p3_closeness(self):
c = nx.<API key>(self.P3)
d = {0: 0.667, 1: 1.000, 2: 0.667}
for n in sorted(self.P3):
assert almost_equal(c[n], d[n], places=3)
def <API key>(self):
c = nx.<API key>(self.K)
d = {
0: 0.529,
1: 0.529,
2: 0.500,
3: 0.600,
4: 0.500,
5: 0.643,
6: 0.643,
7: 0.600,
8: 0.429,
9: 0.310,
}
for n in sorted(self.K):
assert almost_equal(c[n], d[n], places=3)
def <API key>(self):
c = nx.<API key>(self.F)
d = {
"Acciaiuoli": 0.368,
"Albizzi": 0.483,
"Barbadori": 0.4375,
"Bischeri": 0.400,
"Castellani": 0.389,
"Ginori": 0.333,
"Guadagni": 0.467,
"Lamberteschi": 0.326,
"Medici": 0.560,
"Pazzi": 0.286,
"Peruzzi": 0.368,
"Ridolfi": 0.500,
"Salviati": 0.389,
"Strozzi": 0.4375,
"Tornabuoni": 0.483,
}
for n in sorted(self.F):
assert almost_equal(c[n], d[n], places=3)
def <API key>(self):
c = nx.<API key>(self.LM)
d = {
"Napoleon": 0.302,
"Myriel": 0.429,
"MlleBaptistine": 0.413,
"MmeMagloire": 0.413,
"CountessDeLo": 0.302,
"Geborand": 0.302,
"Champtercier": 0.302,
"Cravatte": 0.302,
"Count": 0.302,
"OldMan": 0.302,
"Valjean": 0.644,
"Labarre": 0.394,
"Marguerite": 0.413,
"MmeDeR": 0.394,
"Isabeau": 0.394,
"Gervais": 0.394,
"Listolier": 0.341,
"Tholomyes": 0.392,
"Fameuil": 0.341,
"Blacheville": 0.341,
"Favourite": 0.341,
"Dahlia": 0.341,
"Zephine": 0.341,
"Fantine": 0.461,
"MmeThenardier": 0.461,
"Thenardier": 0.517,
"Cosette": 0.478,
"Javert": 0.517,
"Fauchelevent": 0.402,
"Bamatabois": 0.427,
"Perpetue": 0.318,
"Simplice": 0.418,
"Scaufflaire": 0.394,
"Woman1": 0.396,
"Judge": 0.404,
"Champmathieu": 0.404,
"Brevet": 0.404,
"Chenildieu": 0.404,
"Cochepaille": 0.404,
"Pontmercy": 0.373,
"Boulatruelle": 0.342,
"Eponine": 0.396,
"Anzelma": 0.352,
"Woman2": 0.402,
"MotherInnocent": 0.398,
"Gribier": 0.288,
"MmeBurgon": 0.344,
"Jondrette": 0.257,
"Gavroche": 0.514,
"Gillenormand": 0.442,
"Magnon": 0.335,
"MlleGillenormand": 0.442,
"MmePontmercy": 0.315,
"MlleVaubois": 0.308,
"LtGillenormand": 0.365,
"Marius": 0.531,
"BaronessT": 0.352,
"Mabeuf": 0.396,
"Enjolras": 0.481,
"Combeferre": 0.392,
"Prouvaire": 0.357,
"Feuilly": 0.392,
"Courfeyrac": 0.400,
"Bahorel": 0.394,
"Bossuet": 0.475,
"Joly": 0.394,
"Grantaire": 0.358,
"MotherPlutarch": 0.285,
"Gueulemer": 0.463,
"Babet": 0.463,
"Claquesous": 0.452,
"Montparnasse": 0.458,
"Toussaint": 0.402,
"Child1": 0.342,
"Child2": 0.342,
"Brujon": 0.380,
"MmeHucheloup": 0.353,
}
for n in sorted(self.LM):
assert almost_equal(c[n], d[n], places=3)
def <API key>(self):
edges = [
("s", "u", 10),
("s", "x", 5),
("u", "v", 1),
("u", "x", 2),
("v", "y", 1),
("x", "u", 3),
("x", "v", 5),
("x", "y", 2),
("y", "s", 7),
("y", "v", 6),
]
XG = nx.Graph()
XG.<API key>(edges)
c = nx.<API key>(XG, distance="weight")
d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200}
for n in sorted(XG):
assert almost_equal(c[n], d[n], places=3)
# Tests for incremental closeness centrality.
@staticmethod
def pick_add_edge(g):
u = nx.utils.arbitrary_element(g)
possible_nodes = set(g.nodes())
neighbors = list(g.neighbors(u)) + [u]
possible_nodes.difference_update(neighbors)
v = nx.utils.arbitrary_element(possible_nodes)
return (u, v)
@staticmethod
def pick_remove_edge(g):
u = nx.utils.arbitrary_element(g)
possible_nodes = list(g.neighbors(u))
v = nx.utils.arbitrary_element(possible_nodes)
return (u, v)
def <API key>(self):
with pytest.raises(nx.<API key>):
dir_G = nx.gn_graph(n=5)
prev_cc = None
edge = self.pick_add_edge(dir_G)
insert = True
nx.<API key>(dir_G, edge, prev_cc, insert)
def <API key>(self):
with pytest.raises(nx.NetworkXError):
G = self.undirected_G.copy()
edge = self.pick_add_edge(G)
insert = True
prev_cc = self.undirected_G_cc.copy()
prev_cc.pop(0)
nx.<API key>(G, edge, prev_cc, insert)
def <API key>(self):
with pytest.raises(nx.NetworkXError):
G = self.undirected_G.copy()
edge = self.pick_add_edge(G)
insert = True
prev_cc = self.undirected_G_cc.copy()
num_nodes = len(prev_cc)
prev_cc.pop(0)
prev_cc[num_nodes] = 0.5
nx.<API key>(G, edge, prev_cc, insert)
def <API key>(self):
G = nx.path_graph(3)
prev_cc = nx.<API key>(G)
edge = self.pick_remove_edge(G)
test_cc = nx.<API key>(G, edge, prev_cc, insertion=False)
G.remove_edges_from([edge])
real_cc = nx.<API key>(G)
shared_items = set(test_cc.items()) & set(real_cc.items())
assert len(shared_items) == len(real_cc)
assert 0 in test_cc.values()
def test_incremental(self):
# Check that incremental and regular give same output
G = self.undirected_G.copy()
prev_cc = None
for i in range(5):
if i % 2 == 0:
# Remove an edge
insert = False
edge = self.pick_remove_edge(G)
else:
# Add an edge
insert = True
edge = self.pick_add_edge(G)
# start = timeit.default_timer()
test_cc = nx.<API key>(G, edge, prev_cc, insert)
# inc_elapsed = (timeit.default_timer() - start)
# print(f"incremental time: {inc_elapsed}")
if insert:
G.add_edges_from([edge])
else:
G.remove_edges_from([edge])
# start = timeit.default_timer()
real_cc = nx.<API key>(G)
# reg_elapsed = (timeit.default_timer() - start)
# print(f"regular time: {reg_elapsed}")
# Example output:
# incremental time: 0.208
# regular time: 0.276
# incremental time: 0.00683
# regular time: 0.260
# incremental time: 0.0224
# regular time: 0.278
# incremental time: 0.00804
# regular time: 0.208
# incremental time: 0.00947
# regular time: 0.188
assert set(test_cc.items()) == set(real_cc.items())
prev_cc = test_cc
|
package au.com.houliston.jsonfl;
/**
* Is thrown when the creation string for the JsonFL is invalid
*
* @author Trent Houliston
* @version 1.0
*/
public class <API key> extends Exception
{
/**
* Creates a new <API key> with the passed message
*
* @param message The message to set
*/
public <API key>(String message)
{
super(message);
}
/**
* Creates a new <API key> along with a message and a cause
*
* @param message The message to set
* @param cause The root cause which made this exception
*/
public <API key>(String message, Throwable cause)
{
super(message, cause);
}
}
|
package edu.kit.iti.formal.mandatsverteilung.generierer;
import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl;
public class <API key> extends Einschraenkung {
public <API key>(int wert, int abweichung) {
assert wert > 0;
assert abweichung > 0;
this.wert = wert;
this.abweichung = abweichung;
gewichtung = 1.0;
}
@Override
int ueberpruefeErgebnis(Bundestagswahl b) {
int <API key> = b.getSitzzahl();
int genauigkeit = <API key>.getGenauigkeit();
double minD = (minDistance(genauigkeit * <API key>,
genauigkeit * wert, genauigkeit * abweichung));
return (int) (gewichtung * minD);
}
}
|
#include "definitions.h"
CustomWeakForm::CustomWeakForm(std::vector<std::string> newton_boundaries, double heatcap, double rho, double tau,
double lambda, double alpha, double temp_ext, <API key><double> sln_prev_time, bool JFNK) : WeakForm<double>(1, JFNK)
{
this->set_ext(sln_prev_time);
// Jacobian forms - volumetric.
add_matrix_form(new JacobianFormVol(0, 0, heatcap, rho, lambda, tau));
// Jacobian forms - surface.
<API key>(new JacobianFormSurf(0, 0, newton_boundaries, alpha, lambda));
// Residual forms - volumetric.
ResidualFormVol* res_form = new ResidualFormVol(0, heatcap, rho, lambda, tau);
add_vector_form(res_form);
// Residual forms - surface.
<API key>(new ResidualFormSurf(0, newton_boundaries, alpha, lambda, temp_ext));
}
double CustomWeakForm::JacobianFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (heatcap * rho * u->val[i] * v->val[i] / tau
+ lambda * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
return result;
}
Ord CustomWeakForm::JacobianFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the basis and test function plus two.
return Ord(10);
}
MatrixFormVol<double>* CustomWeakForm::JacobianFormVol::clone() const
{
return new CustomWeakForm::JacobianFormVol(*this);
}
double CustomWeakForm::JacobianFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * alpha * lambda * u->val[i] * v->val[i];
return result;
}
Ord CustomWeakForm::JacobianFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the basis and test function plus two.
return Ord(10);
}
MatrixFormSurf<double>* CustomWeakForm::JacobianFormSurf::clone() const
{
return new CustomWeakForm::JacobianFormSurf(*this);
}
double CustomWeakForm::ResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (heatcap * rho * (u_ext[0]->val[i] - ext[0]->val[i]) * v->val[i] / tau
+ lambda * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i]));
return result;
}
Ord CustomWeakForm::ResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the test function and solution plus two.
return Ord(10);
}
VectorFormVol<double>* CustomWeakForm::ResidualFormVol::clone() const
{
return new CustomWeakForm::ResidualFormVol(*this);
}
double CustomWeakForm::ResidualFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomSurf<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * alpha * lambda * (u_ext[0]->val[i] - temp_ext) * v->val[i];
return result;
}
Ord CustomWeakForm::ResidualFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the test function and solution plus two.
return Ord(10);
}
VectorFormSurf<double>* CustomWeakForm::ResidualFormSurf::clone() const
{
return new CustomWeakForm::ResidualFormSurf(*this);
}
|
# <API key>: true
RSpec.shared_examples 'vcs: having remote' do
describe '#remote' do
it 'sets @remote' do
object.remote = 'some-value'
expect(object.<API key>(:@remote)).to eq 'some-value'
end
end
describe '#remote' do
subject(:remote) { object.remote }
let(:remote_class) { object.send(:remote_class) }
before do
allow(object).to receive(:remote_file_id).and_return 'remote-id'
allow(remote_class).to receive(:new).and_return 'new-instance'
hook if defined?(hook)
object.remote
end
it 'returns an instance of remote class' do
expect(remote_class).to have_received(:new).with('remote-id')
end
it 'sets @remote to new instance' do
expect(object.<API key>(:@remote)).to eq 'new-instance'
end
context 'when @remote is already set' do
let(:hook) { object.<API key>(:@remote, 'existing-value') }
it { is_expected.to eq 'existing-value' }
end
end
describe '#reload' do
before do
allow(object).to receive(:reset_remote)
allow(object.class).to receive(:find)
object.reload
end
it { expect(object).to have_received(:reset_remote) }
it 'reloads the object from database' do
expect(object.class).to have_received(:find)
end
end
describe '#reset_remote' do
subject(:reset_remote) { object.send(:reset_remote) }
before do
object.<API key>(:@remote, 'some-value')
end
it 'resets @remote to nil' do
reset_remote
expect(object.<API key>(:@remote)).to eq nil
end
end
describe '#remote_class' do
subject { object.send(:remote_class) }
it { is_expected.to eq Providers::GoogleDrive::FileSync }
end
end
|
// NOTE: nbApp is defined in app.js
nbApp.directive("<API key>", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: {
color: "@",
language: "@",
reading: "@",
writing: "@",
listening: "@",
speaking: "@",
flag: "@",
},
link: function(scope, element, attrs) {
scope.color = attrs.color;
scope.language = attrs.language;
scope.reading = attrs.reading;
scope.writing = attrs.writing;
scope.listening = attrs.listening;
scope.speaking = attrs.speaking;
scope.flag = attrs.flag;
scope.$watch('language', function(nV, oV) {
if(nV){
RadarChart.defaultConfig.color = function() {};
RadarChart.defaultConfig.radius = 3;
RadarChart.defaultConfig.w = 250;
RadarChart.defaultConfig.h = 250;
/*
* 0 - No Practical Proficiency
* 1 - Elementary Proficiency
* 2 - Limited Working Proficiency
* 3 - Minimum Professional Proficiency
* 4 - Full Professional Proficiency
* 5 - Native or Bilingual Proficiency
Read: the ability to read and understand texts written in the language
Write: the ability to formulate written texts in the language
Listen: the ability to follow and understand speech in the language
Speak: the ability to produce speech in the language and be understood by its speakers.
*/
var data = [
{
className: attrs.language, // optional can be used for styling
axes: [
{axis: "Reading", value: attrs.reading},
{axis: "Writing", value: attrs.writing},
{axis: "Listening", value: attrs.listening},
{axis: "Speaking", value: attrs.speaking},
]
},
];
function mapData() {
return data.map(function(d) {
return {
className: d.className,
axes: d.axes.map(function(axis) {
return {axis: axis.axis, value: axis.value};
})
};
});
}
// chart.config.w;
// chart.config.h;
// chart.config.axisText = true;
// chart.config.levels = 5;
// chart.config.maxValue = 5;
// chart.config.circles = true;
// chart.config.actorLegend = 1;
var chart = RadarChart.chart();
var cfg = chart.config(); // retrieve default config
cfg = chart.config({axisText: true, levels: 5, maxValue: 5, circles: true}); // retrieve default config
var svg = d3.select('.' + attrs.language).append('svg')
.attr('width', 250)
.attr('height', 270);
svg.append('g').classed('single', 1).datum(mapData()).call(chart);
console.log('Rendering new language Radar Viz! --> ' + attrs.language);
}
})
}
};
});
|
/*! return transposed _dsymatrix */
inline _dsymatrix t(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
#ifdef CPPL_DEBUG
WARNING_REPORT;
std::cerr << "This function call has no effect since the matrix is symmetric." << std::endl;
#endif//CPPL_DEBUG
return mat;
}
/*! return its inverse matrix */
inline _dsymatrix i(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix mat_cp(mat);
dsymatrix mat_inv(mat_cp.n);
mat_inv.identity();
char UPLO('l');
CPPL_INT NRHS(mat.n), LDA(mat.n), *IPIV(new CPPL_INT[mat.n]), LDB(mat.n), LWORK(-1), INFO(1);
double *WORK( new double[1] );
dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO);
LWORK = CPPL_INT(WORK[0]);
delete [] WORK;
WORK = new double[LWORK];
dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO);
delete [] WORK;
delete [] IPIV;
if(INFO!=0){
WARNING_REPORT;
std::cerr << "Serious trouble happend. INFO = " << INFO << "." << std::endl;
}
return _(mat_inv);
}
/*! search the index of element having the largest absolute value
in 0-based numbering system */
inline void idamax(CPPL_INT& i, CPPL_INT& j, const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix newmat =mat;
idamax(i, j, newmat);
}
/*! return its largest absolute value */
inline double damax(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix newmat =mat;
return damax(newmat);
}
|
package name.parsak.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import name.parsak.api.Tcpip;
import name.parsak.dto.UsrDptRole;
import name.parsak.model.Department;
import name.parsak.model.Menu;
import name.parsak.model.Role;
import name.parsak.model.User;
import name.parsak.service.UserDBService;
@Controller
public class WebController {
final private String project_name = "JWC";
final private String user_cookie_name = "user";
final private String blank = "";
final private int max_login_time = 7200;
private UserDBService userDBService;
@Autowired(required=true)
@Qualifier(value="UserDBService")
public void setUserDBService(UserDBService us){
this.userDBService = us;
}
// Create Admin User, if it doesn't exist
@RequestMapping(value="setup")
public String setup() {
this.userDBService.setup();
return "redirect:/";
}
// Default page
@RequestMapping({"/", "index"})
public String index(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@ModelAttribute(project_name)Menu menu) {
if (! userid.equals(blank)) {
int id = Integer.parseInt(userid);
User user = this.userDBService.getUserById(id);
if (user != null) {
model.addAttribute("id", userid);
model.addAttribute("name", user.getName());
model.addAttribute("lastname", user.getLastname());
model.addAttribute("email", user.getEmail());
if (this.userDBService.isUserAdmin(user)) {
model.addAttribute("admin", "true");
}
try {
String name = menu.getName();
if (name != null) {
this.userDBService.AddMenu(menu);
}
} catch (<API key> e) {}
// menu.id is used to browse
long menuid = menu.getId();
model.addAttribute("menu", this.userDBService.getMenuDtoById(menuid));
model.addAttribute("parent", menuid);
model.addAttribute("menulist", this.userDBService.getMenuByParent(menuid));
}
}
return "index";
}
// Login User
@RequestMapping(value="login")
public String login(
Model model, @ModelAttribute(project_name)User u,
HttpServletResponse response) {
Long userid = u.getId();
// In case user enters /login without submitting a login form
if (userid != 0) {
User user = this.userDBService.getUser(u.getId(), u.getPassword());
if (user != null) {
Cookie cookie = new Cookie(user_cookie_name, String.valueOf(user.getId()));
cookie.setMaxAge(max_login_time);
response.addCookie(cookie);
}
}
return "redirect:/";
}
// Logout User
@RequestMapping(value="logout")
public String logout(
HttpServletResponse response) {
Cookie cookie = new Cookie(user_cookie_name,blank);
cookie.setMaxAge(0);
response.addCookie(cookie);
return "redirect:/";
}
// Display All Users
@RequestMapping(value="users")
public String users(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
model.addAttribute("userslist", this.userDBService.listUsers());
return "users";
}
}
}
return "redirect:/";
}
// Display All Departments
@RequestMapping(value="departments")
public String departments(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
model.addAttribute("deptlist", this.userDBService.listDepartments());
model.addAttribute("rolelist", this.userDBService.listRoles());
return "departments";
}
}
}
return "redirect:/";
}
@RequestMapping(value="department")
public String department(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@ModelAttribute(project_name)UsrDptRole usrdptrole){
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
String DeptName = usrdptrole.getDeptname();
System.out.println(">> Displaying "+DeptName);
Department department = this.userDBService.getDepartmentByName(DeptName);
model.addAttribute("department", department.getDepartment_name());
model.addAttribute("deptrolelist", this.userDBService.getDepartmentUsers(department));
return "department";
}
}
}
return "redirect:/";
}
@RequestMapping(value="add_user")
public String add_user(
Model model,
@ModelAttribute(project_name)User user,
HttpServletResponse response) {
String user_name = null;
String user_lastname = null;
String user_email = null;
String user_password = null;
try {
user_name = user.getName();
user_lastname = user.getLastname();
user_email = user.getEmail();
user_password = user.getPassword();
} catch (<API key> e) {}
if (user_name != null && user_lastname != null && user_email != null && user_password != null) {
this.userDBService.addUser(user);
}
return "redirect:/users";
}
@RequestMapping(value="update_user")
public String update_user(
Model model,
@ModelAttribute(project_name)User user,
HttpServletResponse response) {
String user_name = null;
String user_lastname = null;
String user_email = null;
String user_password = null;
try {
user_name = user.getName();
user_lastname = user.getLastname();
user_email = user.getEmail();
user_password = user.getPassword();
} catch (<API key> e) {}
if (user_name != null && user_lastname != null && user_email != null && user_password != null) {
this.userDBService.updateUser(user);
}
return "redirect:/user"+user.getId();
}
// Assign UserRole to a user
@RequestMapping(value="add_user_role")
public String AddUserRole(@ModelAttribute(project_name)UsrDptRole usrdptrole) {
String deptname = usrdptrole.getDeptname();
String rolename = usrdptrole.getRolename();
long userid = usrdptrole.getUserid();
if (userid != 0 && !deptname.equals(blank) && !rolename.equals(blank)) {
User user = this.userDBService.getUserById((int) userid);
Department department = this.userDBService.getDepartmentByName(deptname);
Role role = this.userDBService.getRoleByName(rolename);
this.userDBService.AddUserRole(user, department, role);
}
return "redirect:/user"+userid;
}
@RequestMapping(value="remove_userrole")
public String RemoveUserRole(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.removeUserRoleById(deptrole.getId());
return "redirect:/user"+deptrole.getUserid();
}
// Display User{id}
@RequestMapping(value="/user{id}")
public String user(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@PathVariable("id") int id) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
User user = this.userDBService.getUserById(id);
model.addAttribute("userid",user.getId());
model.addAttribute("name",user.getName());
model.addAttribute("lastname",user.getLastname());
model.addAttribute("email",user.getEmail());
model.addAttribute("User", user); // To populate Edit Form
model.addAttribute("deptrolelist",this.userDBService.getUsrDptRoles(user));
model.addAttribute("deptlist", this.userDBService.listDepartments());
model.addAttribute("rolelist", this.userDBService.listRoles());
return "user";
}
}
}
return "redirect:/";
}
// Remove User{id}
@RequestMapping(value="/removeuser{id}")
public String removeuser(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@PathVariable("id") int id) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
User user = this.userDBService.getUserById(id);
this.userDBService.<API key>(user);
this.userDBService.removeUser(user);
return "redirect:/users";
}
}
}
return "redirect:/";
}
@RequestMapping(value="/add_department")
public String addNewDepartment(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.AddDepartment(deptrole.getDeptname());
return "redirect:/departments";
}
@RequestMapping(value="/add_role")
public String addNewRole(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.AddRole(deptrole.getRolename());
return "redirect:/departments";
}
@RequestMapping(value="/api_test")
public String test_api(Model model) {
Tcpip tcpip = new Tcpip();
String response = tcpip.get("http:
model.addAttribute("response", response);
return "api_test";
}
}
|
#pragma once
// njhseq - A library for analyzing sequence data
// This file is part of njhseq.
// njhseq is free software: you can redistribute it and/or modify
// (at your option) any later version.
// njhseq is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// alnInfoHolder.hpp
#include "njhseq/alignment/alnCache/alnInfoHolderBase.hpp"
#if __APPLE__ == 1 && <API key> < 201402L && <API key> <= 101106
#include <sharedMutex.h>
#else
#include <shared_mutex>
#endif
namespace njhseq {
class alnInfoMasterHolder {
public:
// constructors
alnInfoMasterHolder();
alnInfoMasterHolder(const <API key> & gapPars,
const substituteMatrix & scoringArray);
alnInfoMasterHolder(const std::string &masterDirName, const <API key> & gapPars,
const substituteMatrix & scoringArray, bool verbose = false);
// members
std::unordered_map<std::string, alnInfoHolderBase<alnInfoLocal>> localHolder_;
std::unordered_map<std::string, alnInfoHolderBase<alnInfoGlobal>> globalHolder_;
std::hash<std::string> strH_;
void clearHolders();
void addHolder(const <API key> & gapPars,
const substituteMatrix & scoringArray);
// reading
void read(const std::string &masterDirName, bool verbose = false);
// writing
void write(const std::string &masterDirName, bool verbose = false);
void mergeOtherHolder(const alnInfoMasterHolder & otherHolder);
};
namespace alignment {
static std::mutex <API key>;
static std::unordered_map<std::string, std::unique_ptr<std::shared_timed_mutex>> alnCacheDirLocks;
} // namespace alignment
} // namespace njhseq
|
#include "common_header.h"
namespace {
using ArrayType = std::vector<int>;
auto <API key>(const ArrayType &elements,
const ArrayType::value_type x) {
assert(std::is_sorted(elements.cbegin(), elements.cend()));
auto diff = std::numeric_limits<ArrayType::value_type>::max();
std::pair<ArrayType::value_type, ArrayType::value_type> output;
if (not elements.empty()) {
auto left = elements.cbegin();
auto right = std::prev(elements.cend());
while (left != right and diff) {
const auto sum = *left + *right;
const auto new_diff = std::abs(sum - x);
if (new_diff < diff) {
diff = new_diff;
output = std::pair(*left, *right);
}
if (sum < x) {
++left;
} else {
--right;
}
}
}
return output;
}
inline auto
ClosestSumPair_Sort(ArrayType elements, const ArrayType::value_type x) {
std::sort(elements.begin(), elements.end());
return <API key>(elements, x);
}
auto ThreeSum(ArrayType nums, const int target) {
std::sort(nums.begin(), nums.end());
int min_diff = INT_MAX;
int result = 0;
for (std::size_t i = 0; i < nums.size() and min_diff; ++i) {
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
const int sum = nums[i] + nums[left] + nums[right];
if (std::abs(target - sum) < min_diff) {
min_diff = std::abs(target - sum);
result = sum;
}
if (sum < target) {
++left;
} else {
--right;
}
}
}
return result;
}
auto TwoSumLessThan(ArrayType nums, const int K) {
std::sort(nums.begin(), nums.end());
int left = 0;
int right = nums.size() - 1;
int result = -1;
while (left < right) {
const auto sum = nums[left] + nums[right];
if (sum >= K) {
--right;
} else {
result = std::max(result, sum);
++left;
}
}
return result;
}
}//namespace
const ArrayType SAMPLE1 = {10, 22, 28, 29, 30, 40};
const ArrayType SAMPLE2 = {1, 3, 4, 7, 10};
const ArrayType SAMPLE3 = {1, 60, -10, 70, -80, 85};
THE_BENCHMARK(<API key>, SAMPLE1, 54);
SIMPLE_TEST(<API key>, TestSample1, std::pair(22, 30),
SAMPLE1, 54);
SIMPLE_TEST(<API key>, TestSample2, std::pair(4, 10),
SAMPLE2, 15);
SIMPLE_TEST(ClosestSumPair_Sort, TestSample3, std::pair(-80, 85), SAMPLE3, 0);
const ArrayType SAMPLE4 = {-1, 2, 1, -4};
THE_BENCHMARK(ThreeSum, SAMPLE4, 1);
SIMPLE_TEST(ThreeSum, TestSample4, 2, SAMPLE4, 1);
const ArrayType SAMPLE1L = {34, 23, 1, 24, 75, 33, 54, 8};
const ArrayType SAMPLE2L = {10, 20, 30};
THE_BENCHMARK(TwoSumLessThan, SAMPLE1L, 60);
SIMPLE_TEST(TwoSumLessThan, TestSample1, 58, SAMPLE1L, 60);
SIMPLE_TEST(TwoSumLessThan, TestSample2, -1, SAMPLE2L, 15);
|
module XmlResolution
# Most named exceptions in the XmlResolution service we subclass here
# to one of the HTTP classes. Libraries are designed specifically
# to be unaware of this mapping: they only use their specific low level
# exceptions classes.
# In general, if we catch an HttpError at our top level app, we can
# blindly return the error message to the client as a diagnostic,
# and log it. The fact that we're naming these exceptions means
# we're being careful not to leak information, and still be helpful
# to the Client. They are very specific messages; tracebacks will
# not be required.
# When we get an un-named exception, however, the appropriate thing
# to do is to just supply a very terse message to the client (e.g.,
# we wouldn't like to expose errors from an ORM that said something
# like "password 'topsecret' failed in mysql open"). We *will* want
# to log the full error message, and probably a backtrace to boot.
class HttpError < StandardError;
def client_message
"#{status_code} #{status_text} - #{message.chomp('.')}."
end
end
# Most of the following comments are pretty darn obvious - they
# are included for easy navigation in the generated rdoc html files.
# Http400Error's group named exceptions as something the client did
# wrong. It is subclassed from the HttpError exception.
class Http400Error < HttpError; end
# Http400 exception: 400 Bad Request - it is subclassed from Http400Error.
class Http400 < Http400Error
def status_code; 400; end
def status_text; "Bad Request"; end
end
# Http401 exception: 401 Unauthorized - it is subclassed from Http400Error.
class Http401 < Http400Error
def status_code; 401; end
def status_text; "Unauthorized"; end
end
# Http403 exception: 403 Forbidden - it is subclassed from Http400Error.
class Http403 < Http400Error
def status_code; 403; end
def status_text; "Forbidden"; end
end
# Http404 exception: 404 Not Found - it is subclassed from Http400Error.
class Http404 < Http400Error
def status_code; 404; end
def status_text; "Not Found"; end
end
# Http405 exception: 405 Method Not Allowed - it is subclassed from Http400Error.
class Http405 < Http400Error
def status_code; 405; end
def status_text; "Method Not Allowed"; end
end
# Http406 exception: 406 Not Acceptable - it is subclassed from Http400Error.
class Http406 < Http400Error
def status_code; 406; end
def status_text; "Not Acceptable"; end
end
# Http408 exception: 408 Request Timeout - it is subclassed from Http400Error.
class Http408 < Http400Error
def status_code; 408; end
def status_text; "Request Timeout"; end
end
# Http409 exception: 409 Conflict - it is subclassed from Http400Error.
class Http409 < Http400Error
def status_code; 409; end
def status_text; "Conflict"; end
end
# Http410 exception: 410 Gone - it is subclassed from Http400Error.
class Http410 < Http400Error
def status_code; 410; end
def status_text; "Gone"; end
end
# Http411 exception: 411 Length Required - it is subclassed from Http400Error.
class Http411 < Http400Error
def status_code; 411; end
def status_text; "Length Required"; end
end
# Http412 exception: 412 Precondition Failed - it is subclassed from Http400Error.
class Http412 < Http400Error
def status_code; 412; end
def status_text; "Precondition Failed"; end
end
# Http413 exception: 413 Request Entity Too Large - it is subclassed from Http400Error.
class Http413 < Http400Error
def status_code; 413; end
def status_text; "Request Entity Too Large"; end
end
# Http414 exception: 414 Request-URI Too Long - it is subclassed from Http400Error.
class Http414 < Http400Error
def status_code; 414; end
def status_text; "Request-URI Too Long"; end
end
# Http415 exception: 415 Unsupported Media Type - it is subclassed from Http400Error.
class Http415 < Http400Error
def status_code; 415; end
def status_text; "Unsupported Media Type"; end
end
# Http500Error's group errors that are the server's fault.
# It is subclassed from the HttpError exception.
class Http500Error < HttpError; end
# Http500 exception: 500 Internal Service Error - it is subclassed from Http500Error.
class Http500 < Http500Error
def status_code; 500; end
def status_text; "Internal Service Error"; end
end
# Http501 exception: 501 Not Implemented - it is subclassed from Http500Error.
class Http501 < Http500Error
def status_code; 501; end
def status_text; "Not Implemented"; end
end
# Http503 exception: 503 Service Unavailable - it is subclassed from Http500Error.
class Http503 < Http500Error
def status_code; 503; end
def status_text; "Service Unavailable"; end
end
# Http505 exception: 505 HTTP Version Not Supported - it is subclassed from Http500Error.
class Http505 < Http500Error
def status_code; 505; end
def status_text; "HTTP Version Not Supported"; end
end
# BadXmlDocument exception, client's fault (subclasses Http400): Instance document could not be parsed..
class BadXmlDocument < Http415; end
# BadBadXmlDocument exception, client's fault (subclasses BadXmlDocument): ..it *really* could not be parsed
class BadBadXmlDocument < BadXmlDocument; end
# InadequateDataError exception, client's fault (subclasses Http400): Problem with uploaded data (e.g. length 0)
class InadequateDataError < Http400; end
# BadCollectionID exception, client's fault (subclasses Http400): PUT of a Collection ID wasn't suitable
class BadCollectionID < Http400; end
# BadXmlVersion exception, client's fault (subclasses Http415): Unsupported XML version (only 1.0)
class BadXmlVersion < Http415; end
# TooManyDarnSchemas exception, client's fault (subclasses Http400): Possible denial of service - infinite train of schemas
class TooManyDarnSchemas < Http400; end
# LockError exception, server's fault (subclasses Http500): Timed out trying to get a locked file
class LockError < Http500; end
# ConfigurationError exception, server's fault (subclasses Http500): Something wasn't set up correctly
class ConfigurationError < Http500; end
# ResolverError exception, server's fault (subclasses Http500): Result of a programming error
class ResolverError < Http500; end
# The LocationError is caught internally, and is used to indicate that
# the fetch of a Schema could not be performed because the location
# URL scheme was not supported. This results in reporting broken
# link, and is normally not very important: there are many other
# schemas to report on.
# However, if this exception was raised to the top level, we do
# not want to pass the information to the user. That's why it is not
# assigned to an HttpError subclass - we *want* a logged backtrace in
# that case.
class LocationError < StandardError; end
end # of module
|
//krazy:excludeall=qclasses
// Qt-only library, so things like QUrl *should* be used
#include "package.h"
// Qt includes
#include <QtCore/QFile>
#include <QtCore/QStringBuilder>
#include <QtCore/QStringList>
#include <QtCore/QTemporaryFile>
#include <QtCore/QTextStream>
#include <QDebug>
// Apt includes
#include <apt-pkg/algorithms.h>
#include <apt-pkg/debversion.h>
#include <apt-pkg/depcache.h>
#include <apt-pkg/indexfile.h>
#include <apt-pkg/init.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/tagfile.h>
#include <apt-pkg/versionmatch.h>
#include <algorithm>
// Own includes
#include "backend.h"
#include "cache.h"
#include "config.h" // krazy:exclude=includes
#include "markingerrorinfo.h"
namespace QApt {
class PackagePrivate
{
public:
PackagePrivate(pkgCache::PkgIterator iter, Backend *back)
: packageIter(iter)
, backend(back)
, state(0)
, <API key>(false)
, <API key>(false)
{
}
~PackagePrivate()
{
}
pkgCache::PkgIterator packageIter;
QApt::Backend *backend;
int state;
bool <API key>;
bool isForeignArch;
bool <API key>;
pkgCache::PkgFileIterator searchPkgFileIter(QLatin1String label, const QString &release) const;
QString <API key>(QLatin1String label, const QString &release) const;
// Calculate state flags that cannot change
void initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache);
};
pkgCache::PkgFileIterator PackagePrivate::searchPkgFileIter(QLatin1String label, const QString &release) const
{
pkgCache::VerIterator verIter = packageIter.VersionList();
pkgCache::VerFileIterator verFileIter;
pkgCache::PkgFileIterator found;
while (!verIter.end()) {
for (verFileIter = verIter.FileList(); !verFileIter.end(); ++verFileIter) {
for(found = verFileIter.File(); !found.end(); ++found) {
const char *verLabel = found.Label();
const char *verOrigin = found.Origin();
const char *verArchive = found.Archive();
if (verLabel && verOrigin && verArchive) {
if(verLabel == label && verOrigin == label &&
QLatin1String(verArchive) == release) {
return found;
}
}
}
}
++verIter;
}
found = pkgCache::PkgFileIterator(*packageIter.Cache());
return found;
}
QString PackagePrivate::<API key>(QLatin1String label, const QString &release) const
{
pkgCache::PkgFileIterator pkg = searchPkgFileIter(label, release);
// Return empty if no package matches the given label and release
if (pkg.end())
return QString();
// Search for the matching meta-index
pkgSourceList *list = backend->packageSourceList();
pkgIndexFile *index;
// Return empty if the source list doesn't contain an index for the package
if (!list->FindIndex(pkg, index))
return QString();
for (auto I = list->begin(); I != list->end(); ++I) {
vector<pkgIndexFile *> *ifv = (*I)->GetIndexFiles();
if (find(ifv->begin(), ifv->end(), index) == ifv->end())
continue;
// Construct release file path
QString uri = backend->config()->findDirectory("Dir::State::lists")
% QString::fromStdString(URItoFileName((*I)->GetURI()))
% QLatin1String("dists_")
% QString::fromStdString((*I)->GetDist())
% QLatin1String("_Release");
return uri;
}
return QString();
}
void PackagePrivate::initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache)
{
int packageState = 0;
if (!ver.end()) {
// Set flags exclusive to installed packages
packageState |= QApt::Package::Installed;
if (stateCache.CandidateVer && stateCache.Upgradable()) {
packageState |= QApt::Package::Upgradeable;
if (stateCache.Keep())
packageState |= QApt::Package::Held;
}
} else
packageState |= QApt::Package::NotInstalled;
// Broken/garbage statuses are constant until a cache reload
if (stateCache.NowBroken()) {
packageState |= QApt::Package::NowBroken;
}
if (stateCache.InstBroken()) {
packageState |= QApt::Package::InstallBroken;
}
if (stateCache.Garbage) {
packageState |= QApt::Package::IsGarbage;
}
if (stateCache.NowPolicyBroken()) {
packageState |= QApt::Package::NowPolicyBroken;
}
if (stateCache.InstPolicyBroken()) {
packageState |= QApt::Package::InstallPolicyBroken;
}
// Essential/important status can only be changed by cache reload
if (packageIter->Flags & (pkgCache::Flag::Important |
pkgCache::Flag::Essential)) {
packageState |= QApt::Package::IsImportant;
}
if (packageIter->CurrentState == pkgCache::State::ConfigFiles) {
packageState |= QApt::Package::ResidualConfig;
}
// Packages will stay undownloadable until a sources file is refreshed
// and the cache is reloaded.
bool downloadable = true;
if (!stateCache.CandidateVer ||
stateCache.CandidateVerIter(*backend->cache()->depCache()).Downloadable())
downloadable = false;
if (!downloadable)
packageState |= QApt::Package::NotDownloadable;
state |= packageState;
<API key> = true;
}
Package::Package(QApt::Backend* backend, pkgCache::PkgIterator &packageIter)
: d(new PackagePrivate(packageIter, backend))
{
}
Package::~Package()
{
delete d;
}
const pkgCache::PkgIterator &Package::packageIterator() const
{
return d->packageIter;
}
QLatin1String Package::name() const
{
return QLatin1String(d->packageIter.Name());
}
int Package::id() const
{
return d->packageIter->ID;
}
QLatin1String Package::section() const
{
return QLatin1String(d->packageIter.Section());
}
QString Package::sourcePackage() const
{
QString sourcePackage;
// In the APT package record format, the only time when a "Source:" field
// is present is when the binary package name doesn't match the source
// name
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
sourcePackage = QString::fromStdString(rec.SourcePkg());
}
// If the package record didn't have a "Source:" field, then this package's
// name must be the source package's name. (Or there isn't a record for this package)
if (sourcePackage.isEmpty()) {
sourcePackage = name();
}
return sourcePackage;
}
QString Package::shortDescription() const
{
QString shortDescription;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgCache::DescIterator Desc = ver.<API key>();
pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList());
shortDescription = QString::fromUtf8(parser.ShortDesc().data());
return shortDescription;
}
return shortDescription;
}
QString Package::longDescription() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
QString rawDescription;
pkgCache::DescIterator Desc = ver.<API key>();
pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList());
rawDescription = QString::fromUtf8(parser.LongDesc().data());
// Apt acutally returns the whole description, we just want the
// extended part.
rawDescription.remove(shortDescription() % '\n');
// *Now* we're really raw. Sort of. ;)
QString parsedDescription;
// Split at double newline, by "section"
QStringList sections = rawDescription.split(QLatin1String("\n ."));
for (int i = 0; i < sections.count(); ++i) {
sections[i].replace(QRegExp(QLatin1String("\n( |\t)+(-|\\*)")),
QLatin1Literal("\n\r ") % QString::fromUtf8("\xE2\x80\xA2"));
// There should be no new lines within a section.
sections[i].remove(QLatin1Char('\n'));
// Hack to get the lists working again.
sections[i].replace(QLatin1Char('\r'), QLatin1Char('\n'));
// Merge multiple whitespace chars into one
sections[i].replace(QRegExp(QLatin1String("\\ \\ +")), QChar::fromLatin1(' '));
// Remove the initial whitespace
sections[i].remove(0, 1);
// Append to parsedDescription
if (sections[i].startsWith(QLatin1String("\n ") % QString::fromUtf8("\xE2\x80\xA2 ")) || !i) {
parsedDescription += sections[i];
} else {
parsedDescription += QLatin1Literal("\n\n") % sections[i];
}
}
return parsedDescription;
}
return QString();
}
QString Package::maintainer() const
{
QString maintainer;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList());
maintainer = QString::fromUtf8(parser.Maintainer().data());
// This replacement prevents frontends from interpreting '<' as
// an HTML tag opening
maintainer.replace(QLatin1Char('<'), QLatin1String("<"));
}
return maintainer;
}
QString Package::homepage() const
{
QString homepage;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList());
homepage = QString::fromUtf8(parser.Homepage().data());
}
return homepage;
}
QString Package::version() const
{
if (!d->packageIter->CurrentVer) {
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
} else {
return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr());
}
} else {
return QLatin1String(d->packageIter.CurrentVer().VerStr());
}
}
QString Package::upstreamVersion() const
{
const char *ver;
if (!d->packageIter->CurrentVer) {
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
} else {
ver = State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr();
}
} else {
ver = d->packageIter.CurrentVer().VerStr();
}
return QString::fromStdString(_system->VS->UpstreamVersion(ver));
}
QString Package::upstreamVersion(const QString &version)
{
QByteArray ver = version.toLatin1();
return QString::fromStdString(_system->VS->UpstreamVersion(ver.constData()));
}
QString Package::architecture() const
{
pkgDepCache *depCache = d->backend->cache()->depCache();
pkgCache::VerIterator ver = (*depCache)[d->packageIter].InstVerIter(*depCache);
// the arch:all property is part of the version
if (ver && ver.Arch())
return QLatin1String(ver.Arch());
return QLatin1String(d->packageIter.Arch());
}
QStringList Package::availableVersions() const
{
QStringList versions;
// Get available Versions.
for (auto Ver = d->packageIter.VersionList(); !Ver.end(); ++Ver) {
// We always take the first available version.
pkgCache::VerFileIterator VF = Ver.FileList();
if (VF.end())
continue;
pkgCache::PkgFileIterator File = VF.File();
// Files without an archive will have a site
QString archive = (File->Archive) ? QLatin1String(File.Archive()) :
QLatin1String(File.Site());
versions.append(QLatin1String(Ver.VerStr()) % QLatin1String(" (") %
archive % ')');
}
return versions;
}
QString Package::installedVersion() const
{
if (!d->packageIter->CurrentVer) {
return QString();
}
return QLatin1String(d->packageIter.CurrentVer().VerStr());
}
QString Package::availableVersion() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
}
return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr());
}
QString Package::priority() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end())
return QString();
return QLatin1String(ver.PriorityType());
}
QStringList Package::installedFilesList() const
{
QStringList installedFilesList;
QString path = QLatin1String("/var/lib/dpkg/info/") % name() % QLatin1String(".list");
// Fallback for multiarch packages
if (!QFile::exists(path)) {
path = QLatin1String("/var/lib/dpkg/info/") % name() % ':' %
architecture() % QLatin1String(".list");
}
QFile infoFile(path);
if (infoFile.open(QFile::ReadOnly)) {
QTextStream stream(&infoFile);
QString line;
do {
line = stream.readLine();
installedFilesList << line;
} while (!line.isNull());
// The first item won't be a file
installedFilesList.removeFirst();
// Remove non-file directory listings
for (int i = 0; i < installedFilesList.size() - 1; ++i) {
if (installedFilesList.at(i+1).contains(installedFilesList.at(i) + '/')) {
installedFilesList[i] = QString(QLatin1Char(' '));
}
}
installedFilesList.removeAll(QChar::fromLatin1(' '));
// Last line is empty for some reason...
if (!installedFilesList.isEmpty()) {
installedFilesList.removeLast();
}
}
return installedFilesList;
}
QString Package::origin() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(Ver.end())
return QString();
pkgCache::VerFileIterator VF = Ver.FileList();
return QLatin1String(VF.File().Origin());
}
QStringList Package::archives() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(Ver.end())
return QStringList();
QStringList archiveList;
for (auto VF = Ver.FileList(); !VF.end(); ++VF)
archiveList << QLatin1String(VF.File().Archive());
return archiveList;
}
QString Package::component() const
{
QString sect = section();
if(sect.isEmpty())
return QString();
QStringList split = sect.split('/');
if (split.count() > 1)
return split.first();
return QString("main");
}
QByteArray Package::md5Sum() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(ver.end())
return QByteArray();
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
return rec.MD5Hash().c_str();
}
QUrl Package::changelogUrl() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end())
return QUrl();
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
// Find the latest version for the latest changelog
QString versionString;
if (!availableVersion().isEmpty())
versionString = availableVersion();
// Epochs in versions are ignored on changelog servers
if (versionString.contains(QLatin1Char(':'))) {
QStringList epochVersion = versionString.split(QLatin1Char(':'));
// If the version has an epoch, take the stuff after the epoch
versionString = epochVersion.at(1);
}
// Create URL in form using the correct server, file path, and file suffix
Config *config = d->backend->config();
QString server = config->readEntry(QLatin1String("Apt::Changelogs::Server"),
QLatin1String("http://packages.debian.org/changelogs"));
QString path = QLatin1String(rec.FileName().c_str());
path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1);
path += sourcePackage() % '_' % versionString % '/';
bool fromDebian = server.contains(QLatin1String("debian"));
QString suffix = fromDebian ? QLatin1String("changelog.txt")
: QLatin1String("changelog");
return QUrl(server % '/' % path % suffix);
}
QUrl Package::screenshotUrl(QApt::ScreenshotType type) const
{
QUrl url;
switch (type) {
case QApt::Thumbnail:
url = QUrl(controlField(QLatin1String("Thumbnail-Url")));
if(url.isEmpty())
url = QUrl("http://screenshots.debian.net/thumbnail/" % name());
break;
case QApt::Screenshot:
url = QUrl(controlField(QLatin1String("Screenshot-Url")));
if(url.isEmpty())
url = QUrl("http://screenshots.debian.net/screenshot/" % name());
break;
default:
qDebug() << "I do not know how to handle the screenshot type given to me: " << QString::number(type);
}
return url;
}
QDateTime Package::supportedUntil() const
{
if (!isSupported()) {
return QDateTime();
}
QFile lsb_release(QLatin1String("/etc/lsb-release"));
if (!lsb_release.open(QFile::ReadOnly)) {
// Though really, your system is screwed if this happens...
return QDateTime();
}
pkgTagSection sec;
time_t releaseDate = -1;
QString release;
QTextStream stream(&lsb_release);
QString line;
do {
line = stream.readLine();
QStringList split = line.split(QLatin1Char('='));
if (split.size() != 2) {
continue;
}
if (split.at(0) == QLatin1String("DISTRIB_CODENAME")) {
release = split.at(1);
}
} while (!line.isNull());
// Canonical only provides support for Ubuntu, but we don't have to worry
// about Debian systems as long as we assume that this function can fail.
QString releaseFile = d-><API key>(QLatin1String("Ubuntu"), release);
if(!FileExists(releaseFile.toStdString())) {
// happens e.g. when there is no release file and is harmless
return QDateTime();
}
// read the relase file
FileFd fd(releaseFile.toStdString(), FileFd::ReadOnly);
pkgTagFile tag(&fd);
tag.Step(sec);
if(!RFC1123StrToTime(sec.FindS("Date").data(), releaseDate)) {
return QDateTime();
}
// Default to 18m in case the package has no "supported" field
QString supportTimeString = QLatin1String("18m");
QString supportTimeField = controlField(QLatin1String("Supported"));
if (!supportTimeField.isEmpty()) {
supportTimeString = supportTimeField;
}
QChar unit = supportTimeString.at(supportTimeString.length() - 1);
supportTimeString.chop(1); // Remove the letter signifying months/years
const int supportTime = supportTimeString.toInt();
QDateTime supportEnd;
if (unit == QLatin1Char('m')) {
supportEnd = QDateTime::fromTime_t(releaseDate).addMonths(supportTime);
} else if (unit == QLatin1Char('y')) {
supportEnd = QDateTime::fromTime_t(releaseDate).addYears(supportTime);
}
return supportEnd;
}
QString Package::controlField(QLatin1String name) const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end()) {
return QString();
}
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
return QString::fromStdString(rec.RecordField(name.latin1()));
}
QString Package::controlField(const QString &name) const
{
return controlField(QLatin1String(name.toLatin1()));
}
qint64 Package::<API key>() const
{
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
if (!ver.end()) {
return qint64(ver->InstalledSize);
} else {
return qint64(-1);
}
}
qint64 Package::<API key>() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return qint64(-1);
}
return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->InstalledSize);
}
qint64 Package::downloadSize() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return qint64(-1);
}
return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->Size);
}
int Package::state() const
{
int packageState = 0;
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter];
if (!d-><API key>) {
d->initStaticState(ver, stateCache);
}
if (stateCache.Install()) {
packageState |= ToInstall;
}
if (stateCache.Flags & pkgCache::Flag::Auto) {
packageState |= QApt::Package::IsAuto;
}
if (stateCache.iFlags & pkgDepCache::ReInstall) {
packageState |= ToReInstall;
} else if (stateCache.NewInstall()) { // Order matters here.
packageState |= NewInstall;
} else if (stateCache.Upgrade()) {
packageState |= ToUpgrade;
} else if (stateCache.Downgrade()) {
packageState |= ToDowngrade;
} else if (stateCache.Delete()) {
packageState |= ToRemove;
if (stateCache.iFlags & pkgDepCache::Purge) {
packageState |= ToPurge;
}
} else if (stateCache.Keep()) {
packageState |= ToKeep;
}
return packageState | d->state;
}
int Package::staticState() const
{
if (!d-><API key>) {
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter];
d->initStaticState(ver, stateCache);
}
return d->state;
}
int Package::compareVersion(const QString &v1, const QString &v2)
{
// Make deep copies of toStdString(), since otherwise they would
// go out of scope when we call c_str()
string s1 = v1.toStdString();
string s2 = v2.toStdString();
const char *a = s1.c_str();
const char *b = s2.c_str();
int lenA = strlen(a);
int lenB = strlen(b);
return _system->VS->DoCmpVersion(a, a+lenA, b, b+lenB);
}
bool Package::isInstalled() const
{
return !d->packageIter.CurrentVer().end();
}
bool Package::isSupported() const
{
if (origin() == QLatin1String("Ubuntu")) {
QString componentString = component();
if ((componentString == QLatin1String("main") ||
componentString == QLatin1String("restricted")) && isTrusted()) {
return true;
}
}
return false;
}
bool Package::<API key>() const
{
// Excludes installed packages, which are always "interesting"
if (isInstalled())
return false;
// Otherwise, check if the pkgIterator is the "best" from its group
return (d->packageIter.Group().FindPkg() != d->packageIter);
}
QString Package::multiArchTypeString() const
{
return controlField(QLatin1String("Multi-Arch"));
}
MultiArchType Package::multiArchType() const
{
QString typeString = multiArchTypeString();
MultiArchType archType = <API key>;
if (typeString == QLatin1String("same"))
archType = MultiArchSame;
else if (typeString == QLatin1String("foreign"))
archType = MultiArchForeign;
else if (typeString == QLatin1String("allowed"))
archType = MultiArchAllowed;
return archType;
}
bool Package::isForeignArch() const
{
if (!d-><API key>) {
QString arch = architecture();
d->isForeignArch = (d->backend->nativeArchitecture() != arch) & (arch != QLatin1String("all"));
d-><API key> = true;
}
return d->isForeignArch;
}
QList<DependencyItem> Package::depends() const
{
return DependencyInfo::parseDepends(controlField("Depends"), Depends);
}
QList<DependencyItem> Package::preDepends() const
{
return DependencyInfo::parseDepends(controlField("Pre-Depends"), PreDepends);
}
QList<DependencyItem> Package::suggests() const
{
return DependencyInfo::parseDepends(controlField("Suggests"), Suggests);
}
QList<DependencyItem> Package::recommends() const
{
return DependencyInfo::parseDepends(controlField("Recommends"), Recommends);
}
QList<DependencyItem> Package::conflicts() const
{
return DependencyInfo::parseDepends(controlField("Conflicts"), Conflicts);
}
QList<DependencyItem> Package::replaces() const
{
return DependencyInfo::parseDepends(controlField("Replaces"), Replaces);
}
QList<DependencyItem> Package::obsoletes() const
{
return DependencyInfo::parseDepends(controlField("Obsoletes"), Obsoletes);
}
QList<DependencyItem> Package::breaks() const
{
return DependencyInfo::parseDepends(controlField("Breaks"), Breaks);
}
QList<DependencyItem> Package::enhances() const
{
return DependencyInfo::parseDepends(controlField("Enhance"), Enhances);
}
QStringList Package::dependencyList(bool useCandidateVersion) const
{
QStringList dependsList;
pkgCache::VerIterator current;
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if(!useCandidateVersion) {
current = State.InstVerIter(*d->backend->cache()->depCache());
}
if(useCandidateVersion || current.end()) {
current = State.CandidateVerIter(*d->backend->cache()->depCache());
}
// no information found
if(current.end()) {
return dependsList;
}
for(pkgCache::DepIterator D = current.DependsList(); D.end() != true; ++D) {
QString type;
bool isOr = false;
bool isVirtual = false;
QString name;
QString version;
QString versionCompare;
QString finalString;
// check target and or-depends status
pkgCache::PkgIterator Trg = D.TargetPkg();
if ((D->CompareOp & pkgCache::Dep::Or) == pkgCache::Dep::Or) {
isOr=true;
}
// common information
type = QString::fromUtf8(D.DepType());
name = QLatin1String(Trg.Name());
if (!Trg->VersionList) {
isVirtual = true;
} else {
version = QLatin1String(D.TargetVer());
versionCompare = QLatin1String(D.CompType());
}
finalString = QLatin1Literal("<b>") % type % QLatin1Literal(":</b> ");
if (isVirtual) {
finalString += QLatin1Literal("<i>") % name % QLatin1Literal("</i>");
} else {
finalString += name;
}
// Escape the compare operator so it won't be seen as HTML
if (!version.isEmpty()) {
QString compMarkup(versionCompare);
compMarkup.replace(QLatin1Char('<'), QLatin1String("<"));
finalString += QLatin1String(" (") % compMarkup % QLatin1Char(' ') % version % QLatin1Char(')');
}
if (isOr) {
finalString += QLatin1String(" |");
}
dependsList.append(finalString);
}
return dependsList;
}
QStringList Package::requiredByList() const
{
QStringList reverseDependsList;
for(pkgCache::DepIterator it = d->packageIter.RevDependsList(); !it.end(); ++it) {
reverseDependsList << QLatin1String(it.ParentPkg().Name());
}
return reverseDependsList;
}
QStringList Package::providesList() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QStringList();
}
QStringList provides;
for (pkgCache::PrvIterator Prv =
State.CandidateVerIter(*d->backend->cache()->depCache()).ProvidesList(); !Prv.end(); ++Prv) {
provides.append(QLatin1String(Prv.Name()));
}
return provides;
}
QStringList Package::recommendsList() const
{
QStringList recommends;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return recommends;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &rState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Recommends && (rState.CandidateVer != 0 )) {
recommends << QLatin1String(it.TargetPkg().Name());
}
}
return recommends;
}
QStringList Package::suggestsList() const
{
QStringList suggests;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return suggests;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &sState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Suggests && (sState.CandidateVer != 0 )) {
suggests << QLatin1String(it.TargetPkg().Name());
}
}
return suggests;
}
QStringList Package::enhancesList() const
{
QStringList enhances;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return enhances;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &eState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Enhances && (eState.CandidateVer != 0 )) {
enhances << QLatin1String(it.TargetPkg().Name());
}
}
return enhances;
}
QStringList Package::enhancedByList() const
{
QStringList enhancedByList;
Q_FOREACH (QApt::Package *package, d->backend->availablePackages()) {
if (package->enhancesList().contains(name())) {
enhancedByList << package->name();
}
}
return enhancedByList;
}
QList<QApt::MarkingErrorInfo> Package::brokenReason() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
QList<MarkingErrorInfo> reasons;
// check if there is actually something to install
if (!Ver) {
QApt::DependencyInfo info(name(), QString(), NoOperand, InvalidType);
QApt::MarkingErrorInfo error(QApt::<API key>, info);
reasons.append(error);
return reasons;
}
for (pkgCache::DepIterator D = Ver.DependsList(); !D.end();) {
// Compute a single dependency element (glob or)
pkgCache::DepIterator Start;
pkgCache::DepIterator End;
D.GlobOr(Start, End);
pkgCache::PkgIterator Targ = Start.TargetPkg();
if (!d->backend->cache()->depCache()->IsImportantDep(End)) {
continue;
}
if (((*d->backend->cache()->depCache())[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) {
continue;
}
if (!Targ->ProvidesList) {
// Ok, not a virtual package since no provides
pkgCache::VerIterator Ver = (*d->backend->cache()->depCache())[Targ].InstVerIter(*d->backend->cache()->depCache());
QString requiredVersion;
if(Start.TargetVer() != 0) {
requiredVersion = '(' % QLatin1String(Start.CompType())
% QLatin1String(Start.TargetVer()) % ')';
}
if (!Ver.end()) {
// Happens when a package needs an upgraded dep, but the dep won't
// upgrade. Example:
// "apt 0.5.4 but 0.5.3 is to be installed"
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, requiredVersion,
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::<API key>, errorInfo);
reasons.append(error);
} else { // We have the package, but for some reason it won't be installed
// In this case, the required version does not exist at all
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, requiredVersion,
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::DepNotInstallable, errorInfo);
reasons.append(error);
}
} else {
// Ok, candidate has provides. We're a virtual package
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, QString(),
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::VirtualPackage, errorInfo);
reasons.append(error);
}
}
return reasons;
}
bool Package::isTrusted() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!Ver)
return false;
pkgSourceList *Sources = d->backend->packageSourceList();
QHash<pkgCache::PkgFileIterator, pkgIndexFile*> *trustCache = d->backend->cache()->trustCache();
for (pkgCache::VerFileIterator i = Ver.FileList(); !i.end(); ++i)
{
pkgIndexFile *Index;
//FIXME: Should be done in apt
auto trustIter = trustCache->constBegin();
while (trustIter != trustCache->constEnd()) {
if (trustIter.key() == i.File())
break; // Found it
trustIter++;
}
// Find the index of the package file from the package sources
if (trustIter == trustCache->constEnd()) { // Not found
if (!Sources->FindIndex(i.File(), Index))
continue;
} else
Index = trustIter.value();
if (Index->IsTrusted())
return true;
}
return false;
}
bool Package::wouldBreak() const
{
int pkgState = state();
if ((pkgState & ToRemove) || (!(pkgState & Installed) && (pkgState & ToKeep))) {
return false;
}
return pkgState & InstallBroken;
}
void Package::setAuto(bool flag)
{
d->backend->cache()->depCache()->MarkAuto(d->packageIter, flag);
}
void Package::setKeep()
{
d->backend->cache()->depCache()->MarkKeep(d->packageIter, false);
if (d->backend->cache()->depCache()->BrokenCount() > 0) {
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.ResolveByKeep();
}
d->state |= IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setInstall()
{
d->backend->cache()->depCache()->MarkInstall(d->packageIter, true);
d->state &= ~IsManuallyHeld;
// FIXME: can't we get rid of it here?
// if there is something wrong, try to fix it
if (!state() & ToInstall || d->backend->cache()->depCache()->BrokenCount() > 0) {
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Resolve(true);
}
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setReInstall()
{
d->backend->cache()->depCache()->SetReInstall(d->packageIter, true);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setRemove()
{
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Remove(d->packageIter);
Fix.Resolve(true);
d->backend->cache()->depCache()->SetReInstall(d->packageIter, false);
d->backend->cache()->depCache()->MarkDelete(d->packageIter, false);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setPurge()
{
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Remove(d->packageIter);
Fix.Resolve(true);
d->backend->cache()->depCache()->SetReInstall(d->packageIter, false);
d->backend->cache()->depCache()->MarkDelete(d->packageIter, true);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
bool Package::setVersion(const QString &version)
{
pkgDepCache::StateCache &state = (*d->backend->cache()->depCache())[d->packageIter];
QLatin1String defaultCandVer(state.CandVersion);
bool isDefault = (version == defaultCandVer);
pkgVersionMatch Match(version.toLatin1().constData(), pkgVersionMatch::Version);
const pkgCache::VerIterator &Ver = Match.Find(d->packageIter);
if (Ver.end())
return false;
d->backend->cache()->depCache()->SetCandidateVersion(Ver);
for (auto VF = Ver.FileList(); !VF.end(); ++VF) {
if (!VF.File() || !VF.File().Archive())
continue;
d->backend->cache()->depCache()->SetCandidateRelease(Ver, VF.File().Archive());
break;
}
if (isDefault)
d->state &= ~OverrideVersion;
else
d->state |= OverrideVersion;
return true;
}
void Package::setPinned(bool pin)
{
pin ? d->state |= IsPinned : d->state &= ~IsPinned;
}
}
|
extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
final class Contact extends Model
{
const PHONE = 'phone';
const ADDRESS = 'address';
const ADDRESS_COMPLEMENT = 'address_complement';
const POSTAL_CODE = 'postal_code';
const CITY = 'city';
const REGION = 'region';
const COUNTRY = 'country';
const CONTACTABLE_ID = 'contactable_id';
const CONTACTABLE_TYPE = 'contactable_type';
protected $fillable = [
self::PHONE,
self::ADDRESS,
self::ADDRESS_COMPLEMENT,
self::POSTAL_CODE,
self::CITY,
self::REGION,
self::COUNTRY,
];
protected $hidden = [
self::CONTACTABLE_ID,
self::CONTACTABLE_TYPE,
];
}
|
# logutil.py
# A module containing means of interacting with log files.
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))
if not os.path.exists(logdir):
os.mkdir(logdir)
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def get_logger(section, name):
"""
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
|
{% extends "geostitcher/views/templates/base.html" %}
{% block content %}
<div class="gallery">
<div id="error"></div>
<script src="{{context}}/js/gallery.js" type="text/javascript"></script>
<div>
{% for pic in pictures %}
<div class="thumbnail">
<a class={{pic.name}} href="{{context}}/img/{{pic.userid}}/{{pic.name}}">
<img src="{{context}}/img/{{pic.userid}}/{{thumb-prefix}}{{pic.name}}"/>
{% ifequal username page-owner %}
<input id="{{pic.name}}"
name="{{pic.name}}"
type="checkbox"
value="true" />
{% endifequal %}
</a>
</div>
{% endfor %}
{% ifequal user page-owner %}
<input id="delete" type="submit" value="delete images" />
{% endifequal %}
</div>
</div>
<form action="{{context}}/upload/{{dataset_id}}" enctype="multipart/form-data" method="POST">
<input id="file" name="file" type="file" />
<input type="submit" value="Upload" />
</form>
</div>
{% endblock %}
|
@file
Definitions for UpdatePipeline.
This file contains type definitions for UpdatePipeline, a three-staged,
multithreaded update pipeline.
#include <Common/Compat.h>
#include "UpdatePipeline.h"
#include <Hypertable/RangeServer/Global.h>
#include <Hypertable/RangeServer/Response/Callback/Update.h>
#include <Hypertable/RangeServer/UpdateContext.h>
#include <Hypertable/RangeServer/UpdateRecRange.h>
#include <Hypertable/RangeServer/UpdateRecTable.h>
#include <Hypertable/Lib/ClusterId.h>
#include <Hypertable/Lib/RangeServer/Protocol.h>
#include <Common/DynamicBuffer.h>
#include <Common/FailureInducer.h>
#include <Common/Logger.h>
#include <Common/Serialization.h>
#include <chrono>
#include <set>
#include <thread>
using namespace Hypertable;
using namespace Hypertable::RangeServer;
using namespace std;
UpdatePipeline::UpdatePipeline(ContextPtr &context, QueryCachePtr &query_cache,
TimerHandlerPtr &timer_handler, CommitLogPtr &log,
Filesystem::Flags flags) :
m_context(context), m_query_cache(query_cache),
m_timer_handler(timer_handler), m_log(log), m_flags(flags) {
<API key> = m_context->props->get_i64("Hypertable.RangeServer.UpdateCoalesceLimit");
<API key> = m_context->props->get_i32("Hypertable.RangeServer.Testing.MaintenanceNeeded.PauseInterval");
m_update_delay = m_context->props->get_i32("Hypertable.RangeServer.UpdateDelay", 0);
m_max_clock_skew = m_context->props->get_i32("Hypertable.RangeServer.ClockSkew.Max");
m_threads.reserve(3);
m_threads.push_back( thread(&UpdatePipeline::<API key>, this) );
m_threads.push_back( thread(&UpdatePipeline::commit, this) );
m_threads.push_back( thread(&UpdatePipeline::add_and_respond, this) );
}
void UpdatePipeline::add(UpdateContext *uc) {
lock_guard<mutex> lock(<API key>);
m_qualify_queue.push_back(uc);
<API key>.notify_all();
}
void UpdatePipeline::shutdown() {
m_shutdown = true;
<API key>.notify_all();
m_commit_queue_cond.notify_all();
<API key>.notify_all();
for (std::thread &t : m_threads)
t.join();
}
void UpdatePipeline::<API key>() {
UpdateContext *uc;
SerializedKey key;
const uint8_t *mod, *mod_end;
const char *row;
String start_row, end_row;
UpdateRecRangeList *rulist;
int error = Error::OK;
int64_t <API key>;
RangeTransferInfo transfer_info;
bool transfer_pending;
DynamicBuffer *cur_bufp;
DynamicBuffer *transfer_bufp;
uint32_t go_buf_reset_offset;
uint32_t <API key>;
CommitLogPtr transfer_log;
UpdateRecRange range_update;
RangePtr range;
std::mutex &mutex = <API key>;
condition_variable &cond = <API key>;
std::list<UpdateContext *> &queue = m_qualify_queue;
while (true) {
{
unique_lock<std::mutex> lock(mutex);
cond.wait(lock, [this, &queue](){ return !queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = queue.front();
queue.pop_front();
}
rulist = 0;
transfer_bufp = 0;
go_buf_reset_offset = 0;
<API key> = 0;
// This probably shouldn't happen for group commit, but since
// it's only for testing purposes, we'll leave it here
if (m_update_delay)
this_thread::sleep_for(chrono::milliseconds(m_update_delay));
// Global commit log is only available after local recovery
uc->auto_revision = Hypertable::get_ts64();
// TODO: Sanity check mod data (checksum validation)
// hack to workaround xen timestamp issue
if (uc->auto_revision < m_last_revision)
uc->auto_revision = m_last_revision;
for (UpdateRecTable *table_update : uc->updates) {
HT_DEBUG_OUT <<"Update: "<< table_update->id << HT_END;
if (!table_update->id.is_system() && m_context->server_state->readonly()) {
table_update->error = Error::<API key>;
continue;
}
try {
if (!m_context->live_map->lookup(table_update->id.id, table_update->table_info)) {
table_update->error = Error::TABLE_NOT_FOUND;
table_update->error_msg = table_update->id.id;
continue;
}
}
catch (Exception &e) {
table_update->error = e.code();
table_update->error_msg = e.what();
continue;
}
// verify schema
if (table_update->table_info->get_schema()->get_generation() !=
table_update->id.generation) {
table_update->error = Error::<API key>;
table_update->error_msg =
format("Update schema generation mismatch for table %s (received %lld != %lld)",
table_update->id.id, (Lld)table_update->id.generation,
(Lld)table_update->table_info->get_schema()->get_generation());
continue;
}
// Pre-allocate the go_buf - each key could expand by 8 or 9 bytes,
// if auto-assigned (8 for the ts or rev and maybe 1 for possible
// increase in vint length)
table_update->go_buf.reserve(table_update->id.encoded_length() +
table_update->total_buffer_size +
(table_update->total_count * 9));
table_update->id.encode(&table_update->go_buf.ptr);
table_update->go_buf.set_mark();
for (UpdateRequest *request : table_update->requests) {
uc->total_updates++;
mod_end = request->buffer.base + request->buffer.size;
mod = request->buffer.base;
go_buf_reset_offset = table_update->go_buf.fill();
<API key> = uc->root_buf.fill();
memset(&uc->send_back, 0, sizeof(uc->send_back));
while (mod < mod_end) {
key.ptr = mod;
row = key.row();
// error inducer for tests/integration/fail-index-mutator
if (<API key>("<API key>")) {
if (!strcmp(row, "1,+/<API key>\t\t01501")) {
uc->send_back.count++;
uc->send_back.error = Error::INDUCED_FAILURE;
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.len = strlen(row);
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
continue;
}
}
// If the row key starts with '\0' then the buffer is probably
// corrupt, so mark the remaing key/value pairs as bad
if (*row == 0) {
uc->send_back.error = Error::BAD_KEY;
uc->send_back.count = request->count; // fix me !!!!
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.len = mod_end - mod;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
mod = mod_end;
continue;
}
// Look for containing range, add to stop mods if not found
if (!table_update->table_info-><API key>(row, range,
start_row, end_row) ||
range->get_relinquish()) {
if (uc->send_back.error != Error::<API key>
&& uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
if (uc->send_back.count == 0) {
uc->send_back.error = Error::<API key>;
uc->send_back.offset = mod - request->buffer.base;
}
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
uc->send_back.count++;
continue;
}
if ((rulist = table_update->range_map[range.get()]) == 0) {
rulist = new UpdateRecRangeList();
rulist->range = range;
table_update->range_map[range.get()] = rulist;
}
// See if range has some other error preventing it from receiving updates
if ((error = rulist->range->get_error()) != Error::OK) {
if (uc->send_back.error != error && uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
if (uc->send_back.count == 0) {
uc->send_back.error = error;
uc->send_back.offset = mod - request->buffer.base;
}
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
uc->send_back.count++;
continue;
}
if (uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
/*
* Increment update count on range
* (block if maintenance in progress)
*/
if (!rulist->range_blocked) {
if (!rulist->range-><API key>()) {
uc->send_back.error = Error::<API key>;
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.count++;
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
continue;
}
rulist->range_blocked = true;
}
String range_start_row, range_end_row;
rulist->range->get_boundary_rows(range_start_row, range_end_row);
// Make sure range didn't just shrink
if (range_start_row != start_row || range_end_row != end_row) {
rulist->range-><API key>();
table_update->range_map.erase(rulist->range.get());
delete rulist;
continue;
}
/** Fetch range transfer information **/
{
bool <API key>;
transfer_pending = rulist->range->get_transfer_info(transfer_info, transfer_log,
&<API key>, <API key>);
}
if (rulist->transfer_log.get() == 0)
rulist->transfer_log = transfer_log;
HT_ASSERT(rulist->transfer_log.get() == transfer_log.get());
bool <API key> = false;
// Check for clock skew
{
ByteString tmp_key;
const uint8_t *tmp;
int64_t difference, tmp_timestamp;
tmp_key.ptr = key.ptr;
tmp_key.decode_length(&tmp);
if ((*tmp & Key::HAVE_REVISION) == 0) {
if (<API key> > TIMESTAMP_MIN
&& uc->auto_revision < <API key>) {
tmp_timestamp = Hypertable::get_ts64();
if (tmp_timestamp > uc->auto_revision)
uc->auto_revision = tmp_timestamp;
if (uc->auto_revision < <API key>) {
difference = (int32_t)((<API key> - uc->auto_revision)
/ 1000LL);
if (difference > m_max_clock_skew && !Global::<API key>) {
request->error = Error::<API key>;
HT_ERRORF("Clock skew of %lld microseconds exceeds maximum "
"(%lld) range=%s", (Lld)difference,
(Lld)m_max_clock_skew,
rulist->range->get_name().c_str());
uc->send_back.count = 0;
request->send_back_vector.clear();
break;
}
}
}
}
}
if (transfer_pending) {
transfer_bufp = &rulist->transfer_buf;
if (transfer_bufp->empty()) {
transfer_bufp->reserve(table_update->id.encoded_length());
table_update->id.encode(&transfer_bufp->ptr);
transfer_bufp->set_mark();
}
rulist-><API key> = rulist->transfer_buf.fill();
}
else {
transfer_bufp = 0;
rulist-><API key> = 0;
}
if (rulist->range->is_root()) {
if (uc->root_buf.empty()) {
uc->root_buf.reserve(table_update->id.encoded_length());
table_update->id.encode(&uc->root_buf.ptr);
uc->root_buf.set_mark();
<API key> = uc->root_buf.fill();
}
cur_bufp = &uc->root_buf;
}
else
cur_bufp = &table_update->go_buf;
rulist->last_request = request;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
while (mod < mod_end &&
(end_row == "" || (strcmp(row, end_row.c_str()) <= 0))) {
if (transfer_pending) {
if (transfer_info.transferring(row)) {
if (!<API key>) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
cur_bufp = transfer_bufp;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
<API key> = true;
}
table_update->transfer_count++;
}
else {
if (<API key>) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
cur_bufp = &table_update->go_buf;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
<API key> = false;
}
}
}
try {
SchemaPtr schema = table_update->table_info->get_schema();
uint8_t family=*(key.ptr+1+strlen((const char *)key.ptr+1)+1);
ColumnFamilySpec *cf_spec = schema->get_column_family(family);
// reset auto_revision if it's gotten behind
if (uc->auto_revision < <API key>) {
uc->auto_revision = Hypertable::get_ts64();
if (uc->auto_revision < <API key>) {
HT_THROWF(Error::<API key>,
"Auto revision (%lld) is less than latest range "
"revision (%lld) for range %s",
(Lld)uc->auto_revision, (Lld)<API key>,
rulist->range->get_name().c_str());
}
}
// This will transform keys that need to be assigned a
// timestamp and/or revision number by re-writing the key
// with the added timestamp and/or revision tacked on to the end
transform_key(key, cur_bufp, ++uc->auto_revision,&m_last_revision,
cf_spec ? cf_spec-><API key>() : false);
// Validate revision number
if (m_last_revision < <API key>) {
if (m_last_revision != uc->auto_revision) {
HT_THROWF(Error::<API key>,
"Supplied revision (%lld) is less than most recently "
"seen revision (%lld) for range %s",
(Lld)m_last_revision, (Lld)<API key>,
rulist->range->get_name().c_str());
}
}
}
catch (Exception &e) {
HT_ERRORF("%s - %s", e.what(), Error::get_text(e.code()));
request->error = e.code();
break;
}
// Now copy the value (with sanity check)
mod = key.ptr;
key.next(); // skip value
HT_ASSERT(key.ptr <= mod_end);
cur_bufp->add(mod, key.ptr-mod);
mod = key.ptr;
table_update->total_added++;
if (mod < mod_end)
row = key.row();
}
if (request->error == Error::OK) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
// if there were transferring updates, record the latest revision
if (transfer_pending && rulist-><API key> < rulist->transfer_buf.fill()) {
if (rulist-><API key> < m_last_revision)
rulist-><API key> = m_last_revision;
}
}
else {
/*
* If we drop into here, this means that the request is
* being aborted, so reset all of the UpdateRecRangeLists,
* reset the go_buf and the root_buf
*/
for (auto iter = table_update->range_map.begin();
iter != table_update->range_map.end(); ++iter)
(*iter).second->reset_updates(request);
table_update->go_buf.ptr = table_update->go_buf.base + go_buf_reset_offset;
if (<API key>)
uc->root_buf.ptr = uc->root_buf.base + <API key>;
uc->send_back.count = 0;
mod = mod_end;
}
range_update.bufp = 0;
}
transfer_log = 0;
if (uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
}
HT_DEBUGF("Added %d (%d transferring) updates to '%s'",
table_update->total_added, table_update->transfer_count,
table_update->id.id);
if (!table_update->id.is_metadata())
uc->total_added += table_update->total_added;
}
uc->last_revision = m_last_revision;
// Enqueue update
{
lock_guard<std::mutex> lock(<API key>);
m_commit_queue.push_back(uc);
m_commit_queue_cond.notify_all();
<API key>++;
}
}
}
void UpdatePipeline::commit() {
UpdateContext *uc;
SerializedKey key;
std::list<UpdateContext *> coalesce_queue;
uint64_t coalesce_amount = 0;
int error = Error::OK;
uint32_t <API key>;
bool log_needs_syncing {};
while (true) {
// Dequeue next update
{
unique_lock<std::mutex> lock(<API key>);
m_commit_queue_cond.wait(lock, [this](){
return !m_commit_queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = m_commit_queue.front();
m_commit_queue.pop_front();
<API key>
}
<API key> = 0;
log_needs_syncing = false;
// Commit ROOT mutations
if (uc->root_buf.ptr > uc->root_buf.mark) {
if ((error = Global::root_log->write(ClusterId::get(), uc->root_buf, uc->last_revision, Filesystem::Flags::SYNC)) != Error::OK) {
HT_FATALF("Problem writing %d bytes to ROOT commit log - %s",
(int)uc->root_buf.fill(), Error::get_text(error));
}
}
for (UpdateRecTable *table_update : uc->updates) {
coalesce_amount += table_update->total_buffer_size;
// Iterate through all of the ranges, committing any transferring updates
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).second->transfer_buf.ptr > (*iter).second->transfer_buf.mark) {
<API key> += (*iter).second->transfer_buf.ptr - (*iter).second->transfer_buf.mark;
if ((error = (*iter).second->transfer_log->write(ClusterId::get(), (*iter).second->transfer_buf,
(*iter).second-><API key>,
m_flags)) != Error::OK) {
table_update->error = error;
table_update->error_msg = format("Problem writing %d bytes to transfer log",
(int)(*iter).second->transfer_buf.fill());
HT_ERRORF("%s - %s", table_update->error_msg.c_str(), Error::get_text(error));
break;
}
}
}
if (table_update->error != Error::OK)
continue;
constexpr uint32_t NO_LOG_SYNC_FLAGS =
Lib::RangeServer::Protocol::<API key> |
Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG;
if ((table_update->flags & NO_LOG_SYNC_FLAGS) == 0)
log_needs_syncing = true;
// Commit valid (go) mutations
if ((table_update->flags & Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG) == 0 &&
table_update->go_buf.ptr > table_update->go_buf.mark) {
if ((error = m_log->write(ClusterId::get(), table_update->go_buf, uc->last_revision, Filesystem::Flags::NONE)) != Error::OK) {
table_update->error_msg = format("Problem writing %d bytes to commit log (%s) - %s",
(int)table_update->go_buf.fill(),
m_log->get_log_dir().c_str(),
Error::get_text(error));
HT_ERRORF("%s", table_update->error_msg.c_str());
table_update->error = error;
continue;
}
}
}
bool do_sync = false;
if (log_needs_syncing) {
if (<API key> > 0 && coalesce_amount < <API key>) {
coalesce_queue.push_back(uc);
continue;
}
do_sync = true;
}
else if (!coalesce_queue.empty())
do_sync = true;
// Now sync the commit log if needed
if (do_sync) {
size_t retry_count {};
uc->total_syncs++;
while (true) {
if (m_flags == Filesystem::Flags::FLUSH)
error = m_log->flush();
else if (m_flags == Filesystem::Flags::SYNC)
error = m_log->sync();
else
error = Error::OK;
if (error != Error::OK) {
HT_ERRORF("Problem %sing log fragment (%s) - %s",
(m_flags == Filesystem::Flags::FLUSH ? "flush" : "sync"),
m_log-><API key>().c_str(),
Error::get_text(error));
if (++retry_count == 6)
break;
this_thread::sleep_for(chrono::milliseconds(10000));
}
else
break;
}
}
// Enqueue update
{
lock_guard<std::mutex> lock(<API key>);
coalesce_queue.push_back(uc);
while (!coalesce_queue.empty()) {
uc = coalesce_queue.front();
coalesce_queue.pop_front();
m_response_queue.push_back(uc);
}
coalesce_amount = 0;
<API key>.notify_all();
}
}
}
void UpdatePipeline::add_and_respond() {
UpdateContext *uc;
SerializedKey key;
int error = Error::OK;
while (true) {
// Dequeue next update
{
unique_lock<std::mutex> lock(<API key>);
<API key>.wait(lock, [this](){
return !m_response_queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = m_response_queue.front();
m_response_queue.pop_front();
}
/**
* Insert updates into Ranges
*/
for (UpdateRecTable *table_update : uc->updates) {
// Iterate through all of the ranges, inserting updates
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
ByteString value;
Key key_comps;
for (UpdateRecRange &update : (*iter).second->updates) {
Range *rangep = (*iter).first;
lock_guard<Range> lock(*rangep);
uint8_t *ptr = update.bufp->base + update.offset;
uint8_t *end = ptr + update.len;
if (!table_update->id.is_metadata())
uc->total_bytes_added += update.len;
rangep->add_bytes_written( update.len );
std::set<uint8_t> columns;
bool invalidate {};
const char *current_row {};
uint64_t count = 0;
while (ptr < end) {
key.ptr = ptr;
key_comps.load(key);
if (current_row == nullptr)
current_row = key_comps.row;
count++;
ptr += key_comps.length;
value.ptr = ptr;
ptr += value.length();
if (key_comps.column_family_code == 0 && key_comps.flag != FLAG_DELETE_ROW) {
HT_ERRORF("Skipping bad key - column family not specified in "
"non-delete row update on %s row=%s",
table_update->id.id, key_comps.row);
continue;
}
rangep->add(key_comps, value);
// invalidate
if (m_query_cache) {
if (strcmp(current_row, key_comps.row)) {
if (invalidate)
columns.clear();
m_query_cache->invalidate(table_update->id.id, current_row, columns);
columns.clear();
invalidate = false;
current_row = key_comps.row;
}
if (key_comps.flag == FLAG_DELETE_ROW)
invalidate = true;
else
columns.insert(key_comps.column_family_code);
}
}
if (m_query_cache && current_row) {
if (invalidate)
columns.clear();
m_query_cache->invalidate(table_update->id.id, current_row, columns);
}
rangep->add_cells_written(count);
}
}
}
// Decrement usage counters for all referenced ranges
for (UpdateRecTable *table_update : uc->updates) {
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).second->range_blocked)
(*iter).first-><API key>();
}
}
/**
* wait for these ranges to complete maintenance
*/
bool maintenance_needed = false;
for (UpdateRecTable *table_update : uc->updates) {
/*
* If any of the newly updated ranges needs maintenance,
* schedule immediately
*/
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).first->need_maintenance() &&
!Global::maintenance_queue->contains((*iter).first)) {
maintenance_needed = true;
HT_MAYBE_FAIL_X("<API key>", (*iter).first->is_metadata());
if (m_timer_handler)
m_timer_handler-><API key>();
break;
}
}
for (UpdateRequest *request : table_update->requests) {
Response::Callback::Update cb(m_context->comm, request->event);
if (table_update->error != Error::OK) {
if ((error = cb.error(table_update->error, table_update->error_msg)) != Error::OK)
HT_ERRORF("Problem sending error response - %s", Error::get_text(error));
continue;
}
if (request->error == Error::OK) {
/**
* Send back response
*/
if (!request->send_back_vector.empty()) {
StaticBuffer ext(new uint8_t [request->send_back_vector.size() * 16],
request->send_back_vector.size() * 16);
uint8_t *ptr = ext.base;
for (size_t i=0; i<request->send_back_vector.size(); i++) {
Serialization::encode_i32(&ptr, request->send_back_vector[i].error);
Serialization::encode_i32(&ptr, request->send_back_vector[i].count);
Serialization::encode_i32(&ptr, request->send_back_vector[i].offset);
Serialization::encode_i32(&ptr, request->send_back_vector[i].len);
/*
HT_INFOF("Sending back error %x, count %d, offset %d, len %d, table id %s",
request->send_back_vector[i].error, request->send_back_vector[i].count,
request->send_back_vector[i].offset, request->send_back_vector[i].len,
table_update->id.id);
*/
}
if ((error = cb.response(ext)) != Error::OK)
HT_ERRORF("Problem sending OK response - %s", Error::get_text(error));
}
else {
if ((error = cb.response_ok()) != Error::OK)
HT_ERRORF("Problem sending OK response - %s", Error::get_text(error));
}
}
else {
if ((error = cb.error(request->error, "")) != Error::OK)
HT_ERRORF("Problem sending error response - %s", Error::get_text(error));
}
}
}
{
lock_guard<LoadStatistics> lock(*Global::load_statistics);
Global::load_statistics->add_update_data(uc->total_updates, uc->total_added, uc->total_bytes_added, uc->total_syncs);
}
delete uc;
// For testing
if (<API key> > 0 && maintenance_needed)
this_thread::sleep_for(chrono::milliseconds(<API key>));
}
}
void
UpdatePipeline::transform_key(ByteString &bskey, DynamicBuffer *dest_bufp,
int64_t auto_revision, int64_t *revisionp,
bool timeorder_desc) {
size_t len;
const uint8_t *ptr;
len = bskey.decode_length(&ptr);
HT_ASSERT(*ptr == Key::AUTO_TIMESTAMP || *ptr == Key::HAVE_TIMESTAMP);
// if TIME_ORDER DESC was set for this column then we store the timestamps
// NOT in 1-complements!
if (timeorder_desc) {
// if the timestamp was specified by the user: unpack it and pack it
// again w/o 1-complement
if (*ptr == Key::HAVE_TIMESTAMP) {
uint8_t *p=(uint8_t *)ptr+len-8;
int64_t ts=Key::decode_ts64((const uint8_t **)&p);
p=(uint8_t *)ptr+len-8;
Key::encode_ts64((uint8_t **)&p, ts, false);
}
}
dest_bufp->ensure((ptr-bskey.ptr) + len + 9);
Serialization::encode_vi32(&dest_bufp->ptr, len+8);
memcpy(dest_bufp->ptr, ptr, len);
if (*ptr == Key::AUTO_TIMESTAMP)
*dest_bufp->ptr = Key::HAVE_REVISION
| Key::HAVE_TIMESTAMP | Key::REV_IS_TS;
else
*dest_bufp->ptr = Key::HAVE_REVISION
| Key::HAVE_TIMESTAMP;
// if TIME_ORDER DESC then store a flag in the key
if (timeorder_desc)
*dest_bufp->ptr |= Key::TS_CHRONOLOGICAL;
dest_bufp->ptr += len;
Key::encode_ts64(&dest_bufp->ptr, auto_revision,
timeorder_desc ? false : true);
*revisionp = auto_revision;
bskey.ptr = ptr + len;
}
|
#ifndef GLOBALS_H
#define GLOBALS_H
#include <stdio.h>
#include <allegro.h>
#include "resource.h"
//#define LOG_COMMS // Uncomment this line to enable serial comm logging
// <API key>
#define METRIC 0
#define IMPERIAL 1
// Display mode flags
#define FULL_SCREEN_MODE 0
#define WINDOWED_MODE 1
#define <API key> 2
#define <API key> 4
#define WINDOWED_MODE_SET 8
// Password for Datafiles (Tr. Code Definitions and Resources)
#define PASSWORD NULL
// Colors in the main palette
#define C_TRANSP -1
#define C_BLACK 0
#define C_WHITE 1
#define C_RED 255
#define C_BLUE 254
#define C_GREEN 99
#define C_DARK_YELLOW 54
#define C_PURPLE 9
#define C_DARK_GRAY 126
#define C_GRAY 50
#define C_LIGHT_GRAY 55
int <API key>;
// Options
int <API key>;
int display_mode;
// File names
char options_file_name[20];
char data_file_name[20];
char code_defs_file_name[20];
char log_file_name[20];
#ifdef LOG_COMMS
char comm_log_file_name[20];
#endif
void write_log(const char *log_string);
#ifdef LOG_COMMS
void write_comm_log(const char *marker, const char *data);
#endif
DATAFILE *datafile;
#endif
|
-- Move generator logic
module Kurt.GoEngine ( genMove
, simulatePlayout
, EngineState(..)
, newEngineState
, updateEngineState
, newUctTree
) where
import Control.Arrow (second)
import Control.Monad (liftM)
import Control.Monad.Primitive (PrimState)
import Control.Monad.ST (ST, runST, stToIO)
import Control.Parallel.Strategies (parMap, rdeepseq)
import Data.List ((\\))
import qualified Data.Map as M (map)
import Data.Maybe (fromMaybe)
import Data.Time.Clock (UTCTime (..), getCurrentTime,
<API key>)
import Data.Tree (rootLabel)
import Data.Tree.Zipper (findChild, fromTree, hasChildren,
tree)
import System.Random.MWC (Gen, Seed, restore, save, uniform,
withSystemRandom)
import Data.Goban.GameState
import Data.Goban.Types (Color (..), Move (..), Score,
Stone (..), Vertex)
import Data.Goban.Utils (rateScore, winningScore)
import Kurt.Config
import Data.Tree.UCT
import Data.Tree.UCT.GameTree (MoveNode (..), RaveMap,
UCTTreeLoc, newMoveNode,
newRaveMap)
import Debug.TraceOrId (trace)
-- import Data.Tree (drawTree)
data EngineState = EngineState {
getGameState :: !GameState
, getUctTree :: !(UCTTreeLoc Move)
, getRaveMap :: !(RaveMap Move)
, boardSize :: !Int
, getKomi :: !Score
, getConfig :: !KurtConfig
}
type LoopState = (UCTTreeLoc Move, RaveMap Move)
-- result from playout: score, playedMoves, path to startnode in tree
type Result = (Score, [Move], [Move])
-- request for playout: gamestate, path to startnode in tree, seed
type Request = (GameState, [Move], Seed)
newEngineState :: KurtConfig -> EngineState
newEngineState config =
EngineState { getGameState =
newGameState (initialBoardsize config) (initialKomi config)
, getUctTree = newUctTree
, getRaveMap = newRaveMap
, boardSize = initialBoardsize config
, getKomi = initialKomi config
, getConfig = config
}
newUctTree :: UCTTreeLoc Move
newUctTree =
fromTree $ newMoveNode
(trace "UCT tree root move accessed"
(Move (Stone (25,25) White)))
(0.5, 1)
updateEngineState :: EngineState -> Move -> EngineState
updateEngineState eState move =
eState { getGameState = gState', getUctTree = loc' }
where
gState' = updateGameState gState move
gState = getGameState eState
loc' = case move of
(Resign _) -> loc
_otherwise ->
if hasChildren loc
then selectSubtree loc move
else newUctTree
loc = getUctTree eState
selectSubtree :: UCTTreeLoc Move -> Move -> UCTTreeLoc Move
selectSubtree loc move =
loc''
where
loc'' = fromTree $ tree loc'
loc' =
fromMaybe newUctTree
$ findChild ((move ==) . nodeMove . rootLabel) loc
genMove :: EngineState -> Color -> IO (Move, EngineState)
genMove eState color = do
now <- getCurrentTime
let deadline = UTCTime { utctDay = utctDay now
, utctDayTime = thinkPicosecs + utctDayTime now }
let moves = nextMoves gState color
let score = scoreGameState gState
(if null moves
then
if winningScore color score
then return (Pass color, eState)
else return (Resign color, eState)
else (do
seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
(loc', raveMap') <- runUCT loc gState raveMap config deadline seed
let eState' = eState { getUctTree = loc', getRaveMap = raveMap' }
return (bestMoveFromLoc loc' (getState gState) score, eState')))
where
config = getConfig eState
gState = getGameState eState
loc = getUctTree eState
raveMap = M.map (second ((1 +) . (`div` 2))) $ getRaveMap eState
thinkPicosecs =
<API key>
$ fromIntegral (maxTime config) * 1000000000
bestMoveFromLoc :: UCTTreeLoc Move -> GameStateStuff -> Score -> Move
bestMoveFromLoc loc state score =
case principalVariation loc of
[] ->
error "bestMoveFromLoc: principalVariation is empty"
(node : _) ->
if value < 0.1
then
if winningScore color score
then
trace ("bestMoveFromLoc pass " ++ show node)
Pass color
else
trace ("bestMoveFromLoc resign " ++ show node)
Resign color
else
trace ("total sims: " ++ show (nodeVisits$rootLabel$tree$loc)
++ " best: " ++ show node
++ "\n")
-- ++ (drawTree $ fmap show $ tree loc)
move
where
move = nodeMove node
value = nodeValue node
color = nextMoveColor state
runUCT :: UCTTreeLoc Move
-> GameState
-> RaveMap Move
-> KurtConfig
-> UTCTime
-> Seed
-> IO LoopState
runUCT initLoc rootGameState initRaveMap config deadline seed00 = do
uctLoop stateStream0 0
where
uctLoop :: [LoopState] -> Int -> IO LoopState
uctLoop [] _ = return (initLoc, initRaveMap)
uctLoop (st : stateStream) !n = do
_ <- return $! st
let maxRuns = n >= (maxPlayouts config)
now <- getCurrentTime
let timeIsUp = (now > deadline)
(if maxRuns || timeIsUp
then return st
else uctLoop stateStream (n + 1))
stateStream0 = loop0 seed00 (initLoc, initRaveMap)
loop0 :: Seed -> LoopState -> [LoopState]
loop0 seed0 st0 =
map (\(_, st, _) -> st) $ iterate loop (seed0, st0, [])
where
loop (seed, st, results0) =
(seed', st'', results)
where
st'' = updater st' r
r : results = results0 ++ (parMap rdeepseq runOne requests)
(st', seed', requests) = requestor st seed reqNeeded
reqNeeded = max 2 $ maxThreads config - length results0
updater :: LoopState -> Result -> LoopState
updater !st !res =
updateTreeResult st res
requestor :: LoopState -> Seed -> Int -> (LoopState, Seed, [Request])
requestor !st0 seed0 !n =
last $ take n $ iterate r (st0, seed0, [])
where
r :: (LoopState, Seed, [Request]) -> (LoopState, Seed, [Request])
r (!st, seed, rs) = (st', seed', request : rs)
where
seed' = incrSeed seed
st' = (loc, raveMap)
(_, raveMap) = st
request = (leafGameState, path, seed)
(loc, (leafGameState, path)) = nextNode st
nextNode :: LoopState -> (UCTTreeLoc Move, (GameState, [Move]))
nextNode (!loc, !raveMap) =
(loc'', (leafGameState, path))
where
loc'' = backpropagate (\_x -> 0) updateNodeVisits $ expandNode loc' slHeu moves
moves = nextMoves leafGameState $ nextMoveColor $ getState leafGameState
leafGameState = getLeafGameState rootGameState path
(loc', path) = selectLeafPath policy loc
policy = policyRaveUCB1 (<API key> config) (raveWeight config) raveMap
slHeu = <API key> leafGameState config
updateTreeResult :: LoopState -> Result -> LoopState
updateTreeResult (!loc, !raveMap) (!score, !playedMoves, !path) =
(loc', raveMap')
where
raveMap' = updateRaveMap raveMap (rateScore score) $ drop (length playedMoves `div` 3) playedMoves
loc' = backpropagate (rateScore score) updateNodeValue $ getLeaf loc path
simulatePlayout :: GameState -> IO [Move]
simulatePlayout gState = do
seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
let gState' = getLeafGameState gState []
(oneState, playedMoves) <- stToIO $ runOneRandom gState' seed
let score = scoreGameState oneState
trace ("simulatePlayout " ++ show score) $ return ()
return $ reverse playedMoves
runOne :: Request -> Result
runOne (gameState, path, seed) =
(score, playedMoves, path)
where
score = scoreGameState endState
(endState, playedMoves) = runST $ runOneRandom gameState seed
runOneRandom :: GameState -> Seed -> ST s (GameState, [Move])
runOneRandom initState seed = do
rGen <- restore seed
run initState 0 rGen []
where
run :: GameState -> Int -> Gen s -> [Move] -> ST s (GameState, [Move])
run state 1000 _ moves = return (trace ("runOneRandom not done after 1000 moves " ++ show moves) state, [])
run state runCount rGen moves = do
move <- genMoveRand state rGen
let state' = updateGameState state move
case move of
(Pass passColor) -> do
move' <- genMoveRand state' rGen
let state'' = updateGameState state' move'
case move' of
(Pass _) ->
return (state'', moves)
sm@(Move _) ->
run state'' (runCount + 1) rGen (sm : Pass passColor : moves)
(Resign _) ->
error "runOneRandom encountered Resign"
sm@(Move _) ->
run state' (runCount + 1) rGen (sm : moves)
(Resign _) ->
error "runOneRandom encountered Resign"
genMoveRand :: GameState -> Gen s -> ST s Move
genMoveRand state rGen =
pickSane $ freeVertices $ getState state
where
pickSane [] =
return $ Pass color
pickSane [p] = do
let stone = Stone p color
let sane = isSaneMove state stone
return (if sane
then Move stone
else Pass color)
pickSane ps = do
p <- pick ps rGen
let stone = Stone p color
let sane = isSaneMove state stone
(if sane
then return $ Move stone
else pickSane (ps \\ [p]))
color = nextMoveColor $ getState state
pick :: [Vertex] -> Gen s -> ST s Vertex
pick as rGen = do
i <- liftM (`mod` length as) $ uniform rGen
return $ as !! i
incrSeed :: Seed -> Seed
incrSeed !seed =
runST $ do
gen <- restore seed
x <- uniform gen
_ <- return $ x + (1 :: Int)
seed' <- save gen
return $! seed'
|
# k0nsl's blog
mirrored blog posts from my personal platform.
|
// <API key>: AGPL-3.0-only
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { number } from '@storybook/addon-knobs';
import { LightboxGallery, Props } from './LightboxGallery';
import { setup as setupI18n } from '../../js/modules/i18n';
import enMessages from '../../_locales/en/messages.json';
import { IMAGE_JPEG, VIDEO_MP4 } from '../types/MIME';
const i18n = setupI18n('en', enMessages);
const story = storiesOf('Components/LightboxGallery', module);
const createProps = (overrideProps: Partial<Props> = {}): Props => ({
close: action('close'),
i18n,
media: overrideProps.media || [],
onSave: action('onSave'),
selectedIndex: number('selectedIndex', overrideProps.selectedIndex || 0),
});
story.add('Image and Video', () => {
const props = createProps({
media: [
{
attachment: {
contentType: IMAGE_JPEG,
fileName: '<API key>.jpg',
url: '/fixtures/<API key>.jpg',
caption:
'Still from The Lighthouse, starring Robert Pattinson and Willem Defoe.',
},
contentType: IMAGE_JPEG,
index: 0,
message: {
attachments: [],
id: 'image-msg',
received_at: Date.now(),
},
objectURL: '/fixtures/<API key>.jpg',
},
{
attachment: {
contentType: VIDEO_MP4,
fileName: '<API key>.mp4',
url: '/fixtures/<API key>.mp4',
},
contentType: VIDEO_MP4,
index: 1,
message: {
attachments: [],
id: 'video-msg',
received_at: Date.now(),
},
objectURL: '/fixtures/<API key>.mp4',
},
],
});
return <LightboxGallery {...props} />;
});
story.add('Missing Media', () => {
const props = createProps({
media: [
{
attachment: {
contentType: IMAGE_JPEG,
fileName: '<API key>.jpg',
url: '/fixtures/<API key>.jpg',
},
contentType: IMAGE_JPEG,
index: 0,
message: {
attachments: [],
id: 'image-msg',
received_at: Date.now(),
},
objectURL: undefined,
},
],
});
return <LightboxGallery {...props} />;
});
|
// app.photoGrid
var Backbone = require("backbone");
// var _ = require("underscore");
var $ = require("jquery");
var ImageGridFuncs = require("./<API key>");
var ImageCollection = require("../models/<API key>");
var ImageView = require("./photo_grid_image");
module.exports = Backbone.View.extend({
el: '#photo-grid',
initialize: function () {
"use strict";
if (this.$el.length === 1) {
var gridJSON = this.$(".hid");
if (gridJSON.length === 1) {
this.funcs = new ImageGridFuncs();
this.template = this.funcs.slideTemplate();
// there is only one allowed div.hid
gridJSON = JSON.parse(gridJSON[0].innerHTML);
if (gridJSON.spacer_URL && gridJSON.image_URL) {
this.model.set({
parentModel: this.model, // pass as reference
spacerURL: gridJSON.spacer_URL,
imageURL: gridJSON.image_URL,
spacers: gridJSON.spacers,
images: gridJSON.images,
// shuffle image order:
imagesShuffled: this.funcs.shuffleArray(gridJSON.images),
});
this.setupGrid();
}
this.model.on({
'change:currentSlide': this.modelChange
}, this);
app.mindbodyModel.on({
'change:popoverVisible': this.killSlides
}, this);
}
}
},
setupGrid: function () {
"use strict";
var that = this,
spacers = this.model.get("spacers"),
randomInt,
imageCollection = new ImageCollection(),
i;
for (i = 0; i < this.model.get("images").length; i += 1) {
randomInt = that.funcs.getRandomInt(0, spacers.length);
imageCollection.add({
// push some info to individual views:
parentModel: this.model,
order: i,
spacerURL: this.model.get("spacerURL"),
spacer: spacers[randomInt],
imageURL: this.model.get("imageURL"),
image: this.model.get("imagesShuffled")[i],
});
}
imageCollection.each(this.imageView, this);
},
imageView: function (imageModel) {
"use strict";
var imageView = new ImageView({model: imageModel});
this.$el.append(imageView.render().el);
},
modelChange: function () {
"use strict";
var currSlide = this.model.get("currentSlide"),
allImages = this.model.get("imageURL"),
imageInfo,
imageViewer,
imgWidth,
slideDiv;
if (currSlide !== false) {
if (app.mindbodyModel.get("popoverVisible") !== true) {
app.mindbodyModel.set({popoverVisible : true});
}
// retrieve cached DOM object:
imageViewer = app.mbBackGroundShader.openPopUp("imageViewer");
// set the stage:
imageViewer.html(this.template(this.model.toJSON()));
// select div.slide, the ugly way:
slideDiv = imageViewer[0].<API key>("slide")[0];
// pull the array of info about the image:
imageInfo = this.model.get("images")[currSlide];
// calculate the size of the image when it fits the slideshow:
imgWidth = this.funcs.findSlideSize(imageInfo,
slideDiv.offsetWidth,
slideDiv.offsetHeight);
slideDiv.innerHTML = '<img src="' + allImages + imageInfo.filename +
'" style="width: ' + imgWidth + 'px;" />';
}
},
killSlides: function () {
"use strict";
if (app.mindbodyModel.get("popoverVisible") === false) {
// popover is gone. No more slideshow.
this.model.set({currentSlide : false});
}
},
});
|
package ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.transport;
import net.minecraft.item.Item;
import net.minecraftforge.common.util.ForgeDirection;
import ua.pp.shurgent.tfctech.integration.bc.BCStuff;
import ua.pp.shurgent.tfctech.integration.bc.ModPipeIconProvider;
import ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.handlers.<API key>;
import buildcraft.api.core.IIconProvider;
import buildcraft.transport.pipes.PipeItemsQuartz;
import buildcraft.transport.pipes.events.PipeEventItem;
public class <API key> extends PipeItemsQuartz {
public <API key>(Item item) {
super(item);
}
@Override
public IIconProvider getIconProvider() {
return BCStuff.pipeIconProvider;
}
@Override
public int getIconIndex(ForgeDirection direction) {
return ModPipeIconProvider.TYPE.<API key>.ordinal();
}
public void eventHandler(PipeEventItem.AdjustSpeed event) {
super.eventHandler(event);
}
public void eventHandler(PipeEventItem.Entered event) {
event.item.setInsertionHandler(<API key>.INSTANCE);
}
}
|
package org.crazyit.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class StartActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bn = (Button)findViewById(R.id.bn);
bn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
Intent intent = new Intent(StartActivity.this
, SecondActivity.class);
startActivity(intent);
}
});
}
}
|
// Remove the particular item
function removeArr(arr , removeItem){
if(arr.indexOf(removeItem) > -1){
arr.splice(arr.indexOf(removeItem),1);
}
return arr;
}
|
declared in [MTMatrix](MTMatrix.hpp.md)
{ .cpp }
MTMatrix::MTMatrix(int rows, int cols)
{
//std::clog << "MTMatrix(" << rows << ", " << cols << ")" << std::endl;
if (cols > 0 && rows > 0) {
_rows = rows;
_cols = cols;
_elements = new double[_rows * _cols];
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = 0.0; }
}
}
// make a real copy
MTMatrix::MTMatrix(MTMatrix const & m)
: MTMatrix(m._rows,m._cols)
{
//std::clog << "MTMatrix(MTMatrix(" << m._rows << ", " << m._cols << "))" << std::endl;
_transposed = m._transposed;
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = m._elements[i]; }
}
MTMatrix & MTMatrix::operator=(MTMatrix const & m)
{
if (m._cols != _cols || m._rows != _rows) {
if (_elements) {
delete[] _elements;
_elements = nullptr; }
_cols = m._cols; _rows = m._rows;
}
if (! _elements) {
_elements = new double[_rows * _cols];
}
_transposed = m._transposed;
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = m._elements[i]; }
}
deserialize a MTMatrix from its string representation
TODO :exclamation:
{ .cpp }
MTMatrix::MTMatrix(std::string const & str)
{
}
|
package ru.mos.polls.ourapps.ui.adapter;
import java.util.ArrayList;
import java.util.List;
import ru.mos.polls.base.BaseRecyclerAdapter;
import ru.mos.polls.base.<API key>;
import ru.mos.polls.ourapps.model.OurApplication;
import ru.mos.polls.ourapps.vm.item.OurApplicationVM;
public class OurAppsAdapter extends BaseRecyclerAdapter<<API key>> {
public void add(List<OurApplication> list) {
List<<API key>> rbvm = new ArrayList<>();
for (OurApplication ourApp : list) {
rbvm.add(new OurApplicationVM(ourApp));
}
addData(rbvm);
}
}
|
using System;
namespace SourceCodeCounter.Core
{
<summary>
The exception that is thrown when a command-line argument is invalid.
</summary>
internal class <API key> : Exception
{
readonly string _argument;
public <API key>(string argument)
: base("Invalid argument: '" + argument + "'")
{
_argument = argument;
}
public <API key>(string argument, string message)
: base(message)
{
_argument = argument;
}
public <API key>(string argument, string message, Exception inner)
: base(message, inner)
{
_argument = argument;
}
public <API key>(string message, Exception inner)
: base(message, inner)
{
}
public string Argument
{
get { return _argument; }
}
}
}
|
html{
margin:0 auto;
}
body {
background:url(images_white/background.gif) repeat-y top center #fff;
color:#404040;
/* font:76% Verdana,Tahoma,Arial,sans-serif; */
line-height:1.3em;
margin:0 auto;
padding:0;
}
/* Menu */
#top_menu {
position:relative;
/* color: #6666aa; */
/* background-color: #aaccee; */
width:1010px;
margin:0 auto;
}
#top{
margin:0 auto;
}
#humo_menu {
background: linear-gradient(rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
margin:0 auto;
}
#humo_menu a {
color:#000000;
}
/* Pop-up menu */
#humo_menu ul.humo_menu_item2 li a{
background: linear-gradient(rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
}
#humo_menu a:visited { color: #000000; }
#humo_menu a:active {color: #2288dd; }
#humo_menu a:hover {color: #2288dd; }
/* #humo_menu a:hover { */
#humo_menu a:hover, #humo_menu ul.humo_menu_item2 li a:hover {
background:url("images_white/white.jpg") repeat left top;
}
#humo_menu #current {
}
#humo_menu #current a, #humo_menu #current_top {
background:url("images_white/white.jpg") repeat left top;
color:#333;
}
/* top bar in left - content - right boxes: only in main menu */
.mainmenu_bar{
background:none;
/* h2 {border-bottom:4px solid #dadada; color:#4088b8; font-size:1.4em; letter-spacing:-1px; margin:0 0 10px; padding:0 2px 2px 5px;} */
border-bottom:4px solid #dadada; color:#4088b8;
}
#mainmenu_centerbox {
box-shadow: 0px 0px 0px #999;
-moz-box-shadow: 0px 0px 0px #999;
-webkit-box-shadow: 0px 0px 0px #999;
}
.search_bar{
background:url("images_white/white.jpg") repeat left top;
/* background:none; */
}
#content {
display:block;
padding-left:10px;
position:relative;
z-index:3;
height:100%;
/* overflow:auto; */
max-height:90%;
top:35px;
width:1005px;
margin:0 auto;
}
#rtlcontent {
display:block;
padding-right:10px;
position:relative;
z-index:3;
height:100%;
/* overflow:auto; */
max-height:95%;
top:35px;
width:1024px;
margin:0 auto;
}
table.index_table{
width:1000px;
}
/* Tables */
table.humo { background-color: #ffffff; }
/* 1st table A-Z */
.border {
border: none;
/* border-collapse: collapse; */
}
table.humo {
-moz-box-shadow: 0px 0px 0px;
-webkit-box-shadow: 0px 0px 0px;
box-shadow: 0px 0px 0px;
}
table.humo td {
/* border: ridge 1px #3355cc; */
border:none;
/* background-color: #cceeff; */ /* achtergrond gezinsblad en 1e tabel */
border-bottom: 2px solid #dadada;
}
table.humo tr:first-of-type td { border:none; border-bottom: 2px solid #dadada; }
table.humo tr:first-of-type th { border:none; }
/* 2nd table A-Z */
.family_page_toptext {
color: #ffffff;
background-image: none;
color:black;
}
td.style_tree_text { background-color: #eeeeff; }
.table_headline{
background: linear-gradient(to bottom, rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
}
table.standard td.table_header { background-image: none; }
div.photobook{ background-color:#FFFFFF; }
.help_box { background-color:#FFFFFF; }
table.container{ background-color:#FFFFFF; }
table.reltable td { border:0px; }
|
#ifndef AssimpSceneLoader_H
#define AssimpSceneLoader_H
#include <string>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/Importer.hpp>
#include "Common/Singleton.h"
#include "Mesh/Mesh.h"
#include "Shader/ShaderProgram.h"
#include "Scene/Material.h"
using std::string;
class AssimpSceneLoader : public Singleton<AssimpSceneLoader>
{
public:
vector<Mesh*> meshes;
const aiScene* assimpScene;
vector<Material*> materials;
AssimpSceneLoader();
void load(string file);
Mesh * initMesh(aiMesh * assMesh);
void initNode(aiNode * parent);
void printColor(const string &name, const aiColor4D & color);
};
#endif // AssimpSceneLoader_H
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class <API key>
Inherits DevExpress.XtraReports.UI.XtraReport
'XtraReport overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Designer
'It can be modified using the Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim StoredProcQuery1 As DevExpress.DataAccess.Sql.StoredProcQuery = New DevExpress.DataAccess.Sql.StoredProcQuery()
Dim QueryParameter1 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter2 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter3 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter4 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim resources As System.ComponentModel.<API key> = New System.ComponentModel.<API key>(GetType(<API key>))
Dim XrSummary1 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary2 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary3 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary4 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary5 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary6 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary7 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary8 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary9 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary10 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary11 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary12 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary13 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary14 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary15 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary16 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary17 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary18 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Me.Detail = New DevExpress.XtraReports.UI.DetailBand()
Me.XrLabel18 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel19 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel20 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel21 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel22 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel23 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel24 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel25 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel26 = New DevExpress.XtraReports.UI.XRLabel()
Me.TopMargin = New DevExpress.XtraReports.UI.TopMarginBand()
Me.BottomMargin = New DevExpress.XtraReports.UI.BottomMarginBand()
Me.SqlDataSource1 = New DevExpress.DataAccess.Sql.SqlDataSource(Me.components)
Me.GroupHeaderSucursal = New DevExpress.XtraReports.UI.GroupHeaderBand()
Me.XrLabel2 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel1 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel15 = New DevExpress.XtraReports.UI.XRLabel()
Me.GroupHeaderCliente = New DevExpress.XtraReports.UI.GroupHeaderBand()
Me.XrLabel3 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel16 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel17 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel6 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel7 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel8 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel9 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel10 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel11 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel12 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel13 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel14 = New DevExpress.XtraReports.UI.XRLabel()
Me.PageFooterBand1 = New DevExpress.XtraReports.UI.PageFooterBand()
Me.ReportHeaderBand1 = New DevExpress.XtraReports.UI.ReportHeaderBand()
Me.GroupFooterBand1 = New DevExpress.XtraReports.UI.GroupFooterBand()
Me.GroupFooterBand2 = New DevExpress.XtraReports.UI.GroupFooterBand()
Me.XrLabel47 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel46 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel28 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel29 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel30 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel31 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel32 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel33 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel34 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel35 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel36 = New DevExpress.XtraReports.UI.XRLabel()
Me.ReportFooterBand1 = New DevExpress.XtraReports.UI.ReportFooterBand()
Me.XrLabel45 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel27 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel37 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel38 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel39 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel40 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel41 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel42 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel43 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel44 = New DevExpress.XtraReports.UI.XRLabel()
Me.Title = New DevExpress.XtraReports.UI.XRControlStyle()
Me.FieldCaption = New DevExpress.XtraReports.UI.XRControlStyle()
Me.PageInfo = New DevExpress.XtraReports.UI.XRControlStyle()
Me.DataField = New DevExpress.XtraReports.UI.XRControlStyle()
Me.PageHeader = New DevExpress.XtraReports.UI.PageHeaderBand()
Me.XrLabel49 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel48 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrPageInfo4 = New DevExpress.XtraReports.UI.XRPageInfo()
Me.XrPageInfo3 = New DevExpress.XtraReports.UI.XRPageInfo()
Me.XrLabel4 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel5 = New DevExpress.XtraReports.UI.XRLabel()
Me.lblHasta = New DevExpress.XtraReports.UI.XRLabel()
Me.pdFechaFinal = New DevExpress.XtraReports.Parameters.Parameter()
Me.lblCliente = New DevExpress.XtraReports.UI.XRLabel()
Me.psCliente = New DevExpress.XtraReports.Parameters.Parameter()
Me.lblNombreReporte = New DevExpress.XtraReports.UI.XRLabel()
Me.lblEmpresa = New DevExpress.XtraReports.UI.XRLabel()
Me.psEmpresa = New DevExpress.XtraReports.Parameters.Parameter()
Me.piIDBodega = New DevExpress.XtraReports.Parameters.Parameter()
Me.piIDCliente = New DevExpress.XtraReports.Parameters.Parameter()
Me.piConsolidaSucursal = New DevExpress.XtraReports.Parameters.Parameter()
Me.piEnDolar = New DevExpress.XtraReports.Parameters.Parameter()
Me.CalculatedField1 = New DevExpress.XtraReports.UI.CalculatedField()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'Detail
'
Me.Detail.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel18, Me.XrLabel19, Me.XrLabel20, Me.XrLabel21, Me.XrLabel22, Me.XrLabel23, Me.XrLabel24, Me.XrLabel25, Me.XrLabel26})
Me.Detail.HeightF = 21.7083!
Me.Detail.Name = "Detail"
Me.Detail.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.Detail.StyleName = "DataField"
Me.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'XrLabel18
'
Me.XrLabel18.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.SaldoNovencido", "{0:n2}")})
Me.XrLabel18.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel18.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 1.000023!)
Me.XrLabel18.Name = "XrLabel18"
Me.XrLabel18.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel18.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel18.StylePriority.UseFont = False
Me.XrLabel18.StylePriority.UseTextAlignment = False
Me.XrLabel18.Text = "XrLabel18"
Me.XrLabel18.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel19
'
Me.XrLabel19.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldoa30", "{0:n2}")})
Me.XrLabel19.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel19.LocationFloat = New DevExpress.Utils.PointFloat(130.7548!, 1.000023!)
Me.XrLabel19.Name = "XrLabel19"
Me.XrLabel19.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel19.SizeF = New System.Drawing.SizeF(75.74262!, 18.0!)
Me.XrLabel19.StylePriority.UseFont = False
Me.XrLabel19.StylePriority.UseTextAlignment = False
Me.XrLabel19.Text = "XrLabel19"
Me.XrLabel19.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel20
'
Me.XrLabel20.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo31a60", "{0:n2}")})
Me.XrLabel20.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel20.LocationFloat = New DevExpress.Utils.PointFloat(206.4974!, 1.000023!)
Me.XrLabel20.Name = "XrLabel20"
Me.XrLabel20.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel20.SizeF = New System.Drawing.SizeF(90.87666!, 18.0!)
Me.XrLabel20.StylePriority.UseFont = False
Me.XrLabel20.StylePriority.UseTextAlignment = False
Me.XrLabel20.Text = "XrLabel20"
Me.XrLabel20.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel21
'
Me.XrLabel21.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo61a90", "{0:n2}")})
Me.XrLabel21.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel21.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 0.0!)
Me.XrLabel21.Name = "XrLabel21"
Me.XrLabel21.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel21.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel21.StylePriority.UseFont = False
Me.XrLabel21.StylePriority.UseTextAlignment = False
Me.XrLabel21.Text = "XrLabel21"
Me.XrLabel21.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel22
'
Me.XrLabel22.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo91a120", "{0:n2}")})
Me.XrLabel22.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel22.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 0.0!)
Me.XrLabel22.Name = "XrLabel22"
Me.XrLabel22.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel22.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel22.StylePriority.UseFont = False
Me.XrLabel22.StylePriority.UseTextAlignment = False
Me.XrLabel22.Text = "XrLabel22"
Me.XrLabel22.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel23
'
Me.XrLabel23.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo121a180", "{0:n2}")})
Me.XrLabel23.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel23.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 0.0!)
Me.XrLabel23.Name = "XrLabel23"
Me.XrLabel23.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel23.SizeF = New System.Drawing.SizeF(89.2699!, 18.0!)
Me.XrLabel23.StylePriority.UseFont = False
Me.XrLabel23.StylePriority.UseTextAlignment = False
Me.XrLabel23.Text = "XrLabel23"
Me.XrLabel23.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel24
'
Me.XrLabel24.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo181a600", "{0:n2}")})
Me.XrLabel24.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel24.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 0.0!)
Me.XrLabel24.Name = "XrLabel24"
Me.XrLabel24.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel24.SizeF = New System.Drawing.SizeF(85.12994!, 18.0!)
Me.XrLabel24.StylePriority.UseFont = False
Me.XrLabel24.StylePriority.UseTextAlignment = False
Me.XrLabel24.Text = "XrLabel24"
Me.XrLabel24.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel25
'
Me.XrLabel25.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldomas600", "{0:n2}")})
Me.XrLabel25.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel25.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 0.0!)
Me.XrLabel25.Name = "XrLabel25"
Me.XrLabel25.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel25.SizeF = New System.Drawing.SizeF(81.20685!, 18.0!)
Me.XrLabel25.StylePriority.UseFont = False
Me.XrLabel25.StylePriority.UseTextAlignment = False
Me.XrLabel25.Text = "XrLabel25"
Me.XrLabel25.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel26
'
Me.XrLabel26.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.TotalCliente", "{0:n2}")})
Me.XrLabel26.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel26.LocationFloat = New DevExpress.Utils.PointFloat(809.7319!, 0.0!)
Me.XrLabel26.Name = "XrLabel26"
Me.XrLabel26.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel26.SizeF = New System.Drawing.SizeF(80.26801!, 18.0!)
Me.XrLabel26.StylePriority.UseFont = False
Me.XrLabel26.StylePriority.UseTextAlignment = False
Me.XrLabel26.Text = "XrLabel26"
Me.XrLabel26.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'TopMargin
'
Me.TopMargin.HeightF = 100.0!
Me.TopMargin.Name = "TopMargin"
Me.TopMargin.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'BottomMargin
'
Me.BottomMargin.HeightF = 100.0!
Me.BottomMargin.Name = "BottomMargin"
Me.BottomMargin.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'SqlDataSource1
'
Me.SqlDataSource1.ConnectionName = "Ced_Connection"
Me.SqlDataSource1.Name = "SqlDataSource1"
StoredProcQuery1.Name = "<API key>"
QueryParameter1.Name = "@IDBodega"
QueryParameter1.Type = GetType(Integer)
QueryParameter1.ValueInfo = "0"
QueryParameter2.Name = "@IDCliente"
QueryParameter2.Type = GetType(Integer)
QueryParameter2.ValueInfo = "0"
QueryParameter3.Name = "@FechaCorte"
QueryParameter3.Type = GetType(DevExpress.DataAccess.Expression)
QueryParameter3.Value = New DevExpress.DataAccess.Expression("[Parameters.pdFechaFinal]", GetType(Date))
QueryParameter4.Name = "@EnDolar"
QueryParameter4.Type = GetType(DevExpress.DataAccess.Expression)
QueryParameter4.Value = New DevExpress.DataAccess.Expression("[Parameters.piEnDolar]", GetType(Short))
StoredProcQuery1.Parameters.Add(QueryParameter1)
StoredProcQuery1.Parameters.Add(QueryParameter2)
StoredProcQuery1.Parameters.Add(QueryParameter3)
StoredProcQuery1.Parameters.Add(QueryParameter4)
StoredProcQuery1.StoredProcName = "<API key>"
Me.SqlDataSource1.Queries.AddRange(New DevExpress.DataAccess.Sql.SqlQuery() {StoredProcQuery1})
Me.SqlDataSource1.<API key> = resources.GetString("SqlDataSource1.<API key>")
'
'GroupHeaderSucursal
'
Me.GroupHeaderSucursal.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel2, Me.XrLabel1, Me.XrLabel15})
Me.GroupHeaderSucursal.GroupFields.AddRange(New DevExpress.XtraReports.UI.GroupField() {New DevExpress.XtraReports.UI.GroupField("Bodega", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)})
Me.GroupHeaderSucursal.HeightF = 21.33335!
Me.GroupHeaderSucursal.KeepTogether = True
Me.GroupHeaderSucursal.Level = 1
Me.GroupHeaderSucursal.Name = "GroupHeaderSucursal"
Me.GroupHeaderSucursal.RepeatEveryPage = True
'
'XrLabel2
'
Me.XrLabel2.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Bodega")})
Me.XrLabel2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel2.LocationFloat = New DevExpress.Utils.PointFloat(227.5867!, 3.333346!)
Me.XrLabel2.Name = "XrLabel2"
Me.XrLabel2.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel2.SizeF = New System.Drawing.SizeF(363.2288!, 18.0!)
Me.XrLabel2.StyleName = "DataField"
Me.XrLabel2.StylePriority.UseFont = False
Me.XrLabel2.Text = "XrLabel2"
'
'XrLabel1
'
Me.XrLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel1.LocationFloat = New DevExpress.Utils.PointFloat(92.38262!, 1.333332!)
Me.XrLabel1.Name = "XrLabel1"
Me.XrLabel1.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel1.SizeF = New System.Drawing.SizeF(67.70178!, 20.00002!)
Me.XrLabel1.StyleName = "FieldCaption"
Me.XrLabel1.StylePriority.UseFont = False
Me.XrLabel1.Text = "Sucursal"
'
'XrLabel15
'
Me.XrLabel15.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.IDBodega")})
Me.XrLabel15.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel15.LocationFloat = New DevExpress.Utils.PointFloat(175.6743!, 3.333346!)
Me.XrLabel15.Name = "XrLabel15"
Me.XrLabel15.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel15.SizeF = New System.Drawing.SizeF(41.70179!, 18.0!)
Me.XrLabel15.StylePriority.UseFont = False
Me.XrLabel15.Text = "XrLabel15"
'
'GroupHeaderCliente
'
Me.GroupHeaderCliente.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel3, Me.XrLabel16, Me.XrLabel17})
Me.GroupHeaderCliente.GroupFields.AddRange(New DevExpress.XtraReports.UI.GroupField() {New DevExpress.XtraReports.UI.GroupField("IDCliente", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)})
Me.GroupHeaderCliente.HeightF = 20.00002!
Me.GroupHeaderCliente.KeepTogether = True
Me.GroupHeaderCliente.Name = "GroupHeaderCliente"
Me.GroupHeaderCliente.RepeatEveryPage = True
Me.GroupHeaderCliente.StyleName = "FieldCaption"
'
'XrLabel3
'
Me.XrLabel3.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel3.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 0.0!)
Me.XrLabel3.Name = "XrLabel3"
Me.XrLabel3.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel3.SizeF = New System.Drawing.SizeF(67.70178!, 20.00002!)
Me.XrLabel3.StyleName = "FieldCaption"
Me.XrLabel3.StylePriority.UseFont = False
Me.XrLabel3.Text = "Cliente"
'
'XrLabel16
'
Me.XrLabel16.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.IDCliente")})
Me.XrLabel16.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel16.LocationFloat = New DevExpress.Utils.PointFloat(93.29166!, 0.0!)
Me.XrLabel16.Name = "XrLabel16"
Me.XrLabel16.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel16.SizeF = New System.Drawing.SizeF(41.70176!, 18.0!)
Me.XrLabel16.StylePriority.UseFont = False
Me.XrLabel16.Text = "XrLabel16"
'
'XrLabel17
'
Me.XrLabel17.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.NOMBRE")})
Me.XrLabel17.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel17.LocationFloat = New DevExpress.Utils.PointFloat(145.2041!, 0.0!)
Me.XrLabel17.Name = "XrLabel17"
Me.XrLabel17.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel17.SizeF = New System.Drawing.SizeF(298.5751!, 18.0!)
Me.XrLabel17.StylePriority.UseFont = False
Me.XrLabel17.Text = "XrLabel17"
'
'XrLabel6
'
Me.XrLabel6.LocationFloat = New DevExpress.Utils.PointFloat(15.24499!, 149.5!)
Me.XrLabel6.Name = "XrLabel6"
Me.XrLabel6.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel6.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel6.Text = "Saldo Novencido"
'
'XrLabel7
'
Me.XrLabel7.LocationFloat = New DevExpress.Utils.PointFloat(130.7547!, 149.5!)
Me.XrLabel7.Name = "XrLabel7"
Me.XrLabel7.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel7.SizeF = New System.Drawing.SizeF(75.74263!, 18.0!)
Me.XrLabel7.Text = "Saldoa30"
'
'XrLabel8
'
Me.XrLabel8.LocationFloat = New DevExpress.Utils.PointFloat(227.5865!, 149.5!)
Me.XrLabel8.Name = "XrLabel8"
Me.XrLabel8.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel8.SizeF = New System.Drawing.SizeF(69.78761!, 18.0!)
Me.XrLabel8.Text = "Saldo31a60"
'
'XrLabel9
'
Me.XrLabel9.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 149.5!)
Me.XrLabel9.Name = "XrLabel9"
Me.XrLabel9.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel9.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel9.Text = "Saldo61a90"
'
'XrLabel10
'
Me.XrLabel10.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 149.5!)
Me.XrLabel10.Name = "XrLabel10"
Me.XrLabel10.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel10.SizeF = New System.Drawing.SizeF(89.20593!, 18.0!)
Me.XrLabel10.Text = "Saldo91a120"
'
'XrLabel11
'
Me.XrLabel11.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 149.5!)
Me.XrLabel11.Name = "XrLabel11"
Me.XrLabel11.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel11.SizeF = New System.Drawing.SizeF(89.2699!, 18.0!)
Me.XrLabel11.Text = "Saldo121a180"
'
'XrLabel12
'
Me.XrLabel12.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 149.5!)
Me.XrLabel12.Name = "XrLabel12"
Me.XrLabel12.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel12.SizeF = New System.Drawing.SizeF(94.47827!, 18.0!)
Me.XrLabel12.Text = "Saldo181a600"
'
'XrLabel13
'
Me.XrLabel13.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 149.5!)
Me.XrLabel13.Name = "XrLabel13"
Me.XrLabel13.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel13.SizeF = New System.Drawing.SizeF(81.20685!, 18.0!)
Me.XrLabel13.Text = "Saldomas600"
'
'XrLabel14
'
Me.XrLabel14.LocationFloat = New DevExpress.Utils.PointFloat(809.7319!, 149.5!)
Me.XrLabel14.Name = "XrLabel14"
Me.XrLabel14.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel14.SizeF = New System.Drawing.SizeF(80.26813!, 18.0!)
Me.XrLabel14.Text = "Total Cliente"
'
'PageFooterBand1
'
Me.PageFooterBand1.HeightF = 31.00001!
Me.PageFooterBand1.Name = "PageFooterBand1"
'
'ReportHeaderBand1
'
Me.ReportHeaderBand1.HeightF = 0.0!
Me.ReportHeaderBand1.Name = "ReportHeaderBand1"
'
'GroupFooterBand1
'
Me.GroupFooterBand1.HeightF = 1.0!
Me.GroupFooterBand1.Name = "GroupFooterBand1"
'
'GroupFooterBand2
'
Me.GroupFooterBand2.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel47, Me.XrLabel46, Me.XrLabel28, Me.XrLabel29, Me.XrLabel30, Me.XrLabel31, Me.XrLabel32, Me.XrLabel33, Me.XrLabel34, Me.XrLabel35, Me.XrLabel36})
Me.GroupFooterBand2.HeightF = 54.99999!
Me.GroupFooterBand2.Level = 1
Me.GroupFooterBand2.Name = "GroupFooterBand2"
'
'XrLabel47
'
Me.XrLabel47.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Bodega")})
Me.XrLabel47.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel47.LocationFloat = New DevExpress.Utils.PointFloat(175.6743!, 0.0!)
Me.XrLabel47.Name = "XrLabel47"
Me.XrLabel47.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel47.SizeF = New System.Drawing.SizeF(363.2288!, 18.0!)
Me.XrLabel47.StyleName = "DataField"
Me.XrLabel47.StylePriority.UseFont = False
Me.XrLabel47.Text = "XrLabel2"
'
'XrLabel46
'
Me.XrLabel46.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel46.LocationFloat = New DevExpress.Utils.PointFloat(34.375!, 0.0!)
Me.XrLabel46.Name = "XrLabel46"
Me.XrLabel46.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel46.SizeF = New System.Drawing.SizeF(140.3196!, 20.00002!)
Me.XrLabel46.StyleName = "FieldCaption"
Me.XrLabel46.StylePriority.UseFont = False
Me.XrLabel46.Text = "Totales de la Sucursal :"
'
'XrLabel28
'
Me.XrLabel28.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.SaldoNovencido")})
Me.XrLabel28.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel28.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 35.00001!)
Me.XrLabel28.Name = "XrLabel28"
Me.XrLabel28.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel28.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel28.StyleName = "FieldCaption"
Me.XrLabel28.StylePriority.UseFont = False
Me.XrLabel28.StylePriority.UseTextAlignment = False
XrSummary1.FormatString = "{0:n2}"
XrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel28.Summary = XrSummary1
Me.XrLabel28.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel29
'
Me.XrLabel29.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldoa30", "{0:C2}")})
Me.XrLabel29.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel29.LocationFloat = New DevExpress.Utils.PointFloat(130.7548!, 35.00001!)
Me.XrLabel29.Name = "XrLabel29"
Me.XrLabel29.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel29.SizeF = New System.Drawing.SizeF(60.11765!, 18.0!)
Me.XrLabel29.StyleName = "FieldCaption"
Me.XrLabel29.StylePriority.UseFont = False
Me.XrLabel29.StylePriority.UseTextAlignment = False
XrSummary2.FormatString = "{0:n2}"
XrSummary2.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel29.Summary = XrSummary2
Me.XrLabel29.Text = "XrLabel29"
Me.XrLabel29.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel30
'
Me.XrLabel30.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo31a60", "{0:C2}")})
Me.XrLabel30.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel30.LocationFloat = New DevExpress.Utils.PointFloat(206.4975!, 35.00001!)
Me.XrLabel30.Name = "XrLabel30"
Me.XrLabel30.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel30.SizeF = New System.Drawing.SizeF(90.87663!, 18.0!)
Me.XrLabel30.StyleName = "FieldCaption"
Me.XrLabel30.StylePriority.UseFont = False
Me.XrLabel30.StylePriority.UseTextAlignment = False
XrSummary3.FormatString = "{0:n2}"
XrSummary3.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel30.Summary = XrSummary3
Me.XrLabel30.Text = "XrLabel30"
Me.XrLabel30.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel31
'
Me.XrLabel31.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo61a90", "{0:C2}")})
Me.XrLabel31.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel31.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 36.99999!)
Me.XrLabel31.Name = "XrLabel31"
Me.XrLabel31.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel31.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel31.StyleName = "FieldCaption"
Me.XrLabel31.StylePriority.UseFont = False
Me.XrLabel31.StylePriority.UseTextAlignment = False
XrSummary4.FormatString = "{0:n2}"
XrSummary4.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel31.Summary = XrSummary4
Me.XrLabel31.Text = "XrLabel31"
Me.XrLabel31.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel32
'
Me.XrLabel32.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo91a120", "{0:C2}")})
Me.XrLabel32.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel32.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 35.00001!)
Me.XrLabel32.Name = "XrLabel32"
Me.XrLabel32.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel32.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel32.StyleName = "FieldCaption"
Me.XrLabel32.StylePriority.UseFont = False
Me.XrLabel32.StylePriority.UseTextAlignment = False
XrSummary5.FormatString = "{0:n2}"
XrSummary5.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel32.Summary = XrSummary5
Me.XrLabel32.Text = "XrLabel32"
Me.XrLabel32.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel33
'
Me.XrLabel33.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo121a180", "{0:C2}")})
Me.XrLabel33.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel33.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 35.00001!)
Me.XrLabel33.Name = "XrLabel33"
Me.XrLabel33.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel33.SizeF = New System.Drawing.SizeF(89.26993!, 18.0!)
Me.XrLabel33.StyleName = "FieldCaption"
Me.XrLabel33.StylePriority.UseFont = False
Me.XrLabel33.StylePriority.UseTextAlignment = False
XrSummary6.FormatString = "{0:n2}"
XrSummary6.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel33.Summary = XrSummary6
Me.XrLabel33.Text = "XrLabel33"
Me.XrLabel33.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel34
'
Me.XrLabel34.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo181a600", "{0:C2}")})
Me.XrLabel34.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel34.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 35.00001!)
Me.XrLabel34.Name = "XrLabel34"
Me.XrLabel34.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel34.SizeF = New System.Drawing.SizeF(85.13!, 18.0!)
Me.XrLabel34.StyleName = "FieldCaption"
Me.XrLabel34.StylePriority.UseFont = False
Me.XrLabel34.StylePriority.UseTextAlignment = False
XrSummary7.FormatString = "{0:n2}"
XrSummary7.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel34.Summary = XrSummary7
Me.XrLabel34.Text = "XrLabel34"
Me.XrLabel34.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel35
'
Me.XrLabel35.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldomas600", "{0:C2}")})
Me.XrLabel35.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel35.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 35.00001!)
Me.XrLabel35.Name = "XrLabel35"
Me.XrLabel35.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel35.SizeF = New System.Drawing.SizeF(81.20691!, 18.0!)
Me.XrLabel35.StyleName = "FieldCaption"
Me.XrLabel35.StylePriority.UseFont = False
Me.XrLabel35.StylePriority.UseTextAlignment = False
XrSummary8.FormatString = "{0:n2}"
XrSummary8.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel35.Summary = XrSummary8
Me.XrLabel35.Text = "XrLabel35"
Me.XrLabel35.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel36
'
Me.XrLabel36.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.TotalCliente", "{0:C2}")})
Me.XrLabel36.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel36.LocationFloat = New DevExpress.Utils.PointFloat(809.7321!, 35.00001!)
Me.XrLabel36.Name = "XrLabel36"
Me.XrLabel36.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel36.SizeF = New System.Drawing.SizeF(80.26794!, 18.0!)
Me.XrLabel36.StyleName = "FieldCaption"
Me.XrLabel36.StylePriority.UseFont = False
Me.XrLabel36.StylePriority.UseTextAlignment = False
XrSummary9.FormatString = "{0:n2}"
XrSummary9.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel36.Summary = XrSummary9
Me.XrLabel36.Text = "XrLabel36"
Me.XrLabel36.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'ReportFooterBand1
'
Me.ReportFooterBand1.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel45, Me.XrLabel27, Me.XrLabel37, Me.XrLabel38, Me.XrLabel39, Me.XrLabel40, Me.XrLabel41, Me.XrLabel42, Me.XrLabel43, Me.XrLabel44})
Me.ReportFooterBand1.HeightF = 66.45832!
Me.ReportFooterBand1.Name = "ReportFooterBand1"
'
'XrLabel45
'
Me.XrLabel45.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel45.LocationFloat = New DevExpress.Utils.PointFloat(19.76484!, 10.00001!)
Me.XrLabel45.Name = "XrLabel45"
Me.XrLabel45.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel45.SizeF = New System.Drawing.SizeF(140.3196!, 20.00002!)
Me.XrLabel45.StyleName = "FieldCaption"
Me.XrLabel45.StylePriority.UseFont = False
Me.XrLabel45.Text = "Totales Generales :"
'
'XrLabel27
'
Me.XrLabel27.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.TotalCliente", "{0:C2}")})
Me.XrLabel27.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel27.LocationFloat = New DevExpress.Utils.PointFloat(809.7322!, 38.45832!)
Me.XrLabel27.Name = "XrLabel27"
Me.XrLabel27.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel27.SizeF = New System.Drawing.SizeF(80.26794!, 18.0!)
Me.XrLabel27.StyleName = "FieldCaption"
Me.XrLabel27.StylePriority.UseFont = False
Me.XrLabel27.StylePriority.UseTextAlignment = False
XrSummary10.FormatString = "{0:n2}"
XrSummary10.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel27.Summary = XrSummary10
Me.XrLabel27.Text = "XrLabel36"
Me.XrLabel27.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel37
'
Me.XrLabel37.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldomas600", "{0:C2}")})
Me.XrLabel37.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel37.LocationFloat = New DevExpress.Utils.PointFloat(716.9434!, 38.45832!)
Me.XrLabel37.Name = "XrLabel37"
Me.XrLabel37.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel37.SizeF = New System.Drawing.SizeF(81.20691!, 18.0!)
Me.XrLabel37.StyleName = "FieldCaption"
Me.XrLabel37.StylePriority.UseFont = False
Me.XrLabel37.StylePriority.UseTextAlignment = False
XrSummary11.FormatString = "{0:n2}"
XrSummary11.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel37.Summary = XrSummary11
Me.XrLabel37.Text = "XrLabel35"
Me.XrLabel37.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel38
'
Me.XrLabel38.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo181a600", "{0:C2}")})
Me.XrLabel38.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel38.LocationFloat = New DevExpress.Utils.PointFloat(608.9235!, 38.45832!)
Me.XrLabel38.Name = "XrLabel38"
Me.XrLabel38.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel38.SizeF = New System.Drawing.SizeF(85.13!, 18.0!)
Me.XrLabel38.StyleName = "FieldCaption"
Me.XrLabel38.StylePriority.UseFont = False
Me.XrLabel38.StylePriority.UseTextAlignment = False
XrSummary12.FormatString = "{0:n2}"
XrSummary12.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel38.Summary = XrSummary12
Me.XrLabel38.Text = "XrLabel34"
Me.XrLabel38.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel39
'
Me.XrLabel39.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo121a180", "{0:C2}")})
Me.XrLabel39.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel39.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 38.45832!)
Me.XrLabel39.Name = "XrLabel39"
Me.XrLabel39.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel39.SizeF = New System.Drawing.SizeF(89.26993!, 18.0!)
Me.XrLabel39.StyleName = "FieldCaption"
Me.XrLabel39.StylePriority.UseFont = False
Me.XrLabel39.StylePriority.UseTextAlignment = False
XrSummary13.FormatString = "{0:n2}"
XrSummary13.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel39.Summary = XrSummary13
Me.XrLabel39.Text = "XrLabel33"
Me.XrLabel39.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel40
'
Me.XrLabel40.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo91a120", "{0:C2}")})
Me.XrLabel40.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel40.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 38.45832!)
Me.XrLabel40.Name = "XrLabel40"
Me.XrLabel40.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel40.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel40.StyleName = "FieldCaption"
Me.XrLabel40.StylePriority.UseFont = False
Me.XrLabel40.StylePriority.UseTextAlignment = False
XrSummary14.FormatString = "{0:n2}"
XrSummary14.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel40.Summary = XrSummary14
Me.XrLabel40.Text = "XrLabel32"
Me.XrLabel40.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel41
'
Me.XrLabel41.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo61a90", "{0:C2}")})
Me.XrLabel41.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel41.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 40.4583!)
Me.XrLabel41.Name = "XrLabel41"
Me.XrLabel41.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel41.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel41.StyleName = "FieldCaption"
Me.XrLabel41.StylePriority.UseFont = False
Me.XrLabel41.StylePriority.UseTextAlignment = False
XrSummary15.FormatString = "{0:n2}"
XrSummary15.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel41.Summary = XrSummary15
Me.XrLabel41.Text = "XrLabel31"
Me.XrLabel41.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel42
'
Me.XrLabel42.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldo31a60", "{0:C2}")})
Me.XrLabel42.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel42.LocationFloat = New DevExpress.Utils.PointFloat(206.4975!, 38.45832!)
Me.XrLabel42.Name = "XrLabel42"
Me.XrLabel42.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel42.SizeF = New System.Drawing.SizeF(90.87663!, 18.0!)
Me.XrLabel42.StyleName = "FieldCaption"
Me.XrLabel42.StylePriority.UseFont = False
Me.XrLabel42.StylePriority.UseTextAlignment = False
XrSummary16.FormatString = "{0:n2}"
XrSummary16.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel42.Summary = XrSummary16
Me.XrLabel42.Text = "XrLabel30"
Me.XrLabel42.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel43
'
Me.XrLabel43.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.Saldoa30", "{0:C2}")})
Me.XrLabel43.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel43.LocationFloat = New DevExpress.Utils.PointFloat(130.7549!, 38.45832!)
Me.XrLabel43.Name = "XrLabel43"
Me.XrLabel43.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel43.SizeF = New System.Drawing.SizeF(60.11765!, 18.0!)
Me.XrLabel43.StyleName = "FieldCaption"
Me.XrLabel43.StylePriority.UseFont = False
Me.XrLabel43.StylePriority.UseTextAlignment = False
XrSummary17.FormatString = "{0:n2}"
XrSummary17.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel43.Summary = XrSummary17
Me.XrLabel43.Text = "XrLabel29"
Me.XrLabel43.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel44
'
Me.XrLabel44.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.SaldoNovencido")})
Me.XrLabel44.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel44.LocationFloat = New DevExpress.Utils.PointFloat(15.24506!, 38.45832!)
Me.XrLabel44.Name = "XrLabel44"
Me.XrLabel44.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel44.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel44.StyleName = "FieldCaption"
Me.XrLabel44.StylePriority.UseFont = False
Me.XrLabel44.StylePriority.UseTextAlignment = False
XrSummary18.FormatString = "{0:n2}"
XrSummary18.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel44.Summary = XrSummary18
Me.XrLabel44.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'Title
'
Me.Title.BackColor = System.Drawing.Color.Transparent
Me.Title.BorderColor = System.Drawing.Color.Black
Me.Title.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.Title.BorderWidth = 1.0!
Me.Title.Font = New System.Drawing.Font("Times New Roman", 20.0!, System.Drawing.FontStyle.Bold)
Me.Title.ForeColor = System.Drawing.Color.Maroon
Me.Title.Name = "Title"
'
'FieldCaption
'
Me.FieldCaption.BackColor = System.Drawing.Color.Transparent
Me.FieldCaption.BorderColor = System.Drawing.Color.Black
Me.FieldCaption.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.FieldCaption.BorderWidth = 1.0!
Me.FieldCaption.Font = New System.Drawing.Font("Arial", 10.0!, System.Drawing.FontStyle.Bold)
Me.FieldCaption.ForeColor = System.Drawing.Color.Maroon
Me.FieldCaption.Name = "FieldCaption"
'
'PageInfo
'
Me.PageInfo.BackColor = System.Drawing.Color.Transparent
Me.PageInfo.BorderColor = System.Drawing.Color.Black
Me.PageInfo.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.PageInfo.BorderWidth = 1.0!
Me.PageInfo.Font = New System.Drawing.Font("Times New Roman", 10.0!, System.Drawing.FontStyle.Bold)
Me.PageInfo.ForeColor = System.Drawing.Color.Black
Me.PageInfo.Name = "PageInfo"
'
'DataField
'
Me.DataField.BackColor = System.Drawing.Color.Transparent
Me.DataField.BorderColor = System.Drawing.Color.Black
Me.DataField.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.DataField.BorderWidth = 1.0!
Me.DataField.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.DataField.ForeColor = System.Drawing.Color.Black
Me.DataField.Name = "DataField"
Me.DataField.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
'
'PageHeader
'
Me.PageHeader.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel49, Me.XrLabel48, Me.XrPageInfo4, Me.XrPageInfo3, Me.XrLabel4, Me.XrLabel5, Me.lblHasta, Me.lblCliente, Me.lblNombreReporte, Me.lblEmpresa, Me.XrLabel14, Me.XrLabel13, Me.XrLabel12, Me.XrLabel11, Me.XrLabel10, Me.XrLabel9, Me.XrLabel8, Me.XrLabel7, Me.XrLabel6})
Me.PageHeader.HeightF = 177.5!
Me.PageHeader.Name = "PageHeader"
'
'XrLabel49
'
Me.XrLabel49.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "<API key>.CalculatedField1")})
Me.XrLabel49.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel49.LocationFloat = New DevExpress.Utils.PointFloat(215.6208!, 99.12504!)
Me.XrLabel49.Name = "XrLabel49"
Me.XrLabel49.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel49.SizeF = New System.Drawing.SizeF(228.1584!, 22.99999!)
Me.XrLabel49.StylePriority.UseFont = False
Me.XrLabel49.Text = "XrLabel49"
'
'XrLabel48
'
Me.XrLabel48.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel48.LocationFloat = New DevExpress.Utils.PointFloat(125.1225!, 99.12504!)
Me.XrLabel48.Name = "XrLabel48"
Me.XrLabel48.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel48.SizeF = New System.Drawing.SizeF(81.37496!, 23.0!)
Me.XrLabel48.StylePriority.UseFont = False
Me.XrLabel48.Text = "Moneda :"
'
'XrPageInfo4
'
Me.XrPageInfo4.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.XrPageInfo4.Format = "Page {0} of {1}"
Me.XrPageInfo4.LocationFloat = New DevExpress.Utils.PointFloat(654.9127!, 17.125!)
Me.XrPageInfo4.Name = "XrPageInfo4"
Me.XrPageInfo4.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrPageInfo4.SizeF = New System.Drawing.SizeF(81.74994!, 23.0!)
Me.XrPageInfo4.StyleName = "PageInfo"
Me.XrPageInfo4.StylePriority.UseFont = False
Me.XrPageInfo4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrPageInfo3
'
Me.XrPageInfo3.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.XrPageInfo3.Format = "{0:dd/MM/yyyy HH:mm}"
Me.XrPageInfo3.LocationFloat = New DevExpress.Utils.PointFloat(595.5376!, 40.12502!)
Me.XrPageInfo3.Name = "XrPageInfo3"
Me.XrPageInfo3.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrPageInfo3.PageInfo = DevExpress.XtraPrinting.PageInfo.DateTime
Me.XrPageInfo3.SizeF = New System.Drawing.SizeF(141.1249!, 23.0!)
Me.XrPageInfo3.StyleName = "PageInfo"
Me.XrPageInfo3.StylePriority.UseFont = False
Me.XrPageInfo3.StylePriority.UseTextAlignment = False
Me.XrPageInfo3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel4
'
Me.XrLabel4.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel4.LocationFloat = New DevExpress.Utils.PointFloat(124.329!, 76.12502!)
Me.XrLabel4.Name = "XrLabel4"
Me.XrLabel4.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel4.SizeF = New System.Drawing.SizeF(81.37496!, 23.0!)
Me.XrLabel4.StylePriority.UseFont = False
Me.XrLabel4.Text = "Cliente :"
'
'XrLabel5
'
Me.XrLabel5.Font = New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel5.LocationFloat = New DevExpress.Utils.PointFloat(259.9543!, 53.125!)
Me.XrLabel5.Name = "XrLabel5"
Me.XrLabel5.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel5.SizeF = New System.Drawing.SizeF(94.8334!, 23.0!)
Me.XrLabel5.StylePriority.UseFont = False
Me.XrLabel5.Text = "Cortado al :"
'
'lblHasta
'
Me.lblHasta.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.pdFechaFinal, "Text", "{0:dd/MM/yyyy}")})
Me.lblHasta.Font = New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblHasta.LocationFloat = New DevExpress.Utils.PointFloat(378.4542!, 53.125!)
Me.lblHasta.Name = "lblHasta"
Me.lblHasta.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblHasta.SizeF = New System.Drawing.SizeF(120.2498!, 23.0!)
Me.lblHasta.StylePriority.UseFont = False
'
'pdFechaFinal
'
Me.pdFechaFinal.Description = "Parameter1"
Me.pdFechaFinal.Name = "pdFechaFinal"
Me.pdFechaFinal.Type = GetType(Date)
Me.pdFechaFinal.Visible = False
'
'lblCliente
'
Me.lblCliente.CanGrow = False
Me.lblCliente.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.psCliente, "Text", "")})
Me.lblCliente.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblCliente.LocationFloat = New DevExpress.Utils.PointFloat(215.6208!, 76.12502!)
Me.lblCliente.Name = "lblCliente"
Me.lblCliente.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblCliente.SizeF = New System.Drawing.SizeF(538.5416!, 23.0!)
Me.lblCliente.StylePriority.UseFont = False
'
'psCliente
'
Me.psCliente.Description = "Parameter1"
Me.psCliente.Name = "psCliente"
Me.psCliente.Visible = False
'
'lblNombreReporte
'
Me.lblNombreReporte.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Bold)
Me.lblNombreReporte.LocationFloat = New DevExpress.Utils.PointFloat(241.1284!, 30.125!)
Me.lblNombreReporte.Name = "lblNombreReporte"
Me.lblNombreReporte.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblNombreReporte.SizeF = New System.Drawing.SizeF(246.2336!, 23.00001!)
Me.lblNombreReporte.StylePriority.UseFont = False
Me.lblNombreReporte.StylePriority.UseTextAlignment = False
Me.lblNombreReporte.Text = "Análisis de Vencimiento"
Me.lblNombreReporte.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopCenter
'
'lblEmpresa
'
Me.lblEmpresa.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.psEmpresa, "Text", "")})
Me.lblEmpresa.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Bold)
Me.lblEmpresa.LocationFloat = New DevExpress.Utils.PointFloat(189.6207!, 7.124996!)
Me.lblEmpresa.Name = "lblEmpresa"
Me.lblEmpresa.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblEmpresa.SizeF = New System.Drawing.SizeF(344.7917!, 23.0!)
Me.lblEmpresa.StylePriority.UseFont = False
Me.lblEmpresa.StylePriority.UseTextAlignment = False
Me.lblEmpresa.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopCenter
'
'psEmpresa
'
Me.psEmpresa.Description = "Parameter1"
Me.psEmpresa.Name = "psEmpresa"
Me.psEmpresa.Visible = False
'
'piIDBodega
'
Me.piIDBodega.Description = "Parameter1"
Me.piIDBodega.Name = "piIDBodega"
Me.piIDBodega.Type = GetType(Integer)
Me.piIDBodega.ValueInfo = "0"
Me.piIDBodega.Visible = False
'
'piIDCliente
'
Me.piIDCliente.Description = "Parameter1"
Me.piIDCliente.Name = "piIDCliente"
Me.piIDCliente.Type = GetType(Integer)
Me.piIDCliente.ValueInfo = "0"
Me.piIDCliente.Visible = False
'
'piConsolidaSucursal
'
Me.piConsolidaSucursal.Description = "Parameter1"
Me.piConsolidaSucursal.Name = "piConsolidaSucursal"
Me.piConsolidaSucursal.Type = GetType(Short)
Me.piConsolidaSucursal.ValueInfo = "0"
Me.piConsolidaSucursal.Visible = False
'
'piEnDolar
'
Me.piEnDolar.Description = "Parameter1"
Me.piEnDolar.Name = "piEnDolar"
Me.piEnDolar.Type = GetType(Short)
Me.piEnDolar.ValueInfo = "0"
Me.piEnDolar.Visible = False
'
'CalculatedField1
'
Me.CalculatedField1.DataMember = "<API key>"
Me.CalculatedField1.DisplayName = "Moneda"
Me.CalculatedField1.Expression = "Iif([Parameters.piEnDolar]=1,'DOLAR' ,'CORDOBA' )"
Me.CalculatedField1.Name = "CalculatedField1"
'
'<API key>
'
Me.Bands.AddRange(New DevExpress.XtraReports.UI.Band() {Me.Detail, Me.TopMargin, Me.BottomMargin, Me.GroupHeaderSucursal, Me.GroupHeaderCliente, Me.PageFooterBand1, Me.ReportHeaderBand1, Me.GroupFooterBand2, Me.ReportFooterBand1, Me.PageHeader})
Me.CalculatedFields.AddRange(New DevExpress.XtraReports.UI.CalculatedField() {Me.CalculatedField1})
Me.ComponentStorage.AddRange(New System.ComponentModel.IComponent() {Me.SqlDataSource1})
Me.DataMember = "<API key>"
Me.DataSource = Me.SqlDataSource1
Me.Landscape = True
Me.Margins = New System.Drawing.Printing.Margins(100, 103, 100, 100)
Me.PageHeight = 850
Me.PageWidth = 1100
Me.Parameters.AddRange(New DevExpress.XtraReports.Parameters.Parameter() {Me.psCliente, Me.psEmpresa, Me.piIDBodega, Me.piIDCliente, Me.pdFechaFinal, Me.piConsolidaSucursal, Me.piEnDolar})
Me.ScriptLanguage = DevExpress.XtraReports.ScriptLanguage.VisualBasic
Me.StyleSheet.AddRange(New DevExpress.XtraReports.UI.XRControlStyle() {Me.Title, Me.FieldCaption, Me.PageInfo, Me.DataField})
Me.Version = "15.2"
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents Detail As DevExpress.XtraReports.UI.DetailBand
Friend WithEvents TopMargin As DevExpress.XtraReports.UI.TopMarginBand
Friend WithEvents BottomMargin As DevExpress.XtraReports.UI.BottomMarginBand
Friend WithEvents XrLabel15 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel16 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel17 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel18 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel19 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel20 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel21 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel22 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel23 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel24 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel25 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel26 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents SqlDataSource1 As DevExpress.DataAccess.Sql.SqlDataSource
Friend WithEvents GroupHeaderSucursal As DevExpress.XtraReports.UI.GroupHeaderBand
Friend WithEvents XrLabel2 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel1 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents GroupHeaderCliente As DevExpress.XtraReports.UI.GroupHeaderBand
Friend WithEvents XrLabel6 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel7 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel8 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel9 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel10 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel11 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel12 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel13 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel14 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents PageFooterBand1 As DevExpress.XtraReports.UI.PageFooterBand
Friend WithEvents ReportHeaderBand1 As DevExpress.XtraReports.UI.ReportHeaderBand
Friend WithEvents GroupFooterBand1 As DevExpress.XtraReports.UI.GroupFooterBand
Friend WithEvents GroupFooterBand2 As DevExpress.XtraReports.UI.GroupFooterBand
Friend WithEvents XrLabel28 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel29 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel30 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel31 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel32 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel33 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel34 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel35 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel36 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents ReportFooterBand1 As DevExpress.XtraReports.UI.ReportFooterBand
Friend WithEvents Title As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents FieldCaption As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents PageInfo As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents DataField As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents PageHeader As DevExpress.XtraReports.UI.PageHeaderBand
Friend WithEvents XrLabel3 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrPageInfo4 As DevExpress.XtraReports.UI.XRPageInfo
Friend WithEvents XrPageInfo3 As DevExpress.XtraReports.UI.XRPageInfo
Friend WithEvents XrLabel4 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel5 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblHasta As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblCliente As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblNombreReporte As DevExpress.XtraReports.UI.XRLabel
Public WithEvents lblEmpresa As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents psCliente As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents psEmpresa As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piIDBodega As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piIDCliente As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents pdFechaFinal As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piConsolidaSucursal As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piEnDolar As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents XrLabel27 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel37 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel38 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel39 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel40 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel41 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel42 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel43 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel44 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel45 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel47 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel46 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel49 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel48 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents CalculatedField1 As DevExpress.XtraReports.UI.CalculatedField
End Class
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('dashboard/index',['page'=>'Dashboard','breadcrumbs'=>['dashboard/'=>'/home']]);
}
}
|
{# The template expects one input parameter: `active`, which determines what link we are currently at #}
{% load i18n %}
<div class="economy__leftmenu">
<a class="economy__leftbutton resetlink {% if filter is None %}active{% endif %}"
href="{% url '<API key>' %}">{% trans 'X-lists' %}</a>
<a class="economy__leftbutton resetlink {% if filter == 'open' %}active{% endif %}"
href="{% url '<API key>' %}?filter=open">{% trans 'Open' %}</a>
{% if perms.economy.add_socisession %}
<a class="economy__leftbutton resetlink {% if filter == 'closed' %}active{% endif %}"
href="{% url '<API key>' %}?filter=closed">{% trans 'Closed' %}</a>
{% endif %}
</div>
|
// semaphore.cpp
// Circle - A C++ bare metal environment for Raspberry Pi
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include <circle/sched/semaphore.h>
#include <circle/atomic.h>
#include <assert.h>
CSemaphore::CSemaphore (unsigned nInitialCount)
: m_nCount (nInitialCount),
m_Event (TRUE)
{
assert (m_nCount > 0);
}
CSemaphore::~CSemaphore (void)
{
assert (m_nCount > 0);
}
unsigned CSemaphore::GetState (void) const
{
return AtomicGet (&m_nCount);
}
void CSemaphore::Down (void)
{
while (AtomicGet (&m_nCount) == 0)
{
m_Event.Wait ();
}
if (AtomicDecrement (&m_nCount) == 0)
{
assert (m_Event.GetState ());
m_Event.Clear ();
}
}
void CSemaphore::Up (void)
{
if (AtomicIncrement (&m_nCount) == 1)
{
assert (!m_Event.GetState ());
m_Event.Set ();
}
#if NDEBUG
else
{
assert (m_Event.GetState ());
}
#endif
}
boolean CSemaphore::TryDown (void)
{
if (AtomicGet (&m_nCount) == 0)
{
return FALSE;
}
if (AtomicDecrement (&m_nCount) == 0)
{
assert (m_Event.GetState ());
m_Event.Clear ();
}
return TRUE;
}
|
import numpy as np
from scipy import sparse
from scipy.interpolate import interp1d
class calibration(object):
'''
some useful tools for manual calibration
'''
def normalize_zdata(self,z_data,cal_z_data):
return z_data/cal_z_data
def normalize_amplitude(self,z_data,cal_ampdata):
return z_data/cal_ampdata
def normalize_phase(self,z_data,cal_phase):
return z_data*np.exp(-1j*cal_phase)
def normalize_by_func(self,f_data,z_data,func):
return z_data/func(f_data)
def _baseline_als(self,y, lam, p, niter=10):
L = len(y)
D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in range(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = sparse.linalg.spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
def fit_baseline_amp(self,z_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
'''
return self._baseline_als(np.absolute(z_data),lam,p,niter=niter)
def baseline_func_amp(self,z_data,f_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
returns the baseline as a function
the points in between the datapoints are computed by cubic interpolation
'''
return interp1d(f_data, self._baseline_als(np.absolute(z_data),lam,p,niter=niter), kind='cubic')
def baseline_func_phase(self,z_data,f_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
returns the baseline as a function
the points in between the datapoints are computed by cubic interpolation
'''
return interp1d(f_data, self._baseline_als(np.angle(z_data),lam,p,niter=niter), kind='cubic')
def fit_baseline_phase(self,z_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
'''
return self._baseline_als(np.angle(z_data),lam,p,niter=niter)
def GUIbaselinefit(self):
'''
A GUI to help you fit the baseline
'''
self.__lam = 1e6
self.__p = 0.9
niter = 10
self.__baseline = self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, (ax0,ax1) = plt.subplots(nrows=2)
plt.suptitle('Use the sliders to make the green curve match the baseline.')
plt.subplots_adjust(left=0.25, bottom=0.25)
l0, = ax0.plot(np.absolute(self.z_data_raw))
l0b, = ax0.plot(np.absolute(self.__baseline))
l1, = ax1.plot(np.absolute(self.z_data_raw/self.__baseline))
ax0.set_ylabel('amp, rawdata vs. baseline')
ax1.set_ylabel('amp, corrected')
axcolor = '<API key>'
axSmooth = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axAsym = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
axbcorr = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
sSmooth = Slider(axSmooth, 'Smoothness', 0.1, 10., valinit=np.log10(self.__lam),valfmt='1E%f')
sAsym = Slider(axAsym, 'Asymmetry', 1e-4,0.99999, valinit=self.__p,valfmt='%f')
sbcorr = Slider(axbcorr, 'vertical shift',0.7,1.1,valinit=1.)
def update(val):
self.__lam = 10**sSmooth.val
self.__p = sAsym.val
self.__baseline = sbcorr.val*self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
l0.set_ydata(np.absolute(self.z_data_raw))
l0b.set_ydata(np.absolute(self.__baseline))
l1.set_ydata(np.absolute(self.z_data_raw/self.__baseline))
fig.canvas.draw_idle()
sSmooth.on_changed(update)
sAsym.on_changed(update)
sbcorr.on_changed(update)
plt.show()
self.z_data_raw /= self.__baseline
plt.close()
|
#ifndef <API key>
#define <API key>
#include "<API key>.h"
#include <QPointF>
<API key>(QGraphicsItem)
namespace QmlJSDebugger {
class <API key>;
class <API key>
{
public:
enum SelectionType {
ReplaceSelection,
AddToSelection,
RemoveFromSelection
};
<API key>(QGraphicsObject *layerItem,
<API key> *editorView);
void setItems(const QList<QGraphicsItem*> &itemList);
void begin(const QPointF& beginPoint);
void update(const QPointF& updatePoint);
void end();
void clear();
void select(SelectionType selectionType);
QPointF beginPoint() const;
bool isActive() const;
protected:
QGraphicsItem *topFormEditorItem(const QList<QGraphicsItem*> &itemList);
private:
QList<QGraphicsItem*> m_itemList;
QList<QGraphicsItem*> m_oldSelectionList;
<API key> <API key>;
QPointF m_beginPoint;
<API key> *m_editorView;
QGraphicsItem *<API key>;
bool m_isActive;
};
}
#endif // <API key>
|
QUnit.test( "<API key>", function( assert ) {
assert.equal(getIBANCheckDigits( '<API key>' ), '82', 'Get check digits of an IBAN' );
assert.equal(getIBANCheckDigits( '1234567890' ), '', 'If string isn\'t an IBAN, returns empty' );
assert.equal(getIBANCheckDigits( '' ), '', 'If string is empty, returns empty' );
} );
QUnit.test( "<API key>", function( assert ) {
assert.equal(getGlobalIdentifier( 'G28667152', 'ES', '' ), 'ES55000G28667152', 'Obtain a global Id' );
} );
QUnit.test( "<API key>", function( assert ) {
assert.equal(<API key>(
'ABC123-?:',
'<API key>',
'0' ), 'ABC123000', 'Remove unwanted characters' );
assert.equal(<API key>(
'12345',
'0123456789',
'0' ), '12345', 'If the string didn\'t have unwanted characters, returns it' );
} );
QUnit.test( "<API key>", function( assert ) {
assert.equal(<API key>( '510007547061BE00' ), '510007547061111400', 'Replaces letters with digits' );
assert.equal(<API key>( '1234567890' ), '1234567890', 'If we only receive digits, we return them' );
assert.equal(<API key>( '' ), '', 'If we receive empty, we return empty' );
} );
QUnit.test( "<API key>", function( assert ) {
assert.equal(getAccountLength( 'GB' ), 22, 'Returns tohe string th a SEPA country' );
assert.equal(getAccountLength( 'US' ), 0, 'If string isn\'t a SEPA country code, returns empty' );
assert.equal(getAccountLength( '' ), 0, 'If string is empty, returns empty' );
} );
QUnit.test( "testIsSepaCountry", function( assert ) {
assert.equal(isSepaCountry( 'ES' ) , 1, 'Detects SEPA countries' );
assert.equal(isSepaCountry( 'US' ), 0, 'Rejects non SEPA countries' );
assert.equal(isSepaCountry( '' ) , 0, 'If string is empty, returns empty' );
} );
QUnit.test( "testIsValidIban", function( assert ) {
assert.equal(isValidIBAN( '<API key>' ), 1, 'Accepts a good IBAN' );
assert.equal(isValidIBAN( '<API key>' ) , 0, 'Rejects a wrong IBAN' );
assert.equal(isValidIBAN( '' ), 0, 'Rejects empty strings' );
} );
|
<?php
namespace Aqua\SQL;
class Search
extends Select
{
/**
* @var array
*/
public $whereOptions = array();
/**
* @var array
*/
public $havingOptions = array();
/**
* @param array $where
* @param bool $merge
* @return static
*/
public function whereOptions(array $where, $merge = true)
{
if($merge) {
$this->whereOptions = array_merge($this->whereOptions, $where);
} else {
$this->whereOptions = $where;
}
return $this;
}
/**
* @param array $having
* @param bool $merge
* @return static
*/
public function havingOptions(array $having, $merge = true)
{
if($merge) {
$this->havingOptions = array_merge($this->havingOptions, $having);
} else {
$this->havingOptions = $having;
}
return $this;
}
/**
* @param mixed $options
* @param $values
* @param string $type
* @return string|null
*/
public function parseSearch(&$options, &$values, $type = null)
{
if($type === 'where') {
$columns = & $this->whereOptions;
} else {
$columns = & $this->havingOptions;
}
$query = '';
$i = 0;
if(!is_array($options)) {
return null;
} else {
foreach($options as $alias => &$value) {
if($i % 2) {
++$i;
if(is_string($value)) {
$v = strtoupper($value);
if($v === 'AND' || $v === 'OR') {
$query .= "$v ";
continue;
}
}
$query .= 'AND ';
}
if(is_int($alias)) {
if(is_string($value)) {
$query .= "$value ";
++$i;
} else if($q = $this->parseSearch($value, $values, $type)) {
$query .= "$q ";
++$i;
}
} else if(array_key_exists($alias, $columns)) {
if(!is_array($value)) {
$value = array( self::SEARCH_NATURAL, $value );
}
if($this->parseSearchFlags($value, $w, $values, $columns[$alias], $alias)) {
$query .= "$w ";
++$i;
}
}
}
}
if($i === 0) {
return null;
}
$query = preg_replace('/(^\s*(AND|OR)\s*)|(\s*(AND|OR)\s*$)/i', '', $query);
if($i === 1) {
return $query;
} else {
return "($query)";
}
}
public function parseOrder()
{
if(empty($this->order)) return '';
$order = array();
foreach($this->order as $column => $ord) {
if($ord === 'DESC' || $ord === 'ASC') {
if(array_key_exists($column, $this->columns)) {
$column = $this->columns[$column];
}
$order[] = "$column $ord";
} else {
if(array_key_exists($ord, $this->columns)) {
$ord = $this->columns[$ord];
}
$order[] = $ord;
}
}
if(empty($order)) return '';
else return 'ORDER BY ' . implode(', ', $order);
}
}
|
#pragma once
#include <nstd/Base.h>
class DataProtocol
{
public:
enum MessageType
{
errorResponse,
subscribeRequest,
subscribeResponse,
unsubscribeRequest,
unsubscribeResponse,
tradeRequest,
tradeResponse,
<API key>,
<API key>,
registerSinkRequest,
<API key>,
<API key>,
tradeMessage,
channelRequest,
channelResponse,
timeRequest,
timeResponse,
timeMessage,
tickerMessage,
};
enum TradeFlag
{
replayedFlag = 0x01,
syncFlag = 0x02,
};
//enum ChannelType
// tradeType,
// orderBookType,
//enum ChannelFlag
// onlineFlag = 0x01,
#pragma pack(push, 4)
struct Header
{
uint32_t size; // including header
uint64_t source; // client id
uint64_t destination; // client id
uint16_t messageType; // MessageType
};
struct ErrorResponse
{
uint16_t messageType;
uint64_t channelId;
char_t errorMessage[128];
};
struct SubscribeRequest
{
char_t channel[33];
uint64_t maxAge;
uint64_t sinceId;
};
struct SubscribeResponse
{
char_t channel[33];
uint64_t channelId;
uint32_t flags;
};
struct UnsubscribeRequest
{
char_t channel[33];
};
struct UnsubscribeResponse
{
char_t channel[33];
uint64_t channelId;
};
struct <API key>
{
char_t channel[33];
};
struct <API key>
{
char_t channel[33];
uint64_t channelId;
};
struct RegisterSinkRequest
{
char_t channel[33];
};
struct <API key>
{
char_t channel[33];
uint64_t channelId;
};
struct TradeRequest
{
uint64_t maxAge;
uint64_t sinceId;
};
struct Trade
{
uint64_t id;
uint64_t time;
double price;
double amount;
uint32_t flags;
};
struct TradeMessage
{
uint64_t channelId;
Trade trade;
};
struct TimeMessage
{
uint64_t channelId;
uint64_t time;
};
struct TradeResponse
{
uint64_t channelId;
};
struct Channel
{
char_t channel[33];
//uint8_t type;
//uint32_t flags;
};
struct TimeResponse
{
uint64_t time;
};
struct Ticker
{
uint64_t time;
double bid;
double ask;
};
struct TickerMessage
{
uint64_t channelId;
Ticker ticker;
};
#pragma pack(pop)
};
|
title: "हरियाणा में सभी पार्टियां बहुमत से दूर"
layout: item
category: ["politics"]
date: 2019-10-24T11:42:44.692Z
image: <API key>.jpg
<p>नई दिल्ली: हरियाणा चुनाव के नतीजे काफी दिलचस्प हो गए हैं। अब तक के रुझान में भाजपा यहां आगे जरूर चल रही है, लेकिन बहुमत का आंकड़ा उससे दूर है। जबकि कांग्रेस ने जबरदस्त वापसी की है और जेजेपी भी बढ़िया प्रदर्शन कर रही है। ऐसे में बीजेपी को सरकार बनाने के लिए जेजेपी की जरूरत पड़ सकती है। लिहाजा हरियाणा के मुख्यमंत्री मनोहर लाल खट्टर को बीजेपी आलाकमान ने दिल्ली बुलाया है। वहीं कांग्रेस अध्यक्ष सोनिया गांधी ने भी भूपेन्द्र सिंह हुड्डा से बात की है। इस बीच जननायक जनता पार्टी (जेजेपी) की भूमिका काफी अहम हो गई है। जानकारी के मुताबिक प्रदेश के पूर्व मुख्यमंत्री प्रकाश सिंह बादल को भाजपा की ओर से जेजेपी से मध्यस्थता के लिए आगे किया जा सकता है। वहीं यह भी खबर है कि जेजपी ने सीएम पद की शर्त के साथ कांग्रेस को समर्थन का प्रस्ताव दिया है। हालांकि थोड़ी देर में तस्वीर साफ हो जाएगी कि हरियाणा की जनता ने किस पार्टी को प्रदेश की कमान सौंपने का निर्णय लिया है। राज्य में सोमवार को मतदान हुआ था।</p>
|
ALTER TABLE `b_iblock_element` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_element` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `<API key>` (`<API key>`);
ALTER TABLE `b_iblock_element` ADD KEY `MODIFIED_BY`(`MODIFIED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `DATE_CREATE` (`DATE_CREATE`);
ALTER TABLE `b_iblock_element` ADD KEY `CREATED_BY` (`CREATED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE_FROM` (`ACTIVE_FROM`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE_TO` (`ACTIVE_TO`);
ALTER TABLE `b_iblock_element` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_element` ADD KEY `NAME` (`NAME`);
ALTER TABLE `b_iblock_element` ADD KEY `DETAIL_PICTURE` (`DETAIL_PICTURE`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_STATUS_ID` (`WF_STATUS_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_NEW` (`WF_NEW`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_LOCKED_BY` (`WF_LOCKED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_DATE_LOCK` (`WF_DATE_LOCK`);
ALTER TABLE `b_iblock_element` ADD KEY `IN_SECTIONS` (`IN_SECTIONS`);
ALTER TABLE `b_iblock_element` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_element` ADD KEY `TAGS` (`TAGS`);
ALTER TABLE `b_iblock_element` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_LAST_HISTORY_ID` (`WF_LAST_HISTORY_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `SHOW_COUNTER` (`SHOW_COUNTER`);
ALTER TABLE `b_iblock_element` ADD KEY `SHOW_COUNTER_START` (`SHOW_COUNTER_START`);
ALTER TABLE `<API key>` ADD KEY `ELEMENT_ID` (`ELEMENT_ID`);
ALTER TABLE `<API key>` ADD KEY `IPROP_ID` (`IPROP_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_property` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `NAME` (`NAME`);
ALTER TABLE `b_iblock_property` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_property` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_property` ADD KEY `PROPERTY_TYPE` (`PROPERTY_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `ROW_COUNT` (`ROW_COUNT`);
ALTER TABLE `b_iblock_property` ADD KEY `COL_COUNT` (`COL_COUNT`);
ALTER TABLE `b_iblock_property` ADD KEY `LIST_TYPE` (`LIST_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `MULTIPLE` (`MULTIPLE`);
ALTER TABLE `b_iblock_property` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `FILE_TYPE` (`FILE_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `MULTIPLE_CNT` (`MULTIPLE_CNT`);
ALTER TABLE `b_iblock_property` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `WITH_DESCRIPTION` (`WITH_DESCRIPTION`);
ALTER TABLE `b_iblock_property` ADD KEY `SEARCHABLE` (`SEARCHABLE`);
ALTER TABLE `b_iblock_property` ADD KEY `FILTRABLE` (`FILTRABLE`);
ALTER TABLE `b_iblock_property` ADD KEY `IS_REQUIRED` (`IS_REQUIRED`);
ALTER TABLE `b_iblock_property` ADD KEY `VERSION` (`VERSION`);
ALTER TABLE `b_iblock_property` ADD KEY `USER_TYPE` (`USER_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `HINT` (`HINT`);
ALTER TABLE `<API key>` ADD KEY `PROPERTY_ID` (`PROPERTY_ID`);
ALTER TABLE `<API key>` ADD KEY `DEF` (`DEF`);
ALTER TABLE `<API key>` ADD KEY `SORT` (`SORT`);
ALTER TABLE `<API key>` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `ENTITY_TYPE` (`ENTITY_TYPE`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `ENTITY_ID` (`ENTITY_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_section` ADD KEY `MODIFIED_BY` (`MODIFIED_BY`);
ALTER TABLE `b_iblock_section` ADD KEY `DATE_CREATE` (`DATE_CREATE`);
ALTER TABLE `b_iblock_section` ADD KEY `CREATED_BY` (`CREATED_BY`);
ALTER TABLE `b_iblock_section` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_section` ADD KEY `GLOBAL_ACTIVE` (`GLOBAL_ACTIVE`);
ALTER TABLE `b_iblock_section` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_section` ADD KEY `DEPTH_LEVEL` (`DEPTH_LEVEL`);
ALTER TABLE `b_iblock_section` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_section` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `SOCNET_GROUP_ID` (`SOCNET_GROUP_ID`);
ALTER TABLE `<API key>` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `<API key>` ADD KEY `<API key>` (`<API key>`);
ALTER TABLE `<API key>` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `<API key>` ADD KEY `DISPLAY_TYPE` (`DISPLAY_TYPE`);
ALTER TABLE `<API key>` ADD KEY `SMART_FILTER` (`SMART_FILTER`);
ALTER TABLE `<API key>` ADD KEY `DISPLAY_EXPANDED` (`DISPLAY_EXPANDED`);
ALTER TABLE `<API key>` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `<API key>` ADD KEY `SECTION_ID` (`SECTION_ID`);
ALTER TABLE `<API key>` ADD KEY `RIGHT_ID` (`RIGHT_ID`);
ALTER TABLE `<API key>` ADD KEY `IS_INHERITED` (`IS_INHERITED`);
ALTER TABLE `<API key>` ADD KEY `SECTION_ID` (`SECTION_ID`);
ALTER TABLE `b_option` ADD KEY `MODULE_ID` (`MODULE_ID`);
ALTER TABLE `b_option` ADD KEY `SITE_ID` (`SITE_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `FIELD_ID` (`FIELD_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `IS_REQUIRED` (`IS_REQUIRED`);
ALTER TABLE `b_user` ADD KEY `LOGIN` (`LOGIN`);
ALTER TABLE `b_user` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_user` ADD KEY `LID` (`LID`);
ALTER TABLE `b_user` ADD KEY `DATE_REGISTER` (`DATE_REGISTER`);
ALTER TABLE `b_user` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
|
const char * <API key>(void) {
static const char * query =
"SELECT"
" id AS 'ID',"
" shortname AS 'Short',"
" name AS 'Entity Name',"
" currency AS 'Curr.',"
" parent AS 'Parent'"
" FROM entities"
" ORDER BY id";
return query;
}
|
/*
* This section contains meta informations.
*
* $Id$
*/
package jmul.transformation.xml.rules.xml2object;
import jmul.misc.id.ID;
import jmul.misc.id.IntegerID;
import jmul.reflection.classes.ClassDefinition;
import jmul.reflection.classes.ClassHelper;
import jmul.string.TextHelper;
import jmul.transformation.<API key>;
import jmul.transformation.<API key>;
import jmul.transformation.<API key>;
import jmul.transformation.xml.cache.Xml2ObjectCache;
import static jmul.transformation.xml.rules.PersistenceMarkups.ID_ATTRIBUTE;
import static jmul.transformation.xml.rules.PersistenceMarkups.OBJECT_ELEMENT;
import static jmul.transformation.xml.rules.PersistenceMarkups.TYPE_ATTRIBUTE;
import static jmul.transformation.xml.rules.PersistenceMarkups.VALUE_ATTRIBUTE;
import static jmul.transformation.xml.rules.<API key>.OBJECT_CACHE;
import jmul.xml.XmlParserHelper;
import org.w3c.dom.Node;
/**
* An implementation of a transformation rule.
*
* @author Kristian Kutin
*/
public class Xml2ClassRule extends <API key> {
/**
* A class name.
*/
private static final String EXPECTED_TYPE_NAME = Class.class.getName();
/**
* Constructs a transformation rule.
*
* @param anOrigin
* a description of the transformation origin
* @param aDestination
* a description of the transformation destination
* @param aPriority
* a rule priority
*/
public Xml2ClassRule(String anOrigin, String aDestination, int aPriority) {
super(anOrigin, aDestination, aPriority);
}
/**
* The method determines if this rule can be applied to the specified
* object.
*
* @param someParameters
* some transformation parameters, including the object which is to
* be transformed
*
* @return <code>true</code> if the rule is applicable, else
* <code>false</code>
*/
@Override
public boolean isApplicable(<API key> someParameters) {
return RuleHelper.isApplicable(someParameters, EXPECTED_TYPE_NAME);
}
/**
* The method performs the actual transformation.
*
* @param someParameters
* some transformation parameters, including the object which is to
* be transformed
*
* @return the transformed object
*/
@Override
public Object transform(<API key> someParameters) {
// Check some plausibilites first.
if (!someParameters.<API key>(OBJECT_CACHE)) {
String message =
TextHelper.concatenateStrings("Prerequisites for the transformation are missing (", OBJECT_CACHE, ")!");
throw new <API key>(message);
}
Object target = someParameters.getObject();
Node objectElement = (Node) target;
XmlParserHelper.<API key>(objectElement, OBJECT_ELEMENT);
XmlParserHelper.<API key>(objectElement, ID_ATTRIBUTE);
XmlParserHelper.<API key>(objectElement, TYPE_ATTRIBUTE);
XmlParserHelper.<API key>(objectElement, VALUE_ATTRIBUTE);
// Get the required informations.
Xml2ObjectCache objectCache = (Xml2ObjectCache) someParameters.getPrerequisite(OBJECT_CACHE);
String idString = XmlParserHelper.<API key>(objectElement, ID_ATTRIBUTE);
String typeString = XmlParserHelper.<API key>(objectElement, TYPE_ATTRIBUTE);
String valueString = XmlParserHelper.<API key>(objectElement, VALUE_ATTRIBUTE);
ID id = new IntegerID(idString);
ClassDefinition type = null;
try {
type = ClassHelper.getClass(typeString);
} catch (<API key> e) {
String message = TextHelper.concatenateStrings("An unknown class was specified (", typeString, ")!");
throw new <API key>(message, e);
}
Class clazz = null;
try {
ClassDefinition definition = ClassHelper.getClass(valueString);
clazz = definition.getType();
} catch (<API key> e) {
String message = TextHelper.concatenateStrings("An unknown class was specified (", valueString, ")!");
throw new <API key>(message, e);
}
// Instantiate and initialize the specified object
objectCache.addObject(id, clazz, type.getType());
return clazz;
}
}
|
/*
| This file contains definitions for internal routines and structures which
| the LIT library doesn't wish to expose to the world at large
*/
#ifndef LITINTERNAL_H
#define LITINTERNAL_H
typedef struct dir_type {
U8 * entry_ptr;
U32 entry_size;
U32 entry_last_chunk;
U8 * count_ptr;
U32 count_size;
U32 count_last_chunk;
int num_entries;
int num_counts;
U32 entry_aoli_idx;
U32 total_content_size;
} dir_type;
int <API key>(lit_file * litfile, U8 * piece, int piece_size);
int <API key>(lit_file * litfile, dir_type * dirtype);
int lit_i_read_headers(lit_file * litfile);
int lit_i_write_headers(lit_file * litfile);
int <API key>(lit_file * litfile, U8 * hdr, int size);
int lit_i_cache_section(lit_file * litfile, section_type * pSection );
int lit_i_read_sections(lit_file * litfile );
void lit_i_free_dir_type(dir_type * dirtype);
int <API key>(lit_file *,char *, U8 * new_key);
int lit_i_encrypt(U8 * ptr, int size, U8 * new_key);
/*
| This routine will check for the presence of DRM and initialize
| the DRM level and bookkey */
extern int lit_i_read_drm(lit_file *);
/*
| This routine will do the decryption with the bookkey, kept off here
| to get the non-DRM path pure */
extern int lit_i_decrypt(lit_file *, U8 * data_pointer, int size);
/*
| Utility routines...
*/
char * lit_i_strmerge(const char * first, ...);
U8 * <API key>(U8 * p, int remaining, int * size);
int <API key>(U8 * src, int lenSrc, int sizeSrc);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.