answer
stringlengths 15
1.25M
|
|---|
# <API key>: true
require "spec_helper"
describe "Edit initiative", type: :system do
let(:organization) { create(:organization) }
let(:user) { create(:user, :confirmed, organization: organization) }
let(:initiative_title) { translated(initiative.title) }
let(:new_title) { "This is my initiative new title" }
let!(:initiative_type) { create(:initiatives_type, :<API key>, organization: organization) }
let!(:scoped_type) { create(:<API key>, type: initiative_type) }
let!(:<API key>) { create(:initiatives_type, organization: organization) }
let!(:other_scoped_type) { create(:<API key>, type: initiative_type) }
let(:initiative_path) { decidim_initiatives.initiative_path(initiative) }
let(:<API key>) { decidim_initiatives.<API key>(initiative) }
shared_examples "manage update" do
it "can be updated" do
visit initiative_path
click_link("Edit", href: <API key>)
expect(page).to have_content "EDIT INITIATIVE"
within "form.edit_initiative" do
fill_in :initiative_title, with: new_title
click_button "Update"
end
expect(page).to have_content(new_title)
end
end
before do
switch_to_host(organization.host)
login_as user, scope: :user
end
describe "when user is initiative author" do
let(:initiative) { create(:initiative, :created, author: user, scoped_type: scoped_type, organization: organization) }
it_behaves_like "manage update"
context "when initiative is published" do
let(:initiative) { create(:initiative, author: user, scoped_type: scoped_type, organization: organization) }
it "can't be updated" do
visit decidim_initiatives.initiative_path(initiative)
expect(page).not_to have_content "Edit initiative"
visit <API key>
expect(page).to have_content("not authorized")
end
end
end
describe "when author is a committee member" do
let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) }
before do
create(:<API key>, user: user, initiative: initiative)
end
it_behaves_like "manage update"
end
describe "when user is admin" do
let(:user) { create(:user, :confirmed, :admin, organization: organization) }
let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) }
it_behaves_like "manage update"
end
describe "when author is not a committee member" do
let(:initiative) { create(:initiative, :created, scoped_type: scoped_type, organization: organization) }
it "renders an error" do
visit decidim_initiatives.initiative_path(initiative)
expect(page).to have_no_content("Edit initiative")
visit <API key>
expect(page).to have_content("not authorized")
end
end
end
|
from odoo import fields, models
class Job(models.Model):
_inherit = "crm.team"
survey_id = fields.Many2one(
'survey.survey', "Interview Form",
help="Choose an interview form")
def action_print_survey(self):
return self.survey_id.action_print_survey()
|
package com.alessiodp.parties.bukkit.addons.external.skript.expressions;
import ch.njol.skript.classes.Changer;
import ch.njol.skript.doc.Description;
import ch.njol.skript.doc.Examples;
import ch.njol.skript.doc.Name;
import ch.njol.skript.doc.Since;
import ch.njol.skript.expressions.base.<API key>;
import ch.njol.util.coll.CollectionUtils;
import com.alessiodp.parties.api.interfaces.Party;
import org.bukkit.event.Event;
@Name("Party Name")
@Description("Get the name of the given party.")
@Examples({"send \"%name of party with name \"test\"%\"",
"send \"%name of event-party%\""})
@Since("3.0.0")
public class ExprPartyName extends <API key><Party, String> {
static {
register(ExprPartyName.class, String.class, "name", "party");
}
@Override
public Class<? extends String> getReturnType() {
return String.class;
}
@Override
protected String getPropertyName() {
return "name";
}
@Override
public String convert(Party party) {
return party.getName();
}
@Override
public void change(Event e, Object[] delta, Changer.ChangeMode mode){
if (delta != null) {
Party party = getExpr().getSingle(e);
String newName = (String) delta[0];
switch (mode) {
case SET:
party.rename(newName);
break;
case DELETE:
party.rename(null);
break;
default:
break;
}
}
}
@Override
public Class<?>[] acceptChange(final Changer.ChangeMode mode) {
return (mode == Changer.ChangeMode.SET || mode == Changer.ChangeMode.DELETE) ? CollectionUtils.array(String.class) : null;
}
}
|
//CuraEngine is released under the terms of the AGPLv3 or higher.
#ifndef INFILL_SUBDIVCUBE_H
#define INFILL_SUBDIVCUBE_H
#include "../settings/types/Ratio.h"
#include "../utils/IntPoint.h"
#include "../utils/Point3.h"
namespace cura
{
struct LayerIndex;
class Polygons;
class SliceMeshStorage;
class SubDivCube
{
public:
/*!
* Constructor for SubDivCube. Recursively calls itself eight times to flesh out the octree.
* \param mesh contains infill layer data and settings
* \param my_center the center of the cube
* \param depth the recursion depth of the cube (0 is most recursed)
*/
SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth);
~SubDivCube(); //!< destructor (also destroys children)
/*!
* Precompute the octree of subdivided cubes
* \param mesh contains infill layer data and settings
*/
static void precomputeOctree(SliceMeshStorage& mesh, const Point& infill_origin);
/*!
* Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too.
* \param z the specified layer height
* \param result (output) The resulting lines
*/
void <API key>(const coord_t z, Polygons& result);
private:
/*!
* Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too.
* \param z the specified layer height
* \param result (output) The resulting lines
* \param <API key> Array of 3 times a polylines. Used to keep track of line segments that are all pointing the same direction for line segment combining
*/
void <API key>(const coord_t z, Polygons (&<API key>)[3]);
struct CubeProperties
{
coord_t side_length; //!< side length of cubes
coord_t height; //!< height of cubes based. This is the distance from one point of a cube to its 3d opposite.
coord_t square_height; //!< square cut across lengths. This is the diagonal distance across a face of the cube.
coord_t max_draw_z_diff; //!< maximum draw z differences. This is the maximum difference in z at which lines need to be drawn.
coord_t max_line_offset; //!< maximum line offsets. This is the maximum distance at which subdivision lines should be drawn from the 2d cube center.
};
/*!
* Rotates a point 120 degrees about the origin.
* \param target the point to rotate.
*/
static void rotatePoint120(Point& target);
/*!
* Rotates a point to align it with the orientation of the infill.
* \param target the point to rotate.
*/
static void rotatePointInitial(Point& target);
/*!
* Determines if a described theoretical cube should be subdivided based on if a sphere that encloses the cube touches the infill mesh.
* \param mesh contains infill layer data and settings
* \param center the center of the described cube
* \param radius the radius of the enclosing sphere
* \return the described cube should be subdivided
*/
static bool isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coord_t radius);
/*!
* Finds the distance to the infill border at the specified layer from the specified point.
* \param mesh contains infill layer data and settings
* \param layer_nr the number of the specified layer
* \param location the location of the specified point
* \param[out] distance2 the squared distance to the infill border
* \return Code 0: outside, 1: inside, 2: boundary does not exist at specified layer
*/
static coord_t <API key>(SliceMeshStorage& mesh, const LayerIndex layer_nr, Point& location, coord_t* distance2);
/*!
* Adds the defined line to the specified polygons. It assumes that the specified polygons are all parallel lines. Combines line segments with touching ends closer than epsilon.
* \param[out] group the polygons to add the line to
* \param from the first endpoint of the line
* \param to the second endpoint of the line
*/
void addLineAndCombine(Polygons& group, Point from, Point to);
size_t depth; //!< the recursion depth of the cube (0 is most recursed)
Point3 center; //!< center location of the cube in absolute coordinates
SubDivCube* children[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; //!< pointers to this cube's eight octree children
static std::vector<CubeProperties> <API key>; //!< precomputed array of basic properties of cubes based on recursion depth.
static Ratio radius_multiplier; //!< multiplier for the bounding radius when determining if a cube should be subdivided
static Point3Matrix rotation_matrix; //!< The rotation matrix to get from axis aligned cubes to cubes standing on a corner point aligned with the infill_angle
static PointMatrix <API key>; //!< Horizontal rotation applied to infill
static coord_t radius_addition; //!< addition to the bounding radius when determining if a cube should be subdivided
};
}
#endif //INFILL_SUBDIVCUBE_H
|
class CreateColorMappings < ActiveRecord::Migration
def self.up
create_table :color_mappings do |t|
t.references :collage
t.references :tag
t.string :hex
t.timestamps
end
end
def self.down
drop_table :color_mappings
end
end
|
# directory
from . import account_move
from . import account_move_line
from . import account_master_port
|
package com.rapidminer.gui.new_plotter.configuration;
import com.rapidminer.gui.new_plotter.listener.events.<API key>;
import com.rapidminer.gui.new_plotter.utility.DataStructureUtils;
import com.rapidminer.tools.I18N;
import java.awt.BasicStroke;
import java.awt.Color;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Marius Helf
* @deprecated since 9.2.0
*/
@Deprecated
public class LineFormat implements Cloneable {
private static class StrokeFactory {
static public BasicStroke getSolidStroke() {
return new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
}
static public BasicStroke getDottedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 1f, 1f }, 0.0f);
}
static public BasicStroke <API key>() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 4f, 2f }, 0.0f);
}
static public BasicStroke getLongDashedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 7f, 3f }, 0.0f);
}
static public BasicStroke getDashDotStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 6f, 2f, 1f, 2f },
0.0f);
}
static public BasicStroke getStripedStroke() {
return new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 10.0f, new float[] { 0.2f, 0.2f }, 0.0f);
}
}
public enum LineStyle {
NONE(null, I18N.getGUILabel("plotter.linestyle.NONE.label")), SOLID(StrokeFactory.getSolidStroke(), I18N
.getGUILabel("plotter.linestyle.SOLID.label")), DOTS(StrokeFactory.getDottedStroke(), I18N
.getGUILabel("plotter.linestyle.DOTS.label")), SHORT_DASHES(StrokeFactory.<API key>(), I18N
.getGUILabel("plotter.linestyle.SHORT_DASHES.label")), LONG_DASHES(StrokeFactory.getLongDashedStroke(), I18N
.getGUILabel("plotter.linestyle.LONG_DASHES.label")), DASH_DOT(StrokeFactory.getDashDotStroke(), I18N
.getGUILabel("plotter.linestyle.DASH_DOT.label")), STRIPES(StrokeFactory.getStripedStroke(), I18N
.getGUILabel("plotter.linestyle.STRIPES.label"));
private final BasicStroke stroke;
private final String name;
public BasicStroke getStroke() {
return stroke;
}
public String getName() {
return name;
}
private LineStyle(BasicStroke stroke, String name) {
this.stroke = stroke;
this.name = name;
}
}
private List<WeakReference<LineFormatListener>> listeners = new LinkedList<WeakReference<LineFormatListener>>();
private LineStyle style = LineStyle.NONE; // dashed, solid...
private Color color = Color.GRAY;
private float width = 1.0f;
public LineStyle getStyle() {
return style;
}
public void setStyle(LineStyle style) {
if (style != this.style) {
this.style = style;
fireStyleChanged();
}
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
if (color == null ? this.color != null : !color.equals(this.color)) {
this.color = color;
fireColorChanged();
}
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
if (width != this.width) {
this.width = width;
fireWidthChanged();
}
}
private void fireWidthChanged() {
<API key>(new <API key>(this, width));
}
private void fireColorChanged() {
<API key>(new <API key>(this, color));
}
private void fireStyleChanged() {
<API key>(new <API key>(this, style));
}
private void <API key>(<API key> e) {
Iterator<WeakReference<LineFormatListener>> it = listeners.iterator();
while (it.hasNext()) {
LineFormatListener l = it.next().get();
if (l != null) {
l.lineFormatChanged(e);
} else {
it.remove();
}
}
}
@Override
public LineFormat clone() {
LineFormat clone = new LineFormat();
clone.color = new Color(color.getRGB(), true);
clone.style = style;
clone.width = width;
return clone;
}
public BasicStroke getStroke() {
BasicStroke stroke = style.getStroke();
if (stroke != null) {
float[] scaledDashArray = getScaledDashArray();
BasicStroke scaledStroke = new BasicStroke(this.getWidth(), stroke.getEndCap(), stroke.getLineJoin(),
stroke.getMiterLimit(), scaledDashArray, stroke.getDashPhase());
return scaledStroke;
} else {
return null;
}
}
float[] getScaledDashArray() {
BasicStroke stroke = getStyle().getStroke();
if (stroke == null) {
return null;
}
float[] dashArray = stroke.getDashArray();
float[] scaledDashArray;
if (dashArray != null) {
float scalingFactor = getWidth();
if (scalingFactor <= 0) {
scalingFactor = 1;
}
if (scalingFactor != 1) {
scaledDashArray = DataStructureUtils.<API key>(dashArray, scalingFactor);
} else {
scaledDashArray = dashArray;
}
} else {
scaledDashArray = dashArray;
}
return scaledDashArray;
}
public void <API key>(LineFormatListener l) {
listeners.add(new WeakReference<LineFormatListener>(l));
}
public void <API key>(LineFormatListener l) {
Iterator<WeakReference<LineFormatListener>> it = listeners.iterator();
while (it.hasNext()) {
LineFormatListener listener = it.next().get();
if (l != null) {
if (listener != null && listener.equals(l)) {
it.remove();
}
} else {
it.remove();
}
}
}
}
|
package com.nexusplay.containers;
import java.io.File;
import java.io.FileInputStream;
import java.io.<API key>;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.SQLException;
import org.apache.commons.io.IOUtils;
import com.nexusplay.db.SubtitlesDatabase;
import com.nexusplay.security.RandomContainer;
/**
* Contains a proposed change (to a subtitle).
* @author alex
*
*/
public class Change {
private String targetID, changedContent, id, originalContent, votes;
private int nrVotes;
/**
* Constructor for creating new objects, prior to storing them in the database.
* @param changedContent The change's original data
* @param originalContent The change's new data
* @param targetID The object targeted by the change
* @param votes The user IDs that voted this change
*/
public Change(String changedContent, String originalContent, String targetID, String votes){
this.changedContent = changedContent;
this.originalContent = originalContent;
this.targetID = targetID;
this.votes = votes;
nrVotes = votes.length() - votes.replace(";", "").length();
generateId();
}
/**
* This constructor should only be used for recreating a stored object.
* @param changedContent The change's original data
* @param originalContent The change's new data
* @param targetID The object targeted by the change
* @param votes The user IDs that voted this change
* @param id The change's unique ID
*/
public Change(String changedContent, String originalContent, String targetID, String votes, String id){
this.changedContent = changedContent;
this.originalContent = originalContent;
this.targetID = targetID;
this.votes = votes;
nrVotes = votes.length() - votes.replace(";", "").length();
this.id = id;
}
/**
* Commits a change to disk.
* @throws SQLException Thrown if the database is not accessible to us for whatever reason
* @throws <API key> Thrown if we're denied access to the subtitle file
* @throws IOException Thrown if an error appears while writing the file
*/
public void commitChange() throws SQLException, <API key>, IOException{
Subtitle sub = SubtitlesDatabase.getSubtitleByID(targetID);
FileInputStream input = new FileInputStream(SettingsContainer.<API key>() + File.separator + sub.getId() + ".vtt");
String content = IOUtils.toString(input, "UTF-8");
content = content.replaceAll(originalContent, changedContent);
content = content.replaceAll(originalContent.replaceAll("\n", "\r\n"), changedContent.replaceAll("\n", "\r\n"));
FileOutputStream output = new FileOutputStream(SettingsContainer.<API key>() + File.separator + sub.getId() + ".vtt");
IOUtils.write(content, output, "UTF-8");
output.close();
input.close();
}
/**
* Generates a new unique ID for the item
*/
public void generateId()
{
id = (new BigInteger(130, RandomContainer.getRandom())).toString(32);
}
/**
* @return The ID of the Media element associated to this object
*/
public String getTargetID() {
return targetID;
}
/**
* @param targetID The new ID of the Media element associated to this object
*/
public void setTargetID(String targetID) {
this.targetID = targetID;
}
/**
* @return The change itself
*/
public String getChangedContent() {
return changedContent;
}
/**
* @param content The new data to change
*/
public void setChangedContent(String content) {
this.changedContent = content;
}
/**
* @return The change's unique ID
*/
public String getId() {
return id;
}
/**
* @param id The change's new unique ID
*/
public void setId(String id) {
this.id = id;
}
/**
* @return The user IDs who voted for this change
*/
public String getVotes() {
return votes;
}
/**
* @param votes The new user IDs who voted for this change
*/
public void setVotes(String votes) {
this.votes = votes;
nrVotes = votes.length() - votes.replace(";", "").length();
}
/**
* @return The original content prior to changing
*/
public String getOriginalContent() {
return originalContent;
}
/**
* @param originalContent The new original content prior to changing
*/
public void setOriginalContent(String originalContent) {
this.originalContent = originalContent;
}
/**
* @return the nrVotes
*/
public int getNrVotes() {
return nrVotes;
}
/**
* @param nrVotes the nrVotes to set
*/
public void setNrVotes(int nrVotes) {
this.nrVotes = nrVotes;
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Tue May 04 10:00:19 CEST 2010 -->
<TITLE>
Uses of Class mx.database.table.Query
</TITLE>
<META NAME="date" CONTENT="2010-05-04">
<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 mx.database.table.Query";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<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="../../../../mx/database/table/Query.html" title="class in mx.database.table"><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="../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-files/index-1.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?mx/database/table/\class-useQuery.html" target="_top"><B>FRAMES</B></A>
<A HREF="Query.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>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>mx.database.table.Query</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#mx.database.navigator"><B>mx.database.navigator</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#mx.database.table.test"><B>mx.database.table.test</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="mx.database.navigator"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/navigator/package-summary.html">mx.database.navigator</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/navigator/package-summary.html">mx.database.navigator</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../mx/database/navigator/QueryNavigator.html" title="class in mx.database.navigator">QueryNavigator</A></B></CODE>
<BR>
Questa classe viene utilizzata per la gestione della navigazione delle tabelle</TD>
</TR>
</TABLE>
<P>
<A NAME="mx.database.table.test"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A> in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../mx/database/table/test/CalcID.html" title="class in mx.database.table.test">CalcID</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../mx/database/table/test/package-summary.html">mx.database.table.test</A> declared as <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>private <A HREF="../../../../mx/database/table/Query.html" title="class in mx.database.table">Query</A></CODE></FONT></TD>
<TD><CODE><B>QueryTest.</B><B><A HREF="../../../../mx/database/table/test/QueryTest.html#query">query</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<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="<API key>"></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="../../../../mx/database/table/Query.html" title="class in mx.database.table"><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="../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-files/index-1.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?mx/database/table/\class-useQuery.html" target="_top"><B>FRAMES</B></A>
<A HREF="Query.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>
<HR>
</BODY>
</HTML>
|
from ctypes import *
import ctypes.util
import threading
import os
import sys
from warnings import warn
from functools import partial
import collections
import re
import traceback
# vim: ts=4 sw=4 et
if os.name == 'nt':
backend = CDLL('mpv-1.dll')
fs_enc = 'utf-8'
else:
import locale
lc, enc = locale.getlocale(locale.LC_NUMERIC)
# libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is
# still better than segfaulting, we are setting LC_NUMERIC to "C".
locale.setlocale(locale.LC_NUMERIC, 'C')
sofile = ctypes.util.find_library('mpv')
if sofile is None:
raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an "
"mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, maybe consult "
"the documentation for ctypes.util.find_library which this script uses to look up the library "
"filename.")
backend = CDLL(sofile)
fs_enc = sys.<API key>()
class MpvHandle(c_void_p):
pass
class MpvOpenGLCbContext(c_void_p):
pass
class <API key>(AttributeError):
pass
class ErrorCode(object):
""" For documentation on these, see mpv's libmpv/client.h """
SUCCESS = 0
EVENT_QUEUE_FULL = -1
NOMEM = -2
UNINITIALIZED = -3
INVALID_PARAMETER = -4
OPTION_NOT_FOUND = -5
OPTION_FORMAT = -6
OPTION_ERROR = -7
PROPERTY_NOT_FOUND = -8
PROPERTY_FORMAT = -9
<API key> = -10
PROPERTY_ERROR = -11
COMMAND = -12
EXCEPTION_DICT = {
0: None,
-1: lambda *a: MemoryError('mpv event queue full', *a),
-2: lambda *a: MemoryError('mpv cannot allocate memory', *a),
-3: lambda *a: ValueError('Uninitialized mpv handle used', *a),
-4: lambda *a: ValueError('Invalid value for mpv parameter', *a),
-5: lambda *a: AttributeError('mpv option does not exist', *a),
-6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a),
-7: lambda *a: ValueError('Invalid value for mpv option', *a),
-8: lambda *a: AttributeError('mpv property does not exist', *a),
# Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of
# INVALID_PARAMETER when setting a property-mapped option to an invalid value.
-9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a),
-10: lambda *a: <API key>('mpv property is not available', *a),
-11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a),
-12: lambda *a: SystemError('Error running mpv command', *a) }
@staticmethod
def <API key>(ec, *args):
return ValueError(_mpv_error_string(ec).decode('utf-8'), ec, *args)
@classmethod
def raise_for_ec(kls, ec, func, *args):
ec = 0 if ec > 0 else ec
ex = kls.EXCEPTION_DICT.get(ec , kls.<API key>)
if ex:
raise ex(ec, *args)
class MpvFormat(c_int):
NONE = 0
STRING = 1
OSD_STRING = 2
FLAG = 3
INT64 = 4
DOUBLE = 5
NODE = 6
NODE_ARRAY = 7
NODE_MAP = 8
BYTE_ARRAY = 9
def __eq__(self, other):
return self is other or self.value == other or self.value == int(other)
def __repr__(self):
return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP',
'BYTE_ARRAY'][self.value]
class MpvEventID(c_int):
NONE = 0
SHUTDOWN = 1
LOG_MESSAGE = 2
GET_PROPERTY_REPLY = 3
SET_PROPERTY_REPLY = 4
COMMAND_REPLY = 5
START_FILE = 6
END_FILE = 7
FILE_LOADED = 8
TRACKS_CHANGED = 9
TRACK_SWITCHED = 10
IDLE = 11
PAUSE = 12
UNPAUSE = 13
TICK = 14
<API key> = 15
CLIENT_MESSAGE = 16
VIDEO_RECONFIG = 17
AUDIO_RECONFIG = 18
METADATA_UPDATE = 19
SEEK = 20
PLAYBACK_RESTART = 21
PROPERTY_CHANGE = 22
CHAPTER_CHANGE = 23
ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE,
FILE_LOADED, TRACKS_CHANGED, TRACK_SWITCHED, IDLE, PAUSE, UNPAUSE, TICK, <API key>,
CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, METADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE,
CHAPTER_CHANGE )
def __repr__(self):
return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_PROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY',
'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE',
'TICK', '<API key>', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG',
'METADATA_UPDATE', 'SEEK', 'PLAYBACK_RESTART', 'PROPERTY_CHANGE', 'CHAPTER_CHANGE'][self.value]
class MpvNodeList(Structure):
def array_value(self, decode_str=False):
return [ self.values[i].node_value(decode_str) for i in range(self.num) ]
def dict_value(self, decode_str=False):
return { self.keys[i].decode('utf-8'): self.values[i].node_value(decode_str) for i in range(self.num) }
class MpvNode(Structure):
_fields_ = [('val', c_longlong),
('format', MpvFormat)]
def node_value(self, decode_str=False):
return MpvNode.node_cast_value(byref(c_void_p(self.val)), self.format.value, decode_str)
@staticmethod
def node_cast_value(v, fmt, decode_str=False):
dwrap = lambda s: s.decode('utf-8') if decode_str else s
return {
MpvFormat.NONE: lambda v: None,
MpvFormat.STRING: lambda v: dwrap(cast(v, POINTER(c_char_p)).contents.value),
MpvFormat.OSD_STRING: lambda v: cast(v, POINTER(c_char_p)).contents.value.decode('utf-8'),
MpvFormat.FLAG: lambda v: bool(cast(v, POINTER(c_int)).contents.value),
MpvFormat.INT64: lambda v: cast(v, POINTER(c_longlong)).contents.value,
MpvFormat.DOUBLE: lambda v: cast(v, POINTER(c_double)).contents.value,
MpvFormat.NODE: lambda v: cast(v, POINTER(MpvNode)).contents.node_value(decode_str),
MpvFormat.NODE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.array_value(decode_str),
MpvFormat.NODE_MAP: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.dict_value(decode_str),
MpvFormat.BYTE_ARRAY: lambda v: cast(v, POINTER(c_char_p)).contents.value,
}[fmt](v)
MpvNodeList._fields_ = [('num', c_int),
('values', POINTER(MpvNode)),
('keys', POINTER(c_char_p))]
class MpvSubApi(c_int):
<API key> = 1
class MpvEvent(Structure):
_fields_ = [('event_id', MpvEventID),
('error', c_int),
('reply_userdata', c_ulonglong),
('data', c_void_p)]
def as_dict(self):
dtype = {MpvEventID.END_FILE: MpvEventEndFile,
MpvEventID.PROPERTY_CHANGE: MpvEventProperty,
MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty,
MpvEventID.LOG_MESSAGE: MpvEventLogMessage,
MpvEventID.<API key>: <API key>,
MpvEventID.CLIENT_MESSAGE: <API key>
}.get(self.event_id.value, None)
return {'event_id': self.event_id.value,
'error': self.error,
'reply_userdata': self.reply_userdata,
'event': cast(self.data, POINTER(dtype)).contents.as_dict() if dtype else None}
class MpvEventProperty(Structure):
_fields_ = [('name', c_char_p),
('format', MpvFormat),
('data', c_void_p)]
def as_dict(self):
if self.format.value == MpvFormat.STRING:
proptype, _access = ALL_PROPERTIES.get(self.name, (str, None))
return {'name': self.name.decode('utf-8'),
'format': self.format,
'data': self.data,
'value': proptype(cast(self.data, POINTER(c_char_p)).contents.value.decode('utf-8'))}
else:
return {'name': self.name.decode('utf-8'),
'format': self.format,
'data': self.data}
class MpvEventLogMessage(Structure):
_fields_ = [('prefix', c_char_p),
('level', c_char_p),
('text', c_char_p)]
def as_dict(self):
return { 'prefix': self.prefix.decode('utf-8'),
'level': self.level.decode('utf-8'),
'text': self.text.decode('utf-8').rstrip() }
class MpvEventEndFile(c_int):
EOF_OR_INIT_FAILURE = 0
RESTARTED = 1
ABORTED = 2
QUIT = 3
def as_dict(self):
return {'reason': self.value}
class <API key>(Structure):
_fields_ = [('arg0', c_int),
('type', c_char_p)]
def as_dict(self):
pass # TODO
class <API key>(Structure):
_fields_ = [('num_args', c_int),
('args', POINTER(c_char_p))]
def as_dict(self):
return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] }
WakeupCallback = CFUNCTYPE(None, c_void_p)
OpenGlCbUpdateFn = CFUNCTYPE(None, c_void_p)
<API key> = CFUNCTYPE(None, c_void_p, c_char_p)
def _handle_func(name, args, restype, errcheck, ctx=MpvHandle):
func = getattr(backend, name)
func.argtypes = [ctx] + args if ctx else args
if restype is not None:
func.restype = restype
if errcheck is not None:
func.errcheck = errcheck
globals()['_'+name] = func
def bytes_free_errcheck(res, func, *args):
notnull_errcheck(res, func, *args)
rv = cast(res, c_void_p).value
_mpv_free(res)
return rv
def notnull_errcheck(res, func, *args):
if res is None:
raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\
'Please consult your local debugger.'.format(func.__name__, args))
return res
ec_errcheck = ErrorCode.raise_for_ec
def _handle_gl_func(name, args=[], restype=None):
_handle_func(name, args, restype, errcheck=None, ctx=MpvOpenGLCbContext)
backend.<API key>.restype = c_ulong
def <API key>():
ver = backend.<API key>()
return ver>>16, ver&0xFFFF
backend.mpv_free.argtypes = [c_void_p]
_mpv_free = backend.mpv_free
backend.<API key>.argtypes = [c_void_p]
<API key> = backend.<API key>
backend.mpv_create.restype = MpvHandle
_mpv_create = backend.mpv_create
_handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck)
_handle_func('mpv_client_name', [], c_char_p, errcheck=None)
_handle_func('mpv_initialize', [], c_int, ec_errcheck)
_handle_func('mpv_detach_destroy', [], None, errcheck=None)
_handle_func('<API key>', [], None, errcheck=None)
_handle_func('<API key>', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_suspend', [], None, errcheck=None)
_handle_func('mpv_resume', [], None, errcheck=None)
_handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None)
_handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('<API key>', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck)
_handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('<API key>', [c_char_p, c_char_p], c_int, ec_errcheck)
_handle_func('<API key>', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck)
_handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
_handle_func('<API key>', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('<API key>', [c_char_p], c_void_p, bytes_free_errcheck)
_handle_func('<API key>', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('<API key>', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
_handle_func('<API key>', [c_ulonglong], c_int, ec_errcheck)
_handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None)
_handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck)
_handle_func('<API key>', [c_char_p], c_int, ec_errcheck)
_handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None)
_handle_func('mpv_wakeup', [], None, errcheck=None)
_handle_func('<API key>', [WakeupCallback, c_void_p], None, errcheck=None)
_handle_func('mpv_get_wakeup_pipe', [], c_int, errcheck=None)
_handle_func('mpv_get_sub_api', [MpvSubApi], c_void_p, notnull_errcheck)
_handle_gl_func('<API key>', [OpenGlCbUpdateFn, c_void_p])
_handle_gl_func('<API key>', [c_char_p, <API key>, c_void_p], c_int)
_handle_gl_func('mpv_opengl_cb_draw', [c_int, c_int, c_int], c_int)
_handle_gl_func('<API key>', [c_int, c_int], c_int)
_handle_gl_func('<API key>', [c_ulonglong], c_int)
_handle_gl_func('<API key>', [], c_int)
def _ensure_encoding(possibly_bytes):
return possibly_bytes.decode('utf-8') if type(possibly_bytes) is bytes else possibly_bytes
def _event_generator(handle):
while True:
event = _mpv_wait_event(handle, -1).contents
if event.event_id.value == MpvEventID.NONE:
raise StopIteration()
yield event
def load_lua():
""" Use this function if you intend to use mpv's built-in lua interpreter. This is e.g. needed for playback of
youtube urls. """
CDLL('liblua.so', mode=RTLD_GLOBAL)
def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler):
for event in _event_generator(event_handle):
try:
devent = event.as_dict() # copy data from ctypes
eid = devent['event_id']
for callback in event_callbacks:
callback(devent)
if eid in (MpvEventID.SHUTDOWN, MpvEventID.END_FILE):
with playback_cond:
playback_cond.notify_all()
if eid == MpvEventID.PROPERTY_CHANGE:
pc = devent['event']
name = pc['name']
if 'value' in pc:
proptype, _access = ALL_PROPERTIES[name]
if proptype is bytes:
args = (pc['value'],)
else:
args = (proptype(_ensure_encoding(pc['value'])),)
elif pc['format'] == MpvFormat.NONE:
args = (None,)
else:
args = (pc['data'], pc['format'])
for handler in property_handlers[name]:
handler(*args)
if eid == MpvEventID.LOG_MESSAGE and log_handler is not None:
ev = devent['event']
log_handler(ev['level'], ev['prefix'], ev['text'])
if eid == MpvEventID.CLIENT_MESSAGE:
# {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16}
target, *args = devent['event']['args']
if target in message_handlers:
message_handlers[target](*args)
if eid == MpvEventID.SHUTDOWN:
_mpv_detach_destroy(event_handle)
return
except Exception as e:
traceback.print_exc()
class MPV(object):
""" See man mpv(1) for the details of the implemented commands. """
def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, **extra_mpv_opts):
""" Create an MPV instance.
Extra arguments and extra keyword arguments will be passed to mpv as options. """
self._event_thread = None
self.handle = _mpv_create()
<API key>(self.handle, b'audio-display', b'no')
istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
try:
for flag in extra_mpv_flags:
<API key>(self.handle, flag.encode('utf-8'), b'')
for k,v in extra_mpv_opts.items():
<API key>(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
except AttributeError as e:
_mpv_initialize(self.handle)
raise e
_mpv_initialize(self.handle)
self._event_callbacks = []
self._property_handlers = collections.defaultdict(lambda: [])
self._message_handlers = {}
self.<API key> = {}
self._playback_cond = threading.Condition()
self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
self._message_handlers, self._property_handlers, log_handler)
if start_event_thread:
self._event_thread = threading.Thread(target=self._loop, name='<API key>')
self._event_thread.setDaemon(True)
self._event_thread.start()
else:
self._event_thread = None
if log_handler is not None:
self.set_loglevel('terminal-default')
def wait_for_playback(self):
""" Waits until playback of the current title is paused or done """
with self._playback_cond:
self._playback_cond.wait()
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
sema = threading.Semaphore(value=0)
def observer(val):
if cond(val):
sema.release()
self.observe_property(name, observer)
if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
sema.acquire()
self.unobserve_property(name, observer)
def __del__(self):
if self.handle:
self.terminate()
def terminate(self):
self.handle, handle = None, self.handle
if threading.current_thread() is self._event_thread:
# Handle special case to allow event handle to be detached.
# This is necessary since otherwise the event thread would deadlock itself.
grim_reaper = threading.Thread(target=lambda: <API key>(handle))
grim_reaper.start()
else:
<API key>(handle)
if self._event_thread:
self._event_thread.join()
def set_loglevel(self, level):
<API key>(self._event_handle, level.encode('utf-8'))
def command(self, name, *args):
""" Execute a raw command """
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
for arg in args if arg is not None ] + [None]
_mpv_command(self.handle, (c_char_p*len(args))(*args))
def seek(self, amount, reference="relative", precision="default-precise"):
self.command('seek', amount, reference, precision)
def revert_seek(self):
self.command('revert_seek');
def frame_step(self):
self.command('frame_step')
def frame_back_step(self):
self.command('frame_back_step')
def _add_property(self, name, value=None):
self.command('add_property', name, value)
def _cycle_property(self, name, direction='up'):
self.command('cycle_property', name, direction)
def _multiply_property(self, name, factor):
self.command('multiply_property', name, factor)
def screenshot(self, includes='subtitles', mode='single'):
self.command('screenshot', includes, mode)
def screenshot_to_file(self, filename, includes='subtitles'):
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def playlist_next(self, mode='weak'):
self.command('playlist_next', mode)
def playlist_prev(self, mode='weak'):
self.command('playlist_prev', mode)
@staticmethod
def _encode_options(options):
return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
def loadfile(self, filename, mode='replace', **options):
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadlist(self, playlist, mode='replace'):
self.command('loadlist', playlist.encode(fs_enc), mode)
def playlist_clear(self):
self.command('playlist_clear')
def playlist_remove(self, index='current'):
self.command('playlist_remove', index)
def playlist_move(self, index1, index2):
self.command('playlist_move', index1, index2)
def run(self, command, *args):
self.command('run', command, *args)
def quit(self, code=None):
self.command('quit', code)
def quit_watch_later(self, code=None):
self.command('quit_watch_later', code)
def sub_add(self, filename):
self.command('sub_add', filename.encode(fs_enc))
def sub_remove(self, sub_id=None):
self.command('sub_remove', sub_id)
def sub_reload(self, sub_id=None):
self.command('sub_reload', sub_id)
def sub_step(self, skip):
self.command('sub_step', skip)
def sub_seek(self, skip):
self.command('sub_seek', skip)
def toggle_osd(self):
self.command('osd')
def show_text(self, string, duration='-', level=None):
self.command('show_text', string, duration, level)
def show_progress(self):
self.command('show_progress')
def discnav(self, command):
self.command('discnav', command)
def <API key>(self):
self.command('<API key>')
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_remove(self, overlay_id):
self.command('overlay_remove', overlay_id)
def script_message(self, *args):
self.command('script_message', *args)
def script_message_to(self, target, *args):
self.command('script_message_to', target, *args)
def observe_property(self, name, handler):
self._property_handlers[name].append(handler)
<API key>(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.STRING)
def unobserve_property(self, name, handler):
handlers = self._property_handlers[name]
handlers.remove(handler)
if not handlers:
<API key>(self._event_handle, hash(name)&0xffffffffffffffff)
def <API key>(self, target, handler):
self._message_handlers[target] = handler
def <API key>(self, target):
del self._message_handlers[target]
def <API key>(self, callback):
self._event_callbacks.append(callback)
def <API key>(self, callback):
self._event_callbacks.remove(callback)
@staticmethod
def _binding_name(callback_or_cmd):
return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
def <API key>(self, keydef, callback_or_cmd, mode='force'):
""" BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary
code exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in
the first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files,
this is completely fine--but, if you are about to pass untrusted input into this parameter, better double-check
whether this is secure in your case. """
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
'<key> is either the literal character the key produces (ASCII or Unicode character), or a '
'symbolic name (as printed by --input-keylist')
binding_name = MPV._binding_name(keydef)
if callable(callback_or_cmd):
self.<API key>[binding_name] = callback_or_cmd
self.<API key>('key-binding', self.<API key>)
self.command('define-section',
binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
elif isinstance(callback_or_cmd, str):
self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
else:
raise TypeError('<API key> expects either an str with an mpv command or a python callable.')
self.command('enable-section', binding_name)
def <API key>(self, binding_name, key_state, key_name):
self.<API key>[binding_name](key_state, key_name)
def <API key>(self, keydef):
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if callable(callback):
del self.<API key>[binding_name]
if not self.<API key>:
self.<API key>('key-binding')
# Convenience functions
def play(self, filename):
self.loadfile(filename)
# Property accessors
def _get_property(self, name, proptype=str, decode_str=False):
fmt = {int: MpvFormat.INT64,
float: MpvFormat.DOUBLE,
bool: MpvFormat.FLAG,
str: MpvFormat.STRING,
bytes: MpvFormat.STRING,
commalist: MpvFormat.STRING,
MpvFormat.NODE: MpvFormat.NODE}[proptype]
out = cast(<API key>(sizeof(c_void_p)), c_void_p)
outptr = byref(out)
try:
cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, outptr)
rv = MpvNode.node_cast_value(outptr, fmt, decode_str or proptype in (str, commalist))
if proptype is commalist:
rv = proptype(rv)
if proptype is str:
_mpv_free(out)
elif proptype is MpvFormat.NODE:
<API key>(outptr)
return rv
except <API key> as ex:
return None
def _set_property(self, name, value, proptype=str):
ename = name.encode('utf-8')
if type(value) is bytes:
<API key>(self.handle, ename, value)
elif type(value) is bool:
<API key>(self.handle, ename, b'yes' if value else b'no')
elif proptype in (str, int, float):
<API key>(self.handle, ename, str(proptype(value)).encode('utf-8'))
else:
raise TypeError('Cannot set {} property {} to value of type {}'.format(proptype, name, type(value)))
# Dict-like option access
def __getitem__(self, name, file_local=False):
""" Get an option value """
prefix = 'file-local-options/' if file_local else 'options/'
return self._get_property(prefix+name)
def __setitem__(self, name, value, file_local=False):
""" Get an option value """
prefix = 'file-local-options/' if file_local else 'options/'
return self._set_property(prefix+name, value)
def __iter__(self):
return iter(self.options)
def option_info(self, name):
return self._get_property('option-info/'+name)
def commalist(propval=''):
return str(propval).split(',')
node = MpvFormat.NODE
ALL_PROPERTIES = {
'osd-level': (int, 'rw'),
'osd-scale': (float, 'rw'),
'loop': (str, 'rw'),
'loop-file': (str, 'rw'),
'speed': (float, 'rw'),
'filename': (bytes, 'r'),
'file-size': (int, 'r'),
'path': (bytes, 'r'),
'media-title': (bytes, 'r'),
'stream-pos': (int, 'rw'),
'stream-end': (int, 'r'),
'length': (float, 'r'), # deprecated for ages now
'duration': (float, 'r'),
'avsync': (float, 'r'),
'total-avsync-change': (float, 'r'),
'drop-frame-count': (int, 'r'),
'percent-pos': (float, 'rw'),
# 'ratio-pos': (float, 'rw'),
'time-pos': (float, 'rw'),
'time-start': (float, 'r'),
'time-remaining': (float, 'r'),
'playtime-remaining': (float, 'r'),
'chapter': (int, 'rw'),
'edition': (int, 'rw'),
'disc-titles': (int, 'r'),
'disc-title': (str, 'rw'),
# 'disc-menu-active': (bool, 'r'),
'chapters': (int, 'r'),
'editions': (int, 'r'),
'angle': (int, 'rw'),
'pause': (bool, 'rw'),
'core-idle': (bool, 'r'),
'cache': (int, 'r'),
'cache-size': (int, 'rw'),
'cache-free': (int, 'r'),
'cache-used': (int, 'r'),
'cache-speed': (int, 'r'),
'cache-idle': (bool, 'r'),
'<API key>': (int, 'r'),
'paused-for-cache': (bool, 'r'),
# 'pause-for-cache': (bool, 'r'),
'eof-reached': (bool, 'r'),
# '<API key>': (str, 'rw'),
'hr-seek': (str, 'rw'),
'volume': (float, 'rw'),
'volume-max': (int, 'rw'),
'ao-volume': (float, 'rw'),
'mute': (bool, 'rw'),
'ao-mute': (bool, 'rw'),
'<API key>': (float, 'r'),
'audio-delay': (float, 'rw'),
'audio-format': (str, 'r'),
'audio-codec': (str, 'r'),
'audio-codec-name': (str, 'r'),
'audio-bitrate': (float, 'r'),
'<API key>': (float, 'r'),
'audio-samplerate': (int, 'r'),
'audio-channels': (str, 'r'),
'aid': (str, 'rw'),
'audio': (str, 'rw'), # alias for aid
'balance': (int, 'rw'),
'fullscreen': (bool, 'rw'),
'deinterlace': (str, 'rw'),
'colormatrix': (str, 'rw'),
'<API key>': (str, 'rw'),
# '<API key>': (str, 'rw'),
'<API key>': (str, 'rw'),
'ontop': (bool, 'rw'),
'border': (bool, 'rw'),
'framedrop': (str, 'rw'),
'gamma': (float, 'rw'),
'brightness': (int, 'rw'),
'contrast': (int, 'rw'),
'saturation': (int, 'rw'),
'hue': (int, 'rw'),
'hwdec': (str, 'rw'),
'panscan': (float, 'rw'),
'video-format': (str, 'r'),
'video-codec': (str, 'r'),
'video-bitrate': (float, 'r'),
'<API key>': (float, 'r'),
'width': (int, 'r'),
'height': (int, 'r'),
'dwidth': (int, 'r'),
'dheight': (int, 'r'),
'fps': (float, 'r'),
'estimated-vf-fps': (float, 'r'),
'window-scale': (float, 'rw'),
'video-aspect': (str, 'rw'),
'osd-width': (int, 'r'),
'osd-height': (int, 'r'),
'osd-par': (float, 'r'),
'vid': (str, 'rw'),
'video': (str, 'rw'), # alias for vid
'video-align-x': (float, 'rw'),
'video-align-y': (float, 'rw'),
'video-pan-x': (float, 'rw'),
'video-pan-y': (float, 'rw'),
'video-zoom': (float, 'rw'),
'video-unscaled': (bool, 'w'),
'<API key>': (float, 'r'),
'program': (int, 'w'),
'sid': (str, 'rw'),
'sub': (str, 'rw'), # alias for sid
'secondary-sid': (str, 'rw'),
'sub-delay': (float, 'rw'),
'sub-pos': (int, 'rw'),
'sub-visibility': (bool, 'rw'),
'sub-forced-only': (bool, 'rw'),
'sub-scale': (float, 'rw'),
'sub-bitrate': (float, 'r'),
'packet-sub-bitrate': (float, 'r'),
# 'ass-use-margins': (bool, 'rw'),
'<API key>': (bool, 'rw'),
'ass-style-override': (bool, 'rw'),
'stream-capture': (str, 'rw'),
'tv-brightness': (int, 'rw'),
'tv-contrast': (int, 'rw'),
'tv-saturation': (int, 'rw'),
'tv-hue': (int, 'rw'),
'playlist-pos': (int, 'rw'),
'playlist-pos-1': (int, 'rw'), # ugh.
'playlist-count': (int, 'r'),
# 'quvi-format': (str, 'rw'),
'seekable': (bool, 'r'),
'seeking': (bool, 'r'),
'partially-seekable': (bool, 'r'),
'playback-abort': (bool, 'r'),
'cursor-autohide': (str, 'rw'),
'audio-device': (str, 'rw'),
'current-vo': (str, 'r'),
'current-ao': (str, 'r'),
'<API key>': (str, 'r'),
'protocol-list': (str, 'r'),
'mpv-version': (str, 'r'),
'mpv-configuration': (str, 'r'),
'ffmpeg-version': (str, 'r'),
'display-sync-active': (bool, 'r'),
'<API key>': (bytes, 'rw'), # Undocumented
'file-format': (commalist,'r'), # Be careful with this one.
'<API key>': (int, 'r'),
'vsync-ratio': (float, 'r'),
'vo-drop-frame-count': (int, 'r'),
'<API key>': (int, 'r'),
'playback-time': (float, 'rw'),
'<API key>': (float, 'r'),
'demuxer-cache-time': (float, 'r'),
'demuxer-cache-idle': (bool, 'r'),
'idle': (bool, 'r'),
'disc-title-list': (commalist,'r'),
'field-dominance': (str, 'rw'),
'taskbar-progress': (bool, 'rw'),
'on-all-workspaces': (bool, 'rw'),
'video-output-levels': (str, 'r'),
'vo-configured': (bool, 'r'),
'hwdec-current': (str, 'r'),
'hwdec-interop': (str, 'r'),
'<API key>': (int, 'r'),
'<API key>': (int, 'r'),
'sub-use-margins': (bool, 'rw'),
'ass-force-margins': (bool, 'rw'),
'video-rotate': (str, 'rw'),
'video-stereo-mode': (str, 'rw'),
'ab-loop-a': (str, 'r'), # What a mess...
'ab-loop-b': (str, 'r'),
'dvb-channel': (str, 'w'),
'dvb-channel-name': (str, 'rw'),
'window-minimized': (bool, 'r'),
'display-names': (commalist, 'r'),
'display-fps': (float, 'r'), # access apparently misdocumented in the manpage
'<API key>': (float, 'r'),
'vsync-jitter': (float, 'r'),
'video-params': (node, 'r', True),
'video-out-params': (node, 'r', True),
'track-list': (node, 'r', False),
'playlist': (node, 'r', False),
'chapter-list': (node, 'r', False),
'vo-performance': (node, 'r', True),
'filtered-metadata': (node, 'r', False),
'metadata': (node, 'r', False),
'chapter-metadata': (node, 'r', False),
'vf-metadata': (node, 'r', False),
'af-metadata': (node, 'r', False),
'edition-list': (node, 'r', False),
'disc-titles': (node, 'r', False),
'audio-params': (node, 'r', True),
'audio-out-params': (node, 'r', True),
'audio-device-list': (node, 'r', True),
'video-frame-info': (node, 'r', True),
'decoder-list': (node, 'r', True),
'encoder-list': (node, 'r', True),
'vf': (node, 'r', True),
'af': (node, 'r', True),
'options': (node, 'r', True),
'file-local-options': (node, 'r', True),
'property-list': (commalist,'r')}
def bindproperty(MPV, name, proptype, access, decode_str=False):
getter = lambda self: self._get_property(name, proptype, decode_str)
setter = lambda self, value: self._set_property(name, value, proptype)
def barf(*args):
raise NotImplementedError('Access denied')
setattr(MPV, name.replace('-', '_'), property(getter if 'r' in access else barf, setter if 'w' in access else barf))
for name, (proptype, access, *args) in ALL_PROPERTIES.items():
bindproperty(MPV, name, proptype, access, *args)
|
package org.kuali.kfs.module.purap.document.validation.impl;
import org.kuali.kfs.coreservice.framework.parameter.ParameterService;
import org.kuali.kfs.module.purap.PurapConstants;
import org.kuali.kfs.module.purap.<API key>;
import org.kuali.kfs.module.purap.PurapRuleConstants;
import org.kuali.kfs.module.purap.document.RequisitionDocument;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.document.validation.event.<API key>;
public class <API key> extends <API key> {
public boolean validate(<API key> event) {
return super.validate(event);
}
@Override
protected boolean <API key>() {
//if the <API key> parameter is N then we don't
//need to check for the <API key> parameter anymore, just return false.
boolean enableCommodityCode = SpringContext.getBean(ParameterService.class).<API key>(PurapConstants.PURAP_NAMESPACE, "Document", <API key>.<API key>);
if (!enableCommodityCode) {
return false;
} else {
return super.getParameterService().<API key>(RequisitionDocument.class, PurapRuleConstants.<API key>);
}
}
}
|
#pragma once
//\brief: TypeFlags, mostly used to define updatePackets.
//\note: check out class inheritance. it is not true that every unit is "just" a creature.
/*
object
- unit
- - player
- - creature
- - - pet <- probably wrong inheritance from summon not from creature
- - - totem <- probably wrong inheritance from summon not from creature
- - - vehicle
- - - summon (pets and totems are always summons)
- - - - pet
- - - - totem
- gameobject
- dynamicobject
- corpse
- item
- - container
*/
enum TYPE
{
TYPE_OBJECT = 1,
TYPE_ITEM = 2,
TYPE_CONTAINER = 4,
TYPE_UNIT = 8,
TYPE_PLAYER = 16,
TYPE_GAMEOBJECT = 32,
TYPE_DYNAMICOBJECT = 64,
TYPE_CORPSE = 128,
//TYPE_AIGROUP = 256, not used
//TYPE_AREATRIGGER = 512, not used
//TYPE_IN_GUILD = 1024 not used
};
//\todo: remove these typeIds and use flags instead. No reason to use two different enums to define a object type.
enum TYPEID
{
TYPEID_OBJECT = 0,
TYPEID_ITEM = 1,
TYPEID_CONTAINER = 2,
TYPEID_UNIT = 3,
TYPEID_PLAYER = 4,
TYPEID_GAMEOBJECT = 5,
<API key> = 6,
TYPEID_CORPSE = 7,
//TYPEID_AIGROUP = 8, not used
//TYPEID_AREATRIGGER = 9 not used (WoWTrigger is a thing on Cata)
};
#ifdef AE_CATA
enum OBJECT_UPDATE_TYPE
{
UPDATETYPE_VALUES = 0,
<API key> = 1,
<API key> = 2,
<API key> = 3
};
#else
enum OBJECT_UPDATE_TYPE
{
UPDATETYPE_VALUES = 0,
UPDATETYPE_MOVEMENT = 1,
<API key> = 2,
<API key> = 3,
<API key> = 4
};
#endif
enum PHASECOMMANDS
{
PHASE_SET = 0, /// overwrites the phase value with the supplied one
PHASE_ADD = 1, /// adds the new bits to the current phase value
PHASE_DEL = 2, /// removes the given bits from the current phase value
PHASE_RESET = 3 /// sets the default phase of 1, same as PHASE_SET with 1 as the new value
};
|
<?php
declare(strict_types=1);
namespace OC\Files\Mount;
use OC\Files\ObjectStore\<API key>;
use OC\Files\ObjectStore\ObjectStoreStorage;
use OC\Files\Storage\Wrapper\Jail;
use OCP\Files\Config\IRootMountProvider;
use OCP\Files\Storage\IStorageFactory;
use OCP\IConfig;
use OCP\ILogger;
/**
* Mount provider for object store app data folder for previews
*/
class <API key> implements IRootMountProvider {
/** @var ILogger */
private $logger;
/** @var IConfig */
private $config;
public function __construct(ILogger $logger, IConfig $config) {
$this->logger = $logger;
$this->config = $config;
}
/**
* @return MountPoint[]
* @throws \Exception
*/
public function getRootMounts(IStorageFactory $loader): array {
if (!is_array($this->config->getSystemValue('<API key>'))) {
return [];
}
if ($this->config->getSystemValue('objectstore.multibucket.<API key>', false) !== true) {
return [];
}
$instanceId = $this->config-><API key>('instanceid', '');
$mountPoints = [];
$directoryRange = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
$i = 0;
foreach ($directoryRange as $parent) {
foreach ($directoryRange as $child) {
$mountPoints[] = new MountPoint(
<API key>::class,
'/appdata_' . $instanceId . '/preview/' . $parent . '/' . $child,
$this-><API key>($i),
$loader
);
$i++;
}
}
$<API key> = $this-><API key>();
$fakeRootStorage = new ObjectStoreStorage($<API key>);
$fakeRootStorageJail = new Jail([
'storage' => $fakeRootStorage,
'root' => '/appdata_' . $instanceId . '/preview',
]);
// add a fallback location to be able to fetch existing previews from the old bucket
$mountPoints[] = new MountPoint(
$fakeRootStorageJail,
'/appdata_' . $instanceId . '/preview/old-multibucket',
null,
$loader
);
return $mountPoints;
}
protected function <API key>(int $number): array {
$config = $this->config->getSystemValue('<API key>');
// sanity checks
if (empty($config['class'])) {
$this->logger->error('No class given for objectstore', ['app' => 'files']);
}
if (!isset($config['arguments'])) {
$config['arguments'] = [];
}
/*
* Use any provided bucket argument as prefix
* and add the mapping from parent/child => bucket
*/
if (!isset($config['arguments']['bucket'])) {
$config['arguments']['bucket'] = '';
}
$config['arguments']['bucket'] .= "-preview-$number";
// instantiate object store implementation
$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
$config['arguments']['internal-id'] = $number;
return $config['arguments'];
}
protected function <API key>(): array {
$config = $this->config->getSystemValue('<API key>');
// sanity checks
if (empty($config['class'])) {
$this->logger->error('No class given for objectstore', ['app' => 'files']);
}
if (!isset($config['arguments'])) {
$config['arguments'] = [];
}
/*
* Use any provided bucket argument as prefix
* and add the mapping from parent/child => bucket
*/
if (!isset($config['arguments']['bucket'])) {
$config['arguments']['bucket'] = '';
}
$config['arguments']['bucket'] .= '0';
// instantiate object store implementation
$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
return $config['arguments'];
}
}
|
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../../../style.css');
@import url('../../../../../../../tree.css');
</style>
<script src="../../../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../../../cloud.js" type="text/javascript"></script>
<title><API key> </title>
</head>
<body >
<div id="page">
<header id="header" role="banner">
<nav class="aui-header <API key>" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo <API key>">
<a href="http:
</h1>
</div>
<div class="<API key>">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online Clover documentation" target="_blank"
href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="<API key>">
<div class="aui-page-panel-nav <API key>">
<div class="<API key>" style="margin-bottom: 20px;">
<div class="<API key>">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</div>
<div class="<API key>" >
<h1>
<API key>
</h1>
</div>
</div>
<nav class="aui-navgroup <API key>">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading <API key>">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui <API key>">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="<API key> hidden">
<small>No results found.</small>
</p>
<div class="<API key>" data-root-relative="../../../../../../../" data-package-name="com.rapidminer.tools.expression.internal.function.bitwise">
<div class="<API key>"></div>
<div class="<API key>"></div>
</div>
</div>
</div>
</nav> </div>
<section class="<API key>">
<div class="<API key>">
<ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../../../dashboard.html">Project Clover database 5 2017 16:40:29 CST</a></li>
</ol>
<h1 class="aui-h2-clover">
Package com.rapidminer.tools.expression.internal.function.bitwise
</h1>
<div class="aui-tabs horizontal-tabs">
<ul class="tabs-menu">
<li class="menu-item ">
<a href="pkg-summary.html"><strong>Application code</strong></a>
</li>
<li class="menu-item active-tab">
<a href="top-risks.html"><strong>Top risks</strong></a>
</li>
<li class="menu-item ">
<a href="quick-wins.html"><strong>Quick wins</strong></a>
</li>
</ul>
<div class="tabs-pane active-pane" id="tabs-first">
<div> </div>
<div class="aui-message aui-message-warning">
<p class="title">
<strong>Evaluation License</strong>
</p>
<p>
This report was generated with an evaluation server license. <a href="http:
</p>
</div>
<div style="text-align: right; margin-bottom: 10px">
<button class="aui-button aui-button-subtle" id="popupHelp">
<span class="aui-icon aui-icon-small aui-iconfont-help"></span> How to read this chart
</button>
<script>
AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog",
function (content, trigger, showPopup) {
var description = topRisksDescription();
var title = 'Top Risks';
content.css({"padding": "20px"}).html(
'<h2>' + title + '</h2>' + description);
showPopup();
return false;
},
{
width: 600
}
);
</script>
</div>
<div style="padding: 20px; border: 1px solid #cccccc; background-color: #f5f5f5; border-radius: 3px">
<div id="shallowPackageCloud" >
</div>
</div>
</div> <!-- tabs-pane active-pane -->
</div> <!-- aui-tabs horizontal-tabs -->
</div> <!-- class="<API key>" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http:
on 5 2017 17:24:16 CST using coverage data from 1 1970 08:00:00 CST.
</li>
</ul>
<ul>
<li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li>
</ul>
<div id="footer-logo">
<a target="_blank" href="http:
Atlassian
</a>
</div>
</section>
</footer> </section> <!-- class="<API key>" -->
</div> <!-- class="<API key>" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
# Kernel/GenericInterface/Operation/Session/SessionCreate.pm - GenericInterface SessionCreate operation backend
package Kernel::GenericInterface::Operation::Session::SessionCreate;
use strict;
use warnings;
use Kernel::GenericInterface::Operation::Common;
use Kernel::GenericInterface::Operation::Session::Common;
use Kernel::System::VariableCheck qw(IsStringWithData IsHashRefWithData);
use vars qw(@ISA);
=head1 NAME
Kernel::GenericInterface::Operation::Ticket::SessionCreate - GenericInterface Session Create Operation backend
=head1 SYNOPSIS
=head1 PUBLIC INTERFACE
=over 4
=cut
=item new()
usually, you want to create an instance of this
by using Kernel::GenericInterface::Operation->new();
=cut
sub new {
my ( $Type, %Param ) = @_;
my $Self = {};
bless( $Self, $Type );
# check needed objects
for my $Needed (
qw(DebuggerObject ConfigObject MainObject LogObject TimeObject DBObject EncodeObject WebserviceID)
)
{
if ( !$Param{$Needed} ) {
return {
Success => 0,
ErrorMessage => "Got no $Needed!"
};
}
$Self->{$Needed} = $Param{$Needed};
}
# create additional objects
$Self->{CommonObject} = Kernel::GenericInterface::Operation::Common->new( %{$Self} );
$Self->{SessionCommonObject}
= Kernel::GenericInterface::Operation::Session::Common->new( %{$Self} );
return $Self;
}
=item Run()
Retrieve a new session id value.
my $Result = $OperationObject->Run(
Data => {
UserLogin => 'Agent1',
CustomerUserLogin => 'Customer1', # optional, provide UserLogin or CustomerUserLogin
Password => 'some password', # plain text password
},
);
$Result = {
Success => 1, # 0 or 1
ErrorMessage => '', # In case of an error
Data => {
SessionID => $SessionID,
},
};
=cut
sub Run {
my ( $Self, %Param ) = @_;
# check needed stuff
if ( !IsHashRefWithData( $Param{Data} ) ) {
return $Self->{CommonObject}->ReturnError(
ErrorCode => 'SessionCreate.MissingParameter',
ErrorMessage => "SessionCreate: The request is empty!",
);
}
for my $Needed (qw( Password )) {
if ( !$Param{Data}->{$Needed} ) {
return $Self->{CommonObject}->ReturnError(
ErrorCode => 'SessionCreate.MissingParameter',
ErrorMessage => "SessionCreate: $Needed parameter is missing!",
);
}
}
my $SessionID = $Self->{SessionCommonObject}->CreateSessionID(
%Param,
);
if ( !$SessionID ) {
return $Self->{CommonObject}->ReturnError(
ErrorCode => 'SessionCreate.AuthFail',
ErrorMessage => "SessionCreate: Authorization failing!",
);
}
return {
Success => 1,
Data => {
SessionID => $SessionID,
},
};
}
1;
=back
=head1 TERMS AND CONDITIONS
This software is part of the OTRS project (L<http://otrs.org/>).
This software comes with ABSOLUTELY NO WARRANTY. For details, see
the enclosed file COPYING for license information (AGPL). If you
did not receive this file, see L<http:
=cut
|
<?php
/**
* I am a generated class and am required for communicating with plentymarkets.
*/
class <API key>
{
/**
* @var <API key>
*/
public $AttributeValueSets;
/**
* @var <API key>
*/
public $Availability;
/**
* @var string
*/
public $BundleType;
/**
* @var <API key>
*/
public $Categories;
/**
* @var int
*/
public $Condition;
/**
* @var string
*/
public $CustomsTariffNumber;
/**
* @var string
*/
public $DeepLink;
/**
* @var string
*/
public $EAN1;
/**
* @var string
*/
public $EAN2;
/**
* @var string
*/
public $EAN3;
/**
* @var string
*/
public $EAN4;
/**
* @var string
*/
public $ExternalItemID;
/**
* @var int
*/
public $FSK;
/**
* @var <API key>
*/
public $FreeTextFields;
/**
* @var int
*/
public $HasAttributes;
/**
* @var string
*/
public $ISBN;
/**
* @var int
*/
public $Inserted;
/**
* @var <API key>
*/
public $ItemAttributeMarkup;
/**
* @var int
*/
public $ItemID;
/**
* @var string
*/
public $ItemNo;
/**
* @var <API key>
*/
public $ItemProperties;
/**
* @var <API key>
*/
public $ItemSuppliers;
/**
* @var string
*/
public $ItemURL;
/**
* @var int
*/
public $LastUpdate;
/**
* @var int
*/
public $Marking1ID;
/**
* @var int
*/
public $Marking2ID;
/**
* @var string
*/
public $Model;
/**
* @var <API key>
*/
public $Others;
/**
* @var <API key>
*/
public $<API key>;
/**
* @var string
*/
public $Position;
/**
* @var <API key>
*/
public $PriceSet;
/**
* @var int
*/
public $ProducerID;
/**
* @var string
*/
public $ProducerName;
/**
* @var int
*/
public $ProducingCountryID;
/**
* @var int
*/
public $Published;
/**
* @var <API key>
*/
public $Stock;
/**
* @var int
*/
public $StorageLocation;
/**
* @var <API key>
*/
public $Texts;
/**
* @var int
*/
public $Type;
/**
* @var int
*/
public $VATInternalID;
/**
* @var string
*/
public $WebShopSpecial;
}
|
<div id="detail_{{ object.id }}" class="detail box ui-draggable ui-droppable expanded expanded-padding">
<div class="box-header">
<div class="box-name ui-draggable-handle">
<i class="fa fa-fw fa-search"></i>
<span>Details of subscription {{ object.name }}</span>
</div>
<div class="box-icons">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="expand-link">
<i class="fa fa-expand"></i>
</a>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
<div class="no-move"></div>
</div>
<div class="box-content">
<div id="details-content">
<div class="container-fluid">
<div class="row">
<div class="col-sm-8">
<div class="panel panel-primary">
<div class="panel-heading">Your subscription</div>
<div class="panel-body">
<h4 class="page-header">Your subscription</h4>
<div class="form-group">
<label class="col-sm-3 control-label">Subscription category</label>
<div class="col-sm-9 value">{{ subscription.category.label.capitalize }}</div>
</div>
{% if subscription.referrer %}
<div class="form-group">
<label class="col-sm-3 control-label">Referrer</label>
<div class="col-sm-9 value">{{ subscription.referrer }}</div>
</div>
{% endif %}
</div>
<table class="table">
<caption><h4 class="page-header">Modules selected</h4></caption>
<thead>
<tr>
<th>Name</th>
<th>Monthly cost</th>
<th>Yearly cost</th>
</tr>
</thead>
<tbody>
{% for module in subscription.modules.all %}
{% if module.monthly_price > 0 %}
<tr>
<td>{{ label }}</td>
<td>{{ module.monthly_price }} €</td>
<td>{{ module.yearly_price }} €</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
To change details of your subscription, please contact us. last modified, et tout çà.
</div>
</div>
</div>
<div class="col-sm-4">
<div class="panel panel-primary">
<div class="panel-heading">Assigned users</div>
<div class="panel-body">
<h4 class="page-header">Subscription owner</h4>
<div class="form-group">
<label class="col-sm-5 control-label">First name</label>
<div class="col-sm-7 value">
{{ subscription.owner.first_name }}
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Last name</label>
<div class="col-sm-7 value">
{{ subscription.owner.last_name }}
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label">Email</label>
<div class="col-sm-7 value">
{{ subscription.owner.email }}
</div>
</div>
{% if subscription.company_name %}
<div class="form-group">
<label class="col-sm-5 control-label">On behalf of company</label>
<div class="col-sm-7 value">{{ subscription.company_name }}</div>
</div>
{% endif %}
</div>
<table class="table">
<caption><h4 class="page-header">Access accounts</h4></caption>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for account in subscription.<API key>.all %}
<tr>
<td>{{ account.user.profile.label }}</td>
<td>{{ account.user.username }}</td>
<td>{{ account.role.label }}</td>
<td>{% if account.status.label == "created" %}
<button type="button" class="btn btn-primary btn-label-left"><span><i class="fa fa-fw fa-sign-in"></i></span>Created</button>
{% elif account.status.label == "activated" %}
<button type="button" class="btn btn-info btn-label-left"><span><i class="fa fa-fw fa-asterisk"></i></span>Activated</button>
{% elif account.status.label == "ongoing" %}
<button type="button" class="btn btn-success btn-label-left"><span><i class="fa fa-fw fa-thumbs-o-up"></i></span>Ongoing</button>
{% elif account.status.label == "suspended" %}
<button type="button" class="btn btn-info btn-label-left"><span><i class="fa fa-fw fa-asterisk"></i></span>Suspended</button>
{% elif account.status.label == "terminated" %}
<button type="button" class="btn btn-danger btn-label-left"><span><i class="fa fa-fw fa-question"></i></span>Terminated</button>
{% else %}
<button type="button" class="btn btn-default btn-label-left"><span><i class="fa fa-fw fa-question"></i></span>{{ account.status }}</button>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="panel-footer">
<form method="post" class="form-inline add_access_account" role="form" action="{% url 'saas:send_invitation' %}"">
{% csrf_token %}
<input type="hidden" name="<API key>" value="{{ subscription.pk }}" />
<div class="form-group">
<label for="invitation-email">Email</label>
<input type="email" class="form-control" id="invitation-email" name="invitation-email" placeholder="Guest email">
</div>
<button type="submit" class="btn btn-primary btn-label-left"><span><i class="fa fa-fw fa-send"></i></span>Send invitation</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
package storage
import (
"fmt"
"strings"
"time"
mgo "github.com/ilius/mgo"
"github.com/ilius/mgo/bson"
)
func ModifyIndexTTL(db mgo.Database, collection string, index mgo.Index) error {
keyInfo, err := mgo.ParseIndexKey(index.Key)
if err != nil {
return err
}
expireAfterSeconds := int(index.ExpireAfter / time.Second)
fmt.Printf(
"Updating TTL on collection %s to expireAfterSeconds=%d\n",
collection,
expireAfterSeconds,
)
err = db.Run(bson.D{
{"collMod", collection},
{"index", bson.M{
"keyPattern": keyInfo.Key,
"expireAfterSeconds": expireAfterSeconds,
}},
}, nil)
if err != nil {
return err
}
return nil
}
func EnsureIndexWithTTL(db mgo.Database, collection string, index mgo.Index) error {
err := db.C(collection).EnsureIndex(index)
if err != nil {
// if expireAfterSeconds is changed, we need to drop and re-create the index
// unless we use `collMod` added in 2.3.2
if strings.Contains(err.Error(), "already exists with different options") {
return ModifyIndexTTL(db, collection, index)
}
return err
}
return nil
}
|
package com.splicemachine.si.impl;
import splice.com.google.common.base.Function;
import com.splicemachine.si.api.txn.TransactionStatus;
/**
* Provides hooks for tests to provide callbacks. Mainly used to provide thread coordination in tests. It allows tests
* to "trace" the internals of the SI execution.
*/
public class Tracer {
private static transient Function<byte[],byte[]> fRowRollForward = null;
private static transient Function<Long, Object> <API key> = null;
private static transient Function<Object[], Object> fStatus = null;
private static transient Runnable fCompact = null;
private static transient Function<Long, Object> fCommitting = null;
private static transient Function<Long, Object> fWaiting = null;
private static transient Function<Object[], Object> fRegion = null;
private static transient Function<Object, String> bestAccess = null;
public static Integer <API key> = null;
public static void <API key>(Function<byte[],byte[]> f) {
Tracer.fRowRollForward = f;
}
public static boolean <API key>() {
return Tracer.fRowRollForward != null;
}
public static void <API key>(Function<Long, Object> f) {
Tracer.<API key> = f;
}
public static boolean <API key>() {
return Tracer.<API key> != null;
}
public static void registerStatus(Function<Object[], Object> f) {
Tracer.fStatus = f;
}
public static void registerCompact(Runnable f) {
Tracer.fCompact = f;
}
public static void registerCommitting(Function<Long, Object> f) {
Tracer.fCommitting = f;
}
public static void registerBestAccess(Function<Object, String> f) {
Tracer.bestAccess = f;
}
public static void registerWaiting(Function<Long, Object> f) {
Tracer.fWaiting = f;
}
public static void registerRegion(Function<Object[], Object> f) {
Tracer.fRegion = f;
}
public static void traceRowRollForward(byte[] key) {
if (fRowRollForward != null) {
fRowRollForward.apply(key);
}
}
public static void <API key>(long transactionId) {
if (<API key> != null) {
<API key>.apply(transactionId);
}
}
public static void traceStatus(long transactionId, TransactionStatus newStatus, boolean beforeChange) {
if (fStatus != null) {
fStatus.apply(new Object[] {transactionId, newStatus, beforeChange});
}
}
public static void compact() {
if (fCompact != null) {
fCompact.run();
}
}
public static void traceCommitting(long transactionId) {
if (fCommitting != null) {
fCommitting.apply(transactionId);
}
}
public static void traceWaiting(long transactionId) {
if (fWaiting != null) {
fWaiting.apply(transactionId);
}
}
public static void traceRegion(String tableName, Object region) {
if (fRegion != null) {
fRegion.apply(new Object[] {tableName, region});
}
}
public static void traceBestAccess(Object objectParam) {
if (bestAccess != null) {
bestAccess.apply(objectParam);
}
}
}
|
window.<API key> = new Class( {
Implements : [Events, JsTestClass, Options],
Binds : ['onDocumentReady', 'onDocumentError'],
options : {
testMethods : [
{ method : 'initialize_', isAsynchron : false }]
},
constants : {
},
initialize : function( options ) {
this.setOptions( options );
this.webServiceClient;
},
beforeEachTest : function(){
this.webServiceClient = new WebServiceClient({ });
},
afterEachTest : function (){
this.webServiceClient = null;
},
initialize_ : function() {
assertThat( this.webServiceClient, JsHamcrest.Matchers.instanceOf( WebServiceClient ));
}
});
|
package com.sapienter.jbilling.server.user;
import com.sapienter.jbilling.server.user.contact.db.ContactDTO;
import com.sapienter.jbilling.server.user.db.CompanyDAS;
import com.sapienter.jbilling.server.user.db.CompanyDTO;
import com.sapienter.jbilling.server.util.db.CurrencyDAS;
import com.sapienter.jbilling.server.util.db.CurrencyDTO;
import com.sapienter.jbilling.server.util.db.LanguageDAS;
import javax.validation.Valid;
import javax.validation.constraints.Size;
public class CompanyWS implements java.io.Serializable {
private int id;
private Integer currencyId;
private Integer languageId;
@Size(min = 0, max = 100, message = "validation.error.size,0,100")
private String description;
@Valid
private ContactWS contact;
public CompanyWS() {
}
public CompanyWS(int i) {
id = i;
}
public CompanyWS(CompanyDTO companyDto) {
this.id = companyDto.getId();
this.currencyId= companyDto.getCurrencyId();
this.languageId = companyDto.getLanguageId();
this.description = companyDto.getDescription();
ContactDTO contact = new EntityBL(Integer.valueOf(this.id)).getContact();
if (contact != null) {
this.contact = new ContactWS(contact.getId(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getDeleted());
}
}
public CompanyDTO getDTO(){
CompanyDTO dto = new CompanyDAS().find(Integer.valueOf(this.id));
dto.setCurrency(new CurrencyDAS().find(this.currencyId));
dto.setLanguage(new LanguageDAS().find(this.languageId));
dto.setDescription(this.description);
return dto;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getCurrencyId() {
return currencyId;
}
public void setCurrencyId(Integer currencyId) {
this.currencyId = currencyId;
}
public Integer getLanguageId() {
return languageId;
}
public void setLanguageId(Integer languageId) {
this.languageId = languageId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ContactWS getContact() {
return contact;
}
public void setContact(ContactWS contact) {
this.contact = contact;
}
public String toString() {
return "CompanyWS [id=" + id + ", currencyId=" + currencyId
+ ", languageId=" + languageId + ", description=" + description
+ ", contact=" + contact + "]";
}
}
|
.wm_language_place {
display:none;
}
#demo_info .sprite {
display:-moz-inline-box;
display:inline-block;
margin-right:6px;
background-image:url(http://afterlogic.com/img/flags/langs.png);
background-repeat:no-repeat;
padding:1px 6px 1px 28px;
}
#demo_info a.sprite {
color:#555;
text-decoration:none;
-moz-border-radius: 3px;
-<API key>: 3px;
-khtml-border-radius: 3px;
border-radius: 3px;
outline:none;
}
#demo_info a.sprite.active {
background-color:#697787;
color:#fff !important;
}
#demo_info a.sprite:hover {
background-color:#9BB2BF;
color:#333;
}
#demo_info a.sprite.active {
background-color:#697787;
color:#fff !important;
}
#demo_info .title {
margin:0px 0px 10px;
}
.lang_arb {background-position:0px 0px;}
.lang_dan {background-position:0px -20px;}
.lang_dut {background-position:0px -40px;}
.lang_eng {background-position:0px -60px; margin:0px 8px 0px -22px !important;}
.lang_frn {background-position:0px -80px;}
.lang_gmn {background-position:0px -100px;}
.lang_hbw {background-position:0px -120px;}
.lang_hng {background-position:0px -140px;}
.lang_itl {background-position:0px -160px;}
.lang_nrw {background-position:0px -180px;}
.lang_pls {background-position:0px -200px;}
.lang_prt {background-position:0px -220px;}
.lang_rss {background-position:0px -240px;}
.lang_spn {background-position:0px -260px;}
.lang_swd {background-position:0px -280px;}
.lang_trk {background-position:0px -300px;}
.lang_tha {background-position:0px -340px;}
.lang_ukr {background-position:0px -360px;}
.lang_grk {background-position:0px -380px;}
.lang_usa {background-position:0px -323px; width:20px; height:16px; margin:0px 8px 0px -6px !important;padding: 0px !important; vertical-align:middle}
.lang_jap {background-position:0px -400px;}
.wm_mapping_head {
float: right;
margin-top: -14px;
text-align:center;
width: 100px;
position: relative;
}
.wm_mapping_line {
float: right;
margin-top: -20px;
position: relative;
}
.wm_mapping_line select {
width: 100px;
font-size: 10px;
}
.info {
width:380px;
text-align:left;
}
.info div.r2, .info div.r1{
display:block;
height: 1px;
overflow: hidden;
margin:0px 2px;
background-color: #c7cccf;
}
.info div.r1 {
margin:0px 1px;
overflow:hidden;
background-color:#d7dcdf;
border-left:1px solid #c7cccf;
border-right:1px solid #c7cccf;
}
.info div.middle {
padding:10px;
font-family:Verdana,sans-serif;
font-weight:normal;
font-size:11px;
line-height:160%;
background-color: #D7dcdf;
border-left:1px solid #c7cccf;
border-right:1px solid #c7cccf;
color:#464646;
}
.info a, .info a:hover, .info a:link {
color:#4F75C9;
text-decoration:underline;
}
#demo_info a.sprite.active {
background-color:#697787;
color:#fff !important;
}
|
package org.phenotips.<API key>;
import org.phenotips.data.similarity.internal.AbstractVariant;
import org.phenotips.variantstore.shared.GACallInfoFields;
import org.phenotips.variantstore.shared.GAVariantInfoFields;
import org.phenotips.variantstore.shared.VariantUtils;
import java.text.DecimalFormat;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.ga4gh.GACall;
import org.ga4gh.GAVariant;
/**
* A variant from the variant store. Annotated by Exomiser.
*
* @version $Id$
*/
public class VariantStoreVariant extends AbstractVariant
{
private static DecimalFormat df = new DecimalFormat("
/**
* Create a {@link Variant} from a {@link GAVariant} returned by a {@link
* org.phenotips.variantstore.<API key>}.
*
* @param gaVariant a {@link GAVariant}
* @param totIndividuals number of individuals stored in the variant store
*/
public VariantStoreVariant(GAVariant gaVariant, Integer totIndividuals) {
setChrom(gaVariant.getReferenceName());
setPosition((int) (gaVariant.getStart() + 1));
GACall call = gaVariant.getCalls().get(0);
List<Integer> genotype = call.getGenotype();
setGenotype(gaVariant.getReferenceBases(),
StringUtils.join(gaVariant.getAlternateBases(), ','),
StringUtils.join(genotype, '/'));
setEffect(VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE_EFFECT));
String value = VariantUtils.getInfo(call, GACallInfoFields.<API key>);
if (value == null || "null".equals(value)) {
setScore(null);
} else {
setScore(Double.valueOf(value));
}
setAnnotation("geneScore", VariantUtils.getInfo(call, GACallInfoFields.<API key>));
setAnnotation("geneSymbol", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE));
setAnnotation("hgvs", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GENE_HGVS));
value = VariantUtils.getInfo(gaVariant, GAVariantInfoFields.EXAC_AF);
setAnnotation("exacAF", df.format(Double.valueOf(value)));
setAnnotation("gtHet", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GT_HET));
setAnnotation("gtHom", VariantUtils.getInfo(gaVariant, GAVariantInfoFields.GT_HOM));
if (totIndividuals != null) {
value = VariantUtils.getInfo(gaVariant, GAVariantInfoFields.AC_TOT);
Double pcAF = Double.valueOf(value) / (totIndividuals * 2);
setAnnotation("pcAF", df.format(pcAF));
}
}
}
|
package org.sejda.model.exception;
/**
* Exception thrown when a wrong password has been set and it's not possible to open the pdf document (and execute the task)
*
* @author Andrea Vacondio
*
*/
public class <API key> extends TaskIOException {
private static final long serialVersionUID = -<API key>;
/**
* @param message
* @param cause
*/
public <API key>(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
*/
public <API key>(String message) {
super(message);
}
/**
* @param cause
*/
public <API key>(Throwable cause) {
super(cause);
}
}
|
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Model | partner partnerclient plan', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let store = this.owner.lookup('service:store');
let model = store.createRecord('partner/partnerclient-plan', {});
assert.ok(model);
});
});
|
eqauctions-trending
============
Early stages...let's see what becomes of this.
## What is it?
This will be a place to read about trending items
that are sold/located on http://ahungry.com/eqauctions/
for buying/selling on the http://project1999.org
EverQuest classic emulation server.
Don't forget to
shell
git clone git@github.com:ahungry/glyphs.git
first, as it is used extensively throughout this project.
## Used ports
4432 - hunchentoot port
|
package org.bimserver.database.query.literals;
import org.bimserver.database.query.conditions.LiteralCondition;
public class StringLiteral extends LiteralCondition {
private final String value;
public StringLiteral(String value) {
this.value = value;
}
public Object getValue() {
return value;
}
}
|
<?php
/**
* Manager for Plus
*
* !! Most of Plus is handled via Discovery or Wire\Paywall !!
*/
namespace Minds\Core\Plus;
use Minds\Core\Di\Di;
use Minds\Core\Config;
use Minds\Core\Data\ElasticSearch;
use Minds\Core\Data\Cassandra;
use Minds\Core\Wire\Paywall\<API key>;
use Minds\Core\Rewards\Contributions\ContributionValues;
class Manager
{
/** @var Config */
protected $config;
/** @var ElasticSearch\Client */
protected $es;
/** @var Cassandra\Client */
protected $db;
/** @var int */
const <API key> = 30;
/** @var int */
const <API key> = 365;
/** @var int */
const REVENUE_SHARE_PCT = 25;
public function __construct($config = null, $es = null, $db = null)
{
$this->config = $config ?? Di::_()->get('Config');
$this->es = $es ?? Di::_()->get('Database\ElasticSearch');
$this->db = $db ?? Di::_()->get('Database\Cassandra\Cql');
}
/**
* Returns the plus guid
* @return string
*/
public function getPlusGuid(): string
{
return $this->config->get('plus')['handler'];
}
/**
* Returns the plus support tier urn
* @return string
*/
public function <API key>(): string
{
return $this->config->get('plus')['support_tier_urn'];
}
/**
* Returns the subscription price
* @param string $period (month,day)
* @return int (cents)
*/
public function <API key>(string $period): int
{
/** @var string */
$key = '';
switch ($period) {
case 'month':
$key = 'monthly';
break;
case 'year':
$key = 'yearly';
break;
default:
throw new \Exception("Subscription can only be month or year");
}
return $this->config->get('upgrades')['plus'][$key]['usd'] * 100;
}
/**
* Return sum of revenue for the previous subscriptions period (30 days)
* Will return in USD
* @param int $asOfTs
* @return float
*/
public function getActiveRevenue($asOfTs = null): float
{
$revenue = 0;
$from = strtotime(self::<API key> . " days ago", $asOfTs ?? time());
$to = strtotime("+" . self::<API key> . " days", $from);
// Sum the wire takings for the previous 30 days where monthly subscription
$revenue += $this->getRevenue($from, $to, $this-><API key>('month'));
// Sum the wire takings for the previous 30 days where yearly subscription (amortized to month)
$from = strtotime(self::<API key> . " days ago", $asOfTs ?? time());
$to = strtotime("+" . self::<API key> . " days", $from);
$revenue += $this->getRevenue($from, $to, $this-><API key>('year')) / 12;
return round($revenue / 100, 2);
}
/**
* Returns the daily revenue for Plus
* - Assumptions:
* - Subscription is 30 days
* - Amoritize the revenue by dividing the revenue
* for previous 30 days by 30
* - eg: ($300 per month) / 30 = $10 per day
* Will return in USD
* @param int $asOfTime
* @return int
*/
public function getDailyRevenue($asOfTs = null): float
{
return round($this->getActiveRevenue($asOfTs) / self::<API key>, 2);
}
/**
* @var int $from
* @var int $to
* @return int
*/
protected function getRevenue(int $from, int $to, int $amount): int
{
$query = new Cassandra\Prepared\Custom();
// ALLOW FILTERING is used to filter by amount. As subscription volume is small
// and paritioned by receiver_guid, it should not be an issue
$query->query("SELECT SUM(wei) as wei_sum
FROM wire
WHERE receiver_guid=?
AND method='usd'
AND timestamp >= ?
AND timestamp < ?
AND wei=?
ALLOW FILTERING
", [
new \Cassandra\Varint($this->getPlusGuid()),
new \Cassandra\Timestamp($from, 0),
new \Cassandra\Timestamp($to, 0),
new \Cassandra\Varint($amount)
]);
try {
$result = $this->db->request($query);
} catch (\Exception $e) {
error_log(print_r($e, true));
return 0;
}
return (int) $result[0]['wei_sum'];
}
/**
* Return unlocks (deprecated)
* @param int $asOfTs
* @return iterable
*/
public function getUnlocks(int $asOfTs): array
{
return [];
}
/**
* Return the scores of users
* @param int $asOfTs
* @return iterable
*/
public function getScores(int $asOfTs): iterable
{
/** @var array */
$must = [];
$must[] = [
'term' => [
'support_tier_urn' => $this-><API key>(),
],
];
$must[] = [
'range' => [
'@timestamp' => [
'gte' => $asOfTs * 1000,
'lt' => strtotime('midnight tomorrow', $asOfTs) * 1000,
]
]
];
$body = [
'query' => [
'bool' => [
'must' => $must,
],
],
'aggs' => [
'owners' => [
'terms' => [
'field' => 'entity_owner_guid.keyword',
'size' => 5000,
],
'aggs' => [
'actions' => [
'terms' => [
'field' => 'action.keyword',
'size' => 5000,
],
'aggs' => [
'unique_user_actions' => [
'cardinality' => [
'field' => 'user_guid.keyword',
],
]
]
]
]
],
]
];
$query = [
'index' => 'minds-metrics-*',
'body' => $body,
'size' => 0,
];
$prepared = new ElasticSearch\Prepared\Search();
$prepared->query($query);
$response = $this->es->request($prepared);
$total = array_sum(array_map(function ($bucket) {
return $this-><API key>($bucket);
}, $response['aggregations']['owners']['buckets']));
foreach ($response['aggregations']['owners']['buckets'] as $bucket) {
$count = $this-><API key>($bucket);
if (!$count) {
continue;
}
$score = [
'user_guid' => $bucket['key'],
'total' => $total,
'count' => $count,
'sharePct' => $count / $total,
];
yield $score;
}
}
/**
* Returns if a post is Minds+ paywalled or not
* @param <API key> $entity
* @return bool
*/
public function isPlusEntity(<API key> $entity): bool
{
if (!$entity->isPayWall()) {
return false;
}
$threshold = $entity->getWireThreshold();
return $threshold['support_tier']['urn'] === $this-><API key>();
}
/**
* Returns the score of owner bucket interactions
* @param array $bucket
* @return int
*/
private function <API key>(array $bucket): int
{
return array_sum(array_map(function ($bucket) {
return $bucket['unique_user_actions']['value'] * ContributionValues::<API key>($bucket['key']);
}, $bucket['actions']['buckets']));
}
}
|
# -*- coding: utf-8 -*-
"""
Models for Student Identity Verification
This is where we put any models relating to establishing the real-life identity
of a student over a period of time. Right now, the only models are the abstract
`PhotoVerification`, and its one concrete implementation
`<API key>`. The hope is to keep as much of the
photo verification process as generic as possible.
"""
import functools
import json
import logging
import os.path
import uuid
from datetime import timedelta
from email.utils import formatdate
import requests
import six
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.urls import reverse
from django.db import models
from django.dispatch import receiver
from django.utils.functional import cached_property
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy
from model_utils import Choices
from model_utils.models import StatusModel, TimeStampedModel
from opaque_keys.edx.django.models import CourseKeyField
from lms.djangoapps.verify_student.ssencrypt import (
encrypt_and_encode,
<API key>,
random_aes_key,
rsa_encrypt
)
from openedx.core.djangoapps.signals.signals import <API key>
from openedx.core.storage import get_storage
from .utils import <API key>
log = logging.getLogger(__name__)
def generateUUID(): # pylint: disable=invalid-name
""" Utility function; generates UUIDs """
return str(uuid.uuid4())
class <API key>(Exception):
pass
def <API key>(*<API key>):
"""
Helper decorator with arguments to make sure that an object with a `status`
attribute is in one of a list of acceptable status states before a method
is called. You could use it in a class definition like:
@<API key>("submitted", "approved", "denied")
def refund_user(self, user_id):
# Do logic here...
If the object has a status that is not listed when the `refund_user` method
is invoked, it will throw a `<API key>`. This is just to avoid
distracting boilerplate when looking at a Model that needs to go through a
workflow process.
"""
def decorator_func(func):
"""
Decorator function that gets returned
"""
@functools.wraps(func)
def with_status_check(obj, *args, **kwargs):
if obj.status not in <API key>:
exception_msg = (
u"Error calling {} {}: status is '{}', must be one of: {}"
).format(func, obj, obj.status, <API key>)
raise <API key>(exception_msg)
return func(obj, *args, **kwargs)
return with_status_check
return decorator_func
class <API key>(StatusModel):
"""
Each <API key> represents a Student's attempt to establish
their identity through one of several methods that inherit from this Model,
including PhotoVerification and SSOVerification.
.. pii: The User's name is stored in this and sub-models
.. pii_types: name
.. pii_retirement: retained
"""
STATUS = Choices('created', 'ready', 'submitted', 'must_retry', 'approved', 'denied')
user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
# They can change their name later on, so we want to copy the value here so
# we always preserve what it was at the time they requested. We only copy
# this value during the mark_ready() step. Prior to that, you should be
# displaying the user's name from their user.profile.name.
name = models.CharField(blank=True, max_length=255)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
updated_at = models.DateTimeField(auto_now=True, db_index=True)
class Meta(object):
app_label = "verify_student"
abstract = True
ordering = ['-created_at']
@property
def expiration_datetime(self):
"""Datetime that the verification will expire. """
days_good_for = settings.VERIFY_STUDENT["DAYS_GOOD_FOR"]
return self.created_at + timedelta(days=days_good_for)
def <API key>(self):
"""Whether or not the status from this attempt should be displayed to the user."""
raise NotImplementedError
def active_at_datetime(self, deadline):
"""Check whether the verification was active at a particular datetime.
Arguments:
deadline (datetime): The date at which the verification was active
(created before and expiration datetime is after today).
Returns:
bool
"""
return (
self.created_at < deadline and
self.expiration_datetime > now()
)
class ManualVerification(<API key>):
"""
Each ManualVerification represents a user's verification that bypasses the need for
any other verification.
.. pii: The User's name is stored in the parent model
.. pii_types: name
.. pii_retirement: retained
"""
reason = models.CharField(
max_length=255,
blank=True,
help_text=(
'Specifies the reason for manual verification of the user.'
)
)
class Meta(object):
app_label = 'verify_student'
def __unicode__(self):
return '<API key> for {name}, status: {status}'.format(
name=self.name,
status=self.status,
)
def <API key>(self):
"""
Whether or not the status should be displayed to the user.
"""
return False
class SSOVerification(<API key>):
"""
Each SSOVerification represents a Student's attempt to establish their identity
by signing in with SSO. ID verification through SSO bypasses the need for
photo verification.
.. no_pii:
"""
OAUTH2 = 'third_party_auth.models.<API key>'
SAML = 'third_party_auth.models.SAMLProviderConfig'
LTI = 'third_party_auth.models.LTIProviderConfig'
<API key> = (
(OAUTH2, 'OAuth2 Provider'),
(SAML, 'SAML Provider'),
(LTI, 'LTI Provider'),
)
<API key> = models.CharField(
max_length=100,
blank=False,
choices=<API key>,
default=SAML,
help_text=(
'Specifies which type of Identity Provider this verification originated from.'
)
)
<API key> = models.SlugField(
max_length=30, db_index=True, default='default',
help_text=(
'The slug uniquely identifying the Identity Provider this verification originated from.'
))
class Meta(object):
app_label = "verify_student"
def __unicode__(self):
return 'SSOIDVerification for {name}, status: {status}'.format(
name=self.name,
status=self.status,
)
def <API key>(self):
"""Whether or not the status from this attempt should be displayed to the user."""
return False
class PhotoVerification(<API key>):
"""
Each PhotoVerification represents a Student's attempt to establish
their identity by uploading a photo of themselves and a picture ID. An
attempt actually has a number of fields that need to be filled out at
different steps of the approval process. While it's useful as a Django Model
for the querying facilities, **you should only edit a `PhotoVerification`
object through the methods provided**. Initialize them with a user:
attempt = PhotoVerification(user=user)
We track this attempt through various states:
`created`
Initial creation and state we're in after uploading the images.
`ready`
The user has uploaded their images and checked that they can read the
images. There's a separate state here because it may be the case that we
don't actually submit this attempt for review until payment is made.
`submitted`
Submitted for review. The review may be done by a staff member or an
external service. The user cannot make changes once in this state.
`must_retry`
We submitted this, but there was an error on submission (i.e. we did not
get a 200 when we POSTed to Software Secure)
`approved`
An admin or an external service has confirmed that the user's photo and
photo ID match up, and that the photo ID's name matches the user's.
`denied`
The request has been denied. See `error_msg` for details on why. An
admin might later override this and change to `approved`, but the
student cannot re-open this attempt -- they have to create another
attempt and submit it instead.
Because this Model inherits from <API key>, which inherits
from StatusModel, we can also do things like:
attempt.status == PhotoVerification.STATUS.created
attempt.status == "created"
pending_requests = PhotoVerification.submitted.all()
.. pii: The User's name is stored in the parent model, this one stores links to face and photo ID images
.. pii_types: name, image
.. pii_retirement: retained
"""
# See class docstring for description of status states
# Where we place the uploaded image files (e.g. S3 URLs)
face_image_url = models.URLField(blank=True, max_length=255)
photo_id_image_url = models.URLField(blank=True, max_length=255)
# Randomly generated UUID so that external services can post back the
# results of checking a user's photo submission without use exposing actual
# user IDs or something too easily guessable.
receipt_id = models.CharField(
db_index=True,
default=generateUUID,
max_length=255,
)
# Indicates whether or not a user wants to see the verification status
# displayed on their dash. Right now, only relevant for allowing students
# to "dismiss" a failed midcourse reverification message
# TODO: This field is deprecated.
display = models.BooleanField(db_index=True, default=True)
submitted_at = models.DateTimeField(null=True, db_index=True)
# If the review was done by an internal staff member, mark who it was.
reviewing_user = models.ForeignKey(
User,
db_index=True,
default=None,
null=True,
related_name="<API key>",
on_delete=models.CASCADE,
)
# Mark the name of the service used to evaluate this attempt (e.g
# Software Secure).
reviewing_service = models.CharField(blank=True, max_length=255)
# If status is "denied", this should contain text explaining why.
error_msg = models.TextField(blank=True)
# Non-required field. External services can add any arbitrary codes as time
# goes on. We don't try to define an exhuastive list -- this is just
# capturing it so that we can later query for the common problems.
error_code = models.CharField(blank=True, max_length=50)
class Meta(object):
app_label = "verify_student"
abstract = True
ordering = ['-created_at']
def parsed_error_msg(self):
"""
Sometimes, the error message we've received needs to be parsed into
something more human readable
The default behavior is to return the current error message as is.
"""
return self.error_msg
@<API key>("created")
def upload_face_image(self, img):
raise NotImplementedError
@<API key>("created")
def <API key>(self, img):
raise NotImplementedError
@<API key>("created")
def mark_ready(self):
# At any point prior to this, they can change their names via their
# student dashboard. But at this point, we lock the value into the
# attempt.
self.name = self.user.profile.name
self.status = "ready"
self.save()
@<API key>("must_retry", "submitted", "approved", "denied")
def approve(self, user_id=None, service=""):
# If someone approves an outdated version of this, the first one wins
if self.status == "approved":
return
log.info(u"Verification for user '{user_id}' approved by '{reviewer}'.".format(
user_id=self.user, reviewer=user_id
))
self.error_msg = "" # reset, in case this attempt was denied before
self.error_code = "" # reset, in case this attempt was denied before
self.reviewing_user = user_id
self.reviewing_service = service
self.status = "approved"
self.save()
# Emit signal to find and generate eligible certificates
<API key>.send_robust(
sender=PhotoVerification,
user=self.user
)
@<API key>("must_retry", "submitted", "approved", "denied")
def deny(self,
error_msg,
error_code="",
reviewing_user=None,
reviewing_service=""):
log.info(u"Verification for user '{user_id}' denied by '{reviewer}'.".format(
user_id=self.user, reviewer=reviewing_user
))
self.error_msg = error_msg
self.error_code = error_code
self.reviewing_user = reviewing_user
self.reviewing_service = reviewing_service
self.status = "denied"
self.save()
@<API key>("must_retry", "submitted", "approved", "denied")
def system_error(self,
error_msg,
error_code="",
reviewing_user=None,
reviewing_service=""):
"""
Mark that this attempt could not be completed because of a system error.
Status should be moved to `must_retry`. For example, if Software Secure
reported to us that they couldn't process our submission because they
couldn't decrypt the image we sent.
"""
if self.status in ["approved", "denied"]:
return # If we were already approved or denied, just leave it.
self.error_msg = error_msg
self.error_code = error_code
self.reviewing_user = reviewing_user
self.reviewing_service = reviewing_service
self.status = "must_retry"
self.save()
@classmethod
def retire_user(cls, user_id):
"""
Retire user as part of GDPR Phase I
Returns 'True' if records found
:param user_id: int
:return: bool
"""
try:
user_obj = User.objects.get(id=user_id)
except User.DoesNotExist:
return False
photo_objects = cls.objects.filter(
user=user_obj
).update(
name='',
face_image_url='',
photo_id_image_url='',
photo_id_key=''
)
return photo_objects > 0
class <API key>(PhotoVerification):
# This is a base64.urlsafe_encode(rsa_encrypt(photo_id_aes_key), ss_pub_key)
# So first we generate a random AES-256 key to encrypt our photo ID with.
# Then we RSA encrypt it with Software Secure's public key. Then we base64
# encode that. The result is saved here. Actual expected length is 344.
photo_id_key = models.TextField(max_length=1024)
IMAGE_LINK_DURATION = 5 * 60 * 60 * 24 # 5 days in seconds
copy_id_photo_from = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE)
# Fields for functionality of sending email when verification expires
# to notify for expired verification is already sent.
expiry_date = models.DateTimeField(null=True, blank=True, db_index=True)
expiry_email_date = models.DateTimeField(null=True, blank=True, db_index=True)
@<API key>("must_retry", "submitted", "approved", "denied")
def approve(self, user_id=None, service=""):
"""
Approve the verification attempt for user
Valid attempt statuses when calling this method:
`submitted`, `approved`, `denied`
After method completes:
status is set to `approved`
expiry_date is set to one year from now
"""
self.expiry_date = now() + timedelta(
days=settings.VERIFY_STUDENT["DAYS_GOOD_FOR"]
)
super(<API key>, self).approve(user_id, service)
@classmethod
def <API key>(cls, user, <API key>=None):
"""Get initial verification for a user with the 'photo_id_key'.
Arguments:
user(User): user object
<API key>(datetime): override expiration date for initial verification
Return:
<API key> (object) or None
"""
init_verification = cls.objects.filter(
user=user,
status__in=["submitted", "approved"],
created_at__gte=(
<API key> or <API key>()
)
).exclude(photo_id_key='')
return init_verification.latest('created_at') if init_verification.exists() else None
@<API key>("created")
def upload_face_image(self, img_data):
"""
Upload an image of the user's face. `img_data` should be a raw
bytestream of a PNG image. This method will take the data, encrypt it
using our FACE_IMAGE_AES_KEY, encode it with base64 and save it to the
storage backend.
Yes, encoding it to base64 adds compute and disk usage without much real
benefit, but that's what the other end of this API is expecting to get.
"""
# Skip this whole thing if we're running acceptance tests or if we're
# developing and aren't interested in working on student identity
# verification functionality. If you do want to work on it, you have to
# explicitly enable these in your private settings.
if settings.FEATURES.get('<API key>'):
return
aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"]
aes_key = aes_key_str.decode("hex")
path = self._get_path("face")
buff = ContentFile(encrypt_and_encode(img_data, aes_key))
self._storage.save(path, buff)
@<API key>("created")
def <API key>(self, img_data):
"""
Upload an the user's photo ID image. `img_data` should be a raw
bytestream of a PNG image. This method will take the data, encrypt it
using a randomly generated AES key, encode it with base64 and save it
to the storage backend. The random key is also encrypted using Software
Secure's public RSA key and stored in our `photo_id_key` field.
Yes, encoding it to base64 adds compute and disk usage without much real
benefit, but that's what the other end of this API is expecting to get.
"""
# Skip this whole thing if we're running acceptance tests or if we're
# developing and aren't interested in working on student identity
# verification functionality. If you do want to work on it, you have to
# explicitly enable these in your private settings.
if settings.FEATURES.get('<API key>'):
# fake photo id key is set only for initial verification
self.photo_id_key = 'fake-photo-id-key'
self.save()
return
aes_key = random_aes_key()
rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"]
<API key> = rsa_encrypt(aes_key, rsa_key_str)
# Save this to the storage backend
path = self._get_path("photo_id")
buff = ContentFile(encrypt_and_encode(img_data, aes_key))
self._storage.save(path, buff)
# Update our record fields
self.photo_id_key = <API key>.encode('base64')
self.save()
@<API key>("must_retry", "ready", "submitted")
def submit(self, copy_id_photo_from=None):
"""
Submit our verification attempt to Software Secure for validation. This
will set our status to "submitted" if the post is successful, and
"must_retry" if the post fails.
Keyword Arguments:
copy_id_photo_from (<API key>): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with <API key> ID photos.
"""
try:
response = self.send_request(copy_id_photo_from=copy_id_photo_from)
if response.ok:
self.submitted_at = now()
self.status = "submitted"
self.save()
else:
self.status = "must_retry"
self.error_msg = response.text
self.save()
except Exception: # pylint: disable=broad-except
log.exception(
u'Software Secure submission failed for user %s, setting status to must_retry',
self.user.username
)
self.status = "must_retry"
self.save()
def parsed_error_msg(self):
"""
Parse the error messages we receive from SoftwareSecure
Error messages are written in the form:
`[{"photoIdReasons": ["Not provided"]}]`
Returns:
str[]: List of error messages.
"""
parsed_errors = []
error_map = {
'EdX name not provided': 'name_mismatch',
'Name mismatch': 'name_mismatch',
'Photo/ID Photo mismatch': 'photos_mismatched',
'ID name not provided': '<API key>',
'Invalid Id': 'id_invalid',
'No text': 'id_invalid',
'Not provided': 'id_image_missing',
'Photo hidden/No photo': 'id_image_not_clear',
'Text not clear': 'id_image_not_clear',
'Face out of view': '<API key>',
'Image not clear': '<API key>',
'Photo not provided': 'user_image_missing',
}
try:
messages = set()
message_groups = json.loads(self.error_msg)
for message_group in message_groups:
messages = messages.union(set(*six.itervalues(message_group)))
for message in messages:
parsed_error = error_map.get(message)
if parsed_error:
parsed_errors.append(parsed_error)
else:
log.debug(u'Ignoring photo verification error message: %s', message)
except Exception: # pylint: disable=broad-except
log.exception(u'Failed to parse error message for <API key> %d', self.pk)
return parsed_errors
def image_url(self, name, override_receipt_id=None):
"""
We dynamically generate this, since we want it the expiration clock to
start when the message is created, not when the record is created.
Arguments:
name (str): Name of the image (e.g. "photo_id" or "face")
Keyword Arguments:
override_receipt_id (str): If provided, use this receipt ID instead
of the ID for this attempt. This is useful for reverification
where we need to construct a URL to a <API key>
photo ID image.
Returns:
string: The expiring URL for the image.
"""
path = self._get_path(name, override_receipt_id=override_receipt_id)
return self._storage.url(path)
@cached_property
def _storage(self):
"""
Return the configured django storage backend.
"""
config = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]
# Default to the S3 backend for backward compatibility
storage_class = config.get("STORAGE_CLASS", "storages.backends.s3boto.S3BotoStorage")
storage_kwargs = config.get("STORAGE_KWARGS", {})
# Map old settings to the parameters expected by the storage backend
if "AWS_ACCESS_KEY" in config:
storage_kwargs["access_key"] = config["AWS_ACCESS_KEY"]
if "AWS_SECRET_KEY" in config:
storage_kwargs["secret_key"] = config["AWS_SECRET_KEY"]
if "S3_BUCKET" in config:
storage_kwargs["bucket"] = config["S3_BUCKET"]
storage_kwargs["querystring_expire"] = self.IMAGE_LINK_DURATION
return get_storage(storage_class, **storage_kwargs)
def _get_path(self, prefix, override_receipt_id=None):
"""
Returns the path to a resource with this instance's `receipt_id`.
If `override_receipt_id` is given, the path to that resource will be
retrieved instead. This allows us to retrieve images submitted in
previous attempts (used for reverification, where we send a new face
photo with the same photo ID from a previous attempt).
"""
receipt_id = self.receipt_id if override_receipt_id is None else override_receipt_id
return os.path.join(prefix, receipt_id)
def <API key>(self):
"""
Software Secure needs to have both UserPhoto and PhotoID decrypted in
the same manner. So even though this is going to be the same for every
request, we're also using RSA encryption to encrypt the AES key for
faces.
"""
face_aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"]
face_aes_key = face_aes_key_str.decode("hex")
rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"]
<API key> = rsa_encrypt(face_aes_key, rsa_key_str)
return <API key>.encode("base64")
def create_request(self, copy_id_photo_from=None):
"""
Construct the HTTP request to the photo verification service.
Keyword Arguments:
copy_id_photo_from (<API key>): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with <API key> ID photos.
Returns:
tuple of (header, body), where both `header` and `body` are dictionaries.
"""
access_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]
secret_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"]
scheme = "https" if settings.HTTPS == "on" else "http"
callback_url = "{}://{}{}".format(
scheme, settings.SITE_NAME, reverse('<API key>')
)
# If we're copying the photo ID image from a previous verification attempt,
# then we need to send the old image data with the correct image key.
photo_id_url = (
self.image_url("photo_id")
if copy_id_photo_from is None
else self.image_url("photo_id", override_receipt_id=copy_id_photo_from.receipt_id)
)
photo_id_key = (
self.photo_id_key
if copy_id_photo_from is None else
copy_id_photo_from.photo_id_key
)
body = {
"EdX-ID": str(self.receipt_id),
"ExpectedName": self.name,
"PhotoID": photo_id_url,
"PhotoIDKey": photo_id_key,
"SendResponseTo": callback_url,
"UserPhoto": self.image_url("face"),
"UserPhotoKey": self.<API key>(),
}
headers = {
"Content-Type": "application/json",
"Date": formatdate(timeval=None, localtime=False, usegmt=True)
}
_message, _sig, authorization = <API key>(
"POST", headers, body, access_key, secret_key
)
headers['Authorization'] = authorization
return headers, body
def request_message_txt(self):
"""
This is the body of the request we send across. This is never actually
used in the code, but exists for debugging purposes -- you can call
`print attempt.request_message_txt()` on the console and get a readable
rendering of the request that would be sent across, without actually
sending anything.
"""
headers, body = self.create_request()
header_txt = "\n".join(
u"{}: {}".format(h, v) for h, v in sorted(headers.items())
)
body_txt = json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8')
return header_txt + "\n\n" + body_txt
def send_request(self, copy_id_photo_from=None):
"""
Assembles a submission to Software Secure and sends it via HTTPS.
Keyword Arguments:
copy_id_photo_from (<API key>): If provided, re-send the ID photo
data from this attempt. This is used for reverification, in which new face photos
are sent with <API key> ID photos.
Returns:
request.Response
"""
# If <API key> is True, we want to
# skip posting anything to Software Secure. We actually don't even
# create the message because that would require encryption and message
# signing that rely on settings.VERIFY_STUDENT values that aren't set
# in dev. So we just pretend like we successfully posted
if settings.FEATURES.get('<API key>'):
fake_response = requests.Response()
fake_response.status_code = 200
return fake_response
headers, body = self.create_request(copy_id_photo_from=copy_id_photo_from)
response = requests.post(
settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_URL"],
headers=headers,
data=json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8'),
verify=False
)
log.info(u"Sent request to Software Secure for receipt ID %s.", self.receipt_id)
if copy_id_photo_from is not None:
log.info(
(
u"Software Secure attempt with receipt ID %s used the same photo ID "
u"data as the receipt with ID %s"
),
self.receipt_id, copy_id_photo_from.receipt_id
)
log.debug("Headers:\n{}\n\n".format(headers))
log.debug("Body:\n{}\n\n".format(body))
log.debug(u"Return code: {}".format(response.status_code))
log.debug(u"Return message:\n\n{}\n\n".format(response.text))
return response
def <API key>(self):
"""Whether or not the status from this attempt should be displayed to the user."""
return True
class <API key>(TimeStampedModel):
"""
Represent a verification deadline for a particular course.
The verification deadline is the datetime after which
users are no longer allowed to submit photos for initial verification
in a course.
Note that this is NOT the same as the "upgrade" deadline, after
which a user is no longer allowed to upgrade to a verified enrollment.
If no verification deadline record exists for a course,
then that course does not have a deadline. This means that users
can submit photos at any time.
.. no_pii:
"""
class Meta(object):
app_label = "verify_student"
course_key = CourseKeyField(
max_length=255,
db_index=True,
unique=True,
help_text=ugettext_lazy(u"The course for which this deadline applies"),
)
deadline = models.DateTimeField(
help_text=ugettext_lazy(
u"The datetime after which users are no longer allowed "
"to submit photos for verification."
)
)
# The system prefers to set this automatically based on default settings. But
# if the field is set manually we want a way to indicate that so we don't
# overwrite the manual setting of the field.
<API key> = models.BooleanField(default=False)
<API key> = "verify_student.<API key>"
@classmethod
def set_deadline(cls, course_key, deadline, is_explicit=False):
"""
Configure the verification deadline for a course.
If `deadline` is `None`, then the course will have no verification
deadline. In this case, users will be able to verify for the course
at any time.
Arguments:
course_key (CourseKey): Identifier for the course.
deadline (datetime or None): The verification deadline.
"""
if deadline is None:
<API key>.objects.filter(course_key=course_key).delete()
else:
record, created = <API key>.objects.get_or_create(
course_key=course_key,
defaults={"deadline": deadline, "<API key>": is_explicit}
)
if not created:
record.deadline = deadline
record.<API key> = is_explicit
record.save()
@classmethod
def <API key>(cls, course_keys):
"""
Retrieve verification deadlines for particular courses.
Arguments:
course_keys (list): List of `CourseKey`s.
Returns:
dict: Map of course keys to datetimes (verification deadlines)
"""
all_deadlines = cache.get(cls.<API key>)
if all_deadlines is None:
all_deadlines = {
deadline.course_key: deadline.deadline
for deadline in <API key>.objects.all()
}
cache.set(cls.<API key>, all_deadlines)
return {
course_key: all_deadlines[course_key]
for course_key in course_keys
if course_key in all_deadlines
}
@classmethod
def deadline_for_course(cls, course_key):
"""
Retrieve the verification deadline for a particular course.
Arguments:
course_key (CourseKey): The identifier for the course.
Returns:
datetime or None
"""
try:
deadline = cls.objects.get(course_key=course_key)
return deadline.deadline
except cls.DoesNotExist:
return None
@receiver(models.signals.post_save, sender=<API key>)
@receiver(models.signals.post_delete, sender=<API key>)
def <API key>(sender, **kwargs): # pylint: disable=unused-argument
"""Invalidate the cached verification deadline information. """
cache.delete(<API key>.<API key>)
|
# -*- coding: utf-8 -*-
# OpenERP, Open Source Management Solution
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from datetime import datetime
from dateutil.relativedelta import relativedelta
import time
from operator import itemgetter
from itertools import groupby
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
from openerp import netsvc
from openerp import tools
from openerp.tools import float_compare, <API key>
import openerp.addons.decimal_precision as dp
import logging
_logger = logging.getLogger(__name__)
# Incoterms
class stock_incoterms(osv.osv):
_name = "stock.incoterms"
_description = "Incoterms"
_columns = {
'name': fields.char('Name', size=64, required=True, help="Incoterms are series of sales terms.They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices."),
'code': fields.char('Code', size=3, required=True, help="Code for Incoterms"),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide an INCOTERM without deleting it."),
}
_defaults = {
'active': True,
}
stock_incoterms()
class stock_journal(osv.osv):
_name = "stock.journal"
_description = "Stock Journal"
_columns = {
'name': fields.char('Stock Journal', size=32, required=True),
'user_id': fields.many2one('res.users', 'Responsible'),
}
_defaults = {
'user_id': lambda s, c, u, ctx: u
}
stock_journal()
# Stock Location
class stock_location(osv.osv):
_name = "stock.location"
_description = "Location"
_parent_name = "location_id"
_parent_store = True
_parent_order = 'posz,name'
_order = 'parent_left'
# TODO: implement name_search() in a way that matches the results of name_get!
def name_get(self, cr, uid, ids, context=None):
# always return the full hierarchical name
res = self._complete_name(cr, uid, ids, 'complete_name', None, context=context)
return res.items()
def _complete_name(self, cr, uid, ids, name, args, context=None):
""" Forms complete name of location from parent location to child location.
@return: Dictionary of values
"""
res = {}
for m in self.browse(cr, uid, ids, context=context):
names = [m.name]
parent = m.location_id
while parent:
names.append(parent.name)
parent = parent.location_id
res[m.id] = ' / '.join(reversed(names))
return res
def _get_sublocations(self, cr, uid, ids, context=None):
""" return all sublocations of the given stock locations (included) """
return self.search(cr, uid, [('id', 'child_of', ids)], context=context)
def _product_value(self, cr, uid, ids, field_names, arg, context=None):
"""Computes stock value (real and virtual) for a product, as well as stock qty (real and virtual).
@param field_names: Name of field
@return: Dictionary of values
"""
prod_id = context and context.get('product_id', False)
if not prod_id:
return dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
product_product_obj = self.pool.get('product.product')
cr.execute('select distinct product_id, location_id from stock_move where location_id in %s', (tuple(ids), ))
dict1 = cr.dictfetchall()
cr.execute('select distinct product_id, location_dest_id as location_id from stock_move where location_dest_id in %s', (tuple(ids), ))
dict2 = cr.dictfetchall()
<API key> = sorted(dict1+dict2, key=itemgetter('location_id'))
<API key> = dict((k, [v['product_id'] for v in itr]) for k, itr in groupby(<API key>, itemgetter('location_id')))
result = dict([(i, {}.fromkeys(field_names, 0.0)) for i in ids])
result.update(dict([(i, {}.fromkeys(field_names, 0.0)) for i in list(set([aaa['location_id'] for aaa in <API key>]))]))
currency_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.currency_id.id
currency_obj = self.pool.get('res.currency')
currency = currency_obj.browse(cr, uid, currency_id, context=context)
for loc_id, product_ids in <API key>.items():
if prod_id:
product_ids = [prod_id]
c = (context or {}).copy()
c['location'] = loc_id
for prod in product_product_obj.browse(cr, uid, product_ids, context=c):
for f in field_names:
if f == 'stock_real':
if loc_id not in result:
result[loc_id] = {}
result[loc_id][f] += prod.qty_available
elif f == 'stock_virtual':
result[loc_id][f] += prod.virtual_available
elif f == 'stock_real_value':
amount = prod.qty_available * prod.standard_price
amount = currency_obj.round(cr, uid, currency, amount)
result[loc_id][f] += amount
elif f == 'stock_virtual_value':
amount = prod.virtual_available * prod.standard_price
amount = currency_obj.round(cr, uid, currency, amount)
result[loc_id][f] += amount
return result
_columns = {
'name': fields.char('Location Name', size=64, required=True, translate=True),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide a location without deleting it."),
'usage': fields.selection([('supplier', 'Supplier Location'), ('view', 'View'), ('internal', 'Internal Location'), ('customer', 'Customer Location'), ('inventory', 'Inventory'), ('procurement', 'Procurement'), ('production', 'Production'), ('transit', 'Transit Location for Inter-Companies Transfers')], 'Location Type', required=True,
help="""* Supplier Location: Virtual location representing the source location for products coming from your suppliers
\n* View: Virtual location used to create a hierarchical structures for your warehouse, aggregating its child locations ; can't directly contain products
\n* Internal Location: Physical locations inside your own warehouses,
\n* Customer Location: Virtual location representing the destination location for products sent to your customers
\n* Inventory: Virtual location serving as counterpart for inventory operations used to correct stock levels (Physical inventories)
\n* Procurement: Virtual location serving as temporary counterpart for procurement operations when the source (supplier or production) is not known yet. This location should be empty when the procurement scheduler has finished running.
\n* Production: Virtual counterpart location for production operations: this location consumes the raw material and produces finished products
""", select = True),
# temporarily removed, as it's unused: 'allocation_method': fields.selection([('fifo', 'FIFO'), ('lifo', 'LIFO'), ('nearest', 'Nearest')], 'Allocation Method', required=True),
'complete_name': fields.function(_complete_name, type='char', size=256, string="Location Name",
store={'stock.location': (_get_sublocations, ['name', 'location_id'], 10)}),
'stock_real': fields.function(_product_value, type='float', string='Real Stock', multi="stock"),
'stock_virtual': fields.function(_product_value, type='float', string='Virtual Stock', multi="stock"),
'location_id': fields.many2one('stock.location', 'Parent Location', select=True, ondelete='cascade'),
'child_ids': fields.one2many('stock.location', 'location_id', 'Contains'),
'chained_journal_id': fields.many2one('stock.journal', 'Chaining Journal',help="Inventory Journal in which the chained move will be written, if the Chaining Type is not Transparent (no journal is used if left empty)"),
'chained_location_id': fields.many2one('stock.location', 'Chained Location If Fixed'),
'<API key>': fields.selection([('none', 'None'), ('customer', 'Customer'), ('fixed', 'Fixed Location')],
'Chained Location Type', required=True,
help="Determines whether this location is chained to another location, i.e. any incoming product in this location \n" \
"should next go to the chained location. The chained location is determined according to the type :"\
"\n* None: No chaining at all"\
"\n* Customer: The chained location will be taken from the Customer Location field on the Partner form of the Partner that is specified in the Picking list of the incoming products." \
"\n* Fixed Location: The chained location is taken from the next field: Chained Location if Fixed." \
),
'<API key>': fields.selection(
[('auto', 'Automatic Move'), ('manual', 'Manual Operation'), ('transparent', 'Automatic No Step Added')],
'Chaining Type',
required=True,
help="This is used only if you select a chained location type.\n" \
"The 'Automatic Move' value will create a stock move after the current one that will be "\
"validated automatically. With 'Manual Operation', the stock move has to be validated "\
"by a worker. With 'Automatic No Step Added', the location is replaced in the original move."
),
'<API key>': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', help="Shipping Type of the Picking List that will contain the chained move (leave empty to automatically detect the type based on the source and destination locations)."),
'chained_company_id': fields.many2one('res.company', 'Chained Company', help='The company the Picking List containing the chained move will belong to (leave empty to use the default company determination rules'),
'chained_delay': fields.integer('Chaining Lead Time',help="Delay between original move and chained move in days"),
'partner_id': fields.many2one('res.partner', 'Location Address',help="Address of customer or supplier."),
'icon': fields.selection(tools.icons, 'Icon', size=64,help="Icon show in hierarchical tree view"),
'comment': fields.text('Additional Information'),
'posx': fields.integer('Corridor (X)',help="Optional localization details, for information purpose only"),
'posy': fields.integer('Shelves (Y)', help="Optional localization details, for information purpose only"),
'posz': fields.integer('Height (Z)', help="Optional localization details, for information purpose only"),
'parent_left': fields.integer('Left Parent', select=1),
'parent_right': fields.integer('Right Parent', select=1),
'stock_real_value': fields.function(_product_value, type='float', string='Real Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
'stock_virtual_value': fields.function(_product_value, type='float', string='Virtual Stock Value', multi="stock", digits_compute=dp.get_precision('Account')),
'company_id': fields.many2one('res.company', 'Company', select=1, help='Let this field empty if this location is shared between all companies'),
'scrap_location': fields.boolean('Scrap Location', help='Check this box to allow using this location to put scrapped/damaged goods.'),
'<API key>': fields.many2one('account.account', 'Stock Valuation Account (Incoming)', domain = [('type','=','other')],
help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
"this account will be used to hold the value of products being moved from an internal location "
"into this location, instead of the generic Stock Output Account set on the product. "
"This has no effect for internal locations."),
'<API key>': fields.many2one('account.account', 'Stock Valuation Account (Outgoing)', domain = [('type','=','other')],
help="Used for real-time inventory valuation. When set on a virtual location (non internal type), "
"this account will be used to hold the value of products being moved out of this location "
"and into an internal location, instead of the generic Stock Output Account set on the product. "
"This has no effect for internal locations."),
}
_defaults = {
'active': True,
'usage': 'internal',
'<API key>': 'none',
'<API key>': 'manual',
'company_id': lambda self, cr, uid, c: self.pool.get('res.company').<API key>(cr, uid, 'stock.location', context=c),
'posx': 0,
'posy': 0,
'posz': 0,
'icon': False,
'scrap_location': False,
}
def <API key>(self, cr, uid, location, partner=None, product=None, context=None):
""" Finds chained location
@param location: Location id
@param partner: Partner id
@param product: Product id
@return: List of values
"""
result = None
if location.<API key> == 'customer':
if partner:
result = partner.<API key>
else:
loc_id = self.pool['res.partner'].default_get(cr, uid, ['<API key>'], context=context)['<API key>']
result = self.pool['stock.location'].browse(cr, uid, loc_id, context=context)
elif location.<API key> == 'fixed':
result = location.chained_location_id
if result:
return result, location.<API key>, location.chained_delay, location.chained_journal_id and location.chained_journal_id.id or False, location.chained_company_id and location.chained_company_id.id or False, location.<API key>, False
return result
def picking_type_get(self, cr, uid, from_location, to_location, context=None):
""" Gets type of picking.
@param from_location: Source location
@param to_location: Destination location
@return: Location type
"""
result = 'internal'
if (from_location.usage=='internal') and (to_location and to_location.usage in ('customer', 'supplier')):
result = 'out'
elif (from_location.usage in ('supplier', 'customer')) and (to_location.usage == 'internal'):
result = 'in'
return result
def <API key>(self, cr, uid, ids, product_ids=False, context=None):
return self._product_get_report(cr, uid, ids, product_ids, context, recursive=True)
def _product_get_report(self, cr, uid, ids, product_ids=False,
context=None, recursive=False):
""" Finds the product quantity and price for particular location.
@param product_ids: Ids of product
@param recursive: True or False
@return: Dictionary of values
"""
if context is None:
context = {}
product_obj = self.pool.get('product.product')
# Take the user company and pricetype
context['currency_id'] = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id.id
# To be able to offer recursive or non-recursive reports we need to prevent recursive quantities by default
context['compute_child'] = False
if not product_ids:
product_ids = product_obj.search(cr, uid, [], context={'active_test': False})
products = product_obj.browse(cr, uid, product_ids, context=context)
products_by_uom = {}
products_by_id = {}
for product in products:
products_by_uom.setdefault(product.uom_id.id, [])
products_by_uom[product.uom_id.id].append(product)
products_by_id.setdefault(product.id, [])
products_by_id[product.id] = product
result = {}
result['product'] = []
for id in ids:
quantity_total = 0.0
total_price = 0.0
for uom_id in products_by_uom.keys():
fnc = self._product_get
if recursive:
fnc = self._product_all_get
ctx = context.copy()
ctx['uom'] = uom_id
qty = fnc(cr, uid, id, [x.id for x in products_by_uom[uom_id]],
context=ctx)
for product_id in qty.keys():
if not qty[product_id]:
continue
product = products_by_id[product_id]
quantity_total += qty[product_id]
# Compute based on pricetype
# Choose the right filed standard_price to read
amount_unit = product.price_get('standard_price', context=context)[product.id]
price = qty[product_id] * amount_unit
total_price += price
result['product'].append({
'price': amount_unit,
'prod_name': product.name,
'code': product.default_code, # used by lot_overview_all report!
'variants': product.variants or '',
'uom': product.uom_id.name,
'prod_qty': qty[product_id],
'price_value': price,
})
result['total'] = quantity_total
result['total_price'] = total_price
return result
def <API key>(self, cr, uid, ids, product_ids=False, context=None,
states=['done'], what=('in', 'out')):
"""
@param product_ids: Ids of product
@param states: List of states
@param what: Tuple of
@return:
"""
product_obj = self.pool.get('product.product')
if context is None:
context = {}
context.update({
'states': states,
'what': what,
'location': ids
})
return product_obj.<API key>(cr, uid, product_ids, context=context)
def _product_get(self, cr, uid, id, product_ids=False, context=None, states=None):
"""
@param product_ids:
@param states:
@return:
"""
if states is None:
states = ['done']
ids = id and [id] or []
return self.<API key>(cr, uid, ids, product_ids, context=context, states=states)
def _product_all_get(self, cr, uid, id, product_ids=False, context=None, states=None):
if states is None:
states = ['done']
# build the list of ids of children of the location given by id
ids = id and [id] or []
location_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
return self.<API key>(cr, uid, location_ids, product_ids, context, states)
def <API key>(self, cr, uid, id, product_ids=False, context=None, states=None):
if states is None:
states = ['done']
return self._product_all_get(cr, uid, id, product_ids, context, ['confirmed', 'waiting', 'assigned', 'done'])
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None, lock=False):
"""
Attempt to find a quantity ``product_qty`` (in the product's default uom or the uom passed in ``context``) of product ``product_id``
in locations with id ``ids`` and their child locations. If ``lock`` is True, the stock.move lines
of product with id ``product_id`` in the searched location will be write-locked using Postgres's
"FOR UPDATE NOWAIT" option until the transaction is committed or rolled back, to prevent reservin
twice the same products.
If ``lock`` is True and the lock cannot be obtained (because another transaction has locked some of
the same stock.move lines), a log line will be output and False will be returned, as if there was
not enough stock.
:param product_id: Id of product to reserve
:param product_qty: Quantity of product to reserve (in the product's default uom or the uom passed in ``context``)
:param lock: if True, the stock.move lines of product with id ``product_id`` in all locations (and children locations) with ``ids`` will
be write-locked using postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back. This is
to prevent reserving twice the same products.
:param context: optional context dictionary: if a 'uom' key is present it will be used instead of the default product uom to
compute the ``product_qty`` and in the return value.
:return: List of tuples in the form (qty, location_id) with the (partial) quantities that can be taken in each location to
reach the requested product_qty (``qty`` is expressed in the default uom of the product), of False if enough
products could not be found, or the lock could not be obtained (and ``lock`` was True).
"""
result = []
amount = 0.0
if context is None:
context = {}
uom_obj = self.pool.get('product.uom')
uom_rounding = self.pool.get('product.product').browse(cr, uid, product_id, context=context).uom_id.rounding
if context.get('uom'):
uom_rounding = uom_obj.browse(cr, uid, context.get('uom'), context=context).rounding
locations_ids = self.search(cr, uid, [('location_id', 'child_of', ids)])
if locations_ids:
# Fetch only the locations in which this product has ever been processed (in or out)
cr.execute("""SELECT l.id FROM stock_location l WHERE l.id in %s AND
EXISTS (SELECT 1 FROM stock_move m WHERE m.product_id = %s
AND ((state = 'done' AND m.location_dest_id = l.id)
OR (state in ('done','assigned') AND m.location_id = l.id)))
""", (tuple(locations_ids), product_id,))
locations_ids = [i for (i,) in cr.fetchall()]
for id in locations_ids:
if lock:
try:
# Must lock with a separate select query because FOR UPDATE can't be used with
# aggregation/group by's (when individual rows aren't identifiable).
# We use a SAVEPOINT to be able to rollback this part of the transaction without
# failing the whole transaction in case the LOCK cannot be acquired.
cr.execute("SAVEPOINT <API key>")
cr.execute("""SELECT id FROM stock_move
WHERE product_id=%s AND
(
(location_dest_id=%s AND
location_id<>%s AND
state='done')
OR
(location_id=%s AND
location_dest_id<>%s AND
state in ('done', 'assigned'))
)
FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False)
except Exception:
# Here it's likely that the FOR UPDATE NOWAIT failed to get the LOCK,
# so we ROLLBACK to the SAVEPOINT to restore the transaction to its earlier
# state, we return False as if the products were not available, and log it:
cr.execute("ROLLBACK TO <API key>")
_logger.warning("Failed attempt to reserve %s x product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_qty, product_id)
_logger.debug("Trace of the failed product reservation attempt: ", exc_info=True)
return False
# XXX TODO: rewrite this with one single query, possibly even the quantity conversion
cr.execute("""SELECT product_uom, sum(product_qty) AS product_qty
FROM stock_move
WHERE location_dest_id=%s AND
location_id<>%s AND
product_id=%s AND
state='done'
GROUP BY product_uom
""",
(id, id, product_id))
results = cr.dictfetchall()
cr.execute("""SELECT product_uom,-sum(product_qty) AS product_qty
FROM stock_move
WHERE location_id=%s AND
location_dest_id<>%s AND
product_id=%s AND
state in ('done', 'assigned')
GROUP BY product_uom
""",
(id, id, product_id))
results += cr.dictfetchall()
total = 0.0
results2 = 0.0
for r in results:
amount = uom_obj._compute_qty(cr, uid, r['product_uom'], r['product_qty'], context.get('uom', False))
results2 += amount
total += amount
if total <= 0.0:
continue
amount = results2
compare_qty = float_compare(amount, 0, precision_rounding=uom_rounding)
if compare_qty == 1:
if amount > min(total, product_qty):
amount = min(product_qty, total)
result.append((amount, id))
product_qty -= amount
total -= amount
if product_qty <= 0.0:
return result
if total <= 0.0:
continue
return False
stock_location()
class stock_tracking(osv.osv):
_name = "stock.tracking"
_description = "Packs"
def checksum(sscc):
salt = '31' * 8 + '3'
sum = 0
for sscc_part, salt_part in zip(sscc, salt):
sum += int(sscc_part) * int(salt_part)
return (10 - (sum % 10)) % 10
checksum = staticmethod(checksum)
def make_sscc(self, cr, uid, context=None):
sequence = self.pool.get('ir.sequence').get(cr, uid, 'stock.lot.tracking')
try:
return sequence + str(self.checksum(sequence))
except Exception:
return sequence
_columns = {
'name': fields.char('Pack Reference', size=64, required=True, select=True, help="By default, the pack reference is generated following the sscc standard. (Serial number + 1 check digit)"),
'active': fields.boolean('Active', help="By unchecking the active field, you may hide a pack without deleting it."),
'serial': fields.char('Additional Reference', size=64, select=True, help="Other reference or serial number"),
'move_ids': fields.one2many('stock.move', 'tracking_id', 'Moves for this pack', readonly=True),
'date': fields.datetime('Creation Date', required=True),
}
_defaults = {
'active': 1,
'name': make_sscc,
'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
}
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
ids = self.search(cr, user, [('serial', '=', name)]+ args, limit=limit, context=context)
ids += self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
return self.name_get(cr, user, ids, context)
def name_get(self, cr, uid, ids, context=None):
"""Append the serial to the name"""
if not len(ids):
return []
res = [ (r['id'], r['serial'] and '%s [%s]' % (r['name'], r['serial'])
or r['name'] )
for r in self.read(cr, uid, ids, ['name', 'serial'],
context=context) ]
return res
def unlink(self, cr, uid, ids, context=None):
raise osv.except_osv(_('Error!'), _('You cannot remove a lot line.'))
def action_traceability(self, cr, uid, ids, context=None):
""" It traces the information of a product
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
@return: A dictionary of values
"""
return self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
stock_tracking()
# Stock Picking
class stock_picking(osv.osv):
_name = "stock.picking"
_inherit = ['mail.thread']
_description = "Picking List"
_order = "id desc"
def _set_maximum_date(self, cr, uid, ids, name, value, arg, context=None):
""" Calculates planned date if it is greater than 'value'.
@param name: Name of field
@param value: Value of field
@param arg: User defined argument
@return: True or False
"""
if not value:
return False
if isinstance(ids, (int, long)):
ids = [ids]
for pick in self.browse(cr, uid, ids, context=context):
sql_str = """update stock_move set
date_expected='%s'
where
picking_id=%d """ % (value, pick.id)
if pick.max_date:
sql_str += " and (date_expected='" + pick.max_date + "')"
cr.execute(sql_str)
return True
def _set_minimum_date(self, cr, uid, ids, name, value, arg, context=None):
""" Calculates planned date if it is less than 'value'.
@param name: Name of field
@param value: Value of field
@param arg: User defined argument
@return: True or False
"""
if not value:
return False
if isinstance(ids, (int, long)):
ids = [ids]
for pick in self.browse(cr, uid, ids, context=context):
sql_str = """update stock_move set
date_expected='%s'
where
picking_id=%s """ % (value, pick.id)
if pick.min_date:
sql_str += " and (date_expected='" + pick.min_date + "')"
cr.execute(sql_str)
return True
def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None):
""" Finds minimum and maximum dates for picking.
@return: Dictionary of values
"""
res = {}
for id in ids:
res[id] = {'min_date': False, 'max_date': False}
if not ids:
return res
cr.execute("""select
picking_id,
min(date_expected),
max(date_expected)
from
stock_move
where
picking_id IN %s
group by
picking_id""",(tuple(ids),))
for pick, dt1, dt2 in cr.fetchall():
res[pick]['min_date'] = dt1
res[pick]['max_date'] = dt2
return res
def create(self, cr, user, vals, context=None):
if ('name' not in vals) or (vals.get('name')=='/'):
seq_obj_name = self._name
vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
new_id = super(stock_picking, self).create(cr, user, vals, context)
return new_id
_columns = {
'name': fields.char('Reference', size=64, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'origin': fields.char('Source Document', size=64, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Reference of the document", select=True),
'backorder_id': fields.many2one('stock.picking', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
'type': fields.selection([('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], 'Shipping Type', required=True, select=True, help="Shipping type specify, goods coming in or going out."),
'note': fields.text('Notes', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'stock_journal_id': fields.many2one('stock.journal','Stock Journal', select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'location_id': fields.many2one('stock.location', 'Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Keep empty if you produce at the location where the finished products are needed." \
"Set a location if you produce at a fixed location. This can be a partner location " \
"if you subcontract the manufacturing operations.", select=True),
'location_dest_id': fields.many2one('stock.location', 'Dest. Location', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="Location where the system will stock the finished products.", select=True),
'move_type': fields.selection([('direct', 'Partial'), ('one', 'All at once')], 'Delivery Method', required=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="It specifies goods to be deliver partially or all at once"),
'state': fields.selection([
('draft', 'Draft'),
('cancel', 'Cancelled'),
('auto', 'Waiting Another Operation'),
('confirmed', 'Waiting Availability'),
('assigned', 'Ready to Transfer'),
('done', 'Transferred'),
], 'Status', readonly=True, select=True, track_visibility='onchange', help="""
* Draft: not confirmed yet and will not be scheduled until confirmed\n
* Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
* Waiting Availability: still waiting for the availability of products\n
* Ready to Transfer: products reserved, simply waiting for confirmation.\n
* Transferred: has been processed, can't be modified or cancelled anymore\n
* Cancelled: has been cancelled, can't be confirmed anymore"""
),
'min_date': fields.function(get_min_max_date, fnct_inv=_set_minimum_date, multi="min_max_date",
store=True, type='datetime', string='Scheduled Time', select=1, help="Scheduled time for the shipment to be processed"),
'date': fields.datetime('Creation Date', help="Creation date, usually the time of the order.", select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'date_done': fields.datetime('Date of Transfer', help="Date of Completion", states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'max_date': fields.function(get_min_max_date, fnct_inv=_set_maximum_date, multi="min_max_date",
store=True, type='datetime', string='Max. Expected Date', select=2),
'move_lines': fields.one2many('stock.move', 'picking_id', 'Internal Moves', states={'done': [('readonly', True)], 'cancel': [('readonly', True)]}),
'product_id': fields.related('move_lines', 'product_id', type='many2one', relation='product.product', string='Product'),
'auto_picking': fields.boolean('Auto-Picking', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'partner_id': fields.many2one('res.partner', 'Partner', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
'invoice_state': fields.selection([
("invoiced", "Invoiced"),
("2binvoiced", "To Be Invoiced"),
("none", "Not Applicable")], "Invoice Control",
select=True, required=True, readonly=True, track_visibility='onchange', states={'draft': [('readonly', False)]}),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True, states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}),
}
_defaults = {
'name': lambda self, cr, uid, context: '/',
'state': 'draft',
'move_type': 'direct',
'type': 'internal',
'invoice_state': 'none',
'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
'company_id': lambda self, cr, uid, c: self.pool.get('res.company').<API key>(cr, uid, 'stock.picking', context=c)
}
_sql_constraints = [
('name_uniq', 'unique(name, company_id)', 'Reference must be unique per Company!'),
]
def action_process(self, cr, uid, ids, context=None):
if context is None:
context = {}
"""Open the partial picking wizard"""
context.update({
'active_model': self._name,
'active_ids': ids,
'active_id': len(ids) and ids[0] or False
})
return {
'view_type': 'form',
'view_mode': 'form',
'res_model': 'stock.partial.picking',
'type': 'ir.actions.act_window',
'target': 'new',
'context': context,
'nodestroy': True,
}
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
default = default.copy()
picking_obj = self.browse(cr, uid, id, context=context)
move_obj = self.pool.get('stock.move')
if ('name' not in default) or (picking_obj.name == '/'):
seq_obj_name = 'stock.picking.' + picking_obj.type
default['name'] = self.pool.get('ir.sequence').get(cr, uid, seq_obj_name)
default['origin'] = ''
default['backorder_id'] = False
if 'invoice_state' not in default and picking_obj.invoice_state == 'invoiced':
default['invoice_state'] = '2binvoiced'
res = super(stock_picking, self).copy(cr, uid, id, default, context)
if res:
picking_obj = self.browse(cr, uid, res, context=context)
for move in picking_obj.move_lines:
move_obj.write(cr, uid, [move.id], {'tracking_id': False, 'prodlot_id': False, 'move_history_ids2': [(6, 0, [])], 'move_history_ids': [(6, 0, [])]})
return res
def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False):
if view_type == 'form' and not view_id:
mod_obj = self.pool.get('ir.model.data')
if self._name == "stock.picking.in":
model, view_id = mod_obj.<API key>(cr, uid, 'stock', '<API key>')
if self._name == "stock.picking.out":
model, view_id = mod_obj.<API key>(cr, uid, 'stock', '<API key>')
return super(stock_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu)
def onchange_partner_in(self, cr, uid, ids, partner_id=None, context=None):
return {}
def action_explode(self, cr, uid, moves, context=None):
"""Hook to allow other modules to split the moves of a picking."""
return moves
def action_confirm(self, cr, uid, ids, context=None):
""" Confirms picking.
@return: True
"""
pickings = self.browse(cr, uid, ids, context=context)
self.write(cr, uid, ids, {'state': 'confirmed'})
todo = []
for picking in pickings:
for r in picking.move_lines:
if r.state == 'draft':
todo.append(r.id)
todo = self.action_explode(cr, uid, todo, context)
if len(todo):
self.pool.get('stock.move').action_confirm(cr, uid, todo, context=context)
return True
def test_auto_picking(self, cr, uid, ids):
# TODO: Check locations to see if in the same location ?
return True
def action_assign(self, cr, uid, ids, *args):
""" Changes state of picking to available if all moves are confirmed.
@return: True
"""
wf_service = netsvc.LocalService("workflow")
for pick in self.browse(cr, uid, ids):
if pick.state == 'draft':
wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_confirm', cr)
move_ids = [x.id for x in pick.move_lines if x.state == 'confirmed']
if not move_ids:
raise osv.except_osv(_('Warning!'),_('Not enough stock, unable to reserve the products.'))
self.pool.get('stock.move').action_assign(cr, uid, move_ids)
return True
def force_assign(self, cr, uid, ids, *args):
""" Changes state of picking to available if moves are confirmed or waiting.
@return: True
"""
wf_service = netsvc.LocalService("workflow")
for pick in self.browse(cr, uid, ids):
move_ids = [x.id for x in pick.move_lines if x.state in ['confirmed','waiting']]
self.pool.get('stock.move').force_assign(cr, uid, move_ids)
wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
return True
def draft_force_assign(self, cr, uid, ids, *args):
""" Confirms picking directly from draft state.
@return: True
"""
wf_service = netsvc.LocalService("workflow")
for pick in self.browse(cr, uid, ids):
if not pick.move_lines:
raise osv.except_osv(_('Error!'),_('You cannot process picking without stock moves.'))
wf_service.trg_validate(uid, 'stock.picking', pick.id,
'button_confirm', cr)
return True
def draft_validate(self, cr, uid, ids, context=None):
""" Validates picking directly from draft state.
@return: True
"""
wf_service = netsvc.LocalService("workflow")
self.draft_force_assign(cr, uid, ids)
for pick in self.browse(cr, uid, ids, context=context):
move_ids = [x.id for x in pick.move_lines]
self.pool.get('stock.move').force_assign(cr, uid, move_ids)
wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
return self.action_process(
cr, uid, ids, context=context)
def cancel_assign(self, cr, uid, ids, *args):
""" Cancels picking and moves.
@return: True
"""
wf_service = netsvc.LocalService("workflow")
for pick in self.browse(cr, uid, ids):
move_ids = [x.id for x in pick.move_lines]
self.pool.get('stock.move').cancel_assign(cr, uid, move_ids)
wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
return True
def action_assign_wkf(self, cr, uid, ids, context=None):
""" Changes picking state to assigned.
@return: True
"""
self.write(cr, uid, ids, {'state': 'assigned'})
return True
def test_finished(self, cr, uid, ids):
""" Tests whether the move is in done or cancel state or not.
@return: True or False
"""
move_ids = self.pool.get('stock.move').search(cr, uid, [('picking_id', 'in', ids)])
for move in self.pool.get('stock.move').browse(cr, uid, move_ids):
if move.state not in ('done', 'cancel'):
if move.product_qty != 0.0:
return False
else:
move.write({'state': 'done'})
return True
def test_assigned(self, cr, uid, ids):
""" Tests whether the move is in assigned state or not.
@return: True or False
"""
#TOFIX: assignment of move lines should be call before testing assigment otherwise picking never gone in assign state
ok = True
for pick in self.browse(cr, uid, ids):
mt = pick.move_type
# incomming shipments are always set as available if they aren't chained
if pick.type == 'in':
if all([x.state != 'waiting' for x in pick.move_lines]):
return True
for move in pick.move_lines:
if (move.state in ('confirmed', 'draft')) and (mt == 'one'):
return False
if (mt == 'direct') and (move.state == 'assigned') and (move.product_qty):
return True
ok = ok and (move.state in ('cancel', 'done', 'assigned'))
return ok
def action_cancel(self, cr, uid, ids, context=None):
""" Changes picking state to cancel.
@return: True
"""
for pick in self.browse(cr, uid, ids, context=context):
ids2 = [move.id for move in pick.move_lines]
self.pool.get('stock.move').action_cancel(cr, uid, ids2, context)
self.write(cr, uid, ids, {'state': 'cancel', 'invoice_state': 'none'})
return True
# TODO: change and create a move if not parents
def action_done(self, cr, uid, ids, context=None):
"""Changes picking state to done.
This method is called at the end of the workflow by the activity "done".
@return: True
"""
self.write(cr, uid, ids, {'state': 'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
return True
def action_move(self, cr, uid, ids, context=None):
"""Process the Stock Moves of the Picking
This method is called by the workflow by the activity "move".
Normally that happens when the signal button_done is received (button
"Done" pressed on a Picking view).
@return: True
"""
for pick in self.browse(cr, uid, ids, context=context):
todo = []
for move in pick.move_lines:
if move.state == 'draft':
self.pool.get('stock.move').action_confirm(cr, uid, [move.id],
context=context)
todo.append(move.id)
elif move.state in ('assigned','confirmed'):
todo.append(move.id)
if len(todo):
self.pool.get('stock.move').action_done(cr, uid, todo,
context=context)
return True
def get_currency_id(self, cr, uid, picking):
return False
def <API key>(self, cr, uid, picking, context=None):
""" Gets the partner that will be invoiced
Note that this function is inherited in the sale and purchase modules
@param picking: object of the picking for which we are selecting the partner to invoice
@return: object of the partner to invoice
"""
return picking.partner_id and picking.partner_id.id
def <API key>(self, cr, uid, picking):
"""
@return: comment string for invoice
"""
return picking.note or ''
def <API key>(self, cr, uid, move_line, type, context=None):
""" Gets price unit for invoice
@param move_line: Stock move lines
@param type: Type of invoice
@return: The price unit for the move line
"""
if context is None:
context = {}
if type in ('in_invoice', 'in_refund'):
# Take the user company and pricetype
context['currency_id'] = move_line.company_id.currency_id.id
amount_unit = move_line.product_id.price_get('standard_price', context=context)[move_line.product_id.id]
return amount_unit
else:
return move_line.product_id.list_price
def <API key>(self, cr, uid, move_line):
'''Return the discount for the move line'''
return 0.0
def _get_taxes_invoice(self, cr, uid, move_line, type):
""" Gets taxes on invoice
@param move_line: Stock move lines
@param type: Type of invoice
@return: Taxes Ids for the move line
"""
if type in ('in_invoice', 'in_refund'):
taxes = move_line.product_id.supplier_taxes_id
else:
taxes = move_line.product_id.taxes_id
if move_line.picking_id and move_line.picking_id.partner_id and move_line.picking_id.partner_id.id:
return self.pool.get('account.fiscal.position').map_tax(
cr,
uid,
move_line.picking_id.partner_id.<API key>,
taxes
)
else:
return map(lambda x: x.id, taxes)
def <API key>(self, cr, uid, picking, move_line):
return False
def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
'''Call after the creation of the invoice line'''
return
def _invoice_hook(self, cr, uid, picking, invoice_id):
'''Call after the creation of the invoice'''
return
def _get_invoice_type(self, pick):
src_usage = dest_usage = None
inv_type = None
if pick.invoice_state == '2binvoiced':
if pick.move_lines:
src_usage = pick.move_lines[0].location_id.usage
dest_usage = pick.move_lines[0].location_dest_id.usage
if pick.type == 'out' and dest_usage == 'supplier':
inv_type = 'in_refund'
elif pick.type == 'out' and dest_usage == 'customer':
inv_type = 'out_invoice'
elif pick.type == 'in' and src_usage == 'supplier':
inv_type = 'in_invoice'
elif pick.type == 'in' and src_usage == 'customer':
inv_type = 'out_refund'
else:
inv_type = 'out_invoice'
return inv_type
def <API key>(self, cr, uid, picking, partner, invoice, context=None):
""" Builds the dict for grouped invoices
@param picking: picking object
@param partner: object of the partner to invoice (not used here, but may be usefull if this function is inherited)
@param invoice: object of the invoice that we are updating
@return: dict that will be used to update the invoice
"""
comment = self.<API key>(cr, uid, picking)
return {
'name': (invoice.name or '') + ', ' + (picking.name or ''),
'origin': (invoice.origin or '') + ', ' + (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
'comment': (comment and (invoice.comment and invoice.comment + "\n" + comment or comment)) or (invoice.comment and invoice.comment or ''),
'date_invoice': context.get('date_inv', False),
'user_id': uid,
}
def _prepare_invoice(self, cr, uid, picking, partner, inv_type, journal_id, context=None):
""" Builds the dict containing the values for the invoice
@param picking: picking object
@param partner: object of the partner to invoice
@param inv_type: type of the invoice ('out_invoice', 'in_invoice', ...)
@param journal_id: ID of the accounting journal
@return: dict that will be used to create the invoice object
"""
if isinstance(partner, int):
partner = self.pool.get('res.partner').browse(cr, uid, partner, context=context)
if inv_type in ('out_invoice', 'out_refund'):
account_id = partner.<API key>.id
payment_term = partner.<API key>.id or False
else:
account_id = partner.<API key>.id
payment_term = partner.<API key>.id or False
comment = self.<API key>(cr, uid, picking)
invoice_vals = {
'name': picking.name,
'origin': (picking.name or '') + (picking.origin and (':' + picking.origin) or ''),
'type': inv_type,
'account_id': account_id,
'partner_id': partner.id,
'comment': comment,
'payment_term': payment_term,
'fiscal_position': partner.<API key>.id,
'date_invoice': context.get('date_inv', False),
'company_id': picking.company_id.id,
'user_id': uid,
}
cur_id = self.get_currency_id(cr, uid, picking)
if cur_id:
invoice_vals['currency_id'] = cur_id
if journal_id:
invoice_vals['journal_id'] = journal_id
return invoice_vals
def <API key>(self, cr, uid, group, picking, move_line, invoice_id,
invoice_vals, context=None):
""" Builds the dict containing the values for the invoice line
@param group: True or False
@param picking: picking object
@param: move_line: move_line object
@param: invoice_id: ID of the related invoice
@param: invoice_vals: dict used to created the invoice
@return: dict that will be used to create the invoice line
"""
if group:
name = (picking.name or '') + '-' + move_line.name
else:
name = move_line.name
origin = move_line.picking_id.name or ''
if move_line.picking_id.origin:
origin += ':' + move_line.picking_id.origin
if invoice_vals['type'] in ('out_invoice', 'out_refund'):
account_id = move_line.product_id.<API key>.id
if not account_id:
account_id = move_line.product_id.categ_id.\
<API key>.id
else:
account_id = move_line.product_id.<API key>.id
if not account_id:
account_id = move_line.product_id.categ_id.\
<API key>.id
if invoice_vals['fiscal_position']:
fp_obj = self.pool.get('account.fiscal.position')
fiscal_position = fp_obj.browse(cr, uid, invoice_vals['fiscal_position'], context=context)
account_id = fp_obj.map_account(cr, uid, fiscal_position, account_id)
# set UoS if it's a sale and the picking doesn't have one
uos_id = move_line.product_uos and move_line.product_uos.id or False
if not uos_id and invoice_vals['type'] in ('out_invoice', 'out_refund'):
uos_id = move_line.product_uom.id
return {
'name': name,
'origin': origin,
'invoice_id': invoice_id,
'uos_id': uos_id,
'product_id': move_line.product_id.id,
'account_id': account_id,
'price_unit': self.<API key>(cr, uid, move_line, invoice_vals['type']),
'discount': self.<API key>(cr, uid, move_line),
'quantity': move_line.product_uos_qty or move_line.product_qty,
'invoice_line_tax_id': [(6, 0, self._get_taxes_invoice(cr, uid, move_line, invoice_vals['type']))],
'account_analytic_id': self.<API key>(cr, uid, picking, move_line),
}
def <API key>(self, cr, uid, ids, journal_id=False,
group=False, type='out_invoice', context=None):
""" Creates invoice based on the invoice state selected for picking.
@param journal_id: Id of journal
@param group: Whether to create a group invoice or not
@param type: Type invoice to be created
@return: Ids of created invoices for the pickings
"""
if context is None:
context = {}
invoice_obj = self.pool.get('account.invoice')
invoice_line_obj = self.pool.get('account.invoice.line')
partner_obj = self.pool.get('res.partner')
invoices_group = {}
res = {}
inv_type = type
for picking in self.browse(cr, uid, ids, context=context):
if picking.invoice_state != '2binvoiced':
continue
partner = self.<API key>(cr, uid, picking, context=context)
if isinstance(partner, int):
partner = partner_obj.browse(cr, uid, [partner], context=context)[0]
if not partner:
raise osv.except_osv(_('Error, no partner!'),
_('Please put a partner on the picking list if you want to generate invoice.'))
if not inv_type:
inv_type = self._get_invoice_type(picking)
if group and partner.id in invoices_group:
invoice_id = invoices_group[partner.id]
invoice = invoice_obj.browse(cr, uid, invoice_id)
invoice_vals_group = self.<API key>(cr, uid, picking, partner, invoice, context=context)
invoice_obj.write(cr, uid, [invoice_id], invoice_vals_group, context=context)
else:
invoice_vals = self._prepare_invoice(cr, uid, picking, partner, inv_type, journal_id, context=context)
invoice_id = invoice_obj.create(cr, uid, invoice_vals, context=context)
invoices_group[partner.id] = invoice_id
res[picking.id] = invoice_id
for move_line in picking.move_lines:
if move_line.state == 'cancel':
continue
if move_line.scrapped:
# do no invoice scrapped products
continue
vals = self.<API key>(cr, uid, group, picking, move_line,
invoice_id, invoice_vals, context=context)
if vals:
invoice_line_id = invoice_line_obj.create(cr, uid, vals, context=context)
self._invoice_line_hook(cr, uid, move_line, invoice_line_id)
invoice_obj.button_compute(cr, uid, [invoice_id], context=context,
set_total=(inv_type in ('in_invoice', 'in_refund')))
self.write(cr, uid, [picking.id], {
'invoice_state': 'invoiced',
}, context=context)
self._invoice_hook(cr, uid, picking, invoice_id)
self.write(cr, uid, res.keys(), {
'invoice_state': 'invoiced',
}, context=context)
return res
def test_done(self, cr, uid, ids, context=None):
""" Test whether the move lines are done or not.
@return: True or False
"""
ok = False
for pick in self.browse(cr, uid, ids, context=context):
if not pick.move_lines:
return True
for move in pick.move_lines:
if move.state not in ('cancel','done'):
return False
if move.state=='done':
ok = True
return ok
def test_cancel(self, cr, uid, ids, context=None):
""" Test whether the move lines are canceled or not.
@return: True or False
"""
for pick in self.browse(cr, uid, ids, context=context):
for move in pick.move_lines:
if move.state not in ('cancel',):
return False
return True
def allow_cancel(self, cr, uid, ids, context=None):
for pick in self.browse(cr, uid, ids, context=context):
if not pick.move_lines:
return True
for move in pick.move_lines:
if move.state == 'done':
raise osv.except_osv(_('Error!'), _('You cannot cancel the picking as some moves have been done. You should cancel the picking lines.'))
return True
def unlink(self, cr, uid, ids, context=None):
move_obj = self.pool.get('stock.move')
if context is None:
context = {}
for pick in self.browse(cr, uid, ids, context=context):
if pick.state in ['done','cancel']:
raise osv.except_osv(_('Error!'), _('You cannot remove the picking which is in %s state!')%(pick.state,))
else:
ids2 = [move.id for move in pick.move_lines]
ctx = context.copy()
ctx.update({'call_unlink':True})
if pick.state != 'draft':
#Cancelling the move in order to affect Virtual stock of product
move_obj.action_cancel(cr, uid, ids2, ctx)
#Removing the move
move_obj.unlink(cr, uid, ids2, ctx)
return super(stock_picking, self).unlink(cr, uid, ids, context=context)
# FIXME: needs refactoring, this code is partially duplicated in stock_move.do_partial()!
def do_partial(self, cr, uid, ids, partial_datas, context=None):
""" Makes partial picking and moves done.
@param partial_datas : Dictionary containing details of partial picking
like partner_id, partner_id, delivery_date,
delivery moves with product_id, product_qty, uom
@return: Dictionary of values
"""
if context is None:
context = {}
else:
context = dict(context)
res = {}
move_obj = self.pool.get('stock.move')
product_obj = self.pool.get('product.product')
currency_obj = self.pool.get('res.currency')
uom_obj = self.pool.get('product.uom')
sequence_obj = self.pool.get('ir.sequence')
wf_service = netsvc.LocalService("workflow")
for pick in self.browse(cr, uid, ids, context=context):
new_picking = None
complete, too_many, too_few = [], [], []
move_product_qty, prodlot_ids, product_avail, partial_qty, product_uoms = {}, {}, {}, {}, {}
for move in pick.move_lines:
if move.state in ('done', 'cancel'):
continue
partial_data = partial_datas.get('move%s'%(move.id), {})
product_qty = partial_data.get('product_qty',0.0)
move_product_qty[move.id] = product_qty
product_uom = partial_data.get('product_uom',False)
product_price = partial_data.get('product_price',0.0)
product_currency = partial_data.get('product_currency',False)
prodlot_id = partial_data.get('prodlot_id')
prodlot_ids[move.id] = prodlot_id
product_uoms[move.id] = product_uom
partial_qty[move.id] = uom_obj._compute_qty(cr, uid, product_uoms[move.id], product_qty, move.product_uom.id)
if move.product_qty == partial_qty[move.id]:
complete.append(move)
elif move.product_qty > partial_qty[move.id]:
too_few.append(move)
else:
too_many.append(move)
# Average price computation
if (pick.type == 'in') and (move.product_id.cost_method == 'average'):
product = product_obj.browse(cr, uid, move.product_id.id)
move_currency_id = move.company_id.currency_id.id
context['currency_id'] = move_currency_id
qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
if product.id not in product_avail:
# keep track of stock on hand including processed lines not yet marked as done
product_avail[product.id] = product.qty_available
if qty > 0:
new_price = currency_obj.compute(cr, uid, product_currency,
move_currency_id, product_price, round=False)
new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
product.uom_id.id)
if product_avail[product.id] <= 0:
product_avail[product.id] = 0
new_std_price = new_price
else:
# Get the standard price
amount_unit = product.price_get('standard_price', context=context)[product.id]
new_std_price = ((amount_unit * product_avail[product.id])\
+ (new_price * qty))/(product_avail[product.id] + qty)
# Write the field according to price type field
product_obj.write(cr, uid, [product.id], {'standard_price': new_std_price})
# Record the values that were chosen in the wizard, so they can be
# used for inventory valuation if real-time valuation is enabled.
move_obj.write(cr, uid, [move.id],
{'price_unit': product_price,
'price_currency_id': product_currency})
product_avail[product.id] += qty
for move in too_few:
product_qty = move_product_qty[move.id]
if not new_picking:
new_picking_name = pick.name
self.write(cr, uid, [pick.id],
{'name': sequence_obj.get(cr, uid,
'stock.picking.%s'%(pick.type)),
})
new_picking = self.copy(cr, uid, pick.id,
{
'name': new_picking_name,
'move_lines' : [],
'state':'draft',
})
if product_qty != 0:
defaults = {
'product_qty' : product_qty,
'product_uos_qty': product_qty, #TODO: put correct uos_qty
'picking_id' : new_picking,
'state': 'assigned',
'move_dest_id': False,
'price_unit': move.price_unit,
'product_uom': product_uoms[move.id]
}
prodlot_id = prodlot_ids[move.id]
if prodlot_id:
defaults.update(prodlot_id=prodlot_id)
move_obj.copy(cr, uid, move.id, defaults)
move_obj.write(cr, uid, [move.id],
{
'product_qty': move.product_qty - partial_qty[move.id],
'product_uos_qty': move.product_qty - partial_qty[move.id], #TODO: put correct uos_qty
'prodlot_id': False,
'tracking_id': False,
})
if new_picking:
move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking})
for move in complete:
defaults = {'product_uom': product_uoms[move.id], 'product_qty': move_product_qty[move.id]}
if prodlot_ids.get(move.id):
defaults.update({'prodlot_id': prodlot_ids[move.id]})
move_obj.write(cr, uid, [move.id], defaults)
for move in too_many:
product_qty = move_product_qty[move.id]
defaults = {
'product_qty' : product_qty,
'product_uos_qty': product_qty, #TODO: put correct uos_qty
'product_uom': product_uoms[move.id]
}
prodlot_id = prodlot_ids.get(move.id)
if prodlot_ids.get(move.id):
defaults.update(prodlot_id=prodlot_id)
if new_picking:
defaults.update(picking_id=new_picking)
move_obj.write(cr, uid, [move.id], defaults)
# At first we confirm the new picking (if necessary)
if new_picking:
wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr)
# Then we finish the good picking
self.write(cr, uid, [pick.id], {'backorder_id': new_picking})
self.action_move(cr, uid, [new_picking], context=context)
wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr)
wf_service.trg_write(uid, 'stock.picking', pick.id, cr)
delivered_pack_id = pick.id
back_order_name = self.browse(cr, uid, delivered_pack_id, context=context).name
self.message_post(cr, uid, new_picking, body=_("Back order <em>%s</em> has been <b>created</b>.") % (back_order_name), context=context)
else:
self.action_move(cr, uid, [pick.id], context=context)
wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr)
delivered_pack_id = pick.id
delivered_pack = self.browse(cr, uid, delivered_pack_id, context=context)
res[pick.id] = {'delivered_picking': delivered_pack.id or False}
return res
# views associated to each picking type
_VIEW_LIST = {
'out': '<API key>',
'in': '<API key>',
'internal': 'view_picking_form',
}
def _get_view_id(self, cr, uid, type):
"""Get the view id suiting the given type
@param type: the picking type as a string
@return: view i, or False if no view found
"""
res = self.pool.get('ir.model.data').<API key>(cr, uid,
'stock', self._VIEW_LIST.get(type, 'view_picking_form'))
return res and res[1] or False
class <API key>(osv.osv):
def name_get(self, cr, uid, ids, context=None):
if not ids:
return []
reads = self.read(cr, uid, ids, ['name', 'prefix', 'ref'], context)
res = []
for record in reads:
name = record['name']
prefix = record['prefix']
if prefix:
name = prefix + '/' + name
if record['ref']:
name = '%s [%s]' % (name, record['ref'])
res.append((record['id'], name))
return res
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
args = args or []
ids = []
if name:
ids = self.search(cr, uid, [('prefix', '=', name)] + args, limit=limit, context=context)
if not ids:
ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context)
else:
ids = self.search(cr, uid, args, limit=limit, context=context)
return self.name_get(cr, uid, ids, context)
_name = 'stock.production.lot'
_description = 'Serial Number'
def _get_stock(self, cr, uid, ids, field_name, arg, context=None):
""" Gets stock of products for locations
@return: Dictionary of values
"""
if context is None:
context = {}
if 'location_id' not in context:
locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)
else:
locations = context['location_id'] and [context['location_id']] or []
if isinstance(ids, (int, long)):
ids = [ids]
res = {}.fromkeys(ids, 0.0)
if locations:
cr.execute('''select
prodlot_id,
sum(qty)
from
<API key>
where
location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),))
res.update(dict(cr.fetchall()))
return res
def _stock_search(self, cr, uid, obj, name, args, context=None):
""" Searches Ids of products
@return: Ids of locations
"""
locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])
cr.execute('''select
prodlot_id,
sum(qty)
from
<API key>
where
location_id IN %s group by prodlot_id
having sum(qty) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),))
res = cr.fetchall()
ids = [('id', 'in', map(lambda x: x[0], res))]
return ids
_columns = {
'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number, will be displayed as: PREFIX/SERIAL [INT_REF]"),
'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),
'prefix': fields.char('Prefix', size=64, help="Optional prefix to prepend when displaying this serial number: PREFIX/SERIAL [INT_REF]"),
'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),
'date': fields.datetime('Creation Date', required=True),
'stock_available': fields.function(_get_stock, fnct_search=_stock_search, type="float", string="Available", select=True,
help="Current quantity of products with this Serial Number available in company warehouses",
digits_compute=dp.get_precision('Product Unit of Measure')),
'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),
'company_id': fields.many2one('res.company', 'Company', select=True),
'move_ids': fields.one2many('stock.move', 'prodlot_id', 'Moves for this serial number', readonly=True),
}
_defaults = {
'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),
'product_id': lambda x, y, z, c: c.get('product_id', False),
}
_sql_constraints = [
('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),
]
def action_traceability(self, cr, uid, ids, context=None):
""" It traces the information of a product
@param self: The object pointer.
@param cr: A database cursor
@param uid: ID of the user currently logged in
@param ids: List of IDs selected
@param context: A standard dictionary
@return: A dictionary of values
"""
value=self.pool.get('action.traceability').action_traceability(cr,uid,ids,context)
return value
def copy(self, cr, uid, id, default=None, context=None):
context = context or {}
default = default and default.copy() or {}
default.update(date=time.strftime('%Y-%m-%d %H:%M:%S'), move_ids=[])
return super(<API key>, self).copy(cr, uid, id, default=default, context=context)
<API key>()
class <API key>(osv.osv):
_name = 'stock.production.lot.revision'
_description = 'Serial Number Revision'
_columns = {
'name': fields.char('Revision Name', size=64, required=True),
'description': fields.text('Description'),
'date': fields.date('Revision Date'),
'indice': fields.char('Revision Number', size=16),
'author_id': fields.many2one('res.users', 'Author'),
'lot_id': fields.many2one('stock.production.lot', 'Serial Number', select=True, ondelete='cascade'),
'company_id': fields.related('lot_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True),
}
_defaults = {
'author_id': lambda x, y, z, c: z,
'date': fields.date.context_today,
}
<API key>()
# Move
# Fields:
# location_dest_id is only used for predicting futur stocks
class stock_move(osv.osv):
def _getSSCC(self, cr, uid, context=None):
cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))
res = cr.fetchone()
return (res and res[0]) or False
_name = "stock.move"
_description = "Stock Move"
_order = 'date_expected desc, id'
_log_create = False
def action_partial_move(self, cr, uid, ids, context=None):
if context is None: context = {}
if context.get('active_model') != self._name:
context.update(active_ids=ids, active_model=self._name)
partial_id = self.pool.get("stock.partial.move").create(
cr, uid, {}, context=context)
return {
'name':_("Products to Process"),
'view_mode': 'form',
'view_id': False,
'view_type': 'form',
'res_model': 'stock.partial.move',
'res_id': partial_id,
'type': 'ir.actions.act_window',
'nodestroy': True,
'target': 'new',
'domain': '[]',
'context': context
}
def name_get(self, cr, uid, ids, context=None):
res = []
for line in self.browse(cr, uid, ids, context=context):
name = line.location_id.name+' > '+line.location_dest_id.name
# optional prefixes
if line.product_id.code:
name = line.product_id.code + ': ' + name
if line.picking_id.origin:
name = line.picking_id.origin + '/ ' + name
res.append((line.id, name))
return res
def _check_tracking(self, cr, uid, ids, context=None):
""" Checks if serial number is assigned to stock move or not.
@return: True or False
"""
for move in self.browse(cr, uid, ids, context=context):
if not move.prodlot_id and \
(move.state == 'done' and \
( \
(move.product_id.track_production and move.location_id.usage == 'production') or \
(move.product_id.track_production and move.location_dest_id.usage == 'production') or \
(move.product_id.track_incoming and move.location_id.usage == 'supplier') or \
(move.product_id.track_outgoing and move.location_dest_id.usage == 'customer') or \
(move.product_id.track_incoming and move.location_id.usage == 'inventory') \
)):
return False
return True
def _check_product_lot(self, cr, uid, ids, context=None):
""" Checks whether move is done or not and production lot is assigned to that move.
@return: True or False
"""
for move in self.browse(cr, uid, ids, context=context):
if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id):
return False
return True
_columns = {
'name': fields.char('Description', required=True, select=True),
'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),
'create_date': fields.datetime('Creation Date', readonly=True, select=True),
'date': fields.datetime('Date', required=True, select=True, help="Move date: scheduled date until move is done, then date of actual move processing", states={'done': [('readonly', True)]}),
'date_expected': fields.datetime('Scheduled Date', states={'done': [('readonly', True)]},required=True, select=True, help="Scheduled date for the processing of this move"),
'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type','<>','service')],states={'done': [('readonly', True)]}),
'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
required=True,states={'done': [('readonly', True)]},
help="This is the quantity of products from an inventory "
"point of view. For moves in the state 'done', this is the "
"quantity of products that were actually moved. For other "
"moves, this is the quantity of product that is planned to "
"be moved. Lowering this quantity does not generate a "
"backorder. Changing this quantity on assigned moves affects "
"the product reservation, and should be done with care."
),
'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True,states={'done': [('readonly', True)]}),
'product_uos_qty': fields.float('Quantity (UOS)', digits_compute=dp.get_precision('Product Unit of Measure'), states={'done': [('readonly', True)]}),
'product_uos': fields.many2one('product.uom', 'Product UOS', states={'done': [('readonly', True)]}),
'product_packaging': fields.many2one('product.packaging', 'Packaging', help="It specifies attributes of packaging like type, quantity of packaging,etc."),
'location_id': fields.many2one('stock.location', 'Source Location', required=True, select=True,states={'done': [('readonly', True)]}, help="Sets a location if you produce at a fixed location. This can be a partner location if you subcontract the manufacturing operations."),
'location_dest_id': fields.many2one('stock.location', 'Destination Location', required=True,states={'done': [('readonly', True)]}, select=True, help="Location where the system will stock the finished products."),
'partner_id': fields.many2one('res.partner', 'Destination Address ', states={'done': [('readonly', True)]}, help="Optional address where goods are to be delivered, specifically used for allotment"),
'prodlot_id': fields.many2one('stock.production.lot', 'Serial Number', states={'done': [('readonly', True)]}, help="Serial number is used to put a serial number on the production", select=True),
'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, states={'done': [('readonly', True)]}, help="Logistical shipping unit: pallet, box, pack ..."),
'auto_validate': fields.boolean('Auto Validate'),
'move_dest_id': fields.many2one('stock.move', 'Destination Move', help="Optional: next stock move when chaining them", select=True),
'move_history_ids': fields.many2many('stock.move', '<API key>', 'parent_id', 'child_id', 'Move History (child moves)'),
'move_history_ids2': fields.many2many('stock.move', '<API key>', 'child_id', 'parent_id', 'Move History (parent moves)'),
'picking_id': fields.many2one('stock.picking', 'Reference', select=True,states={'done': [('readonly', True)]}),
'note': fields.text('Notes'),
'state': fields.selection([('draft', 'New'),
('cancel', 'Cancelled'),
('waiting', 'Waiting Another Move'),
('confirmed', 'Waiting Availability'),
('assigned', 'Available'),
('done', 'Done'),
], 'Status', readonly=True, select=True,
help= "* New: When the stock move is created and not yet confirmed.\n"\
"* Waiting Another Move: This state can be seen when a move is waiting for another one, for example in a chained flow.\n"\
"* Waiting Availability: This state is reached when the procurement resolution is not straight forward. It may need the scheduler to run, a component to me manufactured...\n"\
"* Available: When products are reserved, it is set to \'Available\'.\n"\
"* Done: When the shipment is processed, the state is \'Done\'."),
'price_unit': fields.float('Unit Price', digits_compute= dp.get_precision('Product Price'), help="Technical field used to record the product cost set by the user during a picking confirmation (when average price costing method is used)"),
'price_currency_id': fields.many2one('res.currency', 'Currency for average price', help="Technical field used to record the currency chosen by the user during a picking confirmation (when average price costing method is used)"),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
'backorder_id': fields.related('picking_id','backorder_id',type='many2one', relation="stock.picking", string="Back Order of", select=True),
'origin': fields.related('picking_id','origin',type='char', size=64, relation="stock.picking", string="Source", store=True),
# used for colors in tree views:
'scrapped': fields.related('location_dest_id','scrap_location',type='boolean',relation='stock.location',string='Scrapped', readonly=True),
'type': fields.related('picking_id', 'type', type='selection', selection=[('out', 'Sending Goods'), ('in', 'Getting Goods'), ('internal', 'Internal')], string='Shipping Type'),
}
def _check_location(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
if (record.state=='done') and (record.location_id.usage == 'view'):
raise osv.except_osv(_('Error'), _('You cannot move product %s from a location of type view %s.')% (record.product_id.name, record.location_id.name))
if (record.state=='done') and (record.location_dest_id.usage == 'view' ):
raise osv.except_osv(_('Error'), _('You cannot move product %s to a location of type view %s.')% (record.product_id.name, record.location_dest_id.name))
return True
_constraints = [
(_check_tracking,
'You must assign a serial number for this product.',
['prodlot_id']),
(_check_location, 'You cannot move products from or to a location of the type view.',
['location_id','location_dest_id']),
(_check_product_lot,
'You try to assign a lot which is not from the same product.',
['prodlot_id'])]
def <API key>(self, cr, uid, context=None):
""" Gets default address of partner for destination location
@return: Address id or False
"""
mod_obj = self.pool.get('ir.model.data')
picking_type = context.get('picking_type')
location_id = False
if context is None:
context = {}
if context.get('move_line', []):
if context['move_line'][0]:
if isinstance(context['move_line'][0], (tuple, list)):
location_id = context['move_line'][0][2] and context['move_line'][0][2].get('location_dest_id',False)
else:
move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])
location_id = move_list and move_list['location_dest_id'][0] or False
elif context.get('address_out_id', False):
property_out = self.pool.get('res.partner').browse(cr, uid, context['address_out_id'], context).<API key>
location_id = property_out and property_out.id or False
else:
location_xml_id = False
if picking_type in ('in', 'internal'):
location_xml_id = '<API key>'
elif picking_type == 'out':
location_xml_id = '<API key>'
if location_xml_id:
try:
location_model, location_id = mod_obj.<API key>(cr, uid, 'stock', location_xml_id)
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
except (orm.except_orm, ValueError):
location_id = False
return location_id
def <API key>(self, cr, uid, context=None):
""" Gets default address of partner for source location
@return: Address id or False
"""
mod_obj = self.pool.get('ir.model.data')
picking_type = context.get('picking_type')
location_id = False
if context is None:
context = {}
if context.get('move_line', []):
try:
location_id = context['move_line'][0][2]['location_id']
except:
pass
elif context.get('address_in_id', False):
part_obj_add = self.pool.get('res.partner').browse(cr, uid, context['address_in_id'], context=context)
if part_obj_add:
location_id = part_obj_add.<API key>.id
else:
location_xml_id = False
if picking_type == 'in':
location_xml_id = '<API key>'
elif picking_type in ('out', 'internal'):
location_xml_id = '<API key>'
if location_xml_id:
try:
location_model, location_id = mod_obj.<API key>(cr, uid, 'stock', location_xml_id)
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
except (orm.except_orm, ValueError):
location_id = False
return location_id
def <API key>(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
return user.company_id.partner_id.id
def _default_move_type(self, cr, uid, context=None):
""" Gets default type of move
@return: type
"""
if context is None:
context = {}
picking_type = context.get('picking_type')
type = 'internal'
if picking_type == 'in':
type = 'in'
elif picking_type == 'out':
type = 'out'
return type
_defaults = {
'location_id': <API key>,
'location_dest_id': <API key>,
'partner_id': <API key>,
'type': _default_move_type,
'state': 'draft',
'priority': '1',
'product_qty': 1.0,
'scrapped' : False,
'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
'company_id': lambda self,cr,uid,c: self.pool.get('res.company').<API key>(cr, uid, 'stock.move', context=c),
'date_expected': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
}
def write(self, cr, uid, ids, vals, context=None):
if isinstance(ids, (int, long)):
ids = [ids]
if uid != 1:
frozen_fields = set(['product_qty', 'product_uom', 'product_uos_qty', 'product_uos', 'location_id', 'location_dest_id', 'product_id'])
for move in self.browse(cr, uid, ids, context=context):
if move.state == 'done':
if frozen_fields.intersection(vals):
raise osv.except_osv(_('Operation Forbidden!'),
_('Quantities, Units of Measure, Products and Locations cannot be modified on stock moves that have already been processed (except by the Administrator).'))
return super(stock_move, self).write(cr, uid, ids, vals, context=context)
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
default = default.copy()
default.update({'move_history_ids2': [], 'move_history_ids': []})
return super(stock_move, self).copy(cr, uid, id, default, context=context)
def _auto_init(self, cursor, context=None):
res = super(stock_move, self)._auto_init(cursor, context=context)
cursor.execute('SELECT indexname \
FROM pg_indexes \
WHERE indexname = \'<API key>\'')
if not cursor.fetchone():
cursor.execute('CREATE INDEX <API key> \
ON stock_move (product_id, state, location_id, location_dest_id)')
return res
def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False,
loc_id=False, product_id=False, uom_id=False, context=None):
""" On change of production lot gives a warning message.
@param prodlot_id: Changed production lot id
@param product_qty: Quantity of product
@param loc_id: Location id
@param product_id: Product id
@return: Warning message
"""
if not prodlot_id or not loc_id:
return {}
ctx = context and context.copy() or {}
ctx['location_id'] = loc_id
ctx.update({'raise-exception': True})
uom_obj = self.pool.get('product.uom')
product_obj = self.pool.get('product.product')
product_uom = product_obj.browse(cr, uid, product_id, context=ctx).uom_id
prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, context=ctx)
location = self.pool.get('stock.location').browse(cr, uid, loc_id, context=ctx)
uom = uom_obj.browse(cr, uid, uom_id, context=ctx)
amount_actual = uom_obj._compute_qty_obj(cr, uid, product_uom, prodlot.stock_available, uom, context=ctx)
warning = {}
if (location.usage == 'internal') and (product_qty > (amount_actual or 0.0)):
warning = {
'title': _('Insufficient Stock for Serial Number !'),
'message': _('You are moving %.2f %s but only %.2f %s available for this serial number.') % (product_qty, uom.name, amount_actual, uom.name)
}
return {'warning': warning}
def onchange_quantity(self, cr, uid, ids, product_id, product_qty,
product_uom, product_uos):
""" On change of product quantity finds UoM and UoS quantities
@param product_id: Product id
@param product_qty: Changed Quantity of product
@param product_uom: Unit of measure of product
@param product_uos: Unit of sale of product
@return: Dictionary of values
"""
result = {
'product_uos_qty': 0.00
}
warning = {}
if (not product_id) or (product_qty <=0.0):
result['product_qty'] = 0.0
return {'value': result}
product_obj = self.pool.get('product.product')
uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
# Warn if the quantity was decreased
if ids:
for move in self.read(cr, uid, ids, ['product_qty']):
if product_qty < move['product_qty']:
warning.update({
'title': _('Information'),
'message': _("By changing this quantity here, you accept the "
"new quantity as complete: OpenERP will not "
"automatically generate a back order.") })
break
if product_uos and product_uom and (product_uom != product_uos):
result['product_uos_qty'] = product_qty * uos_coeff['uos_coeff']
else:
result['product_uos_qty'] = product_qty
return {'value': result, 'warning': warning}
def <API key>(self, cr, uid, ids, product_id, product_uos_qty,
product_uos, product_uom):
""" On change of product quantity finds UoM and UoS quantities
@param product_id: Product id
@param product_uos_qty: Changed UoS Quantity of product
@param product_uom: Unit of measure of product
@param product_uos: Unit of sale of product
@return: Dictionary of values
"""
result = {
'product_qty': 0.00
}
warning = {}
if (not product_id) or (product_uos_qty <=0.0):
result['product_uos_qty'] = 0.0
return {'value': result}
product_obj = self.pool.get('product.product')
uos_coeff = product_obj.read(cr, uid, product_id, ['uos_coeff'])
# Warn if the quantity was decreased
for move in self.read(cr, uid, ids, ['product_uos_qty']):
if product_uos_qty < move['product_uos_qty']:
warning.update({
'title': _('Warning: No Back Order'),
'message': _("By changing the quantity here, you accept the "
"new quantity as complete: OpenERP will not "
"automatically generate a Back Order.") })
break
if product_uos and product_uom and (product_uom != product_uos):
result['product_qty'] = product_uos_qty / uos_coeff['uos_coeff']
else:
result['product_qty'] = product_uos_qty
return {'value': result, 'warning': warning}
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False,
loc_dest_id=False, partner_id=False):
""" On change of product id, if finds UoM, UoS, quantity and UoS quantity.
@param prod_id: Changed Product id
@param loc_id: Source location id
@param loc_dest_id: Destination location id
@param partner_id: Address id of partner
@return: Dictionary of values
"""
if not prod_id:
return {}
user = self.pool.get('res.users').browse(cr, uid, uid)
lang = user and user.lang or False
if partner_id:
addr_rec = self.pool.get('res.partner').browse(cr, uid, partner_id)
if addr_rec:
lang = addr_rec and addr_rec.lang or False
ctx = {'lang': lang}
product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
uos_id = product.uos_id and product.uos_id.id or False
result = {
'product_uom': product.uom_id.id,
'product_uos': uos_id,
'product_qty': 1.00,
'product_uos_qty' : self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'],
'prodlot_id' : False,
}
if not ids:
result['name'] = product.partner_ref
if loc_id:
result['location_id'] = loc_id
if loc_dest_id:
result['location_dest_id'] = loc_dest_id
return {'value': result}
def onchange_move_type(self, cr, uid, ids, type, context=None):
""" On change of move type gives sorce and destination location.
@param type: Move Type
@return: Dictionary of values
"""
mod_obj = self.pool.get('ir.model.data')
location_source_id = '<API key>'
location_dest_id = '<API key>'
if type == 'in':
location_source_id = '<API key>'
location_dest_id = '<API key>'
elif type == 'out':
location_source_id = '<API key>'
location_dest_id = '<API key>'
try:
source_location = mod_obj.<API key>(cr, uid, 'stock', location_source_id)
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [source_location[1]], 'read', context=context)
except (orm.except_orm, ValueError):
source_location = False
try:
dest_location = mod_obj.<API key>(cr, uid, 'stock', location_dest_id)
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [dest_location[1]], 'read', context=context)
except (orm.except_orm, ValueError):
dest_location = False
return {'value':{'location_id': source_location and source_location[1] or False, 'location_dest_id': dest_location and dest_location[1] or False}}
def onchange_date(self, cr, uid, ids, date, date_expected, context=None):
if not date_expected:
date_expected = time.strftime('%Y-%m-%d %H:%M:%S')
return {'value':{'date': date_expected}}
def _chain_compute(self, cr, uid, moves, context=None):
""" Finds whether the location has chained location type or not.
@param moves: Stock moves
@return: Dictionary containing destination location with chained location type.
"""
result = {}
for m in moves:
dest = self.pool.get('stock.location').<API key>(
cr,
uid,
m.location_dest_id,
m.picking_id and m.picking_id.partner_id and m.picking_id.partner_id,
m.product_id,
context
)
if dest:
if dest[1] == 'transparent':
newdate = (datetime.strptime(m.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=dest[2] or 0)).strftime('%Y-%m-%d')
self.write(cr, uid, [m.id], {
'date': newdate,
'location_dest_id': dest[0].id})
if m.picking_id and (dest[3] or dest[5]):
self.pool.get('stock.picking').write(cr, uid, [m.picking_id.id], {
'stock_journal_id': dest[3] or m.picking_id.stock_journal_id.id,
'type': dest[5] or m.picking_id.type
}, context=context)
m.location_dest_id = dest[0]
res2 = self._chain_compute(cr, uid, [m], context=context)
for pick_id in res2.keys():
result.setdefault(pick_id, [])
result[pick_id] += res2[pick_id]
else:
result.setdefault(m.picking_id, [])
result[m.picking_id].append( (m, dest) )
return result
def <API key>(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
"""Prepare the definition (values) to create a new chained picking.
:param str picking_name: desired new picking name
:param browse_record picking: source picking (being chained to)
:param str picking_type: desired new picking type
:param list moves_todo: specification of the stock moves to be later included in this
picking, in the form::
[[move, (dest_location, auto_packing, chained_delay, chained_journal,
chained_company_id, <API key>)],
]
See also :meth:`stock_location.<API key>`.
"""
res_company = self.pool.get('res.company')
return {
'name': picking_name,
'origin': tools.ustr(picking.origin or ''),
'type': picking_type,
'note': picking.note,
'move_type': picking.move_type,
'auto_picking': moves_todo[0][1][1] == 'auto',
'stock_journal_id': moves_todo[0][1][3],
'company_id': moves_todo[0][1][4] or res_company.<API key>(cr, uid, 'stock.company', context=context),
'partner_id': picking.partner_id.id,
'invoice_state': 'none',
'date': picking.date,
}
def <API key>(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None):
picking_obj = self.pool.get('stock.picking')
return picking_obj.create(cr, uid, self.<API key>(cr, uid, picking_name, picking, picking_type, moves_todo, context=context))
def <API key>(self, cr, uid, moves, context=None):
res_obj = self.pool.get('res.company')
location_obj = self.pool.get('stock.location')
move_obj = self.pool.get('stock.move')
wf_service = netsvc.LocalService("workflow")
new_moves = []
if context is None:
context = {}
seq_obj = self.pool.get('ir.sequence')
for picking, todo in self._chain_compute(cr, uid, moves, context=context).items():
ptype = todo[0][1][5] and todo[0][1][5] or location_obj.picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])
if picking:
# name of new picking according to its type
if ptype == 'internal':
new_pick_name = seq_obj.get(cr, uid,'stock.picking')
else :
new_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + ptype)
pickid = self.<API key>(cr, uid, new_pick_name, picking, ptype, todo, context=context)
# Need to check name of old picking because it always considers picking as "OUT" when created from Sales Order
old_ptype = location_obj.picking_type_get(cr, uid, picking.move_lines[0].location_id, picking.move_lines[0].location_dest_id)
if old_ptype != picking.type:
old_pick_name = seq_obj.get(cr, uid, 'stock.picking.' + old_ptype)
self.pool.get('stock.picking').write(cr, uid, [picking.id], {'name': old_pick_name, 'type': old_ptype}, context=context)
else:
pickid = False
for move, (loc, dummy, delay, dummy, company_id, ptype, invoice_state) in todo:
new_id = move_obj.copy(cr, uid, move.id, {
'location_id': move.location_dest_id.id,
'location_dest_id': loc.id,
'date': time.strftime('%Y-%m-%d'),
'picking_id': pickid,
'state': 'waiting',
'company_id': company_id or res_obj.<API key>(cr, uid, 'stock.company', context=context) ,
'move_history_ids': [],
'date_expected': (datetime.strptime(move.date, '%Y-%m-%d %H:%M:%S') + relativedelta(days=delay or 0)).strftime('%Y-%m-%d'),
'move_history_ids2': []}
)
move_obj.write(cr, uid, [move.id], {
'move_dest_id': new_id,
'move_history_ids': [(4, new_id)]
})
new_moves.append(self.browse(cr, uid, [new_id])[0])
if pickid:
wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)
if new_moves:
new_moves += self.<API key>(cr, uid, new_moves, context)
return new_moves
def action_confirm(self, cr, uid, ids, context=None):
""" Confirms stock move.
@return: List of ids.
"""
moves = self.browse(cr, uid, ids, context=context)
self.write(cr, uid, ids, {'state': 'confirmed'})
self.<API key>(cr, uid, moves, context)
return []
def action_assign(self, cr, uid, ids, *args):
""" Changes state to confirmed or waiting.
@return: List of values
"""
todo = []
for move in self.browse(cr, uid, ids):
if move.state in ('confirmed', 'waiting'):
todo.append(move.id)
res = self.check_assign(cr, uid, todo)
return res
def force_assign(self, cr, uid, ids, context=None):
""" Changes the state to assigned.
@return: True
"""
self.write(cr, uid, ids, {'state': 'assigned'})
wf_service = netsvc.LocalService('workflow')
for move in self.browse(cr, uid, ids, context):
if move.picking_id:
wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
return True
def cancel_assign(self, cr, uid, ids, context=None):
""" Changes the state to confirmed.
@return: True
"""
self.write(cr, uid, ids, {'state': 'confirmed'})
# fix for bug lp:707031
# called write of related picking because changing move availability does
# not trigger workflow of picking in order to change the state of picking
wf_service = netsvc.LocalService('workflow')
for move in self.browse(cr, uid, ids, context):
if move.picking_id:
wf_service.trg_write(uid, 'stock.picking', move.picking_id.id, cr)
return True
# Duplicate stock.move
def check_assign(self, cr, uid, ids, context=None):
""" Checks the product type and accordingly writes the state.
@return: No. of moves done
"""
done = []
count = 0
pickings = {}
if context is None:
context = {}
for move in self.browse(cr, uid, ids, context=context):
if move.product_id.type == 'consu' or move.location_id.usage == 'supplier':
if move.state in ('confirmed', 'waiting'):
done.append(move.id)
pickings[move.picking_id.id] = 1
continue
if move.state in ('confirmed', 'waiting'):
# Important: we must pass lock=True to _product_reserve() to avoid race conditions and double reservations
res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id}, lock=True)
if res:
#<API key> depends on the next status for correct functioning
#the test does not work correctly if the same product occurs multiple times
#in the same order. This is e.g. the case when using the button 'split in two' of
#the stock outgoing form
self.write(cr, uid, [move.id], {'state':'assigned'})
done.append(move.id)
pickings[move.picking_id.id] = 1
r = res.pop(0)
product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, ids, move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty']
cr.execute('update stock_move set location_id=%s, product_qty=%s, product_uos_qty=%s where id=%s', (r[1], r[0],product_uos_qty, move.id))
while res:
r = res.pop(0)
product_uos_qty = self.pool.get('stock.move').onchange_quantity(cr, uid, ids, move.product_id.id, r[0], move.product_id.uom_id.id, move.product_id.uos_id.id)['value']['product_uos_qty']
move_id = self.copy(cr, uid, move.id, {'product_uos_qty': product_uos_qty, 'product_qty': r[0], 'location_id': r[1]})
done.append(move_id)
if done:
count += len(done)
self.write(cr, uid, done, {'state': 'assigned'})
if count:
for pick_id in pickings:
wf_service = netsvc.LocalService("workflow")
wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
return count
def setlast_tracking(self, cr, uid, ids, context=None):
tracking_obj = self.pool.get('stock.tracking')
picking = self.browse(cr, uid, ids, context=context)[0].picking_id
if picking:
last_track = [line.tracking_id.id for line in picking.move_lines if line.tracking_id]
if not last_track:
last_track = tracking_obj.create(cr, uid, {}, context=context)
else:
last_track.sort()
last_track = last_track[-1]
self.write(cr, uid, ids, {'tracking_id': last_track})
return True
# Cancel move => cancel others move and pickings
def action_cancel(self, cr, uid, ids, context=None):
""" Cancels the moves and if all moves are cancelled it cancels the picking.
@return: True
"""
if not len(ids):
return True
if context is None:
context = {}
pickings = set()
for move in self.browse(cr, uid, ids, context=context):
if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):
if move.picking_id:
pickings.add(move.picking_id.id)
if move.move_dest_id and move.move_dest_id.state == 'waiting':
self.write(cr, uid, [move.move_dest_id.id], {'state': 'confirmed'}, context=context)
if context.get('call_unlink',False) and move.move_dest_id.picking_id:
wf_service = netsvc.LocalService("workflow")
wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False}, context=context)
if not context.get('call_unlink',False):
for pick in self.pool.get('stock.picking').browse(cr, uid, list(pickings), context=context):
if all(move.state == 'cancel' for move in pick.move_lines):
self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'}, context=context)
wf_service = netsvc.LocalService("workflow")
for id in ids:
wf_service.trg_trigger(uid, 'stock.move', id, cr)
return True
def <API key>(self, cr, uid, move, context=None):
"""
Return the accounts and journal to use to post Journal Entries for the real-time
valuation of the move.
:param context: context dictionary that can explicitly mention the company to consider via the 'force_company' key
:raise: osv.except_osv() is any mandatory account or journal is not defined.
"""
product_obj=self.pool.get('product.product')
accounts = product_obj.<API key>(cr, uid, move.product_id.id, context)
if move.location_id.<API key>:
acc_src = move.location_id.<API key>.id
else:
acc_src = accounts['stock_account_input']
if move.location_dest_id.<API key>:
acc_dest = move.location_dest_id.<API key>.id
else:
acc_dest = accounts['<API key>']
acc_valuation = accounts.get('<API key>', False)
journal_id = accounts['stock_journal']
if acc_dest == acc_valuation:
raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Output Account of this product and Valuation account on category of this product are same.'))
if acc_src == acc_valuation:
raise osv.except_osv(_('Error!'), _('Cannot create Journal Entry, Input Account of this product and Valuation account on category of this product are same.'))
if not acc_src:
raise osv.except_osv(_('Error!'), _('Please define stock input account for this product or its category: "%s" (id: %d)') % \
(move.product_id.name, move.product_id.id,))
if not acc_dest:
raise osv.except_osv(_('Error!'), _('Please define stock output account for this product or its category: "%s" (id: %d)') % \
(move.product_id.name, move.product_id.id,))
if not journal_id:
raise osv.except_osv(_('Error!'), _('Please define journal on the product category: "%s" (id: %d)') % \
(move.product_id.categ_id.name, move.product_id.categ_id.id,))
if not acc_valuation:
raise osv.except_osv(_('Error!'), _('Please define inventory valuation account on the product category: "%s" (id: %d)') % \
(move.product_id.categ_id.name, move.product_id.categ_id.id,))
return journal_id, acc_src, acc_dest, acc_valuation
def <API key>(self, cr, uid, move, context=None):
"""
Return the reference amount and reference currency representing the inventory valuation for this move.
These reference values should possibly be converted before being posted in Journals to adapt to the primary
and secondary currencies of the relevant accounts.
"""
product_uom_obj = self.pool.get('product.uom')
# by default the reference currency is that of the move's company
<API key> = move.company_id.currency_id.id
default_uom = move.product_id.uom_id.id
qty = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)
# if product is set to average price and a specific value was entered in the picking wizard,
# we use it
if move.product_id.cost_method == 'average' and move.price_unit:
reference_amount = qty * move.price_unit
<API key> = move.price_currency_id.id or <API key>
# Otherwise we default to the company's valuation price type, considering that the values of the
# valuation field are expressed in the default currency of the move's company.
else:
if context is None:
context = {}
currency_ctx = dict(context, currency_id = move.company_id.currency_id.id)
amount_unit = move.product_id.price_get('standard_price', context=currency_ctx)[move.product_id.id]
reference_amount = amount_unit * qty
return reference_amount, <API key>
def <API key>(self, cr, uid, move, context=None):
"""
Generate the appropriate accounting moves if the product being moves is subject
to real_time valuation tracking, and the source or destination location is
a transit location or is outside of the company.
"""
if move.product_id.valuation == 'real_time': # FIXME: product valuation should perhaps be a property?
if context is None:
context = {}
src_company_ctx = dict(context,force_company=move.location_id.company_id.id)
dest_company_ctx = dict(context,force_company=move.location_dest_id.company_id.id)
account_moves = []
# Outgoing moves (or cross-company output part)
if move.location_id.company_id \
and (move.location_id.usage == 'internal' and move.location_dest_id.usage != 'internal'\
or move.location_id.company_id != move.location_dest_id.company_id):
journal_id, acc_src, acc_dest, acc_valuation = self.<API key>(cr, uid, move, src_company_ctx)
reference_amount, <API key> = self.<API key>(cr, uid, move, src_company_ctx)
#returning goods to supplier
if move.location_dest_id.usage == 'supplier':
account_moves += [(journal_id, self.<API key>(cr, uid, move, acc_valuation, acc_src, reference_amount, <API key>, context))]
else:
account_moves += [(journal_id, self.<API key>(cr, uid, move, acc_valuation, acc_dest, reference_amount, <API key>, context))]
# Incoming moves (or cross-company input part)
if move.location_dest_id.company_id \
and (move.location_id.usage != 'internal' and move.location_dest_id.usage == 'internal'\
or move.location_id.company_id != move.location_dest_id.company_id):
journal_id, acc_src, acc_dest, acc_valuation = self.<API key>(cr, uid, move, dest_company_ctx)
reference_amount, <API key> = self.<API key>(cr, uid, move, src_company_ctx)
#goods return from customer
if move.location_id.usage == 'customer':
account_moves += [(journal_id, self.<API key>(cr, uid, move, acc_dest, acc_valuation, reference_amount, <API key>, context))]
else:
account_moves += [(journal_id, self.<API key>(cr, uid, move, acc_src, acc_valuation, reference_amount, <API key>, context))]
move_obj = self.pool.get('account.move')
for j_id, move_lines in account_moves:
move_obj.create(cr, uid,
{
'journal_id': j_id,
'line_id': move_lines,
'ref': move.picking_id and move.picking_id.name}, context=context)
def action_done(self, cr, uid, ids, context=None):
""" Makes the move done and if all moves are done, it will finish the picking.
@return:
"""
picking_ids = []
move_ids = []
wf_service = netsvc.LocalService("workflow")
if context is None:
context = {}
todo = []
for move in self.browse(cr, uid, ids, context=context):
if move.state=="draft":
todo.append(move.id)
if todo:
self.action_confirm(cr, uid, todo, context=context)
todo = []
for move in self.browse(cr, uid, ids, context=context):
if move.state in ['done','cancel']:
continue
move_ids.append(move.id)
if move.picking_id:
picking_ids.append(move.picking_id.id)
if move.move_dest_id.id and (move.state != 'done'):
# Downstream move should only be triggered if this move is the last pending upstream move
<API key> = self.search(cr, uid, [('id','!=',move.id),('state','not in',['done','cancel']),
('move_dest_id','=',move.move_dest_id.id)], context=context)
if not <API key>:
self.write(cr, uid, [move.id], {'move_history_ids': [(4, move.move_dest_id.id)]})
if move.move_dest_id.state in ('waiting', 'confirmed'):
self.force_assign(cr, uid, [move.move_dest_id.id], context=context)
if move.move_dest_id.picking_id:
wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)
if move.move_dest_id.auto_validate:
self.action_done(cr, uid, [move.move_dest_id.id], context=context)
self.<API key>(cr, uid, move, context=context)
if move.state not in ('confirmed','done','assigned'):
todo.append(move.id)
if todo:
self.action_confirm(cr, uid, todo, context=context)
self.write(cr, uid, move_ids, {'state': 'done', 'date': time.strftime(<API key>)}, context=context)
for id in move_ids:
wf_service.trg_trigger(uid, 'stock.move', id, cr)
for pick_id in picking_ids:
wf_service.trg_write(uid, 'stock.picking', pick_id, cr)
return True
def <API key>(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, <API key>, context=None):
"""
Generate the account.move.line values to post to track the stock valuation difference due to the
processing of the given stock move.
"""
# prepare default values considering that the destination accounts have the <API key> as their main currency
partner_id = (move.picking_id.partner_id and self.pool.get('res.partner').<API key>(move.picking_id.partner_id).id) or False
debit_line_vals = {
'name': move.name,
'product_id': move.product_id and move.product_id.id or False,
'quantity': move.product_qty,
'ref': move.picking_id and move.picking_id.name or False,
'date': time.strftime('%Y-%m-%d'),
'partner_id': partner_id,
'debit': reference_amount,
'account_id': dest_account_id,
}
credit_line_vals = {
'name': move.name,
'product_id': move.product_id and move.product_id.id or False,
'quantity': move.product_qty,
'ref': move.picking_id and move.picking_id.name or False,
'date': time.strftime('%Y-%m-%d'),
'partner_id': partner_id,
'credit': reference_amount,
'account_id': src_account_id,
}
# if we are posting to accounts in a different currency, provide correct values in both currencies correctly
# when compatible with the optional secondary currency on the account.
# Financial Accounts only accept amounts in secondary currencies if there's no secondary currency on the account
# or if it's the same as that of the secondary amount being posted.
account_obj = self.pool.get('account.account')
src_acct, dest_acct = account_obj.browse(cr, uid, [src_account_id, dest_account_id], context=context)
<API key> = src_acct.company_id.currency_id.id
<API key> = dest_acct.company_id.currency_id.id
cur_obj = self.pool.get('res.currency')
if <API key> != <API key>:
# fix credit line:
credit_line_vals['credit'] = cur_obj.compute(cr, uid, <API key>, <API key>, reference_amount, context=context)
if (not src_acct.currency_id) or src_acct.currency_id.id == <API key>:
credit_line_vals.update(currency_id=<API key>, amount_currency=-reference_amount)
if <API key> != <API key>:
# fix debit line:
debit_line_vals['debit'] = cur_obj.compute(cr, uid, <API key>, <API key>, reference_amount, context=context)
if (not dest_acct.currency_id) or dest_acct.currency_id.id == <API key>:
debit_line_vals.update(currency_id=<API key>, amount_currency=reference_amount)
return [(0, 0, debit_line_vals), (0, 0, credit_line_vals)]
def unlink(self, cr, uid, ids, context=None):
if context is None:
context = {}
ctx = context.copy()
for move in self.browse(cr, uid, ids, context=context):
if move.state != 'draft' and not ctx.get('call_unlink', False):
raise osv.except_osv(_('User Error!'), _('You can only delete draft moves.'))
return super(stock_move, self).unlink(
cr, uid, ids, context=ctx)
# _create_lot function is not used anywhere
def _create_lot(self, cr, uid, ids, product_id, prefix=False):
""" Creates production lot
@return: Production lot id
"""
prodlot_obj = self.pool.get('stock.production.lot')
prodlot_id = prodlot_obj.create(cr, uid, {'prefix': prefix, 'product_id': product_id})
return prodlot_id
def action_scrap(self, cr, uid, ids, quantity, location_id, context=None):
""" Move the scrap/damaged product into scrap location
@param cr: the database cursor
@param uid: the user id
@param ids: ids of stock move object to be scrapped
@param quantity : specify scrap qty
@param location_id : specify scrap location
@param context: context arguments
@return: Scraped lines
"""
#quantity should in MOVE UOM
if quantity <= 0:
raise osv.except_osv(_('Warning!'), _('Please provide a positive quantity to scrap.'))
res = []
for move in self.browse(cr, uid, ids, context=context):
source_location = move.location_id
if move.state == 'done':
source_location = move.location_dest_id
if source_location.usage != 'internal':
#restrict to scrap from a virtual location because it's meaningless and it may introduce errors in stock ('creating' new products from nowhere)
raise osv.except_osv(_('Error!'), _('Forbidden operation: it is not allowed to scrap products from a virtual location.'))
move_qty = move.product_qty
uos_qty = quantity / move_qty * move.product_uos_qty
default_val = {
'location_id': source_location.id,
'product_qty': quantity,
'product_uos_qty': uos_qty,
'state': move.state,
'scrapped': True,
'location_dest_id': location_id,
'tracking_id': move.tracking_id.id,
'prodlot_id': move.prodlot_id.id,
}
new_move = self.copy(cr, uid, move.id, default_val)
res += [new_move]
product_obj = self.pool.get('product.product')
for product in product_obj.browse(cr, uid, [move.product_id.id], context=context):
if move.picking_id:
uom = product.uom_id.name if product.uom_id else ''
message = _("%s %s %s has been <b>moved to</b> scrap.") % (quantity, uom, product.name)
move.picking_id.message_post(body=message)
self.action_done(cr, uid, res, context=context)
return res
# action_split function is not used anywhere
# FIXME: deprecate this method
def action_split(self, cr, uid, ids, quantity, split_by_qty=1, prefix=False, with_lot=True, context=None):
""" Split Stock Move lines into production lot which specified split by quantity.
@param cr: the database cursor
@param uid: the user id
@param ids: ids of stock move object to be splited
@param split_by_qty : specify split by qty
@param prefix : specify prefix of production lot
@param with_lot : if true, prodcution lot will assign for split line otherwise not.
@param context: context arguments
@return: Splited move lines
"""
if context is None:
context = {}
if quantity <= 0:
raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
res = []
for move in self.browse(cr, uid, ids, context=context):
if split_by_qty <= 0 or quantity == 0:
return res
uos_qty = split_by_qty / move.product_qty * move.product_uos_qty
quantity_rest = quantity % split_by_qty
uos_qty_rest = split_by_qty / move.product_qty * move.product_uos_qty
update_val = {
'product_qty': split_by_qty,
'product_uos_qty': uos_qty,
}
for idx in range(int(quantity//split_by_qty)):
if not idx and move.product_qty<=quantity:
current_move = move.id
else:
current_move = self.copy(cr, uid, move.id, {'state': move.state})
res.append(current_move)
if with_lot:
update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
self.write(cr, uid, [current_move], update_val)
if quantity_rest > 0:
idx = int(quantity//split_by_qty)
update_val['product_qty'] = quantity_rest
update_val['product_uos_qty'] = uos_qty_rest
if not idx and move.product_qty<=quantity:
current_move = move.id
else:
current_move = self.copy(cr, uid, move.id, {'state': move.state})
res.append(current_move)
if with_lot:
update_val['prodlot_id'] = self._create_lot(cr, uid, [current_move], move.product_id.id)
self.write(cr, uid, [current_move], update_val)
return res
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None):
""" Consumed product with specific quatity from specific source location
@param cr: the database cursor
@param uid: the user id
@param ids: ids of stock move object to be consumed
@param quantity : specify consume quantity
@param location_id : specify source location
@param context: context arguments
@return: Consumed lines
"""
#quantity should in MOVE UOM
if context is None:
context = {}
if quantity <= 0:
raise osv.except_osv(_('Warning!'), _('Please provide proper quantity.'))
res = []
for move in self.browse(cr, uid, ids, context=context):
move_qty = move.product_qty
if move_qty <= 0:
raise osv.except_osv(_('Error!'), _('Cannot consume a move with negative or zero quantity.'))
quantity_rest = move.product_qty
quantity_rest -= quantity
uos_qty_rest = quantity_rest / move_qty * move.product_uos_qty
if quantity_rest <= 0:
quantity_rest = 0
uos_qty_rest = 0
quantity = move.product_qty
uos_qty = quantity / move_qty * move.product_uos_qty
if float_compare(quantity_rest, 0, precision_rounding=move.product_id.uom_id.rounding):
default_val = {
'product_qty': quantity,
'product_uos_qty': uos_qty,
'state': move.state,
'location_id': location_id or move.location_id.id,
}
current_move = self.copy(cr, uid, move.id, default_val)
res += [current_move]
update_val = {}
update_val['product_qty'] = quantity_rest
update_val['product_uos_qty'] = uos_qty_rest
self.write(cr, uid, [move.id], update_val)
else:
quantity_rest = quantity
uos_qty_rest = uos_qty
res += [move.id]
update_val = {
'product_qty' : quantity_rest,
'product_uos_qty' : uos_qty_rest,
'location_id': location_id or move.location_id.id,
}
self.write(cr, uid, [move.id], update_val)
self.action_done(cr, uid, res, context=context)
return res
# FIXME: needs refactoring, this code is partially duplicated in stock_picking.do_partial()!
def do_partial(self, cr, uid, ids, partial_datas, context=None):
""" Makes partial pickings and moves done.
@param partial_datas: Dictionary containing details of partial picking
like partner_id, delivery_date, delivery
moves with product_id, product_qty, uom
"""
res = {}
picking_obj = self.pool.get('stock.picking')
product_obj = self.pool.get('product.product')
currency_obj = self.pool.get('res.currency')
uom_obj = self.pool.get('product.uom')
wf_service = netsvc.LocalService("workflow")
if context is None:
context = {}
complete, too_many, too_few = [], [], []
move_product_qty = {}
prodlot_ids = {}
for move in self.browse(cr, uid, ids, context=context):
if move.state in ('done', 'cancel'):
continue
partial_data = partial_datas.get('move%s'%(move.id), False)
assert partial_data, _('Missing partial picking data for move #%s.') % (move.id)
product_qty = partial_data.get('product_qty',0.0)
move_product_qty[move.id] = product_qty
product_uom = partial_data.get('product_uom',False)
product_price = partial_data.get('product_price',0.0)
product_currency = partial_data.get('product_currency',False)
prodlot_ids[move.id] = partial_data.get('prodlot_id')
if move.product_qty == product_qty:
complete.append(move)
elif move.product_qty > product_qty:
too_few.append(move)
else:
too_many.append(move)
# Average price computation
if (move.picking_id.type == 'in') and (move.product_id.cost_method == 'average'):
product = product_obj.browse(cr, uid, move.product_id.id)
move_currency_id = move.company_id.currency_id.id
context['currency_id'] = move_currency_id
qty = uom_obj._compute_qty(cr, uid, product_uom, product_qty, product.uom_id.id)
if qty > 0:
new_price = currency_obj.compute(cr, uid, product_currency,
move_currency_id, product_price, round=False)
new_price = uom_obj._compute_price(cr, uid, product_uom, new_price,
product.uom_id.id)
if product.qty_available <= 0:
new_std_price = new_price
else:
# Get the standard price
amount_unit = product.price_get('standard_price', context=context)[product.id]
new_std_price = ((amount_unit * product.qty_available)\
+ (new_price * qty))/(product.qty_available + qty)
product_obj.write(cr, uid, [product.id],{'standard_price': new_std_price})
# Record the values that were chosen in the wizard, so they can be
# used for inventory valuation if real-time valuation is enabled.
self.write(cr, uid, [move.id],
{'price_unit': product_price,
'price_currency_id': product_currency,
})
for move in too_few:
product_qty = move_product_qty[move.id]
if product_qty != 0:
defaults = {
'product_qty' : product_qty,
'product_uos_qty': product_qty,
'picking_id' : move.picking_id.id,
'state': 'assigned',
'move_dest_id': False,
'price_unit': move.price_unit,
}
prodlot_id = prodlot_ids[move.id]
if prodlot_id:
defaults.update(prodlot_id=prodlot_id)
new_move = self.copy(cr, uid, move.id, defaults)
complete.append(self.browse(cr, uid, new_move))
self.write(cr, uid, [move.id],
{
'product_qty': move.product_qty - product_qty,
'product_uos_qty': move.product_qty - product_qty,
'prodlot_id': False,
'tracking_id': False,
})
for move in too_many:
self.write(cr, uid, [move.id],
{
'product_qty': move.product_qty,
'product_uos_qty': move.product_qty,
})
complete.append(move)
for move in complete:
if prodlot_ids.get(move.id):
self.write(cr, uid, [move.id],{'prodlot_id': prodlot_ids.get(move.id)})
self.action_done(cr, uid, [move.id], context=context)
if move.picking_id.id :
# TOCHECK : Done picking if all moves are done
cr.execute("""
SELECT move.id FROM stock_picking pick
RIGHT JOIN stock_move move ON move.picking_id = pick.id AND move.state = %s
WHERE pick.id = %s""",
('done', move.picking_id.id))
res = cr.fetchall()
if len(res) == len(move.picking_id.move_lines):
picking_obj.action_move(cr, uid, [move.picking_id.id])
wf_service.trg_validate(uid, 'stock.picking', move.picking_id.id, 'button_done', cr)
return [move.id for move in complete]
stock_move()
class stock_inventory(osv.osv):
_name = "stock.inventory"
_description = "Inventory"
_columns = {
'name': fields.char('Inventory Reference', size=64, required=True, readonly=True, states={'draft': [('readonly', False)]}),
'date': fields.datetime('Creation Date', required=True, readonly=True, states={'draft': [('readonly', False)]}),
'date_done': fields.datetime('Date done'),
'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
'move_ids': fields.many2many('stock.move', '<API key>', 'inventory_id', 'move_id', 'Created Moves'),
'state': fields.selection( (('draft', 'Draft'), ('cancel','Cancelled'), ('confirm','Confirmed'), ('done', 'Done')), 'Status', readonly=True, select=True),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True, readonly=True, states={'draft':[('readonly',False)]}),
}
_defaults = {
'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
'state': 'draft',
'company_id': lambda self,cr,uid,c: self.pool.get('res.company').<API key>(cr, uid, 'stock.inventory', context=c)
}
def copy(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
default = default.copy()
default.update({'move_ids': [], 'date_done': False})
return super(stock_inventory, self).copy(cr, uid, id, default, context=context)
def <API key>(self, cr, uid, inventory_line, move_vals):
""" Creates a stock move from an inventory line
@param inventory_line:
@param move_vals:
@return:
"""
return self.pool.get('stock.move').create(cr, uid, move_vals)
def action_done(self, cr, uid, ids, context=None):
""" Finish the inventory
@return: True
"""
if context is None:
context = {}
move_obj = self.pool.get('stock.move')
for inv in self.browse(cr, uid, ids, context=context):
move_obj.action_done(cr, uid, [x.id for x in inv.move_ids], context=context)
self.write(cr, uid, [inv.id], {'state':'done', 'date_done': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context)
return True
def action_confirm(self, cr, uid, ids, context=None):
""" Confirm the inventory and writes its finished date
@return: True
"""
if context is None:
context = {}
# to perform the correct inventory corrections we need analyze stock location by
# location, never recursively, so we use a special context
product_context = dict(context, compute_child=False)
location_obj = self.pool.get('stock.location')
for inv in self.browse(cr, uid, ids, context=context):
move_ids = []
for line in inv.inventory_line_id:
pid = line.product_id.id
product_context.update(uom=line.product_uom.id, to_date=inv.date, date=inv.date, prodlot_id=line.prod_lot_id.id)
amount = location_obj._product_get(cr, uid, line.location_id.id, [pid], product_context)[pid]
change = line.product_qty - amount
lot_id = line.prod_lot_id.id
if change:
location_id = line.product_id.<API key>.id
value = {
'name': _('INV:') + (line.inventory_id.name or ''),
'product_id': line.product_id.id,
'product_uom': line.product_uom.id,
'prodlot_id': lot_id,
'date': inv.date,
}
if change > 0:
value.update( {
'product_qty': change,
'location_id': location_id,
'location_dest_id': line.location_id.id,
})
else:
value.update( {
'product_qty': -change,
'location_id': line.location_id.id,
'location_dest_id': location_id,
})
move_ids.append(self.<API key>(cr, uid, line, value))
self.write(cr, uid, [inv.id], {'state': 'confirm', 'move_ids': [(6, 0, move_ids)]})
self.pool.get('stock.move').action_confirm(cr, uid, move_ids, context=context)
return True
def action_cancel_draft(self, cr, uid, ids, context=None):
""" Cancels the stock move and change inventory state to draft.
@return: True
"""
for inv in self.browse(cr, uid, ids, context=context):
self.pool.get('stock.move').action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
self.write(cr, uid, [inv.id], {'state':'draft'}, context=context)
return True
def <API key>(self, cr, uid, ids, context=None):
""" Cancels both stock move and inventory
@return: True
"""
move_obj = self.pool.get('stock.move')
account_move_obj = self.pool.get('account.move')
for inv in self.browse(cr, uid, ids, context=context):
move_obj.action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context)
for move in inv.move_ids:
account_move_ids = account_move_obj.search(cr, uid, [('name', '=', move.name)])
if account_move_ids:
account_move_data_l = account_move_obj.read(cr, uid, account_move_ids, ['state'], context=context)
for account_move in account_move_data_l:
if account_move['state'] == 'posted':
raise osv.except_osv(_('User Error!'),
_('In order to cancel this inventory, you must first unpost related journal entries.'))
account_move_obj.unlink(cr, uid, [account_move['id']], context=context)
self.write(cr, uid, [inv.id], {'state': 'cancel'}, context=context)
return True
stock_inventory()
class <API key>(osv.osv):
_name = "stock.inventory.line"
_description = "Inventory Line"
_rec_name = "inventory_id"
_columns = {
'inventory_id': fields.many2one('stock.inventory', 'Inventory', ondelete='cascade', select=True),
'location_id': fields.many2one('stock.location', 'Location', required=True),
'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True),
'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
'company_id': fields.related('inventory_id','company_id',type='many2one',relation='res.company',string='Company',store=True, select=True, readonly=True),
'prod_lot_id': fields.many2one('stock.production.lot', 'Serial Number', domain="[('product_id','=',product_id)]"),
'state': fields.related('inventory_id','state',type='char',string='Status',readonly=True),
}
def <API key>(self, cr, uid, context=None):
try:
location_model, location_id = self.pool.get('ir.model.data').<API key>(cr, uid, 'stock', '<API key>')
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [location_id], 'read', context=context)
except (orm.except_orm, ValueError):
location_id = False
return location_id
_defaults = {
'location_id': <API key>
}
def <API key>(self, cr, uid, ids, location_id, product, uom=False, to_date=False):
""" Changes UoM and name if product_id changes.
@param location_id: Location id
@param product: Changed product_id
@param uom: UoM product
@return: Dictionary of changed values
"""
if not product:
return {'value': {'product_qty': 0.0, 'product_uom': False, 'prod_lot_id': False}}
obj_product = self.pool.get('product.product').browse(cr, uid, product)
uom = uom or obj_product.uom_id.id
amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date, 'compute_child': False})[product]
result = {'product_qty': amount, 'product_uom': uom, 'prod_lot_id': False}
return {'value': result}
<API key>()
# Stock Warehouse
class stock_warehouse(osv.osv):
_name = "stock.warehouse"
_description = "Warehouse"
_columns = {
'name': fields.char('Name', size=128, required=True, select=True),
'company_id': fields.many2one('res.company', 'Company', required=True, select=True),
'partner_id': fields.many2one('res.partner', 'Owner Address'),
'lot_input_id': fields.many2one('stock.location', 'Location Input', required=True, domain=[('usage','<>','view')]),
'lot_stock_id': fields.many2one('stock.location', 'Location Stock', required=True, domain=[('usage','=','internal')]),
'lot_output_id': fields.many2one('stock.location', 'Location Output', required=True, domain=[('usage','<>','view')]),
}
def <API key>(self, cr, uid, context=None):
try:
<API key>, lot_input_stock_id = self.pool.get('ir.model.data').<API key>(cr, uid, 'stock', '<API key>')
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [lot_input_stock_id], 'read', context=context)
except (ValueError, orm.except_orm):
# the user does not have read access on the location or it does not exists
lot_input_stock_id = False
return lot_input_stock_id
def <API key>(self, cr, uid, context=None):
try:
lot_output_model, lot_output_id = self.pool.get('ir.model.data').<API key>(cr, uid, 'stock', '<API key>')
with tools.mute_logger('openerp.osv.orm'):
self.pool.get('stock.location').check_access_rule(cr, uid, [lot_output_id], 'read', context=context)
except (ValueError, orm.except_orm):
# the user does not have read access on the location or it does not exists
lot_output_id = False
return lot_output_id
_defaults = {
'company_id': lambda self, cr, uid, c: self.pool.get('res.company').<API key>(cr, uid, 'stock.inventory', context=c),
'lot_input_id': <API key>,
'lot_stock_id': <API key>,
'lot_output_id': <API key>,
}
stock_warehouse()
# "Empty" Classes that are used to vary from the original stock.picking (that are dedicated to the internal pickings)
# in order to offer a different usability with different views, labels, available reports/wizards...
class stock_picking_in(osv.osv):
_name = "stock.picking.in"
_inherit = "stock.picking"
_table = "stock_picking"
_description = "Incoming Shipments"
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
def check_access_rights(self, cr, uid, operation, raise_exception=True):
#override in order to redirect the check of acces rights on the stock.picking object
return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
def check_access_rule(self, cr, uid, ids, operation, context=None):
#override in order to redirect the check of acces rules on the stock.picking object
return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
#override in order to trigger the workflow of stock.picking at the end of create, write and unlink operation
#instead of it's own workflow (which is not existing)
return self.pool.get('stock.picking')._workflow_trigger(cr, uid, ids, trigger, context=context)
def _workflow_signal(self, cr, uid, ids, signal, context=None):
#override in order to fire the workflow signal on given stock.picking workflow instance
#instead of it's own workflow (which is not existing)
return self.pool.get('stock.picking')._workflow_signal(cr, uid, ids, signal, context=context)
def message_post(self, *args, **kwargs):
"""Post the message on stock.picking to be able to see it in the form view when using the chatter"""
return self.pool.get('stock.picking').message_post(*args, **kwargs)
def message_subscribe(self, *args, **kwargs):
"""Send the subscribe action on stock.picking model as it uses _name in request"""
return self.pool.get('stock.picking').message_subscribe(*args, **kwargs)
def message_unsubscribe(self, *args, **kwargs):
"""Send the unsubscribe action on stock.picking model to match with subscribe"""
return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs)
def default_get(self, cr, uid, fields_list, context=None):
# merge defaults from stock.picking with possible defaults defined on stock.picking.in
defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context)
in_defaults = super(stock_picking_in, self).default_get(cr, uid, fields_list, context=context)
defaults.update(in_defaults)
return defaults
_columns = {
'backorder_id': fields.many2one('stock.picking.in', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
'state': fields.selection(
[('draft', 'Draft'),
('auto', 'Waiting Another Operation'),
('confirmed', 'Waiting Availability'),
('assigned', 'Ready to Receive'),
('done', 'Received'),
('cancel', 'Cancelled'),],
'Status', readonly=True, select=True,
help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
* Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
* Waiting Availability: still waiting for the availability of products\n
* Ready to Receive: products reserved, simply waiting for confirmation.\n
* Received: has been processed, can't be modified or cancelled anymore\n
* Cancelled: has been cancelled, can't be confirmed anymore"""),
}
_defaults = {
'type': 'in',
}
class stock_picking_out(osv.osv):
_name = "stock.picking.out"
_inherit = "stock.picking"
_table = "stock_picking"
_description = "Delivery Orders"
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
return self.pool.get('stock.picking').search(cr, user, args, offset, limit, order, context, count)
def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
return self.pool.get('stock.picking').read(cr, uid, ids, fields=fields, context=context, load=load)
def check_access_rights(self, cr, uid, operation, raise_exception=True):
#override in order to redirect the check of acces rights on the stock.picking object
return self.pool.get('stock.picking').check_access_rights(cr, uid, operation, raise_exception=raise_exception)
def check_access_rule(self, cr, uid, ids, operation, context=None):
#override in order to redirect the check of acces rules on the stock.picking object
return self.pool.get('stock.picking').check_access_rule(cr, uid, ids, operation, context=context)
def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
#override in order to trigger the workflow of stock.picking at the end of create, write and unlink operation
#instead of it's own workflow (which is not existing)
return self.pool.get('stock.picking')._workflow_trigger(cr, uid, ids, trigger, context=context)
def _workflow_signal(self, cr, uid, ids, signal, context=None):
#override in order to fire the workflow signal on given stock.picking workflow instance
#instead of it's own workflow (which is not existing)
return self.pool.get('stock.picking')._workflow_signal(cr, uid, ids, signal, context=context)
def message_post(self, *args, **kwargs):
"""Post the message on stock.picking to be able to see it in the form view when using the chatter"""
return self.pool.get('stock.picking').message_post(*args, **kwargs)
def message_subscribe(self, *args, **kwargs):
"""Send the subscribe action on stock.picking model as it uses _name in request"""
return self.pool.get('stock.picking').message_subscribe(*args, **kwargs)
def message_unsubscribe(self, *args, **kwargs):
"""Send the unsubscribe action on stock.picking model to match with subscribe"""
return self.pool.get('stock.picking').message_unsubscribe(*args, **kwargs)
def default_get(self, cr, uid, fields_list, context=None):
# merge defaults from stock.picking with possible defaults defined on stock.picking.out
defaults = self.pool['stock.picking'].default_get(cr, uid, fields_list, context=context)
out_defaults = super(stock_picking_out, self).default_get(cr, uid, fields_list, context=context)
defaults.update(out_defaults)
return defaults
_columns = {
'backorder_id': fields.many2one('stock.picking.out', 'Back Order of', states={'done':[('readonly', True)], 'cancel':[('readonly',True)]}, help="If this shipment was split, then this field links to the shipment which contains the already processed part.", select=True),
'state': fields.selection(
[('draft', 'Draft'),
('auto', 'Waiting Another Operation'),
('confirmed', 'Waiting Availability'),
('assigned', 'Ready to Deliver'),
('done', 'Delivered'),
('cancel', 'Cancelled'),],
'Status', readonly=True, select=True,
help="""* Draft: not confirmed yet and will not be scheduled until confirmed\n
* Waiting Another Operation: waiting for another move to proceed before it becomes automatically available (e.g. in Make-To-Order flows)\n
* Waiting Availability: still waiting for the availability of products\n
* Ready to Deliver: products reserved, simply waiting for confirmation.\n
* Delivered: has been processed, can't be modified or cancelled anymore\n
* Cancelled: has been cancelled, can't be confirmed anymore"""),
}
_defaults = {
'type': 'out',
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
#include <kotaka/paths/account.h>
#include <kotaka/paths/verb.h>
inherit LIB_VERB;
inherit "/lib/sort";
inherit "~/lib/banlist";
inherit "~System/lib/string/align";
string *query_parse_methods()
{
return ({ "raw" });
}
int compare_sites(string a, string b)
{
int o1a, o2a, o3a, o4a, cidra;
int o1b, o2b, o3b, o4b, cidrb;
sscanf(a, "%d.%d.%d.%d/%d", o1a, o2a, o3a, o4a, cidra);
sscanf(b, "%d.%d.%d.%d/%d", o1b, o2b, o3b, o4b, cidrb);
if (o1a < o1b) {
return -1;
}
if (o1a > o1b) {
return 1;
}
if (o2a < o2b) {
return -1;
}
if (o2a > o2b) {
return 1;
}
if (o3a < o3b) {
return -1;
}
if (o3a > o3b) {
return 1;
}
if (o4a < o4b) {
return -1;
}
if (o4a > o4b) {
return 1;
}
if (cidra < cidrb) {
return -1;
}
if (cidra > cidrb) {
return 1;
}
return 0;
}
string query_help_title()
{
return "Sitebans";
}
string *query_help_contents()
{
return ({ "Lists sitebans" });
}
void main(object actor, mapping roles)
{
string *sites;
object user;
int sz;
user = query_user();
if (user->query_class() < 3) {
send_out("You do not have sufficient access rights to list sitebans.\n");
return;
}
if (roles["raw"]) {
send_out("Usage: sitebans\n");
return;
}
sites = BAND->query_sitebans();
sz = sizeof(sites);
qsort(sites, 0, sz, "compare_sites");
if (sz) {
mapping *bans;
int i;
bans = allocate(sz);
for (i = 0; i < sz; i++) {
mapping ban;
ban = BAND->query_siteban(sites[i]);
if (!ban) {
sites[i] = nil;
continue;
}
bans[i] = ban;
}
sites -= ({ nil });
bans -= ({ nil });
send_out(print_bans("Site", sites, bans));
send_out("\n");
} else {
send_out("There are no banned sites.\n");
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ext.Net
{
<summary>
</summary>
public partial class RadialAxis
{
<summary>
</summary>
public RadialAxis(Config config)
{
this.Apply(config);
}
<summary>
</summary>
public static implicit operator RadialAxis(RadialAxis.Config config)
{
return new RadialAxis(config);
}
<summary>
</summary>
new public partial class Config : AbstractAxis.Config
{
<summary>
</summary>
public static implicit operator RadialAxis.Builder(RadialAxis.Config config)
{
return new RadialAxis.Builder(config);
}
private int steps = 0;
<summary>
</summary>
[DefaultValue(0)]
public virtual int Steps
{
get
{
return this.steps;
}
set
{
this.steps = value;
}
}
private int maximum = 0;
<summary>
</summary>
[DefaultValue(0)]
public virtual int Maximum
{
get
{
return this.maximum;
}
set
{
this.maximum = value;
}
}
}
}
}
|
package uploads
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/grafana/loki/pkg/storage/chunk"
"github.com/grafana/loki/pkg/storage/chunk/local"
chunk_util "github.com/grafana/loki/pkg/storage/chunk/util"
"github.com/grafana/loki/pkg/storage/stores/shipper/util"
util_log "github.com/grafana/loki/pkg/util/log"
)
type Config struct {
Uploader string
IndexDir string
UploadInterval time.Duration
DBRetainPeriod time.Duration
<API key> bool
}
type TableManager struct {
cfg Config
boltIndexClient BoltDBIndexClient
storageClient StorageClient
metrics *metrics
tables map[string]*Table
tablesMtx sync.RWMutex
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewTableManager(cfg Config, boltIndexClient BoltDBIndexClient, storageClient StorageClient, registerer prometheus.Registerer) (*TableManager, error) {
ctx, cancel := context.WithCancel(context.Background())
tm := TableManager{
cfg: cfg,
boltIndexClient: boltIndexClient,
storageClient: storageClient,
metrics: newMetrics(registerer),
ctx: ctx,
cancel: cancel,
}
tables, err := tm.loadTables()
if err != nil {
return nil, err
}
tm.tables = tables
go tm.loop()
return &tm, nil
}
func (tm *TableManager) loop() {
tm.wg.Add(1)
defer tm.wg.Done()
tm.uploadTables(context.Background(), false)
syncTicker := time.NewTicker(tm.cfg.UploadInterval)
defer syncTicker.Stop()
for {
select {
case <-syncTicker.C:
tm.uploadTables(context.Background(), false)
case <-tm.ctx.Done():
return
}
}
}
func (tm *TableManager) Stop() {
level.Info(util_log.Logger).Log("msg", "stopping table manager")
tm.cancel()
tm.wg.Wait()
tm.uploadTables(context.Background(), true)
}
func (tm *TableManager) QueryPages(ctx context.Context, queries []chunk.IndexQuery, callback chunk.QueryPagesCallback) error {
queriesByTable := util.QueriesByTable(queries)
for tableName, queries := range queriesByTable {
err := tm.query(ctx, tableName, queries, callback)
if err != nil {
return err
}
}
return nil
}
func (tm *TableManager) query(ctx context.Context, tableName string, queries []chunk.IndexQuery, callback chunk.QueryPagesCallback) error {
tm.tablesMtx.RLock()
defer tm.tablesMtx.RUnlock()
table, ok := tm.tables[tableName]
if !ok {
return nil
}
return util.DoParallelQueries(ctx, table, queries, callback)
}
func (tm *TableManager) BatchWrite(ctx context.Context, batch chunk.WriteBatch) error {
boltWriteBatch, ok := batch.(*local.BoltWriteBatch)
if !ok {
return errors.New("invalid write batch")
}
for tableName, tableWrites := range boltWriteBatch.Writes {
table, err := tm.getOrCreateTable(tableName)
if err != nil {
return err
}
err = table.Write(ctx, tableWrites)
if err != nil {
return err
}
}
return nil
}
func (tm *TableManager) getOrCreateTable(tableName string) (*Table, error) {
tm.tablesMtx.RLock()
table, ok := tm.tables[tableName]
tm.tablesMtx.RUnlock()
if !ok {
tm.tablesMtx.Lock()
defer tm.tablesMtx.Unlock()
table, ok = tm.tables[tableName]
if !ok {
var err error
table, err = NewTable(filepath.Join(tm.cfg.IndexDir, tableName), tm.cfg.Uploader, tm.storageClient,
tm.boltIndexClient, tm.cfg.<API key>)
if err != nil {
return nil, err
}
tm.tables[tableName] = table
}
}
return table, nil
}
func (tm *TableManager) uploadTables(ctx context.Context, force bool) {
tm.tablesMtx.RLock()
defer tm.tablesMtx.RUnlock()
level.Info(util_log.Logger).Log("msg", "uploading tables")
status := statusSuccess
for _, table := range tm.tables {
err := table.Snapshot()
if err != nil {
// we do not want to stop uploading of dbs due to failures in snapshotting them so logging just the error here.
level.Error(util_log.Logger).Log("msg", "failed to snapshot table for reads", "table", table.name, "err", err)
}
err = table.Upload(ctx, force)
if err != nil {
// continue uploading other tables while skipping cleanup for a failed one.
status = statusFailure
level.Error(util_log.Logger).Log("msg", "failed to upload dbs", "table", table.name, "err", err)
continue
}
// cleanup unwanted dbs from the table
err = table.Cleanup(tm.cfg.DBRetainPeriod)
if err != nil {
// we do not want to stop uploading of dbs due to failures in cleaning them up so logging just the error here.
level.Error(util_log.Logger).Log("msg", "failed to cleanup uploaded dbs past their retention period", "table", table.name, "err", err)
}
}
tm.metrics.<API key>.WithLabelValues(status).Inc()
}
func (tm *TableManager) loadTables() (map[string]*Table, error) {
localTables := make(map[string]*Table)
filesInfo, err := ioutil.ReadDir(tm.cfg.IndexDir)
if err != nil {
return nil, err
}
// regex matching table name patters, i.e prefix+period_number
re, err := regexp.Compile(`.+[0-9]+$`)
if err != nil {
return nil, err
}
for _, fileInfo := range filesInfo {
if !re.MatchString(fileInfo.Name()) {
continue
}
// since we are moving to keeping files for same table in a folder, if current element is a file we need to move it inside a directory with the same name
// i.e file index_123 would be moved to path index_123/index_123.
if !fileInfo.IsDir() {
level.Info(util_log.Logger).Log("msg", fmt.Sprintf("found a legacy file %s, moving it to folder with same name", fileInfo.Name()))
filePath := filepath.Join(tm.cfg.IndexDir, fileInfo.Name())
// create a folder with .temp suffix since we can't create a directory with same name as file.
tempDirPath := filePath + ".temp"
if err := chunk_util.EnsureDirectory(tempDirPath); err != nil {
return nil, err
}
// move the file to temp dir.
if err := os.Rename(filePath, filepath.Join(tempDirPath, fileInfo.Name())); err != nil {
return nil, err
}
// rename the directory to name of the file
if err := os.Rename(tempDirPath, filePath); err != nil {
return nil, err
}
}
level.Info(util_log.Logger).Log("msg", fmt.Sprintf("loading table %s", fileInfo.Name()))
table, err := LoadTable(filepath.Join(tm.cfg.IndexDir, fileInfo.Name()), tm.cfg.Uploader, tm.storageClient,
tm.boltIndexClient, tm.cfg.<API key>, tm.metrics)
if err != nil {
return nil, err
}
if table == nil {
// if table is nil it means it has no files in it so remove the folder for that table.
err := os.Remove(filepath.Join(tm.cfg.IndexDir, fileInfo.Name()))
if err != nil {
level.Error(util_log.Logger).Log("msg", "failed to remove empty table folder", "table", fileInfo.Name(), "err", err)
}
continue
}
// Queries are only done against table snapshots so it's important we snapshot as soon as the table is loaded.
err = table.Snapshot()
if err != nil {
return nil, err
}
localTables[fileInfo.Name()] = table
}
return localTables, nil
}
|
#include "SessionShiny.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <r/RExec.hpp>
#include <session/SessionOptions.hpp>
#include <session/<API key>.hpp>
using namespace core;
namespace session {
namespace modules {
namespace shiny {
namespace {
void onPackageLoaded(const std::string& pkgname)
{
// we need an up to date version of shiny when running in server mode
// to get the websocket protocol/path and port randomizing changes
if (session::options().programMode() == <API key>)
{
if (pkgname == "shiny")
{
if (!module_context::<API key>("shiny", "0.8"))
{
module_context::consoleWriteError("\nWARNING: To run Shiny "
"applications with RStudio you need to install the "
"latest version of the Shiny package from CRAN (version 0.8 "
"or higher is required).\n\n");
}
}
}
}
bool isShinyAppDir(const FilePath& filePath)
{
bool hasServer = filePath.childPath("server.R").exists() ||
filePath.childPath("server.r").exists();
if (hasServer)
{
bool hasUI = filePath.childPath("ui.R").exists() ||
filePath.childPath("ui.r").exists() ||
filePath.childPath("www").exists();
return hasUI;
}
else
{
return false;
}
}
std::string <API key>(
boost::shared_ptr<source_database::SourceDocument> pDoc)
{
const char * const kShinyType = "shiny";
if (!pDoc->path().empty())
{
FilePath filePath = module_context::resolveAliasedPath(pDoc->path());
std::string filename = filePath.filename();
if (boost::algorithm::iequals(filename, "ui.r") &&
boost::algorithm::icontains(pDoc->contents(), "shinyUI"))
{
return kShinyType;
}
else if (boost::algorithm::iequals(filename, "server.r") &&
boost::algorithm::icontains(pDoc->contents(), "shinyServer"))
{
return kShinyType;
}
else if (filePath.extensionLowerCase() == ".r" &&
isShinyAppDir(filePath.parent()))
{
return kShinyType;
}
}
return std::string();
}
Error <API key>(const json::JsonRpcRequest& request,
json::JsonRpcResponse* pResponse)
{
json::Object capsJson;
capsJson["installed"] = module_context::isPackageInstalled("shiny");
pResponse->setResult(capsJson);
return Success();
}
} // anonymous namespace
Error initialize()
{
using namespace module_context;
events().onPackageLoaded.connect(onPackageLoaded);
// run app features require shiny v0.8 (the version where the
// shiny.launch.browser option can be a function)
if (module_context::<API key>("shiny", "0.8"))
events().<API key>.connect(<API key>);
ExecBlock initBlock;
initBlock.addFunctions()
(boost::bind(registerRpcMethod, "<API key>", <API key>));
return initBlock.execute();
}
} // namespace crypto
} // namespace modules
} // namesapce session
|
from django import forms
# future use
|
package cn.dlb.bim.models.ifc4;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Ifc Sub Contract Resource Type Enum</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see cn.dlb.bim.models.ifc4.Ifc4Package#<API key>()
* @model
* @generated
*/
public enum <API key> implements Enumerator {
/**
* The '<em><b>NULL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NULL_VALUE
* @generated
* @ordered
*/
NULL(0, "NULL", "NULL"),
/**
* The '<em><b>NOTDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NOTDEFINED_VALUE
* @generated
* @ordered
*/
NOTDEFINED(1, "NOTDEFINED", "NOTDEFINED"),
/**
* The '<em><b>WORK</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #WORK_VALUE
* @generated
* @ordered
*/
WORK(2, "WORK", "WORK"),
/**
* The '<em><b>USERDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #USERDEFINED_VALUE
* @generated
* @ordered
*/
USERDEFINED(3, "USERDEFINED", "USERDEFINED"),
/**
* The '<em><b>PURCHASE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #PURCHASE_VALUE
* @generated
* @ordered
*/
PURCHASE(4, "PURCHASE", "PURCHASE");
/**
* The '<em><b>NULL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NULL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NULL
* @model
* @generated
* @ordered
*/
public static final int NULL_VALUE = 0;
/**
* The '<em><b>NOTDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NOTDEFINED
* @model
* @generated
* @ordered
*/
public static final int NOTDEFINED_VALUE = 1;
/**
* The '<em><b>WORK</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>WORK</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #WORK
* @model
* @generated
* @ordered
*/
public static final int WORK_VALUE = 2;
/**
* The '<em><b>USERDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #USERDEFINED
* @model
* @generated
* @ordered
*/
public static final int USERDEFINED_VALUE = 3;
/**
* The '<em><b>PURCHASE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>PURCHASE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #PURCHASE
* @model
* @generated
* @ordered
*/
public static final int PURCHASE_VALUE = 4;
/**
* An array of all the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final <API key>[] VALUES_ARRAY = new <API key>[] { NULL, NOTDEFINED, WORK, USERDEFINED, PURCHASE, };
/**
* A public read-only list of all the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<<API key>> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static <API key> get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
<API key> result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static <API key> getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
<API key> result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Sub Contract Resource Type Enum</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static <API key> get(int value) {
switch (value) {
case NULL_VALUE:
return NULL;
case NOTDEFINED_VALUE:
return NOTDEFINED;
case WORK_VALUE:
return WORK;
case USERDEFINED_VALUE:
return USERDEFINED;
case PURCHASE_VALUE:
return PURCHASE;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private <API key>(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //<API key>
|
DELETE FROM database_variables WHERE name = '<API key>';
|
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
global $mod_strings;
$module_menu = Array(
Array("index.php?module=Teams&action=EditView&return_module=Teams&return_action=DetailView", $mod_strings['LNK_NEW_TEAM'], "CreateTeams"),
Array("index.php?module=Teams&action=index", $mod_strings['LNK_LIST_TEAM'], "Teams"),
Array("index.php?module=TeamNotices&action=index", $mod_strings['LNK_LIST_TEAMNOTICE'], "Teams"),
Array("index.php?module=TeamNotices&action=EditView", translate('LNK_NEW_TEAM_NOTICE','TeamNotices'), "Teams")
);
|
<?php
/**
* sfGuardGroupUtf8 form.
*
* @package rrr
* @subpackage form
* @author Your name here
* @version SVN: $Id: <API key>.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
*/
class <API key> extends <API key>
{
/**
* @see sfGuardGroupForm
*/
public function configure()
{
parent::configure();
}
}
|
*
// * Tanaguru - Automated webpage assessment
// * This program is free software: you can redistribute it and/or modify
// * published by the Free Software Foundation, either version 3 of the
// * This program is distributed in the hope that it will be useful,
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * Contact us by mail: tanaguru AT tanaguru DOT org
//package org.tanaguru.rules.rgaa32017;
//import org.apache.commons.lang3.tuple.ImmutablePair;
//import org.tanaguru.entity.audit.ProcessResult;
//import org.tanaguru.entity.audit.TestSolution;
//import org.tanaguru.rules.keystore.HtmlElementStore;
//import org.tanaguru.rules.keystore.RemarkMessageStore;
//import org.tanaguru.rules.rgaa32017.test.<API key>;
**
// * Unit test class for the implementation of the rule 10-9-1 of the referential Rgaa 3-2017.
// * @author
//public class <API key> extends <API key> {
// /**
// * Default constructor
// * @param testName
// */
// public <API key> (String testName){
// super(testName);
// @Override
// protected void <API key>() {
// <API key>(
// "org.tanaguru.rules.rgaa32017.Rgaa32017Rule100901");
// @Override
// protected void setUpWebResourceMap() {
// addWebResource("Rgaa32017.Test.10.9.1-1Passed-01");
// addWebResource("Rgaa32017.Test.10.9.1-2Failed-01");
// addWebResource("Rgaa32017.Test.10.9.1-2Failed-02");
// // addWebResource("Rgaa32017.Test.10.9.1-3NMI-01");
/ addWebResource("Rgaa32017.Test.10.9.1-4NA-01");
// @Override
// protected void setProcess() {
// // checkResultIsPassed(processPageTest("Rgaa32017.Test.10.9.1-1Passed-01"), 0);
// ProcessResult processResult = processPageTest("Rgaa32017.Test.10.9.1-2Failed-01");
// checkResultIsFailed(processResult, 1, 1);
/ <API key>(
/ processResult,
/ TestSolution.FAILED,
/ <API key>,
/ "h1",
/ 1,
/ new ImmutablePair("#<API key>", "#<API key>"));
// processResult = processPageTest("Rgaa32017.Test.10.9.1-2Failed-02");
// checkResultIsFailed(processResult, 1, 1);
/ <API key>(
/ processResult,
/ TestSolution.FAILED,
/ RemarkMessageStore.<API key>,
/ HtmlElementStore.P_ELEMENT,
/ 1,
/ new ImmutablePair("#<API key>", "#<API key>"));
/ ProcessResult processResult = processPageTest("Rgaa32017.Test.10.9.1-3NMI-01");
/ <API key>(processResult); // temporary result to make the result buildable before implementation
/ <API key>(processResult, 1, 1);
/ <API key>(
/ processResult,
/ TestSolution.NEED_MORE_INFO,
/ <API key>,
/ "p",
/ 1);
/ <API key>(processPageTest("Rgaa32017.Test.10.9.1-4NA-01"));
// @Override
// protected void setConsolidate() {
// // The consolidate method can be removed when real implementation is done.
// // The assertions are automatically tested regarding the file names by
// // the abstract parent class
/ assertEquals(TestSolution.NOT_TESTED,
/ consolidate("Rgaa32017.Test.10.9.1-3NMI-01").getValue());
|
import { NPS } from './NPS'
export default NPS
|
<?php
/**#@+ @ignore */
require_once DEDALO_ROOT . '/lib/Zend/Media/Id3/TextFrame.php';
final class <API key> extends <API key>
{
private $_number;
private $_total;
/**
* Constructs the class with given parameters and parses object related
* data.
*
* @param Zend_Io_Reader $reader The reader object.
* @param Array $options The options array.
*/
public function __construct($reader = null, &$options = array())
{
<API key>::__construct($reader, $options);
$this->setEncoding(<API key>::ISO88591);
if ($this->_reader === null) {
return;
}
$this->_reader->skip(1);
$this->setText($this->_reader->readString8($this->_reader->getSize()));
@list ($this->_number, $this->_total) = explode("/", $this->getText());
}
/**
* Returns the number.
*
* @return integer
*/
public function getNumber()
{
return intval($this->_number);
}
/**
* Sets the number.
*
* @param integer $number The number.
*/
public function setNumber($part)
{
$this->setText
($this->_number = strval($part) .
($this->_total ? '/' . $this->_total : ''),
<API key>::ISO88591);
}
/**
* Returns the total number.
*
* @return integer
*/
public function getTotal()
{
return intval($this->_total);
}
/**
* Sets the total number.
*
* @param integer $total The total number.
*/
public function setTotal($total)
{
$this->setText
(($this->_number ? $this->_number : '?') . "/" .
($this->_total = strval($total)),
<API key>::ISO88591);
}
}
|
<?php
/* @var $this <API key> */
/* @var $model Aenderungsantrag */
$this->breadcrumbs = array(
Yii::t('app', 'Administration') => $this->createUrl('/admin/index'),
$model->label(2) => array('index'),
Yii::t('app', 'Create'),
);
$this->menu = array(
array('label' => $model->label(2), 'url' => array('index'), "icon" => "home"),
array('label' => "Durchsuchen", 'url' => array('admin'), "icon" => "th-list"),
);
?>
<h1><?php echo GxHtml::encode($model->label()) . ' ' . Yii::t('app', 'Create'); ?></h1>
<?php
$this->renderPartial('_form', array(
'model' => $model,
'buttons' => 'create'));
?>
|
'use strict';
/**
* @ngdoc directive
* @name GO.Core.CustomFields.goCustomFieldsEdit
*
* @description
* Prints custom fields form fieldsets.
*
*
* @param {string} ngModel The customFields model property of the model the customFields belong to
* @param {string} serverModel The custom fields server model.
*
* @example
* <<API key> ng-model="contact.customFields" server-model="GO\Modules\GroupOffice\Contacts\Model\ContactCustomFields"></<API key>>
*/
angular.module('GO.Core').directive('goCustomFieldsEdit', [
'$templateCache',
'$compile',
'GO.Core.Directives.CustomFields',
function ($templateCache, $compile, CustomFields) {
var buildTemplate = function (customFieldSetStore) {
var tpl = '';
for (var i = 0, l = customFieldSetStore.items.length; i < l; i++) {
var fieldSet = customFieldSetStore.items[i];
tpl += '<fieldset><h3>{{::"' + fieldSet.name + '" | goT}}</h3>';
for (var n = 0, cl = fieldSet.fields.length; n < cl; n++) {
var field = fieldSet.fields[n];
tpl += buildFunctions[field.type](field);
}
tpl += '</fieldset>';
}
return tpl;
};
var buildFunctions = {
formName: null,
text: function (field) {
return '<md-input-container class="md-block">\
<md-icon>star</md-icon>\
<label>{{::"' + field.name + '" | goT}}</label>\
<input name="' + field.databaseName + '" type="text" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\
<md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\
<div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\
<div ng-message="required">\
{{::"This field is required" | goT}}\
</div>\
</div>\
</md-input-container>';
},
textarea: function (field) {
return '<md-input-container class="md-block">\
<md-icon>star</md-icon>\
<label>{{::"' + field.name + '" | goT}}</label>\
<textarea id="' + field.databaseName + '" name="' + field.databaseName + '" maxlength="' + field.data.maxLength + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></textarea>\
<md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\
<div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\
<div ng-message="required">\
{{::"This field is required" | goT}}\
</div>\
</div>\
</md-input-container>';
},
select: function (field) {
var tpl = '<md-input-container class="md-block">\
<md-icon>star</md-icon>\
<label>{{::"' + field.name + '" | goT}}</label>\
<md-select name="' + field.databaseName + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '">';
for (var i = 0, l = field.data.options.length; i < l; i++) {
tpl += '<md-option value="' + field.data.options[i] + '">{{::"' + field.data.options[i] + '" | goT}}</md-option>';
}
tpl += '</md-select>\
<md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\
<div class="md-errors-spacer"></div>\
<div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\
<div ng-message="required">\
{{::"This field is required" | goT}}\
</div>\
</div>';
tpl += '</md-input-container>';
return tpl;
},
checkbox: function (field) {
return '<md-input-container class="md-block">\
<md-checkbox id="cf_{{field.id}}" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"> {{::"' + field.name + '" | goT}}</md-checkbox>\
<md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\
</md-input-container>';
},
date: function (field) {
return '<go-date-picker id="cf_{{field.id}}" name="dateOfBirth" hint="{{::\''+field.hintText+'\' | goT }}" label="' + field.name + '" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '"></go-date-picker>';
},
number: function (field) {
return '<md-input-container class="md-block">\
<md-icon>star</md-icon>\
<label>{{::"' + field.name + '" | goT}}</label>\
<input go-number id="cf_{{field.id}}" name="' + field.databaseName + '" type="text" ng-model="goModel[\'' + field.databaseName + '\']" ng-required="' + (field.required ? 'true' : 'false') + '" />\
<md-hint>{{::"'+field.hintText+'" | goT}}</md-hint>\
<div ng-messages="formController.' + field.databaseName + '.$error" role="alert">\
<div ng-message="required">\
{{::"This field is required" | goT}}\
</div>\
</div>\
</md-input-container>';
}
};
return {
restrict: 'E',
scope: {
goModel: '=ngModel',
serverModel: '@',
formController: '='
},
link: function (scope, element, attrs) {
var customFieldSetStore = CustomFields.getFieldSetStore(attrs.serverModel);
//TODO load is called twice now
customFieldSetStore.promise.then(function () {
var tpl = buildTemplate(customFieldSetStore);
element.html(tpl);
$compile(element.contents())(scope);
});
}
};
}]);
|
import React from 'react'
import { observer } from 'mobx-react'
import styled from 'styled-components'
import autobind from 'autobind-decorator'
import SearchInput from '../SearchInput'
import Palette from '../../styleUtils/Palette'
import filterImage from './images/filter'
const border = '1px solid rgba(216, 219, 226, 0.4)'
const Wrapper = styled.div<any>`
position: relative;
margin-top: -1px;
`
const Button = styled.div<any>`
width: 16px;
height: 16px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
`
const List = styled.div<any>`
position: absolute;
top: 24px;
right: -7px;
z-index: 9999;
padding: 8px;
background: ${Palette.grayscale[1]};
border-radius: 4px;
border: ${border};
box-shadow: 0 0 4px 0 rgba(32, 34, 52, 0.13);
`
const Tip = styled.div<any>`
position: absolute;
top: -6px;
right: 8px;
width: 10px;
height: 10px;
background: ${Palette.grayscale[1]};
border-top: ${border};
border-left: ${border};
border-bottom: 1px solid transparent;
border-right: 1px solid transparent;
transform: rotate(45deg);
`
const ListItems = styled.div<any>`
width: 199px;
height: 32px;
`
type Props = {
searchPlaceholder?: string,
searchValue?: string,
onSearchChange?: (value: string) => void,
}
type State = {
showDropdownList: boolean
}
@observer
class DropdownFilter extends React.Component<Props, State> {
static defaultProps = {
searchPlaceholder: 'Filter',
}
state: State = {
showDropdownList: false,
}
itemMouseDown: boolean | undefined
componentDidMount() {
window.addEventListener('mousedown', this.handlePageClick, false)
}
<API key>() {
window.removeEventListener('mousedown', this.handlePageClick, false)
}
@autobind
handlePageClick() {
if (!this.itemMouseDown) {
this.setState({ showDropdownList: false })
}
}
handleButtonClick() {
this.setState(prevState => ({ showDropdownList: !prevState.showDropdownList }))
}
handleCloseClick() {
this.setState({ showDropdownList: false })
}
renderList() {
if (!this.state.showDropdownList) {
return null
}
return (
<List
onMouseDown={() => { this.itemMouseDown = true }}
onMouseUp={() => { this.itemMouseDown = false }}
data-test-id="dropdownFilter-list"
>
<Tip />
<ListItems>
<SearchInput
width="100%"
alwaysOpen
placeholder={this.props.searchPlaceholder}
value={this.props.searchValue}
onChange={this.props.onSearchChange}
useFilterIcon
focusOnMount
disablePrimary
onCloseClick={() => { this.handleCloseClick() }}
/>
</ListItems>
</List>
)
}
renderButton() {
return (
<Button
data-test-id="<API key>"
onMouseDown={() => { this.itemMouseDown = true }}
onMouseUp={() => { this.itemMouseDown = false }}
onClick={() => { this.handleButtonClick() }}
<API key>={{
__html:
filterImage(this.props.searchValue ? Palette.primary : Palette.grayscale[5]),
}}
/>
)
}
render() {
return (
<Wrapper>
{this.renderButton()}
{this.renderList()}
</Wrapper>
)
}
}
export default DropdownFilter
|
"""
Block Depth Transformer
"""
from __future__ import absolute_import
from openedx.core.djangoapps.content.block_structure.transformer import <API key>
class <API key>(<API key>):
"""
Keep track of the depth of each block within the block structure. In case
of multiple paths to a given node (in a DAG), use the shallowest depth.
"""
WRITE_VERSION = 1
READ_VERSION = 1
BLOCK_DEPTH = 'block_depth'
def __init__(self, requested_depth=None):
self.requested_depth = requested_depth
@classmethod
def name(cls):
return "blocks_api:block_depth"
@classmethod
def get_block_depth(cls, block_structure, block_key):
"""
Return the precalculated depth of a block within the block_structure:
Arguments:
block_structure: a BlockStructure instance
block_key: the key of the block whose depth we want to know
Returns:
int
"""
return block_structure.<API key>(
block_key,
cls,
cls.BLOCK_DEPTH,
)
def transform(self, usage_info, block_structure):
"""
Mutates block_structure based on the given usage_info.
"""
for block_key in block_structure.<API key>():
parents = block_structure.get_parents(block_key)
if parents:
block_depth = min(
self.get_block_depth(block_structure, parent_key)
for parent_key in parents
) + 1
else:
block_depth = 0
block_structure.<API key>(
block_key,
self,
self.BLOCK_DEPTH,
block_depth
)
if self.requested_depth is not None:
block_structure.<API key>(
lambda block_key: self.get_block_depth(block_structure, block_key) > self.requested_depth
)
|
#!/usr/bin/env ruby
# Exit codes:
# 0 Test run successful (even with reruns)
# 1 Unspecified error
# 2 Linting failed
# 4 No profile given
# 8 Gettext isn't installed
# 16 Gettext files did not validate
# 32 Cucumber failed
# 64 Rspec failed
# TODO: Use Open4 to continuously flush STDOUT output from the cucumber
# processes.
require 'rubygems'
require 'fileutils'
require 'pry'
require 'open4'
PROFILES = ['default']
def die(exit_code, error)
puts "Error: #{error}"
exit exit_code
end
def run_command(cmd)
pid, stdin, stdout, _stderr = Open4.open4("#{cmd} 2>&1")
stdin.close
puts stdout.read 1024 until stdout.eof?
Process.waitpid2(pid).last.exitstatus
end
def gettext_installed?
`which msgcat >> /dev/null`
if $CHILD_STATUS.exitstatus == 0
return true
else
return false
end
end
def gettext_file_valid?(file)
`msgcat #{file} >> /dev/null`
if $CHILD_STATUS.exitstatus == 0
return true
else
return false
end
end
def gettext_files_valid?
files = ['locale/vinylla.pot']
files += Dir.glob('localeleihs.po')
files.each do |file|
return false unless gettext_file_valid?(file)
end
true
end
def rerun_cucumber(maximum = 3, run_count = 0)
return true if run_count >= maximum
if File.exist?('tmp/rererun.txt')
FileUtils.mv('tmp/rererun.txt', 'tmp/rerun.txt')
end
return false unless File.exist?('tmp/rerun.txt') && File.size('tmp/rerun.txt') > 0
puts 'Rerun necessary.'
exitstatus = run_command('bundle exec cucumber -p rerun')
run_count += 1
if exitstatus != 0
rerun_cucumber(maximum, run_count)
else
die(0, 'All went well after rerunning.')
end
end
# Do we know what we're doing?
profile = ARGV[0]
if PROFILES.include?(profile) == false
die(4, "Please specify a valid profile, one of #{PROFILES.join(', ')}.")
end
# 1. Prerequisites for testing
# We're not actually using gettext yet in Vinylla and it's undecided
# whether we will.
# if not gettext_installed?
# die(8, "Gettext isn't installed. Make sure you have gettext and \
# msgcat and msgmerge are in your PATH.")
# end
# if not gettext_files_valid?
# die(16, 'The gettext files did not validate.')
# end
# 2. Linting
exitstatus = run_command('bundle exec rubocop --lint')
die(2, 'Rubocop is disgusted. Clean up that filthy code!') if exitstatus != 0
# 3. Testing proper
exitstatus = run_command('bundle exec rspec')
die(64, 'Rspec failed') if exitstatus != 0
# puts 'Prerequisites for running the tests are met'
# puts 'Starting Cucumber...'
# FileUtils.rm_f(['tmp/rerun.txt', 'tmp/rererun.txt'])
# exitstatus = run_command("bundle exec cucumber -p #{profile}")
# Rerun for failures, up to n times
# if exitstatus != 0
# rerun(4)
# else
# die(0, 'All went well on the very first run. The planets must be in alignment.')
# end
|
import ast
from odoo import api, exceptions, models, _
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
@api.model
def _get_priorities(self):
"""
Load priorities from parameters.
:return: dict
"""
key = 'mail.sending.job.priorities'
try:
priorities = ast.literal_eval(
self.env['ir.config_parameter'].sudo().get_param(
key, default='{}'))
# Catch exception to have a understandable error message
except (ValueError, SyntaxError):
raise exceptions.UserError(
_("Error to load the system parameter (%s) "
"of priorities") % key)
# As literal_eval can transform str into any format, check if we
# have a real dict
if not isinstance(priorities, dict):
raise exceptions.UserError(
_("Error to load the system parameter (%s) of priorities.\n"
"Invalid dictionary") % key)
return priorities
@api.multi
def send_mail(self, auto_commit=False):
"""
Set a priority on subsequent generated mail.mail, using priorities
set into the configuration.
:return: dict/action
"""
active_ids = self.env.context.get('active_ids')
default_priority = self.env.context.get('<API key>')
if active_ids and not default_priority:
priorities = self._get_priorities()
size = len(active_ids)
limits = [lim for lim in priorities if lim <= size]
if limits:
prio = priorities.get(max(limits))
self = self.with_context(<API key>=prio)
return super().send_mail(auto_commit=auto_commit)
|
<?php
/**
* This is a prototype for a services action.
*
*/
abstract class <API key> implements <API key> {
use <API key>;
protected $collection = null;
/**
* Create an instance of the ServiceAction type.
*/
public function __construct($params = array()) {
$this->collection = Billrun_Factory::db()->servicesCollection();
$this->baseCode = 1500;
}
/**
* Get the array of fields to be set in the query record from the user input.
* @return array - Array of fields to set.
*/
protected function getQueryFields() {
return Billrun_Factory::config()->getConfigValue('services.fields');
}
}
|
#feedbackForm { width: 100%; }
#feedbackForm label { width: 250px; }
#feedbackForm label.error, #commentForm input.submit { margin-left: 253px; }
input[type=text], input[type=password], select, textarea, .inputbox { padding: 3px 5px; font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 100%; border: 1px solid #999; }
.button { padding: 3px 5px; border: 1px solid #333333; color: #CCCCCC; font-size: 85%; text-transform: uppercase;}
.button:hover, .button:focus { border: 1px solid #999999; background: #333333; color: #FFFFFF;}
input.error { border: 1px dotted red; background-color: #FFBABA;}
form.cmxform legend { padding-left: 0;}
form.cmxform legend, form.cmxform label { color: #333;}
form.cmxform fieldset { border: none; background-color: #f6f6f6;}
form.cmxform fieldset fieldset { background: none;}
form.cmxform label.error, label.error { color: red; font-style: italic}
form.cmxform fieldset { margin-bottom: 10px;}
form.cmxform legend { padding: 0 2px; font-weight: bold; _margin: 0 -7px; /* IE Win */}
form.cmxform label { display: inline-block; line-height: 1.8; vertical-align: top; cursor: hand;}
form.cmxform fieldset p { list-style: none; padding: 5px; margin: 0;}
form.cmxform fieldset fieldset { border: none; margin: 3px 0 0;}
form.cmxform fieldset fieldset legend { padding: 0 0 5px; font-weight: normal;}
form.cmxform fieldset fieldset label { display: block; width: auto;}
form.cmxform label { width: 100px; } /* Width of labels */
form.cmxform fieldset fieldset label { margin-left: 103px; } /* Width plus 3 (html space) */
form.cmxform label.error { margin-left: 103px; width: 220px;}
form.cmxform input.submit { margin-left: 103px;}
form.cmxform label.error { display: none; }
.btn-action { background-color:#e2001a; color:#fff; padding:5px; border: none; cursor: pointer; }
a.btn-action:hover { color: #fff; }
.comment { color: #666; }
span.required { color: #f00; }
label.error { float: none; display: inline; clear: none; width: 400px; padding-left: 15px; }
form ul { padding: 15px; }
form li { padding:4px; }
form ul:hover { background-color: #f4f4f4; }
form ul.noeditable:hover { background-color: #fff; }
|
<table mat-table
*ngIf="dataSource"
[dataSource]="dataSource"
[trackBy]="tableTrackerFn"
class="ya-data-table">
<ng-container matColumnDef="order">
<th mat-header-cell *matHeaderCellDef style="width: 1px">
<td mat-cell *matCellDef="let queue">
{{ queue.order }}
</td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef style="width: 200px">Name</th>
<td mat-cell *matCellDef="let queue">
{{ queue.name }}
</td>
</ng-container>
<ng-container matColumnDef="issuer">
<th mat-header-cell *matHeaderCellDef style="width: 200px">Issuer</th>
<td mat-cell *matCellDef="let queue">
<app-label *ngFor="let group of queue.groups" icon="people">{{ group }}</app-label>
<app-label *ngFor="let user of queue.users" icon="person">{{ user }}</app-label>
<ng-container *ngIf="!queue.groups && !queue.users">-</ng-container>
</td>
</ng-container>
<ng-container matColumnDef="level">
<th mat-header-cell *matHeaderCellDef style="width: 100px">Min. level</th>
<td mat-cell *matCellDef="let queue">
<<API key> [level]="queue.minLevel" [grayscale]="true">
</<API key>>
</td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef style="width: 100px">Action</th>
<td mat-cell *matCellDef="let queue">
<span *ngIf="queue.state === 'ENABLED'">
ACCEPT
</span>
<span *ngIf="queue.state === 'BLOCKED'" [style.visibility]="(visibility$ | async) ? 'visible' : 'hidden'">
HOLD
</span>
<span *ngIf="queue.state === 'DISABLED'">
REJECT
</span>
</td>
</ng-container>
<ng-container matColumnDef="pending">
<th mat-header-cell *matHeaderCellDef width="1">Pending</th>
<td mat-cell *matCellDef="let queue" style="text-align: center">
{{ (queue.entry?.length || 0) | number }}
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let queue">
<mat-menu #queueMenu="matMenu" overlapTrigger="false" class="ya-menu">
<button mat-menu-item
[matMenuTriggerFor]="actions">
Change action
</button>
</mat-menu>
<mat-menu #actions="matMenu" class="ya-menu">
<button mat-menu-item
(click)="enableQueue(queue)">
<mat-icon>check</mat-icon>
ACCEPT
</button>
<button mat-menu-item
(click)="blockQueue(queue)">
<mat-icon>pause</mat-icon>
HOLD
</button>
<button mat-menu-item
(click)="disableQueue(queue)">
<mat-icon>close</mat-icon>
REJECT
</button>
</mat-menu>
<button mat-button
[matMenuTriggerFor]="queueMenu"
class="icon"
(click)="$event.stopPropagation()">
<mat-icon>more_vert</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
|
DELETE FROM `landblock_instance` WHERE `landblock` = 0xA8E0;
INSERT INTO `landblock_instance` (`guid`, `weenie_Class_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)
VALUES (0x7A8E0026, 30749, 0xA8E00108, 82.301, 85.604, 23.137, 0, 0, 0, -1, False, '2019-02-10 00:00:00'); /* Defiled Temple Lower Wing */
/* @teleloc 0xA8E00108 [82.301000 85.604000 23.137000] 0.000000 0.000000 0.000000 -1.000000 */
INSERT INTO `landblock_instance` (`guid`, `weenie_Class_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)
VALUES (0x7A8E0027, 30750, 0xA8E00103, 61.8602, 108.275, 23.137, 0.735976, 0, 0, 0.677008, False, '2019-02-10 00:00:00'); /* Defiled Temple Middle Wing */
/* @teleloc 0xA8E00103 [61.860200 108.275000 23.137000] 0.735976 0.000000 0.000000 0.677008 */
INSERT INTO `landblock_instance` (`guid`, `weenie_Class_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)
VALUES (0x7A8E0028, 30752, 0xA8E00112, 83.878, 129.746, 23.137, 1, 0, 0, 0, False, '2019-02-10 00:00:00'); /* Defiled Temple Asylum */
/* @teleloc 0xA8E00112 [83.878000 129.746000 23.137000] 1.000000 0.000000 0.000000 0.000000 */
INSERT INTO `landblock_instance` (`guid`, `weenie_Class_Id`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`, `is_Link_Child`, `last_Modified`)
VALUES (0x7A8E0029, 30751, 0xA8E0010D, 106.189, 105.741, 23.137, -0.722811, 0, 0, -0.691046, False, '2019-02-10 00:00:00'); /* Defiled Temple Upper Wing */
/* @teleloc 0xA8E0010D [106.189000 105.741000 23.137000] -0.722811 0.000000 0.000000 -0.691046 */
|
'use strict'
var config = {}
config.facebook = {
'appID': '261938654297222',
'app<API key>,
'callbackUrl': '/login/facebook/callback/'
}
config.server = {
'port': process.env.PORT || 3000,
'env': process.env.NODE_ENV || 'dev',
'dbUrl': process.env.MONGODB_URI || 'mongodb://localhost:27017/minihero',
'sessionSecret': 'Minihero FTW!'
}
config.defaultLocation = {
// The default location shown to signed out users on /missions is Amsterdam!
latitude: 52.370216,
longitude: 4.895168
}
config.apiKeys = {
google: '<Google Api>'
}
module.exports = config
|
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var <API key> = require("./<API key>").<API key>;
var <API key> = require("./<API key>").<API key>;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new <API key>().getRules());
this.$outdent = new <API key>();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
return null;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
<?php
include_once("bqf_strings.php");
class <API key> extends <API key> {
public function testUnescape() {
$tests = array(
array("one", "one"),
array('<a href="test">test</a>', '<a href="test">test</a>'),
array(' with spaces ', ' with spaces '),
array(' "quoted"', 'quoted'),
array(" `it's a comment` ", "it's a comment"),
array(' "a new\nline" ', "a new\nline"),
array(' "delimited \" in string"', "delimited \" in string"),
array(' "cross \\\' delimit"', "cross \\' delimit")
);
foreach ($tests as $test) {
$this->assertEquals(bqf_unescape_string($test[0]), $test[1]);
}
}
}
|
\hypertarget{<API key>}{\section{Particle\-System\-:\-:Grav\-Obj Strukturreferenz}
\label{<API key>}\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}}
}
{\ttfamily \#include $<$Particle\-System.\-h$>$}
\subsection*{Öffentliche Attribute}
\begin{DoxyCompactItemize}
\item
cl\-\_\-float \hyperlink{<API key>}{x}
\item
cl\-\_\-float \hyperlink{<API key>}{y}
\item
cl\-\_\-float \hyperlink{<API key>}{z}
\item
cl\-\_\-float \hyperlink{<API key>}{mass}
\end{DoxyCompactItemize}
\subsection{Ausführliche Beschreibung}
Definiert in Zeile 49 der Datei Particle\-System.\-h.
\subsection{Dokumentation der Datenelemente}
\hypertarget{<API key>}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!mass@{mass}}
\index{mass@{mass}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}}
\subsubsection[{mass}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::mass}}\label{<API key>}
Definiert in Zeile 53 der Datei Particle\-System.\-h.
\hypertarget{<API key>}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!x@{x}}
\index{x@{x}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}}
\subsubsection[{x}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::x}}\label{<API key>}
Definiert in Zeile 50 der Datei Particle\-System.\-h.
\hypertarget{<API key>}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!y@{y}}
\index{y@{y}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}}
\subsubsection[{y}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::y}}\label{<API key>}
Definiert in Zeile 51 der Datei Particle\-System.\-h.
\hypertarget{<API key>}{\index{Particle\-System\-::\-Grav\-Obj@{Particle\-System\-::\-Grav\-Obj}!z@{z}}
\index{z@{z}!ParticleSystem::GravObj@{Particle\-System\-::\-Grav\-Obj}}
\subsubsection[{z}]{\setlength{\rightskip}{0pt plus 5cm}cl\-\_\-float Particle\-System\-::\-Grav\-Obj\-::z}}\label{<API key>}
Definiert in Zeile 52 der Datei Particle\-System.\-h.
Die Dokumentation für diese Struktur wurde erzeugt aufgrund der Datei\-:\begin{DoxyCompactItemize}
\item
/daten/\-Projekte/eclipse\-\_\-workspace/\-C\-L\-G\-L\-\_\-test/\hyperlink{<API key>}{Particle\-System.\-h}\end{DoxyCompactItemize}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Rgaa32016 Test.11.01.2 NA 03</title>
</head>
<body class="NA">
<div>
<h1>Rgaa32016 Test.11.01.2 NA 03</h1>
<!-- START [test-detail] -->
<div class="test-detail" lang="fr">
Chaque <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/2016/glossaire.html
</div>
<!-- END [test-detail] -->
<ul>
<li> The form field has an id attribute</li>
<li> The value of the id attribute is unique</li>
</ul>
<p></p>
<div class="testcase">
<form action="http://action.html" method="post">
<p> <input type="password" id="text" title="password input title" /> <input type="submit" value="Send" /> <input type="reset" /> </p>
</form>
</div>
<p class="test-explanation"> NA: the page has no form field associated with a label tag </p>
</div>
</body>
</html>
|
# -*- encoding: utf-8 -*-
# res_partner
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from osv import fields, osv
from datetime import datetime, timedelta
from openerp.tools.translate import _
class res_company(osv.osv):
_name = "res.company"
_inherit = "res.company"
_columns = {
'web_discount': fields.float('Descuento web (%)'),
}
|
package com.stratelia.webactiv.util.node.model;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.<API key>;
import java.io.Serializable;
import java.text.ParseException;
import org.silverpeas.search.indexEngine.model.IndexEntry;
import com.silverpeas.util.clipboard.ClipboardSelection;
import com.silverpeas.util.clipboard.SilverpeasKeyData;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.util.DateUtil;
public class NodeSelection extends ClipboardSelection implements Serializable {
private static final long serialVersionUID = -<API key>;
public static DataFlavor NodeDetailFlavor;
static {
NodeDetailFlavor = new DataFlavor(NodeDetail.class, "Node");
}
private NodeDetail nodeDetail;
public NodeSelection(NodeDetail node) {
super();
nodeDetail = node;
super.addFlavor(NodeDetailFlavor);
}
@Override
public synchronized Object getTransferData(DataFlavor parFlavor)
throws <API key> {
Object transferedData;
try {
transferedData = super.getTransferData(parFlavor);
} catch (<API key> e) {
if (parFlavor.equals(NodeDetailFlavor)) {
transferedData = nodeDetail;
} else {
throw e;
}
}
return transferedData;
}
@Override
public IndexEntry getIndexEntry() {
NodePK pk = nodeDetail.getNodePK();
IndexEntry indexEntry = new IndexEntry(pk.getInstanceId(), "Node", pk.getId());
indexEntry.setTitle(nodeDetail.getName());
return indexEntry;
}
@Override
public SilverpeasKeyData getKeyData() {
SilverpeasKeyData keyData = new SilverpeasKeyData();
keyData.setTitle(nodeDetail.getName());
keyData.setAuthor(nodeDetail.getCreatorId());
try {
keyData.setCreationDate(DateUtil.parse(nodeDetail.getCreationDate()));
} catch (ParseException e) {
SilverTrace.error("node", "NodeSelection.getKeyData()", "root.EX_NO_MESSAGE", e);
}
keyData.setDesc(nodeDetail.getDescription());
return keyData;
}
}
|
import React, { useState } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { TimeZone } from '@grafana/data';
import { CollapsableSection, Field, Input, RadioButtonGroup, TagsInput } from '@grafana/ui';
import { selectors } from '@grafana/e2e-selectors';
import { FolderPicker } from 'app/core/components/Select/FolderPicker';
import { DashboardModel } from '../../state/DashboardModel';
import { <API key> } from '../DeleteDashboard/<API key>';
import { TimePickerSettings } from './TimePickerSettings';
import { <API key>, <API key> } from 'app/features/dashboard/state/actions';
import { PreviewSettings } from './PreviewSettings';
import { config } from '@grafana/runtime';
interface OwnProps {
dashboard: DashboardModel;
}
export type Props = OwnProps & ConnectedProps<typeof connector>;
const <API key> = [
{ value: 0, label: 'Default' },
{ value: 1, label: 'Shared crosshair' },
{ value: 2, label: 'Shared Tooltip' },
];
export function <API key>({ dashboard, updateTimeZone, updateWeekStart }: Props): JSX.Element {
const [renderCounter, setRenderCounter] = useState(0);
const onFolderChange = (folder: { id: number; title: string }) => {
dashboard.meta.folderId = folder.id;
dashboard.meta.folderTitle = folder.title;
dashboard.meta.<API key> = true;
};
const onBlur = (event: React.FocusEvent<HTMLInputElement>) => {
dashboard[event.currentTarget.name as 'title' | 'description'] = event.currentTarget.value;
};
const onTooltipChange = (graphTooltip: number) => {
dashboard.graphTooltip = graphTooltip;
setRenderCounter(renderCounter + 1);
};
const <API key> = (intervals: string[]) => {
dashboard.timepicker.refresh_intervals = intervals.filter((i) => i.trim() !== '');
};
const onNowDelayChange = (nowDelay: string) => {
dashboard.timepicker.nowDelay = nowDelay;
};
const <API key> = (hide: boolean) => {
dashboard.timepicker.hidden = hide;
setRenderCounter(renderCounter + 1);
};
const onLiveNowChange = (v: boolean) => {
dashboard.liveNow = v;
setRenderCounter(renderCounter + 1);
};
const onTimeZoneChange = (timeZone: TimeZone) => {
dashboard.timezone = timeZone;
setRenderCounter(renderCounter + 1);
updateTimeZone(timeZone);
};
const onWeekStartChange = (weekStart: string) => {
dashboard.weekStart = weekStart;
setRenderCounter(renderCounter + 1);
updateWeekStart(weekStart);
};
const onTagsChange = (tags: string[]) => {
dashboard.tags = tags;
setRenderCounter(renderCounter + 1);
};
const onEditableChange = (value: boolean) => {
dashboard.editable = value;
setRenderCounter(renderCounter + 1);
};
const editableOptions = [
{ label: 'Editable', value: true },
{ label: 'Read-only', value: false },
];
return (
<div style={{ maxWidth: '600px' }}>
<h3 className="<API key>" aria-label={selectors.pages.Dashboard.Settings.General.title}>
General
</h3>
<div className="gf-form-group">
<Field label="Name">
<Input id="title-input" name="title" onBlur={onBlur} defaultValue={dashboard.title} />
</Field>
<Field label="Description">
<Input id="description-input" name="description" onBlur={onBlur} defaultValue={dashboard.description} />
</Field>
<Field label="Tags">
<TagsInput id="tags-input" tags={dashboard.tags} onChange={onTagsChange} />
</Field>
<Field label="Folder">
<FolderPicker
inputId="<API key>"
initialTitle={dashboard.meta.folderTitle}
initialFolderId={dashboard.meta.folderId}
onChange={onFolderChange}
enableCreateNew={true}
dashboardId={dashboard.id}
skipInitialLoad={true}
/>
</Field>
<Field
label="Editable"
description="Set to read-only to disable all editing. Reload the dashboard for changes to take effect"
>
<RadioButtonGroup value={dashboard.editable} options={editableOptions} onChange={onEditableChange} />
</Field>
</div>
{config.featureToggles.dashboardPreviews && config.featureToggles.<API key> && (
<PreviewSettings uid={dashboard.uid} />
)}
<TimePickerSettings
onTimeZoneChange={onTimeZoneChange}
onWeekStartChange={onWeekStartChange}
<API key>={<API key>}
onNowDelayChange={onNowDelayChange}
<API key>={<API key>}
onLiveNowChange={onLiveNowChange}
refreshIntervals={dashboard.timepicker.refresh_intervals}
timePickerHidden={dashboard.timepicker.hidden}
nowDelay={dashboard.timepicker.nowDelay}
timezone={dashboard.timezone}
weekStart={dashboard.weekStart}
liveNow={dashboard.liveNow}
/>
<CollapsableSection label="Panel options" isOpen={true}>
<Field
label="Graph tooltip"
description="Controls tooltip and hover highlight behavior across different panels"
>
<RadioButtonGroup onChange={onTooltipChange} options={<API key>} value={dashboard.graphTooltip} />
</Field>
</CollapsableSection>
<div className="gf-form-button-row">
{dashboard.meta.canDelete && <<API key> dashboard={dashboard} />}
</div>
</div>
);
}
const mapDispatchToProps = {
updateTimeZone: <API key>,
updateWeekStart: <API key>,
};
const connector = connect(null, mapDispatchToProps);
export const GeneralSettings = connector(<API key>);
|
# This file is part of pi-led-control.
# pi-led-control is free software: you can redistribute it and/or modify
# (at your option) any later version.
# pi-led-control is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import datetime
import logging
from server.programs.abstractprogram import AbstractProgram
class ScheduledProgram(AbstractProgram):
def __init__(self, program, timeOfDay):
super().__init__()
self._program = program
self._timeOfDay = timeOfDay
def run(self):
now = datetime.datetime.now()
secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second
if secondsInCurrentDay < self._timeOfDay:
sleepDuration = self._timeOfDay - secondsInCurrentDay
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
def setThreadStopEvent(self, threadStopEvent):
self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent)
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
return self._program.getCurrentColor()
def setLastColor(self, lastColor):
self._program.setLastColor(lastColor)
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Fri Mar 21 17:32:01 PDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.java.chatroom.groupchat3 Class Hierarchy</title>
<meta name="date" content="2014-03-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.java.chatroom.groupchat3 Class Hierarchy";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/java/chatroom/basic2threading/package-tree.html">Prev</a></li>
<li><a href="../../../../com/java/chatroom/privatechat4/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/java/chatroom/groupchat3/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h1 class="title">Hierarchy For Package com.java.chatroom.groupchat3</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Client.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Client</span></a></li>
<li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/CloseUtil.html" title="class in com.java.chatroom.groupchat3"><span class="strong">CloseUtil</span></a></li>
<li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/MultiServer.html" title="class in com.java.chatroom.groupchat3"><span class="strong">MultiServer</span></a></li>
<li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Receive.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Receive</span></a> (implements java.lang.Runnable)</li>
<li type="circle">com.java.chatroom.groupchat3.<a href="../../../../com/java/chatroom/groupchat3/Send.html" title="class in com.java.chatroom.groupchat3"><span class="strong">Send</span></a> (implements java.lang.Runnable)</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/java/chatroom/basic2threading/package-tree.html">Prev</a></li>
<li><a href="../../../../com/java/chatroom/privatechat4/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/java/chatroom/groupchat3/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
from pathlib import Path
from inxs.cli import main as _main
from tests import equal_documents
def main(*args):
_args = ()
for arg in args:
if isinstance(arg, Path):
_args += (str(arg),)
else:
_args += (arg,)
_main(_args)
# TODO case-study with this use-case
def test_mods_to_tei(datadir):
main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml")
assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml")
|
var _ = require('underscore');
deepExtend = function(obj) {
var parentRE = /
slice = Array.prototype.slice,
hasOwnProperty = Object.prototype.hasOwnProperty;
_.each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (hasOwnProperty.call(source, prop)) {
if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) {
obj[prop] = source[prop];
}
else if (_.isString(source[prop]) && parentRE.test(source[prop])) {
if (_.isString(obj[prop])) {
obj[prop] = source[prop].replace(parentRE, obj[prop]);
}
}
else if (_.isArray(obj[prop]) || _.isArray(source[prop])){
if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){
throw 'Error: Trying to combine an array with a non-array (' + prop + ')';
} else {
obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);});
}
}
else if (_.isObject(obj[prop]) || _.isObject(source[prop])){
if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){
throw 'Error: Trying to combine an object with a non-object (' + prop + ')';
} else {
obj[prop] = _.deepExtend(obj[prop], source[prop]);
}
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
};
exports.deepExtend = deepExtend;
|
package output;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class XmlParserJhove {
public static void main(String args[]) throws Exception {
JOptionPane.showMessageDialog(null, "Please choose the XML File to analyse", "XmlParsing", JOptionPane.QUESTION_MESSAGE);
String xmlfile = utilities.BrowserDialogs.chooseFile();
parseXmlFile(xmlfile);
}
public static void parseXmlFile(String xmlfile) {
try {
<API key> dbFactory = <API key>.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlfile);
PrintWriter xmlsummary = new PrintWriter(new FileWriter((jhoveValidations.<API key>.<API key> + "//" + "<API key>" + ".xml")));
String xmlVersion = "xml version='1.0'";
String xmlEncoding = "encoding='ISO-8859-1'";
String xmlxslStyleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"JhoveCustomized.xsl\"?>";
xmlsummary.println("<?" + xmlVersion + " " + xmlEncoding + "?>");
xmlsummary.println(xmlxslStyleSheet);
xmlsummary.println("<<API key>>");
output.XslStyleSheetsJhove.JhoveCustomizedXsl();
ArrayList<String> errormessages = new ArrayList<String>();
doc.getDocumentElement().normalize();
NodeList nList = doc.<API key>("item");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
xmlsummary.println("<File>");
String testutf8 = eElement.<API key>("filename").item(0).getTextContent();
if (testutf8.contains("&")) {
String sub = utilities.GenericUtilities.normaliseToUtf8(testutf8);
xmlsummary.println("<FileName>" + sub + "</FileName>");
} else {
xmlsummary.println("<FileName>" + eElement.<API key>("filename").item(0).getTextContent() + "</FileName>");
}
if (eElement.<API key>("creationyear").item(0)!= null) {
xmlsummary.println("<CreationYear>" + eElement.<API key>("creationyear").item(0).getTextContent() + "</CreationYear>");
}
if (eElement.<API key>("creationsoftware").item(0)!= null) {
xmlsummary.println("<CreationSoftware>" + eElement.<API key>("creationsoftware").item(0).getTextContent() + "</CreationSoftware>");
}
if (eElement.<API key>("encryption").item(0)!= null) {
xmlsummary.println("<Encryption>" + eElement.<API key>("encryption").item(0).getTextContent() + "</Encryption>");
}
if (eElement.<API key>("PdfType").item(0)!= null) {
xmlsummary.println("<PdfType>" + eElement.<API key>("PdfType").item(0).getTextContent() + "</PdfType>");
}
xmlsummary.println("<Module>" + eElement.<API key>("reportingModule").item(0).getTextContent() + "</Module>");
xmlsummary.println("<Status>" + eElement.<API key>("status").item(0).getTextContent() + "</Status>");
String status = eElement.<API key>("status").item(0).getTextContent();
if ((status.contains("Not")) || (status.contains("not"))) {
System.out.println(eElement.<API key>("filename").item(0).getTextContent());
int lenmessages = eElement.<API key>("message").getLength();
xmlsummary.println("<JhoveMessages>" + lenmessages + "</JhoveMessages>");
for (int temp3 = 0; temp3 < lenmessages; temp3++) {
String error = eElement.<API key>("message").item(temp3).getTextContent();
int writtenmessage = temp3 + 1;
//TODO: get rid of xml escaping characters
error = error.replace("\"", """);
error = error.replace("\'", "'");
error = error.replace("<", "<");
error = error.replace(">", ">");
error = error.replace("&", " &");
xmlsummary.println("<Message" + writtenmessage + ">" + error + "</Message" + writtenmessage + ">");
errormessages.add(error);
}
}
xmlsummary.println("</File>"); //TODO: should be changed to File, but as well in XSLT
}
}
Collections.sort(errormessages);
int i;
// copy ErrorList because later the no. of entries of each
// element will be counted
ArrayList<String> originerrors = new ArrayList<String>();
for (i = 0; i < errormessages.size(); i++) { // There might be a
// pre-defined
// function for this
originerrors.add(errormessages.get(i));
}
// get rid of redundant entries
i = 0;
while (i < errormessages.size() - 1) {
if (errormessages.get(i).equals(errormessages.get(i + 1))) {
errormessages.remove(i);
} else {
i++;
}
}
xmlsummary.println("<SampleSummary>");
xmlsummary.println("<ExaminedPdfFiles>" + nList.getLength() + "</ExaminedPdfFiles>");
xmlsummary.println("<<API key>>" + errormessages.size() + "</<API key>>");
// how often does each JHOVE error occur?
int j = 0;
int temp1;
for (i = 0; i < errormessages.size(); i++) {
temp1 = 0;
for (j = 0; j < originerrors.size(); j++) {
if (errormessages.get(i).equals(originerrors.get(j))) {
temp1++;
}
}
xmlsummary.println("<JhoveMessage>");
xmlsummary.println("<MessageText>" + errormessages.get(i) + "</MessageText>");
xmlsummary.println("<Occurance>" + temp1 + "</Occurance>");
xmlsummary.println("</JhoveMessage>");
}
xmlsummary.println("</SampleSummary>");
xmlsummary.println("</<API key>>");
xmlsummary.close();
}
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e, "error message", JOptionPane.ERROR_MESSAGE);
}
}
}
|
{-# LANGUAGE <API key> #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -<API key> #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE FlexibleInstances #-}
module PontariusService.Types where
import Control.Applicative
import Control.Lens
import Control.Monad.Reader
import DBus
import DBus.Signal
import DBus.Types
import Data.ByteString (ByteString)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX as Time
import Data.Typeable
import Data.UUID (UUID)
import qualified Data.UUID as UUID
import Data.Word
import qualified Network.Xmpp as Xmpp
type SSID = ByteString
data BatchLink = BatchLinkIgnore
| BatchLinkExisting UUID
| BatchLinkNewContact Text
instance Representable BatchLink where
type RepType BatchLink = 'TypeStruct '[ 'DBusSimpleType 'TypeByte
, 'DBusSimpleType 'TypeString]
toRep BatchLinkIgnore = DBVStruct (StructCons
(DBVByte 0) (StructSingleton (DBVString "")))
toRep (BatchLinkExisting uuid)
= DBVStruct (StructCons (DBVByte 1) (StructSingleton (toRep uuid)))
toRep (BatchLinkNewContact name)
= DBVStruct (StructCons (DBVByte 2) (StructSingleton (toRep name)))
fromRep
(DBVStruct (StructCons (DBVByte 0) (StructSingleton _)))
= Just BatchLinkIgnore
fromRep (DBVStruct (StructCons (DBVByte 1) (StructSingleton uuid)))
= BatchLinkExisting <$> (fromRep uuid)
fromRep (DBVStruct (StructCons (DBVByte 2) (StructSingleton (DBVString name))))
= Just $ BatchLinkNewContact name
data PontariusState = CredentialsUnset
| IdentityNotFound
| IdentitiesAvailable
| CreatingIdentity
| Disabled
| Authenticating
| Authenticated
| <API key>
deriving (Show, Eq)
data AccountState = AccountEnabled
| AccountDisabled
deriving (Show, Eq)
data PeerStatus = Unavailable
| Available
deriving (Show, Eq)
instance Representable UTCTime where
type RepType UTCTime = 'DBusSimpleType 'TypeUInt32
toRep = DBVUInt32 . round . <API key>
fromRep (DBVUInt32 x) = Just . <API key> $ fromIntegral x
instance DBus.Representable Xmpp.Jid where
type RepType Xmpp.Jid = 'DBusSimpleType 'TypeString
toRep = DBus.DBVString . Xmpp.jidToText
fromRep (DBus.DBVString s) = Xmpp.jidFromText s
instance (Ord a, DBus.Representable a) => DBus.Representable (Set a) where
type RepType (Set a) = RepType [a]
toRep = toRep . Set.toList
fromRep = fmap Set.fromList . fromRep
instance Representable (Maybe KeyID) where
type RepType (Maybe KeyID) = RepType KeyID
toRep Nothing = toRep Text.empty
toRep (Just k) = toRep k
fromRep v = case fromRep v of
Nothing -> Nothing
Just v' | Text.null v' -> Just Nothing
| otherwise -> Just (Just v')
instance Representable (Maybe UTCTime) where
type RepType (Maybe UTCTime) = RepType UTCTime
toRep Nothing = toRep (0 :: Word32)
toRep (Just t) = toRep t
fromRep v = case fromRep v of
Nothing -> Nothing
Just t' | t' == (0 :: Word32) -> Just Nothing
| otherwise -> Just . Just $ <API key>
$ fromIntegral t'
type KeyID = Text
type SessionID = ByteString
data ConnectionStatus = Connected
| Disconnected
deriving (Show, Eq, Ord)
data InitResponse = KeyOK
| SelectKey
data Ent = Ent { entityJid :: Xmpp.Jid
, entityDisplayName :: Text
, entityDescription :: Text
} deriving (Show, Typeable)
data AkeEvent = AkeEvent { akeEventStart :: UTCTime
, akeEventSuccessfull :: Bool
, akeEventPeerJid :: Xmpp.Jid
, akeEventOurJid :: Xmpp.Jid
, akeEventPeerkeyID :: KeyID
, akeEventOurkeyID :: KeyID
} deriving (Show, Eq)
data ChallengeEvent =
ChallengeEvent { <API key> :: Bool
, <API key> :: UTCTime
, <API key> :: UTCTime
, <API key> :: Text
, <API key> :: Text
} deriving (Show, Eq)
data RevocationEvent =
RevocationEvent { <API key> :: KeyID
, revocationEventTime :: UTCTime
}
data <API key> =
RevocationlEvent { <API key> :: KeyID
, <API key> :: UTCTime
}
makePrisms ''PontariusState
makeRepresentable ''PontariusState
makePrisms ''AccountState
makeRepresentable ''AccountState
makeRepresentable ''<API key>
makeRepresentable ''ConnectionStatus
makeRepresentable ''InitResponse
makeRepresentable ''Ent
makeRepresentable ''AkeEvent
makeRepresentable ''ChallengeEvent
makeRepresentable ''RevocationEvent
makeRepresentable ''PeerStatus
instance DBus.Representable UUID where
type RepType UUID = RepType Text
toRep = toRep . Text.pack . UUID.toString
fromRep = UUID.fromString . Text.unpack <=< fromRep
data AddPeerFailed =
AddPeerFailed { addPeerFailedPeer :: !Xmpp.Jid
, addPeerFailedReason :: !Text
} deriving (Show)
makeRepresentable ''AddPeerFailed
makeLensesWith camelCaseFields ''AddPeerFailed
data RemovePeerFailed =
RemovePeerFailed { <API key> :: !Xmpp.Jid
, <API key> :: !Text
} deriving (Show)
makeRepresentable ''RemovePeerFailed
makeLensesWith camelCaseFields ''RemovePeerFailed
|
class Transfer < Entry
state_machine :initial => :open, :namespace => :transfer do
event :close do
transition :paid => :closed
end
state :open, :value => 400
state :closed, :value => 430
end
def <API key>
[BankAccount, CreditCard]
end
end
|
#!/usr/bin/env python
# This file is part of Essentia
# Essentia is free software: you can redistribute it and/or modify it under
# option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# details.
from essentia_test import *
class TestHPCP(TestCase):
def testEmpty(self):
hpcp = HPCP()([], [])
self.assertEqualVector(hpcp, [0.]*12)
def testZeros(self):
hpcp = HPCP()([0]*10, [0]*10)
self.assertEqualVector(hpcp, [0.]*12)
def testSin440(self):
# Tests whether a real audio signal of one pure tone gets read as a
# single semitone activation, and gets read into the right pcp bin
sampleRate = 44100
audio = MonoLoader(filename = join(testdata.audio_dir, 'generated/synthesised/sin440_0db.wav'),
sampleRate = sampleRate)()
speaks = SpectralPeaks(sampleRate = sampleRate,
maxPeaks = 1,
maxFrequency = sampleRate/2,
minFrequency = 0,
magnitudeThreshold = 0,
orderBy = 'magnitude')
(freqs, mags) = speaks(Spectrum()(audio))
hpcp = HPCP()(freqs, mags)
self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.])
def testAllSemitones(self):
# Tests whether a spectral peak output of 12 consecutive semitones
# yields a HPCP of all 1's
tonic = 440
freqs = [(tonic * 2**(x/12.)) for x in range(12)]
mags = [1] * 12
hpcp = HPCP()(freqs, mags)
self.assertEqualVector(hpcp, [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.])
def <API key>(self):
# Make sure that the submediant of a key based on 440 is in the
# correct location (submediant was randomly selected from all the
# tones)
tonic = 440
submediant = tonic * 2**(9./12.)
hpcp = HPCP()([submediant], [1])
self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.])
def testMaxShifted(self):
# Tests whether a HPCP reading with only the dominant semitone
# activated is correctly shifted so that the dominant is at the
# position 0
tonic = 440
dominant = tonic * 2**(7./12.)
hpcp = HPCP(maxShifted=True)([dominant], [1])
self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.])
def chordHelper(self, half_steps, tunning, strength):
notes = [tunning*(2.**(half_steps[i]/12.)) for i in range(len(half_steps))]
hpcp = HPCP(maxShifted=False)([notes[0], notes[1], notes[2]], strength)
for i in range(len(hpcp)):
if i in half_steps: self.assertTrue(hpcp[i]>0)
elif (i - 12) in half_steps: self.assertTrue(hpcp[i]>0)
else: self.assertEqual(hpcp[i], 0)
def testChord(self):
tunning = 440
AMajor = [0, 4, 7] # AMajor = A4-C#5-E5
self.chordHelper(AMajor, tunning, [1,1,1])
CMajor = [3, -4, -2] # CMajor = C5-F4-G4
self.chordHelper(CMajor, tunning, [1,1,1])
CMajor = [-4, 3, -2] # CMajor = C5-F4-G4
self.chordHelper(CMajor, tunning, [1,0.5,0.2])
CMajor = [-4, -2, 3] # CMajor = C5-F4-G4
self.chordHelper(CMajor, tunning, [1,0.5,0.2])
CMajor = [3, 8, 10] # CMajor = C5-F5-G5
self.chordHelper(CMajor, tunning, [1,0.5,0.2])
AMinor = [0, 3, 7] # AMinor = A4-C5-E5
self.chordHelper(AMinor, tunning, [1,0.5,0.2])
CMinor = [3, 6, 10] # CMinor = C5-E5-G5
self.chordHelper(CMinor, tunning, [1,0.5,0.2])
# Test of various parameter logical bounds
def testLowFrequency(self):
hpcp = HPCP(minFrequency=100, maxFrequency=1000)([99], [1])
self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.])
def testHighFrequency(self):
hpcp = HPCP(minFrequency=100, maxFrequency=1000)([1001], [1])
self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.])
def testSmallMinRange(self):
self.<API key>(HPCP(), {'minFrequency':1, 'splitFrequency':200})
def testSmallMaxRange(self):
self.<API key>(HPCP(), {'maxFrequency':1199, 'splitFrequency':1000})
def <API key>(self):
self.<API key>(HPCP(), {'bandPreset':False, 'maxFrequency':200, 'minFrequency':1})
def <API key>(self):
self.<API key>(HPCP(), {'size':13})
def testHarmonics(self):
# Regression test for the 'harmonics' parameter
tone = 100. # arbitrary frequency [Hz]
freqs = [tone, tone*2, tone*3, tone*4]
mags = [1]*4
hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3)
hpcp = hpcpAlg(freqs, mags)
expected = [0., 0., 0., 0.1340538263, 0., 0.2476127148, 0., 0., 0., 0., 1., 0.]
self.<API key>(hpcp, expected, 1e-4)
def testRegression(self):
# Just makes sure algorithm does not crash on a real data source. This
# test is not really looking for correctness. Maybe consider revising
inputSize = 512
sampleRate = 44100
audio = MonoLoader(filename = join(testdata.audio_dir, join('recorded', 'musicbox.wav')),
sampleRate = sampleRate)()
fc = FrameCutter(frameSize = inputSize,
hopSize = inputSize)
windowingAlg = Windowing(type = 'blackmanharris62')
specAlg = Spectrum(size=inputSize)
sPeaksAlg = SpectralPeaks(sampleRate = sampleRate,
maxFrequency = sampleRate/2,
minFrequency = 0,
orderBy = 'magnitude')
hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3)
frame = fc(audio)
while len(frame) != 0:
spectrum = specAlg(windowingAlg(frame))
(freqs, mags) = sPeaksAlg(spectrum)
hpcp = hpcpAlg(freqs,mags)
self.assertTrue(not any(numpy.isnan(hpcp)))
self.assertTrue(not any(numpy.isinf(hpcp)))
frame = fc(audio)
suite = allTests(TestHPCP)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
|
import CodeClipboard from './CodeClipboard';
export default CodeClipboard;
|
--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
<API key> = <API key>:new {
playerRaces = { "object/creature/player/bothan_male.iff",
"object/creature/player/bothan_female.iff",
"object/creature/player/human_male.iff",
"object/creature/player/human_female.iff",
"object/creature/player/ithorian_male.iff",
"object/creature/player/ithorian_female.iff",
"object/creature/player/moncal_male.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_male.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_male.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_male.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_male.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/wookiee_male.iff",
"object/creature/player/wookiee_female.iff",
"object/creature/player/zabrak_male.iff",
"object/creature/player/zabrak_female.iff" },
-- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK,
-- <API key>, <API key>, <API key>, HEAVYLAUNCHERATTACK
attackType = MELEEATTACK,
-- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, LIGHTSABER
damageType = LIGHTSABER,
-- NONE, LIGHT, MEDIUM, HEAVY
armorPiercing = MEDIUM,
-- <API key>, <API key>, <API key>, <API key>, <API key>
-- <API key>, <API key>, <API key>, <API key>, combat_general,
-- <API key>, jedi_general, <API key>
xpType = "jedi_general",
-- See http:
<API key> = { "<API key>" },
-- See http:
<API key> = { "<API key>" },
-- See http:
<API key> = { "melee_defense" },
-- Leave as "dodge" for now, may have additions later
<API key> = { "saber_block" },
-- See http:
speedModifiers = { "<API key>" },
-- Leave blank for now
damageModifiers = { },
-- The values below are the default values. To be used for blue frog objects primarily
healthAttackCost = 50,
actionAttackCost = 85,
mindAttackCost = 35,
forceCost = 36,
pointBlankRange = 0,
pointBlankAccuracy = 20,
idealRange = 3,
idealAccuracy = 15,
maxRange = 5,
maxRangeAccuracy = 5,
minDamage = 195,
maxDamage = 285,
attackSpeed = 5.1,
woundsRatio = 25,
<API key> = { "<API key>" },
noTrade = 1,
childObjects = {
{templateFile = "object/tangible/inventory/<API key>.iff", x = 0, z = 0, y = 0, ox = 0, oy = 0, oz = 0, ow = 0, cellid = -1, containmentType = 4}
},
<API key> = {1, 1, 2, 2, 2, 2, 2, 1, 1, 1},
<API key> = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "SR", "UT", "CD", "OQ", "OQ", "OQ", "OQ"},
experimentalWeights = {1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1},
<API key> = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "expEffeciency", "expEffeciency", "expEffeciency"},
<API key> = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "forcecost", "attackhealthcost", "attackactioncost", "attackmindcost"},
experimentalMin = {0, 0, 195, 285, 5.1, 19, 40, 50, 85, 35},
experimentalMax = {0, 0, 215, 305, 4.8, 31, 36, 45, 55, 30},
<API key> = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
<API key> = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1},
}
ObjectTemplates:addTemplate(<API key>, "object/weapon/melee/polearm/crafted_saber/<API key>.iff")
|
<html>
<head>
<title>Frankenstein, 1831, Vol. 3, Chap. 1, Frame 2</title>
</head>
<body>
<p>
I <a href="../V3notes/trembled.html">trembled violently</a> at
his exordium, and my father continued
"I confess, my son, that I have always looked forward to your
marriage with our dear Elizabeth as <a
href="../V3notes/domestic.html">the tie of our domestic
comfort</a>, and the stay of my declining years. You were
attached to each other from your earliest infancy; you studied
together, and appeared, in dispositions and tastes, entirely
suited to one another. But so blind is the experience of man,
that what I conceived to be the best assistants to my plan, may
have entirely destroyed it. You, perhaps, regard her as your
sister, without any wish that she might become your wife. Nay,
you may have met with another whom you may love; and, considering
yourself as bound in honour to Elizabeth, this struggle may
occasion the poignant misery which you appear to feel."</p><p>
"My dear father, re-assure yourself. I love my cousin tenderly
and sincerely. I never saw any woman who excited, as Elizabeth
does, my warmest admiration and affection. My future hopes and
prospects are entirely bound up in the expectation of our union."</p><p>
"The expression of your sentiments on this subject, my dear
Victor, gives me more pleasure than I have for some time
experienced. If you feel thus, we shall assuredly be happy,
however present events may cast a gloom over us. But it is this
gloom which appears to have taken so strong a hold of your mind,
that I wish to dissipate. Tell me, therefore, whether you object
to an immediate solemnisation of the marriage. We have been
unfortunate, and recent events have drawn us from that every-day
tranquillity befitting my years and infirmities. You are younger;
yet I do not suppose, possessed as you are of a competent
fortune, that an <a href="../V3notes/earlymar.html">early
marriage would at all interfere with any future plans of honour
and utility</a> that you may have formed. Do not suppose,
however, that I wish to dictate happiness to you, or that a delay
on your part would cause me any serious uneasiness. Interpret my
words with <a href="../V3notes/candour.html">candour</a>, and
answer me, I conjure you, with confidence and sincerity."</p>
</body>
</html>
|
package org.animotron.cache;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*
*/
public interface Cache {
public boolean available(String key) throws IOException;
public void get(String key, OutputStream out) throws IOException;
public void get(String key, StringBuilder out) throws IOException;
public String get(String key) throws IOException;
public OutputStream stream(String key, OutputStream out) throws IOException;
public OutputStream stream(String key, StringBuilder out) throws IOException;
public void drop(String key) throws IOException;
}
|
<?php
require_once 'ke_db.php';
require_once 'ke_tools.php';
abstract class ke_model extends ke_tools
{
protected $db;
protected $table_name;
public $errors;
public function __construct($name)
{
$this->db = new ke_db();
$this->table_name = $name;
$this->errors = '';
}
protected function new_error_msg($msg)
{
$this->errors .= $msg;
}
abstract public function exists();
abstract public function save();
Esta función sirve para eliminar los datos del objeto de la base de datos
abstract public function delete();
devuelve el número de elementos de la tabla
public function total()
{
$num = 0;
$aux = $this->db->select("SELECT COUNT(*) as num FROM ".$this->table_name.";");
if($aux)
$num = intval($aux[0]['num']);
return $num;
}
}
?>
|
// generator: ilarkesto.mda.legacy.generator.EntityGenerator
package scrum.server.collaboration;
import java.util.*;
import ilarkesto.persistence.*;
import ilarkesto.core.logging.Log;
import ilarkesto.base.*;
import ilarkesto.base.time.*;
import ilarkesto.auth.*;
public abstract class GComment
extends AEntity
implements ilarkesto.auth.ViewProtected<scrum.server.admin.User>, ilarkesto.search.Searchable, java.lang.Comparable<Comment> {
public final CommentDao getDao() {
return commentDao;
}
protected void repairDeadDatob(ADatob datob) {
}
@Override
public void storeProperties(Map properties) {
super.storeProperties(properties);
properties.put("parentId", this.parentId);
properties.put("authorId", this.authorId);
properties.put("published", this.published);
properties.put("authorName", this.authorName);
properties.put("authorEmail", this.authorEmail);
properties.put("authorNameVisible", this.authorNameVisible);
properties.put("text", this.text);
properties.put("dateAndTime", this.dateAndTime == null ? null : this.dateAndTime.toString());
}
public int compareTo(Comment other) {
return toString().toLowerCase().compareTo(other.toString().toLowerCase());
}
private static final ilarkesto.core.logging.Log LOG = ilarkesto.core.logging.Log.get(GComment.class);
public static final String TYPE = "comment";
// - Searchable
public boolean matchesKey(String key) {
if (super.matchesKey(key)) return true;
if (matchesKey(getText(), key)) return true;
return false;
}
// - parent
private String parentId;
private transient ilarkesto.persistence.AEntity parentCache;
private void updateParentCache() {
parentCache = this.parentId == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById(this.parentId);
}
public final String getParentId() {
return this.parentId;
}
public final ilarkesto.persistence.AEntity getParent() {
if (parentCache == null) updateParentCache();
return parentCache;
}
public final void setParent(ilarkesto.persistence.AEntity parent) {
parent = prepareParent(parent);
if (isParent(parent)) return;
this.parentId = parent == null ? null : parent.getId();
parentCache = parent;
fireModified("parent="+parent);
}
protected ilarkesto.persistence.AEntity prepareParent(ilarkesto.persistence.AEntity parent) {
return parent;
}
protected void <API key>(String entityId) {
if (this.parentId == null || entityId.equals(this.parentId)) {
repairMissingMaster();
}
}
public final boolean isParentSet() {
return this.parentId != null;
}
public final boolean isParent(ilarkesto.persistence.AEntity parent) {
if (this.parentId == null && parent == null) return true;
return parent != null && parent.getId().equals(this.parentId);
}
protected final void updateParent(Object value) {
setParent(value == null ? null : (ilarkesto.persistence.AEntity)getDaoService().getById((String)value));
}
// - author
private String authorId;
private transient scrum.server.admin.User authorCache;
private void updateAuthorCache() {
authorCache = this.authorId == null ? null : (scrum.server.admin.User)userDao.getById(this.authorId);
}
public final String getAuthorId() {
return this.authorId;
}
public final scrum.server.admin.User getAuthor() {
if (authorCache == null) updateAuthorCache();
return authorCache;
}
public final void setAuthor(scrum.server.admin.User author) {
author = prepareAuthor(author);
if (isAuthor(author)) return;
this.authorId = author == null ? null : author.getId();
authorCache = author;
fireModified("author="+author);
}
protected scrum.server.admin.User prepareAuthor(scrum.server.admin.User author) {
return author;
}
protected void <API key>(String entityId) {
if (this.authorId == null || entityId.equals(this.authorId)) {
setAuthor(null);
}
}
public final boolean isAuthorSet() {
return this.authorId != null;
}
public final boolean isAuthor(scrum.server.admin.User author) {
if (this.authorId == null && author == null) return true;
return author != null && author.getId().equals(this.authorId);
}
protected final void updateAuthor(Object value) {
setAuthor(value == null ? null : (scrum.server.admin.User)userDao.getById((String)value));
}
// - published
private boolean published;
public final boolean isPublished() {
return published;
}
public final void setPublished(boolean published) {
published = preparePublished(published);
if (isPublished(published)) return;
this.published = published;
fireModified("published="+published);
}
protected boolean preparePublished(boolean published) {
return published;
}
public final boolean isPublished(boolean published) {
return this.published == published;
}
protected final void updatePublished(Object value) {
setPublished((Boolean)value);
}
// - authorName
private java.lang.String authorName;
public final java.lang.String getAuthorName() {
return authorName;
}
public final void setAuthorName(java.lang.String authorName) {
authorName = prepareAuthorName(authorName);
if (isAuthorName(authorName)) return;
this.authorName = authorName;
fireModified("authorName="+authorName);
}
protected java.lang.String prepareAuthorName(java.lang.String authorName) {
authorName = Str.<API key>(authorName);
return authorName;
}
public final boolean isAuthorNameSet() {
return this.authorName != null;
}
public final boolean isAuthorName(java.lang.String authorName) {
if (this.authorName == null && authorName == null) return true;
return this.authorName != null && this.authorName.equals(authorName);
}
protected final void updateAuthorName(Object value) {
setAuthorName((java.lang.String)value);
}
// - authorEmail
private java.lang.String authorEmail;
public final java.lang.String getAuthorEmail() {
return authorEmail;
}
public final void setAuthorEmail(java.lang.String authorEmail) {
authorEmail = prepareAuthorEmail(authorEmail);
if (isAuthorEmail(authorEmail)) return;
this.authorEmail = authorEmail;
fireModified("authorEmail="+authorEmail);
}
protected java.lang.String prepareAuthorEmail(java.lang.String authorEmail) {
authorEmail = Str.<API key>(authorEmail);
return authorEmail;
}
public final boolean isAuthorEmailSet() {
return this.authorEmail != null;
}
public final boolean isAuthorEmail(java.lang.String authorEmail) {
if (this.authorEmail == null && authorEmail == null) return true;
return this.authorEmail != null && this.authorEmail.equals(authorEmail);
}
protected final void updateAuthorEmail(Object value) {
setAuthorEmail((java.lang.String)value);
}
// - authorNameVisible
private boolean authorNameVisible;
public final boolean isAuthorNameVisible() {
return authorNameVisible;
}
public final void <API key>(boolean authorNameVisible) {
authorNameVisible = <API key>(authorNameVisible);
if (isAuthorNameVisible(authorNameVisible)) return;
this.authorNameVisible = authorNameVisible;
fireModified("authorNameVisible="+authorNameVisible);
}
protected boolean <API key>(boolean authorNameVisible) {
return authorNameVisible;
}
public final boolean isAuthorNameVisible(boolean authorNameVisible) {
return this.authorNameVisible == authorNameVisible;
}
protected final void <API key>(Object value) {
<API key>((Boolean)value);
}
// - text
private java.lang.String text;
public final java.lang.String getText() {
return text;
}
public final void setText(java.lang.String text) {
text = prepareText(text);
if (isText(text)) return;
this.text = text;
fireModified("text="+text);
}
protected java.lang.String prepareText(java.lang.String text) {
text = Str.<API key>(text);
return text;
}
public final boolean isTextSet() {
return this.text != null;
}
public final boolean isText(java.lang.String text) {
if (this.text == null && text == null) return true;
return this.text != null && this.text.equals(text);
}
protected final void updateText(Object value) {
setText((java.lang.String)value);
}
// - dateAndTime
private ilarkesto.base.time.DateAndTime dateAndTime;
public final ilarkesto.base.time.DateAndTime getDateAndTime() {
return dateAndTime;
}
public final void setDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) {
dateAndTime = prepareDateAndTime(dateAndTime);
if (isDateAndTime(dateAndTime)) return;
this.dateAndTime = dateAndTime;
fireModified("dateAndTime="+dateAndTime);
}
protected ilarkesto.base.time.DateAndTime prepareDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) {
return dateAndTime;
}
public final boolean isDateAndTimeSet() {
return this.dateAndTime != null;
}
public final boolean isDateAndTime(ilarkesto.base.time.DateAndTime dateAndTime) {
if (this.dateAndTime == null && dateAndTime == null) return true;
return this.dateAndTime != null && this.dateAndTime.equals(dateAndTime);
}
protected final void updateDateAndTime(Object value) {
value = value == null ? null : new ilarkesto.base.time.DateAndTime((String)value);
setDateAndTime((ilarkesto.base.time.DateAndTime)value);
}
public void updateProperties(Map<?, ?> properties) {
for (Map.Entry entry : properties.entrySet()) {
String property = (String) entry.getKey();
if (property.equals("id")) continue;
Object value = entry.getValue();
if (property.equals("parentId")) updateParent(value);
if (property.equals("authorId")) updateAuthor(value);
if (property.equals("published")) updatePublished(value);
if (property.equals("authorName")) updateAuthorName(value);
if (property.equals("authorEmail")) updateAuthorEmail(value);
if (property.equals("authorNameVisible")) <API key>(value);
if (property.equals("text")) updateText(value);
if (property.equals("dateAndTime")) updateDateAndTime(value);
}
}
protected void <API key>(String entityId) {
super.<API key>(entityId);
<API key>(entityId);
<API key>(entityId);
}
public void ensureIntegrity() {
super.ensureIntegrity();
if (!isParentSet()) {
repairMissingMaster();
return;
}
try {
getParent();
} catch (<API key> ex) {
LOG.info("Repairing dead parent reference");
<API key>(this.parentId);
}
try {
getAuthor();
} catch (<API key> ex) {
LOG.info("Repairing dead author reference");
<API key>(this.authorId);
}
}
static CommentDao commentDao;
public static final void setCommentDao(CommentDao commentDao) {
GComment.commentDao = commentDao;
}
}
|
const { Array } = require.main.require('./Tag/Classes');
class GetTag extends Array {
constructor(client) {
super(client, {
name: 'get',
args: [
{
name: 'array'
}, {
name: 'index'
}
],
minArgs: 2, maxArgs: 2
});
}
async execute(ctx, args) {
const res = await super.execute(ctx, args, true);
args = args.parsedArgs;
let arr = await this.loadArray(ctx, args.array);
let index = this.parseInt(args.index, 'index');
return res.setContent(arr[index]);
}
get implicit() { return false; }
}
module.exports = GetTag;
|
'use strict';
(function() {
describe('Browser charm view', function() {
var container, CharmView, cleanIconHelper, factory, models, node, utils,
view, views, Y, testContainer;
before(function(done) {
Y = YUI(GlobalConfig).use(
'datatype-date',
'<API key>',
'charmstore-api',
'json-stringify',
'juju-charm-models',
'juju-tests-utils',
'juju-tests-factory',
'node',
'node-event-simulate',
'<API key>',
function(Y) {
views = Y.namespace('juju.browser.views');
models = Y.namespace('juju.models');
utils = Y.namespace('juju-tests.utils');
factory = Y.namespace('juju-tests.factory');
CharmView = views.BrowserCharmView;
cleanIconHelper = utils.stubCharmIconPath();
done();
});
});
beforeEach(function() {
window.flags = {};
container = utils.makeContainer(this, 'container');
var testcontent = [
'<div id=testcontent><div class="bws-view-data">',
'</div></div>'
].join();
Y.Node.create(testcontent).appendTo(container);
// Mock out a dummy location for the Store used in view instances.
window.juju_config = {
charmworldURL: 'http://localhost'
};
node = Y.one('#testcontent');
});
afterEach(function() {
window.flags = {};
if (view) {
view.destroy();
}
if (testContainer) {
testContainer.remove(true);
}
node.remove(true);
delete window.juju_config;
container.remove(true);
});
after(function() {
cleanIconHelper();
});
it('renders for inspector mode correctly', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(this),
forInspector: true
});
view.render();
assert.isNull(view.get('container').one('.heading'));
// There is no 'related charms' tab to display.
assert.equal(view.get('container').all('.related-charms').size(), 0);
});
// Return the charm heading node included in the charm detail view.
var makeHeading = function(context, is_subordinate) {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
data.is_subordinate = is_subordinate;
utils.makeContainer(context);
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(context)
});
view.render();
var heading = view.get('container').one('.header');
assert.isNotNull(heading);
return heading;
};
it('avoids showing the subordinate message for non-subordinate charms',
function() {
var heading = makeHeading(this, false);
assert.notInclude(heading.getContent(), 'Subordinate charm');
});
it('shows the subordinate message if the charm is a subordinate',
function() {
var heading = makeHeading(this, true);
assert.include(heading.getContent(), 'Subordinate charm');
});
it('renders local charms for inspector mode correctly', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
data.url = 'local:precise/apache2-10';
var charm = new models.Charm(data);
charm.set('scheme', 'local');
view = new CharmView({
entity: charm,
container: utils.makeContainer(this),
forInspector: true
});
view.render();
assert.isNull(view.get('container').one('.heading'));
assert.isNull(view.get('container').one('#readme'));
assert.isNull(view.get('container').one('#configuration'));
assert.isNull(view.get('container').one('#code'));
assert.isNull(view.get('container').one('#features'));
});
it('has sharing links', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/wordpress',
code_source: { location: 'lp:~foo'}
}),
container: utils.makeContainer(this),
charmstore: factory.makeFakeCharmstore()
});
view.render();
var links = container.all('#sharing a');
assert.equal(links.size(), 3);
});
it('should be able to locate a readme file', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo' }
})
});
view._locateReadme().should.eql('readme.rst');
// Matches for caps as well.
view.get('entity').set('files', [
'hooks/install',
'README.md'
]);
view._locateReadme().should.eql('README.md');
});
it('can generate source, bug, and revno links from its charm', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/ceph-9',
name: 'ceph',
code_source: { location: 'lp:~foo'}
})
});
var url = view._getSourceLink(
view.get('entity').get('code_source').location);
assert.equal('http://bazaar.launchpad.net/~foo/files', url);
assert.equal(
'http://bazaar.launchpad.net/~foo/revision/1',
view._getRevnoLink(url, 1));
assert.equal(
'https://bugs.launchpad.net/charms/+source/ceph',
view._getBugLink(view.get('entity').get('name')));
});
it('excludes source svg files from the source tab', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'icon.svg',
'readme.rst'
],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo'}
}),
container: utils.makeContainer(this)
});
view.render();
var options = Y.one('#code').all('select option');
assert.equal(options.size(), 3);
assert.deepEqual(
options.get('text'),
['Select --', 'readme.rst', 'hooks/install']);
});
it('can generate useful display data for commits', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/ceph-9',
code_source: {
location: 'lp:~foo'
}
})
});
var revisions = [
{
authors: [{
email: 'jdoe@example.com',
name: 'John Doe'
}],
date: '2013-05-02T10:05:32Z',
message: 'The fnord had too much fleem.',
revno: 1
},
{
authors: [{
email: 'jdoe@example.com',
name: 'John Doe'
}],
date: '2013-05-02T10:05:45Z',
message: 'Fnord needed more fleem.',
revno: 2
}
];
var url = view._getSourceLink(
view.get('entity').get('code_source').location);
var commits = view.<API key>(revisions, url);
assert.equal(
'http://bazaar.launchpad.net/~foo/revision/1',
commits.first.revnoLink);
assert.equal(
'http://bazaar.launchpad.net/~foo/revision/2',
commits.remaining[0].revnoLink);
});
it('should be able to display the readme content', function() {
view = new CharmView({
activeTab: '#readme',
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo'}
}),
container: utils.makeContainer(this),
charmstore: {
getFile: function(url, filename, success, failure) {
success({
target: {
responseText: 'README content.'
}
});
}
}
});
view.render();
Y.one('#readme').get('text').should.eql('README content.');
});
// EVENTS
it('should catch when the add control is clicked', function(done) {
view = new CharmView({
activeTab: '#readme',
entity: new models.Charm({
files: [
'hooks/install'
],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo' }
}),
container: utils.makeContainer(this)
});
// Hook up to the callback for the click event.
view.<API key> = function(ev) {
ev.halt();
Y.one('#readme h3').get('text').should.eql('Charm has no README');
done();
};
view.render();
node.one('.charm .add').simulate('click');
});
it('<API key> displays the config panel', function(done) {
var fakeStore = new Y.juju.charmstore.APIv4({
charmstoreURL: 'localhost/'
});
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install'
],
id: 'precise/ceph-9',
url: 'cs:precise/ceph-9',
code_source: { location: 'lp:~foo' },
options: {
configName: 'test'
}
}),
container: utils.makeContainer(this),
charmstore: fakeStore
});
var fireStub = utils.makeStubMethod(view, 'fire');
this._cleanups.push(fireStub.reset);
view.set('deployService', function(charm, serviceAttrs) {
var serviceCharm = view.get('entity');
assert.deepEqual(charm, serviceCharm);
assert.equal(charm.get('id'), 'cs:precise/ceph-9');
assert.equal(serviceAttrs.icon, 'localhost/v4/precise/ceph-9/icon.svg');
assert.equal(fireStub.calledOnce(), true);
var fireArgs = fireStub.lastArguments();
assert.equal(fireArgs[0], 'changeState');
assert.deepEqual(fireArgs[1], {
sectionA: {
component: 'charmbrowser',
metadata: {
id: null }}});
done();
});
view.<API key>({halt: function() {}});
});
it('should load a file when a hook is selected', function() {
view = new CharmView({
entity: new models.Charm({
files: [
'hooks/install',
'readme.rst'
],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo' }
}),
container: utils.makeContainer(this),
charmstore: {
getFile: function(url, filename, success, failure) {
success({
target: {
responseText: '<install hook content>'
}
});
}
}
});
view.render();
Y.one('#code').all('select option').size().should.equal(3);
// Select the hooks install and the content should update.
Y.one('#code').all('select option').item(2).set(
'selected', 'selected');
Y.one('#code').one('select').simulate('change');
var content = Y.one('#code').one('div.filecontent');
// Content is escaped, so we read it out as text, not tags.
content.get('text').should.eql('<install hook content>');
});
it('should be able to render markdown as html', function() {
view = new CharmView({
activeTab: '#readme',
entity: new models.Charm({
files: [
'readme.md'
],
id: 'precise/wordpress-9',
code_source: { location: 'lp:~foo' }
}),
container: utils.makeContainer(this),
charmstore: {
getFile: function(url, filename, success, failure) {
success({
target: {
responseText: 'README Header\n============='
}
});
}
}
});
view.render();
Y.one('#readme').get('innerHTML').should.eql(
'<h1>README Header</h1>');
});
it('should display the config data in the config tab', function() {
view = new CharmView({
entity: new models.Charm({
files: [],
id: 'precise/ceph-9',
code_source: { location: 'lp:~foo' },
options: {
'client-port': {
'default': 9160,
'description': 'Port for client communcation',
'type': 'int'
}
}
}),
container: utils.makeContainer(this)
});
view.render();
Y.one('#configuration dd div').get('text').should.eql(
'Default: 9160');
Y.one('#configuration dd p').get('text').should.eql(
'Port for client communcation');
});
it('should catch when the open log is clicked', function(done) {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
// Hook up to the callback for the click event.
view._toggleLog = function(ev) {
ev.halt();
done();
};
view.render();
node.one('.changelog .expand').simulate('click');
});
it('changelog is reformatted and displayed', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
view.render();
// Basics that we have the right number of nodes.
node.all('.remaining li').size().should.eql(9);
node.all('.first p').size().should.eql(1);
// The reminaing starts out hidden.
assert(node.one('.changelog .remaining').hasClass('hidden'));
});
it('<API key> sets the flag for no requires, no provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
},
'requires': {
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for no requires, 1 provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {}
},
'requires': {
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for no requires, many provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {},
'two': {}
},
'requires': {
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for 1 requires, no provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
},
'requires': {
'foo': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for 1 requires, 1 provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {}
},
'requires': {
'foo': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for 1 requires, many provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {},
'two': {}
},
'requires': {
'foo': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for many requires, no provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
},
'requires': {
'foo': {},
'two': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for many requires, 1 provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {}
},
'requires': {
'foo': {},
'two': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('<API key> sets the flag for many requires, many provides',
function() {
var charm = new models.Charm({
files: [],
id: 'precise/ceph-9',
relations: {
'provides': {
'foo': {},
'two': {}
},
'requires': {
'foo': {},
'two': {}
}
}
});
view = new CharmView({
entity: charm
});
var interfaceIntro = view.<API key>(
charm.get('requires'), charm.get('provides'));
assert(Y.Object.hasKey(interfaceIntro, '<API key>'));
});
it('shows and hides an indicator', function(done) {
var hit = 0;
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
view.showIndicator = function() {
hit += 1;
};
view.hideIndicator = function() {
hit += 1;
hit.should.equal(2);
done();
};
view.render();
});
it('selects the proper tab when given one', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
activeTab: '#configuration',
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
view.render();
// We've selected the activeTab specified.
var selected = view.get('container').one('nav .active');
assert.equal(selected.getAttribute('href'), '#configuration');
});
it('sets the proper change request when closed', function(done) {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
activeTab: '#configuration',
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
view.on('changeState', function(ev) {
assert.equal(ev.details[0].sectionA.metadata.id, null,
'The charm id is not set to null.');
assert.equal(ev.details[0].sectionA.metadata.hash, null,
'The charm details hash is not set to null.');
done();
});
view.render();
view.get('container').one('.charm .back').simulate('click');
});
it('renders related charms when interface tab selected', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
testContainer = utils.makeContainer(this);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
activeTab: '#related-charms',
entity: new models.Charm(data),
renderTo: testContainer
});
view.render();
assert.equal(
testContainer.all('#related-charms .token').size(),
18);
assert.equal(view.get('entity').get('id'), 'cs:precise/apache2-27');
assert.isTrue(view.<API key>);
});
it('ignore invalid tab selections', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
testContainer = utils.makeContainer(this);
// We don't want any files so we don't have to mock/load them.
data.files = [];
var fakeStore = factory.makeFakeCharmstore();
view = new CharmView({
activeTab: '#bws-does-not-exist',
entity: new models.Charm(data),
renderTo: testContainer,
charmstore: fakeStore
});
view.render();
assert.equal(
testContainer.one('nav .active').getAttribute('href'),
'#summary');
});
it('should open header links in a new tab', function() {
var data = utils.loadFixture('data/browsercharm.json', true);
// We don't want any files so we don't have to mock/load them.
data.files = [];
view = new CharmView({
entity: new models.Charm(data),
container: utils.makeContainer(this)
});
view.render();
var links = view.get('container').all('.header .details li a');
// Check that we've found the links, otherwise the assert in .each will
// succeed when there are no links.
assert.equal(links.size() > 0, true);
links.each(function(link) {
assert.equal(link.getAttribute('target'), '_blank');
});
});
});
})();
|
import React, { useMemo } from 'react';
import { cx, css } from '@emotion/css';
import { MenuItem, WithContextMenu, MenuGroup, useTheme2 } from '@grafana/ui';
import { SelectableValue, GrafanaTheme2 } from '@grafana/data';
import { Seg } from './Seg';
import { unwrap } from './unwrap';
import { toSelectableValue } from './toSelectableValue';
import { AddButton } from './AddButton';
export type PartParams = Array<{
value: string;
options: (() => Promise<string[]>) | null;
}>;
type Props = {
parts: Array<{
name: string;
params: PartParams;
}>;
getNewPartOptions: () => Promise<SelectableValue[]>;
onChange: (partIndex: number, paramValues: string[]) => void;
onRemovePart: (index: number) => void;
onAddNewPart: (type: string) => void;
};
const <API key> = (onClick: () => void) => {
return (
<MenuGroup label="">
<MenuItem label="remove" onClick={onClick} />
</MenuGroup>
);
};
const <API key> = css({
paddingRight: '0',
marginRight: '0',
});
const RemovableName = ({ name, onRemove }: { name: string; onRemove: () => void }) => {
return (
<WithContextMenu renderMenuItems={() => <API key>(onRemove)}>
{({ openMenu }) => (
<button className={cx('gf-form-label', <API key>)} onClick={openMenu}>
{name}
</button>
)}
</WithContextMenu>
);
};
type PartProps = {
name: string;
params: PartParams;
onRemove: () => void;
onChange: (paramValues: string[]) => void;
};
const <API key> = css({
paddingLeft: '0',
paddingRight: '0',
marginLeft: '0',
marginRight: '0',
});
const getPartClass = (theme: GrafanaTheme2) => {
return cx(
'gf-form-label',
css({
paddingLeft: '0',
// gf-form-label class makes certain css attributes incorrect
// for the selectbox-dropdown, so we have to "reset" them back
lineHeight: theme.typography.body.lineHeight,
fontSize: theme.typography.body.fontSize,
})
);
};
const Part = ({ name, params, onChange, onRemove }: PartProps): JSX.Element => {
const theme = useTheme2();
const partClass = useMemo(() => getPartClass(theme), [theme]);
const onParamChange = (par: string, i: number) => {
const newParams = params.map((p) => p.value);
newParams[i] = par;
onChange(newParams);
};
return (
<div className={partClass}>
<RemovableName name={name} onRemove={onRemove} />(
{params.map((p, i) => {
const { value, options } = p;
const isLast = i === params.length - 1;
const loadOptions =
options !== null ? () => options().then((items) => items.map(toSelectableValue)) : undefined;
return (
<React.Fragment key={i}>
<Seg
allowCustomValue
value={value}
buttonClassName={<API key>}
loadOptions={loadOptions}
onChange={(v) => {
onParamChange(unwrap(v.value), i);
}}
/>
{!isLast && ','}
</React.Fragment>
);
})}
)
</div>
);
};
export const PartListSection = ({
parts,
getNewPartOptions,
onAddNewPart,
onRemovePart,
onChange,
}: Props): JSX.Element => {
return (
<>
{parts.map((part, index) => (
<Part
key={index}
name={part.name}
params={part.params}
onRemove={() => {
onRemovePart(index);
}}
onChange={(pars) => {
onChange(index, pars);
}}
/>
))}
<AddButton loadOptions={getNewPartOptions} onAdd={onAddNewPart} />
</>
);
};
|
package org.asqatasun.rules.rgaa22;
import java.util.LinkedHashSet;
import org.apache.commons.lang3.StringUtils;
import org.asqatasun.entity.audit.EvidenceElement;
import org.asqatasun.entity.audit.ProcessResult;
import org.asqatasun.entity.audit.SourceCodeRemark;
import org.asqatasun.entity.audit.TestSolution;
import static org.asqatasun.rules.keystore.AttributeStore.TITLE_ATTR;
import org.asqatasun.rules.keystore.HtmlElementStore;
import org.asqatasun.rules.keystore.RemarkMessageStore;
import org.asqatasun.rules.rgaa22.test.<API key>;
/**
* Unit test class for the implementation of the rule 1.2 of the referential RGAA 2.2.
*
* @author jkowalczyk
*/
public class Rgaa22Rule01021Test extends <API key> {
/**
* Default constructor
*/
public Rgaa22Rule01021Test (String testName){
super(testName);
}
@Override
protected void <API key>() {
<API key>(
"org.asqatasun.rules.rgaa22.Rgaa22Rule01021");
}
@Override
protected void setUpWebResourceMap() {
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-01",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-01.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-02",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-02.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-03",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-03.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-04",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-04.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-05",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-05.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-2Failed-06",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-2Failed-06.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-01",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-01.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-02",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-02.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-3NMI-03",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-3NMI-03.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-01",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-01.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-02",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-02.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-03",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-03.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-04",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-04.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-05",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-05.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-06",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-06.html"));
getWebResourceMap().put("Rgaa22.Test.1.2-4NA-07",
<API key>().createPage(
<API key>() + "rgaa22/Rgaa22Rule01021/RGAA22.Test.1.2-4NA-07.html"));
}
@Override
protected void setProcess() {
ProcessResult processResult = processPageTest("Rgaa22.Test.1.2-2Failed-01");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
SourceCodeRemark processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
EvidenceElement ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-2Failed-02");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-2Failed-03");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "!§:;.,?%*\\~/@()[]^_°=+-"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-2Failed-04");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-2Failed-05");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "mock-iframe1.html"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-2Failed-06");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.FAILED, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.FAILED, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "mock-frame1.html"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-3NMI-01");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "title of mock-frame1"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-3NMI-02");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue());
assertEquals(HtmlElementStore.IFRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-iframe1"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-3NMI-03");
// check number of elements in the page
assertEquals(1, processResult.getElementCounter());
// check test result
assertEquals(TestSolution.NEED_MORE_INFO, processResult.getValue());
// check number of remarks and their value
assertEquals(1, processResult.getRemarkSet().size());
processRemark = ((SourceCodeRemark)((LinkedHashSet)processResult.getRemarkSet()).iterator().next());
assertEquals(RemarkMessageStore.<API key>, processRemark.getMessageCode());
assertEquals(TestSolution.NEED_MORE_INFO, processRemark.getIssue());
assertEquals(HtmlElementStore.FRAME_ELEMENT, processRemark.getTarget());
assertNotNull(processRemark.getSnippet());
// check number of evidence elements and their value
assertEquals(1, processRemark.getElementList().size());
ee = processRemark.getElementList().iterator().next();
assertTrue(StringUtils.contains(ee.getValue(), "Title of mock-frame1"));
assertEquals(TITLE_ATTR, ee.getEvidence().getCode());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-01");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-02");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-03");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-04");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-05");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-06");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
processResult = processPageTest("Rgaa22.Test.1.2-4NA-07");
// check test result
assertEquals(TestSolution.NOT_APPLICABLE, processResult.getValue());
// check test has no remark
assertNull(processResult.getRemarkSet());
}
@Override
protected void setConsolidate() {
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-01").getValue());
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-02").getValue());
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-03").getValue());
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-04").getValue());
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-05").getValue());
assertEquals(TestSolution.FAILED,
consolidate("Rgaa22.Test.1.2-2Failed-06").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("Rgaa22.Test.1.2-3NMI-01").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("Rgaa22.Test.1.2-3NMI-02").getValue());
assertEquals(TestSolution.NEED_MORE_INFO,
consolidate("Rgaa22.Test.1.2-3NMI-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-01").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-02").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-03").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-04").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-05").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-06").getValue());
assertEquals(TestSolution.NOT_APPLICABLE,
consolidate("Rgaa22.Test.1.2-4NA-07").getValue());
}
}
|
export const BattleAvatarNumbers = {
1: 'lucas',
2: 'dawn',
3: 'youngster-gen4',
4: 'lass-gen4dp',
5: 'camper',
6: 'picnicker',
7: 'bugcatcher',
8: 'aromalady',
9: 'twins-gen4dp',
10: 'hiker-gen4',
11: 'battlegirl-gen4',
12: 'fisherman-gen4',
13: 'cyclist-gen4',
14: 'cyclistf-gen4',
15: 'blackbelt-gen4dp',
16: 'artist-gen4',
17: 'pokemonbreeder-gen4',
18: '<API key>',
19: 'cowgirl',
20: 'jogger',
21: 'pokefan-gen4',
22: 'pokefanf-gen4',
23: 'pokekid',
24: 'youngcouple-gen4dp',
25: 'acetrainer-gen4dp',
26: 'acetrainerf-gen4dp',
27: 'waitress-gen4',
28: 'veteran-gen4',
29: 'ninjaboy',
30: 'dragontamer',
31: 'birdkeeper-gen4dp',
32: 'doubleteam',
33: 'richboy-gen4',
34: 'lady-gen4',
35: 'gentleman-gen4dp',
36: 'madame-gen4dp',
37: 'beauty-gen4dp',
38: 'collector',
39: 'policeman-gen4',
40: 'pokemonranger-gen4',
41: 'pokemonrangerf-gen4',
42: 'scientist-gen4dp',
43: 'swimmer-gen4dp',
44: 'swimmerf-gen4dp',
45: 'tuber',
46: 'tuberf',
47: 'sailor',
48: 'sisandbro',
49: 'ruinmaniac',
50: 'psychic-gen4',
51: 'psychicf-gen4',
52: 'gambler',
53: 'guitarist-gen4',
54: 'acetrainersnow',
55: 'acetrainersnowf',
56: 'skier',
57: 'skierf-gen4dp',
58: 'roughneck-gen4',
59: 'clown',
60: 'worker-gen4',
61: 'schoolkid-gen4dp',
62: 'schoolkidf-gen4',
63: 'roark',
64: 'barry',
65: 'byron',
66: 'aaron',
67: 'bertha',
68: 'flint',
69: 'lucian',
70: 'cynthia-gen4',
71: 'bellepa',
72: 'rancher',
73: 'mars',
74: 'galacticgrunt',
75: 'gardenia',
76: 'crasherwake',
77: 'maylene',
78: 'fantina',
79: 'candice',
80: 'volkner',
81: 'parasollady-gen4',
82: 'waiter-gen4dp',
83: 'interviewers',
84: 'cameraman',
85: 'reporter',
86: 'idol',
87: 'cyrus',
88: 'jupiter',
89: 'saturn',
90: 'galacticgruntf',
91: 'argenta',
92: 'palmer',
93: 'thorton',
94: 'buck',
95: 'darach',
96: 'marley',
97: 'mira',
98: 'cheryl',
99: 'riley',
100: 'dahlia',
101: 'ethan',
102: 'lyra',
103: 'twins-gen4',
104: 'lass-gen4',
105: 'acetrainer-gen4',
106: 'acetrainerf-gen4',
107: 'juggler',
108: 'sage',
109: 'li',
110: 'gentleman-gen4',
111: 'teacher',
112: 'beauty',
113: 'birdkeeper',
114: 'swimmer-gen4',
115: 'swimmerf-gen4',
116: 'kimonogirl',
117: 'scientist-gen4',
118: 'acetrainercouple',
119: 'youngcouple',
120: 'supernerd',
121: 'medium',
122: 'schoolkid-gen4',
123: 'blackbelt-gen4',
124: 'pokemaniac',
125: 'firebreather',
126: 'burglar',
127: 'biker-gen4',
128: 'skierf',
129: 'boarder',
130: 'rocketgrunt',
131: 'rocketgruntf',
132: 'archer',
133: 'ariana',
134: 'proton',
135: 'petrel',
136: 'eusine',
137: 'lucas-gen4pt',
138: 'dawn-gen4pt',
139: 'madame-gen4',
140: 'waiter-gen4',
141: 'falkner',
142: 'bugsy',
143: 'whitney',
144: 'morty',
145: 'chuck',
146: 'jasmine',
147: 'pryce',
148: 'clair',
149: 'will',
150: 'koga',
151: 'bruno',
152: 'karen',
153: 'lance',
154: 'brock',
155: 'misty',
156: 'ltsurge',
157: 'erika',
158: 'janine',
159: 'sabrina',
160: 'blaine',
161: 'blue',
162: 'red',
163: 'red',
164: 'silver',
165: 'giovanni',
166: 'unknownf',
167: 'unknown',
168: 'unknown',
169: 'hilbert',
170: 'hilda',
171: 'youngster',
172: 'lass',
173: 'schoolkid',
174: 'schoolkidf',
175: 'smasher',
176: 'linebacker',
177: 'waiter',
178: 'waitress',
179: 'chili',
180: 'cilan',
181: 'cress',
182: 'nurseryaide',
183: 'preschoolerf',
184: 'preschooler',
185: 'twins',
186: 'pokemonbreeder',
187: 'pokemonbreederf',
188: 'lenora',
189: 'burgh',
190: 'elesa',
191: 'clay',
192: 'skyla',
193: 'pokemonranger',
194: 'pokemonrangerf',
195: 'worker',
196: 'backpacker',
197: 'backpackerf',
198: 'fisherman',
199: 'musician',
200: 'dancer',
201: 'harlequin',
202: 'artist',
203: 'baker',
204: 'psychic',
205: 'psychicf',
206: 'cheren',
207: 'bianca',
208: 'plasmagrunt-gen5bw',
209: 'n',
210: 'richboy',
211: 'lady',
212: 'pilot',
213: 'workerice',
214: 'hoopster',
215: 'scientistf',
216: 'clerkf',
217: 'acetrainerf',
218: 'acetrainer',
219: 'blackbelt',
220: 'scientist',
221: 'striker',
222: 'brycen',
223: 'iris',
224: 'drayden',
225: 'roughneck',
226: 'janitor',
227: 'pokefan',
228: 'pokefanf',
229: 'doctor',
230: 'nurse',
231: 'hooligans',
232: 'battlegirl',
233: 'parasollady',
234: 'clerk',
235: 'clerk-boss',
236: 'backers',
237: 'backersf',
238: 'veteran',
239: 'veteranf',
240: 'biker',
241: 'infielder',
242: 'hiker',
243: 'madame',
244: 'gentleman',
245: 'plasmagruntf-gen5bw',
246: 'shauntal',
247: 'marshal',
248: 'grimsley',
249: 'caitlin',
250: 'ghetsis-gen5bw',
251: 'depotagent',
252: 'swimmer',
253: 'swimmerf',
254: 'policeman',
255: 'maid',
256: 'ingo',
257: 'alder',
258: 'cyclist',
259: 'cyclistf',
260: 'cynthia',
261: 'emmet',
262: 'hilbert-dueldisk',
263: 'hilda-dueldisk',
264: 'hugh',
265: 'rosa',
266: 'nate',
267: 'colress',
268: 'beauty-gen5bw2',
269: 'ghetsis',
270: 'plasmagrunt',
271: 'plasmagruntf',
272: 'iris-gen5bw2',
273: 'brycenman',
274: 'shadowtriad',
275: 'rood',
276: 'zinzolin',
277: 'cheren-gen5bw2',
278: 'marlon',
279: 'roxie',
280: 'roxanne',
281: 'brawly',
282: 'wattson',
283: 'flannery',
284: 'norman',
285: 'winona',
286: 'tate',
287: 'liza',
288: 'juan',
289: 'guitarist',
290: 'steven',
291: 'wallace',
292: 'bellelba',
293: 'benga',
294: 'ash',
'#bw2elesa': 'elesa-gen5bw2',
'#teamrocket': 'teamrocket',
'#yellow': 'yellow',
'#zinnia': 'zinnia',
'#clemont': 'clemont',
'#wally': 'wally',
breeder: 'pokemonbreeder',
breederf: 'pokemonbreederf',
1001: '#1001',
1002: '#1002',
1003: '#1003',
1005: '#1005',
1010: '#1010',
};
|
package nikita.common.config;
/**
* Constants used for ElasticSearch queries
*/
public class ESConstants {
public static final String QUERY_SIZE = "size";
public static final String QUERY_FROM = "from";
public static final String QUERY_QUERY = "query";
public static final String QUERY_PREFIX = "prefix";
public static final String QUERY_MATCH_PHRASE = "match_phrase";
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PODEMOS. Scientific and cultural cooperation with the United States to avoid a human capital flight</title>
<meta property="og:title" content="PODEMOS: Scientific and cultural cooperation with the United States to avoid a human capital flight" />
<meta property="og:description" content="In order to reverse brain drain of Spanish scientist to the United States, we
will strengthen scientific, cultural and educational cooperation with this
country. To do this, we will increase the budget for grants for further studies
and professional internships and scientific research related to projects by
Spaniards, and we will promote incentives to encourage the return of Spanish
researchers having expanded their training in the United States.
In addition, we will develop a United Plan, an initiative to establish greater
cultural, educational and economic ties with the Hispanic community in the US,
almost a third of the population of that country. The network of Instituto
Cervantes centres will help to reinforce its Latin American connection to
organize and promote cultural activities that involve the richness of Spanish
language and culture in Spain and America.
We will also create a network of business incubators and accelerators in the
United States and Spain to contribute to the creation of viable and innovative
business projects in both countries, especially in the field of social and
solidarity economy, to facilitate the entry of Spanish SMEs in the US market and
the subsequent profit." />
<meta property="og:image" content="http://lasonrisadeunpais.es/wp-content/plugins/programa/data/meta-programa.png" />
</head>
<body>
<script type="text/javascript">
var url_base = '/en/programa/?medida=332';
window.location = url_base;
</script>
<h1>Scientific and cultural cooperation with the United States to avoid a human capital flight</h1>
<div>
<p>In order to reverse brain drain of Spanish scientist to the United States, we will strengthen scientific, cultural and educational cooperation with this country. To do this, we will increase the budget for grants for further studies and professional internships and scientific research related to projects by Spaniards, and we will promote incentives to encourage the return of Spanish researchers having expanded their training in the United States.</p>
<p>In addition, we will develop a United Plan, an initiative to establish greater cultural, educational and economic ties with the Hispanic community in the US, almost a third of the population of that country. The network of Instituto Cervantes centres will help to reinforce its Latin American connection to organize and promote cultural activities that involve the richness of Spanish language and culture in Spain and America.</p>
<p>We will also create a network of business incubators and accelerators in the United States and Spain to contribute to the creation of viable and innovative business projects in both countries, especially in the field of social and solidarity economy, to facilitate the entry of Spanish SMEs in the US market and the subsequent profit.</p>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>About Cella</title>
<link rel="stylesheet" type="text/css" href="styles/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="styles/chosen.css" />
<link rel="stylesheet" type="text/css" href="styles/jquery-ui/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="styles/style.css" />
</head>
<body>
<div class="container">
<header class="navbar navbar-fixed-top" data-dropdown="dropdown">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="/">Cella</a>
<ul class="nav" style="float: right">
<li class="dropdown">
<a class="dropdown-toggle" href="
data-toggle="dropdown"
title="Helpful links about the housing lottery">
<span class="caret"></span>
Lottery Links
</a>
<ul class="dropdown-menu">
<li>
<a href="http:
Lottery Results Live
</a>
</li>
<li>
<a href="http://brown.edu/Student_Services/Residential_Council/lottery/" target="_blank">
Housing Lottery Website
</a>
</li>
<li>
<a href="http://reslife.brown.edu/current_students/lottery/floorplans/floorplans.html" target="_blank">
Floorplans
</a>
</li>
<li>
<a href="http://reslife.brown.edu/current_students/lottery/index.html" target="_blank">ResLife</a>
</li>
</ul>
</li>
<li class="active"><a href="about.html">About</a></li>
</ul>
</div>
</div>
</header>
{{{ content }}}
<footer>
</footer>
</div>
<!-- scripts -->
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/bootstrap-dropdown.js"></script>
</body>
</html>
|
# <API key>: true
# == Schema Information
# Table name: packages
# id :integer not null, primary key
# name :string(255)
# initial_price :decimal(, )
# at_the_door_price :decimal(, )
# attendee_limit :integer
# expires_at :datetime
# requires_track :boolean
# event_id :integer
# created_at :datetime
# updated_at :datetime
# deleted_at :datetime
# <API key> :boolean default(FALSE), not null
# description :text
# Indexes
# <API key> (event_id)
require 'spec_helper'
describe Package do
let(:user) { create(:user) }
let(:event) { create(:event, user: user) }
let(:package) { create(:package, event: event, initial_price: 10, at_the_door_price: 50) }
context '#current_price' do
before(:each) do
# set openieng tier before any tiers created here
o = event.opening_tier
o.date = 1.week.ago
o.increase_by_dollars = 0
o.save
end
it 'is the initial price' do
expect(package.current_price).to eq package.initial_price
end
it 'changes based on the date' do
tier = create(:pricing_tier, date: 2.day.ago, event: event)
expected = package.initial_price + tier.increase_by_dollars
expect(package.current_price).to eq expected
end
it 'changes based on the number of registrants for this event' do
tier = create(:pricing_tier, registrants: 10, event: event)
20.times do
create(:registration, event: event)
end
expected = package.initial_price + tier.increase_by_dollars
expect(package.current_price).to eq expected
end
it 'does not change if the tiers are not yet eligible' do
event.registrations.destroy_all
# The Delorean replicates a long lasting issue that Travis discovered
Delorean.time_travel_to(10.days.from_now) do
tier = create(:pricing_tier, date: 19.days.from_now, event: event)
tier2 = create(:pricing_tier, registrants: 10, event: event, date: nil)
expect(event.current_tier).to eq event.opening_tier
expect(package.current_price).to eq package.initial_price
end
end
it 'changes base on two tiers' do
tier = create(:pricing_tier, registrants: 10, event: event, date: nil)
tier2 = create(:pricing_tier, date: 2.day.ago, event: event)
11.times do
create(:registration, event: event)
end
expect(event.current_tier).to eq tier2
expected = package.initial_price + tier.increase_by_dollars + tier2.increase_by_dollars
expect(package.current_price).to eq expected
end
context 'optionally does not change based on passing tiers' do
before(:each) do
package.<API key> = true
end
it 'tier by date passes' do
tier = create(:pricing_tier, date: Date.today, event: event)
expected = package.initial_price
expect(package.current_price).to eq expected
end
end
end
context '#price_at_tier' do
it 'redirects functionality to the tier' do
tier = create(:pricing_tier, date: Date.today, event: event)
expect(tier).to receive(:price_of)
package.price_at_tier(tier)
end
it 'correctly calculates the value' do
tier = create(:pricing_tier, registrants: 2, event: event)
allow(tier).to receive(:should_apply_amount?) { true }
allow(event).to receive(:pricing_tiers) { [tier] }
expected = package.initial_price + tier.amount
expect(package.price_at_tier(tier)).to eq expected
end
context 'a new tier is current' do
before(:each) do
@new_tier = create(:pricing_tier,
event: event,
date: 1.day.from_now,
increase_by_dollars: 3)
Delorean.jump 4.days
event.reload
expect(event.pricing_tiers.count).to eq 2
expect(event.current_tier).to_not eq event.opening_tier
expect(event.current_tier).to eq @new_tier
end
after(:each) do
Delorean.back_to_the_present
end
it 'reflects the price of a previous tier' do
expected = package.initial_price
expect(package.price_at_tier(event.opening_tier)).to eq expected
end
end
end
end
|
<?php return unserialize('a:1:{i:0;O:30:"Doctrine\\ORM\\Mapping\\OneToMany":6:{s:8:"mappedBy";s:9:"container";s:12:"targetEntity";s:7:"Element";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:0;s:7:"indexBy";N;}}');
|
public class Generic{
public static void main(String[] args){
Car <String> car1 = new Car <String> ();
car1.setName("Buick");
car1.setPrice("100");
System.out.printf("name=%s,price=%s\n",car1.getName(),car1.getPrice());
Car <Integer> car2 = new Car <Integer> ();
car2.setName(001);
car2.setPrice(100);
System.out.printf("name=%d,price=%d\n",car2.getName(),car2.getPrice());
Integer[] array = {1,2,3,4,5,6,7,8,9};
car2.print(array);
}
}
/*generic class*/
class Car <T> {
private T name;
private T price;
public Car(){
this.name = null;
this.price = null;
}
public Car(T name,T price){
this.name = name;
this.price = price;
}
public void setName(T name){
this.name = name;
}
public T getName(){
return this.name;
}
public void setPrice(T price){
this.price = price;
}
public T getPrice(){
return this.price;
}
public <A> void print(A[] array){
for (A var:array)
System.out.printf("%s",var);
}
}
|
<?php
$dictionary['RealtyTemplates']['fields']['<API key>'] =
array (
'name' => '<API key>',
'type' => 'link',
'relationship' => '<API key>',
'source'=>'non-db',
'vname'=>'<API key>',
);
|
<div class="item dragHandle" data-bind="css: {
'unseen': !seen(), 'selected': selected(), 'checked': checked(),
'forwarded': forwarded(), 'answered': answered(), 'deleted': deleted() || threadHideAnimation(),
'nosubject': emptySubject(),
'threaded': threadPart(),
'show': threadShowAnimation()
}">
<div class="item_content">
<span class="controls">
<!-- <label class="custom_checkbox" data-bind="css: {'checked': checked()}">
<span class="icon"></span>
<input type="checkbox" data-bind="checked: checked" />
</label>
<span class="custom_checkbox" data-bind="click: function () { checked(!checked()); }, css: {'checked': checked()}">
<span class="icon"></span>
</span>
<span class="separator"></span>
<span class="flag" data-bind="css: {'flagged': flagged(), 'partial': partialFlagged()}"></span>
</span>
<span class="data">
<span class="size" data-bind="text: friendlySize()"></span>
<span class="date" data-bind="text: date"></span>
<span class="attachments has_attachments" data-bind="visible: hasAttachments(),
css: {'has_ical_attachment': showCalendarIcon(), '<API key>': hasVcardAttachment()}"></span>
<span class="marker"></span>
<span class="from fadeout">
<span data-bind="text: fromOrToText()"></span>
<span class="other_senders" data-bind="text: threadSendersText(), visible: <API key>()"></span>
</span>
<span class="separator"></span>
<span class="thread" data-bind="text: threadCount(), visible: threadCountVisible(), click: openThread, css: {'unreed': threadUnreedCount() > 0}"></span>
<span class="thread loading" data-i18n="MAILBOX/THREAD_LOADING" data-bind="i18n: 'text', visible: <API key>()"></span>
<span class="subject fadeout">
<span class="importance" data-bind="visible: importance() === Enums.Importance.High"></span>
<span data-bind="text: subjectForDisplay()"></span>
</span>
</span>
<div class="separator"></div>
</div>
</div>
<!-- ko if: <API key>() -->
<div class="item threaded <API key>" data-bind="css:{'show': threadShowAnimation(), 'deleted': threadHideAnimation()}">
<div class="item_content">
<span class="link" data-i18n="MAILBOX/<API key>" data-bind="i18n: 'text', click: loadNextMessages, visible: <API key>()"></span>
<span style="color: #999999; font-size: 15px;" data-i18n="MAILBOX/THREAD_LOADING" data-bind="i18n: 'text', visible: !<API key>()"></span>
</div>
</div>
|
import * as React from 'react';
import renderOrder from '../renderOrder';
import { RenderLayer } from '../browser_utils/Utils';
import { SharedState } from '../citybound';
import { shadersForLandUses } from './stripedShaders';
import colors from '../colors';
export const LAND_USES = [
"Residential",
"Commercial",
"Industrial",
"Agricultural",
"Recreational",
"Administrative",
];
const landUseInstances = new Map(LAND_USES.map(landUse => [landUse, new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors[landUse]])]));
const <API key> = new Float32Array([0.0, 0.0, 0.0, 1.0, 0.0, ...colors.buildingOutlines]);
export function ZonePlanningLayers({ state }: {
state: SharedState;
}) {
const { zoneGroups, zoneOutlineGroups, <API key> } = state.planning.rendering.currentPreview;
return <>
{[...zoneGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.addedGesturesZones} decal={true} batches={[...groups.values()].map(groupMesh => ({
mesh: groupMesh,
instances: landUseInstances.get(landUse)
}))} />)}
{[...zoneGroups.entries()].reverse().map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.<API key>} decal={true} shader={shadersForLandUses[landUse]} batches={[...groups.values()].map(groupMesh => ({
mesh: groupMesh,
instances: landUseInstances.get(landUse)
}))} />)}
{[...zoneOutlineGroups.entries()].map(([landUse, groups]) => <RenderLayer renderOrder={renderOrder.<API key>} decal={true} batches={[...groups.values()].map(groupMesh => ({
mesh: groupMesh,
instances: landUseInstances.get(landUse)
}))} />)}
<RenderLayer renderOrder={renderOrder.buildingOutlines} decal={true} batches={[...<API key>.values()].map(groupMesh => ({
mesh: groupMesh,
instances: <API key>
}))} />
</>;
}
|
-- | This module provides the data type and parser for a trait file
module Trait (
Trait(..)
, defaultTrait
, trait
) where
import Maker
import Modifier
import Scoped(Label)
data Trait = Trait {
trait_name :: Label
, agnatic :: Bool
, birth :: Double -- ^ Chance of being assigned on birth. Default 0
, cached :: Bool
, cannot_inherit :: Bool
, cannot_marry :: Bool
, caste_tier :: Maybe Int -- ^ The trait is a caste trait, and this
-- defines the order of the castes.
, customizer :: Bool -- ^ Blocks the trait from being available in the Designer
, education :: Bool
, immortal :: Bool
, in_hiding :: Bool
, inbred :: Bool
, incapacitating :: Bool
, inherit_chance :: Double
, is_epidemic :: Bool
, is_health :: Bool
, is_illness :: Bool
, leader :: Bool
, leadership_traits :: Maybe Int
, lifestyle :: Bool
, opposites :: [Label]
, personality :: Bool
, prevent_decadence :: Bool
, priest :: Bool
, pilgrimage :: Bool
, random :: Bool
, rebel_inherited :: Bool -- ^ Unknown purpose
, religious :: Bool
, religious_branch :: Maybe Label
, ruler_designer_cost :: Maybe Int -- ^ The postive cost in the Ruler Designer
, tolerates :: [Label] -- ^ A list of the religion groups tolerated by this character
, modifiers :: [Modifier]
} deriving (Eq, Ord, Show)
trait :: Maker Trait
trait = Trait
<$> label key
<*> boolProp "agnatic"
<*> ((number ~@ "birth") `defaultingTo` 0)
<*> boolProp "cached"
<*> boolProp "cannot_inherit"
<*> boolProp "cannot_marry"
<*> intProp "caste_tier"
<*> boolProp "customizer"
<*> boolProp "education"
<*> boolProp "immortal"
<*> boolProp "in_hiding"
<*> boolProp "inbred"
<*> boolProp "incapacitating"
<*> (number ~@ "inherit_chance") `defaultingTo` 0
<*> boolProp "is_epidemic"
<*> boolProp "is_health"
<*> boolProp "is_illness"
<*> boolProp "leader"
<*> intProp "leadership_traits"
<*> boolProp "lifestyle"
<*> (opposites @@ "opposites") `defaultingTo` []
<*> boolProp "personality"
<*> boolProp "prevent_decadence"
<*> boolProp "priest"
<*> boolProp "pilgrimage"
<*> boolProp "random"
<*> boolProp "rebel_inherited"
<*> boolProp "religious"
<*> fetchString @? "religious_branch"
<*> intProp "ruler_designer_cost"
<*> tolerations
<*> tryMap modifier
where boolProp key = ((fetchBool @@ key) `defaultingTo` False) <?> key
intProp :: Label → Maker (Maybe Int)
intProp key = fmap round <$> number ~? key <?> key
opposites = error "opposite traits are not implemented"
tolerations = return []
defaultTrait :: Trait
defaultTrait =
Trait { trait_name = undefined, agnatic = False, birth = 0, cached = False
, cannot_inherit = False, cannot_marry = False, caste_tier = Nothing
, customizer = False, education = False, immortal = False
, in_hiding = False, inbred = False, incapacitating = False
, inherit_chance = 0, is_epidemic = False, is_health = False
, is_illness = False, leader = False, leadership_traits = Nothing
, lifestyle = False, opposites = [], personality = False
, prevent_decadence = False, priest = False, pilgrimage = False
, random = False, rebel_inherited = False, religious = False
, religious_branch = Nothing, ruler_designer_cost = Nothing
, tolerates = [], modifiers = [] }
|
// Protocol Buffers for Go with Gadgets
// modification, are permitted provided that the following conditions are
// met:
// in the documentation and/or other materials provided with the
// distribution.
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package generator
import (
"bytes"
"go/parser"
"go/printer"
"go/token"
"path"
"strings"
"gx/ipfs/<API key>/gogo-protobuf/gogoproto"
"gx/ipfs/<API key>/gogo-protobuf/proto"
descriptor "gx/ipfs/<API key>/gogo-protobuf/protoc-gen-gogo/descriptor"
plugin "gx/ipfs/<API key>/gogo-protobuf/protoc-gen-gogo/plugin"
)
func (d *FileDescriptor) Messages() []*Descriptor {
return d.desc
}
func (d *FileDescriptor) Enums() []*EnumDescriptor {
return d.enum
}
func (d *Descriptor) IsGroup() bool {
return d.group
}
func (g *Generator) IsGroup(field *descriptor.<API key>) bool {
if d, ok := g.typeNameToObject[field.GetTypeName()].(*Descriptor); ok {
return d.IsGroup()
}
return false
}
func (g *Generator) TypeNameByObject(typeName string) Object {
o, ok := g.typeNameToObject[typeName]
if !ok {
g.Fail("can't find object with type", typeName)
}
return o
}
func (g *Generator) OneOfTypeName(message *Descriptor, field *descriptor.<API key>) string {
typeName := message.TypeName()
ccTypeName := CamelCaseSlice(typeName)
fieldName := g.GetOneOfFieldName(message, field)
tname := ccTypeName + "_" + fieldName
// It is possible for this to collide with a message or enum
// nested in this message. Check for collisions.
ok := true
for _, desc := range message.nested {
if strings.Join(desc.TypeName(), "_") == tname {
ok = false
break
}
}
for _, enum := range message.enums {
if strings.Join(enum.TypeName(), "_") == tname {
ok = false
break
}
}
if !ok {
tname += "_"
}
return tname
}
type PluginImports interface {
NewImport(pkg string) Single
GenerateImports(file *FileDescriptor)
}
type pluginImports struct {
generator *Generator
singles []Single
}
func NewPluginImports(generator *Generator) *pluginImports {
return &pluginImports{generator, make([]Single, 0)}
}
func (this *pluginImports) NewImport(pkg string) Single {
imp := newImportedPackage(this.generator.ImportPrefix, pkg)
this.singles = append(this.singles, imp)
return imp
}
func (this *pluginImports) GenerateImports(file *FileDescriptor) {
for _, s := range this.singles {
if s.IsUsed() {
this.generator.PrintImport(GoPackageName(s.Name()), GoImportPath(s.Location()))
}
}
}
type Single interface {
Use() string
IsUsed() bool
Name() string
Location() string
}
type importedPackage struct {
used bool
pkg string
name string
importPrefix string
}
func newImportedPackage(importPrefix string, pkg string) *importedPackage {
return &importedPackage{
pkg: pkg,
importPrefix: importPrefix,
}
}
func (this *importedPackage) Use() string {
if !this.used {
this.name = string(cleanPackageName(this.pkg))
this.used = true
}
return this.name
}
func (this *importedPackage) IsUsed() bool {
return this.used
}
func (this *importedPackage) Name() string {
return this.name
}
func (this *importedPackage) Location() string {
return this.importPrefix + this.pkg
}
func (g *Generator) GetFieldName(message *Descriptor, field *descriptor.<API key>) string {
goTyp, _ := g.GoType(message, field)
fieldname := CamelCase(*field.Name)
if gogoproto.IsCustomName(field) {
fieldname = gogoproto.GetCustomName(field)
}
if gogoproto.IsEmbed(field) {
fieldname = EmbedFieldName(goTyp)
}
if field.OneofIndex != nil {
fieldname = message.OneofDecl[int(*field.OneofIndex)].GetName()
fieldname = CamelCase(fieldname)
}
for _, f := range methodNames {
if f == fieldname {
return fieldname + "_"
}
}
if !gogoproto.IsProtoSizer(message.file.FileDescriptorProto, message.DescriptorProto) {
if fieldname == "Size" {
return fieldname + "_"
}
}
return fieldname
}
func (g *Generator) GetOneOfFieldName(message *Descriptor, field *descriptor.<API key>) string {
goTyp, _ := g.GoType(message, field)
fieldname := CamelCase(*field.Name)
if gogoproto.IsCustomName(field) {
fieldname = gogoproto.GetCustomName(field)
}
if gogoproto.IsEmbed(field) {
fieldname = EmbedFieldName(goTyp)
}
for _, f := range methodNames {
if f == fieldname {
return fieldname + "_"
}
}
if !gogoproto.IsProtoSizer(message.file.FileDescriptorProto, message.DescriptorProto) {
if fieldname == "Size" {
return fieldname + "_"
}
}
return fieldname
}
func (g *Generator) IsMap(field *descriptor.<API key>) bool {
if !field.IsMessage() {
return false
}
byName := g.ObjectNamed(field.GetTypeName())
desc, ok := byName.(*Descriptor)
if byName == nil || !ok || !desc.GetOptions().GetMapEntry() {
return false
}
return true
}
func (g *Generator) GetMapKeyField(field, keyField *descriptor.<API key>) *descriptor.<API key> {
if !gogoproto.IsCastKey(field) {
return keyField
}
keyField = proto.Clone(keyField).(*descriptor.<API key>)
if keyField.Options == nil {
keyField.Options = &descriptor.FieldOptions{}
}
keyType := gogoproto.GetCastKey(field)
if err := proto.SetExtension(keyField.Options, gogoproto.E_Casttype, &keyType); err != nil {
g.Fail(err.Error())
}
return keyField
}
func (g *Generator) GetMapValueField(field, valField *descriptor.<API key>) *descriptor.<API key> {
if gogoproto.IsCustomType(field) && gogoproto.IsCastValue(field) {
g.Fail("cannot have a customtype and casttype: ", field.String())
}
valField = proto.Clone(valField).(*descriptor.<API key>)
if valField.Options == nil {
valField.Options = &descriptor.FieldOptions{}
}
stdtime := gogoproto.IsStdTime(field)
if stdtime {
if err := proto.SetExtension(valField.Options, gogoproto.E_Stdtime, &stdtime); err != nil {
g.Fail(err.Error())
}
}
stddur := gogoproto.IsStdDuration(field)
if stddur {
if err := proto.SetExtension(valField.Options, gogoproto.E_Stdduration, &stddur); err != nil {
g.Fail(err.Error())
}
}
if valType := gogoproto.GetCastValue(field); len(valType) > 0 {
if err := proto.SetExtension(valField.Options, gogoproto.E_Casttype, &valType); err != nil {
g.Fail(err.Error())
}
}
if valType := gogoproto.GetCustomType(field); len(valType) > 0 {
if err := proto.SetExtension(valField.Options, gogoproto.E_Customtype, &valType); err != nil {
g.Fail(err.Error())
}
}
nullable := gogoproto.IsNullable(field)
if err := proto.SetExtension(valField.Options, gogoproto.E_Nullable, &nullable); err != nil {
g.Fail(err.Error())
}
return valField
}
// GoMapValueTypes returns the map value Go type and the alias map value Go type (for casting), taking into
// account whether the map is nullable or the value is a message.
func GoMapValueTypes(mapField, valueField *descriptor.<API key>, goValueType, goValueAliasType string) (nullable bool, outGoType string, outGoAliasType string) {
nullable = gogoproto.IsNullable(mapField) && (valueField.IsMessage() || gogoproto.IsCustomType(mapField))
if nullable {
// ensure the non-aliased Go value type is a pointer for consistency
if strings.HasPrefix(goValueType, "*") {
outGoType = goValueType
} else {
outGoType = "*" + goValueType
}
outGoAliasType = goValueAliasType
} else {
outGoType = strings.Replace(goValueType, "*", "", 1)
outGoAliasType = strings.Replace(goValueAliasType, "*", "", 1)
}
return
}
func GoTypeToName(goTyp string) string {
return strings.Replace(strings.Replace(goTyp, "*", "", -1), "[]", "", -1)
}
func EmbedFieldName(goTyp string) string {
goTyp = GoTypeToName(goTyp)
goTyps := strings.Split(goTyp, ".")
if len(goTyps) == 1 {
return goTyp
}
if len(goTyps) == 2 {
return goTyps[1]
}
panic("unreachable")
}
func (g *Generator) GeneratePlugin(p Plugin) {
plugins = []Plugin{p}
p.Init(g)
// Generate the output. The generator runs for every file, even the files
// that we don't generate output for, so that we can collate the full list
// of exported symbols to support public imports.
genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
for _, file := range g.genFiles {
genFileMap[file] = true
}
for _, file := range g.allFiles {
g.Reset()
g.writeOutput = genFileMap[file]
g.generatePlugin(file, p)
if !g.writeOutput {
continue
}
g.Response.File = append(g.Response.File, &plugin.<API key>{
Name: proto.String(file.goFileName(g.pathType)),
Content: proto.String(g.String()),
})
}
}
func (g *Generator) generatePlugin(file *FileDescriptor, p Plugin) {
g.writtenImports = make(map[string]bool)
g.file = file
// Run the plugins before the imports so we know which imports are necessary.
p.Generate(file)
// Generate header and imports last, though they appear first in the output.
rem := g.Buffer
g.Buffer = new(bytes.Buffer)
g.generateHeader()
p.GenerateImports(g.file)
g.generateImports()
if !g.writeOutput {
return
}
g.Write(rem.Bytes())
// Reformat generated code.
contents := string(g.Buffer.Bytes())
fset := token.NewFileSet()
ast, err := parser.ParseFile(fset, "", g, parser.ParseComments)
if err != nil {
g.Fail("bad Go source code was generated:", contents, err.Error())
return
}
g.Reset()
err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
if err != nil {
g.Fail("generated Go source code could not be reformatted:", err.Error())
}
}
func GetCustomType(field *descriptor.<API key>) (packageName string, typ string, err error) {
return getCustomType(field)
}
func getCustomType(field *descriptor.<API key>) (packageName string, typ string, err error) {
if field.Options != nil {
var v interface{}
v, err = proto.GetExtension(field.Options, gogoproto.E_Customtype)
if err == nil && v.(*string) != nil {
ctype := *(v.(*string))
packageName, typ = splitCPackageType(ctype)
return packageName, typ, nil
}
}
return "", "", err
}
func splitCPackageType(ctype string) (packageName string, typ string) {
ss := strings.Split(ctype, ".")
if len(ss) == 1 {
return "", ctype
}
packageName = strings.Join(ss[0:len(ss)-1], ".")
typeName := ss[len(ss)-1]
importStr := strings.Map(badToUnderscore, packageName)
typ = importStr + "." + typeName
return packageName, typ
}
func getCastType(field *descriptor.<API key>) (packageName string, typ string, err error) {
if field.Options != nil {
var v interface{}
v, err = proto.GetExtension(field.Options, gogoproto.E_Casttype)
if err == nil && v.(*string) != nil {
ctype := *(v.(*string))
packageName, typ = splitCPackageType(ctype)
return packageName, typ, nil
}
}
return "", "", err
}
func FileName(file *FileDescriptor) string {
fname := path.Base(file.FileDescriptorProto.GetName())
fname = strings.Replace(fname, ".proto", "", -1)
fname = strings.Replace(fname, "-", "_", -1)
fname = strings.Replace(fname, ".", "_", -1)
return CamelCase(fname)
}
func (g *Generator) AllFiles() *descriptor.FileDescriptorSet {
set := &descriptor.FileDescriptorSet{}
set.File = make([]*descriptor.FileDescriptorProto, len(g.allFiles))
for i := range g.allFiles {
set.File[i] = g.allFiles[i].FileDescriptorProto
}
return set
}
func (d *Descriptor) Path() string {
return d.path
}
func (g *Generator) useTypes() string {
pkg := strings.Map(badToUnderscore, "github.com/gogo/protobuf/types")
g.customImports = append(g.customImports, "github.com/gogo/protobuf/types")
return pkg
}
func (d *FileDescriptor) GoPackageName() string {
return string(d.packageName)
}
|
// Use, modification, and distribution is subject to the Boost Software
// Contact the author at: fernando_cacciola@hotmail.com
// Revision History
// 19 Nov 2001 Syntatic changes as suggested by Darin Adler (Fernando Cacciola)
// 08 Nov 2001 Fixes to accommodate MSVC (Fernando Cacciola)
// 04 Nov 2001 Fixes to accommodate gcc2.92 (Fernando Cacciola)
// 30 Oct 2001 Some fixes suggested by Daryle Walker (Fernando Cacciola)
// 25 Oct 2001 Initial boostification (Fernando Cacciola)
// 23 Jan 2004 Inital add to cvs (post review)s
// 22 Jun 2011 Added support for specializing cast policies via numeric_cast_traits (Brandon Kohn).
#ifndef <API key>
#define <API key>
#include <boost/detail/workaround.hpp>
#if BOOST_WORKAROUND(BOOST_MSVC, < 1300) || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
# include<boost/numeric/conversion/detail/old_numeric_cast.hpp>
#else
#include <boost/type.hpp>
#include <boost/numeric/conversion/converter.hpp>
#include <boost/numeric/conversion/numeric_cast_traits.hpp>
namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{
template <typename Target, typename Source>
inline Target numeric_cast( Source arg )
{
typedef numeric::conversion_traits<Target, Source> conv_traits;
typedef numeric::numeric_cast_traits<Target, Source> cast_traits;
typedef abt_boost::numeric::converter
<
Target,
Source,
conv_traits,
typename cast_traits::overflow_policy,
typename cast_traits::rounding_policy,
abt_boost::numeric::raw_converter< conv_traits >,
typename cast_traits::<API key>
> converter;
return converter::convert(arg);
}
using numeric::bad_numeric_cast;
} // namespace abt_boost
#endif
#endif
|
package org.kercoin.magrit.sshd;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.sshd.SshServer;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.util.SecurityUtils;
import org.apache.sshd.server.CommandFactory;
import org.apache.sshd.server.ForwardingFilter;
import org.apache.sshd.server.<API key>;
import org.apache.sshd.server.UserAuth;
import org.apache.sshd.server.auth.UserAuthNone;
import org.apache.sshd.server.auth.UserAuthPublicKey;
import org.apache.sshd.server.keyprovider.<API key>;
import org.apache.sshd.server.keyprovider.<API key>;
import org.apache.sshd.server.session.ServerSession;
import org.kercoin.magrit.core.Configuration;
import org.kercoin.magrit.core.Context;
import org.kercoin.magrit.core.Configuration.Authentication;
import org.kercoin.magrit.core.services.Service;
import org.kercoin.magrit.core.services.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class Server implements Service.UseTCP {
protected final Logger log = LoggerFactory.getLogger(getClass());
private SshServer sshd;
private final int port;
@Inject
public Server(final Context ctx, CommandFactory factory) {
port = ctx.configuration().getSshPort();
sshd = SshServer.setUpDefaultServer();
if (SecurityUtils.<API key>()) {
sshd.setKeyPairProvider(new <API key>("key.pem"));
} else {
sshd.setKeyPairProvider(new <API key>("key.ser"));
}
<API key> auth = null;
if (ctx.configuration().getAuthentication() == Configuration.Authentication.SSH_PUBLIC_KEYS) {
auth = ctx.getInjector().getInstance(<API key>.class);
}
setupUserAuth(auth);
sshd.setCommandFactory(factory);
if (!ctx.configuration().isRemoteAllowed()) {
sshd.setSessionFactory(new <API key>());
}
sshd.setForwardingFilter(new ForwardingFilter() {
public boolean canForwardAgent(ServerSession session) {
return false;
}
public boolean canForwardX11(ServerSession session) {
return false;
}
public boolean canListen(InetSocketAddress address, ServerSession session) {
return false;
}
public boolean canConnect(InetSocketAddress address, ServerSession session) {
return false;
}
});
}
private void setupUserAuth(<API key> auth) {
List<NamedFactory<UserAuth>> list = new ArrayList<NamedFactory<UserAuth>>();
if (auth != null) {
list.add(new UserAuthPublicKey.Factory());
sshd.<API key>(auth);
} else {
list.add(new UserAuthNone.Factory());
}
sshd.<API key>(list);
}
@Override
public void start() throws ServiceException {
sshd.setPort(port);
try {
sshd.start();
} catch (IOException e) {
throw new ServiceException(e);
}
}
@Override
public String getName() {
return "SSH Service";
}
@Override
public int getTCPPort() {
return port;
}
@Override
public void logConfig(ConfigurationLogger log, Configuration cfg) {
log.logKey("SSHd", cfg.getSshPort());
log.logKey("Listening", cfg.isRemoteAllowed() ? "everybody" : "localhost");
log.logKey("Authent", cfg.getAuthentication().external());
if (cfg.getAuthentication() == Authentication.SSH_PUBLIC_KEYS) {
log.logSubKey("Keys dir", cfg.<API key>());
}
log.logKey("Home dir", cfg.<API key>());
log.logKey("Work dir", cfg.getWorkHomeDir());
}
}
|
/**
* BLOCK: blocks
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
import "./editor.scss";
import "./style.scss";
import React from "react";
import Select from "react-select";
const {
PanelBody,
PanelRow,
ServerSideRender,
TextControl,
SelectControl
} = wp.components;
var el = wp.element.createElement;
const { InspectorControls } = wp.editor;
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
registerBlockType("bos/<API key>", {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __("Evidence - block"), // Block title.
icon: "shield",
category: "badgeos-blocks",
keywords: [
__("Evidence - block"),
__("block"),
__("Evidence")
],
supports: {
// Turn off ability to edit HTML of block content
html: false,
// Turn off reusable block feature
reusable: false,
// Add alignwide and alignfull options
align: false
},
attributes: {
achievement: {
type: "string",
default: ""
},
user_id: {
type: "string",
default: ""
},
award_id: {
type: "string",
default: ""
},
},
edit: props => {
const {
attributes: {
achievement,
user_id,
award_id,
},
setAttributes
} = props;
let achievements_list = [];
let entries = [];
let user_lists = [];
wp.apiFetch({ path: `badgeos/<API key>/0/0`, method: 'GET' }).then(posts =>
posts.map(function (post) {
console.log(post);
entries.push(post);
})
);
wp.apiFetch({ path: "badgeos/achievements" }).then(posts =>
posts.map(function (post) {
achievements_list.push(post);
})
);
wp.apiFetch({ path: "badgeos/user-lists" }).then(posts =>
posts.map(function (post) {
user_lists.push(post);
})
);
let selectedAwardId = [];
if (null !== award_id && award_id != "") {
selectedAwardId = JSON.parse(award_id);
}
function handleAwardChange(award_id) {
props.setAttributes({ award_id: JSON.stringify(award_id) });
}
function loadawardids() {
entries = [];
var achievement_val = 0;
if (achievement) {
var achievement_array = JSON.parse(achievement)
achievement_val = achievement_array.value;
}
var user_id_val = 0;
if (user_id) {
var user_array = JSON.parse(user_id);
user_id_val = user_array.value;
}
wp.apiFetch({ path: "badgeos/<API key>/" + achievement_val + "/" + user_id_val + "", method: 'GET' }).then(posts =>
posts.map(function (post) {
entries.push(post);
})
);
}
let selectedUser = [];
if (null !== user_id && user_id != "") {
selectedUser = JSON.parse(user_id);
}
function handleUserChange(user_id) {
props.setAttributes({ user_id: JSON.stringify(user_id) });
loadawardids();
}
let selectedAchievement = [];
if (null !== achievement && achievement != "") {
selectedAchievement = JSON.parse(achievement);
}
function <API key>(achievement_val) {
props.setAttributes({
achievement: JSON.stringify(achievement_val)
});
loadawardids();
}
// Creates a <p class='<API key>'></p>.
return [
el("div", {
className: "<API key>",
style: { textAlign: "center" }
},
el(ServerSideRender, {
block: 'bos/<API key>',
attributes: props.attributes
})
),
<InspectorControls>
<PanelBody
title={__("Achievement", "badgeos")}
className="bos-block-inspector"
>
<PanelRow>
<label
htmlFor="bos-block-roles"
className="<API key>"
>
{__("Achievement", "badgeos")}
</label>
</PanelRow>
<PanelRow>
<Select
className="<API key>"
name="<API key>"
value={selectedAchievement}
onChange={<API key>}
options={achievements_list}
menuPlacement="auto"
/>
</PanelRow>
<PanelRow>
<label
htmlFor="bos-block-roles"
className="<API key>"
>
{__("User", "badgeos")}
</label>
</PanelRow>
<PanelRow>
<Select
className="<API key>"
name="<API key>"
value={selectedUser}
onChange={handleUserChange}
options={user_lists}
menuPlacement="auto"
/>
</PanelRow>
<PanelRow>
<label
htmlFor="bos-block-roles"
className="<API key>"
>
{__("Award Id", "badgeos")}
</label>
</PanelRow>
<PanelRow>
<Select
className="<API key>"
name="<API key>"
value={selectedAwardId}
onChange={handleAwardChange}
options={entries}
menuPlacement="auto"
/>
</PanelRow>
</PanelBody>
</InspectorControls>
];
},
save: props => {
return <div>Content</div>;
}
});
|
<?php
/**
* @package WordPress
* @subpackage Fast_Blog_Theme
* @since Fast Blog 1.0
*/
?>
<!-- Sidebar -->
<ul id="sidebar" class="<?php fastblog_option('sidebar'); ?>">
<?php dynamic_sidebar('sidebar'); ?>
</ul>
<!-- // Sidebar -->
|
# -*- coding: utf-8 -*-
from openerp import models, fields
class <API key>(models.Model):
_inherit = "account.bank.statement.line"
name = fields.Char(
string='Memo',
required=False,
default="",
)
|
# -*- coding: utf-8 -*-
# Etalage -- Open Data POIs portal
# By: Emmanuel Raviart <eraviart@easter-eggs.com>
# This file is part of Etalage.
# Etalage is free software; you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# Etalage is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""Context loaded and saved in WSGI requests"""
import gettext
import webob
from . import conf
__all__ = ['Ctx', 'null_ctx']
class Ctx(object):
_parent = None
default_values = dict(
_lang = None,
_scopes = UnboundLocalError,
_translator = None,
<API key> = None,
category_tags_slug = None,
container_base_url = None,
distance = None, # Max distance in km
gadget_id = None,
hide_directory = False,
req = None,
subscriber = None,
)
env_keys = ('_lang', '_scopes', '_translator')
def __init__(self, req = None):
if req is not None:
self.req = req
etalage_env = req.environ.get('etalage', {})
for key in object.__getattribute__(self, 'env_keys'):
value = etalage_env.get(key)
if value is not None:
setattr(self, key, value)
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
parent = object.__getattribute__(self, '_parent')
if parent is None:
default_values = object.__getattribute__(self, 'default_values')
if name in default_values:
return default_values[name]
raise
return getattr(parent, name)
@property
def _(self):
return self.translator.ugettext
def blank_req(self, path, environ = None, base_url = None, headers = None, POST = None, **kw):
env = environ.copy() if environ else {}
etalage_env = env.setdefault('etalage', {})
for key in self.env_keys:
value = getattr(self, key)
if value is not None:
etalage_env[key] = value
return webob.Request.blank(path, environ = env, base_url = base_url, headers = headers, POST = POST, **kw)
def get_containing(self, name, depth = 0):
"""Return the n-th (n = ``depth``) context containing attribute named ``name``."""
ctx_dict = object.__getattribute__(self, '__dict__')
if name in ctx_dict:
if depth <= 0:
return self
depth -= 1
parent = ctx_dict.get('_parent')
if parent is None:
return None
return parent.get_containing(name, depth = depth)
def get_inherited(self, name, default = UnboundLocalError, depth = 1):
ctx = self.get_containing(name, depth = depth)
if ctx is None:
if default is UnboundLocalError:
raise AttributeError('Attribute %s not found in %s' % (name, self))
return default
return object.__getattribute__(ctx, name)
def iter(self):
yield self
parent = object.__getattribute__(self, '_parent')
if parent is not None:
for ancestor in parent.iter():
yield ancestor
def iter_containing(self, name):
ctx_dict = object.__getattribute__(self, '__dict__')
if name in ctx_dict:
yield self
parent = ctx_dict.get('_parent')
if parent is not None:
for ancestor in parent.iter_containing(name):
yield ancestor
def iter_inherited(self, name):
for ctx in self.iter_containing(name):
yield object.__getattribute__(ctx, name)
def lang_del(self):
del self._lang
if self.req is not None and self.req.environ.get('etalage') is not None \
and '_lang' in self.req.environ['etalage']:
del self.req.environ['etalage']['_lang']
def lang_get(self):
if self._lang is None:
# self._lang = self.req.accept_language.best_matches('en-US') if self.req is not None else []
# Note: Don't forget to add country-less language code when only a "language-COUNTRY" code is given.
self._lang = ['fr-FR', 'fr']
if self.req is not None:
self.req.environ.setdefault('etalage', {})['_lang'] = self._lang
return self._lang
def lang_set(self, lang):
self._lang = lang
if self.req is not None:
self.req.environ.setdefault('etalage', {})['_lang'] = self._lang
# Reinitialize translator for new languages.
if self._translator is not None:
# Don't del self._translator, because attribute _translator can be defined in a parent.
self._translator = None
if self.req is not None and self.req.environ.get('etalage') is not None \
and '_translator' in self.req.environ['etalage']:
del self.req.environ['etalage']['_translator']
lang = property(lang_get, lang_set, lang_del)
def new(self, **kwargs):
ctx = Ctx()
ctx._parent = self
for name, value in kwargs.iteritems():
setattr(ctx, name, value)
return ctx
@property
def parent(self):
return object.__getattribute__(self, '_parent')
def scopes_del(self):
del self._scopes
if self.req is not None and self.req.environ.get('wenoit_etalage') is not None \
and '_scopes' in self.req.environ['wenoit_etalage']:
del self.req.environ['wenoit_etalage']['_scopes']
def scopes_get(self):
return self._scopes
def scopes_set(self, scopes):
self._scopes = scopes
if self.req is not None:
self.req.environ.setdefault('wenoit_etalage', {})['_scopes'] = scopes
scopes = property(scopes_get, scopes_set, scopes_del)
@property
def session(self):
return self.req.environ.get('beaker.session') if self.req is not None else None
@property
def translator(self):
"""Get a valid translator object from one or several languages names."""
if self._translator is None:
languages = self.lang
if not languages:
return gettext.NullTranslations()
if not isinstance(languages, list):
languages = [languages]
translator = gettext.NullTranslations()
<API key> = conf['<API key>'] or {}
for name, i18n_dir in [
('biryani', conf['biryani_i18n_dir']),
(conf['package_name'], conf['i18n_dir']),
] + sorted(<API key>.iteritems()):
if name is not None and i18n_dir is not None:
translator = new_translator(name, i18n_dir, languages, fallback = translator)
self._translator = translator
return self._translator
null_ctx = Ctx()
null_ctx.lang = ['fr-FR', 'fr']
def new_translator(domain, localedir, languages, fallback = None):
new = gettext.translation(domain, localedir, fallback = True, languages = languages)
if fallback is not None:
new.add_fallback(fallback)
return new
|
<?php
if (!defined('STATUSNET') && !defined('LACONICA')) {
exit(1);
}
class <API key> extends Action
{
var $peopletag = null;
var $tagger = null;
/**
* Prepare to run
*/
function prepare($args)
{
parent::prepare($args);
if (!common_logged_in()) {
// TRANS: Client error displayed when trying to perform an action while not logged in.
$this->clientError(_('You must be logged in to unsubscribe from a list.'));
return false;
}
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
// TRANS: Client error displayed when trying to use another method than POST.
$this->clientError(_('This action only accepts POST requests.'));
return false;
}
// CSRF protection
$token = $this->trimmed('token');
if (!$token || $token != <API key>()) {
// TRANS: Client error displayed when the session token does not match or is not given.
$this->clientError(_('There was a problem with your session token.'.
' Try again, please.'));
return false;
}
$tagger_arg = $this->trimmed('tagger');
$tag_arg = $this->trimmed('tag');
$id = intval($this->arg('id'));
if ($id) {
$this->peopletag = Profile_list::getKV('id', $id);
} else {
// TRANS: Client error displayed when trying to perform an action without providing an ID.
$this->clientError(_('No ID given.'), 404);
return false;
}
if (!$this->peopletag || $this->peopletag->private) {
// TRANS: Client error displayed trying to reference a non-existing list.
$this->clientError(_('No such list.'), 404);
return false;
}
$this->tagger = Profile::getKV('id', $this->peopletag->tagger);
return true;
}
/**
* Handle the request
*
* On POST, add the current user to the group
*
* @param array $args unused
*
* @return void
*/
function handle($args)
{
parent::handle($args);
$cur = common_current_user();
try {
<API key>::add($this->peopletag, $cur);
} catch (Exception $e) {
// TRANS: Server error displayed subscribing to a list fails.
// TRANS: %1$s is a user nickname, %2$s is a list, %3$s is the error message (no period).
$this->serverError(sprintf(_('Could not subscribe user %1$s to list %2$s: %3$s'),
$cur->nickname, $this->peopletag->tag), $e->getMessage());
}
if ($this->boolean('ajax')) {
$this->startHTML('text/xml;charset=utf-8');
$this->elementStart('head');
// TRANS: Title of form to subscribe to a list.
// TRANS: %1%s is a user nickname, %2$s is a list, %3$s is a tagger nickname.
$this->element('title', null, sprintf(_('%1$s subscribed to list %2$s by %3$s'),
$cur->nickname,
$this->peopletag->tag,
$this->tagger->nickname));
$this->elementEnd('head');
$this->elementStart('body');
$lf = new <API key>($this, $this->peopletag);
$lf->show();
$this->elementEnd('body');
$this->endHTML();
} else {
common_redirect(common_local_url('<API key>',
array('tagger' => $this->tagger->nickname,
'tag' =>$this->peopletag->tag)),
303);
}
}
}
|
package org.openjst.protocols.basic.encoder;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.<API key>;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.openjst.commons.io.buffer.DataBufferException;
import org.openjst.commons.security.checksum.CRC16;
import org.openjst.protocols.basic.constants.<API key>;
import org.openjst.protocols.basic.pdu.PDU;
public class ProtocolEncoder extends OneToOneEncoder {
public static final byte[] RESERVED = new byte[]{0, 0, 0, 0, 0};
@Override
protected Object encode(final <API key> ctx, final Channel channel, final Object msg) throws Exception {
if (msg instanceof PDU) {
return encodePacket((PDU) msg);
} else {
return msg;
}
}
public static ChannelBuffer encodePacket(final PDU packet) throws DataBufferException {
final byte[] msgBody = packet.encode();
final ChannelBuffer buffer = ChannelBuffers.buffer(16 + msgBody.length);
buffer.writeByte(<API key>.VERSION);
buffer.writeShort(0);
buffer.writeShort(packet.getType());
buffer.writeInt(msgBody.length);
buffer.writeBytes(RESERVED);
buffer.writeShort(CRC16.checksum(msgBody));
if (msgBody.length > 0) {
buffer.writeBytes(msgBody);
}
return buffer;
}
}
|
package com.thegame.server.presentation.exceptions;
import com.thegame.server.common.exceptions.TypifiedException;
/**
* @author e103880
*/
public class <API key> extends TypifiedException{
private final <API key> exceptionType;
private final Object[] arguments;
public <API key>(final <API key> _exceptionType){
this(_exceptionType,new Object[]{});
}
public <API key>(final <API key> _exceptionType,final Object... _arguments){
super(_exceptionType.getDescription());
this.exceptionType=_exceptionType;
this.arguments=_arguments;
}
public <API key>(final Throwable _cause,final <API key> _exceptionType){
this(_cause,_exceptionType,new Object[]{});
}
public <API key>(final Throwable _cause,final <API key> _exceptionType,final Object... _arguments){
super(_exceptionType.getDescription(),_cause);
this.exceptionType=_exceptionType;
this.arguments=_arguments;
}
@Override
public <API key> getExceptionType(){
return this.exceptionType;
}
@Override
public Object[] getArguments() {
return arguments;
}
@Override
public String getMessage() {
return getProcessedMessage();
}
}
|
/**
* @ngdoc service
* @name ftepApp.SubscriptionService
* @description
* # SubscriptionService
* Service for subscriptions.
*/
'use strict';
define(['../ftepmodules', 'traversonHal'], function (ftepmodules, <API key>) {
ftepmodules.service('SubscriptionService', [ 'ftepProperties', '$q', 'traverson', function (ftepProperties, $q, traverson) {
var self = this;
traverson.registerMediaType(<API key>.mediaType, <API key>);
var rootUri = ftepProperties.URLv2;
var halAPI = traverson.from(rootUri).jsonHal().useAngularHttp();
var deleteAPI = traverson.from(rootUri).useAngularHttp();
this.<API key> = function(user) {
var deferred = $q.defer();
halAPI.from(rootUri + '/subscriptions/search/findByOwner?owner=' + user._links.self.href)
.newRequest()
.getResource()
.result
.then(
function(document) {
deferred.resolve(document);
}, function(error) {
MessageService.addError('Failed to get subscriptions for user ' + user.name, error);
deferred.reject();
});
return deferred.promise;
};
this.updateSubscription = function(subscription) {
var patchedSubscription = {
packageName: subscription.packageName,
storageQuota: subscription.storageQuota,
processingQuota: subscription.processingQuota,
subscriptionStart: subscription.subscriptionStart,
subscriptionEnd: subscription.subscriptionEnd,
commentText: subscription.commentText
};
var deferred = $q.defer();
halAPI.from(rootUri + '/subscriptions/' + subscription.id)
.newRequest()
.patch(patchedSubscription)
.result
.then(
function(document) {
deferred.resolve(document);
}, function(error) {
MessageService.addError('Failed to update subscription ' + subscription.id, error);
deferred.reject();
});
return deferred.promise;
};
this.createSubscription = function(subscription, subscriptionOwner, subscriptionCreator) {
var newSubscription = {
owner: subscriptionOwner._links.self.href,
packageName: subscription.packageName,
storageQuota: subscription.storageQuota,
processingQuota: subscription.processingQuota,
subscriptionStart: subscription.subscriptionStart,
subscriptionEnd: subscription.subscriptionEnd,
commentText: subscription.commentText,
creator: subscriptionCreator._links.self.href
};
var deferred = $q.defer();
halAPI.from(rootUri + '/subscriptions')
.newRequest()
.post(newSubscription)
.result
.then(
function(document) {
deferred.resolve(document);
}, function(error) {
MessageService.addError('Failed to update subscription ' + subscription.id, error);
deferred.reject();
});
return deferred.promise;
};
this.deleteSubscription = function(subscription) {
var deferred = $q.defer();
deleteAPI.from(rootUri + '/subscriptions/' + subscription.id)
.newRequest()
.delete()
.result
.then(
function(document) {
if (200 <= document.status && document.status < 300) {
deferred.resolve(document);
} else {
MessageService.addError('Failed to delete subscription ' + subscription.id, error);
deferred.reject();
}
}, function(error) {
MessageService.addError('Failed to delete subscription ' + subscription.id, error);
deferred.reject();
});
return deferred.promise;
};
this.cancelSubscription = function(subscription) {
var deferred = $q.defer();
halAPI.from(rootUri + '/subscriptions/' + subscription.id + "/cancel")
.newRequest()
.post()
.result
.then(
function(document) {
deferred.resolve(document);
}, function(error) {
MessageService.addError('Failed to cancel subscription ' + subscription.id, error);
deferred.reject();
});
return deferred.promise;
};
return this;
}]);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.