code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
Bitrix 16.5 Business Demo = 16d7a678d19259b91107fcffd1fa68c9
| Java |
package eu.ehri.project.models.base;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.frames.modules.javahandler.JavaHandler;
import com.tinkerpop.frames.modules.javahandler.JavaHandlerContext;
import eu.ehri.project.definitions.Ontology;
import eu.ehri.project.models.events.SystemEvent;
import eu.ehri.project.models.utils.JavaHandlerUtils;
public interface Actioner extends NamedEntity {
/**
* Fetch a list of Actions for this user in newest-first order.
*
* @return
*/
@JavaHandler
public Iterable<SystemEvent> getActions();
@JavaHandler
public Iterable<SystemEvent> getLatestAction();
/**
* Implementation of complex methods.
*/
abstract class Impl implements JavaHandlerContext<Vertex>, Actioner {
public Iterable<SystemEvent> getLatestAction() {
return frameVertices(gremlin()
.out(Ontology.ACTIONER_HAS_LIFECYCLE_ACTION)
.out(Ontology.ENTITY_HAS_EVENT));
}
public Iterable<SystemEvent> getActions() {
return frameVertices(gremlin().as("n").out(Ontology.ACTIONER_HAS_LIFECYCLE_ACTION)
.loop("n", JavaHandlerUtils.noopLoopFunc, JavaHandlerUtils.noopLoopFunc)
.out(Ontology.ENTITY_HAS_EVENT));
}
}
}
| Java |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AppointmentsManagement.Classes;
namespace AppointmentsManagement.Forms
{
public partial class wfnSrvcOffrdForm : WeifenLuo.WinFormsUI.Docking.DockContent
{
#region "GLOBAL VARIABLES..."
//Records;
cadmaFunctions.NavFuncs myNav = new cadmaFunctions.NavFuncs();
bool beenToCheckBx = false;
long rec_cur_indx = 0;
bool is_last_rec = false;
long totl_rec = 0;
long last_rec_num = 0;
public string rec_SQL = "";
public string recDt_SQL = "";
bool obey_evnts = false;
bool autoLoad = false;
public bool txtChngd = false;
public string srchWrd = "%";
bool addRec = false;
bool editRec = false;
bool someLinesFailed = false;
bool vwRecs = false;
bool addRecs = false;
bool editRecs = false;
bool delRecs = false;
//Line Dtails;
long ldt_cur_indx = 0;
bool is_last_ldt = false;
long totl_ldt = 0;
long last_ldt_num = 0;
bool obey_ldt_evnts = false;
public int curid = -1;
public string curCode = "";
#endregion
public wfnSrvcOffrdForm()
{
InitializeComponent();
}
private void wfnGLIntfcForm_Load(object sender, EventArgs e)
{
Color[] clrs = Global.mnFrm.cmCde.getColors();
this.BackColor = clrs[0];
this.tabPage1.BackColor = clrs[0];
this.disableFormButtons();
this.curid = Global.mnFrm.cmCde.getOrgFuncCurID(Global.mnFrm.cmCde.Org_id);
this.curCode = Global.mnFrm.cmCde.getPssblValNm(this.curid);
this.loadPanel();
}
public void disableFormButtons()
{
bool vwSQL = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[5]);
bool rcHstry = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[6]);
this.vwRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[4]);
this.addRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]);
this.editRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[11]);
this.delRecs = Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[12]);
this.vwSQLButton.Enabled = vwSQL;
this.rcHstryButton.Enabled = rcHstry;
this.vwSQLDtButton.Enabled = vwSQL;
this.rcHstryDtButton.Enabled = rcHstry;
this.saveButton.Enabled = false;
this.addButton.Enabled = this.addRecs;
this.editButton.Enabled = this.editRecs;
this.addDtButton.Enabled = this.editRecs;
this.delDtButton.Enabled = this.editRecs;
this.delButton.Enabled = this.delRecs;
}
#region "SERVICE TYPES..."
public void loadPanel()
{
Cursor.Current = Cursors.Default;
this.obey_evnts = false;
if (this.searchInComboBox.SelectedIndex < 0)
{
this.searchInComboBox.SelectedIndex = 1;
}
if (searchForTextBox.Text.Contains("%") == false)
{
this.searchForTextBox.Text = "%" + this.searchForTextBox.Text.Replace(" ", "%") + "%";
}
if (this.searchForTextBox.Text == "%%")
{
this.searchForTextBox.Text = "%";
}
int dsply = 0;
if (this.dsplySizeComboBox.Text == ""
|| int.TryParse(this.dsplySizeComboBox.Text, out dsply) == false)
{
this.dsplySizeComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
this.is_last_rec = false;
this.totl_rec = Global.mnFrm.cmCde.Big_Val;
this.getPnlData();
this.obey_evnts = true;
this.srvcsOffrdListView.Focus();
}
private void getPnlData()
{
this.updtTotals();
this.populateSrvsTypListVw();
this.updtNavLabels();
}
private void updtTotals()
{
Global.mnFrm.cmCde.navFuncts.FindNavigationIndices(
long.Parse(this.dsplySizeComboBox.Text), this.totl_rec);
if (this.rec_cur_indx >= Global.mnFrm.cmCde.navFuncts.totalGroups)
{
this.rec_cur_indx = Global.mnFrm.cmCde.navFuncts.totalGroups - 1;
}
if (this.rec_cur_indx < 0)
{
this.rec_cur_indx = 0;
}
Global.mnFrm.cmCde.navFuncts.currentNavigationIndex = this.rec_cur_indx;
}
private void updtNavLabels()
{
this.moveFirstButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveFirstBtnStatus();
this.movePreviousButton.Enabled = Global.mnFrm.cmCde.navFuncts.movePrevBtnStatus();
this.moveNextButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveNextBtnStatus();
this.moveLastButton.Enabled = Global.mnFrm.cmCde.navFuncts.moveLastBtnStatus();
this.positionTextBox.Text = Global.mnFrm.cmCde.navFuncts.displayedRecordsNumbers();
if (this.is_last_rec == true ||
this.totl_rec != Global.mnFrm.cmCde.Big_Val)
{
this.totalRecsLabel.Text = Global.mnFrm.cmCde.navFuncts.totalRecordsLabel();
}
else
{
this.totalRecsLabel.Text = "of Total";
}
}
private void populateSrvsTypListVw()
{
this.obey_evnts = false;
DataSet dtst = Global.get_SrvcTyps(this.searchForTextBox.Text,
this.searchInComboBox.Text, this.rec_cur_indx,
int.Parse(this.dsplySizeComboBox.Text), Global.mnFrm.cmCde.Org_id);
this.srvcsOffrdListView.Items.Clear();
this.clearDtInfo();
this.loadDtPanel();
if (!this.editRec)
{
this.disableDtEdit();
}
//System.Windows.Forms.Application.DoEvents();
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.last_rec_num = Global.mnFrm.cmCde.navFuncts.startIndex() + i;
ListViewItem nwItem = new ListViewItem(new string[] {
(Global.mnFrm.cmCde.navFuncts.startIndex() + i).ToString(),
dtst.Tables[0].Rows[i][1].ToString(),
dtst.Tables[0].Rows[i][0].ToString()});
this.srvcsOffrdListView.Items.Add(nwItem);
}
this.correctNavLbls(dtst);
if (this.srvcsOffrdListView.Items.Count > 0)
{
this.obey_evnts = true;
this.srvcsOffrdListView.Items[0].Selected = true;
}
else
{
}
this.obey_evnts = true;
}
private void populateDt(int HdrID)
{
//Global.mnFrm.cmCde.minimizeMemory();
this.clearDtInfo();
//System.Windows.Forms.Application.DoEvents();
if (this.editRec == false)
{
this.disableDtEdit();
}
this.obey_evnts = false;
DataSet dtst = Global.get_One_ServTypeDt(HdrID);
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.serviceTypeIDTextBox.Text = dtst.Tables[0].Rows[i][0].ToString();
this.serviceNameTextBox.Text = dtst.Tables[0].Rows[i][1].ToString();
this.servTypeDescTextBox.Text = dtst.Tables[0].Rows[i][2].ToString();
this.salesItemIDTextBox.Text = dtst.Tables[0].Rows[i][4].ToString();
this.salesItemTextBox.Text = Global.get_InvItemNm(
int.Parse(dtst.Tables[0].Rows[i][4].ToString()));
this.priceCurLabel.Text = this.curCode;
this.priceLabel.Text = Global.get_InvItemPrice(int.Parse(dtst.Tables[0].Rows[i][4].ToString())).ToString("#,##0.00");
string orgnlItm = dtst.Tables[0].Rows[i][5].ToString();
this.srvcTypeComboBox.Items.Clear();
this.srvcTypeComboBox.Items.Add(orgnlItm);
if (this.editRec == false)
{
}
this.srvcTypeComboBox.SelectedItem = orgnlItm;
this.isEnabledCheckBox.Checked = Global.mnFrm.cmCde.cnvrtBitStrToBool(dtst.Tables[0].Rows[i][3].ToString());
}
this.loadDtPanel();
this.obey_evnts = true;
}
private void correctNavLbls(DataSet dtst)
{
long totlRecs = dtst.Tables[0].Rows.Count;
if (this.rec_cur_indx == 0 && totlRecs == 0)
{
this.is_last_rec = true;
this.totl_rec = 0;
this.last_rec_num = 0;
this.rec_cur_indx = 0;
this.updtTotals();
this.updtNavLabels();
}
else if (this.totl_rec == Global.mnFrm.cmCde.Big_Val
&& totlRecs < long.Parse(this.dsplySizeComboBox.Text))
{
this.totl_rec = this.last_rec_num;
if (totlRecs == 0)
{
this.rec_cur_indx -= 1;
this.updtTotals();
this.populateSrvsTypListVw();
}
else
{
this.updtTotals();
}
}
}
private bool shdObeyEvts()
{
return this.obey_evnts;
}
private void PnlNavButtons(object sender, System.EventArgs e)
{
System.Windows.Forms.ToolStripButton sentObj = (System.Windows.Forms.ToolStripButton)sender;
this.totalRecsLabel.Text = "";
if (sentObj.Name.ToLower().Contains("first"))
{
this.is_last_rec = false;
this.rec_cur_indx = 0;
}
else if (sentObj.Name.ToLower().Contains("previous"))
{
this.is_last_rec = false;
this.rec_cur_indx -= 1;
}
else if (sentObj.Name.ToLower().Contains("next"))
{
this.is_last_rec = false;
this.rec_cur_indx += 1;
}
else if (sentObj.Name.ToLower().Contains("last"))
{
this.is_last_rec = true;
this.totl_rec = Global.get_Ttl_SrvsTyps(this.searchForTextBox.Text,
this.searchInComboBox.Text, Global.mnFrm.cmCde.Org_id);
this.updtTotals();
this.rec_cur_indx = Global.mnFrm.cmCde.navFuncts.totalGroups - 1;
}
this.getPnlData();
}
private void clearDtInfo()
{
this.obey_evnts = false;
//
this.serviceTypeIDTextBox.Text = "-1";
this.serviceNameTextBox.Text = "";
this.servTypeDescTextBox.Text = "";
this.isEnabledCheckBox.Checked = false;
this.salesItemIDTextBox.Text = "-1";
this.salesItemTextBox.Text = "";
this.priceLabel.Text = "0.00";
this.priceCurLabel.Text = this.curCode;
if (this.editRec == false)
{
this.srvcTypeComboBox.Items.Clear();
}
this.obey_evnts = true;
}
private void prpareForDtEdit()
{
this.obey_evnts = false;
this.saveButton.Enabled = true;
this.serviceNameTextBox.ReadOnly = false;
this.serviceNameTextBox.BackColor = Color.FromArgb(255, 255, 128);
this.servTypeDescTextBox.ReadOnly = false;
this.servTypeDescTextBox.BackColor = Color.White;
this.salesItemTextBox.ReadOnly = false;
this.salesItemTextBox.BackColor = Color.White;// FromArgb(255, 255, 128);
string brgtSQL = "";
bool isDynmc = false;
DataSet dtst = Global.mnFrm.cmCde.getLovValues("%", "Both", 0, 5000,
ref brgtSQL, Global.mnFrm.cmCde.getLovID("System Codes for Appointment Services"),
ref isDynmc, -1, "", "", "");
object orgnlItm = null;
if (this.srvcTypeComboBox.SelectedIndex >= 0)
{
orgnlItm = this.srvcTypeComboBox.SelectedItem;
}
if (this.addRec)
{
this.srvcTypeComboBox.Items.Clear();
for (int i = 0; i < dtst.Tables[0].Rows.Count; i++)
{
this.srvcTypeComboBox.Items.Add(dtst.Tables[0].Rows[i][0].ToString());
}
}
if (orgnlItm != null)
{
this.srvcTypeComboBox.SelectedItem = orgnlItm;
}
this.srvcTypeComboBox.BackColor = Color.FromArgb(255, 255, 128);
this.obey_evnts = true;
}
private void disableDtEdit()
{
if (this.editButton.Text == "STOP")
{
EventArgs e = new EventArgs();
this.editButton_Click(this.editButton, e);
}
this.addRec = false;
this.editRec = false;
this.saveButton.Enabled = false;
this.editButton.Enabled = this.editRecs;
this.addButton.Enabled = this.addRecs;
this.serviceNameTextBox.ReadOnly = true;
this.serviceNameTextBox.BackColor = Color.WhiteSmoke;
this.servTypeDescTextBox.ReadOnly = true;
this.servTypeDescTextBox.BackColor = Color.WhiteSmoke;
this.salesItemTextBox.ReadOnly = true;
this.salesItemTextBox.BackColor = Color.WhiteSmoke;
if (this.srvcTypeComboBox.SelectedIndex >= 0)
{
object orgnlItm = this.srvcTypeComboBox.SelectedItem;
this.srvcTypeComboBox.Items.Clear();
this.srvcTypeComboBox.Items.Add(orgnlItm);
this.srvcTypeComboBox.SelectedItem = orgnlItm;
}
else
{
this.srvcTypeComboBox.Items.Clear();
}
this.srvcTypeComboBox.BackColor = Color.WhiteSmoke;
}
private void searchForTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.goButton.PerformClick();
}
}
private void positionTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Up)
{
this.PnlNavButtons(this.movePreviousButton, ex);
}
else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Down)
{
this.PnlNavButtons(this.moveNextButton, ex);
}
}
private void goButton_Click(object sender, EventArgs e)
{
this.loadPanel();
}
#endregion
private void srvcsOffrdListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.obey_evnts == false || this.srvcsOffrdListView.SelectedItems.Count > 1)
{
return;
}
//this.populateDt(-100000);
if (this.srvcsOffrdListView.SelectedItems.Count == 1)
{
this.populateDt(int.Parse(this.srvcsOffrdListView.SelectedItems[0].SubItems[2].Text));
}
else if (this.addRec == false)
{
this.clearDtInfo();
this.disableDtEdit();
this.disableLnsEdit();
this.dataDefDataGridView.Rows.Clear();
}
}
private void loadDtPanel()
{
this.changeGridVw();
this.obey_ldt_evnts = false;
if (this.searchInDtComboBox.SelectedIndex < 0)
{
this.searchInDtComboBox.SelectedIndex = 2;
}
if (this.searchForDtTextBox.Text.Contains("%") == false)
{
this.searchForDtTextBox.Text = "%" + this.searchForDtTextBox.Text.Replace(" ", "%") + "%";
}
if (this.searchForDtTextBox.Text == "%%")
{
this.searchForDtTextBox.Text = "%";
}
int dsply = 0;
if (this.dsplySizeDtComboBox.Text == ""
|| int.TryParse(this.dsplySizeDtComboBox.Text, out dsply) == false)
{
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
//this.groupBox8.Height = this.g.Bottom - this.toolStrip4.Bottom - 50;
this.ldt_cur_indx = 0;
this.is_last_ldt = false;
this.last_ldt_num = 0;
this.totl_ldt = Global.mnFrm.cmCde.Big_Val;
this.getldtPnlData();
//this.dataDefDataGridView.Focus();
this.obey_ldt_evnts = true;
//SendKeys.Send("{TAB}");
//System.Windows.Forms.Application.DoEvents();
//SendKeys.Send("{HOME}");
//System.Windows.Forms.Application.DoEvents();
}
private void getldtPnlData()
{
this.updtldtTotals();
this.populateDtLines(int.Parse(this.serviceTypeIDTextBox.Text));
this.updtldtNavLabels();
}
private void updtldtTotals()
{
int dsply = 0;
if (this.dsplySizeDtComboBox.Text == ""
|| int.TryParse(this.dsplySizeDtComboBox.Text, out dsply) == false)
{
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
}
this.myNav.FindNavigationIndices(
long.Parse(this.dsplySizeDtComboBox.Text), this.totl_ldt);
if (this.ldt_cur_indx >= this.myNav.totalGroups)
{
this.ldt_cur_indx = this.myNav.totalGroups - 1;
}
if (this.ldt_cur_indx < 0)
{
this.ldt_cur_indx = 0;
}
this.myNav.currentNavigationIndex = this.ldt_cur_indx;
}
private void updtldtNavLabels()
{
this.moveFirstDtButton.Enabled = this.myNav.moveFirstBtnStatus();
this.movePreviousDtButton.Enabled = this.myNav.movePrevBtnStatus();
this.moveNextDtButton.Enabled = this.myNav.moveNextBtnStatus();
this.moveLastDtButton.Enabled = this.myNav.moveLastBtnStatus();
this.positionDtTextBox.Text = this.myNav.displayedRecordsNumbers();
if (this.is_last_ldt == true ||
this.totl_ldt != Global.mnFrm.cmCde.Big_Val)
{
this.totalRecsDtLabel.Text = this.myNav.totalRecordsLabel();
}
else
{
this.totalRecsDtLabel.Text = "of Total";
}
}
private void populateDtLines(int HdrID)
{
this.dataDefDataGridView.Rows.Clear();
if (HdrID > 0 && this.addRec == false && this.editRec == false)
{
this.disableLnsEdit();
}
this.obey_ldt_evnts = false;
//System.Windows.Forms.Application.DoEvents();
DataSet dtst = Global.get_datadfntns(HdrID,
this.searchForDtTextBox.Text,
this.searchInDtComboBox.Text,
this.ldt_cur_indx,
int.Parse(this.dsplySizeDtComboBox.Text));
int rwcnt = dtst.Tables[0].Rows.Count;
for (int i = 0; i < rwcnt; i++)
{
this.last_ldt_num = this.myNav.startIndex() + i;
//System.Windows.Forms.Application.DoEvents();
this.dataDefDataGridView.RowCount += 1;//, this.apprvlStatusTextBox.Text.Insert(this.rgstrDtDataGridView.RowCount - 1, 1);
int rowIdx = this.dataDefDataGridView.RowCount - 1;
this.dataDefDataGridView.Rows[rowIdx].HeaderCell.Value = (i + 1).ToString();
//Object[] cellDesc = new Object[27];
this.dataDefDataGridView.Rows[rowIdx].Cells[0].Value = dtst.Tables[0].Rows[i][2].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[1].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[2].Value = dtst.Tables[0].Rows[i][3].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[3].Value = dtst.Tables[0].Rows[i][4].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[4].Value = dtst.Tables[0].Rows[i][5].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[5].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[6].Value = dtst.Tables[0].Rows[i][6].ToString();
this.dataDefDataGridView.Rows[rowIdx].Cells[7].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[8].Value = Global.mnFrm.cmCde.cnvrtBitStrToBool(dtst.Tables[0].Rows[i][7].ToString());
this.dataDefDataGridView.Rows[rowIdx].Cells[9].Value = dtst.Tables[0].Rows[i][0].ToString();
}
this.correctldtNavLbls(dtst);
this.obey_ldt_evnts = true;
System.Windows.Forms.Application.DoEvents();
}
private void correctldtNavLbls(DataSet dtst)
{
long totlRecs = dtst.Tables[0].Rows.Count;
if (this.totl_ldt == Global.mnFrm.cmCde.Big_Val
&& totlRecs < long.Parse(this.dsplySizeDtComboBox.Text))
{
this.totl_ldt = this.last_ldt_num;
if (totlRecs == 0)
{
this.ldt_cur_indx -= 1;
this.updtldtTotals();
this.populateDtLines(int.Parse(this.serviceTypeIDTextBox.Text));
}
else
{
this.updtldtTotals();
}
}
}
private bool shdObeyldtEvts()
{
return this.obey_ldt_evnts;
}
private void DtPnlNavButtons(object sender, System.EventArgs e)
{
System.Windows.Forms.ToolStripButton sentObj = (System.Windows.Forms.ToolStripButton)sender;
this.totalRecsDtLabel.Text = "";
if (sentObj.Name.ToLower().Contains("first"))
{
this.is_last_ldt = false;
this.ldt_cur_indx = 0;
}
else if (sentObj.Name.ToLower().Contains("previous"))
{
this.is_last_ldt = false;
this.ldt_cur_indx -= 1;
}
else if (sentObj.Name.ToLower().Contains("next"))
{
this.is_last_ldt = false;
this.ldt_cur_indx += 1;
}
else if (sentObj.Name.ToLower().Contains("last"))
{
this.is_last_ldt = true;
this.totl_ldt = Global.get_ttl_datadfntns(int.Parse(this.serviceTypeIDTextBox.Text),
this.searchForDtTextBox.Text,
this.searchInDtComboBox.Text);
this.updtldtTotals();
this.ldt_cur_indx = this.myNav.totalGroups - 1;
}
this.getldtPnlData();
}
private void prpareForLnsEdit()
{
this.saveButton.Enabled = true;
this.dataDefDataGridView.ReadOnly = false;
this.dataDefDataGridView.Columns[0].ReadOnly = false;
this.dataDefDataGridView.Columns[0].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[2].ReadOnly = false;
this.dataDefDataGridView.Columns[2].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[3].ReadOnly = false;
this.dataDefDataGridView.Columns[3].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 128);
this.dataDefDataGridView.Columns[4].ReadOnly = false;
this.dataDefDataGridView.Columns[4].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[6].ReadOnly = false;
this.dataDefDataGridView.Columns[6].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[8].ReadOnly = false;
this.dataDefDataGridView.Columns[8].DefaultCellStyle.BackColor = Color.White;
this.dataDefDataGridView.Columns[9].ReadOnly = true;
this.dataDefDataGridView.Columns[9].DefaultCellStyle.BackColor = Color.Gainsboro;
}
private void disableLnsEdit()
{
this.addRec = false;
this.editRec = false;
this.saveButton.Enabled = false;
this.dataDefDataGridView.ReadOnly = true;
this.dataDefDataGridView.Columns[0].ReadOnly = true;
this.dataDefDataGridView.Columns[0].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[2].ReadOnly = true;
this.dataDefDataGridView.Columns[2].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[3].ReadOnly = true;
this.dataDefDataGridView.Columns[3].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[4].ReadOnly = true;
this.dataDefDataGridView.Columns[4].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[6].ReadOnly = true;
this.dataDefDataGridView.Columns[6].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[8].ReadOnly = true;
this.dataDefDataGridView.Columns[8].DefaultCellStyle.BackColor = Color.Gainsboro;
this.dataDefDataGridView.Columns[9].ReadOnly = true;
this.dataDefDataGridView.Columns[9].DefaultCellStyle.BackColor = Color.Gainsboro;
System.Windows.Forms.Application.DoEvents();
}
private void vwSQLDtButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.showSQL(this.recDt_SQL, 5);
}
private void rcHstryDtButton_Click(object sender, EventArgs e)
{
if (this.dataDefDataGridView.CurrentCell != null
&& this.dataDefDataGridView.SelectedRows.Count <= 0)
{
this.dataDefDataGridView.Rows[this.dataDefDataGridView.CurrentCell.RowIndex].Selected = true;
}
if (this.dataDefDataGridView.SelectedRows.Count <= 0)
{
Global.mnFrm.cmCde.showMsg("Please select a Record First!", 0);
return;
}
Global.mnFrm.cmCde.showRecHstry(
Global.get_DT_Rec_Hstry(int.Parse(this.dataDefDataGridView.SelectedRows[0].Cells[9].Value.ToString())), 6);
}
private void vwSQLButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.showSQL(this.rec_SQL, 5);
}
private void rcHstryButton_Click(object sender, EventArgs e)
{
if (this.serviceTypeIDTextBox.Text == "-1"
|| this.serviceTypeIDTextBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Please select a Record First!", 0);
return;
}
Global.mnFrm.cmCde.showRecHstry(
Global.get_Rec_Hstry(int.Parse(this.serviceTypeIDTextBox.Text)), 6);
}
private void positionDtTextBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Up)
{
this.DtPnlNavButtons(this.movePreviousDtButton, ex);
}
else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Down)
{
this.DtPnlNavButtons(this.moveNextDtButton, ex);
}
}
private void dsplySizeDtComboBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.loadDtPanel();
}
}
private void resetButton_Click(object sender, EventArgs e)
{
Global.mnFrm.cmCde.minimizeMemory();
this.searchInComboBox.SelectedIndex = 1;
this.searchForTextBox.Text = "%";
this.searchInDtComboBox.SelectedIndex = 2;
this.searchForDtTextBox.Text = "%";
this.dsplySizeComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
this.dsplySizeDtComboBox.Text = Global.mnFrm.cmCde.get_CurPlcy_Mx_Dsply_Recs().ToString();
this.rec_cur_indx = 0;
this.ldt_cur_indx = 0;
this.loadPanel();
}
private void addButton_Click(object sender, EventArgs e)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.editButton.Text == "STOP")
{
this.editButton.PerformClick();
}
//this.editGBVButton.Enabled = false;
this.clearDtInfo();
this.dataDefDataGridView.Rows.Clear();
this.addRec = true;
this.editRec = false;
this.prpareForDtEdit();
ToolStripButton mybtn = (ToolStripButton)sender;
this.changeGridVw();
this.prpareForLnsEdit();
this.serviceNameTextBox.Focus();
this.editButton.Enabled = false;
this.addButton.Enabled = false;
this.addDtButton.PerformClick();
//this.addPriceButton.PerformClick();
}
private void editButton_Click(object sender, EventArgs e)
{
if (this.editButton.Text == "EDIT")
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[8]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.serviceTypeIDTextBox.Text == "" || this.serviceTypeIDTextBox.Text == "-1")
{
Global.mnFrm.cmCde.showMsg("No record to Edit!", 0);
return;
}
this.addRec = false;
this.editRec = true;
this.prpareForDtEdit();
this.prpareForLnsEdit();
//this.addGBVButton.Enabled = false;
this.editButton.Text = "STOP";
this.serviceNameTextBox.Focus();
//this.editMenuItem.Text = "STOP EDITING";
}
else
{
this.saveButton.Enabled = false;
this.addRec = false;
this.editRec = false;
this.addButton.Enabled = this.addRecs;
this.editButton.Enabled = this.editRecs;
this.addDtButton.Enabled = this.editRecs;
this.delDtButton.Enabled = this.editRecs;
this.editButton.Text = "EDIT";
//this.editMenuItem.Text = "Edit Item";
this.disableDtEdit();
this.disableLnsEdit();
System.Windows.Forms.Application.DoEvents();
//this.loadPanel();
}
System.Windows.Forms.Application.DoEvents();
}
private void delButton_Click(object sender, EventArgs e)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[9]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
if (this.serviceTypeIDTextBox.Text == "" || this.serviceTypeIDTextBox.Text == "-1")
{
Global.mnFrm.cmCde.showMsg("Please select the Record to DELETE!", 0);
return;
}
if (Global.isSrvsTypInUse(int.Parse(this.serviceTypeIDTextBox.Text)) == true)
{
Global.mnFrm.cmCde.showMsg("This Service Type is in Use!", 0);
return;
}
if (Global.mnFrm.cmCde.showMsg("Are you sure you want to DELETE the selected Record?" +
"\r\nThis action cannot be undone!", 1) == DialogResult.No)
{
//Global.mnFrm.cmCde.showMsg("Operation Cancelled!", 4);
return;
}
Global.deleteSrvsTyp(int.Parse(this.serviceTypeIDTextBox.Text), this.serviceNameTextBox.Text);
this.loadPanel();
}
private void delDtButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
if (this.dataDefDataGridView.CurrentCell != null
&& this.dataDefDataGridView.SelectedRows.Count <= 0)
{
this.dataDefDataGridView.Rows[this.dataDefDataGridView.CurrentCell.RowIndex].Selected = true;
}
if (this.dataDefDataGridView.SelectedRows.Count <= 0)
{
Global.mnFrm.cmCde.showMsg("Please select the Record(s) to Delete!", 0);
return;
}
if (Global.mnFrm.cmCde.showMsg("Are you sure you want to DELETE the selected Line?" +
"\r\nThis action cannot be undone!", 1) == DialogResult.No)
{
//Global.mnFrm.cmCde.showMsg("Operation Cancelled!", 4);
return;
}
int cnt = this.dataDefDataGridView.SelectedRows.Count;
for (int i = 0; i < cnt; i++)
{
if (this.dataDefDataGridView.SelectedRows[0].Cells[2].Value == null)
{
this.dataDefDataGridView.SelectedRows[0].Cells[2].Value = string.Empty;
}
long lnID = -1;
long.TryParse(this.dataDefDataGridView.SelectedRows[0].Cells[9].Value.ToString(), out lnID);
if (lnID > 0)
{
if (Global.isSrvcDataCaptureInUse(lnID))
{
Global.mnFrm.cmCde.showMsg("The Record at Row(" + (i + 1) + ") has been Used hence cannot be Deleted!", 0);
continue;
}
Global.deleteSrvsTypLn(lnID, this.dataDefDataGridView.SelectedRows[0].Cells[2].Value.ToString());
}
this.dataDefDataGridView.Rows.RemoveAt(this.dataDefDataGridView.SelectedRows[0].Index);
}
//this.loadDtPanel();
}
private void salesItemTextBox_TextChanged(object sender, EventArgs e)
{
if (!this.obey_evnts)
{
return;
}
this.txtChngd = true;
}
private void salesItemTextBox_Leave(object sender, EventArgs e)
{
if (this.txtChngd == false)
{
return;
}
this.txtChngd = false;
TextBox mytxt = (TextBox)sender;
this.obey_evnts = false;
this.srchWrd = mytxt.Text;
if (!mytxt.Text.Contains("%"))
{
this.srchWrd = "%" + this.srchWrd.Replace(" ", "%") + "%";
}
if (mytxt.Name == "salesItemTextBox")
{
this.salesItemTextBox.Text = "";
this.salesItemIDTextBox.Text = "-1";
this.salesItemButton_Click(this.salesItemButton, e);
}
this.srchWrd = "%";
this.obey_evnts = true;
this.txtChngd = false;
}
private void salesItemButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
string[] selVals = new string[1];
selVals[0] = this.salesItemIDTextBox.Text;
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Inventory Items"), ref selVals,
true, false, Global.mnFrm.cmCde.Org_id,
this.srchWrd, "Both", true);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.salesItemIDTextBox.Text = selVals[i];
this.salesItemTextBox.Text = Global.get_InvItemNm
(int.Parse(selVals[i]));
this.priceLabel.Text = Global.get_InvItemPrice(int.Parse(selVals[i])).ToString("#,##0.00");
}
}
}
private void saveButton_Click(object sender, EventArgs e)
{
if (this.addRec == true)
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[10]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
}
else
{
if (Global.mnFrm.cmCde.test_prmssns(Global.dfltPrvldgs[11]) == false)
{
Global.mnFrm.cmCde.showMsg("You don't have permission to perform" +
" this action!\nContact your System Administrator!", 0);
return;
}
}
if (this.serviceNameTextBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Please enter a Service Name!", 0);
return;
}
long oldRecID = Global.getSrvsTypID(this.serviceNameTextBox.Text,
Global.mnFrm.cmCde.Org_id);
if (oldRecID > 0
&& this.addRec == true)
{
Global.mnFrm.cmCde.showMsg("Service Name is already in use in this Organisation!", 0);
return;
}
if (oldRecID > 0
&& this.editRec == true
&& oldRecID.ToString() !=
this.serviceTypeIDTextBox.Text)
{
Global.mnFrm.cmCde.showMsg("New Service Name is already in use in this Organisation!", 0);
return;
}
if (this.srvcTypeComboBox.Text == "")
{
Global.mnFrm.cmCde.showMsg("Type of Service cannot be empty!", 0);
return;
}
if (this.addRec == true)
{
Global.createSrvsTyp(this.serviceNameTextBox.Text,
this.servTypeDescTextBox.Text, int.Parse(this.salesItemIDTextBox.Text),
this.isEnabledCheckBox.Checked, this.srvcTypeComboBox.Text,
Global.mnFrm.cmCde.Org_id);
//this.saveGBVButton.Enabled = false;
//this.addgbv = false;
//this.editgbv = true;
this.editButton.Enabled = this.editRecs;
this.addButton.Enabled = this.addRecs;
//Global.mnFrm.cmCde.showMsg("Record Saved!", 3);
System.Windows.Forms.Application.DoEvents();
this.serviceTypeIDTextBox.Text = Global.getSrvsTypID(this.serviceNameTextBox.Text,
Global.mnFrm.cmCde.Org_id).ToString();
this.someLinesFailed = false;
this.saveGridView(int.Parse(this.serviceTypeIDTextBox.Text));
if (this.someLinesFailed == false)
{
this.loadPanel();
}
else
{
this.editRec = true;
this.addRec = false;
this.saveButton.Enabled = true;
}
this.someLinesFailed = false;
}
else if (this.editRec == true)
{
Global.updateSrvsTyp(int.Parse(this.serviceTypeIDTextBox.Text), this.serviceNameTextBox.Text,
this.servTypeDescTextBox.Text, int.Parse(this.salesItemIDTextBox.Text),
this.isEnabledCheckBox.Checked, this.srvcTypeComboBox.Text);
this.someLinesFailed = false;
this.saveGridView(int.Parse(this.serviceTypeIDTextBox.Text));
if (this.someLinesFailed == false)
{
//this.loadPanel();
if (this.srvcsOffrdListView.SelectedItems.Count > 0)
{
this.srvcsOffrdListView.SelectedItems[0].SubItems[1].Text = this.serviceNameTextBox.Text;
}
}
else
{
this.editRec = true;
this.saveButton.Enabled = true;
}
this.someLinesFailed = false;
// Global.mnFrm.cmCde.showMsg("Record Saved!", 3);
}
}
private bool checkDtRqrmnts(int rwIdx)
{
this.dfltFill(rwIdx);
if (this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value.ToString() == "")
{
return false;
}
int dataDefID = int.Parse(this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value.ToString());
string dataCtgry = this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value.ToString();
string dataLabel = this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value.ToString();
if (dataCtgry == "")
{
Global.mnFrm.cmCde.showMsg("Data Category cannot be Empty!", 0);
return false;
}
if (dataLabel == "")
{
Global.mnFrm.cmCde.showMsg("Data Label cannot be Empty!", 0);
return false;
}
long oldDataDefID = Global.getSrvcsDataDefID(dataLabel, dataCtgry, int.Parse(this.serviceTypeIDTextBox.Text));
if (oldDataDefID > 0
&& dataDefID <= 0)
{
Global.mnFrm.cmCde.showMsg("Data Definition Category & Label Combination is already Defined in this Service!", 0);
return false;
}
if (oldDataDefID > 0
&& dataDefID > 0
&& oldDataDefID != dataDefID)
{
Global.mnFrm.cmCde.showMsg("New Data Definition Category & Label Combination is already Defined in this Service!", 0);
return false;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value.ToString() == "")
{
Global.mnFrm.cmCde.showMsg("Data Label cannot be Empty!", 0);
return false;
}
return true;
}
private void saveGridView(int srvcTypHdrID)
{
int svd = 0;
if (this.dataDefDataGridView.Rows.Count > 0)
{
this.dataDefDataGridView.EndEdit();
//this.itemsDataGridView.Rows[0].Cells[1].Selected = true;
System.Windows.Forms.Application.DoEvents();
}
for (int i = 0; i < this.dataDefDataGridView.Rows.Count; i++)
{
if (!this.checkDtRqrmnts(i))
{
this.dataDefDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(255, 100, 100);
this.someLinesFailed = true;
continue;
}
else
{
//Check if Doc Ln Rec Exists
//Create if not else update
int hdrID = int.Parse(this.serviceTypeIDTextBox.Text);
long dataDefID = int.Parse(this.dataDefDataGridView.Rows[i].Cells[9].Value.ToString());
string dataCtgry = this.dataDefDataGridView.Rows[i].Cells[0].Value.ToString();
string dataLabel = this.dataDefDataGridView.Rows[i].Cells[2].Value.ToString();
string dataType = this.dataDefDataGridView.Rows[i].Cells[3].Value.ToString();
string dataValLov = this.dataDefDataGridView.Rows[i].Cells[4].Value.ToString();
string dataValLovDesc = this.dataDefDataGridView.Rows[i].Cells[6].Value.ToString();
bool enbld = (bool)this.dataDefDataGridView.Rows[i].Cells[8].Value;
if (dataDefID <= 0)
{
dataDefID = Global.getNewDataDefID();
Global.createDataDefntn(hdrID, dataCtgry, dataLabel, enbld, dataType, dataValLov, dataValLovDesc);
this.dataDefDataGridView.Rows[i].Cells[9].Value = dataDefID;
}
else
{
Global.updateDataDefntn(dataDefID, dataCtgry, dataLabel, enbld, dataType, dataValLov, dataValLovDesc);
}
svd++;
this.dataDefDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.Lime;
}
}
this.dataDefDataGridView.EndEdit();
Global.mnFrm.cmCde.showMsg(svd + " Line(s) Saved Successfully!", 3);
}
private void dfltFill(int rwIdx)
{
if (this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[0].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[2].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[3].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[4].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[4].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[6].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[6].Value = string.Empty;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[8].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[8].Value = false;
}
if (this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value == null)
{
this.dataDefDataGridView.Rows[rwIdx].Cells[9].Value = "-1";
}
}
private void isEnabledCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (this.shdObeyEvts() == false || beenToCheckBx == true)
{
beenToCheckBx = false;
return;
}
beenToCheckBx = true;
if (this.addRec == false && this.editRec == false)
{
this.isEnabledCheckBox.Checked = !this.isEnabledCheckBox.Checked;
}
}
private void addDtButton_Click(object sender, EventArgs e)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
return;
}
this.createDtRows(1);
this.prpareForLnsEdit();
}
private void changeGridVw()
{
/*
* Room/Hall
Field/Yard
Restaurant Table
Gym/Sport Subscription,
Rental Item
*/
}
public void createDtRows(int num)
{
this.dataDefDataGridView.DefaultCellStyle.ForeColor = Color.Black;
this.obey_ldt_evnts = false;
for (int i = 0; i < num; i++)
{
this.dataDefDataGridView.Rows.Insert(0, 1);
int rowIdx = 0;// this.dataDefDataGridView.RowCount - 1;
this.dataDefDataGridView.Rows[rowIdx].Cells[0].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[1].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[2].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[3].Value = "TEXT";
this.dataDefDataGridView.Rows[rowIdx].Cells[4].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[5].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[6].Value = "";
this.dataDefDataGridView.Rows[rowIdx].Cells[7].Value = "...";
this.dataDefDataGridView.Rows[rowIdx].Cells[8].Value = false;
this.dataDefDataGridView.Rows[rowIdx].Cells[9].Value = "-1";
}
this.obey_ldt_evnts = true;
}
private void serviceTypesForm_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.Control && e.KeyCode == Keys.S)
{
if (this.saveButton.Enabled == true)
{
this.saveButton_Click(this.saveButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.N)
{
if (this.addButton.Enabled == true)
{
this.addButton_Click(this.addButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.E)
{
if (this.editButton.Enabled == true)
{
this.editButton_Click(this.editButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.R)
{
this.resetButton.PerformClick();
}
else if ((e.Control && e.KeyCode == Keys.F) || e.KeyCode == Keys.F5)
{
if (this.goButton.Enabled == true)
{
this.goButton_Click(this.goButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else if (e.Control && e.KeyCode == Keys.Delete)
{
if (this.delButton.Enabled == true)
{
this.delButton_Click(this.delButton, ex);
}
e.Handled = true;
e.SuppressKeyPress = true;
}
else
{
e.Handled = false;
e.SuppressKeyPress = false;
if (this.serviceNameTextBox.Focused)
{
//Global.mnFrm.cmCde.listViewKeyDown(this.serviceNameTextBox.Text, e);
}
}
}
private void searchForTextBox_Click(object sender, EventArgs e)
{
this.searchForTextBox.SelectAll();
}
private void srvcTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
this.changeGridVw();
}
private void dataDefDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e == null || this.obey_ldt_evnts == false)
{
return;
}
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
bool prv = this.obey_ldt_evnts;
this.obey_ldt_evnts = false;
this.dfltFill(e.RowIndex);
if (e.ColumnIndex == 1
|| e.ColumnIndex == 5
|| e.ColumnIndex == 7)
{
if (this.addRec == false && this.editRec == false)
{
Global.mnFrm.cmCde.showMsg("Must be in ADD/EDIT mode First!", 0);
this.obey_ldt_evnts = true;
return;
}
}
if (e.ColumnIndex == 1)
{
int[] selVals = new int[1];
selVals[0] = Global.mnFrm.cmCde.getPssblValID(
this.dataDefDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString(),
Global.mnFrm.cmCde.getLovID("Appointment Data Capture Category"));
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Appointment Data Capture Category"), ref selVals,
true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[0].Value = Global.mnFrm.cmCde.getPssblValNm(
selVals[i]);
}
this.obey_ldt_evnts = true;
}
}
else if (e.ColumnIndex == 5)
{
//LOV Names
string[] selVals = new string[1];
selVals[0] = Global.mnFrm.cmCde.getLovID(this.dataDefDataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()).ToString();
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Non-Dynamic LOV Names"), ref selVals, true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[4].Value = Global.mnFrm.cmCde.getLovNm(int.Parse(selVals[i]));
}
}
}
else if (e.ColumnIndex == 7)
{
//LOV Names
string[] selVals = new string[1];
selVals[0] = Global.mnFrm.cmCde.getLovID(this.dataDefDataGridView.Rows[e.RowIndex].Cells[6].Value.ToString()).ToString();
DialogResult dgRes = Global.mnFrm.cmCde.showPssblValDiag(
Global.mnFrm.cmCde.getLovID("Non-Dynamic LOV Names"), ref selVals, true, false,
this.srchWrd, "Both", this.autoLoad);
if (dgRes == DialogResult.OK)
{
for (int i = 0; i < selVals.Length; i++)
{
this.dataDefDataGridView.Rows[e.RowIndex].Cells[6].Value = Global.mnFrm.cmCde.getLovNm(int.Parse(selVals[i]));
}
}
}
this.obey_ldt_evnts = true;
}
private void dataDefDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e == null || this.obey_ldt_evnts == false)
{
return;
}
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
this.dfltFill(e.RowIndex);
bool prv = this.obey_ldt_evnts;
this.obey_ldt_evnts = false;
if (e.ColumnIndex == 0)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(1, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
else if (e.ColumnIndex == 4)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(5, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
else if (e.ColumnIndex == 6)
{
this.autoLoad = true;
DataGridViewCellEventArgs e1 = new DataGridViewCellEventArgs(7, e.RowIndex);
this.obey_ldt_evnts = true;
this.dataDefDataGridView_CellContentClick(this.dataDefDataGridView, e1);
this.autoLoad = false;
}
this.obey_ldt_evnts = true;
}
private void rfrshDtButton_Click(object sender, EventArgs e)
{
this.loadDtPanel();
}
private void searchForDtTextBox_KeyDown(object sender, KeyEventArgs e)
{
EventArgs ex = new EventArgs();
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
this.rfrshDtButton.PerformClick();
}
}
}
}
| Java |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Events</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="EventDetail">
<h3>Christening</h3>
<table class="infolist eventlist">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnGRAMPSID">E2683</td>
</tr>
<tr>
<td class="ColumnAttribute">Date</td>
<td class="ColumnColumnDate">
1692-06-22
</td>
</tr>
<tr>
<td class="ColumnAttribute">Place</td>
<td class="ColumnColumnPlace">
<a href="../../../plc/d/c/d15f5fbf06e36c82f6fe416cacd.html" title="">
</a>
</td>
</tr>
</tbody>
</table>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/0/0/d15f5fd909a134ee791a002d00.html">
CUTCLIFFE, Mary
<span class="grampsid"> [I2492]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:10<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::geomDecomp
Description
Geometrical domain decomposition
SourceFiles
geomDecomp.C
\*---------------------------------------------------------------------------*/
#ifndef geomDecomp_H
#define geomDecomp_H
#include "OpenFOAM-2.1.x/src/parallel/decompose/decompositionMethods/decompositionMethod/decompositionMethod.H"
#include "OpenFOAM-2.1.x/src/OpenFOAM/primitives/Vector/Vector.H"
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class geomDecomp Declaration
\*---------------------------------------------------------------------------*/
class geomDecomp
:
public decompositionMethod
{
protected:
// Protected data
const dictionary& geomDecomDict_;
Vector<label> n_;
scalar delta_;
tensor rotDelta_;
public:
// Constructors
//- Construct given the decomposition dictionary
// and the derived type name
geomDecomp
(
const dictionary& decompositionDict,
const word& derivedType
);
//- Return for every coordinate the wanted processor number.
virtual labelList decompose
(
const pointField& points,
const scalarField& pointWeights
) = 0;
//- Like decompose but with uniform weights on the points
virtual labelList decompose(const pointField&) = 0;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_33) on Fri Aug 03 11:43:00 PDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.hp.hpl.jena.sparql.ARQConstants (Apache Jena ARQ)
</TITLE>
<META NAME="date" CONTENT="2012-08-03">
<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 com.hp.hpl.jena.sparql.ARQConstants (Apache Jena ARQ)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/hp/hpl/jena/sparql/ARQConstants.html" title="class in com.hp.hpl.jena.sparql"><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-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/hp/hpl/jena/sparql//class-useARQConstants.html" target="_top"><B>FRAMES</B></A>
<A HREF="ARQConstants.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.hp.hpl.jena.sparql.ARQConstants</B></H2>
</CENTER>
No usage of com.hp.hpl.jena.sparql.ARQConstants
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/hp/hpl/jena/sparql/ARQConstants.html" title="class in com.hp.hpl.jena.sparql"><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-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/hp/hpl/jena/sparql//class-useARQConstants.html" target="_top"><B>FRAMES</B></A>
<A HREF="ARQConstants.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Licenced under the Apache License, Version 2.0
</BODY>
</HTML>
| Java |
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "base58.h"
#include "clientversion.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "core_io.h"
#include "keystore.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include <univalue.h>
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
static bool fCreateBlank;
static std::map<std::string,UniValue> registers;
static const int CONTINUE_EXECUTION=-1;
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRawTx(int argc, char* argv[])
{
//
// Parameters
//
gArgs.ParseParameters(argc, argv);
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
try {
SelectParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
fCreateBlank = gArgs.GetBoolArg("-create", false);
if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help"))
{
// First part of help message is specific to this utility
std::string strUsage = strprintf(_("%s berycoin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" berycoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded berycoin transaction") + "\n" +
" berycoin-tx [options] -create [commands] " + _("Create hex-encoded berycoin transaction") + "\n" +
"\n";
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-create", _("Create new, empty TX."));
strUsage += HelpMessageOpt("-json", _("Select JSON output"));
strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
AppendParamsHelpMessages(strUsage);
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Commands:"));
strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX"));
strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX"));
strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N"));
strUsage += HelpMessageOpt("replaceable(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
_("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
_("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
_("This command requires JSON registers:") +
_("prevtxs=JSON object") + ", " +
_("privatekeys=JSON object") + ". " +
_("See signrawtransaction docs for format of sighash flags, JSON objects."));
fprintf(stdout, "%s", strUsage.c_str());
strUsage = HelpMessageGroup(_("Register Commands:"));
strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
return CONTINUE_EXECUTION;
}
static void RegisterSetJson(const std::string& key, const std::string& rawJson)
{
UniValue val;
if (!val.read(rawJson)) {
std::string strErr = "Cannot parse JSON for key " + key;
throw std::runtime_error(strErr);
}
registers[key] = val;
}
static void RegisterSet(const std::string& strInput)
{
// separate NAME:VALUE in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register input requires NAME:VALUE");
std::string key = strInput.substr(0, pos);
std::string valStr = strInput.substr(pos + 1, std::string::npos);
RegisterSetJson(key, valStr);
}
static void RegisterLoad(const std::string& strInput)
{
// separate NAME:FILENAME in string
size_t pos = strInput.find(':');
if ((pos == std::string::npos) ||
(pos == 0) ||
(pos == (strInput.size() - 1)))
throw std::runtime_error("Register load requires NAME:FILENAME");
std::string key = strInput.substr(0, pos);
std::string filename = strInput.substr(pos + 1, std::string::npos);
FILE *f = fopen(filename.c_str(), "r");
if (!f) {
std::string strErr = "Cannot open file " + filename;
throw std::runtime_error(strErr);
}
// load file chunks into one big buffer
std::string valStr;
while ((!feof(f)) && (!ferror(f))) {
char buf[4096];
int bread = fread(buf, 1, sizeof(buf), f);
if (bread <= 0)
break;
valStr.insert(valStr.size(), buf, bread);
}
int error = ferror(f);
fclose(f);
if (error) {
std::string strErr = "Error reading file " + filename;
throw std::runtime_error(strErr);
}
// evaluate as JSON buffer register
RegisterSetJson(key, valStr);
}
static CAmount ExtractAndValidateValue(const std::string& strValue)
{
CAmount value;
if (!ParseMoney(strValue, value))
throw std::runtime_error("invalid TX output value");
return value;
}
static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newVersion = atoi64(cmdVal);
if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION)
throw std::runtime_error("Invalid TX version requested");
tx.nVersion = (int) newVersion;
}
static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal)
{
int64_t newLocktime = atoi64(cmdVal);
if (newLocktime < 0LL || newLocktime > 0xffffffffLL)
throw std::runtime_error("Invalid TX locktime requested");
tx.nLockTime = (unsigned int) newLocktime;
}
static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
throw std::runtime_error("Invalid TX input index '" + strInIdx + "'");
}
// set the nSequence to MAX_INT - 2 (= RBF opt in flag)
int cnt = 0;
for (CTxIn& txin : tx.vin) {
if (strInIdx == "" || cnt == inIdx) {
if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) {
txin.nSequence = MAX_BIP125_RBF_SEQUENCE;
}
}
++cnt;
}
}
static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput)
{
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// separate TXID:VOUT in string
if (vStrInputParts.size()<2)
throw std::runtime_error("TX input missing separator");
// extract and validate TXID
std::string strTxid = vStrInputParts[0];
if ((strTxid.size() != 64) || !IsHex(strTxid))
throw std::runtime_error("invalid TX input txid");
uint256 txid(uint256S(strTxid));
static const unsigned int minTxOutSz = 9;
static const unsigned int maxVout = dgpMaxBlockSize / minTxOutSz;
// extract and validate vout
std::string strVout = vStrInputParts[1];
int vout = atoi(strVout);
if ((vout < 0) || (vout > (int)maxVout))
throw std::runtime_error("invalid TX input vout");
// extract the optional sequence number
uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max();
if (vStrInputParts.size() > 2)
nSequenceIn = std::stoul(vStrInputParts[2]);
// append to transaction input list
CTxIn txin(txid, vout, CScript(), nSequenceIn);
tx.vin.push_back(txin);
}
static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:ADDRESS
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() != 2)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate ADDRESS
std::string strAddr = vStrInputParts[1];
CBitcoinAddress addr(strAddr);
if (!addr.IsValid())
throw std::runtime_error("invalid TX output address");
// build standard output script via GetScriptForDestination()
CScript scriptPubKey = GetScriptForDestination(addr.Get());
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:PUBKEY[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
throw std::runtime_error("TX output missing or too many separators");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract and validate PUBKEY
CPubKey pubkey(ParseHex(vStrInputParts[1]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
CScript scriptPubKey = GetScriptForRawPubKey(pubkey);
// Extract and validate FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts[2];
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (bSegWit) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress redeemScriptAddr(scriptPubKey);
scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput)
{
// Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
// Check that there are enough parameters
if (vStrInputParts.size()<3)
throw std::runtime_error("Not enough multisig parameters");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// Extract REQUIRED
uint32_t required = stoul(vStrInputParts[1]);
// Extract NUMKEYS
uint32_t numkeys = stoul(vStrInputParts[2]);
// Validate there are the correct number of pubkeys
if (vStrInputParts.size() < numkeys + 3)
throw std::runtime_error("incorrect number of multisig pubkeys");
if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required)
throw std::runtime_error("multisig parameter mismatch. Required " \
+ std::to_string(required) + " of " + std::to_string(numkeys) + "signatures.");
// extract and validate PUBKEYs
std::vector<CPubKey> pubkeys;
for(int pos = 1; pos <= int(numkeys); pos++) {
CPubKey pubkey(ParseHex(vStrInputParts[pos + 2]));
if (!pubkey.IsFullyValid())
throw std::runtime_error("invalid TX output pubkey");
pubkeys.push_back(pubkey);
}
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == numkeys + 4) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
else if (vStrInputParts.size() > numkeys + 4) {
// Validate that there were no more parameters passed
throw std::runtime_error("Too many parameters");
}
CScript scriptPubKey = GetScriptForMultisig(required, pubkeys);
if (bSegWit) {
for (CPubKey& pubkey : pubkeys) {
if (!pubkey.IsCompressed()) {
throw std::runtime_error("Uncompressed pubkeys are not useable for SegWit outputs");
}
}
// Call GetScriptForWitness() to build a P2WSH scriptPubKey
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
// Get the address for the redeem script, then call
// GetScriptForDestination() to construct a P2SH scriptPubKey.
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput)
{
CAmount value = 0;
// separate [VALUE:]DATA in string
size_t pos = strInput.find(':');
if (pos==0)
throw std::runtime_error("TX output value not specified");
if (pos != std::string::npos) {
// Extract and validate VALUE
value = ExtractAndValidateValue(strInput.substr(0, pos));
}
// extract and validate DATA
std::string strData = strInput.substr(pos + 1, std::string::npos);
if (!IsHex(strData))
throw std::runtime_error("invalid TX output data");
std::vector<unsigned char> data = ParseHex(strData);
CTxOut txout(value, CScript() << OP_RETURN << data);
tx.vout.push_back(txout);
}
static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput)
{
// separate VALUE:SCRIPT[:FLAGS]
std::vector<std::string> vStrInputParts;
boost::split(vStrInputParts, strInput, boost::is_any_of(":"));
if (vStrInputParts.size() < 2)
throw std::runtime_error("TX output missing separator");
// Extract and validate VALUE
CAmount value = ExtractAndValidateValue(vStrInputParts[0]);
// extract and validate script
std::string strScript = vStrInputParts[1];
CScript scriptPubKey = ParseScript(strScript);
// Extract FLAGS
bool bSegWit = false;
bool bScriptHash = false;
if (vStrInputParts.size() == 3) {
std::string flags = vStrInputParts.back();
bSegWit = (flags.find("W") != std::string::npos);
bScriptHash = (flags.find("S") != std::string::npos);
}
if (scriptPubKey.size() > MAX_SCRIPT_SIZE) {
throw std::runtime_error(strprintf(
"script exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_SIZE));
}
if (bSegWit) {
scriptPubKey = GetScriptForWitness(scriptPubKey);
}
if (bScriptHash) {
if (scriptPubKey.size() > MAX_SCRIPT_ELEMENT_SIZE) {
throw std::runtime_error(strprintf(
"redeemScript exceeds size limit: %d > %d", scriptPubKey.size(), MAX_SCRIPT_ELEMENT_SIZE));
}
CBitcoinAddress addr(scriptPubKey);
scriptPubKey = GetScriptForDestination(addr.Get());
}
// construct TxOut, append to transaction output list
CTxOut txout(value, scriptPubKey);
tx.vout.push_back(txout);
}
static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx)
{
// parse requested deletion index
int inIdx = atoi(strInIdx);
if (inIdx < 0 || inIdx >= (int)tx.vin.size()) {
std::string strErr = "Invalid TX input index '" + strInIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete input from transaction
tx.vin.erase(tx.vin.begin() + inIdx);
}
static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx)
{
// parse requested deletion index
int outIdx = atoi(strOutIdx);
if (outIdx < 0 || outIdx >= (int)tx.vout.size()) {
std::string strErr = "Invalid TX output index '" + strOutIdx + "'";
throw std::runtime_error(strErr.c_str());
}
// delete output from transaction
tx.vout.erase(tx.vout.begin() + outIdx);
}
static const unsigned int N_SIGHASH_OPTS = 6;
static const struct {
const char *flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
{"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
{"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
{"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY},
};
static bool findSighashFlags(int& flags, const std::string& flagStr)
{
flags = 0;
for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) {
if (flagStr == sighashOptions[i].flagStr) {
flags = sighashOptions[i].flags;
return true;
}
}
return false;
}
static CAmount AmountFromValue(const UniValue& value)
{
if (!value.isNum() && !value.isStr())
throw std::runtime_error("Amount is not a number or string");
CAmount amount;
if (!ParseFixedPoint(value.getValStr(), 8, &amount))
throw std::runtime_error("Invalid amount");
if (!MoneyRange(amount))
throw std::runtime_error("Amount out of range");
return amount;
}
static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
{
int nHashType = SIGHASH_ALL;
if (flagStr.size() > 0)
if (!findSighashFlags(nHashType, flagStr))
throw std::runtime_error("unknown sighash flag/sign option");
std::vector<CTransaction> txVariants;
txVariants.push_back(tx);
// mergedTx will end up with all the signatures; it
// starts as a clone of the raw tx:
CMutableTransaction mergedTx(txVariants[0]);
bool fComplete = true;
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
if (!registers.count("privatekeys"))
throw std::runtime_error("privatekeys register variable must be set.");
CBasicKeyStore tempKeystore;
UniValue keysObj = registers["privatekeys"];
for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) {
if (!keysObj[kidx].isStr())
throw std::runtime_error("privatekey not a std::string");
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(keysObj[kidx].getValStr());
if (!fGood)
throw std::runtime_error("privatekey not valid");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
// Add previous txouts given in the RPC call:
if (!registers.count("prevtxs"))
throw std::runtime_error("prevtxs register variable must be set.");
UniValue prevtxsObj = registers["prevtxs"];
{
for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) {
UniValue prevOut = prevtxsObj[previdx];
if (!prevOut.isObject())
throw std::runtime_error("expected prevtxs internal object");
std::map<std::string, UniValue::VType> types = {
{"txid", UniValue::VSTR},
{"vout", UniValue::VNUM},
{"scriptPubKey", UniValue::VSTR},
};
if (!prevOut.checkObject(types))
throw std::runtime_error("prevtxs internal object typecheck fail");
uint256 txid = ParseHashUV(prevOut["txid"], "txid");
int nOut = atoi(prevOut["vout"].getValStr());
if (nOut < 0)
throw std::runtime_error("vout must be positive");
COutPoint out(txid, nOut);
std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
std::string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw std::runtime_error(err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
if (prevOut.exists("amount")) {
newcoin.out.nValue = AmountFromValue(prevOut["amount"]);
}
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// if redeemScript given and private keys given,
// add redeemScript to the tempKeystore so it can be signed:
if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
prevOut.exists("redeemScript")) {
UniValue v = prevOut["redeemScript"];
std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
const CKeyStore& keystore = tempKeystore;
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
fComplete = false;
continue;
}
const CScript& prevPubKey = coin.out.scriptPubKey;
const CAmount& amount = coin.out.nValue;
SignatureData sigdata;
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata);
// ... and merge in other signatures:
for (const CTransaction& txv : txVariants)
sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i));
UpdateTransaction(mergedTx, i, sigdata);
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount)))
fComplete = false;
}
if (fComplete) {
// do nothing... for now
// perhaps store this for later optional JSON output
}
tx = mergedTx;
}
class Secp256k1Init
{
ECCVerifyHandle globalVerifyHandle;
public:
Secp256k1Init() {
ECC_Start();
}
~Secp256k1Init() {
ECC_Stop();
}
};
static void MutateTx(CMutableTransaction& tx, const std::string& command,
const std::string& commandVal)
{
std::unique_ptr<Secp256k1Init> ecc;
if (command == "nversion")
MutateTxVersion(tx, commandVal);
else if (command == "locktime")
MutateTxLocktime(tx, commandVal);
else if (command == "replaceable") {
MutateTxRBFOptIn(tx, commandVal);
}
else if (command == "delin")
MutateTxDelInput(tx, commandVal);
else if (command == "in")
MutateTxAddInput(tx, commandVal);
else if (command == "delout")
MutateTxDelOutput(tx, commandVal);
else if (command == "outaddr")
MutateTxAddOutAddr(tx, commandVal);
else if (command == "outpubkey") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutPubKey(tx, commandVal);
} else if (command == "outmultisig") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxAddOutMultiSig(tx, commandVal);
} else if (command == "outscript")
MutateTxAddOutScript(tx, commandVal);
else if (command == "outdata")
MutateTxAddOutData(tx, commandVal);
else if (command == "sign") {
if (!ecc) { ecc.reset(new Secp256k1Init()); }
MutateTxSign(tx, commandVal);
}
else if (command == "load")
RegisterLoad(commandVal);
else if (command == "set")
RegisterSet(commandVal);
else
throw std::runtime_error("unknown command");
}
static void OutputTxJSON(const CTransaction& tx)
{
UniValue entry(UniValue::VOBJ);
TxToUniv(tx, uint256(), entry);
std::string jsonOutput = entry.write(4);
fprintf(stdout, "%s\n", jsonOutput.c_str());
}
static void OutputTxHash(const CTransaction& tx)
{
std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
fprintf(stdout, "%s\n", strHexHash.c_str());
}
static void OutputTxHex(const CTransaction& tx)
{
std::string strHex = EncodeHexTx(tx);
fprintf(stdout, "%s\n", strHex.c_str());
}
static void OutputTx(const CTransaction& tx)
{
if (gArgs.GetBoolArg("-json", false))
OutputTxJSON(tx);
else if (gArgs.GetBoolArg("-txid", false))
OutputTxHash(tx);
else
OutputTxHex(tx);
}
static std::string readStdin()
{
char buf[4096];
std::string ret;
while (!feof(stdin)) {
size_t bread = fread(buf, 1, sizeof(buf), stdin);
ret.append(buf, bread);
if (bread < sizeof(buf))
break;
}
if (ferror(stdin))
throw std::runtime_error("error reading stdin");
boost::algorithm::trim_right(ret);
return ret;
}
static int CommandLineRawTx(int argc, char* argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches; Permit common stdin convention "-"
while (argc > 1 && IsSwitchChar(argv[1][0]) &&
(argv[1][1] != 0)) {
argc--;
argv++;
}
CMutableTransaction tx;
int startArg;
if (!fCreateBlank) {
// require at least one param
if (argc < 2)
throw std::runtime_error("too few parameters");
// param: hex-encoded bitcoin transaction
std::string strHexTx(argv[1]);
if (strHexTx == "-") // "-" implies standard input
strHexTx = readStdin();
if (!DecodeHexTx(tx, strHexTx, true))
throw std::runtime_error("invalid transaction encoding");
startArg = 2;
} else
startArg = 1;
for (int i = startArg; i < argc; i++) {
std::string arg = argv[i];
std::string key, value;
size_t eqpos = arg.find('=');
if (eqpos == std::string::npos)
key = arg;
else {
key = arg.substr(0, eqpos);
value = arg.substr(eqpos + 1);
}
MutateTx(tx, key, value);
}
OutputTx(tx);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try {
int ret = AppInitRawTx(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRawTx()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "AppInitRawTx()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRawTx(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRawTx()");
} catch (...) {
PrintExceptionContinue(nullptr, "CommandLineRawTx()");
}
return ret;
}
| Java |
package net.minecraft.src;
public class BlockJukeBox extends BlockContainer
{
protected BlockJukeBox(int par1)
{
super(par1, Material.wood);
this.setCreativeTab(CreativeTabs.tabDecorations);
}
/**
* Called upon block activation (right click on the block.)
*/
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
if (par1World.getBlockMetadata(par2, par3, par4) == 0)
{
return false;
}
else
{
this.ejectRecord(par1World, par2, par3, par4);
return true;
}
}
/**
* Insert the specified music disc in the jukebox at the given coordinates
*/
public void insertRecord(World par1World, int par2, int par3, int par4, ItemStack par5ItemStack)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var6 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var6 != null)
{
var6.func_96098_a(par5ItemStack.copy());
par1World.setBlockMetadata(par2, par3, par4, 1, 2);
}
}
}
/**
* Ejects the current record inside of the jukebox.
*/
public void ejectRecord(World par1World, int par2, int par3, int par4)
{
if (!par1World.isRemote)
{
TileEntityRecordPlayer var5 = (TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4);
if (var5 != null)
{
ItemStack var6 = var5.func_96097_a();
if (var6 != null)
{
par1World.playAuxSFX(1005, par2, par3, par4, 0);
par1World.playRecord((String)null, par2, par3, par4);
var5.func_96098_a((ItemStack)null);
par1World.setBlockMetadata(par2, par3, par4, 0, 2);
float var7 = 0.7F;
double var8 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
double var10 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.2D + 0.6D;
double var12 = (double)(par1World.rand.nextFloat() * var7) + (double)(1.0F - var7) * 0.5D;
ItemStack var14 = var6.copy();
EntityItem var15 = new EntityItem(par1World, (double)par2 + var8, (double)par3 + var10, (double)par4 + var12, var14);
var15.delayBeforeCanPickup = 10;
par1World.spawnEntityInWorld(var15);
}
}
}
}
/**
* ejects contained items into the world, and notifies neighbours of an update, as appropriate
*/
public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6)
{
this.ejectRecord(par1World, par2, par3, par4);
super.breakBlock(par1World, par2, par3, par4, par5, par6);
}
/**
* Drops the block items with a specified chance of dropping the specified items
*/
public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7)
{
if (!par1World.isRemote)
{
super.dropBlockAsItemWithChance(par1World, par2, par3, par4, par5, par6, 0);
}
}
/**
* Returns a new instance of a block's tile entity class. Called on placing the block.
*/
public TileEntity createNewTileEntity(World par1World)
{
return new TileEntityRecordPlayer();
}
/**
* If this returns true, then comparators facing away from this block will use the value from
* getComparatorInputOverride instead of the actual redstone signal strength.
*/
public boolean hasComparatorInputOverride()
{
return true;
}
/**
* If hasComparatorInputOverride returns true, the return value from this is used instead of the redstone signal
* strength when this block inputs to a comparator.
*/
public int getComparatorInputOverride(World par1World, int par2, int par3, int par4, int par5)
{
ItemStack var6 = ((TileEntityRecordPlayer)par1World.getBlockTileEntity(par2, par3, par4)).func_96097_a();
return var6 == null ? 0 : var6.itemID + 1 - Item.record13.itemID;
}
}
| Java |
from bottle import route, template, error, request, static_file, get, post
from index import get_index
from bmarks import get_bmarks
from tags import get_tags
from add import add_tags
from bmarklet import get_bmarklet
from account import get_account
from edit_tags import get_edit_tags
from importbm import get_import_bm
from edit import do_edit
from login import do_login
from register import do_register
@route('/')
def myroot():
return_data = get_index()
return return_data
@route('/account', method=['GET', 'POST'])
def bmarks():
return_data = get_bmarklet()
return return_data
@route('/add', method=['GET', 'POST'])
def bmarks():
return_data = add_tags()
return return_data
@route('/bmarklet')
def bmarks():
return_data = get_bmarklet()
return return_data
@route('/bmarks')
def bmarks():
return_data = get_bmarks()
return return_data
@route('/edit', method=['GET', 'POST'])
def bmarks():
return_data = do_edit()
return return_data
@route('/edit_tags', method=['GET', 'POST'])
def bmarks():
return_data = get_edit_tags()
return return_data
@route('/import', method=['GET', 'POST'])
def bmarks():
return_data = get_import_bm()
return return_data
@route('/login', method=['GET', 'POST'])
def bmarks():
return_data = do_login()
return return_data
@route('/register', method=['GET', 'POST'])
def bmarks():
return_data = do_register()
return return_data
@route('/tags')
def bmarks():
return_data = get_tags()
return return_data
# serve css
@get('/<filename:re:.*\.css>')
def send_css(filename):
return static_file(filename, root='css')
# serve javascript
@get('/<filename:re:.*\.js>')
def send_js(filename):
return static_file(filename, root='js')
# serve images
@get('<filename:re:.*\.png>')
def send_img(filename):
return static_file(filename, root='images')
# serve fonts
@get('<filename:re:.*\.(woff|woff2)>')
def send_font(filename):
return static_file(filename, root='fonts')
@error(404)
def handle404(error):
return '<H1>Ooops, its not here<BR>'
@error(500)
def handle500(error):
return '<H1>Oops, its broken: {}<BR>'.format(error)
| Java |
LetsModReboot
=============
Learning to mod mc with Pahimar
| Java |
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLJPanel;
import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
import com.jogamp.opengl.glu.GLU;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import static com.jogamp.opengl.GL.GL_COLOR_BUFFER_BIT;
import static com.jogamp.opengl.GL.GL_DEPTH_BUFFER_BIT;
/**
* This program demonstrates geometric primitives and their attributes.
*
* @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes
*/
public class LinesDemo//
// extends GLSkeleton<GLJPanel>
implements GLEventListener, KeyListener {
private GLU glu;
// public static void main(String[] args) {
// final GLCanvas glcanvas = createCanvas();
//
// final JFrame frame = new JFrame("Basic Frame");
//
// frame.getContentPane().add(glcanvas);
// frame.setSize(frame.getContentPane().getPreferredSize());
// frame.setVisible(true);
//
// frame.repaint();
// }
// public static GLCanvas createCanvas() {
// final GLProfile profile = GLProfile.get(GLProfile.GL2);
// GLCapabilities capabilities = new GLCapabilities(profile);
//
// final GLCanvas glcanvas = new GLCanvas(capabilities);
// LinesDemo b = new LinesDemo();
// glcanvas.addGLEventListener(b);
//// glcanvas.setSize(screenSize, screenSize);
//
// return glcanvas;
// }
// @Override
protected GLJPanel createDrawable() {
GLCapabilities caps = new GLCapabilities(null);
//
GLJPanel panel = new GLJPanel(caps);
panel.addGLEventListener(this);
panel.addKeyListener(this);
return panel;
}
public void run() {
GLJPanel demo = createDrawable();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("LinesDemo");
frame.setSize(400, 150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(demo);
frame.setVisible(true);
demo.requestFocusInWindow();
}
public static void main(String[] args) {
new LinesDemo().run();
}
public void init(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
glu = new GLU();
//
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glShadeModel(GL2.GL_FLAT);
}
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
//
int i;
float coordinateSize = 300;
// gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// gl.glClearColor(1f, 1f, 1f, 1f);
// gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
// gl.glLoadIdentity();
// gl.glOrtho(-coordinateSize, coordinateSize, -coordinateSize, coordinateSize, -1, 1);
/* select white for all LinesDemo */
gl.glColor3f(1.0f, 1.0f, 1.0f);
/* in 1st row, 3 LinesDemo, each with a different stipple */
gl.glEnable(GL2.GL_LINE_STIPPLE);
gl.glEnable(GL2.GL_POINT_SMOOTH);
gl.glBegin(GL2.GL_POINTS);
gl.glPointSize(10e5f);
gl.glVertex2i(200, 200);
gl.glEnd();
gl.glDisable(GL2.GL_POINT_SMOOTH);
gl.glLineStipple(1, (short) 0x0101); /* dotted */
drawOneLine(gl, 50.0f, 125.0f, 150.0f, 125.0f);
gl.glLineStipple(1, (short) 0x00FF); /* dashed */
drawOneLine(gl, 150.0f, 125.0f, 250.0f, 125.0f);
drawOneLine(gl, 150.0f, 125.0f, 250.0f, 200f);
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 250.0f, 125.0f, 350.0f, 125.0f);
/* in 2nd row, 3 wide LinesDemo, each with different stipple */
gl.glLineWidth(5.0f);
gl.glLineStipple(1, (short) 0x0101); /* dotted */
drawOneLine(gl, 50.0f, 100.0f, 150.0f, 100.f);
gl.glLineStipple(1, (short) 0x00FF); /* dashed */
drawOneLine(gl, 150.0f, 100.0f, 250.0f, 100.0f);
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 250.0f, 100.0f, 350.0f, 100.0f);
gl.glLineWidth(1.0f);
/* in 3rd row, 6 LinesDemo, with dash/dot/dash stipple */
/* as part of a single connected line strip */
gl.glLineStipple(1, (short) 0x1C47); /* dash/dot/dash */
gl.glBegin(GL.GL_LINE_STRIP);
for (i = 0; i < 7; i++)
gl.glVertex2f(50.0f + ((float) i * 50.0f), 75.0f);
gl.glEnd();
/* in 4th row, 6 independent LinesDemo with same stipple */
for (i = 0; i < 6; i++) {
drawOneLine(gl, 50.0f + ((float) i * 50.0f), 50.0f,
50.0f + ((float) (i + 1) * 50.0f), 50.0f);
}
/* in 5th row, 1 line, with dash/dot/dash stipple */
/* and a stipple repeat factor of 5 */
gl.glLineStipple(5, (short) 0x1C47); /* dash/dot/dash */
drawOneLine(gl, 50.0f, 25.0f, 350.0f, 25.0f);
gl.glDisable(GL2.GL_LINE_STIPPLE);
gl.glFlush();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
GL2 gl = drawable.getGL().getGL2();
//
gl.glViewport(0, 0, w, h);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluOrtho2D(0.0, (double) w, 0.0, (double) h);
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged,
boolean deviceChanged) {
}
private void drawOneLine(GL2 gl, float x1, float y1, float x2, float y2) {
// gl.glBegin(GL.GL_LINES);
gl.glVertex2f((x1), (y1));
gl.glVertex2f((x2), (y2));
// gl.glEnd();
}
public void keyTyped(KeyEvent key) {
}
public void keyPressed(KeyEvent key) {
switch (key.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
System.exit(0);
break;
default:
break;
}
}
public void keyReleased(KeyEvent key) {
}
public void dispose(GLAutoDrawable arg0) {
}
} | Java |
/*-------------------------------------------------------------------------
*
* prepjointree.c
* Planner preprocessing for subqueries and join tree manipulation.
*
* NOTE: the intended sequence for invoking these operations is
* pull_up_sublinks
* inline_set_returning_functions
* pull_up_subqueries
* do expression preprocessing (including flattening JOIN alias vars)
* reduce_outer_joins
*
*
* Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/backend/optimizer/prep/prepjointree.c,v 1.73 2010/07/06 19:18:56 momjian Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "catalog/pg_type.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/placeholder.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
typedef struct pullup_replace_vars_context
{
PlannerInfo *root;
List *targetlist; /* tlist of subquery being pulled up */
RangeTblEntry *target_rte; /* RTE of subquery */
bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */
int varno; /* varno of subquery */
bool need_phvs; /* do we need PlaceHolderVars? */
bool wrap_non_vars; /* do we need 'em on *all* non-Vars? */
Node **rv_cache; /* cache for results with PHVs */
} pullup_replace_vars_context;
typedef struct reduce_outer_joins_state
{
Relids relids; /* base relids within this subtree */
bool contains_outer; /* does subtree contain outer join(s)? */
List *sub_states; /* List of states for subtree components */
} reduce_outer_joins_state;
static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
Relids *relids);
static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
Relids available_rels, Node **jtlink);
static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
RangeTblEntry *rte,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel);
static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
RangeTblEntry *rte);
static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
int parentRTindex, Query *setOpQuery,
int childRToffset);
static void make_setop_translation_list(Query *query, Index newvarno,
List **translated_vars);
static bool is_simple_subquery(Query *subquery);
static bool is_simple_union_all(Query *subquery);
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
List *colTypes);
static bool is_safe_append_member(Query *subquery);
static void replace_vars_in_jointree(Node *jtnode,
pullup_replace_vars_context *context,
JoinExpr *lowest_outer_join);
static Node *pullup_replace_vars(Node *expr,
pullup_replace_vars_context *context);
static Node *pullup_replace_vars_callback(Var *var,
replace_rte_variables_context *context);
static reduce_outer_joins_state *reduce_outer_joins_pass1(Node *jtnode);
static void reduce_outer_joins_pass2(Node *jtnode,
reduce_outer_joins_state *state,
PlannerInfo *root,
Relids nonnullable_rels,
List *nonnullable_vars,
List *forced_null_vars);
static void substitute_multiple_relids(Node *node,
int varno, Relids subrelids);
static void fix_append_rel_relids(List *append_rel_list, int varno,
Relids subrelids);
static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
/*
* pull_up_sublinks
* Attempt to pull up ANY and EXISTS SubLinks to be treated as
* semijoins or anti-semijoins.
*
* A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
* sub-SELECT up to become a rangetable entry and treating the implied
* comparisons as quals of a semijoin. However, this optimization *only*
* works at the top level of WHERE or a JOIN/ON clause, because we cannot
* distinguish whether the ANY ought to return FALSE or NULL in cases
* involving NULL inputs. Also, in an outer join's ON clause we can only
* do this if the sublink is degenerate (ie, references only the nullable
* side of the join). In that case it is legal to push the semijoin
* down into the nullable side of the join. If the sublink references any
* nonnullable-side variables then it would have to be evaluated as part
* of the outer join, which makes things way too complicated.
*
* Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
* by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
*
* This routine searches for such clauses and does the necessary parsetree
* transformations if any are found.
*
* This routine has to run before preprocess_expression(), so the quals
* clauses are not yet reduced to implicit-AND format. That means we need
* to recursively search through explicit AND clauses, which are
* probably only binary ANDs. We stop as soon as we hit a non-AND item.
*/
void
pull_up_sublinks(PlannerInfo *root)
{
Node *jtnode;
Relids relids;
/* Begin recursion through the jointree */
jtnode = pull_up_sublinks_jointree_recurse(root,
(Node *) root->parse->jointree,
&relids);
/*
* root->parse->jointree must always be a FromExpr, so insert a dummy one
* if we got a bare RangeTblRef or JoinExpr out of the recursion.
*/
if (IsA(jtnode, FromExpr))
root->parse->jointree = (FromExpr *) jtnode;
else
root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
}
/*
* Recurse through jointree nodes for pull_up_sublinks()
*
* In addition to returning the possibly-modified jointree node, we return
* a relids set of the contained rels into *relids.
*/
static Node *
pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
Relids *relids)
{
if (jtnode == NULL)
{
*relids = NULL;
}
else if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
*relids = bms_make_singleton(varno);
/* jtnode is returned unmodified */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
List *newfromlist = NIL;
Relids frelids = NULL;
FromExpr *newf;
Node *jtlink;
ListCell *l;
/* First, recurse to process children and collect their relids */
foreach(l, f->fromlist)
{
Node *newchild;
Relids childrelids;
newchild = pull_up_sublinks_jointree_recurse(root,
lfirst(l),
&childrelids);
newfromlist = lappend(newfromlist, newchild);
frelids = bms_join(frelids, childrelids);
}
/* Build the replacement FromExpr; no quals yet */
newf = makeFromExpr(newfromlist, NULL);
/* Set up a link representing the rebuilt jointree */
jtlink = (Node *) newf;
/* Now process qual --- all children are available for use */
newf->quals = pull_up_sublinks_qual_recurse(root, f->quals, frelids,
&jtlink);
/*
* Note that the result will be either newf, or a stack of JoinExprs
* with newf at the base. We rely on subsequent optimization steps to
* flatten this and rearrange the joins as needed.
*
* Although we could include the pulled-up subqueries in the returned
* relids, there's no need since upper quals couldn't refer to their
* outputs anyway.
*/
*relids = frelids;
jtnode = jtlink;
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j;
Relids leftrelids;
Relids rightrelids;
Node *jtlink;
/*
* Make a modifiable copy of join node, but don't bother copying its
* subnodes (yet).
*/
j = (JoinExpr *) palloc(sizeof(JoinExpr));
memcpy(j, jtnode, sizeof(JoinExpr));
jtlink = (Node *) j;
/* Recurse to process children and collect their relids */
j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
&leftrelids);
j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
&rightrelids);
/*
* Now process qual, showing appropriate child relids as available,
* and attach any pulled-up jointree items at the right place. In the
* inner-join case we put new JoinExprs above the existing one (much
* as for a FromExpr-style join). In outer-join cases the new
* JoinExprs must go into the nullable side of the outer join. The
* point of the available_rels machinations is to ensure that we only
* pull up quals for which that's okay.
*
* XXX for the moment, we refrain from pulling up IN/EXISTS clauses
* appearing in LEFT or RIGHT join conditions. Although it is
* semantically valid to do so under the above conditions, we end up
* with a query in which the semijoin or antijoin must be evaluated
* below the outer join, which could perform far worse than leaving it
* as a sublink that is executed only for row pairs that meet the
* other join conditions. Fixing this seems to require considerable
* restructuring of the executor, but maybe someday it can happen.
*
* We don't expect to see any pre-existing JOIN_SEMI or JOIN_ANTI
* nodes here.
*/
switch (j->jointype)
{
case JOIN_INNER:
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
bms_union(leftrelids,
rightrelids),
&jtlink);
break;
case JOIN_LEFT:
#ifdef NOT_USED /* see XXX comment above */
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
rightrelids,
&j->rarg);
#endif
break;
case JOIN_FULL:
/* can't do anything with full-join quals */
break;
case JOIN_RIGHT:
#ifdef NOT_USED /* see XXX comment above */
j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
leftrelids,
&j->larg);
#endif
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) j->jointype);
break;
}
/*
* Although we could include the pulled-up subqueries in the returned
* relids, there's no need since upper quals couldn't refer to their
* outputs anyway. But we *do* need to include the join's own rtindex
* because we haven't yet collapsed join alias variables, so upper
* levels would mistakenly think they couldn't use references to this
* join.
*/
*relids = bms_join(leftrelids, rightrelids);
if (j->rtindex)
*relids = bms_add_member(*relids, j->rtindex);
jtnode = jtlink;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return jtnode;
}
/*
* Recurse through top-level qual nodes for pull_up_sublinks()
*
* jtlink points to the link in the jointree where any new JoinExprs should be
* inserted. If we find multiple pull-up-able SubLinks, they'll get stacked
* there in the order we encounter them. We rely on subsequent optimization
* to rearrange the stack if appropriate.
*/
static Node *
pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
Relids available_rels, Node **jtlink)
{
if (node == NULL)
return NULL;
if (IsA(node, SubLink))
{
SubLink *sublink = (SubLink *) node;
JoinExpr *j;
/* Is it a convertible ANY or EXISTS clause? */
if (sublink->subLinkType == ANY_SUBLINK)
{
j = convert_ANY_sublink_to_join(root, sublink,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
else if (sublink->subLinkType == EXISTS_SUBLINK)
{
j = convert_EXISTS_sublink_to_join(root, sublink, false,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
/* Else return it unmodified */
return node;
}
if (not_clause(node))
{
/* If the immediate argument of NOT is EXISTS, try to convert */
SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
JoinExpr *j;
if (sublink && IsA(sublink, SubLink))
{
if (sublink->subLinkType == EXISTS_SUBLINK)
{
j = convert_EXISTS_sublink_to_join(root, sublink, true,
available_rels);
if (j)
{
/* Yes, insert the new join node into the join tree */
j->larg = *jtlink;
*jtlink = (Node *) j;
/* and return NULL representing constant TRUE */
return NULL;
}
}
}
/* Else return it unmodified */
return node;
}
if (and_clause(node))
{
/* Recurse into AND clause */
List *newclauses = NIL;
ListCell *l;
foreach(l, ((BoolExpr *) node)->args)
{
Node *oldclause = (Node *) lfirst(l);
Node *newclause;
newclause = pull_up_sublinks_qual_recurse(root,
oldclause,
available_rels,
jtlink);
if (newclause)
newclauses = lappend(newclauses, newclause);
}
/* We might have got back fewer clauses than we started with */
if (newclauses == NIL)
return NULL;
else if (list_length(newclauses) == 1)
return (Node *) linitial(newclauses);
else
return (Node *) make_andclause(newclauses);
}
/* Stop if not an AND */
return node;
}
/*
* inline_set_returning_functions
* Attempt to "inline" set-returning functions in the FROM clause.
*
* If an RTE_FUNCTION rtable entry invokes a set-returning function that
* contains just a simple SELECT, we can convert the rtable entry to an
* RTE_SUBQUERY entry exposing the SELECT directly. This is especially
* useful if the subquery can then be "pulled up" for further optimization,
* but we do it even if not, to reduce executor overhead.
*
* This has to be done before we have started to do any optimization of
* subqueries, else any such steps wouldn't get applied to subqueries
* obtained via inlining. However, we do it after pull_up_sublinks
* so that we can inline any functions used in SubLink subselects.
*
* Like most of the planner, this feels free to scribble on its input data
* structure.
*/
void
inline_set_returning_functions(PlannerInfo *root)
{
ListCell *rt;
foreach(rt, root->parse->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
if (rte->rtekind == RTE_FUNCTION)
{
Query *funcquery;
/* Check safety of expansion, and expand if possible */
funcquery = inline_set_returning_function(root, rte);
if (funcquery)
{
/* Successful expansion, replace the rtable entry */
rte->rtekind = RTE_SUBQUERY;
rte->subquery = funcquery;
rte->funcexpr = NULL;
rte->funccoltypes = NIL;
rte->funccoltypmods = NIL;
}
}
}
}
/*
* pull_up_subqueries
* Look for subqueries in the rangetable that can be pulled up into
* the parent query. If the subquery has no special features like
* grouping/aggregation then we can merge it into the parent's jointree.
* Also, subqueries that are simple UNION ALL structures can be
* converted into "append relations".
*
* If this jointree node is within the nullable side of an outer join, then
* lowest_outer_join references the lowest such JoinExpr node; otherwise it
* is NULL. This forces use of the PlaceHolderVar mechanism for references
* to non-nullable targetlist items, but only for references above that join.
*
* If we are looking at a member subquery of an append relation,
* containing_appendrel describes that relation; else it is NULL.
* This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
* items, and puts some additional restrictions on what can be pulled up.
*
* A tricky aspect of this code is that if we pull up a subquery we have
* to replace Vars that reference the subquery's outputs throughout the
* parent query, including quals attached to jointree nodes above the one
* we are currently processing! We handle this by being careful not to
* change the jointree structure while recursing: no nodes other than
* subquery RangeTblRef entries will be replaced. Also, we can't turn
* pullup_replace_vars loose on the whole jointree, because it'll return a
* mutated copy of the tree; we have to invoke it just on the quals, instead.
* This behavior is what makes it reasonable to pass lowest_outer_join as a
* pointer rather than some more-indirect way of identifying the lowest OJ.
* Likewise, we don't replace append_rel_list members but only their
* substructure, so the containing_appendrel reference is safe to use.
*/
Node *
pull_up_subqueries(PlannerInfo *root, Node *jtnode,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel)
{
if (jtnode == NULL)
return NULL;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
/*
* Is this a subquery RTE, and if so, is the subquery simple enough to
* pull up?
*
* If we are looking at an append-relation member, we can't pull it up
* unless is_safe_append_member says so.
*/
if (rte->rtekind == RTE_SUBQUERY &&
is_simple_subquery(rte->subquery) &&
(containing_appendrel == NULL ||
is_safe_append_member(rte->subquery)))
return pull_up_simple_subquery(root, jtnode, rte,
lowest_outer_join,
containing_appendrel);
/*
* Alternatively, is it a simple UNION ALL subquery? If so, flatten
* into an "append relation".
*
* It's safe to do this regardless of whether this query is itself an
* appendrel member. (If you're thinking we should try to flatten the
* two levels of appendrel together, you're right; but we handle that
* in set_append_rel_pathlist, not here.)
*/
if (rte->rtekind == RTE_SUBQUERY &&
is_simple_union_all(rte->subquery))
return pull_up_simple_union_all(root, jtnode, rte);
/* Otherwise, do nothing at this node. */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
Assert(containing_appendrel == NULL);
foreach(l, f->fromlist)
lfirst(l) = pull_up_subqueries(root, lfirst(l),
lowest_outer_join, NULL);
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
Assert(containing_appendrel == NULL);
/* Recurse, being careful to tell myself when inside outer join */
switch (j->jointype)
{
case JOIN_INNER:
j->larg = pull_up_subqueries(root, j->larg,
lowest_outer_join, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
lowest_outer_join, NULL);
break;
case JOIN_LEFT:
case JOIN_SEMI:
case JOIN_ANTI:
j->larg = pull_up_subqueries(root, j->larg,
lowest_outer_join, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
j, NULL);
break;
case JOIN_FULL:
j->larg = pull_up_subqueries(root, j->larg,
j, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
j, NULL);
break;
case JOIN_RIGHT:
j->larg = pull_up_subqueries(root, j->larg,
j, NULL);
j->rarg = pull_up_subqueries(root, j->rarg,
lowest_outer_join, NULL);
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) j->jointype);
break;
}
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return jtnode;
}
/*
* pull_up_simple_subquery
* Attempt to pull up a single simple subquery.
*
* jtnode is a RangeTblRef that has been tentatively identified as a simple
* subquery by pull_up_subqueries. We return the replacement jointree node,
* or jtnode itself if we determine that the subquery can't be pulled up after
* all.
*
* rte is the RangeTblEntry referenced by jtnode. Remaining parameters are
* as for pull_up_subqueries.
*/
static Node *
pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
JoinExpr *lowest_outer_join,
AppendRelInfo *containing_appendrel)
{
Query *parse = root->parse;
int varno = ((RangeTblRef *) jtnode)->rtindex;
Query *subquery;
PlannerInfo *subroot;
int rtoffset;
pullup_replace_vars_context rvcontext;
ListCell *lc;
/*
* Need a modifiable copy of the subquery to hack on. Even if we didn't
* sometimes choose not to pull up below, we must do this to avoid
* problems if the same subquery is referenced from multiple jointree
* items (which can't happen normally, but might after rule rewriting).
*/
subquery = copyObject(rte->subquery);
/*
* Create a PlannerInfo data structure for this subquery.
*
* NOTE: the next few steps should match the first processing in
* subquery_planner(). Can we refactor to avoid code duplication, or
* would that just make things uglier?
*/
subroot = makeNode(PlannerInfo);
subroot->parse = subquery;
subroot->glob = root->glob;
subroot->query_level = root->query_level;
subroot->parent_root = root->parent_root;
subroot->planner_cxt = CurrentMemoryContext;
subroot->init_plans = NIL;
subroot->cte_plan_ids = NIL;
subroot->eq_classes = NIL;
subroot->append_rel_list = NIL;
subroot->rowMarks = NIL;
subroot->hasRecursion = false;
subroot->wt_param_id = -1;
subroot->non_recursive_plan = NULL;
/* No CTEs to worry about */
Assert(subquery->cteList == NIL);
/*
* Pull up any SubLinks within the subquery's quals, so that we don't
* leave unoptimized SubLinks behind.
*/
if (subquery->hasSubLinks)
pull_up_sublinks(subroot);
/*
* Similarly, inline any set-returning functions in its rangetable.
*/
inline_set_returning_functions(subroot);
/*
* Recursively pull up the subquery's subqueries, so that
* pull_up_subqueries' processing is complete for its jointree and
* rangetable.
*
* Note: we should pass NULL for containing-join info even if we are
* within an outer join in the upper query; the lower query starts with a
* clean slate for outer-join semantics. Likewise, we say we aren't
* handling an appendrel member.
*/
subquery->jointree = (FromExpr *)
pull_up_subqueries(subroot, (Node *) subquery->jointree, NULL, NULL);
/*
* Now we must recheck whether the subquery is still simple enough to pull
* up. If not, abandon processing it.
*
* We don't really need to recheck all the conditions involved, but it's
* easier just to keep this "if" looking the same as the one in
* pull_up_subqueries.
*/
if (is_simple_subquery(subquery) &&
(containing_appendrel == NULL || is_safe_append_member(subquery)))
{
/* good to go */
}
else
{
/*
* Give up, return unmodified RangeTblRef.
*
* Note: The work we just did will be redone when the subquery gets
* planned on its own. Perhaps we could avoid that by storing the
* modified subquery back into the rangetable, but I'm not gonna risk
* it now.
*/
return jtnode;
}
/*
* Adjust level-0 varnos in subquery so that we can append its rangetable
* to upper query's. We have to fix the subquery's append_rel_list as
* well.
*/
rtoffset = list_length(parse->rtable);
OffsetVarNodes((Node *) subquery, rtoffset, 0);
OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
/*
* Upper-level vars in subquery are now one level closer to their parent
* than before.
*/
IncrementVarSublevelsUp((Node *) subquery, -1, 1);
IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
/*
* The subquery's targetlist items are now in the appropriate form to
* insert into the top query, but if we are under an outer join then
* non-nullable items may have to be turned into PlaceHolderVars. If we
* are dealing with an appendrel member then anything that's not a simple
* Var has to be turned into a PlaceHolderVar. Set up appropriate context
* data for pullup_replace_vars.
*/
rvcontext.root = root;
rvcontext.targetlist = subquery->targetList;
rvcontext.target_rte = rte;
rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
rvcontext.varno = varno;
rvcontext.need_phvs = (lowest_outer_join != NULL ||
containing_appendrel != NULL);
rvcontext.wrap_non_vars = (containing_appendrel != NULL);
/* initialize cache array with indexes 0 .. length(tlist) */
rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
sizeof(Node *));
/*
* Replace all of the top query's references to the subquery's outputs
* with copies of the adjusted subtlist items, being careful not to
* replace any of the jointree structure. (This'd be a lot cleaner if we
* could use query_tree_mutator.) We have to use PHVs in the targetList,
* returningList, and havingQual, since those are certainly above any
* outer join. replace_vars_in_jointree tracks its location in the
* jointree and uses PHVs or not appropriately.
*/
parse->targetList = (List *)
pullup_replace_vars((Node *) parse->targetList, &rvcontext);
parse->returningList = (List *)
pullup_replace_vars((Node *) parse->returningList, &rvcontext);
replace_vars_in_jointree((Node *) parse->jointree, &rvcontext,
lowest_outer_join);
Assert(parse->setOperations == NULL);
parse->havingQual = pullup_replace_vars(parse->havingQual, &rvcontext);
/*
* Replace references in the translated_vars lists of appendrels. When
* pulling up an appendrel member, we do not need PHVs in the list of the
* parent appendrel --- there isn't any outer join between. Elsewhere, use
* PHVs for safety. (This analysis could be made tighter but it seems
* unlikely to be worth much trouble.)
*/
foreach(lc, root->append_rel_list)
{
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
bool save_need_phvs = rvcontext.need_phvs;
if (appinfo == containing_appendrel)
rvcontext.need_phvs = false;
appinfo->translated_vars = (List *)
pullup_replace_vars((Node *) appinfo->translated_vars, &rvcontext);
rvcontext.need_phvs = save_need_phvs;
}
/*
* Replace references in the joinaliasvars lists of join RTEs.
*
* You might think that we could avoid using PHVs for alias vars of joins
* below lowest_outer_join, but that doesn't work because the alias vars
* could be referenced above that join; we need the PHVs to be present in
* such references after the alias vars get flattened. (It might be worth
* trying to be smarter here, someday.)
*/
foreach(lc, parse->rtable)
{
RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
if (otherrte->rtekind == RTE_JOIN)
otherrte->joinaliasvars = (List *)
pullup_replace_vars((Node *) otherrte->joinaliasvars,
&rvcontext);
}
/*
* Now append the adjusted rtable entries to upper query. (We hold off
* until after fixing the upper rtable entries; no point in running that
* code on the subquery ones too.)
*/
parse->rtable = list_concat(parse->rtable, subquery->rtable);
/*
* Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already
* adjusted the marker rtindexes, so just concat the lists.)
*/
parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
/*
* We also have to fix the relid sets of any PlaceHolderVar nodes in the
* parent query. (This could perhaps be done by pullup_replace_vars(),
* but it seems cleaner to use two passes.) Note in particular that any
* PlaceHolderVar nodes just created by pullup_replace_vars() will be
* adjusted, so having created them with the subquery's varno is correct.
*
* Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
* already checked that this won't require introducing multiple subrelids
* into the single-slot AppendRelInfo structs.
*/
if (parse->hasSubLinks || root->glob->lastPHId != 0 ||
root->append_rel_list)
{
Relids subrelids;
subrelids = get_relids_in_jointree((Node *) subquery->jointree, false);
substitute_multiple_relids((Node *) parse, varno, subrelids);
fix_append_rel_relids(root->append_rel_list, varno, subrelids);
}
/*
* And now add subquery's AppendRelInfos to our list.
*/
root->append_rel_list = list_concat(root->append_rel_list,
subroot->append_rel_list);
/*
* We don't have to do the equivalent bookkeeping for outer-join info,
* because that hasn't been set up yet. placeholder_list likewise.
*/
Assert(root->join_info_list == NIL);
Assert(subroot->join_info_list == NIL);
Assert(root->placeholder_list == NIL);
Assert(subroot->placeholder_list == NIL);
/*
* Miscellaneous housekeeping.
*
* Although replace_rte_variables() faithfully updated parse->hasSubLinks
* if it copied any SubLinks out of the subquery's targetlist, we still
* could have SubLinks added to the query in the expressions of FUNCTION
* and VALUES RTEs copied up from the subquery. So it's necessary to copy
* subquery->hasSubLinks anyway. Perhaps this can be improved someday.
*/
parse->hasSubLinks |= subquery->hasSubLinks;
/*
* subquery won't be pulled up if it hasAggs or hasWindowFuncs, so no work
* needed on those flags
*/
/*
* Return the adjusted subquery jointree to replace the RangeTblRef entry
* in parent's jointree.
*/
return (Node *) subquery->jointree;
}
/*
* pull_up_simple_union_all
* Pull up a single simple UNION ALL subquery.
*
* jtnode is a RangeTblRef that has been identified as a simple UNION ALL
* subquery by pull_up_subqueries. We pull up the leaf subqueries and
* build an "append relation" for the union set. The result value is just
* jtnode, since we don't actually need to change the query jointree.
*/
static Node *
pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
Query *subquery = rte->subquery;
int rtoffset;
List *rtable;
/*
* Append the subquery rtable entries to upper query.
*/
rtoffset = list_length(root->parse->rtable);
/*
* Append child RTEs to parent rtable.
*
* Upper-level vars in subquery are now one level closer to their parent
* than before. We don't have to worry about offsetting varnos, though,
* because any such vars must refer to stuff above the level of the query
* we are pulling into.
*/
rtable = copyObject(subquery->rtable);
IncrementVarSublevelsUp_rtable(rtable, -1, 1);
root->parse->rtable = list_concat(root->parse->rtable, rtable);
/*
* Recursively scan the subquery's setOperations tree and add
* AppendRelInfo nodes for leaf subqueries to the parent's
* append_rel_list.
*/
Assert(subquery->setOperations);
pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
rtoffset);
/*
* Mark the parent as an append relation.
*/
rte->inh = true;
return jtnode;
}
/*
* pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
*
* Note that setOpQuery is the Query containing the setOp node, whose rtable
* is where to look up the RTE if setOp is a RangeTblRef. This is *not* the
* same as root->parse, which is the top-level Query we are pulling up into.
*
* parentRTindex is the appendrel parent's index in root->parse->rtable.
*
* The child RTEs have already been copied to the parent. childRToffset
* tells us where in the parent's range table they were copied.
*/
static void
pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
Query *setOpQuery, int childRToffset)
{
if (IsA(setOp, RangeTblRef))
{
RangeTblRef *rtr = (RangeTblRef *) setOp;
int childRTindex;
AppendRelInfo *appinfo;
/*
* Calculate the index in the parent's range table
*/
childRTindex = childRToffset + rtr->rtindex;
/*
* Build a suitable AppendRelInfo, and attach to parent's list.
*/
appinfo = makeNode(AppendRelInfo);
appinfo->parent_relid = parentRTindex;
appinfo->child_relid = childRTindex;
appinfo->parent_reltype = InvalidOid;
appinfo->child_reltype = InvalidOid;
make_setop_translation_list(setOpQuery, childRTindex,
&appinfo->translated_vars);
appinfo->parent_reloid = InvalidOid;
root->append_rel_list = lappend(root->append_rel_list, appinfo);
/*
* Recursively apply pull_up_subqueries to the new child RTE. (We
* must build the AppendRelInfo first, because this will modify it.)
* Note that we can pass NULL for containing-join info even if we're
* actually under an outer join, because the child's expressions
* aren't going to propagate up above the join.
*/
rtr = makeNode(RangeTblRef);
rtr->rtindex = childRTindex;
(void) pull_up_subqueries(root, (Node *) rtr, NULL, appinfo);
}
else if (IsA(setOp, SetOperationStmt))
{
SetOperationStmt *op = (SetOperationStmt *) setOp;
/* Recurse to reach leaf queries */
pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
childRToffset);
pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
childRToffset);
}
else
{
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(setOp));
}
}
/*
* make_setop_translation_list
* Build the list of translations from parent Vars to child Vars for
* a UNION ALL member. (At this point it's just a simple list of
* referencing Vars, but if we succeed in pulling up the member
* subquery, the Vars will get replaced by pulled-up expressions.)
*/
static void
make_setop_translation_list(Query *query, Index newvarno,
List **translated_vars)
{
List *vars = NIL;
ListCell *l;
foreach(l, query->targetList)
{
TargetEntry *tle = (TargetEntry *) lfirst(l);
if (tle->resjunk)
continue;
vars = lappend(vars, makeVar(newvarno,
tle->resno,
exprType((Node *) tle->expr),
exprTypmod((Node *) tle->expr),
0));
}
*translated_vars = vars;
}
/*
* is_simple_subquery
* Check a subquery in the range table to see if it's simple enough
* to pull up into the parent query.
*/
static bool
is_simple_subquery(Query *subquery)
{
/*
* Let's just make sure it's a valid subselect ...
*/
if (!IsA(subquery, Query) ||
subquery->commandType != CMD_SELECT ||
subquery->utilityStmt != NULL ||
subquery->intoClause != NULL)
elog(ERROR, "subquery is bogus");
/*
* Can't currently pull up a query with setops (unless it's simple UNION
* ALL, which is handled by a different code path). Maybe after querytree
* redesign...
*/
if (subquery->setOperations)
return false;
/*
* Can't pull up a subquery involving grouping, aggregation, sorting,
* limiting, or WITH. (XXX WITH could possibly be allowed later)
*
* We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
* clauses, because pullup would cause the locking to occur semantically
* higher than it should. Implicit FOR UPDATE/SHARE is okay because in
* that case the locking was originally declared in the upper query
* anyway.
*/
if (subquery->hasAggs ||
subquery->hasWindowFuncs ||
subquery->groupClause ||
subquery->havingQual ||
subquery->sortClause ||
subquery->distinctClause ||
subquery->limitOffset ||
subquery->limitCount ||
subquery->hasForUpdate ||
subquery->cteList)
return false;
/*
* Don't pull up a subquery that has any set-returning functions in its
* targetlist. Otherwise we might well wind up inserting set-returning
* functions into places where they mustn't go, such as quals of higher
* queries.
*/
if (expression_returns_set((Node *) subquery->targetList))
return false;
/*
* Don't pull up a subquery that has any volatile functions in its
* targetlist. Otherwise we might introduce multiple evaluations of these
* functions, if they get copied to multiple places in the upper query,
* leading to surprising results. (Note: the PlaceHolderVar mechanism
* doesn't quite guarantee single evaluation; else we could pull up anyway
* and just wrap such items in PlaceHolderVars ...)
*/
if (contain_volatile_functions((Node *) subquery->targetList))
return false;
/*
* Hack: don't try to pull up a subquery with an empty jointree.
* query_planner() will correctly generate a Result plan for a jointree
* that's totally empty, but I don't think the right things happen if an
* empty FromExpr appears lower down in a jointree. It would pose a
* problem for the PlaceHolderVar mechanism too, since we'd have no way to
* identify where to evaluate a PHV coming out of the subquery. Not worth
* working hard on this, just to collapse SubqueryScan/Result into Result;
* especially since the SubqueryScan can often be optimized away by
* setrefs.c anyway.
*/
if (subquery->jointree->fromlist == NIL)
return false;
return true;
}
/*
* is_simple_union_all
* Check a subquery to see if it's a simple UNION ALL.
*
* We require all the setops to be UNION ALL (no mixing) and there can't be
* any datatype coercions involved, ie, all the leaf queries must emit the
* same datatypes.
*/
static bool
is_simple_union_all(Query *subquery)
{
SetOperationStmt *topop;
/* Let's just make sure it's a valid subselect ... */
if (!IsA(subquery, Query) ||
subquery->commandType != CMD_SELECT ||
subquery->utilityStmt != NULL ||
subquery->intoClause != NULL)
elog(ERROR, "subquery is bogus");
/* Is it a set-operation query at all? */
topop = (SetOperationStmt *) subquery->setOperations;
if (!topop)
return false;
Assert(IsA(topop, SetOperationStmt));
/* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
if (subquery->sortClause ||
subquery->limitOffset ||
subquery->limitCount ||
subquery->rowMarks ||
subquery->cteList)
return false;
/* Recursively check the tree of set operations */
return is_simple_union_all_recurse((Node *) topop, subquery,
topop->colTypes);
}
static bool
is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
{
if (IsA(setOp, RangeTblRef))
{
RangeTblRef *rtr = (RangeTblRef *) setOp;
RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
Query *subquery = rte->subquery;
Assert(subquery != NULL);
/* Leaf nodes are OK if they match the toplevel column types */
/* We don't have to compare typmods here */
return tlist_same_datatypes(subquery->targetList, colTypes, true);
}
else if (IsA(setOp, SetOperationStmt))
{
SetOperationStmt *op = (SetOperationStmt *) setOp;
/* Must be UNION ALL */
if (op->op != SETOP_UNION || !op->all)
return false;
/* Recurse to check inputs */
return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
}
else
{
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(setOp));
return false; /* keep compiler quiet */
}
}
/*
* is_safe_append_member
* Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
* safe to pull up.
*/
static bool
is_safe_append_member(Query *subquery)
{
FromExpr *jtnode;
/*
* It's only safe to pull up the child if its jointree contains exactly
* one RTE, else the AppendRelInfo data structure breaks. The one base RTE
* could be buried in several levels of FromExpr, however.
*
* Also, the child can't have any WHERE quals because there's no place to
* put them in an appendrel. (This is a bit annoying...) If we didn't
* need to check this, we'd just test whether get_relids_in_jointree()
* yields a singleton set, to be more consistent with the coding of
* fix_append_rel_relids().
*/
jtnode = subquery->jointree;
while (IsA(jtnode, FromExpr))
{
if (jtnode->quals != NULL)
return false;
if (list_length(jtnode->fromlist) != 1)
return false;
jtnode = linitial(jtnode->fromlist);
}
if (!IsA(jtnode, RangeTblRef))
return false;
return true;
}
/*
* Helper routine for pull_up_subqueries: do pullup_replace_vars on every
* expression in the jointree, without changing the jointree structure itself.
* Ugly, but there's no other way...
*
* If we are at or below lowest_outer_join, we can suppress use of
* PlaceHolderVars wrapped around the replacement expressions.
*/
static void
replace_vars_in_jointree(Node *jtnode,
pullup_replace_vars_context *context,
JoinExpr *lowest_outer_join)
{
if (jtnode == NULL)
return;
if (IsA(jtnode, RangeTblRef))
{
/* nothing to do here */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
replace_vars_in_jointree(lfirst(l), context, lowest_outer_join);
f->quals = pullup_replace_vars(f->quals, context);
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
bool save_need_phvs = context->need_phvs;
if (j == lowest_outer_join)
{
/* no more PHVs in or below this join */
context->need_phvs = false;
lowest_outer_join = NULL;
}
replace_vars_in_jointree(j->larg, context, lowest_outer_join);
replace_vars_in_jointree(j->rarg, context, lowest_outer_join);
j->quals = pullup_replace_vars(j->quals, context);
/*
* We don't bother to update the colvars list, since it won't be used
* again ...
*/
context->need_phvs = save_need_phvs;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
}
/*
* Apply pullup variable replacement throughout an expression tree
*
* Returns a modified copy of the tree, so this can't be used where we
* need to do in-place replacement.
*/
static Node *
pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
{
return replace_rte_variables(expr,
context->varno, 0,
pullup_replace_vars_callback,
(void *) context,
context->outer_hasSubLinks);
}
static Node *
pullup_replace_vars_callback(Var *var,
replace_rte_variables_context *context)
{
pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
int varattno = var->varattno;
Node *newnode;
/*
* If PlaceHolderVars are needed, we cache the modified expressions in
* rcon->rv_cache[]. This is not in hopes of any material speed gain
* within this function, but to avoid generating identical PHVs with
* different IDs. That would result in duplicate evaluations at runtime,
* and possibly prevent optimizations that rely on recognizing different
* references to the same subquery output as being equal(). So it's worth
* a bit of extra effort to avoid it.
*/
if (rcon->need_phvs &&
varattno >= InvalidAttrNumber &&
varattno <= list_length(rcon->targetlist) &&
rcon->rv_cache[varattno] != NULL)
{
/* Just copy the entry and fall through to adjust its varlevelsup */
newnode = copyObject(rcon->rv_cache[varattno]);
}
else if (varattno == InvalidAttrNumber)
{
/* Must expand whole-tuple reference into RowExpr */
RowExpr *rowexpr;
List *colnames;
List *fields;
bool save_need_phvs = rcon->need_phvs;
int save_sublevelsup = context->sublevels_up;
/*
* If generating an expansion for a var of a named rowtype (ie, this
* is a plain relation RTE), then we must include dummy items for
* dropped columns. If the var is RECORD (ie, this is a JOIN), then
* omit dropped columns. Either way, attach column names to the
* RowExpr for use of ruleutils.c.
*
* In order to be able to cache the results, we always generate the
* expansion with varlevelsup = 0, and then adjust if needed.
*/
expandRTE(rcon->target_rte,
var->varno, 0 /* not varlevelsup */ , var->location,
(var->vartype != RECORDOID),
&colnames, &fields);
/* Adjust the generated per-field Vars, but don't insert PHVs */
rcon->need_phvs = false;
context->sublevels_up = 0; /* to match the expandRTE output */
fields = (List *) replace_rte_variables_mutator((Node *) fields,
context);
rcon->need_phvs = save_need_phvs;
context->sublevels_up = save_sublevelsup;
rowexpr = makeNode(RowExpr);
rowexpr->args = fields;
rowexpr->row_typeid = var->vartype;
rowexpr->row_format = COERCE_IMPLICIT_CAST;
rowexpr->colnames = colnames;
rowexpr->location = var->location;
newnode = (Node *) rowexpr;
/*
* Insert PlaceHolderVar if needed. Notice that we are wrapping one
* PlaceHolderVar around the whole RowExpr, rather than putting one
* around each element of the row. This is because we need the
* expression to yield NULL, not ROW(NULL,NULL,...) when it is forced
* to null by an outer join.
*/
if (rcon->need_phvs)
{
/* RowExpr is certainly not strict, so always need PHV */
newnode = (Node *)
make_placeholder_expr(rcon->root,
(Expr *) newnode,
bms_make_singleton(rcon->varno));
/* cache it with the PHV, and with varlevelsup still zero */
rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
}
}
else
{
/* Normal case referencing one targetlist element */
TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
if (tle == NULL) /* shouldn't happen */
elog(ERROR, "could not find attribute %d in subquery targetlist",
varattno);
/* Make a copy of the tlist item to return */
newnode = copyObject(tle->expr);
/* Insert PlaceHolderVar if needed */
if (rcon->need_phvs)
{
bool wrap;
if (newnode && IsA(newnode, Var) &&
((Var *) newnode)->varlevelsup == 0)
{
/* Simple Vars always escape being wrapped */
wrap = false;
}
else if (rcon->wrap_non_vars)
{
/* Wrap all non-Vars in a PlaceHolderVar */
wrap = true;
}
else
{
/*
* If it contains a Var of current level, and does not contain
* any non-strict constructs, then it's certainly nullable and
* we don't need to insert a PlaceHolderVar. (Note: in future
* maybe we should insert PlaceHolderVars anyway, when a tlist
* item is expensive to evaluate?
*/
if (contain_vars_of_level((Node *) newnode, 0) &&
!contain_nonstrict_functions((Node *) newnode))
{
/* No wrap needed */
wrap = false;
}
else
{
/* Else wrap it in a PlaceHolderVar */
wrap = true;
}
}
if (wrap)
newnode = (Node *)
make_placeholder_expr(rcon->root,
(Expr *) newnode,
bms_make_singleton(rcon->varno));
/*
* Cache it if possible (ie, if the attno is in range, which it
* probably always should be). We can cache the value even if we
* decided we didn't need a PHV, since this result will be
* suitable for any request that has need_phvs.
*/
if (varattno > InvalidAttrNumber &&
varattno <= list_length(rcon->targetlist))
rcon->rv_cache[varattno] = copyObject(newnode);
}
}
/* Must adjust varlevelsup if tlist item is from higher query */
if (var->varlevelsup > 0)
IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
return newnode;
}
/*
* reduce_outer_joins
* Attempt to reduce outer joins to plain inner joins.
*
* The idea here is that given a query like
* SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
* we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
* is strict. The strict operator will always return NULL, causing the outer
* WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
* columns. Therefore, there's no need for the join to produce null-extended
* rows in the first place --- which makes it a plain join not an outer join.
* (This scenario may not be very likely in a query written out by hand, but
* it's reasonably likely when pushing quals down into complex views.)
*
* More generally, an outer join can be reduced in strength if there is a
* strict qual above it in the qual tree that constrains a Var from the
* nullable side of the join to be non-null. (For FULL joins this applies
* to each side separately.)
*
* Another transformation we apply here is to recognize cases like
* SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
* If the join clause is strict for b.y, then only null-extended rows could
* pass the upper WHERE, and we can conclude that what the query is really
* specifying is an anti-semijoin. We change the join type from JOIN_LEFT
* to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be
* removed to prevent bogus selectivity calculations, but we leave it to
* distribute_qual_to_rels to get rid of such clauses.
*
* Also, we get rid of JOIN_RIGHT cases by flipping them around to become
* JOIN_LEFT. This saves some code here and in some later planner routines,
* but the main reason to do it is to not need to invent a JOIN_REVERSE_ANTI
* join type.
*
* To ease recognition of strict qual clauses, we require this routine to be
* run after expression preprocessing (i.e., qual canonicalization and JOIN
* alias-var expansion).
*/
void
reduce_outer_joins(PlannerInfo *root)
{
reduce_outer_joins_state *state;
/*
* To avoid doing strictness checks on more quals than necessary, we want
* to stop descending the jointree as soon as there are no outer joins
* below our current point. This consideration forces a two-pass process.
* The first pass gathers information about which base rels appear below
* each side of each join clause, and about whether there are outer
* join(s) below each side of each join clause. The second pass examines
* qual clauses and changes join types as it descends the tree.
*/
state = reduce_outer_joins_pass1((Node *) root->parse->jointree);
/* planner.c shouldn't have called me if no outer joins */
if (state == NULL || !state->contains_outer)
elog(ERROR, "so where are the outer joins?");
reduce_outer_joins_pass2((Node *) root->parse->jointree,
state, root, NULL, NIL, NIL);
}
/*
* reduce_outer_joins_pass1 - phase 1 data collection
*
* Returns a state node describing the given jointree node.
*/
static reduce_outer_joins_state *
reduce_outer_joins_pass1(Node *jtnode)
{
reduce_outer_joins_state *result;
result = (reduce_outer_joins_state *)
palloc(sizeof(reduce_outer_joins_state));
result->relids = NULL;
result->contains_outer = false;
result->sub_states = NIL;
if (jtnode == NULL)
return result;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
result->relids = bms_make_singleton(varno);
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
reduce_outer_joins_state *sub_state;
sub_state = reduce_outer_joins_pass1(lfirst(l));
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
reduce_outer_joins_state *sub_state;
/* join's own RT index is not wanted in result->relids */
if (IS_OUTER_JOIN(j->jointype))
result->contains_outer = true;
sub_state = reduce_outer_joins_pass1(j->larg);
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
sub_state = reduce_outer_joins_pass1(j->rarg);
result->relids = bms_add_members(result->relids,
sub_state->relids);
result->contains_outer |= sub_state->contains_outer;
result->sub_states = lappend(result->sub_states, sub_state);
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return result;
}
/*
* reduce_outer_joins_pass2 - phase 2 processing
*
* jtnode: current jointree node
* state: state data collected by phase 1 for this node
* root: toplevel planner state
* nonnullable_rels: set of base relids forced non-null by upper quals
* nonnullable_vars: list of Vars forced non-null by upper quals
* forced_null_vars: list of Vars forced null by upper quals
*/
static void
reduce_outer_joins_pass2(Node *jtnode,
reduce_outer_joins_state *state,
PlannerInfo *root,
Relids nonnullable_rels,
List *nonnullable_vars,
List *forced_null_vars)
{
/*
* pass 2 should never descend as far as an empty subnode or base rel,
* because it's only called on subtrees marked as contains_outer.
*/
if (jtnode == NULL)
elog(ERROR, "reached empty jointree");
if (IsA(jtnode, RangeTblRef))
elog(ERROR, "reached base rel");
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
ListCell *s;
Relids pass_nonnullable_rels;
List *pass_nonnullable_vars;
List *pass_forced_null_vars;
/* Scan quals to see if we can add any constraints */
pass_nonnullable_rels = find_nonnullable_rels(f->quals);
pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
nonnullable_rels);
/* NB: we rely on list_concat to not damage its second argument */
pass_nonnullable_vars = find_nonnullable_vars(f->quals);
pass_nonnullable_vars = list_concat(pass_nonnullable_vars,
nonnullable_vars);
pass_forced_null_vars = find_forced_null_vars(f->quals);
pass_forced_null_vars = list_concat(pass_forced_null_vars,
forced_null_vars);
/* And recurse --- but only into interesting subtrees */
Assert(list_length(f->fromlist) == list_length(state->sub_states));
forboth(l, f->fromlist, s, state->sub_states)
{
reduce_outer_joins_state *sub_state = lfirst(s);
if (sub_state->contains_outer)
reduce_outer_joins_pass2(lfirst(l), sub_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
bms_free(pass_nonnullable_rels);
/* can't so easily clean up var lists, unfortunately */
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
int rtindex = j->rtindex;
JoinType jointype = j->jointype;
reduce_outer_joins_state *left_state = linitial(state->sub_states);
reduce_outer_joins_state *right_state = lsecond(state->sub_states);
List *local_nonnullable_vars = NIL;
bool computed_local_nonnullable_vars = false;
/* Can we simplify this join? */
switch (jointype)
{
case JOIN_INNER:
break;
case JOIN_LEFT:
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_INNER;
break;
case JOIN_RIGHT:
if (bms_overlap(nonnullable_rels, left_state->relids))
jointype = JOIN_INNER;
break;
case JOIN_FULL:
if (bms_overlap(nonnullable_rels, left_state->relids))
{
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_INNER;
else
jointype = JOIN_LEFT;
}
else
{
if (bms_overlap(nonnullable_rels, right_state->relids))
jointype = JOIN_RIGHT;
}
break;
case JOIN_SEMI:
case JOIN_ANTI:
/*
* These could only have been introduced by pull_up_sublinks,
* so there's no way that upper quals could refer to their
* righthand sides, and no point in checking.
*/
break;
default:
elog(ERROR, "unrecognized join type: %d",
(int) jointype);
break;
}
/*
* Convert JOIN_RIGHT to JOIN_LEFT. Note that in the case where we
* reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
* longer matches the internal ordering of any CoalesceExpr's built to
* represent merged join variables. We don't care about that at
* present, but be wary of it ...
*/
if (jointype == JOIN_RIGHT)
{
Node *tmparg;
tmparg = j->larg;
j->larg = j->rarg;
j->rarg = tmparg;
jointype = JOIN_LEFT;
right_state = linitial(state->sub_states);
left_state = lsecond(state->sub_states);
}
/*
* See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
* the join's own quals are strict for any var that was forced null by
* higher qual levels. NOTE: there are other ways that we could
* detect an anti-join, in particular if we were to check whether Vars
* coming from the RHS must be non-null because of table constraints.
* That seems complicated and expensive though (in particular, one
* would have to be wary of lower outer joins). For the moment this
* seems sufficient.
*/
if (jointype == JOIN_LEFT)
{
List *overlap;
local_nonnullable_vars = find_nonnullable_vars(j->quals);
computed_local_nonnullable_vars = true;
/*
* It's not sufficient to check whether local_nonnullable_vars and
* forced_null_vars overlap: we need to know if the overlap
* includes any RHS variables.
*/
overlap = list_intersection(local_nonnullable_vars,
forced_null_vars);
if (overlap != NIL &&
bms_overlap(pull_varnos((Node *) overlap),
right_state->relids))
jointype = JOIN_ANTI;
}
/* Apply the jointype change, if any, to both jointree node and RTE */
if (rtindex && jointype != j->jointype)
{
RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
Assert(rte->rtekind == RTE_JOIN);
Assert(rte->jointype == j->jointype);
rte->jointype = jointype;
}
j->jointype = jointype;
/* Only recurse if there's more to do below here */
if (left_state->contains_outer || right_state->contains_outer)
{
Relids local_nonnullable_rels;
List *local_forced_null_vars;
Relids pass_nonnullable_rels;
List *pass_nonnullable_vars;
List *pass_forced_null_vars;
/*
* If this join is (now) inner, we can add any constraints its
* quals provide to those we got from above. But if it is outer,
* we can pass down the local constraints only into the nullable
* side, because an outer join never eliminates any rows from its
* non-nullable side. Also, there is no point in passing upper
* constraints into the nullable side, since if there were any
* we'd have been able to reduce the join. (In the case of upper
* forced-null constraints, we *must not* pass them into the
* nullable side --- they either applied here, or not.) The upshot
* is that we pass either the local or the upper constraints,
* never both, to the children of an outer join.
*
* At a FULL join we just punt and pass nothing down --- is it
* possible to be smarter?
*/
if (jointype != JOIN_FULL)
{
local_nonnullable_rels = find_nonnullable_rels(j->quals);
if (!computed_local_nonnullable_vars)
local_nonnullable_vars = find_nonnullable_vars(j->quals);
local_forced_null_vars = find_forced_null_vars(j->quals);
if (jointype == JOIN_INNER)
{
/* OK to merge upper and local constraints */
local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
nonnullable_rels);
local_nonnullable_vars = list_concat(local_nonnullable_vars,
nonnullable_vars);
local_forced_null_vars = list_concat(local_forced_null_vars,
forced_null_vars);
}
}
else
{
/* no use in calculating these */
local_nonnullable_rels = NULL;
local_forced_null_vars = NIL;
}
if (left_state->contains_outer)
{
if (jointype == JOIN_INNER)
{
/* pass union of local and upper constraints */
pass_nonnullable_rels = local_nonnullable_rels;
pass_nonnullable_vars = local_nonnullable_vars;
pass_forced_null_vars = local_forced_null_vars;
}
else if (jointype != JOIN_FULL) /* ie, LEFT/SEMI/ANTI */
{
/* can't pass local constraints to non-nullable side */
pass_nonnullable_rels = nonnullable_rels;
pass_nonnullable_vars = nonnullable_vars;
pass_forced_null_vars = forced_null_vars;
}
else
{
/* no constraints pass through JOIN_FULL */
pass_nonnullable_rels = NULL;
pass_nonnullable_vars = NIL;
pass_forced_null_vars = NIL;
}
reduce_outer_joins_pass2(j->larg, left_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
if (right_state->contains_outer)
{
if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
{
/* pass appropriate constraints, per comment above */
pass_nonnullable_rels = local_nonnullable_rels;
pass_nonnullable_vars = local_nonnullable_vars;
pass_forced_null_vars = local_forced_null_vars;
}
else
{
/* no constraints pass through JOIN_FULL */
pass_nonnullable_rels = NULL;
pass_nonnullable_vars = NIL;
pass_forced_null_vars = NIL;
}
reduce_outer_joins_pass2(j->rarg, right_state, root,
pass_nonnullable_rels,
pass_nonnullable_vars,
pass_forced_null_vars);
}
bms_free(local_nonnullable_rels);
}
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
}
/*
* substitute_multiple_relids - adjust node relid sets after pulling up
* a subquery
*
* Find any PlaceHolderVar nodes in the given tree that reference the
* pulled-up relid, and change them to reference the replacement relid(s).
* We do not need to recurse into subqueries, since no subquery of the current
* top query could (yet) contain such a reference.
*
* NOTE: although this has the form of a walker, we cheat and modify the
* nodes in-place. This should be OK since the tree was copied by
* pullup_replace_vars earlier. Avoid scribbling on the original values of
* the bitmapsets, though, because expression_tree_mutator doesn't copy those.
*/
typedef struct
{
int varno;
Relids subrelids;
} substitute_multiple_relids_context;
static bool
substitute_multiple_relids_walker(Node *node,
substitute_multiple_relids_context *context)
{
if (node == NULL)
return false;
if (IsA(node, PlaceHolderVar))
{
PlaceHolderVar *phv = (PlaceHolderVar *) node;
if (bms_is_member(context->varno, phv->phrels))
{
phv->phrels = bms_union(phv->phrels,
context->subrelids);
phv->phrels = bms_del_member(phv->phrels,
context->varno);
}
/* fall through to examine children */
}
/* Shouldn't need to handle planner auxiliary nodes here */
Assert(!IsA(node, SpecialJoinInfo));
Assert(!IsA(node, AppendRelInfo));
Assert(!IsA(node, PlaceHolderInfo));
return expression_tree_walker(node, substitute_multiple_relids_walker,
(void *) context);
}
static void
substitute_multiple_relids(Node *node, int varno, Relids subrelids)
{
substitute_multiple_relids_context context;
context.varno = varno;
context.subrelids = subrelids;
/*
* Must be prepared to start with a Query or a bare expression tree.
*/
query_or_expression_tree_walker(node,
substitute_multiple_relids_walker,
(void *) &context,
0);
}
/*
* fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
*
* When we pull up a subquery, any AppendRelInfo references to the subquery's
* RT index have to be replaced by the substituted relid (and there had better
* be only one). We also need to apply substitute_multiple_relids to their
* translated_vars lists, since those might contain PlaceHolderVars.
*
* We assume we may modify the AppendRelInfo nodes in-place.
*/
static void
fix_append_rel_relids(List *append_rel_list, int varno, Relids subrelids)
{
ListCell *l;
int subvarno = -1;
/*
* We only want to extract the member relid once, but we mustn't fail
* immediately if there are multiple members; it could be that none of the
* AppendRelInfo nodes refer to it. So compute it on first use. Note that
* bms_singleton_member will complain if set is not singleton.
*/
foreach(l, append_rel_list)
{
AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
/* The parent_relid shouldn't ever be a pullup target */
Assert(appinfo->parent_relid != varno);
if (appinfo->child_relid == varno)
{
if (subvarno < 0)
subvarno = bms_singleton_member(subrelids);
appinfo->child_relid = subvarno;
}
/* Also finish fixups for its translated vars */
substitute_multiple_relids((Node *) appinfo->translated_vars,
varno, subrelids);
}
}
/*
* get_relids_in_jointree: get set of RT indexes present in a jointree
*
* If include_joins is true, join RT indexes are included; if false,
* only base rels are included.
*/
Relids
get_relids_in_jointree(Node *jtnode, bool include_joins)
{
Relids result = NULL;
if (jtnode == NULL)
return result;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
result = bms_make_singleton(varno);
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
result = bms_join(result,
get_relids_in_jointree(lfirst(l),
include_joins));
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
result = get_relids_in_jointree(j->larg, include_joins);
result = bms_join(result,
get_relids_in_jointree(j->rarg, include_joins));
if (include_joins && j->rtindex)
result = bms_add_member(result, j->rtindex);
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return result;
}
/*
* get_relids_for_join: get set of base RT indexes making up a join
*/
Relids
get_relids_for_join(PlannerInfo *root, int joinrelid)
{
Node *jtnode;
jtnode = find_jointree_node_for_rel((Node *) root->parse->jointree,
joinrelid);
if (!jtnode)
elog(ERROR, "could not find join node %d", joinrelid);
return get_relids_in_jointree(jtnode, false);
}
/*
* find_jointree_node_for_rel: locate jointree node for a base or join RT index
*
* Returns NULL if not found
*/
static Node *
find_jointree_node_for_rel(Node *jtnode, int relid)
{
if (jtnode == NULL)
return NULL;
if (IsA(jtnode, RangeTblRef))
{
int varno = ((RangeTblRef *) jtnode)->rtindex;
if (relid == varno)
return jtnode;
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
{
jtnode = find_jointree_node_for_rel(lfirst(l), relid);
if (jtnode)
return jtnode;
}
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
if (relid == j->rtindex)
return jtnode;
jtnode = find_jointree_node_for_rel(j->larg, relid);
if (jtnode)
return jtnode;
jtnode = find_jointree_node_for_rel(j->rarg, relid);
if (jtnode)
return jtnode;
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
return NULL;
}
| Java |
/*
* This is a plugin for GIMP.
*
* Copyright (C) 1997 Xavier Bouchoux
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* This plug-in produces sinus textures.
*
* Please send any patches or suggestions to me: Xavier.Bouchoux@ensimag.imag.fr.
*/
/* Version 0.99 */
#include "config.h"
#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>
#include "libgimp/stdplugins-intl.h"
#define PLUG_IN_PROC "plug-in-sinus"
#define PLUG_IN_BINARY "sinus"
#define PLUG_IN_ROLE "gimp-sinus"
/*
* This structure is used for persistent data.
*/
#define B_W 0L /* colors setting */
#define USE_FG_BG 1L
#define USE_COLORS 2L
#define LINEAR 0L /* colorization settings */
#define BILINEAR 1L
#define SINUS 2L
#define IDEAL 0L /* Perturbation settings */
#define PERTURBED 1L
typedef struct
{
gdouble scalex;
gdouble scaley;
gdouble cmplx;
gdouble blend_power;
guint32 seed;
gint tiling;
glong perturbation;
glong colorization;
glong colors;
GimpRGB col1;
GimpRGB col2;
gboolean random_seed;
} SinusVals;
static SinusVals svals =
{
15.0,
15.0,
1.0,
0.0,
42,
TRUE,
PERTURBED,
LINEAR,
USE_COLORS,
{ 1.0, 1.0, 0.0, 1.0 },
{ 0.0, 0.0, 1.0, 1.0 },
FALSE
};
typedef struct
{
gint height, width;
gdouble c11, c12, c13, c21, c22, c23, c31, c32, c33;
gdouble (*blend) (double );
guchar r, g, b, a;
gint dr, dg, db, da;
} params;
typedef struct
{
gint width;
gint height;
gint bpp;
gdouble scale;
guchar *bits;
} mwPreview;
static gboolean drawable_is_grayscale = FALSE;
static mwPreview *thePreview;
static GimpDrawable *drawable;
/* preview stuff -- to be removed as soon as we have a real libgimp preview */
#define PREVIEW_SIZE 100
static gboolean do_preview = TRUE;
static GtkWidget * mw_preview_new (GtkWidget *parent,
mwPreview *mwp);
static mwPreview * mw_preview_build_virgin (GimpDrawable *drw);
/* Declare functions */
static void query (void);
static void run (const gchar *name,
gint nparams,
const GimpParam *param,
gint *nreturn_vals,
GimpParam **return_vals);
static void sinus (void);
static gdouble linear (gdouble v);
static gdouble bilinear (gdouble v);
static gdouble cosinus (gdouble v);
static gint sinus_dialog (void);
static void sinus_do_preview (GtkWidget *widget);
static void assign_block_4 (guchar *dest, gdouble grey, params *p);
static void assign_block_3 (guchar *dest, gdouble grey, params *p);
static void assign_block_2 (guchar *dest, gdouble grey, params *p);
static void assign_block_1 (guchar *dest, gdouble grey, params *p);
static void compute_block_x (guchar *dest_row,
guint rowstride,
gint x0, gint y0, gint w, gint h,
gint bpp,
void (*assign)(guchar *dest, gdouble grey,
params *p),
params *p);
const GimpPlugInInfo PLUG_IN_INFO =
{
NULL, /* init_proc */
NULL, /* quit_proc */
query, /* query_proc */
run, /* run_proc */
};
MAIN ()
static void
query (void)
{
static const GimpParamDef args[] =
{
{ GIMP_PDB_INT32, "run-mode", "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" },
{ GIMP_PDB_IMAGE, "image", "Input image (unused)" },
{ GIMP_PDB_DRAWABLE, "drawable", "Input drawable" },
{ GIMP_PDB_FLOAT, "xscale", "Scale value for x axis" },
{ GIMP_PDB_FLOAT, "yscale", "Scale value dor y axis" },
{ GIMP_PDB_FLOAT, "complex", "Complexity factor" },
{ GIMP_PDB_INT32, "seed", "Seed value for random number generator" },
{ GIMP_PDB_INT32, "tiling", "If set, the pattern generated will tile" },
{ GIMP_PDB_INT32, "perturb", "If set, the pattern is a little more distorted..." },
{ GIMP_PDB_INT32, "colors", "where to take the colors (0= B&W, 1= fg/bg, 2= col1/col2)"},
{ GIMP_PDB_COLOR, "col1", "fist color (sometimes unused)" },
{ GIMP_PDB_COLOR, "col2", "second color (sometimes unused)" },
{ GIMP_PDB_FLOAT, "alpha1", "alpha for the first color (used if the drawable has an alpha chanel)" },
{ GIMP_PDB_FLOAT, "alpha2", "alpha for the second color (used if the drawable has an alpha chanel)" },
{ GIMP_PDB_INT32, "blend", "0= linear, 1= bilinear, 2= sinusoidal" },
{ GIMP_PDB_FLOAT, "blend-power", "Power used to strech the blend" }
};
gimp_install_procedure (PLUG_IN_PROC,
N_("Generate complex sinusoidal textures"),
"FIX ME: sinus help",
"Xavier Bouchoux",
"Xavier Bouchoux",
"1997",
N_("_Sinus..."),
"RGB*, GRAY*",
GIMP_PLUGIN,
G_N_ELEMENTS (args), 0,
args, NULL);
gimp_plugin_menu_register (PLUG_IN_PROC, "<Image>/Filters/Render/Pattern");
}
static void
run (const gchar *name,
gint nparams,
const GimpParam *param,
gint *nreturn_vals,
GimpParam **return_vals)
{
static GimpParam values[1];
GimpRunMode run_mode;
GimpPDBStatusType status = GIMP_PDB_SUCCESS;
run_mode = param[0].data.d_int32;
*nreturn_vals = 1;
*return_vals = values;
values[0].type = GIMP_PDB_STATUS;
values[0].data.d_status = status;
INIT_I18N ();
switch (run_mode)
{
case GIMP_RUN_INTERACTIVE:
/* Possibly retrieve data */
gimp_get_data (PLUG_IN_PROC, &svals);
/* In order to prepare the dialog I need to know whether it's grayscale or not */
drawable = gimp_drawable_get (param[2].data.d_drawable);
thePreview = mw_preview_build_virgin(drawable);
drawable_is_grayscale = gimp_drawable_is_gray (drawable->drawable_id);
if (! sinus_dialog ())
return;
break;
case GIMP_RUN_NONINTERACTIVE:
/* Make sure all the arguments are there! */
if (nparams != 17)
{
status = GIMP_PDB_CALLING_ERROR;
}
else
{
svals.scalex = param[3].data.d_float;
svals.scaley = param[4].data.d_float;
svals.cmplx = param[5].data.d_float;
svals.seed = param[6].data.d_int32;
svals.tiling = param[7].data.d_int32;
svals.perturbation = param[8].data.d_int32;
svals.colors = param[9].data.d_int32;
svals.col1 = param[10].data.d_color;
svals.col2 = param[11].data.d_color;
gimp_rgb_set_alpha (&svals.col1, param[12].data.d_float);
gimp_rgb_set_alpha (&svals.col2, param[13].data.d_float);
svals.colorization = param[14].data.d_int32;
svals.blend_power = param[15].data.d_float;
if (svals.random_seed)
svals.seed = g_random_int ();
}
break;
case GIMP_RUN_WITH_LAST_VALS:
/* Possibly retrieve data */
gimp_get_data (PLUG_IN_PROC, &svals);
if (svals.random_seed)
svals.seed = g_random_int ();
break;
default:
break;
}
/* Get the specified drawable */
drawable = gimp_drawable_get (param[2].data.d_drawable);
/* Make sure that the drawable is gray or RGB */
if ((status == GIMP_PDB_SUCCESS) &&
(gimp_drawable_is_rgb (drawable->drawable_id) ||
gimp_drawable_is_gray (drawable->drawable_id)))
{
gimp_progress_init (_("Sinus: rendering"));
gimp_tile_cache_ntiles (1);
sinus ();
if (run_mode != GIMP_RUN_NONINTERACTIVE)
gimp_displays_flush ();
/* Store data */
if (run_mode == GIMP_RUN_INTERACTIVE)
gimp_set_data (PLUG_IN_PROC, &svals, sizeof (SinusVals));
}
else
{
status = GIMP_PDB_EXECUTION_ERROR;
}
values[0].data.d_status = status;
gimp_drawable_detach (drawable);
}
/*
* Main procedure
*/
static void
prepare_coef (params *p)
{
GimpRGB color1;
GimpRGB color2;
gdouble scalex = svals.scalex;
gdouble scaley = svals.scaley;
GRand *gr;
gr = g_rand_new ();
g_rand_set_seed (gr, svals.seed);
switch (svals.colorization)
{
case BILINEAR:
p->blend = bilinear;
break;
case SINUS:
p->blend = cosinus;
break;
case LINEAR:
default:
p->blend = linear;
}
if (svals.perturbation==IDEAL)
{
/* Presumably the 0 * g_rand_int ()s are to pop random
* values off the prng, I don't see why though. */
p->c11= 0 * g_rand_int (gr);
p->c12= g_rand_double_range (gr, -1, 1) * scaley;
p->c13= g_rand_double_range (gr, 0, 2 * G_PI);
p->c21= 0 * g_rand_int (gr);
p->c22= g_rand_double_range (gr, -1, 1) * scaley;
p->c23= g_rand_double_range (gr, 0, 2 * G_PI);
p->c31= g_rand_double_range (gr, -1, 1) * scalex;
p->c32= 0 * g_rand_int (gr);
p->c33= g_rand_double_range (gr, 0, 2 * G_PI);
}
else
{
p->c11= g_rand_double_range (gr, -1, 1) * scalex;
p->c12= g_rand_double_range (gr, -1, 1) * scaley;
p->c13= g_rand_double_range (gr, 0, 2 * G_PI);
p->c21= g_rand_double_range (gr, -1, 1) * scalex;
p->c22= g_rand_double_range (gr, -1, 1) * scaley;
p->c23= g_rand_double_range (gr, 0, 2 * G_PI);
p->c31= g_rand_double_range (gr, -1, 1) * scalex;
p->c32= g_rand_double_range (gr, -1, 1) * scaley;
p->c33= g_rand_double_range (gr, 0, 2 * G_PI);
}
if (svals.tiling)
{
p->c11= ROUND (p->c11/(2*G_PI))*2*G_PI;
p->c12= ROUND (p->c12/(2*G_PI))*2*G_PI;
p->c21= ROUND (p->c21/(2*G_PI))*2*G_PI;
p->c22= ROUND (p->c22/(2*G_PI))*2*G_PI;
p->c31= ROUND (p->c31/(2*G_PI))*2*G_PI;
p->c32= ROUND (p->c32/(2*G_PI))*2*G_PI;
}
color1 = svals.col1;
color2 = svals.col2;
if (drawable_is_grayscale)
{
gimp_rgb_set (&color1, 1.0, 1.0, 1.0);
gimp_rgb_set (&color2, 0.0, 0.0, 0.0);
}
else
{
switch (svals.colors)
{
case USE_COLORS:
break;
case B_W:
gimp_rgb_set (&color1, 1.0, 1.0, 1.0);
gimp_rgb_set (&color2, 0.0, 0.0, 0.0);
break;
case USE_FG_BG:
gimp_context_get_background (&color1);
gimp_context_get_foreground (&color2);
break;
}
}
gimp_rgba_get_uchar (&color1, &p->r, &p->g, &p->b, &p->a);
gimp_rgba_subtract (&color2, &color1);
p->dr = color2.r * 255.0;
p->dg = color2.g * 255.0;
p->db = color2.b * 255.0;
p->da = color2.a * 255.0;
g_rand_free (gr);
}
static void
sinus (void)
{
params p;
gint bytes;
GimpPixelRgn dest_rgn;
gint x1, y1, x2, y2;
gpointer pr;
gint progress, max_progress;
prepare_coef(&p);
gimp_drawable_mask_bounds(drawable->drawable_id, &x1, &y1, &x2, &y2);
p.width = drawable->width;
p.height = drawable->height;
bytes = drawable->bpp;
gimp_pixel_rgn_init (&dest_rgn, drawable,
x1, y1, x2 - x1, y2 - y1, TRUE,TRUE);
progress = 0;
max_progress = (x2 - x1) * (y2 - y1);
for (pr = gimp_pixel_rgns_register (1, &dest_rgn);
pr != NULL;
pr = gimp_pixel_rgns_process (pr))
{
switch (bytes)
{
case 4:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
4, assign_block_4, &p);
break;
case 3:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
3, assign_block_3, &p);
break;
case 2:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
2, assign_block_2, &p);
break;
case 1:
compute_block_x (dest_rgn.data, dest_rgn.rowstride,
dest_rgn.x, dest_rgn.y, dest_rgn.w, dest_rgn.h,
1, assign_block_1, &p);
break;
}
progress += dest_rgn.w * dest_rgn.h;
gimp_progress_update ((double) progress / (double) max_progress);
}
gimp_progress_update (1.0);
gimp_drawable_flush (drawable);
gimp_drawable_merge_shadow (drawable->drawable_id, TRUE);
gimp_drawable_update (drawable->drawable_id, x1, y1, x2 - x1, y2 - y1);
}
static gdouble
linear (gdouble v)
{
double a = v - (int) v;
return (a < 0 ? 1.0 + a : a);
}
static gdouble
bilinear (gdouble v)
{
double a = v - (int) v;
a = (a < 0 ? 1.0 + a : a);
return (a > 0.5 ? 2 - 2 * a : 2 * a);
}
static gdouble
cosinus (gdouble v)
{
return 0.5 - 0.5 * sin ((v + 0.25) * G_PI * 2);
}
static void
assign_block_4 (guchar *dest, gdouble grey, params *p)
{
dest[0] = p->r + (gint) (grey * p->dr);
dest[1] = p->g + (gint) (grey * p->dg);
dest[2] = p->b + (gint) (grey * p->db);
dest[3] = p->a + (gint) (grey * p->da);
}
static void
assign_block_3 (guchar *dest, gdouble grey, params *p)
{
dest[0] = p->r + (gint) (grey * p->dr);
dest[1] = p->g + (gint) (grey * p->dg);
dest[2] = p->b + (gint) (grey * p->db);
}
static void
assign_block_2 (guchar *dest, gdouble grey, params *p)
{
dest[0] = (guchar) (grey * 255.0);
dest[1] = p->a + (gint)(grey * p->da);
}
static void
assign_block_1 (guchar *dest, gdouble grey, params *p)
{
dest[0]= (guchar) (grey * 255.0);
}
static void
compute_block_x (guchar *dest_row, guint rowstride,
gint x0, gint y0, gint w, gint h,
gint bpp,
void (*assign)(guchar *dest, gdouble grey, params *p),
params *p)
{
gint i, j;
gdouble x, y, grey;
gdouble pow_exp;
guchar *dest;
pow_exp = exp (svals.blend_power);
for (j = y0; j < y0 + h; j++)
{
y= ((gdouble) j) / p->height;
dest = dest_row;
for (i = x0; i < x0 + w; i++)
{
gdouble c;
x = ((gdouble) i) / p->width;
c = 0.5 * sin(p->c31 * x + p->c32 * y + p->c33);
grey = sin(p->c11 * x + p->c12 * y + p->c13) * (0.5 + 0.5 * c) +
sin(p->c21 * x + p->c22 * y + p->c23) * (0.5 - 0.5 * c);
grey = pow(p->blend(svals.cmplx * (0.5 + 0.5 * grey)), pow_exp);
assign (dest, grey, p);
dest += bpp;
}
dest_row += rowstride;
}
}
static void
alpha_scale_cb (GtkAdjustment *adj,
gpointer data)
{
GimpColorButton *color_button;
GimpRGB color;
if (!data)
return;
color_button = GIMP_COLOR_BUTTON (data);
gimp_color_button_get_color (GIMP_COLOR_BUTTON (color_button), &color);
gimp_rgb_set_alpha (&color, gtk_adjustment_get_value (adj));
gimp_color_button_set_color (GIMP_COLOR_BUTTON (color_button), &color);
}
static void
alpha_scale_update (GtkWidget *color_button,
gpointer data)
{
GtkAdjustment *adj;
GimpRGB color;
adj = GTK_ADJUSTMENT (data);
gimp_color_button_get_color (GIMP_COLOR_BUTTON (color_button), &color);
gtk_adjustment_set_value (adj, color.a);
sinus_do_preview (NULL);
}
static void
sinus_toggle_button_update (GtkWidget *widget,
gpointer data)
{
gimp_toggle_button_update (widget, data);
sinus_do_preview (NULL);
}
static void
sinus_radio_button_update (GtkWidget *widget,
gpointer data)
{
gimp_radio_button_update (widget, data);
sinus_do_preview (NULL);
}
static void
sinus_double_adjustment_update (GtkAdjustment *adjustment,
gpointer data)
{
gimp_double_adjustment_update (adjustment, data);
sinus_do_preview (NULL);
}
static void
sinus_random_update (GObject *unused,
gpointer data)
{
sinus_do_preview (NULL);
}
/*****************************************/
/* The note book */
/*****************************************/
static gint
sinus_dialog (void)
{
GtkWidget *dlg;
GtkWidget *main_hbox;
GtkWidget *preview;
GtkWidget *notebook;
GtkWidget *page;
GtkWidget *frame;
GtkWidget *label;
GtkWidget *vbox;
GtkWidget *vbox2;
GtkWidget *hbox;
GtkWidget *table;
GtkWidget *toggle;
GtkWidget *push_col1 = NULL;
GtkWidget *push_col2 = NULL;
GtkAdjustment *adj;
gboolean run;
gimp_ui_init (PLUG_IN_BINARY, TRUE);
/* Create Main window with a vbox */
/* ============================== */
dlg = gimp_dialog_new (_("Sinus"), PLUG_IN_ROLE,
NULL, 0,
gimp_standard_help_func, PLUG_IN_PROC,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OK, GTK_RESPONSE_OK,
NULL);
gtk_dialog_set_alternative_button_order (GTK_DIALOG (dlg),
GTK_RESPONSE_OK,
GTK_RESPONSE_CANCEL,
-1);
gimp_window_set_transient (GTK_WINDOW (dlg));
main_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (main_hbox), 12);
gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))),
main_hbox, TRUE, TRUE, 0);
gtk_widget_show (main_hbox);
/* Create preview */
/* ============== */
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (main_hbox), vbox, FALSE, FALSE, 0);
gtk_widget_show (vbox);
preview = mw_preview_new (vbox, thePreview);
/* Create the notebook */
/* =================== */
notebook = gtk_notebook_new ();
gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
gtk_box_pack_start (GTK_BOX (main_hbox), notebook, FALSE, FALSE, 0);
gtk_widget_show (notebook);
/* Create the drawing settings frame */
/* ================================= */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
frame = gimp_frame_new (_("Drawing Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
table = gtk_table_new (3, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_table_set_row_spacings (GTK_TABLE (table), 6);
gtk_container_add (GTK_CONTAINER(frame), table);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("_X scale:"), 140, 8,
svals.scalex, 0.0001, 100.0, 0.0001, 5, 4,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.scalex);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 1,
_("_Y scale:"), 140, 8,
svals.scaley, 0.0001, 100.0, 0.0001, 5, 4,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.scaley);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 2,
_("Co_mplexity:"), 140, 8,
svals.cmplx, 0.0, 15.0, 0.01, 5, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.cmplx);
gtk_widget_show (table);
frame= gimp_frame_new (_("Calculation Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
table = gtk_table_new (3, 1, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
hbox = gimp_random_seed_new (&svals.seed, &svals.random_seed);
label = gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
_("R_andom seed:"), 1.0, 0.5,
hbox, 1, TRUE);
gtk_label_set_mnemonic_widget (GTK_LABEL (label),
GIMP_RANDOM_SEED_SPINBUTTON (hbox));
g_signal_connect (GIMP_RANDOM_SEED_SPINBUTTON_ADJ (hbox),
"value-changed", G_CALLBACK (sinus_random_update), NULL);
gtk_widget_show (table);
toggle = gtk_check_button_new_with_mnemonic (_("_Force tiling?"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), svals.tiling);
gtk_box_pack_start (GTK_BOX (vbox), toggle, FALSE, FALSE, 0);
gtk_widget_show (toggle);
g_signal_connect (toggle, "toggled",
G_CALLBACK (sinus_toggle_button_update),
&svals.tiling);
vbox2 = gimp_int_radio_group_new (FALSE, NULL,
G_CALLBACK (sinus_radio_button_update),
&svals.perturbation, svals.perturbation,
_("_Ideal"), IDEAL, NULL,
_("_Distorted"), PERTURBED, NULL,
NULL);
gtk_box_pack_start (GTK_BOX (vbox), vbox2, FALSE, FALSE, 0);
gtk_widget_show (vbox2);
label = gtk_label_new_with_mnemonic (_("_Settings"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
/* Color settings dialog: */
/* ====================== */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
if (drawable_is_grayscale)
{
frame = gimp_frame_new (_("Colors"));
gtk_box_pack_start(GTK_BOX(page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
/*if in grey scale, the colors are necessarily black and white */
label = gtk_label_new (_("The colors are white and black."));
gtk_misc_set_alignment (GTK_MISC (label), 0.5, 0.5);
gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
gtk_widget_show (label);
}
else
{
frame = gimp_int_radio_group_new (TRUE, _("Colors"),
G_CALLBACK (sinus_radio_button_update),
&svals.colors, svals.colors,
_("Bl_ack & white"),
B_W, NULL,
_("_Foreground & background"),
USE_FG_BG, NULL,
_("C_hoose here:"),
USE_COLORS, NULL,
NULL);
gtk_box_pack_start(GTK_BOX(page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
vbox = gtk_bin_get_child (GTK_BIN (frame));
hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 12);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
push_col1 = gimp_color_button_new (_("First color"), 32, 32,
&svals.col1,
GIMP_COLOR_AREA_SMALL_CHECKS);
gtk_box_pack_start (GTK_BOX (hbox), push_col1, FALSE, FALSE, 0);
gtk_widget_show (push_col1);
g_signal_connect (push_col1, "color-changed",
G_CALLBACK (gimp_color_button_get_color),
&svals.col1);
push_col2 = gimp_color_button_new (_("Second color"), 32, 32,
&svals.col2,
GIMP_COLOR_AREA_SMALL_CHECKS);
gtk_box_pack_start (GTK_BOX (hbox), push_col2, FALSE, FALSE, 0);
gtk_widget_show (push_col2);
g_signal_connect (push_col2, "color-changed",
G_CALLBACK (gimp_color_button_get_color),
&svals.col2);
gtk_widget_show (hbox);
}
frame = gimp_frame_new (_("Alpha Channels"));
gtk_box_pack_start (GTK_BOX (page), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
gtk_widget_set_sensitive (frame,
gimp_drawable_has_alpha (drawable->drawable_id));
table = gtk_table_new (2, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_table_set_row_spacings (GTK_TABLE (table), 6);
gtk_container_add (GTK_CONTAINER (frame), table);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("F_irst color:"), 0, 0,
svals.col1.a, 0.0, 1.0, 0.01, 0.1, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (alpha_scale_cb),
push_col1);
if (push_col1)
g_signal_connect (push_col1, "color-changed",
G_CALLBACK (alpha_scale_update),
adj);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 1,
_("S_econd color:"), 0, 0,
svals.col2.a, 0.0, 1.0, 0.01, 0.1, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (alpha_scale_cb),
push_col2);
if (push_col2)
g_signal_connect (push_col2, "color-changed",
G_CALLBACK (alpha_scale_update),
adj);
gtk_widget_show (table);
label = gtk_label_new_with_mnemonic (_("Co_lors"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
/* blend settings dialog: */
/* ====================== */
page = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_set_border_width (GTK_CONTAINER (page), 12);
frame = gimp_frame_new (_("Blend Settings"));
gtk_box_pack_start (GTK_BOX (page), frame, TRUE, TRUE, 0);
gtk_widget_show (frame);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 12);
gtk_container_add (GTK_CONTAINER (frame), vbox);
gtk_widget_show (vbox);
frame =
gimp_int_radio_group_new (TRUE, _("Gradient"),
G_CALLBACK (sinus_radio_button_update),
&svals.colorization, svals.colorization,
_("L_inear"), LINEAR, NULL,
_("Bili_near"), BILINEAR, NULL,
_("Sin_usoidal"), SINUS, NULL,
NULL);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
table = gtk_table_new (1, 3, FALSE);
gtk_table_set_col_spacings (GTK_TABLE (table), 6);
gtk_box_pack_start (GTK_BOX (vbox), table, TRUE, TRUE, 0);
adj = gimp_scale_entry_new (GTK_TABLE (table), 0, 0,
_("_Exponent:"), 0, 0,
svals.blend_power, -7.5, 7.5, 0.01, 5.0, 2,
TRUE, 0, 0,
NULL, NULL);
g_signal_connect (adj, "value-changed",
G_CALLBACK (sinus_double_adjustment_update),
&svals.blend_power);
gtk_widget_show (table);
label = gtk_label_new_with_mnemonic (_("_Blend"));
gtk_notebook_append_page (GTK_NOTEBOOK (notebook), page, label);
gtk_widget_show (page);
gtk_widget_show (dlg);
sinus_do_preview (preview);
run = (gimp_dialog_run (GIMP_DIALOG (dlg)) == GTK_RESPONSE_OK);
gtk_widget_destroy (dlg);
return run;
}
/******************************************************************/
/* Draw preview image. if DoCompute is TRUE then recompute image. */
/******************************************************************/
static void
sinus_do_preview (GtkWidget *widget)
{
static GtkWidget *theWidget = NULL;
gint rowsize;
guchar *buf;
params p;
if (!do_preview)
return;
if (theWidget == NULL)
{
theWidget = widget;
}
rowsize = thePreview->width * thePreview->bpp;
buf = g_new (guchar, thePreview->width*thePreview->height*thePreview->bpp);
p.height = thePreview->height;
p.width = thePreview->width;
prepare_coef (&p);
if (thePreview->bpp == 3) /* [dindinx]: it looks to me that this is always true... */
compute_block_x (buf, rowsize, 0, 0, thePreview->width, thePreview->height,
3, assign_block_3, &p);
else if (thePreview->bpp == 1)
{
compute_block_x (buf, rowsize, 0, 0, thePreview->width,
thePreview->height, 1, assign_block_1, &p);
}
gimp_preview_area_draw (GIMP_PREVIEW_AREA (theWidget),
0, 0, thePreview->width, thePreview->height,
GIMP_RGB_IMAGE,
buf,
rowsize);
g_free (buf);
}
static void
mw_preview_toggle_callback (GtkWidget *widget,
gpointer data)
{
gimp_toggle_button_update (widget, data);
sinus_do_preview (NULL);
}
static mwPreview *
mw_preview_build_virgin (GimpDrawable *drw)
{
mwPreview *mwp;
mwp = g_new (mwPreview, 1);
if (drw->width > drw->height)
{
mwp->scale = (gdouble) drw->width / (gdouble) PREVIEW_SIZE;
mwp->width = PREVIEW_SIZE;
mwp->height = drw->height / mwp->scale;
}
else
{
mwp->scale = (gdouble) drw->height / (gdouble) PREVIEW_SIZE;
mwp->height = PREVIEW_SIZE;
mwp->width = drw->width / mwp->scale;
}
mwp->bpp = 3;
mwp->bits = NULL;
return mwp;
}
static GtkWidget *
mw_preview_new (GtkWidget *parent,
mwPreview *mwp)
{
GtkWidget *preview;
GtkWidget *frame;
GtkWidget *vbox;
GtkWidget *button;
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 6);
gtk_box_pack_start (GTK_BOX (parent), vbox, FALSE, FALSE, 0);
gtk_widget_show (vbox);
frame = gtk_aspect_frame_new (NULL, 0.5, 0.5, 1, TRUE);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
gtk_widget_show (frame);
preview = gimp_preview_area_new ();
gtk_widget_set_size_request (preview, mwp->width, mwp->height);
gtk_container_add (GTK_CONTAINER (frame), preview);
gtk_widget_show (preview);
button = gtk_check_button_new_with_mnemonic (_("Do _preview"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), do_preview);
gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
gtk_widget_show (button);
g_signal_connect (button, "toggled",
G_CALLBACK (mw_preview_toggle_callback),
&do_preview);
return preview;
}
| Java |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package mod
* @subpackage coursework
* @copyright 2011 University of London Computer Centre {@link ulcc.ac.uk}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(__FILE__) . '/../../../../config.php');
global $CFG, $USER;
$submissionid = required_param('submissionid', PARAM_INT);
$cmid = optional_param('cmid', 0, PARAM_INT);
$feedbackid = optional_param('feedbackid', 0, PARAM_INT);
$assessorid = optional_param('assessorid', $USER->id, PARAM_INT);
$stage_identifier = optional_param('stage_identifier', 'uh-oh', PARAM_RAW);
$params = array(
'submissionid' => $submissionid,
'cmid' => $cmid,
'feedbackid' => $feedbackid,
'assessorid' => $assessorid,
'stage_identifier' => $stage_identifier,
);
$controller = new mod_coursework\controllers\feedback_controller($params);
$controller->new_feedback(); | Java |
body, html {
margin: 0px;
background-color: black;
overflow: hidden;
height: 100%;
}
canvas[resize] {
width: 100%;
height: 100%;
}
#container {
display: flex;
height: 100vh;
align-content: center;
align-items: center;
position: absolute;
top: 0px;
}
video {
flex: 1 1 100vw;
align-self: center;
width: 100vw;
/*transform: translateY(-50%);*/
}
.draw {
position: absolute;
top: 0px;
left: 0px;
}
#render canvas{
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
#htmlUI {
position: absolute;
top: 0px;
background: #00AFEF;
width: 100vw;
height: 100vh;
} | Java |
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ofte.services.MetaDataCreations;
/**
* Servlet implementation class ScheduledTransferRemoteasDestination
*/
@SuppressWarnings("serial")
@WebServlet("/ScheduledTransferRemoteasDestination")
public class ScheduledTransferRemoteasDestination extends HttpServlet {
// private static final long serialVersionUID = 1L;
HashMap<String, String> hashMap = new HashMap<String, String>();
// com.ofte.services.MetaDataCreations metaDataCreations = new
// MetaDataCreations();
MetaDataCreations metaDataCreations = new MetaDataCreations();
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// read form fields
String schedulername = request.getParameter("schedulername");
// String jobName = request.getParameter("jname");
String sourceDirectory = request.getParameter("sd");
String sourceTriggerPattern = request.getParameter("stp");
String sourceFilePattern = request.getParameter("sfp");
String destinationDirectory = request.getParameter("dd");
String destinationFilePattern = request.getParameter("dfp");
String destinationTriggerPattern = request.getParameter("dtp");
String hostIp = request.getParameter("hostip");
String userName = request.getParameter("username");
String password = request.getParameter("password");
String port = request.getParameter("port");
String pollUnits = request.getParameter("pu");
String pollInterval = request.getParameter("pi");
// String XMLFilePath = request.getParameter("xmlfilename");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("-sn", schedulername);
// hashMap.put("-jn", jobName);
hashMap.put("-sd", sourceDirectory);
hashMap.put("-tr", sourceTriggerPattern);
hashMap.put("-sfp", sourceFilePattern);
hashMap.put("-sftp-d", destinationDirectory);
hashMap.put("-trd", destinationTriggerPattern);
hashMap.put("-hi", hostIp);
hashMap.put("-un", userName);
hashMap.put("-pw", password);
hashMap.put("-po", port);
hashMap.put("-pu", pollUnits);
hashMap.put("-pi", pollInterval);
hashMap.put("-dfp", destinationFilePattern);
// hashMap.put("-gt", XMLFilePath);
// System.out.println(hashMap);
// System.out.println("username: " + username);
// System.out.println("password: " + password);
// String str[] = {"-mn "+monitorName,"-jn "+jobName,"-sd
// "+sourceDirectory,"-tr "+sourceTriggerPattern,"-sfp
// "+sourceFilePattern,"-dd
// "+destinationDirectory,destinationFilePattern,"-trd
// "+destinationTriggerPattern,"-pu "+pollUnits,"-pi "+pollInterval,"-gt
// "+XMLFilePath};
// for(int i=0;i<str.length;i++) {
// System.out.println(str[i]);
// }
try {
// metaDataCreations.fetchingUIDetails(hashMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// String string = "-mn "+monitorName+",-jn "+jobName+",-pi
// "+pollInterval+",-pu "+pollUnits+",-dd "+destinationDirectory+" "+
// sourceDirectory+",-tr "+sourceTriggerPattern+",-trd
// "+destinationTriggerPattern+",-gt "+XMLFilePath+",-sfp
// "+sourceFilePattern;
// FileWriter fileWriter = new FileWriter("D:\\UIDetails.txt");
// fileWriter.write(string);
// fileWriter.close();
Runnable r = new Runnable() {
public void run() {
// runYourBackgroundTaskHere();
try {
metaDataCreations.fetchingUIDetails(hashMap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(r).start();
// Example example = new Example();
// hashMap.put("monitorName", monitorName);
// example.result("-mn "+monitorName+" -jn "+jobName+" -pi
// "+pollInterval+" -pu "+pollUnits+" -dd "+destinationDirectory+" "+
// sourceDirectory+" -tr "+sourceTriggerPattern+" -trd
// "+destinationTriggerPattern+" -gt "+XMLFilePath+" -sfp
// "+sourceFilePattern);
// do some processing here...
// get response writer
// PrintWriter writer = response.getWriter();
// build HTML code
// String htmlRespone = "<html>";
// htmlRespone += "<h2>Your username is: " + username + "<br/>";
// htmlRespone += "Your password is: " + password + "</h2>";
// htmlRespone += "</html>";
// return response
// writer.println(htmlRespone);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('successfully submited');");
out.println(
"window.open('http://localhost:8080/TestingUI/Open_OFTE_Scheduled_Transfers_Page.html','_self')");
out.println("</script>");
}
}
| Java |
package xde.lincore.mcscript.math;
public enum RoundingMethod {
Round, Floor, Ceil, CastInt;
public int round(final double value) {
switch (this) {
case Round:
return (int) Math.round(value);
case Floor:
return (int) Math.floor(value);
case Ceil:
return (int) Math.ceil(value);
case CastInt:
return (int) value;
default:
throw new UnsupportedOperationException();
}
}
public long roundToLong(final double value) {
switch (this) {
case Round:
return Math.round(value);
case Floor:
return (long) Math.floor(value);
case Ceil:
return (long) Math.ceil(value);
case CastInt:
return (long) value;
default:
throw new UnsupportedOperationException();
}
}
}
| Java |
package com.baselet.gwt.client.view;
import java.util.List;
import com.baselet.control.basics.geom.Rectangle;
import com.baselet.control.config.SharedConfig;
import com.baselet.control.enums.ElementId;
import com.baselet.element.Selector;
import com.baselet.element.interfaces.GridElement;
import com.baselet.gwt.client.element.ComponentGwt;
import com.baselet.gwt.client.element.ElementFactoryGwt;
import com.baselet.gwt.client.resources.HelptextFactory;
import com.baselet.gwt.client.resources.HelptextResources;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.CanvasElement;
import com.google.gwt.user.client.ui.FocusWidget;
public class DrawCanvas {
private final Canvas canvas = Canvas.createIfSupported();
/*
setScaling can be used to set the size the canvas for the next time draw() is used
DISCLAIMER: if scaling is set to anything other than 1, this WILL break the way selected elements are viewed,
furthermore the dragging will still remain the same and will not update to the new scale.
This function is solely meant to be used for high-res exporting of the diagram
*/
private double scaling = 1.0d;
private boolean scaleHasChangedSinceLastDraw = false;
public void setScaling(double scaling) {
this.scaling = scaling;
scaleHasChangedSinceLastDraw = true;
}
void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector, boolean forceRedraw) {
if (SharedConfig.getInstance().isDev_mode()) {
CanvasUtils.drawGridOn(getContext2d());
}
if (drawEmptyInfo && gridElements.isEmpty()) {
drawEmptyInfoText(getScaling());
}
else {
// if (tryOptimizedDrawing()) return;
for (GridElement ge : gridElements) {
if (forceRedraw) {
((ComponentGwt) ge.getComponent()).afterModelUpdate();
}
((ComponentGwt) ge.getComponent()).drawOn(getContext2d(), selector.isSelected(ge), getScaling());
}
}
if (selector instanceof SelectorNew && ((SelectorNew) selector).isLassoActive()) {
((SelectorNew) selector).drawLasso(getContext2d());
}
}
public void draw(boolean drawEmptyInfo, List<GridElement> gridElements, Selector selector) {
if (isScaleHasChangedSinceLastDraw()) {
draw(drawEmptyInfo, gridElements, selector, true);
setScaleHasChangedSinceLastDraw(false);
}
else {
draw(drawEmptyInfo, gridElements, selector, false);
}
}
public double getScaling() {
return scaling;
}
public boolean isScaleHasChangedSinceLastDraw() {
return scaleHasChangedSinceLastDraw;
}
public void setScaleHasChangedSinceLastDraw(boolean scaleHasChangedSinceLastDraw) {
this.scaleHasChangedSinceLastDraw = scaleHasChangedSinceLastDraw;
}
public Context2dWrapper getContext2d() {
return new Context2dGwtWrapper(canvas.getContext2d());
}
public void clearAndSetSize(int width, int height) {
// setCoordinateSpace always clears the canvas. To avoid that see https://groups.google.com/d/msg/google-web-toolkit/dpc84mHeKkA/3EKxrlyFCEAJ
canvas.setCoordinateSpaceWidth(width);
canvas.setCoordinateSpaceHeight(height);
}
public String toDataUrl(String type) {
return canvas.toDataUrl(type);
}
public void drawEmptyInfoText(double scaling) {
double elWidth = 440;
double elHeight = 246;
double elXPos = getWidth() / 2.0 - elWidth / 2;
double elYPos = getHeight() / 2.0 - elHeight / 2;
HelptextFactory factory = GWT.create(HelptextFactory.class);
HelptextResources resources = factory.getInstance();
String helptext = resources.helpText().getText();
GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), helptext, "", null);
((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, scaling);
}
/* used to display temporal invalid if vs code passes a wrong uxf */
void drawInvalidDiagramInfo() {
double elWidth = 440;
double elHeight = 246;
double elXPos = getWidth() / 2.0 - elWidth / 2;
double elYPos = getHeight() / 2.0 - elHeight / 2;
String invalidDiagramText = "valign=center\n" +
"halign=center\n" +
".uxf file is currently invalid and can't be displayed.\n" +
"Please revert changes or load a valid file";
GridElement emptyElement = ElementFactoryGwt.create(ElementId.Text, new Rectangle(elXPos, elYPos, elWidth, elHeight), invalidDiagramText, "", null);
((ComponentGwt) emptyElement.getComponent()).drawOn(getContext2d(), false, getScaling());
}
public int getWidth() {
return canvas.getCoordinateSpaceWidth();
}
public int getHeight() {
return canvas.getCoordinateSpaceHeight();
}
public CanvasElement getCanvasElement() {
return canvas.getCanvasElement();
}
public FocusWidget getWidget() {
return canvas;
}
// TODO would not work because canvas gets always resized and therefore cleaned -> so everything must be redrawn
// private boolean tryOptimizedDrawing() {
// List<GridElement> geToRedraw = new ArrayList<GridElement>();
// for (GridElement ge : gridElements) {
// if(((GwtComponent) ge.getComponent()).isRedrawNecessary()) {
// for (GridElement geRedraw : geToRedraw) {
// if (geRedraw.getRectangle().intersects(ge.getRectangle())) {
// return false;
// }
// }
// geToRedraw.add(ge);
// }
// }
//
// for (GridElement ge : gridElements) {
// elementCanvas.getContext2d().clearRect(0, 0, ge.getRectangle().getWidth(), ge.getRectangle().getHeight());
// ((GwtComponent) ge.getComponent()).drawOn(elementCanvas.getContext2d());
// }
// return true;
// }
}
| Java |
#!/usr/bin/env python
class Message(object):
"""
Base type of a message sent through the pipeline.
Define some attributes and methods to form your message.
I suggest you don't alter this class. You're are free to do so, of course. It's your own decision.
Though, I suggest you create your own message type and let it inherit from this class.
"""
pass
| Java |
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.internal.registry;
import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.input.ParserContext;
import com.sk89q.worldedit.extension.input.InputParseException;
import com.sk89q.worldedit.extension.input.NoMatchException;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* An abstract implementation of a factory for internal usage.
*
* @param <E> the element that the factory returns
*/
public abstract class AbstractFactory<E> {
protected final WorldEdit worldEdit;
protected final List<InputParser<E>> parsers = new ArrayList<InputParser<E>>();
/**
* Create a new factory.
*
* @param worldEdit the WorldEdit instance
*/
protected AbstractFactory(WorldEdit worldEdit) {
checkNotNull(worldEdit);
this.worldEdit = worldEdit;
}
public E parseFromInput(String input, ParserContext context) throws InputParseException {
E match;
for (InputParser<E> parser : parsers) {
match = parser.parseFromInput(input, context);
if (match != null) {
return match;
}
}
throw new NoMatchException("No match for '" + input + "'");
}
}
| Java |
# Install dependencies of the cloud_controller component
package "libmysqlclient-dev" do
action :install
end
| Java |
{% extends 'index.html' %} {% load static %}
{% load staticfiles %}
{% block css %}
<link href="/static/tools/style.css" rel="stylesheet" type="text/css" />
<link href="/static/tools/960.css" rel="stylesheet" type="text/css" />
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'>
{% endblock %}
{% block content %}
<div id="shim"></div>
<div id="content">
<div class="logo_box"><h1>Portal do Conhecimento<br/>&<br/>CMPaaS</h1></div>
<div class="main_box">
<h2>Este serviço está em construção.<br/><span>Estamos trabalhando para disponibilizá-lo em breve. Você pode ter mais informações pelos contatos:</span></h2>
<ul class="info">
<li>
<h3><i class="fa fa-phone"></i></h3>
<p>+55 (27) 4009-2061<br/>+55 (27) 4009-2817<br/>+55 (27) 4009-2124</p>
</li>
<li>
<h3><i class="fa fa-road"></i></h3>
<p>Laboratório de Informática na Educação<br/>
Departamento de Informática<br/>
Universidade Federal do Espírito Santo<br/>
Av. Fernando Ferrari, 514, 29075-910 - Vitória - ES, Brasil</p>
</li>
<li>
<h3><li><a href="https://www.facebook.com/cmpaas/"><i class="fa fa-facebook-square"></i></a>
</li></h3>
</li>
</ul>
</div>
{% endblock %}
{% block javascript %}
<script src="/static/js/cufon-yui.js"></script>
<script type="text/javascript">
Cufon.replace('h1,h3', {fontFamily: font-family: 'Fjalla One', hover:true})
</script>
{% endblock %} | Java |
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CampaignBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Mautic\ApiBundle\Serializer\Driver\ApiMetadataDriver;
use Mautic\CoreBundle\Doctrine\Mapping\ClassMetadataBuilder;
use Mautic\CoreBundle\Entity\FormEntity;
use Mautic\FormBundle\Entity\Form;
use Mautic\LeadBundle\Entity\LeadList;
use Mautic\LeadBundle\Form\Validator\Constraints\LeadListAccess;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Mapping\ClassMetadata;
/**
* Class Campaign
*
* @package Mautic\CampaignBundle\Entity
*/
class Campaign extends FormEntity
{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $description;
/**
* @var null|\DateTime
*/
private $publishUp;
/**
* @var null|\DateTime
*/
private $publishDown;
/**
* @var \Mautic\CategoryBundle\Entity\Category
**/
private $category;
/**
* @var ArrayCollection
*/
private $events;
/**
* @var ArrayCollection
*/
private $leads;
/**
* @var ArrayCollection
*/
private $lists;
/**
* @var ArrayCollection
*/
private $forms;
/**
* @var array
*/
private $canvasSettings = array();
/**
* Constructor
*/
public function __construct ()
{
$this->events = new ArrayCollection();
$this->leads = new ArrayCollection();
$this->lists = new ArrayCollection();
$this->forms = new ArrayCollection();
}
/**
*
*/
public function __clone()
{
$this->leads = new ArrayCollection();
$this->events = new ArrayCollection();
$this->lists = new ArrayCollection();
$this->forms = new ArrayCollection();
$this->id = null;
parent::__clone();
}
/**
* @param ORM\ClassMetadata $metadata
*/
public static function loadMetadata (ORM\ClassMetadata $metadata)
{
$builder = new ClassMetadataBuilder($metadata);
$builder->setTable('campaigns')
->setCustomRepositoryClass('Mautic\CampaignBundle\Entity\CampaignRepository');
$builder->addIdColumns();
$builder->addPublishDates();
$builder->addCategory();
$builder->createOneToMany('events', 'Event')
->setIndexBy('id')
->setOrderBy(array('order' => 'ASC'))
->mappedBy('campaign')
->cascadeAll()
->fetchExtraLazy()
->build();
$builder->createOneToMany('leads', 'Lead')
->setIndexBy('id')
->mappedBy('campaign')
->fetchExtraLazy()
->build();
$builder->createManyToMany('lists', 'Mautic\LeadBundle\Entity\LeadList')
->setJoinTable('campaign_leadlist_xref')
->setIndexBy('id')
->addInverseJoinColumn('leadlist_id', 'id', false, false, 'CASCADE')
->addJoinColumn('campaign_id', 'id', true, false, 'CASCADE')
->build();
$builder->createManyToMany('forms', 'Mautic\FormBundle\Entity\Form')
->setJoinTable('campaign_form_xref')
->setIndexBy('id')
->addInverseJoinColumn('form_id', 'id', false, false, 'CASCADE')
->addJoinColumn('campaign_id', 'id', true, false, 'CASCADE')
->build();
$builder->createField('canvasSettings', 'array')
->columnName('canvas_settings')
->nullable()
->build();
}
/**
* @param ClassMetadata $metadata
*/
public static function loadValidatorMetadata (ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new Assert\NotBlank(array(
'message' => 'mautic.core.name.required'
)));
}
/**
* Prepares the metadata for API usage
*
* @param $metadata
*/
public static function loadApiMetadata(ApiMetadataDriver $metadata)
{
$metadata->setGroupPrefix('campaign')
->addListProperties(
array(
'id',
'name',
'category',
'description'
)
)
->addProperties(
array(
'publishUp',
'publishDown',
'events',
'leads',
'forms',
'lists',
'canvasSettings'
)
)
->build();
}
/**
* @return array
*/
public function convertToArray ()
{
return get_object_vars($this);
}
/**
* @param string $prop
* @param mixed $val
*
* @return void
*/
protected function isChanged ($prop, $val)
{
$getter = "get" . ucfirst($prop);
$current = $this->$getter();
if ($prop == 'category') {
$currentId = ($current) ? $current->getId() : '';
$newId = ($val) ? $val->getId() : null;
if ($currentId != $newId) {
$this->changes[$prop] = array($currentId, $newId);
}
} elseif ($current != $val) {
$this->changes[$prop] = array($current, $val);
}
}
/**
* Get id
*
* @return integer
*/
public function getId ()
{
return $this->id;
}
/**
* Set description
*
* @param string $description
*
* @return Campaign
*/
public function setDescription ($description)
{
$this->isChanged('description', $description);
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription ()
{
return $this->description;
}
/**
* Set name
*
* @param string $name
*
* @return Campaign
*/
public function setName ($name)
{
$this->isChanged('name', $name);
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName ()
{
return $this->name;
}
/**
* Add events
*
* @param $key
* @param \Mautic\CampaignBundle\Entity\Event $event
*
* @return Campaign
*/
public function addEvent ($key, Event $event)
{
if ($changes = $event->getChanges()) {
$this->changes['events']['added'][$key] = array($key, $changes);
}
$this->events[$key] = $event;
return $this;
}
/**
* Remove events
*
* @param \Mautic\CampaignBundle\Entity\Event $event
*/
public function removeEvent (\Mautic\CampaignBundle\Entity\Event $event)
{
$this->changes['events']['removed'][$event->getId()] = $event->getName();
$this->events->removeElement($event);
}
/**
* Get events
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getEvents ()
{
return $this->events;
}
/**
* Set publishUp
*
* @param \DateTime $publishUp
*
* @return Campaign
*/
public function setPublishUp ($publishUp)
{
$this->isChanged('publishUp', $publishUp);
$this->publishUp = $publishUp;
return $this;
}
/**
* Get publishUp
*
* @return \DateTime
*/
public function getPublishUp ()
{
return $this->publishUp;
}
/**
* Set publishDown
*
* @param \DateTime $publishDown
*
* @return Campaign
*/
public function setPublishDown ($publishDown)
{
$this->isChanged('publishDown', $publishDown);
$this->publishDown = $publishDown;
return $this;
}
/**
* Get publishDown
*
* @return \DateTime
*/
public function getPublishDown ()
{
return $this->publishDown;
}
/**
* @return mixed
*/
public function getCategory ()
{
return $this->category;
}
/**
* @param mixed $category
*/
public function setCategory ($category)
{
$this->isChanged('category', $category);
$this->category = $category;
}
/**
* Add lead
*
* @param $key
* @param \Mautic\CampaignBundle\Entity\Lead $lead
*
* @return Campaign
*/
public function addLead ($key, Lead $lead)
{
$action = ($this->leads->contains($lead)) ? 'updated' : 'added';
$leadEntity = $lead->getLead();
$this->changes['leads'][$action][$leadEntity->getId()] = $leadEntity->getPrimaryIdentifier();
$this->leads[$key] = $lead;
return $this;
}
/**
* Remove lead
*
* @param Lead $lead
*/
public function removeLead (Lead $lead)
{
$leadEntity = $lead->getLead();
$this->changes['leads']['removed'][$leadEntity->getId()] = $leadEntity->getPrimaryIdentifier();
$this->leads->removeElement($lead);
}
/**
* Get leads
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getLeads ()
{
return $this->leads;
}
/**
* @return ArrayCollection
*/
public function getLists ()
{
return $this->lists;
}
/**
* Add list
*
* @param LeadList $list
* @return Campaign
*/
public function addList(LeadList $list)
{
$this->lists[] = $list;
$this->changes['lists']['added'][$list->getId()] = $list->getName();
return $this;
}
/**
* Remove list
*
* @param LeadList $list
*/
public function removeList(LeadList $list)
{
$this->changes['lists']['removed'][$list->getId()] = $list->getName();
$this->lists->removeElement($list);
}
/**
* @return ArrayCollection
*/
public function getForms()
{
return $this->forms;
}
/**
* Add form
*
* @param Form $form
*
* @return Campaign
*/
public function addForm(Form $form)
{
$this->forms[] = $form;
$this->changes['forms']['added'][$form->getId()] = $form->getName();
return $this;
}
/**
* Remove form
*
* @param Form $form
*/
public function removeForm(Form $form)
{
$this->changes['forms']['removed'][$form->getId()] = $form->getName();
$this->forms->removeElement($form);
}
/**
* @return mixed
*/
public function getCanvasSettings ()
{
return $this->canvasSettings;
}
/**
* @param array $canvasSettings
*/
public function setCanvasSettings (array $canvasSettings)
{
$this->canvasSettings = $canvasSettings;
}
}
| Java |
package com.derpgroup.livefinder.manager;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class TwitchFollowedStreamsResponse {
private TwitchStream[] streams;
public TwitchStream[] getStreams() {
return streams.clone();
}
public void setStreams(TwitchStream[] streams) {
this.streams = streams.clone();
}
@Override
public String toString() {
return "TwitchFollowedStreamsResponse [streams=" + Arrays.toString(streams)
+ "]";
}
}
| Java |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>ErrorToken - jgo.tools.compiler.lexer.ErrorToken</title>
<meta name="description" content="ErrorToken - jgo.tools.compiler.lexer.ErrorToken" />
<meta name="keywords" content="ErrorToken jgo.tools.compiler.lexer.ErrorToken" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript">
if(top === self) {
var url = '../../../../index.html';
var hash = 'jgo.tools.compiler.lexer.ErrorToken';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="type">
<div id="definition">
<img src="../../../../lib/class_big.png" />
<p id="owner"><a href="../../../package.html" class="extype" name="jgo">jgo</a>.<a href="../../package.html" class="extype" name="jgo.tools">tools</a>.<a href="../package.html" class="extype" name="jgo.tools.compiler">compiler</a>.<a href="package.html" class="extype" name="jgo.tools.compiler.lexer">lexer</a></p>
<h1>ErrorToken</h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">case class</span>
</span>
<span class="symbol">
<span class="name">ErrorToken</span><span class="params">(<span name="msg">msg: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result"> extends <a href="Token.html" class="extype" name="jgo.tools.compiler.lexer.Token">Token</a> with <span class="extype" name="scala.Product">Product</span> with <span class="extype" name="scala.Serializable">Serializable</span></span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.Serializable">Serializable</span>, <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.Product">Product</span>, <span class="extype" name="scala.Equals">Equals</span>, <a href="Token.html" class="extype" name="jgo.tools.compiler.lexer.Token">Token</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="jgo.tools.compiler.lexer.ErrorToken"><span>ErrorToken</span></li><li class="in" name="scala.Serializable"><span>Serializable</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.Product"><span>Product</span></li><li class="in" name="scala.Equals"><span>Equals</span></li><li class="in" name="jgo.tools.compiler.lexer.Token"><span>Token</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="constructors" class="members">
<h3>Instance Constructors</h3>
<ol><li name="jgo.tools.compiler.lexer.ErrorToken#<init>" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="<init>(msg:String):jgo.tools.compiler.lexer.ErrorToken"></a>
<a id="<init>:ErrorToken"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">new</span>
</span>
<span class="symbol">
<span class="name">ErrorToken</span><span class="params">(<span name="msg">msg: <span class="extype" name="scala.Predef.String">String</span></span>)</span>
</span>
</h4>
</li></ol>
</div>
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:AnyRef):Boolean"></a>
<a id="!=(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:AnyRef):Boolean"></a>
<a id="==(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="jgo.tools.compiler.lexer.ErrorToken#chars" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="chars:String"></a>
<a id="chars:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">chars</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="jgo.tools.compiler.lexer.ErrorToken">ErrorToken</a> → <a href="Token.html" class="extype" name="jgo.tools.compiler.lexer.Token">Token</a></dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="jgo.tools.compiler.lexer.ErrorToken#msg" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="msg:String"></a>
<a id="msg:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">msg</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="jgo.tools.compiler.lexer.Token#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="Token.html" class="extype" name="jgo.tools.compiler.lexer.Token">Token</a> → AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.Serializable">
<h3>Inherited from <span class="extype" name="scala.Serializable">Serializable</span></h3>
</div><div class="parent" name="java.io.Serializable">
<h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3>
</div><div class="parent" name="scala.Product">
<h3>Inherited from <span class="extype" name="scala.Product">Product</span></h3>
</div><div class="parent" name="scala.Equals">
<h3>Inherited from <span class="extype" name="scala.Equals">Equals</span></h3>
</div><div class="parent" name="jgo.tools.compiler.lexer.Token">
<h3>Inherited from <a href="Token.html" class="extype" name="jgo.tools.compiler.lexer.Token">Token</a></h3>
</div><div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
<script defer="defer" type="text/javascript" id="jquery-js" src="../../../../lib/jquery.js"></script><script defer="defer" type="text/javascript" id="jquery-ui-js" src="../../../../lib/jquery-ui.js"></script><script defer="defer" type="text/javascript" id="tools-tooltip-js" src="../../../../lib/tools.tooltip.js"></script><script defer="defer" type="text/javascript" id="template-js" src="../../../../lib/template.js"></script>
</body>
</html> | Java |
// Copyright 2015 ThoughtWorks, Inc.
//
// This file is part of Gauge-CSharp.
//
// Gauge-CSharp is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Gauge-CSharp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Gauge-CSharp. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using Gauge.CSharp.Lib;
using Gauge.CSharp.Runner.Models;
using Gauge.CSharp.Runner.Strategy;
namespace Gauge.CSharp.Runner
{
public interface ISandbox
{
// Used only from tests.
// Don't return Assembly here! assembly instance returned on sandbox side
// would be replaced by assembly instance on runner side, thus making any asserts on it useless.
string TargetLibAssemblyVersion { get; }
ExecutionResult ExecuteMethod(GaugeMethod gaugeMethod, params string[] args);
bool TryScreenCapture(out byte[] screenShotBytes);
List<GaugeMethod> GetStepMethods();
void InitializeDataStore(string dataStoreType);
IEnumerable<string> GetStepTexts(GaugeMethod gaugeMethod);
List<string> GetAllStepTexts();
void ClearObjectCache();
IEnumerable<string> GetAllPendingMessages();
IEnumerable<byte[]> GetAllPendingScreenshots();
void StartExecutionScope(string tag);
void CloseExectionScope();
ExecutionResult ExecuteHooks(string hookType, IHooksStrategy strategy, IList<string> applicableTags, object executionContext);
IEnumerable<string> Refactor(GaugeMethod methodInfo, IList<Tuple<int, int>> parameterPositions,
IList<string> parametersList, string newStepValue);
}
} | Java |
' Copyright 2012 Daniel Wagner O. de Medeiros
'
' This file is part of DWSIM.
'
' DWSIM is free software: you can redistribute it and/or modify
' it under the terms of the GNU General Public License as published by
' the Free Software Foundation, either version 3 of the License, or
' (at your option) any later version.
'
' DWSIM is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
' GNU General Public License for more details.
'
' You should have received a copy of the GNU General Public License
' along with DWSIM. If not, see <http://www.gnu.org/licenses/>.
Imports DWSIM.Thermodynamics.BaseClasses
Imports DWSIM.Thermodynamics.PropertyPackages
Imports System.IO
Public Class FormConfigPRSV2
Inherits FormConfigPropertyPackageBase
Public Loaded = False
Public param As System.Collections.Specialized.StringDictionary
Private Sub ConfigFormUNIQUAC_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FaTabStripItem1.Controls.Add(New PropertyPackageSettingsEditingControl(_pp) With {.Dock = DockStyle.Fill})
Loaded = False
Me.Text += " (" & _pp.Tag & ") [" + _pp.ComponentName + "]"
Me.KryptonDataGridView2.DataSource = Nothing
Me.FaTabStripItem2.Visible = True
Me.KryptonDataGridView2.Rows.Clear()
Dim nf As String = "0.0000"
If TypeOf _pp Is PRSV2PropertyPackage Then
Dim ppu As PRSV2PropertyPackage = _pp
For Each cp As ConstantProperties In _comps.Values
gt0: If ppu.m_pr.InteractionParameters.ContainsKey(cp.Name.ToLower) Then
For Each cp2 As ConstantProperties In _comps.Values
If cp.Name <> cp2.Name Then
If Not ppu.m_pr.InteractionParameters(cp.Name.ToLower).ContainsKey(cp2.Name.ToLower) Then
'check if collection has id2 as primary id
If ppu.m_pr.InteractionParameters.ContainsKey(cp2.Name.ToLower) Then
If Not ppu.m_pr.InteractionParameters(cp2.Name.ToLower).ContainsKey(cp.Name.ToLower) Then
ppu.m_pr.InteractionParameters(cp.Name.ToLower).Add(cp2.Name.ToLower, New PropertyPackages.Auxiliary.PRSV2_IPData)
Dim a12 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kij
Dim a21 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kji
KryptonDataGridView2.Rows.Add(New Object() {(cp2.Name), (cp.Name), Format(a12, nf), Format(a21, nf)})
With KryptonDataGridView2.Rows(KryptonDataGridView2.Rows.Count - 1)
.Cells(0).Tag = cp.Name.ToLower
.Cells(1).Tag = cp2.Name.ToLower
End With
End If
End If
Else
Dim a12 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kij
Dim a21 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kji
KryptonDataGridView2.Rows.Add(New Object() {(cp.Name), (cp2.Name), Format(a12, nf), Format(a21, nf)})
With KryptonDataGridView2.Rows(KryptonDataGridView2.Rows.Count - 1)
.Cells(0).Tag = cp.Name.ToLower
.Cells(1).Tag = cp2.Name.ToLower
End With
End If
End If
Next
Else
ppu.m_pr.InteractionParameters.Add(cp.Name.ToLower, New Dictionary(Of String, PropertyPackages.Auxiliary.PRSV2_IPData))
GoTo gt0
End If
Next
dgvu1.Rows.Clear()
For Each cp As ConstantProperties In _comps.Values
gt1: If ppu.m_pr._data.ContainsKey(cp.Name.ToLower) Then
Dim kappa1 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa1
Dim kappa2 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa2
Dim kappa3 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa3
dgvu1.Rows.Add(New Object() {(cp.Name), kappa1, kappa2, kappa3})
Else
ppu.m_pr._data.Add(cp.Name.ToLower, New PropertyPackages.Auxiliary.PRSV2Param)
GoTo gt1
End If
Next
Else
Dim ppu As PRSV2VLPropertyPackage = _pp
For Each cp As ConstantProperties In _comps.Values
gt0a: If ppu.m_pr.InteractionParameters.ContainsKey(cp.Name.ToLower) Then
For Each cp2 As ConstantProperties In _comps.Values
If cp.Name <> cp2.Name Then
If Not ppu.m_pr.InteractionParameters(cp.Name.ToLower).ContainsKey(cp2.Name.ToLower) Then
'check if collection has id2 as primary id
If ppu.m_pr.InteractionParameters.ContainsKey(cp2.Name.ToLower) Then
If Not ppu.m_pr.InteractionParameters(cp2.Name.ToLower).ContainsKey(cp.Name.ToLower) Then
ppu.m_pr.InteractionParameters(cp.Name.ToLower).Add(cp2.Name.ToLower, New PropertyPackages.Auxiliary.PRSV2_IPData)
Dim a12 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kij
Dim a21 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kji
KryptonDataGridView2.Rows.Add(New Object() {(cp2.Name), (cp.Name), Format(a12, nf), Format(a21, nf)})
With KryptonDataGridView2.Rows(KryptonDataGridView2.Rows.Count - 1)
.Cells(0).Tag = cp.Name.ToLower
.Cells(1).Tag = cp2.Name.ToLower
End With
End If
End If
Else
Dim a12 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kij
Dim a21 As Double = ppu.m_pr.InteractionParameters(cp.Name.ToLower)(cp2.Name.ToLower).kji
KryptonDataGridView2.Rows.Add(New Object() {(cp.Name), (cp2.Name), Format(a12, nf), Format(a21, nf)})
With KryptonDataGridView2.Rows(KryptonDataGridView2.Rows.Count - 1)
.Cells(0).Tag = cp.Name.ToLower
.Cells(1).Tag = cp2.Name.ToLower
End With
End If
End If
Next
Else
ppu.m_pr.InteractionParameters.Add(cp.Name.ToLower, New Dictionary(Of String, PropertyPackages.Auxiliary.PRSV2_IPData))
GoTo gt0a
End If
Next
dgvu1.Rows.Clear()
For Each cp As ConstantProperties In _comps.Values
gt2: If ppu.m_pr._data.ContainsKey(cp.Name.ToLower) Then
Dim kappa1 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa1
Dim kappa2 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa2
Dim kappa3 As Double = ppu.m_pr._data(cp.Name.ToLower).kappa3
dgvu1.Rows.Add(New Object() {(cp.Name), kappa1, kappa2, kappa3})
Else
ppu.m_pr._data.Add(cp.Name.ToLower, New PropertyPackages.Auxiliary.PRSV2Param)
GoTo gt2
End If
Next
End If
Loaded = True
End Sub
Private Sub FormConfigPR_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
Loaded = True
End Sub
Private Sub KryptonDataGridView2_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs)
If e.FormattedValue <> Nothing Then
If Double.TryParse(e.FormattedValue, New Double) = False Then
MessageBox.Show(Calculator.GetLocalString("Ovalorinseridoinvlid"), Calculator.GetLocalString("Parmetroinvlido"), MessageBoxButtons.OK, MessageBoxIcon.Error)
e.Cancel = True
End If
End If
End Sub
Private Sub dgvu1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvu1.CellValueChanged
If Loaded Then
If TypeOf _pp Is PRSV2PropertyPackage Then
Dim ppu As PRSV2PropertyPackage = _pp
Dim value As Object = dgvu1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim id1 As String = dgvu1.Rows(e.RowIndex).Cells(1).Value.ToString.ToLower
Select Case e.ColumnIndex
Case 1
ppu.m_pr._data(id1).kappa1 = value
Case 2
ppu.m_pr._data(id1).kappa2 = value
Case 3
ppu.m_pr._data(id1).kappa3 = value
End Select
Else
Dim ppu As PRSV2VLPropertyPackage = _pp
Dim value As Object = dgvu1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim id1 As String = dgvu1.Rows(e.RowIndex).Cells(1).Value.ToString.ToLower
Select Case e.ColumnIndex
Case 1
ppu.m_pr._data(id1).kappa1 = value
Case 2
ppu.m_pr._data(id1).kappa2 = value
Case 3
ppu.m_pr._data(id1).kappa3 = value
End Select
End If
End If
End Sub
Private Sub KryptonDataGridView2_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles KryptonDataGridView2.CellValueChanged
If Loaded Then
Dim oldvalue As Double, tp As String = ""
If TypeOf _pp Is PRSV2PropertyPackage Then
Dim ppu As PRSV2PropertyPackage = _pp
Dim value As Object = KryptonDataGridView2.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim id1 As String = KryptonDataGridView2.Rows(e.RowIndex).Cells(0).Tag.ToString.ToLower
Dim id2 As String = KryptonDataGridView2.Rows(e.RowIndex).Cells(1).Tag.ToString.ToLower
Select Case e.ColumnIndex
Case 2
oldvalue = ppu.m_pr.InteractionParameters(id1)(id2).kij
ppu.m_pr.InteractionParameters(id1)(id2).kij = value
tp = "PRSV2_KIJ"
Case 3
oldvalue = ppu.m_pr.InteractionParameters(id1)(id2).kji
ppu.m_pr.InteractionParameters(id1)(id2).kji = value
tp = "PRSV2_KJI"
End Select
If Not _form Is Nothing Then
_form.AddUndoRedoAction(New SharedClasses.UndoRedoAction() With {.AType = Interfaces.Enums.UndoRedoActionType.PropertyPackagePropertyChanged,
.Name = String.Format(_pp.Flowsheet.GetTranslatedString("UndoRedo_PropertyPackagePropertyChanged"), _pp.Tag, tp, oldvalue, value),
.OldValue = oldvalue, .NewValue = CDbl(value), .ObjID = id1, .ObjID2 = id2,
.Tag = _pp, .PropertyName = tp})
End If
Else
Dim ppu As PRSV2VLPropertyPackage = _pp
Dim value As Object = KryptonDataGridView2.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
Dim id1 As String = KryptonDataGridView2.Rows(e.RowIndex).Cells(0).Tag.ToString.ToLower
Dim id2 As String = KryptonDataGridView2.Rows(e.RowIndex).Cells(1).Tag.ToString.ToLower
Select Case e.ColumnIndex
Case 2
oldvalue = ppu.m_pr.InteractionParameters(id1)(id2).kij
ppu.m_pr.InteractionParameters(id1)(id2).kij = value
tp = "PRSV2VL_KIJ"
Case 3
oldvalue = ppu.m_pr.InteractionParameters(id1)(id2).kji
ppu.m_pr.InteractionParameters(id1)(id2).kji = value
tp = "PRSV2VL_KJI"
End Select
If Not _form Is Nothing Then
_form.AddUndoRedoAction(New SharedClasses.UndoRedoAction() With {.AType = Interfaces.Enums.UndoRedoActionType.PropertyPackagePropertyChanged,
.Name = String.Format(_pp.Flowsheet.GetTranslatedString("UndoRedo_PropertyPackagePropertyChanged"), _pp.Tag, tp, oldvalue, value),
.OldValue = oldvalue, .NewValue = CDbl(value), .ObjID = id1, .ObjID2 = id2,
.Tag = _pp, .PropertyName = tp})
End If
End If
End If
End Sub
End Class | Java |
// test
#ifndef TEST_HPP
#define TEST_HPP
#include <iostream>
#include <cmath>
#include <cassert>
#include "ga.hpp"
#include "ioga.hpp"
#include "ray.hpp"
#include "elem.hpp"
#include "rt.hpp"
#include "grid.hpp"
using namespace std;
#endif
| Java |
/*
* SMDataSignature.h
*
* Copyright 2019 Avérous Julien-Pierre
*
* This file is part of SMFoundation.
*
* SMFoundation is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SMFoundation is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SMFoundation. If not, see <http://www.gnu.org/licenses/>.
*
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*
** SMDataSignature
*/
#pragma mark - SMDataSignature
@interface SMDataSignature : NSObject
+ (BOOL)validateSignature:(NSData *)signature data:(NSData *)data publicKey:(NSData *)publicKey;
@end
NS_ASSUME_NONNULL_END
| Java |
#!/bin/bash
#SBATCH --job-name=heatwave_projections_py_mpi # Job name
#SBATCH -p batch # partition (this is the queue your job will be added to)
#SBATCH --ntasks=4 # Number of MPI ranks
#SBATCH --nodes=2 # Number of nodes
#SBATCH --mem-per-cpu=3000mb # Memory per processor
#SBATCH --time=36:00:00 # time allocation, which has the format (D-HH:MM), here set to 36 hours
#SBATCH --mail-type=ALL # Mail events (NONE, BEGIN, END, FAIL, ALL)
#SBATCH --mail-user=jeffrey.newman@adelaide.edu.au # Where to send mail
pwd; hostname; date
echo "Running Heatwave analysis program (v Small) on $SLURM_JOB_NUM_NODES nodes with $SLURM_NTASKS tasks, each with $SLURM_CPUS_PER_TASK cores."
module load GEOS/3.5.0-foss-2016uofa
module load GDAL/2.1.0-foss-2016uofa
module load Python/3.6.0-foss-2016uofa
module load R/3.3.0-foss-2016uofa
mpirun -np 4 python "/home/a1091793/Code/HeatwaveAnalaysis/Heatrisk_South_Australia_GoyderProjections/ParallelHeatRiskAnalysis2Phoenix.py" | Java |
<?php
/*
* This file is part of PHP-FFmpeg.
*
* (c) Alchemy <info@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FFMpeg\Media;
use Alchemy\BinaryDriver\Exception\ExecutionFailureException;
use FFMpeg\Filters\Audio\AudioFilters;
use FFMpeg\Format\FormatInterface;
use FFMpeg\Filters\Audio\SimpleFilter;
use FFMpeg\Exception\RuntimeException;
use FFMpeg\Exception\InvalidArgumentException;
use FFMpeg\Filters\Audio\AudioFilterInterface;
use FFMpeg\Filters\FilterInterface;
use FFMpeg\Format\ProgressableInterface;
class Audio extends AbstractStreamableMedia
{
/**
* {@inheritdoc}
*
* @return AudioFilters
*/
public function filters()
{
return new AudioFilters($this);
}
/**
* {@inheritdoc}
*
* @return Audio
*/
public function addFilter(FilterInterface $filter)
{
if (!$filter instanceof AudioFilterInterface) {
throw new InvalidArgumentException('Audio only accepts AudioFilterInterface filters');
}
$this->filters->add($filter);
return $this;
}
/**
* Exports the audio in the desired format, applies registered filters.
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return Audio
* @throws RuntimeException
*/
public function save(FormatInterface $format, $outputPathfile)
{
$listeners = null;
if ($format instanceof ProgressableInterface) {
$listeners = $format->createProgressListener($this, $this->ffprobe, 1, 1, 0);
}
$commands = $this->buildCommand($format, $outputPathfile);
try {
$this->driver->command($commands, false, $listeners);
} catch (ExecutionFailureException $e) {
$this->cleanupTemporaryFile($outputPathfile);
throw new RuntimeException('Encoding failed', $e->getCode(), $e);
}
return $this;
}
/**
* Returns the final command as a string, useful for debugging purposes.
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return string
* @since 0.11.0
*/
public function getFinalCommand(FormatInterface $format, $outputPathfile) {
return implode(' ', $this->buildCommand($format, $outputPathfile));
}
/**
* Builds the command which will be executed with the provided format
*
* @param FormatInterface $format
* @param string $outputPathfile
* @return string[] An array which are the components of the command
* @since 0.11.0
*/
protected function buildCommand(FormatInterface $format, $outputPathfile) {
$commands = array('-y', '-i', $this->pathfile);
$filters = clone $this->filters;
$filters->add(new SimpleFilter($format->getExtraParams(), 10));
if ($this->driver->getConfiguration()->has('ffmpeg.threads')) {
$filters->add(new SimpleFilter(array('-threads', $this->driver->getConfiguration()->get('ffmpeg.threads'))));
}
if (null !== $format->getAudioCodec()) {
$filters->add(new SimpleFilter(array('-acodec', $format->getAudioCodec())));
}
foreach ($filters as $filter) {
$commands = array_merge($commands, $filter->apply($this, $format));
}
if (null !== $format->getAudioKiloBitrate()) {
$commands[] = '-b:a';
$commands[] = $format->getAudioKiloBitrate() . 'k';
}
if (null !== $format->getAudioChannels()) {
$commands[] = '-ac';
$commands[] = $format->getAudioChannels();
}
$commands[] = $outputPathfile;
return $commands;
}
/**
* Gets the waveform of the video.
*
* @param integer $width
* @param integer $height
* @param array $colors Array of colors for ffmpeg to use. Color format is #000000 (RGB hex string with #)
* @return Waveform
*/
public function waveform($width = 640, $height = 120, $colors = array(Waveform::DEFAULT_COLOR))
{
return new Waveform($this, $this->driver, $this->ffprobe, $width, $height, $colors);
}
/**
* Concatenates a list of audio files into one unique audio file.
*
* @param array $sources
* @return Concat
*/
public function concat($sources)
{
return new Concat($sources, $this->driver, $this->ffprobe);
}
}
| Java |
#
## val.fm support
#
{
url_regex => qr{\bval\.fm\b},
code => sub {
my ($content) = @_;
if ($content =~ m{class="song-text.*?>(.*?)</div>}si) {
my $lyrics = $1;
$lyrics =~ s{<p\s+class=['"]verse['"]>}{\n\n}gi;
$lyrics =~ s{<.*?>}{}sg;
return if unpack('A*', $lyrics) eq '';
return $lyrics;
}
return;
}
}
| Java |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import itertools
import json
import erpnext
import frappe
import copy
from erpnext.controllers.item_variant import (ItemVariantExistsError,
copy_attributes_to_variant, get_variant, make_variant_item_code, validate_item_variant_attributes)
from erpnext.setup.doctype.item_group.item_group import (get_parent_item_groups, invalidate_cache_for)
from frappe import _, msgprint
from frappe.utils import (cint, cstr, flt, formatdate, get_timestamp, getdate,
now_datetime, random_string, strip)
from frappe.utils.html_utils import clean_html
from frappe.website.doctype.website_slideshow.website_slideshow import \
get_slideshow
from frappe.website.render import clear_cache
from frappe.website.website_generator import WebsiteGenerator
from six import iteritems
class DuplicateReorderRows(frappe.ValidationError):
pass
class StockExistsForTemplate(frappe.ValidationError):
pass
class InvalidBarcode(frappe.ValidationError):
pass
class Item(WebsiteGenerator):
website = frappe._dict(
page_title_field="item_name",
condition_field="show_in_website",
template="templates/generators/item.html",
no_cache=1
)
def onload(self):
super(Item, self).onload()
self.set_onload('stock_exists', self.stock_ledger_created())
self.set_asset_naming_series()
def set_asset_naming_series(self):
if not hasattr(self, '_asset_naming_series'):
from erpnext.assets.doctype.asset.asset import get_asset_naming_series
self._asset_naming_series = get_asset_naming_series()
self.set_onload('asset_naming_series', self._asset_naming_series)
def autoname(self):
if frappe.db.get_default("item_naming_by") == "Naming Series":
if self.variant_of:
if not self.item_code:
template_item_name = frappe.db.get_value("Item", self.variant_of, "item_name")
self.item_code = make_variant_item_code(self.variant_of, template_item_name, self)
else:
from frappe.model.naming import set_name_by_naming_series
set_name_by_naming_series(self)
self.item_code = self.name
self.item_code = strip(self.item_code)
self.name = self.item_code
def before_insert(self):
if not self.description:
self.description = self.item_name
# if self.is_sales_item and not self.get('is_item_from_hub'):
# self.publish_in_hub = 1
def after_insert(self):
'''set opening stock and item price'''
if self.standard_rate:
for default in self.item_defaults:
self.add_price(default.default_price_list)
if self.opening_stock:
self.set_opening_stock()
def validate(self):
self.get_doc_before_save()
super(Item, self).validate()
if not self.item_name:
self.item_name = self.item_code
if not self.description:
self.description = self.item_name
self.validate_uom()
self.validate_description()
self.add_default_uom_in_conversion_factor_table()
self.validate_conversion_factor()
self.validate_item_type()
self.check_for_active_boms()
self.fill_customer_code()
self.check_item_tax()
self.validate_barcode()
self.validate_warehouse_for_reorder()
self.update_bom_item_desc()
self.synced_with_hub = 0
self.validate_has_variants()
self.validate_stock_exists_for_template_item()
self.validate_attributes()
self.validate_variant_attributes()
self.validate_variant_based_on_change()
self.validate_website_image()
self.make_thumbnail()
self.validate_fixed_asset()
self.validate_retain_sample()
self.validate_uom_conversion_factor()
self.validate_item_defaults()
self.update_defaults_from_item_group()
self.validate_stock_for_has_batch_and_has_serial()
if not self.get("__islocal"):
self.old_item_group = frappe.db.get_value(self.doctype, self.name, "item_group")
self.old_website_item_groups = frappe.db.sql_list("""select item_group
from `tabWebsite Item Group`
where parentfield='website_item_groups' and parenttype='Item' and parent=%s""", self.name)
def on_update(self):
invalidate_cache_for_item(self)
self.validate_name_with_item_group()
self.update_variants()
self.update_item_price()
self.update_template_item()
def validate_description(self):
'''Clean HTML description if set'''
if cint(frappe.db.get_single_value('Stock Settings', 'clean_description_html')):
self.description = clean_html(self.description)
def add_price(self, price_list=None):
'''Add a new price'''
if not price_list:
price_list = (frappe.db.get_single_value('Selling Settings', 'selling_price_list')
or frappe.db.get_value('Price List', _('Standard Selling')))
if price_list:
item_price = frappe.get_doc({
"doctype": "Item Price",
"price_list": price_list,
"item_code": self.name,
"currency": erpnext.get_default_currency(),
"price_list_rate": self.standard_rate
})
item_price.insert()
def set_opening_stock(self):
'''set opening stock'''
if not self.is_stock_item or self.has_serial_no or self.has_batch_no:
return
if not self.valuation_rate and self.standard_rate:
self.valuation_rate = self.standard_rate
if not self.valuation_rate:
frappe.throw(_("Valuation Rate is mandatory if Opening Stock entered"))
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
# default warehouse, or Stores
for default in self.item_defaults:
default_warehouse = (default.default_warehouse
or frappe.db.get_single_value('Stock Settings', 'default_warehouse')
or frappe.db.get_value('Warehouse', {'warehouse_name': _('Stores')}))
if default_warehouse:
stock_entry = make_stock_entry(item_code=self.name, target=default_warehouse, qty=self.opening_stock,
rate=self.valuation_rate, company=default.company)
stock_entry.add_comment("Comment", _("Opening Stock"))
def make_route(self):
if not self.route:
return cstr(frappe.db.get_value('Item Group', self.item_group,
'route')) + '/' + self.scrub((self.item_name if self.item_name else self.item_code) + '-' + random_string(5))
def validate_website_image(self):
if frappe.flags.in_import:
return
"""Validate if the website image is a public file"""
auto_set_website_image = False
if not self.website_image and self.image:
auto_set_website_image = True
self.website_image = self.image
if not self.website_image:
return
# find if website image url exists as public
file_doc = frappe.get_all("File", filters={
"file_url": self.website_image
}, fields=["name", "is_private"], order_by="is_private asc", limit_page_length=1)
if file_doc:
file_doc = file_doc[0]
if not file_doc:
if not auto_set_website_image:
frappe.msgprint(_("Website Image {0} attached to Item {1} cannot be found").format(self.website_image, self.name))
self.website_image = None
elif file_doc.is_private:
if not auto_set_website_image:
frappe.msgprint(_("Website Image should be a public file or website URL"))
self.website_image = None
def make_thumbnail(self):
if frappe.flags.in_import:
return
"""Make a thumbnail of `website_image`"""
import requests.exceptions
if not self.is_new() and self.website_image != frappe.db.get_value(self.doctype, self.name, "website_image"):
self.thumbnail = None
if self.website_image and not self.thumbnail:
file_doc = None
try:
file_doc = frappe.get_doc("File", {
"file_url": self.website_image,
"attached_to_doctype": "Item",
"attached_to_name": self.name
})
except frappe.DoesNotExistError:
pass
# cleanup
frappe.local.message_log.pop()
except requests.exceptions.HTTPError:
frappe.msgprint(_("Warning: Invalid attachment {0}").format(self.website_image))
self.website_image = None
except requests.exceptions.SSLError:
frappe.msgprint(
_("Warning: Invalid SSL certificate on attachment {0}").format(self.website_image))
self.website_image = None
# for CSV import
if self.website_image and not file_doc:
try:
file_doc = frappe.get_doc({
"doctype": "File",
"file_url": self.website_image,
"attached_to_doctype": "Item",
"attached_to_name": self.name
}).insert()
except IOError:
self.website_image = None
if file_doc:
if not file_doc.thumbnail_url:
file_doc.make_thumbnail()
self.thumbnail = file_doc.thumbnail_url
def validate_fixed_asset(self):
if self.is_fixed_asset:
if self.is_stock_item:
frappe.throw(_("Fixed Asset Item must be a non-stock item."))
if not self.asset_category:
frappe.throw(_("Asset Category is mandatory for Fixed Asset item"))
if self.stock_ledger_created():
frappe.throw(_("Cannot be a fixed asset item as Stock Ledger is created."))
if not self.is_fixed_asset:
asset = frappe.db.get_all("Asset", filters={"item_code": self.name, "docstatus": 1}, limit=1)
if asset:
frappe.throw(_('"Is Fixed Asset" cannot be unchecked, as Asset record exists against the item'))
def validate_retain_sample(self):
if self.retain_sample and not frappe.db.get_single_value('Stock Settings', 'sample_retention_warehouse'):
frappe.throw(_("Please select Sample Retention Warehouse in Stock Settings first"))
if self.retain_sample and not self.has_batch_no:
frappe.throw(_(" {0} Retain Sample is based on batch, please check Has Batch No to retain sample of item").format(
self.item_code))
def get_context(self, context):
context.show_search = True
context.search_link = '/product_search'
context.parents = get_parent_item_groups(self.item_group)
self.set_variant_context(context)
self.set_attribute_context(context)
self.set_disabled_attributes(context)
return context
def set_variant_context(self, context):
if self.has_variants:
context.no_cache = True
# load variants
# also used in set_attribute_context
context.variants = frappe.get_all("Item",
filters={"variant_of": self.name, "show_variant_in_website": 1},
order_by="name asc")
variant = frappe.form_dict.variant
if not variant and context.variants:
# the case when the item is opened for the first time from its list
variant = context.variants[0]
if variant:
context.variant = frappe.get_doc("Item", variant)
for fieldname in ("website_image", "web_long_description", "description",
"website_specifications"):
if context.variant.get(fieldname):
value = context.variant.get(fieldname)
if isinstance(value, list):
value = [d.as_dict() for d in value]
context[fieldname] = value
if self.slideshow:
if context.variant and context.variant.slideshow:
context.update(get_slideshow(context.variant))
else:
context.update(get_slideshow(self))
def set_attribute_context(self, context):
if self.has_variants:
attribute_values_available = {}
context.attribute_values = {}
context.selected_attributes = {}
# load attributes
for v in context.variants:
v.attributes = frappe.get_all("Item Variant Attribute",
fields=["attribute", "attribute_value"],
filters={"parent": v.name})
for attr in v.attributes:
values = attribute_values_available.setdefault(attr.attribute, [])
if attr.attribute_value not in values:
values.append(attr.attribute_value)
if v.name == context.variant.name:
context.selected_attributes[attr.attribute] = attr.attribute_value
# filter attributes, order based on attribute table
for attr in self.attributes:
values = context.attribute_values.setdefault(attr.attribute, [])
if cint(frappe.db.get_value("Item Attribute", attr.attribute, "numeric_values")):
for val in sorted(attribute_values_available.get(attr.attribute, []), key=flt):
values.append(val)
else:
# get list of values defined (for sequence)
for attr_value in frappe.db.get_all("Item Attribute Value",
fields=["attribute_value"],
filters={"parent": attr.attribute}, order_by="idx asc"):
if attr_value.attribute_value in attribute_values_available.get(attr.attribute, []):
values.append(attr_value.attribute_value)
context.variant_info = json.dumps(context.variants)
def set_disabled_attributes(self, context):
"""Disable selection options of attribute combinations that do not result in a variant"""
if not self.attributes or not self.has_variants:
return
context.disabled_attributes = {}
attributes = [attr.attribute for attr in self.attributes]
def find_variant(combination):
for variant in context.variants:
if len(variant.attributes) < len(attributes):
continue
if "combination" not in variant:
ref_combination = []
for attr in variant.attributes:
idx = attributes.index(attr.attribute)
ref_combination.insert(idx, attr.attribute_value)
variant["combination"] = ref_combination
if not (set(combination) - set(variant["combination"])):
# check if the combination is a subset of a variant combination
# eg. [Blue, 0.5] is a possible combination if exists [Blue, Large, 0.5]
return True
for i, attr in enumerate(self.attributes):
if i == 0:
continue
combination_source = []
# loop through previous attributes
for prev_attr in self.attributes[:i]:
combination_source.append([context.selected_attributes.get(prev_attr.attribute)])
combination_source.append(context.attribute_values[attr.attribute])
for combination in itertools.product(*combination_source):
if not find_variant(combination):
context.disabled_attributes.setdefault(attr.attribute, []).append(combination[-1])
def add_default_uom_in_conversion_factor_table(self):
uom_conv_list = [d.uom for d in self.get("uoms")]
if self.stock_uom not in uom_conv_list:
ch = self.append('uoms', {})
ch.uom = self.stock_uom
ch.conversion_factor = 1
to_remove = []
for d in self.get("uoms"):
if d.conversion_factor == 1 and d.uom != self.stock_uom:
to_remove.append(d)
[self.remove(d) for d in to_remove]
def update_template_tables(self):
template = frappe.get_doc("Item", self.variant_of)
# add item taxes from template
for d in template.get("taxes"):
self.append("taxes", {"tax_type": d.tax_type, "tax_rate": d.tax_rate})
# copy re-order table if empty
if not self.get("reorder_levels"):
for d in template.get("reorder_levels"):
n = {}
for k in ("warehouse", "warehouse_reorder_level",
"warehouse_reorder_qty", "material_request_type"):
n[k] = d.get(k)
self.append("reorder_levels", n)
def validate_conversion_factor(self):
check_list = []
for d in self.get('uoms'):
if cstr(d.uom) in check_list:
frappe.throw(
_("Unit of Measure {0} has been entered more than once in Conversion Factor Table").format(d.uom))
else:
check_list.append(cstr(d.uom))
if d.uom and cstr(d.uom) == cstr(self.stock_uom) and flt(d.conversion_factor) != 1:
frappe.throw(
_("Conversion factor for default Unit of Measure must be 1 in row {0}").format(d.idx))
def validate_item_type(self):
if self.has_serial_no == 1 and self.is_stock_item == 0 and not self.is_fixed_asset:
msgprint(_("'Has Serial No' can not be 'Yes' for non-stock item"), raise_exception=1)
if self.has_serial_no == 0 and self.serial_no_series:
self.serial_no_series = None
def check_for_active_boms(self):
if self.default_bom:
bom_item = frappe.db.get_value("BOM", self.default_bom, "item")
if bom_item not in (self.name, self.variant_of):
frappe.throw(
_("Default BOM ({0}) must be active for this item or its template").format(bom_item))
def fill_customer_code(self):
""" Append all the customer codes and insert into "customer_code" field of item table """
cust_code = []
for d in self.get('customer_items'):
cust_code.append(d.ref_code)
self.customer_code = ','.join(cust_code)
def check_item_tax(self):
"""Check whether Tax Rate is not entered twice for same Tax Type"""
check_list = []
for d in self.get('taxes'):
if d.tax_type:
account_type = frappe.db.get_value("Account", d.tax_type, "account_type")
if account_type not in ['Tax', 'Chargeable', 'Income Account', 'Expense Account']:
frappe.throw(
_("Item Tax Row {0} must have account of type Tax or Income or Expense or Chargeable").format(d.idx))
else:
if d.tax_type in check_list:
frappe.throw(_("{0} entered twice in Item Tax").format(d.tax_type))
else:
check_list.append(d.tax_type)
def validate_barcode(self):
from stdnum import ean
if len(self.barcodes) > 0:
for item_barcode in self.barcodes:
options = frappe.get_meta("Item Barcode").get_options("barcode_type").split('\n')
if item_barcode.barcode:
duplicate = frappe.db.sql(
"""select parent from `tabItem Barcode` where barcode = %s and parent != %s""", (item_barcode.barcode, self.name))
if duplicate:
frappe.throw(_("Barcode {0} already used in Item {1}").format(
item_barcode.barcode, duplicate[0][0]), frappe.DuplicateEntryError)
item_barcode.barcode_type = "" if item_barcode.barcode_type not in options else item_barcode.barcode_type
if item_barcode.barcode_type and item_barcode.barcode_type.upper() in ('EAN', 'UPC-A', 'EAN-13', 'EAN-8'):
if not ean.is_valid(item_barcode.barcode):
frappe.throw(_("Barcode {0} is not a valid {1} code").format(
item_barcode.barcode, item_barcode.barcode_type), InvalidBarcode)
def validate_warehouse_for_reorder(self):
'''Validate Reorder level table for duplicate and conditional mandatory'''
warehouse = []
for d in self.get("reorder_levels"):
if not d.warehouse_group:
d.warehouse_group = d.warehouse
if d.get("warehouse") and d.get("warehouse") not in warehouse:
warehouse += [d.get("warehouse")]
else:
frappe.throw(_("Row {0}: An Reorder entry already exists for this warehouse {1}")
.format(d.idx, d.warehouse), DuplicateReorderRows)
if d.warehouse_reorder_level and not d.warehouse_reorder_qty:
frappe.throw(_("Row #{0}: Please set reorder quantity").format(d.idx))
def stock_ledger_created(self):
if not hasattr(self, '_stock_ledger_created'):
self._stock_ledger_created = len(frappe.db.sql("""select name from `tabStock Ledger Entry`
where item_code = %s limit 1""", self.name))
return self._stock_ledger_created
def validate_name_with_item_group(self):
# causes problem with tree build
if frappe.db.exists("Item Group", self.name):
frappe.throw(
_("An Item Group exists with same name, please change the item name or rename the item group"))
def update_item_price(self):
frappe.db.sql("""update `tabItem Price` set item_name=%s,
item_description=%s, brand=%s where item_code=%s""",
(self.item_name, self.description, self.brand, self.name))
def on_trash(self):
super(Item, self).on_trash()
frappe.db.sql("""delete from tabBin where item_code=%s""", self.name)
frappe.db.sql("delete from `tabItem Price` where item_code=%s", self.name)
for variant_of in frappe.get_all("Item", filters={"variant_of": self.name}):
frappe.delete_doc("Item", variant_of.name)
def before_rename(self, old_name, new_name, merge=False):
if self.item_name == old_name:
frappe.db.set_value("Item", old_name, "item_name", new_name)
if merge:
# Validate properties before merging
if not frappe.db.exists("Item", new_name):
frappe.throw(_("Item {0} does not exist").format(new_name))
field_list = ["stock_uom", "is_stock_item", "has_serial_no", "has_batch_no"]
new_properties = [cstr(d) for d in frappe.db.get_value("Item", new_name, field_list)]
if new_properties != [cstr(self.get(fld)) for fld in field_list]:
frappe.throw(_("To merge, following properties must be same for both items")
+ ": \n" + ", ".join([self.meta.get_label(fld) for fld in field_list]))
def after_rename(self, old_name, new_name, merge):
if self.route:
invalidate_cache_for_item(self)
clear_cache(self.route)
frappe.db.set_value("Item", new_name, "item_code", new_name)
if merge:
self.set_last_purchase_rate(new_name)
self.recalculate_bin_qty(new_name)
for dt in ("Sales Taxes and Charges", "Purchase Taxes and Charges"):
for d in frappe.db.sql("""select name, item_wise_tax_detail from `tab{0}`
where ifnull(item_wise_tax_detail, '') != ''""".format(dt), as_dict=1):
item_wise_tax_detail = json.loads(d.item_wise_tax_detail)
if isinstance(item_wise_tax_detail, dict) and old_name in item_wise_tax_detail:
item_wise_tax_detail[new_name] = item_wise_tax_detail[old_name]
item_wise_tax_detail.pop(old_name)
frappe.db.set_value(dt, d.name, "item_wise_tax_detail",
json.dumps(item_wise_tax_detail), update_modified=False)
def set_last_purchase_rate(self, new_name):
last_purchase_rate = get_last_purchase_details(new_name).get("base_rate", 0)
frappe.db.set_value("Item", new_name, "last_purchase_rate", last_purchase_rate)
def recalculate_bin_qty(self, new_name):
from erpnext.stock.stock_balance import repost_stock
frappe.db.auto_commit_on_many_writes = 1
existing_allow_negative_stock = frappe.db.get_value("Stock Settings", None, "allow_negative_stock")
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
repost_stock_for_warehouses = frappe.db.sql_list("""select distinct warehouse
from tabBin where item_code=%s""", new_name)
# Delete all existing bins to avoid duplicate bins for the same item and warehouse
frappe.db.sql("delete from `tabBin` where item_code=%s", new_name)
for warehouse in repost_stock_for_warehouses:
repost_stock(new_name, warehouse)
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", existing_allow_negative_stock)
frappe.db.auto_commit_on_many_writes = 0
def copy_specification_from_item_group(self):
self.set("website_specifications", [])
if self.item_group:
for label, desc in frappe.db.get_values("Item Website Specification",
{"parent": self.item_group}, ["label", "description"]):
row = self.append("website_specifications")
row.label = label
row.description = desc
def update_bom_item_desc(self):
if self.is_new():
return
if self.db_get('description') != self.description:
frappe.db.sql("""
update `tabBOM`
set description = %s
where item = %s and docstatus < 2
""", (self.description, self.name))
frappe.db.sql("""
update `tabBOM Item`
set description = %s
where item_code = %s and docstatus < 2
""", (self.description, self.name))
frappe.db.sql("""
update `tabBOM Explosion Item`
set description = %s
where item_code = %s and docstatus < 2
""", (self.description, self.name))
def update_template_item(self):
"""Set Show in Website for Template Item if True for its Variant"""
if self.variant_of:
if self.show_in_website:
self.show_variant_in_website = 1
self.show_in_website = 0
if self.show_variant_in_website:
# show template
template_item = frappe.get_doc("Item", self.variant_of)
if not template_item.show_in_website:
template_item.show_in_website = 1
template_item.flags.dont_update_variants = True
template_item.flags.ignore_permissions = True
template_item.save()
def validate_item_defaults(self):
companies = list(set([row.company for row in self.item_defaults]))
if len(companies) != len(self.item_defaults):
frappe.throw(_("Cannot set multiple Item Defaults for a company."))
def update_defaults_from_item_group(self):
"""Get defaults from Item Group"""
if self.item_group and not self.item_defaults:
item_defaults = frappe.db.get_values("Item Default", {"parent": self.item_group},
['company', 'default_warehouse','default_price_list','buying_cost_center','default_supplier',
'expense_account','selling_cost_center','income_account'], as_dict = 1)
if item_defaults:
for item in item_defaults:
self.append('item_defaults', {
'company': item.company,
'default_warehouse': item.default_warehouse,
'default_price_list': item.default_price_list,
'buying_cost_center': item.buying_cost_center,
'default_supplier': item.default_supplier,
'expense_account': item.expense_account,
'selling_cost_center': item.selling_cost_center,
'income_account': item.income_account
})
else:
warehouse = ''
defaults = frappe.defaults.get_defaults() or {}
# To check default warehouse is belong to the default company
if defaults.get("default_warehouse") and frappe.db.exists("Warehouse",
{'name': defaults.default_warehouse, 'company': defaults.company}):
warehouse = defaults.default_warehouse
self.append("item_defaults", {
"company": defaults.get("company"),
"default_warehouse": warehouse
})
def update_variants(self):
if self.flags.dont_update_variants or \
frappe.db.get_single_value('Item Variant Settings', 'do_not_update_variants'):
return
if self.has_variants:
variants = frappe.db.get_all("Item", fields=["item_code"], filters={"variant_of": self.name})
if variants:
if len(variants) <= 30:
update_variants(variants, self, publish_progress=False)
frappe.msgprint(_("Item Variants updated"))
else:
frappe.enqueue("erpnext.stock.doctype.item.item.update_variants",
variants=variants, template=self, now=frappe.flags.in_test, timeout=600)
def validate_has_variants(self):
if not self.has_variants and frappe.db.get_value("Item", self.name, "has_variants"):
if frappe.db.exists("Item", {"variant_of": self.name}):
frappe.throw(_("Item has variants."))
def validate_stock_exists_for_template_item(self):
if self.stock_ledger_created() and self._doc_before_save:
if (cint(self._doc_before_save.has_variants) != cint(self.has_variants)
or self._doc_before_save.variant_of != self.variant_of):
frappe.throw(_("Cannot change Variant properties after stock transaction. You will have to make a new Item to do this.").format(self.name),
StockExistsForTemplate)
if self.has_variants or self.variant_of:
if not self.is_child_table_same('attributes'):
frappe.throw(
_('Cannot change Attributes after stock transaction. Make a new Item and transfer stock to the new Item'))
def validate_variant_based_on_change(self):
if not self.is_new() and (self.variant_of or (self.has_variants and frappe.get_all("Item", {"variant_of": self.name}))):
if self.variant_based_on != frappe.db.get_value("Item", self.name, "variant_based_on"):
frappe.throw(_("Variant Based On cannot be changed"))
def validate_uom(self):
if not self.get("__islocal"):
check_stock_uom_with_bin(self.name, self.stock_uom)
if self.has_variants:
for d in frappe.db.get_all("Item", filters={"variant_of": self.name}):
check_stock_uom_with_bin(d.name, self.stock_uom)
if self.variant_of:
template_uom = frappe.db.get_value("Item", self.variant_of, "stock_uom")
if template_uom != self.stock_uom:
frappe.throw(_("Default Unit of Measure for Variant '{0}' must be same as in Template '{1}'")
.format(self.stock_uom, template_uom))
def validate_uom_conversion_factor(self):
if self.uoms:
for d in self.uoms:
value = get_uom_conv_factor(d.uom, self.stock_uom)
if value:
d.conversion_factor = value
def validate_attributes(self):
if not (self.has_variants or self.variant_of):
return
if not self.variant_based_on:
self.variant_based_on = 'Item Attribute'
if self.variant_based_on == 'Item Attribute':
attributes = []
if not self.attributes:
frappe.throw(_("Attribute table is mandatory"))
for d in self.attributes:
if d.attribute in attributes:
frappe.throw(
_("Attribute {0} selected multiple times in Attributes Table".format(d.attribute)))
else:
attributes.append(d.attribute)
def validate_variant_attributes(self):
if self.is_new() and self.variant_of and self.variant_based_on == 'Item Attribute':
args = {}
for d in self.attributes:
if cstr(d.attribute_value).strip() == '':
frappe.throw(_("Please specify Attribute Value for attribute {0}").format(d.attribute))
args[d.attribute] = d.attribute_value
variant = get_variant(self.variant_of, args, self.name)
if variant:
frappe.throw(_("Item variant {0} exists with same attributes")
.format(variant), ItemVariantExistsError)
validate_item_variant_attributes(self, args)
def validate_stock_for_has_batch_and_has_serial(self):
if self.stock_ledger_created():
for value in ["has_batch_no", "has_serial_no"]:
if frappe.db.get_value("Item", self.name, value) != self.get_value(value):
frappe.throw(_("Cannot change {0} as Stock Transaction for Item {1} exist.".format(value, self.name)))
def get_timeline_data(doctype, name):
'''returns timeline data based on stock ledger entry'''
out = {}
items = dict(frappe.db.sql('''select posting_date, count(*)
from `tabStock Ledger Entry` where item_code=%s
and posting_date > date_sub(curdate(), interval 1 year)
group by posting_date''', name))
for date, count in iteritems(items):
timestamp = get_timestamp(date)
out.update({timestamp: count})
return out
def validate_end_of_life(item_code, end_of_life=None, disabled=None, verbose=1):
if (not end_of_life) or (disabled is None):
end_of_life, disabled = frappe.db.get_value("Item", item_code, ["end_of_life", "disabled"])
if end_of_life and end_of_life != "0000-00-00" and getdate(end_of_life) <= now_datetime().date():
msg = _("Item {0} has reached its end of life on {1}").format(item_code, formatdate(end_of_life))
_msgprint(msg, verbose)
if disabled:
_msgprint(_("Item {0} is disabled").format(item_code), verbose)
def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
if not is_stock_item:
is_stock_item = frappe.db.get_value("Item", item_code, "is_stock_item")
if is_stock_item != 1:
msg = _("Item {0} is not a stock Item").format(item_code)
_msgprint(msg, verbose)
def validate_cancelled_item(item_code, docstatus=None, verbose=1):
if docstatus is None:
docstatus = frappe.db.get_value("Item", item_code, "docstatus")
if docstatus == 2:
msg = _("Item {0} is cancelled").format(item_code)
_msgprint(msg, verbose)
def _msgprint(msg, verbose):
if verbose:
msgprint(msg, raise_exception=True)
else:
raise frappe.ValidationError(msg)
def get_last_purchase_details(item_code, doc_name=None, conversion_rate=1.0):
"""returns last purchase details in stock uom"""
# get last purchase order item details
last_purchase_order = frappe.db.sql("""\
select po.name, po.transaction_date, po.conversion_rate,
po_item.conversion_factor, po_item.base_price_list_rate,
po_item.discount_percentage, po_item.base_rate
from `tabPurchase Order` po, `tabPurchase Order Item` po_item
where po.docstatus = 1 and po_item.item_code = %s and po.name != %s and
po.name = po_item.parent
order by po.transaction_date desc, po.name desc
limit 1""", (item_code, cstr(doc_name)), as_dict=1)
# get last purchase receipt item details
last_purchase_receipt = frappe.db.sql("""\
select pr.name, pr.posting_date, pr.posting_time, pr.conversion_rate,
pr_item.conversion_factor, pr_item.base_price_list_rate, pr_item.discount_percentage,
pr_item.base_rate
from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pr_item
where pr.docstatus = 1 and pr_item.item_code = %s and pr.name != %s and
pr.name = pr_item.parent
order by pr.posting_date desc, pr.posting_time desc, pr.name desc
limit 1""", (item_code, cstr(doc_name)), as_dict=1)
purchase_order_date = getdate(last_purchase_order and last_purchase_order[0].transaction_date
or "1900-01-01")
purchase_receipt_date = getdate(last_purchase_receipt and
last_purchase_receipt[0].posting_date or "1900-01-01")
if (purchase_order_date > purchase_receipt_date) or \
(last_purchase_order and not last_purchase_receipt):
# use purchase order
last_purchase = last_purchase_order[0]
purchase_date = purchase_order_date
elif (purchase_receipt_date > purchase_order_date) or \
(last_purchase_receipt and not last_purchase_order):
# use purchase receipt
last_purchase = last_purchase_receipt[0]
purchase_date = purchase_receipt_date
else:
return frappe._dict()
conversion_factor = flt(last_purchase.conversion_factor)
out = frappe._dict({
"base_price_list_rate": flt(last_purchase.base_price_list_rate) / conversion_factor,
"base_rate": flt(last_purchase.base_rate) / conversion_factor,
"discount_percentage": flt(last_purchase.discount_percentage),
"purchase_date": purchase_date
})
conversion_rate = flt(conversion_rate) or 1.0
out.update({
"price_list_rate": out.base_price_list_rate / conversion_rate,
"rate": out.base_rate / conversion_rate,
"base_rate": out.base_rate
})
return out
def invalidate_cache_for_item(doc):
invalidate_cache_for(doc, doc.item_group)
website_item_groups = list(set((doc.get("old_website_item_groups") or [])
+ [d.item_group for d in doc.get({"doctype": "Website Item Group"}) if d.item_group]))
for item_group in website_item_groups:
invalidate_cache_for(doc, item_group)
if doc.get("old_item_group") and doc.get("old_item_group") != doc.item_group:
invalidate_cache_for(doc, doc.old_item_group)
def check_stock_uom_with_bin(item, stock_uom):
if stock_uom == frappe.db.get_value("Item", item, "stock_uom"):
return
matched = True
ref_uom = frappe.db.get_value("Stock Ledger Entry",
{"item_code": item}, "stock_uom")
if ref_uom:
if cstr(ref_uom) != cstr(stock_uom):
matched = False
else:
bin_list = frappe.db.sql("select * from tabBin where item_code=%s", item, as_dict=1)
for bin in bin_list:
if (bin.reserved_qty > 0 or bin.ordered_qty > 0 or bin.indented_qty > 0
or bin.planned_qty > 0) and cstr(bin.stock_uom) != cstr(stock_uom):
matched = False
break
if matched and bin_list:
frappe.db.sql("""update tabBin set stock_uom=%s where item_code=%s""", (stock_uom, item))
if not matched:
frappe.throw(
_("Default Unit of Measure for Item {0} cannot be changed directly because you have already made some transaction(s) with another UOM. You will need to create a new Item to use a different Default UOM.").format(item))
def get_item_defaults(item_code, company):
item = frappe.get_cached_doc('Item', item_code)
out = item.as_dict()
for d in item.item_defaults:
if d.company == company:
row = copy.deepcopy(d.as_dict())
row.pop("name")
out.update(row)
return out
def set_item_default(item_code, company, fieldname, value):
item = frappe.get_cached_doc('Item', item_code)
for d in item.item_defaults:
if d.company == company:
if not d.get(fieldname):
frappe.db.set_value(d.doctype, d.name, fieldname, value)
return
# no row found, add a new row for the company
d = item.append('item_defaults', {fieldname: value, "company": company})
d.db_insert()
item.clear_cache()
@frappe.whitelist()
def get_uom_conv_factor(uom, stock_uom):
uoms = [uom, stock_uom]
value = ""
uom_details = frappe.db.sql("""select to_uom, from_uom, value from `tabUOM Conversion Factor`\
where to_uom in ({0})
""".format(', '.join(['"' + frappe.db.escape(i, percent=False) + '"' for i in uoms])), as_dict=True)
for d in uom_details:
if d.from_uom == stock_uom and d.to_uom == uom:
value = 1/flt(d.value)
elif d.from_uom == uom and d.to_uom == stock_uom:
value = d.value
if not value:
uom_stock = frappe.db.get_value("UOM Conversion Factor", {"to_uom": stock_uom}, ["from_uom", "value"], as_dict=1)
uom_row = frappe.db.get_value("UOM Conversion Factor", {"to_uom": uom}, ["from_uom", "value"], as_dict=1)
if uom_stock and uom_row:
if uom_stock.from_uom == uom_row.from_uom:
value = flt(uom_stock.value) * 1/flt(uom_row.value)
return value
@frappe.whitelist()
def get_item_attribute(parent, attribute_value=''):
if not frappe.has_permission("Item"):
frappe.msgprint(_("No Permission"), raise_exception=1)
return frappe.get_all("Item Attribute Value", fields = ["attribute_value"],
filters = {'parent': parent, 'attribute_value': ("like", "%%%s%%" % attribute_value)})
def update_variants(variants, template, publish_progress=True):
count=0
for d in variants:
variant = frappe.get_doc("Item", d)
copy_attributes_to_variant(template, variant)
variant.save()
count+=1
if publish_progress:
frappe.publish_progress(count*100/len(variants), title = _("Updating Variants..."))
| Java |
// ************************************************************************** //
// 24 Bomb //
// By: rcargou <rcargou@student.42.fr> ::: :::::::: //
// By: nmohamed <nmohamed@student.42.fr> :+: :+: :+: //
// By: adjivas <adjivas@student.42.fr> +:+ +:+ +:+ //
// By: vjacquie <vjacquie@student.42.fr> +#+ +:+ +#+ //
// By: jmoiroux <jmoiroux@student.42.fr> +#+#+#+#+#+ +#+ //
// Created: 2015/10/16 17:03:20 by rcargou #+# #+# //
// Updated: 2015/10/27 14:00:02 by rcargou ### ########.fr //
// //
// ************************************************************************** //
#include <mapparser.class.hpp>
#include <entity.class.hpp>
#include <wall.class.hpp>
#include <bomb.class.hpp>
#include <fire.class.hpp>
#include <player.class.hpp>
#include <enemy.class.hpp>
#include <boss.class.hpp>
#include <globject.class.hpp>
#include <event.class.hpp>
Entity *** Mapparser::map_from_file( char *map_path ) {
if (NULL != main_event->map)
Mapparser::free_old_map();
Entity *** tmp = Mapparser::map_alloc();
Entity * elem = NULL;
std::fstream file;
std::string line;
std::string casemap;
int i = 0,
j = globject::mapY_size - 1,
x = 0;
Mapparser::valid_map(map_path);
file.open(map_path , std::fstream::in);
for (int x = 0; x < 3; x++)
std::getline(file, line);
while (j >= 0) {
i = ((globject::mapX_size - 1) * 4 );
x = globject::mapX_size - 1;
std::getline(file, line);
while (i >= 0) {
casemap += line[i];
casemap += line[i + 1];
casemap += line[i + 2];
elem = Mapparser::get_entity_from_map( casemap, (float)x, (float)j );
if (elem->type == PLAYER || elem->type == ENEMY || elem->type == BOSS) {
tmp[j][x] = Factory::create_empty((int)x, (int)j);
main_event->char_list.push_back(elem);
}
else
tmp[j][x] = elem;
casemap.clear();
i -= 4;
x--;
if ( i < 0 )
break;
}
j--;
}
main_event->w_log("Mapparser::map_from_file LOADED");
return tmp;
}
Entity * Mapparser::get_entity_from_map( std::string & casemap, float x, float y) {
Entity * tmp = NULL;
if ( g_mapcase.count(casemap) == 0) {
main_event->w_error("Map file Case Syntax error/doesn't exist");
throw std::exception();
}
else {
switch (g_mapcase.at(casemap)) {
case EMPTY: return static_cast<Entity*>( Factory::create_empty(x, y) );
case WALL_INDESTRUCTIBLE: return static_cast<Entity*>( Factory::create_wall(WALL_INDESTRUCTIBLE, x, y, WALL_INDESTRUCTIBLE) );
case WALL_HP_1: return static_cast<Entity*>( Factory::create_wall(WALL_HP_1, x, y, WALL_HP_1) );
case WALL_HP_2: return static_cast<Entity*>( Factory::create_wall(WALL_HP_2, x, y, WALL_HP_2) );
case WALL_HP_3: return static_cast<Entity*>( Factory::create_wall(WALL_HP_3, x, y, WALL_HP_3) );
case WALL_HP_4: return static_cast<Entity*>( Factory::create_wall(WALL_HP_4, x, y, WALL_HP_4) );
case ENEMY1: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY1) );
case ENEMY2: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY2) );
case ENEMY3: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY3) );
case ENEMY4: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY4) );
case ENEMY5: return static_cast<Entity*>( Factory::create_enemy(ENEMY, x, y, ENEMY5) );
case BOSS_A: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_A, BOSS_A) );
case BOSS_B: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_B, BOSS_B) );
case BOSS_C: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_C) );
case BOSS_D: return static_cast<Entity*>( Factory::create_boss(BOSS, x, y, BOSS_C, BOSS_D) );
case PLAYER1: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER1) );
case PLAYER2: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER2) );
case PLAYER3: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER3) );
case PLAYER4: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER4) );
case PLAYER5: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER5) );
case PLAYER6: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER6) );
case PLAYER7: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER7) );
case PLAYER8: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER8) );
case PLAYER9: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER9) );
case PLAYER10: return static_cast<Entity*>( Factory::create_player( PLAYER, x, y, PLAYER10) );
case BONUS_POWER_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_POWER_UP) );
case BONUS_PLUS_ONE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_PLUS_ONE) );
case BONUS_KICK: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_KICK) );
case BONUS_CHANGE: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_CHANGE) );
case BONUS_REMOTE_BOMB: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_REMOTE_BOMB) );
case BONUS_SPEED_UP: return static_cast<Entity*>( Factory::create_player( BONUS, x, y, BONUS_SPEED_UP) );
default: return static_cast<Entity*>( Factory::create_empty(x, y) );
}
}
return tmp;
}
int Mapparser::valid_map( char const *map_path ) {
std::fstream file;
std::string line;
int x = 0,
y = 0,
j = 0;
if( access( map_path, F_OK ) < 0 ) {
main_event->w_error("Mapparser::valid_map file access error");
throw std::exception();
}
file.open(map_path , std::fstream::in);
if (!file.is_open()) {
main_event->w_error("Mapparser::valid_map file open error");
throw std::exception();
}
std::getline(file, line); // y: 20
if (line.length() >= 4)
x = std::stoi(&line[3]);
else
main_event->w_exception("map line 1 error");
std::getline(file, line); // x: 20
if (line.length() >= 4)
y = std::stoi(&line[3]);
else
main_event->w_exception("map line 2 error");
std::getline(file, line); // <-- MAP -->
j = 0;
while ( std::getline(file, line) ) {
if ((int)line.length() != (4 * x - 1) ) {
main_event->w_exception("width doesn't correspond");
}
if (j >= y - 1)
break;
j++;
}
if (j != y - 1)
main_event->w_exception("Map height doesn't correspond");
file.close();
return 0;
}
Entity *** Mapparser::map_alloc() { // return map 2d without entity
int y = 0;
Entity *** new_map = NULL;
// TO DELETE SI SEGFAULT
// if (main_event->map != NULL) {
// while (y < globject::mapY_size) {
// std::free(main_event->map[y]);
// main_event->map[y] = NULL;
// y++;
// }
// std::free(main_event->map);
// main_event->map = NULL;
// }
/////////////////////
new_map = (Entity ***)std::malloc(sizeof(Entity **) * globject::mapY_size);
if (new_map == NULL) {
main_event->w_error("Mapparser::map_alloc() new_map Allocation error");
throw std::exception();
}
y = 0;
while (y < globject::mapY_size) {
new_map[y] = NULL;
new_map[y] = (Entity **)std::malloc(sizeof(Entity *) * globject::mapX_size);
if (new_map[y] == NULL) {
main_event->w_error("Mapparser::map_alloc() new_map[y] Allocation error");
throw std::exception();
}
y++;
}
return new_map;
}
void Mapparser::free_old_map() {
int y = 0;
while (y < globject::mapY_size) {
if (NULL != main_event->map[y])
std::free( main_event->map[y]);
y++;
}
if (NULL != main_event->map)
std::free(main_event->map);
main_event->map = NULL;
}
void Mapparser::get_error() const {
if (NULL != Mapparser::error)
std::cerr << Mapparser::error;
}
std::string * Mapparser::error = NULL;
Mapparser::Mapparser() {}
Mapparser::~Mapparser() {}
Mapparser::Mapparser( Mapparser const & src ) {
*this = src;
}
Mapparser & Mapparser::operator=( Mapparser const & rhs ) {
if (this != &rhs) {
this->error = rhs.error;
}
return *this;
}
| Java |
import unittest
import os
from ui import main
print os.getcwd()
class TestMain(unittest.TestCase):
def setUp(self):
self.m = main.MainWindow()
def test_mainWindow(self):
assert(self.m)
def test_dataframe(self):
import numpy
#Random 25x4 Numpy Matrix
self.m.render_dataframe(numpy.random.rand(25,4) ,name='devel',rownames=xrange(0,25))
assert(self.m.active_robject)
assert(self.m.active_robject.columns)
assert(self.m.active_robject.column_data)
def test_imports(self):
datasets = ['iris','Nile','morley','freeny','sleep','mtcars']
for a in datasets:
main.rsession.r('%s=%s' % (a,a))
self.m.sync_with_r()
assert(a in self.m.robjects)
unittest.main() | Java |
package osberbot.bo;
/**
* TODO: Description
*
* @author Tititesouris
* @since 2016/03/20
*/
public class ViewerBO {
private Integer id;
private String name;
private Boolean moderator;
private RankBO rank;
public ViewerBO(Integer id, String name, RankBO rank) {
this.id = id;
this.name = name;
this.rank = rank;
}
public boolean hasPower(PowerBO power) {
if (rank != null)
return rank.hasPower(power);
return moderator;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public RankBO getRank() {
return rank;
}
public void setRank(RankBO rank) {
this.rank = rank;
}
}
| Java |
from datetime import datetime
import factory
from zds.forum.factories import PostFactory, TopicFactory
from zds.gallery.factories import GalleryFactory, UserGalleryFactory
from zds.utils.factories import LicenceFactory, SubCategoryFactory
from zds.utils.models import Licence
from zds.tutorialv2.models.database import PublishableContent, Validation, ContentReaction
from zds.tutorialv2.models.versioned import Container, Extract
from zds.tutorialv2.publication_utils import publish_content
from zds.tutorialv2.utils import init_new_repo
text_content = "Ceci est un texte bidon, **avec markown**"
tricky_text_content = (
"Ceci est un texte contenant plein d'images, pour la publication. Le modifier affectera le test !\n\n"
"# Les images\n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"Image: \n\n"
"# Et donc ...\n\n"
"Voilà :)"
)
class PublishableContentFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a PublishableContent.
"""
class Meta:
model = PublishableContent
title = factory.Sequence("Mon contenu No{}".format)
description = factory.Sequence("Description du contenu No{}".format)
type = "TUTORIAL"
creation_date = datetime.now()
pubdate = datetime.now()
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
light = attrs.pop("light", True)
author_list = attrs.pop("author_list", None)
add_license = attrs.pop("add_license", True)
add_category = attrs.pop("add_category", True)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
licence = attrs.get("licence", None)
auths = author_list or []
if add_license:
given_licence = licence or Licence.objects.first()
if isinstance(given_licence, str) and given_licence:
given_licence = Licence.objects.filter(title=given_licence).first() or Licence.objects.first()
licence = given_licence or LicenceFactory()
text = text_content
if not light:
text = tricky_text_content
publishable_content = super()._generate(create, attrs)
publishable_content.gallery = GalleryFactory()
publishable_content.licence = licence
for auth in auths:
publishable_content.authors.add(auth)
if add_category:
publishable_content.subcategory.add(SubCategoryFactory())
publishable_content.save()
for author in publishable_content.authors.all():
UserGalleryFactory(user=author, gallery=publishable_content.gallery, mode="W")
init_new_repo(publishable_content, text, text)
return publishable_content
class ContainerFactory(factory.Factory):
"""
Factory that creates a Container.
"""
class Meta:
model = Container
title = factory.Sequence(lambda n: "Mon container No{}".format(n + 1))
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
db_object = attrs.pop("db_object", None)
light = attrs.pop("light", True)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
parent = attrs.get("parent", None)
# Needed because we use container.title later
container = super()._generate(create, attrs)
text = text_content
if not light:
text = tricky_text_content
sha = parent.repo_add_container(container.title, text, text)
container = parent.children[-1]
if db_object:
db_object.sha_draft = sha
db_object.save()
return container
class ExtractFactory(factory.Factory):
"""
Factory that creates a Extract.
"""
class Meta:
model = Extract
title = factory.Sequence(lambda n: "Mon extrait No{}".format(n + 1))
@classmethod
def _generate(cls, create, attrs):
# These parameters are only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (they are removed from attrs).
light = attrs.pop("light", True)
db_object = attrs.pop("db_object", None)
# This parameter will be saved in the database,
# which is why we use attrs.get() (it stays in attrs).
container = attrs.get("container", None)
# Needed because we use extract.title later
extract = super()._generate(create, attrs)
parent = container
text = text_content
if not light:
text = tricky_text_content
sha = parent.repo_add_extract(extract.title, text)
extract = parent.children[-1]
if db_object:
db_object.sha_draft = sha
db_object.save()
return extract
class ContentReactionFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a ContentReaction.
"""
class Meta:
model = ContentReaction
ip_address = "192.168.3.1"
text = "Bonjour, je me présente, je m'appelle l'homme au texte bidonné"
@classmethod
def _generate(cls, create, attrs):
note = super()._generate(create, attrs)
note.pubdate = datetime.now()
note.save()
note.related_content.last_note = note
note.related_content.save()
return note
class BetaContentFactory(PublishableContentFactory):
"""
Factory that creates a PublishableContent with a beta version and a beta topic.
"""
@classmethod
def _generate(cls, create, attrs):
# This parameter is only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (it is removed from attrs).
beta_forum = attrs.pop("forum", None)
# Creates the PublishableContent (see PublishableContentFactory._generate() for more info)
publishable_content = super()._generate(create, attrs)
if publishable_content.authors.count() > 0 and beta_forum is not None:
beta_topic = TopicFactory(
title="[beta]" + publishable_content.title, author=publishable_content.authors.first(), forum=beta_forum
)
publishable_content.sha_beta = publishable_content.sha_draft
publishable_content.beta_topic = beta_topic
publishable_content.save()
PostFactory(topic=beta_topic, position=1, author=publishable_content.authors.first())
beta_topic.save()
return publishable_content
class PublishedContentFactory(PublishableContentFactory):
"""
Factory that creates a PublishableContent and the publish it.
"""
@classmethod
def _generate(cls, create, attrs):
# This parameter is only used inside _generate() and won't be saved in the database,
# which is why we use attrs.pop() (it is removed from attrs).
is_major_update = attrs.pop("is_major_update", True)
# Creates the PublishableContent (see PublishableContentFactory._generate() for more info)
content = super()._generate(create, attrs)
published = publish_content(content, content.load_version(), is_major_update)
content.sha_public = content.sha_draft
content.public_version = published
content.save()
return content
class ValidationFactory(factory.django.DjangoModelFactory):
"""
Factory that creates a Validation.
"""
class Meta:
model = Validation
| Java |
//============================================================================
// Name : BoxyLady
// Author : Darren Green
// Copyright : (C) Darren Green 2011-2020
// Description : Music sequencer
//
// License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
// This is free software; you are free to change and redistribute it.
// There is NO WARRANTY, to the extent permitted by law.
// Contact: darren.green@stir.ac.uk http://www.pinkmongoose.co.uk
//============================================================================
#ifndef DICTIONARY_H_
#define DICTIONARY_H_
#include <unordered_map>
#include "Global.h"
#include "Sequence.h"
#include "Blob.h"
namespace BoxyLady {
enum class dic_item_protection {
temp, normal, locked, system, active
};
enum class dic_item_type {
null, patch, macro
};
class DictionaryItem;
class Dictionary;
class DictionaryMutex;
class DictionaryItem {
friend class DictionaryMutex;
friend class Dictionary;
private:
int semaphor_;
dic_item_type type_;
dic_item_protection protection_level_;
Blob macro_;
Sequence sequence_;
public:
DictionaryItem(dic_item_type type = dic_item_type::null) :
semaphor_(0), type_(type), protection_level_(
dic_item_protection::normal) {
}
dic_item_protection ProtectionLevel() const {
return protection_level_;
}
void Protect(dic_item_protection level) {
protection_level_ = level;
}
bool isMacro() const {
return type_ == dic_item_type::macro;
}
bool isPatch() const {
return type_ == dic_item_type::patch;
}
bool isNull() const {
return type_ == dic_item_type::null;
}
dic_item_type getType() const {
return type_;
}
Blob& getMacro() {
return macro_;
}
Sequence& getSequence() {
return sequence_;
}
static bool ValidName(std::string);
};
typedef std::unordered_map<std::string, DictionaryItem> DictionaryType;
typedef DictionaryType::iterator DictionaryIterator;
typedef std::list<DictionaryIterator> DictionaryIteratorList;
class DictionaryMutex {
private:
DictionaryItem &item_;
public:
DictionaryMutex(DictionaryItem &item) :
item_(item) {
item_.semaphor_++;
}
~DictionaryMutex() {
item_.semaphor_--;
}
};
class Dictionary {
private:
DictionaryType dictionary_;
DictionaryItem invalid_item_;
public:
DictionaryIterator begin() {
return dictionary_.begin();
}
DictionaryIterator end() {
return dictionary_.end();
}
bool Exists(std::string name) const {
auto item = dictionary_.find(name);
return item != dictionary_.end();
}
DictionaryItem& Find(std::string name) {
auto item = dictionary_.find(name);
if (item != dictionary_.end())
return item->second;
else
return invalid_item_;
}
Sequence& FindSequence(std::string name) {
return Find(name).sequence_;
}
Sequence& FindSequence(Blob &Q) {
const std::string name = Q["@"].atom();
return FindSequence(name);
}
DictionaryItem& Insert(DictionaryItem item, std::string name) {
if (!item.ValidName(name))
throw EDictionary().msg(name + ": Illegal character in name.");
if (Exists(name))
throw EDictionary().msg(name + ": Name already used.");
dictionary_.insert( { { name, item } });
return Find(name);
}
Sequence& InsertSequence(std::string name) {
DictionaryItem item;
item.type_ = dic_item_type::patch;
return Insert(item, name).sequence_;
}
bool Delete(std::string name, bool protect = false) {
auto item = dictionary_.find(name);
if (item != dictionary_.end()) {
if (item->second.semaphor_)
return false;
if (protect
&& (item->second.protection_level_
> dic_item_protection::normal))
return false;
else {
dictionary_.erase(item);
return true;
}
} else
return false;
}
void Clear(bool protect = false) {
DictionaryIteratorList list;
for (auto item = dictionary_.begin(); item != dictionary_.end();
item++) {
if (!item->second.semaphor_)
if ((!protect)
|| (item->second.protection_level_
<= dic_item_protection::normal))
list.push_back(item);
}
for (auto it : list)
dictionary_.erase(it);
}
void Rename(std::string old_name, std::string new_name) {
auto node = dictionary_.extract(old_name); //@suppress("Method cannot be resolved")
node.key() = new_name; //@suppress("Method cannot be resolved")
dictionary_.insert(move(node)); //@suppress("Invalid arguments") @suppress("Function cannot be resolved")
}
void ListEntries(Blob &Q);
static void WriteSlotProtection(std::string&, dic_item_protection);
template<class T>
static void SWrite(std::string&, T, int);
};
}
#endif /* DICTIONARY_H_ */
| Java |
package miscellaneous;
import java.util.Arrays;
public class Gen {
private static int greyCode(int n1){
return n1 ^ (n1 >> 1);
}
/*
* Advances l1 to next lexicographical higher combination.
* cap is the largest value allowed for one index.
* return false
*/
public static boolean nextComb(int[] l1, int cap){
for (int ptr = l1.length-1;;){
if (ptr < 0) return false;
if (l1[ptr] == cap - 1){
l1[ptr] = 0;
ptr--;
}
else {
l1[ptr]++;
break;
}
}
return true;
}
/*
* Advances l1 to next lexicographical higher permutation.
* 1
* Find the highest index i such that s[i] < s[i+1].
* If no such index exists, the permutation is the last permutation.
* 2
* Find the highest index j > i such that s[j] > s[i].
* Such a j must exist, since i+1 is such an index.
* 3
* Swap s[i] with s[j].
* 4
* Reverse all the order of all of the elements after index i
*/
public static void swap(int[] l1, int a, int b){
int k1 = l1[a];l1[a]=l1[b];l1[b]=k1;
}
public static void rev(int[] l1, int a, int b){
for (int i = 0; i < (b-a+1)/2;i++) swap(l1,a+i,b-i);
}
public static boolean nextPerm(int[] l1) {
for (int i = l1.length- 2; i >=0; i--) {
if (l1[i] < l1[i + 1]){
for (int k = l1.length - 1; k>=0;k--){
if (l1[k]>=l1[i]){
swap(l1,i,k);
rev(l1,i+1,l1.length-1);
return true;
}
}
}
}
rev(l1,0,l1.length-1);
return false;
}
public static int[] permInv(int[] l1){
int[] fin = new int[l1.length];
for (int i = 0; i< l1.length;i++){
fin[l1[i]]=i;
}
return fin;
}
} | Java |
#
# -*- coding: utf-8 -*-
# Dia Group Resize Plugin
# Copyright (c) 2015, Alexandre Machado <axmachado@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys, dia
import os
import pygtk
pygtk.require("2.0")
import gtk
import locale
class ResizeWindow(object):
def __init__(self, group, data):
self.group = group
self.data = data
self.initWindow()
def initWindow(self):
self.dlg = gtk.Dialog()
self.dlg.set_title('Group Resize')
self.dlg.set_border_width(6)
self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5)
self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY)
self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
self.dlg.set_has_separator(True)
self.dlg.set_modal(False)
self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None)
self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None)
def dimensionsFrame(self, label):
frame = gtk.Frame(label)
table = gtk.Table(rows=4, columns=2)
ignore = gtk.RadioButton(group=None, label="do not change")
ignore.show()
smallest = gtk.RadioButton(group=ignore, label="shrink to smallest")
smallest.show()
largest = gtk.RadioButton(group=ignore, label="enlarge to largest")
largest.show()
specify = gtk.RadioButton(group=ignore, label="resize to:")
specify.show()
value = gtk.Entry()
value.show()
specify.connect("toggled", self.enableValueEntry, value)
self.enableValueEntry(specify, value)
table.attach (ignore, 0, 1, 0, 1)
table.attach (smallest, 0, 1, 1, 2)
table.attach (largest, 0, 1, 2, 3)
table.attach (specify, 0, 1, 3, 4)
table.attach (value, 1, 2, 3, 4)
frame.add(table)
table.show()
frame.show()
options = {
'ignore': ignore,
'smallest': smallest,
'largest': largest,
'specify': specify,
'value': value
}
return frame, options
def enableValueEntry(self, radioSpecify, entrySpecify, *args):
entrySpecify.set_sensitive(radioSpecify.get_active())
def contentsFrameWidth(self):
frame, self.widthOptions = self.dimensionsFrame('Width')
return frame
def contentsFrameHeight(self):
frame, self.heightOptions = self.dimensionsFrame('Height')
return frame
def dialogContents(self):
contents = gtk.VBox(spacing=5)
contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True)
contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True)
contents.show()
return contents
def getSelectedGroupOption(self, options):
value = options['value'].get_text()
for opt in 'ignore', 'smallest', 'largest', 'specify':
if options[opt].get_active():
return (opt,value)
return ('ignore',value)
def getValue(self, opt, value, elProperty):
if opt == 'specify':
return self.toFloat(value)
else:
values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ]
if opt == 'smallest':
return min(values)
else:
return max(values)
def adjustWidth(self, value):
for obj in self.group:
pos = obj.properties['obj_pos'].value
if obj.properties.has_key("elem_width"):
difference = value - obj.properties['elem_width'].value
handleLeft = obj.handles[3]
handleRight = obj.handles[4]
amount = difference/2
obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0)
obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0)
obj.move(pos.x, pos.y)
def adjustHeight(self, value):
for obj in self.group:
pos = obj.properties['obj_pos'].value
if obj.properties.has_key("elem_height"):
difference = value - obj.properties['elem_height'].value
handleTop = obj.handles[1]
handleBottom = obj.handles[6]
amount = difference/2
obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0)
obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0)
obj.move(pos.x, pos.y)
def toFloat(self, valor):
return locale.atof(valor)
def clickAplicar(self, *args):
optWidth = self.getSelectedGroupOption(self.widthOptions)
optHeight = self.getSelectedGroupOption(self.heightOptions)
try:
if optWidth[0] != 'ignore':
width = self.getValue(optWidth[0], optWidth[1], 'elem_width')
self.adjustWidth(width)
if optHeight[0] != 'ignore':
height = self.getValue(optHeight[0], optHeight[1], 'elem_height')
self.adjustHeight(height)
if dia.active_display():
diagram = dia.active_display().diagram
for obj in self.group:
diagram.update_connections(obj)
except Exception,e:
dia.message(gtk.MESSAGE_ERROR, repr(e))
if dia.active_display():
dia.active_display().add_update_all()
dia.active_display().flush()
def show(self):
self.dlg.show()
def hide(self, *args):
self.dlg.hide()
def run(self):
return self.dlg.run()
def dia_group_resize_db (data,flags):
diagram = dia.active_display().diagram
group = diagram.get_sorted_selected()
if len(group) > 0:
win = ResizeWindow(group, data)
win.show()
else:
dia.message(gtk.MESSAGE_INFO, "Please select a group of objects")
dia.register_action("ObjectGroupResize", "Group Resize",
"/DisplayMenu/Objects/ObjectsExtensionStart",
dia_group_resize_db)
| Java |
# SagittariuSEC
This repository is stale and only serves as public archive for my master thesis. However, rules developed for the thesis serve as a base for frankenstack correlator. Please see [this repo](https://github.com/ccdcoe/frankenSEC) for more up-to-date version of the rules.
## Old readme
This SEC ruleset is designed to indentify common attack patterns from server log files. Currently, it supports identification of authentication attacks from various services, general web application injections and some forms of DNS amplification attacks.
NOTE: Please edit action.sec file to match your environment.
```
pattern=\S*(?:192\\.168\\.\d{1,3}\\.\d{1,3})
```
For example if your internal network uses 10.0.0.0/8 range then use the following regular expression:
```
pattern=\S*(?:10(?:\\.\d{1,3}){3})
```
### Simple deployment
```
cd /opt
git pull https://github.com/markuskont/SagittariuSEC
sec --detach --conf=/opt/SagittariuSEC/rules/\*.sec --input=/var/log/\*.log --syslog=daemon
```
Rules in actions.sec file can be used to block attackers in real time. Some basic scripts for that are provided in Scripts folder. These scripts can be executed over key-based SSH connection on central firewall.
```
vim /opt/SagittariuSEC/rules/actions.sec
```
```
action=logonly; event IP_BLOCKED_$+{remote_IP}; shellcmd (ssh root@firewall.domain.ex 'bash -s' -- < /opt/SagittariuSEC/scripts/iptables.sh $+{remote_IP}
```
Simple ruleset update, custom actions will be preserved
```
cd /opt/SagittariuSEC/
mv rules/actions.sec /tmp/ && git pull && mv /tmp/actions.sec rules/
```
| Java |
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - pygmaps </title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(37.750000, -122.427325);
var myOptions = {
zoom: 13,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(37.707418, -122.447039);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "222 Whittier St, Daly City, CA 94014, USA employee_id 485",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721335, -122.429407);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "435 Vienna St, San Francisco, CA 94112, USA employee_id 383",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706102, -122.450627);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "80 Risel Ave, Daly City, CA 94014, USA employee_id 525",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719312, -122.428504);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "928 Persia Ave, San Francisco, CA 94112, USA employee_id 93",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716105, -122.437706);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "801 Lisbon St, San Francisco, CA 94112, USA employee_id 1364",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714655, -122.436449);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1169 Geneva Ave, San Francisco, CA 94112, USA employee_id 1312",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719745, -122.443181);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "16 Navajo Ave, San Francisco, CA 94112, USA employee_id 1874",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713955, -122.439535);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "55 Curtis St, San Francisco, CA 94112, USA employee_id 971",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715138, -122.435856);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "924 Naples St, San Francisco, CA 94112, USA employee_id 236",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705865, -122.450057);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "59 Risel Ave, Daly City, CA 94014, USA employee_id 1528",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720619, -122.431192);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "600 Persia Ave, San Francisco, CA 94112, USA employee_id 1864",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706156, -122.450468);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "72 Risel Ave, Daly City, CA 94014, USA employee_id 708",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712880, -122.439150);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "135 Morse St, San Francisco, CA 94112, USA employee_id 1355",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710570, -122.449228);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "562 Ellington Ave, San Francisco, CA 94112, USA employee_id 529",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705126, -122.448653);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "324 Frankfort St, Daly City, CA 94014, USA employee_id 547",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713952, -122.440165);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "56 Curtis St, San Francisco, CA 94112, USA employee_id 517",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710839, -122.438039);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1183 Munich St, San Francisco, CA 94112, USA employee_id 1545",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704876, -122.451706);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "510 Bellevue Ave, Daly City, CA 94014, USA employee_id 939",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712817, -122.434488);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "417 Rolph St, San Francisco, CA 94112, USA employee_id 74",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715740, -122.440196);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "966 Geneva Ave, San Francisco, CA 94112, USA employee_id 302",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712829, -122.431958);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1499 Geneva Ave, San Francisco, CA 94112, USA employee_id 359",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711065, -122.446626);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "720 Morse St, San Francisco, CA 94112, USA employee_id 1392",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718336, -122.442164);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2150 Alemany Blvd, San Francisco, CA 94112, USA employee_id 2161",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706396, -122.450254);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "631 Hanover St, Daly City, CA 94014, USA employee_id 1785",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720781, -122.431428);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "502 Naples St, San Francisco, CA 94112, USA employee_id 253",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714951, -122.437109);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1131 Geneva Ave, San Francisco, CA 94112, USA employee_id 388",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712299, -122.440232);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "233 Pope St, San Francisco, CA 94112, USA employee_id 377",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711405, -122.435790);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "200 Cordova St, San Francisco, CA 94112, USA employee_id 1446",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711171, -122.446392);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5601 Mission St, San Francisco, CA 94112, USA employee_id 1521",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721311, -122.431203);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "474 Naples St, San Francisco, CA 94112, USA employee_id 1952",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720635, -122.428441);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "446 Moscow St, San Francisco, CA 94112, USA employee_id 128",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716351, -122.437603);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "301 Amazon Ave, San Francisco, CA 94112, USA employee_id 1626",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705624, -122.451269);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "260 Acton St, Daly City, CA 94014, USA employee_id 1054",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711412, -122.433893);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1 Naylor St, San Francisco, CA 94112, USA employee_id 693",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715337, -122.436784);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "934 Edinburgh St, San Francisco, CA 94112, USA employee_id 1208",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711418, -122.447039);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5620 Mission St, San Francisco, CA 94112, USA employee_id 2033",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717344, -122.442116);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "820 Geneva Ave, San Francisco, CA 94112, USA employee_id 1179",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720139, -122.430164);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "750 Persia Ave, San Francisco, CA 94112, USA employee_id 551",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713817, -122.433971);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "975 Athens St, San Francisco, CA 94112, USA employee_id 915",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717345, -122.441312);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "855 Geneva Ave, San Francisco, CA 94112, USA employee_id 2017",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714753, -122.440363);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "20 Curtis St, San Francisco, CA 94112, USA employee_id 1374",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718863, -122.442497);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "34 Bannock St, San Francisco, CA 94112, USA employee_id 475",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713768, -122.434010);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "981 Athens St, San Francisco, CA 94112, USA employee_id 1399",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711307, -122.437906);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1225 Naples St, San Francisco, CA 94112, USA employee_id 1419",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719157, -122.429961);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "551 Athens St, San Francisco, CA 94112, USA employee_id 137",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712030, -122.431075);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "737 Rolph St, San Francisco, CA 94112, USA employee_id 616",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716494, -122.441022);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "899 Geneva Ave, San Francisco, CA 94112, USA employee_id 439",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704113, -122.449915);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "708 Acton St, Daly City, CA 94014, USA employee_id 1661",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719500, -122.440566);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2044 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1436",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715816, -122.438598);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "850 Lisbon St, San Francisco, CA 94112, USA employee_id 1811",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710955, -122.436691);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1144 Munich St, San Francisco, CA 94112, USA employee_id 1456",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713768, -122.434010);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "981 Athens St, San Francisco, CA 94112, USA employee_id 1948",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720253, -122.442814);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "222 Seneca Ave, San Francisco, CA 94112, USA employee_id 964",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709256, -122.445324);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "242 Lowell St, San Francisco, CA 94112, USA employee_id 460",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710869, -122.433206);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "781 Prague St, San Francisco, CA 94112, USA employee_id 86",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.708451, -122.445935);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "440 Hanover St, San Francisco, CA 94112, USA employee_id 641",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720870, -122.431248);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "598 Persia Ave, San Francisco, CA 94112, USA employee_id 911",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719428, -122.429354);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "524 Moscow St, San Francisco, CA 94112, USA employee_id 1966",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716861, -122.441020);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5098 Mission St, San Francisco, CA 94112, USA employee_id 1281",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719484, -122.430812);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "555 Vienna St, San Francisco, CA 94112, USA employee_id 765",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718319, -122.443246);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "730 Geneva Ave, San Francisco, CA 94112, USA employee_id 1950",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715001, -122.438644);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1062 Geneva Ave, San Francisco, CA 94112, USA employee_id 1681",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716646, -122.437312);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "751 Lisbon St, San Francisco, CA 94112, USA employee_id 733",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707339, -122.444193);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "428 Lowell St, San Francisco, CA 94112, USA employee_id 1260",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715356, -122.434677);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "827 Vienna St, San Francisco, CA 94112, USA employee_id 1397",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717452, -122.442325);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2201 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1056",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704931, -122.450703);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "302 Acton St, Daly City, CA 94014, USA employee_id 512",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712180, -122.430433);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1576 Geneva Ave, San Francisco, CA 94112, USA employee_id 920",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705795, -122.452031);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "439 Templeton Ave, Daly City, CA 94014, USA employee_id 1402",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705295, -122.449214);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "439 Bellevue Ave, Daly City, CA 94014, USA employee_id 1534",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718922, -122.430139);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "567 Athens St, San Francisco, CA 94112, USA employee_id 1161",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719645, -122.442508);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1198 Cayuga Ave, San Francisco, CA 94112, USA employee_id 433",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704428, -122.449119);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "361 Frankfort St, Daly City, CA 94014, USA employee_id 1834",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712097, -122.436040);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "102 Cordova St, San Francisco, CA 94112, USA employee_id 217",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713970, -122.434465);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "976 Athens St, San Francisco, CA 94112, USA employee_id 565",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720755, -122.440328);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1101 Cayuga Ave, San Francisco, CA 94112, USA employee_id 2181",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715075, -122.438819);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1050 Geneva Ave, San Francisco, CA 94112, USA employee_id 536",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705754, -122.451949);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "449 Templeton Ave, Daly City, CA 94014, USA employee_id 580",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714455, -122.432822);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "899 Moscow St, San Francisco, CA 94112, USA employee_id 1717",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709040, -122.448493);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "728 Brunswick St, San Francisco, CA 94112, USA employee_id 854",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706769, -122.449489);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "615 Hanover St, Daly City, CA 94014, USA employee_id 2100",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714466, -122.439780);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "25 Curtis St, San Francisco, CA 94112, USA employee_id 2079",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712805, -122.433227);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "4 S Hill Blvd, San Francisco, CA 94112, USA employee_id 1145",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710285, -122.433059);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "198 Naylor St, San Francisco, CA 94112, USA employee_id 1028",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718632, -122.441273);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2099 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1862",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712720, -122.435761);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "43 Cordova St, San Francisco, CA 94112, USA employee_id 1656",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710100, -122.448641);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5715 Mission St, San Francisco, CA 94112, USA employee_id 1786",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712163, -122.430349);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1580 Geneva Ave, San Francisco, CA 94112, USA employee_id 322",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712375, -122.431055);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1544 Geneva Ave, San Francisco, CA 94112, USA employee_id 1590",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712394, -122.435022);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1121 Athens St, San Francisco, CA 94112, USA employee_id 1283",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707112, -122.449736);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "618 Hanover St, Daly City, CA 94014, USA employee_id 1618",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706562, -122.451221);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "199 Acton St, Daly City, CA 94014, USA employee_id 27",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712744, -122.439745);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "207 Morse St, San Francisco, CA 94112, USA employee_id 1992",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719341, -122.430513);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "554 Athens St, San Francisco, CA 94112, USA employee_id 940",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707353, -122.450127);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "131 Winchester St, Daly City, CA 94014, USA employee_id 208",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719543, -122.430767);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "553 Vienna St, San Francisco, CA 94112, USA employee_id 1739",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719645, -122.442508);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1198 Cayuga Ave, San Francisco, CA 94112, USA employee_id 1075",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704536, -122.448801);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "343 Frankfort St, Daly City, CA 94014, USA employee_id 1284",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716063, -122.439535);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "965 Geneva Ave, San Francisco, CA 94112, USA employee_id 864",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709109, -122.445628);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "240 Lowell St, San Francisco, CA 94112, USA employee_id 110",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706396, -122.450254);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "631 Hanover St, Daly City, CA 94014, USA employee_id 702",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714446, -122.430587);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "799 Moscow St, San Francisco, CA 94112, USA employee_id 2062",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706532, -122.449361);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "16 Risel Ave, Daly City, CA 94014, USA employee_id 238",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715999, -122.437379);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "900 Madrid St, San Francisco, CA 94112, USA employee_id 627",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713323, -122.437458);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "31 Morse St, San Francisco, CA 94112, USA employee_id 1112",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720705, -122.430437);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "645 Persia Ave, San Francisco, CA 94112, USA employee_id 613",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721764, -122.430797);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "444 Naples St, San Francisco, CA 94112, USA employee_id 204",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711150, -122.434295);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2 Naylor St, San Francisco, CA 94112, USA employee_id 72",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718319, -122.443246);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "730 Geneva Ave, San Francisco, CA 94112, USA employee_id 1890",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720432, -122.440481);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1117 Cayuga Ave, San Francisco, CA 94112, USA employee_id 853",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718932, -122.438829);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "4963 Mission St, San Francisco, CA 94112, USA employee_id 2130",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715420, -122.438155);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1063 Geneva Ave, San Francisco, CA 94112, USA employee_id 1164",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704167, -122.449968);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "706 Acton St, Daly City, CA 94014, USA employee_id 1877",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705234, -122.450918);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "498 Bellevue Ave, Daly City, CA 94014, USA employee_id 697",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720274, -122.443129);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "231 Seneca Ave, San Francisco, CA 94112, USA employee_id 133",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704428, -122.449119);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "361 Frankfort St, Daly City, CA 94014, USA employee_id 390",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720523, -122.431800);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "526 Naples St, San Francisco, CA 94112, USA employee_id 2166",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706396, -122.450254);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "631 Hanover St, Daly City, CA 94014, USA employee_id 1766",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716822, -122.437179);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "731 Lisbon St, San Francisco, CA 94112, USA employee_id 2011",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711454, -122.432412);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "616 Rolph St, San Francisco, CA 94112, USA employee_id 1725",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704568, -122.449096);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "355 Frankfort St, Daly City, CA 94014, USA employee_id 1274",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705160, -122.449611);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "459 Bellevue Ave, Daly City, CA 94014, USA employee_id 130",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711547, -122.437721);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1201 Naples St, San Francisco, CA 94112, USA employee_id 1938",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721426, -122.429401);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "431 Vienna St, San Francisco, CA 94112, USA employee_id 223",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715694, -122.440122);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "974 Geneva Ave, San Francisco, CA 94112, USA employee_id 1368",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713954, -122.434992);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1253 Geneva Ave, San Francisco, CA 94112, USA employee_id 371",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713188, -122.437810);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "57 Morse St, San Francisco, CA 94112, USA employee_id 1479",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720202, -122.440980);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1138 Cayuga Ave, San Francisco, CA 94112, USA employee_id 905",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718831, -122.430247);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "575 Athens St, San Francisco, CA 94112, USA employee_id 575",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704882, -122.449368);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "360 Frankfort St, Daly City, CA 94014, USA employee_id 1216",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704329, -122.449669);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "395 Frankfort St, Daly City, CA 94014, USA employee_id 952",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715586, -122.438086);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "855 Lisbon St, San Francisco, CA 94112, USA employee_id 2159",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717775, -122.441829);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "817 Geneva Ave, San Francisco, CA 94112, USA employee_id 2152",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707331, -122.449607);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "176 Oliver St, Daly City, CA 94014, USA employee_id 1478",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712765, -122.431871);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1599 Geneva Ave, San Francisco, CA 94112, USA employee_id 499",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711634, -122.430967);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "748 Rolph St, San Francisco, CA 94112, USA employee_id 1822",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705982, -122.451406);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "232 Acton St, Daly City, CA 94014, USA employee_id 1600",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716787, -122.441671);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "860 Geneva Ave, San Francisco, CA 94112, USA employee_id 1532",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706396, -122.450254);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "631 Hanover St, Daly City, CA 94014, USA employee_id 1201",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719107, -122.428503);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "418 Munich St, San Francisco, CA 94112, USA employee_id 298",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717864, -122.442716);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2200 Alemany Blvd, San Francisco, CA 94112, USA employee_id 894",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714306, -122.440257);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "42 Curtis St, San Francisco, CA 94112, USA employee_id 1223",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721330, -122.430569);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "463 Naples St, San Francisco, CA 94112, USA employee_id 2191",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704346, -122.449357);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "373 Frankfort St, Daly City, CA 94014, USA employee_id 1549",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716351, -122.437603);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "301 Amazon Ave, San Francisco, CA 94112, USA employee_id 2019",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715173, -122.435147);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "901 Naples St, San Francisco, CA 94112, USA employee_id 590",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706695, -122.450905);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "674 Hanover St, Daly City, CA 94014, USA employee_id 1894",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718676, -122.443076);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "731 Geneva Ave, San Francisco, CA 94112, USA employee_id 973",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720202, -122.440980);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1138 Cayuga Ave, San Francisco, CA 94112, USA employee_id 2115",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705865, -122.450057);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "59 Risel Ave, Daly City, CA 94014, USA employee_id 970",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721611, -122.428894);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "724 Brazil Ave, San Francisco, CA 94112, USA employee_id 1040",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706079, -122.450970);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "231 Acton St, Daly City, CA 94014, USA employee_id 1431",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714908, -122.435344);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "941 Naples St, San Francisco, CA 94112, USA employee_id 1300",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704428, -122.449119);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "361 Frankfort St, Daly City, CA 94014, USA employee_id 1787",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719013, -122.431168);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "587 Vienna St, San Francisco, CA 94112, USA employee_id 82",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.703712, -122.450675);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "724 Templeton Ave, Daly City, CA 94014, USA employee_id 1957",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712825, -122.431946);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1501 Geneva Ave, San Francisco, CA 94112, USA employee_id 508",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712641, -122.438644);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "142 Newton St, San Francisco, CA 94112, USA employee_id 266",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720836, -122.428773);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "445 Athens St, San Francisco, CA 94112, USA employee_id 858",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714446, -122.430587);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "799 Moscow St, San Francisco, CA 94112, USA employee_id 1749",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706015, -122.449774);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "43 Risel Ave, Daly City, CA 94014, USA employee_id 912",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718813, -122.429202);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "551 Moscow St, San Francisco, CA 94112, USA employee_id 634",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719719, -122.428849);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "899 Persia Ave, San Francisco, CA 94112, USA employee_id 1757",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715711, -122.435589);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "527 Amazon Ave, San Francisco, CA 94112, USA employee_id 1722",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720705, -122.430437);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "645 Persia Ave, San Francisco, CA 94112, USA employee_id 1733",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720836, -122.428773);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "445 Athens St, San Francisco, CA 94112, USA employee_id 1046",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717877, -122.441956);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "801 Geneva Ave, San Francisco, CA 94112, USA employee_id 545",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712373, -122.436415);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1224 Athens St, San Francisco, CA 94112, USA employee_id 3",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714265, -122.437001);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1162 Geneva Ave, San Francisco, CA 94112, USA employee_id 1438",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705376, -122.448976);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "427 Bellevue Ave, Daly City, CA 94014, USA employee_id 1962",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715582, -122.438915);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1025 Geneva Ave, San Francisco, CA 94112, USA employee_id 1117",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720141, -122.431000);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "524 Vienna St, San Francisco, CA 94112, USA employee_id 299",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717864, -122.442716);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2200 Alemany Blvd, San Francisco, CA 94112, USA employee_id 772",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713594, -122.434087);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1315 Geneva Ave, San Francisco, CA 94112, USA employee_id 1930",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718474, -122.430125);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "831 Russia Ave, San Francisco, CA 94112, USA employee_id 2189",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721012, -122.428560);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "431 Athens St, San Francisco, CA 94112, USA employee_id 501",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714446, -122.430587);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "799 Moscow St, San Francisco, CA 94112, USA employee_id 1066",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720047, -122.429978);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "504 Athens St, San Francisco, CA 94112, USA employee_id 101",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713760, -122.439452);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "65 Curtis St, San Francisco, CA 94112, USA employee_id 1319",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713273, -122.437528);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "35 Morse St, San Francisco, CA 94112, USA employee_id 759",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705796, -122.449434);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "436 Bellevue Ave, Daly City, CA 94014, USA employee_id 240",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719232, -122.442470);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "171 Seneca Ave, San Francisco, CA 94112, USA employee_id 1403",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712865, -122.433882);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1350 Geneva Ave, San Francisco, CA 94112, USA employee_id 49",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711145, -122.437771);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1184 Munich St, San Francisco, CA 94112, USA employee_id 1636",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710064, -122.447743);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "25 Whittier St, San Francisco, CA 94112, USA employee_id 638",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711298, -122.429729);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "814 Rolph St, San Francisco, CA 94112, USA employee_id 1437",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710751, -122.438234);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "275 Curtis St, San Francisco, CA 94112, USA employee_id 897",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719823, -122.428415);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "487 Moscow St, San Francisco, CA 94112, USA employee_id 340",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719840, -122.442825);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "207 Seneca Ave, San Francisco, CA 94112, USA employee_id 441",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720139, -122.430164);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "750 Persia Ave, San Francisco, CA 94112, USA employee_id 84",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704882, -122.449368);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "360 Frankfort St, Daly City, CA 94014, USA employee_id 523",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715999, -122.437379);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "900 Madrid St, San Francisco, CA 94112, USA employee_id 29",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714019, -122.438087);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "218 Rolph St, San Francisco, CA 94112, USA employee_id 2116",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719929, -122.430067);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "508 Athens St, San Francisco, CA 94112, USA employee_id 1567",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719157, -122.429961);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "551 Athens St, San Francisco, CA 94112, USA employee_id 1468",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718068, -122.441003);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "61 Seneca Ave, San Francisco, CA 94112, USA employee_id 2132",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705263, -122.449309);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "443 Bellevue Ave, Daly City, CA 94014, USA employee_id 1603",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720141, -122.431000);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "524 Vienna St, San Francisco, CA 94112, USA employee_id 1377",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704346, -122.449357);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "373 Frankfort St, Daly City, CA 94014, USA employee_id 2012",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.708978, -122.444411);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "376 Hanover St, San Francisco, CA 94112, USA employee_id 1007",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712650, -122.435742);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "45 Cordova St, San Francisco, CA 94112, USA employee_id 1338",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718780, -122.429843);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "566 Moscow St, San Francisco, CA 94112, USA employee_id 39",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704882, -122.449368);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "360 Frankfort St, Daly City, CA 94014, USA employee_id 783",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720806, -122.429808);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "469 Vienna St, San Francisco, CA 94112, USA employee_id 1177",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719548, -122.428180);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "931 Persia Ave, San Francisco, CA 94112, USA employee_id 234",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705651, -122.451786);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "475 Templeton Ave, Daly City, CA 94014, USA employee_id 1485",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706000, -122.450927);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "237 Acton St, Daly City, CA 94014, USA employee_id 67",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706018, -122.450780);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "88 Risel Ave, Daly City, CA 94014, USA employee_id 511",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710384, -122.448400);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5699 Mission St, San Francisco, CA 94112, USA employee_id 1847",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717002, -122.438732);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "772 Paris St, San Francisco, CA 94112, USA employee_id 1097",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704174, -122.450634);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "694 Templeton Ave, Daly City, CA 94014, USA employee_id 1793",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718659, -122.441715);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2106 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1902",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704882, -122.449368);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "360 Frankfort St, Daly City, CA 94014, USA employee_id 1266",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706564, -122.449167);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "8 Risel Ave, Daly City, CA 94014, USA employee_id 1807",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713265, -122.437051);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1118 Naples St, San Francisco, CA 94112, USA employee_id 929",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718952, -122.429028);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "539 Moscow St, San Francisco, CA 94112, USA employee_id 1776",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714700, -122.432909);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "836 Moscow St, San Francisco, CA 94112, USA employee_id 347",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709200, -122.443729);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "340 Hanover St, San Francisco, CA 94112, USA employee_id 541",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707304, -122.446092);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "251 Whittier St, Daly City, CA 94014, USA employee_id 230",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705688, -122.449751);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "452 Bellevue Ave, Daly City, CA 94014, USA employee_id 188",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714748, -122.435495);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "953 Naples St, San Francisco, CA 94112, USA employee_id 1544",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710637, -122.437565);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1171 Munich St, San Francisco, CA 94112, USA employee_id 1175",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711323, -122.438577);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1254 Naples St, San Francisco, CA 94112, USA employee_id 667",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704310, -122.451223);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "18 Alexander Ave, Daly City, CA 94014, USA employee_id 696",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712152, -122.432997);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "515 Rolph St, San Francisco, CA 94112, USA employee_id 52",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711684, -122.438310);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1220 Naples St, San Francisco, CA 94112, USA employee_id 26",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714789, -122.435429);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "949 Naples St, San Francisco, CA 94112, USA employee_id 1027",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712128, -122.433989);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "468 Rolph St, San Francisco, CA 94112, USA employee_id 254",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704921, -122.451620);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "506 Bellevue Ave, Daly City, CA 94014, USA employee_id 1571",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711947, -122.437455);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1185 Naples St, San Francisco, CA 94112, USA employee_id 614",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711112, -122.432854);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "743 Prague St, San Francisco, CA 94112, USA employee_id 296",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705566, -122.451220);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "264 Acton St, Daly City, CA 94014, USA employee_id 297",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704935, -122.450986);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "499 Bellevue Ave, Daly City, CA 94014, USA employee_id 1474",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712765, -122.431871);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1599 Geneva Ave, San Francisco, CA 94112, USA employee_id 1042",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719886, -122.442897);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "211 Seneca Ave, San Francisco, CA 94112, USA employee_id 1342",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721592, -122.429241);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "411 Vienna St, San Francisco, CA 94112, USA employee_id 1116",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711862, -122.428320);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1669 Geneva Ave, San Francisco, CA 94134, USA employee_id 94",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716179, -122.438339);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "816 Lisbon St, San Francisco, CA 94112, USA employee_id 1595",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719454, -122.428800);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "900 Persia Ave, San Francisco, CA 94112, USA employee_id 2163",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710398, -122.445372);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "155 Lowell St, San Francisco, CA 94112, USA employee_id 309",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719539, -122.429219);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "512 Moscow St, San Francisco, CA 94112, USA employee_id 1133",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712741, -122.438615);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "136 Newton St, San Francisco, CA 94112, USA employee_id 1983",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719343, -122.428032);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "998 Persia Ave, San Francisco, CA 94112, USA employee_id 1954",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713894, -122.433233);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "943 Moscow St, San Francisco, CA 94112, USA employee_id 1250",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711532, -122.430377);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "776 Rolph St, San Francisco, CA 94112, USA employee_id 1587",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.708572, -122.447200);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "145 Whittier St, San Francisco, CA 94112, USA employee_id 895",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712068, -122.438348);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "198 Newton St, San Francisco, CA 94112, USA employee_id 1599",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706000, -122.450927);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "237 Acton St, Daly City, CA 94014, USA employee_id 454",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707487, -122.447051);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "216 Whittier St, Daly City, CA 94014, USA employee_id 2074",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715845, -122.435795);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "851 Edinburgh St, San Francisco, CA 94112, USA employee_id 778",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715138, -122.435856);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "924 Naples St, San Francisco, CA 94112, USA employee_id 1748",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718864, -122.441373);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2098 Alemany Blvd, San Francisco, CA 94112, USA employee_id 797",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704918, -122.451271);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "598 Templeton Ave, Daly City, CA 94014, USA employee_id 1358",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720928, -122.430403);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "480 Vienna St, San Francisco, CA 94112, USA employee_id 2086",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714455, -122.432822);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "899 Moscow St, San Francisco, CA 94112, USA employee_id 2063",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705451, -122.451540);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "501 Templeton Ave, Daly City, CA 94014, USA employee_id 724",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714446, -122.430587);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "799 Moscow St, San Francisco, CA 94112, USA employee_id 1482",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718767, -122.442621);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "46 Bannock St, San Francisco, CA 94112, USA employee_id 1812",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718956, -122.443315);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1271 Cayuga Ave, San Francisco, CA 94112, USA employee_id 1838",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718957, -122.429710);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "554 Moscow St, San Francisco, CA 94112, USA employee_id 2021",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710064, -122.447743);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "25 Whittier St, San Francisco, CA 94112, USA employee_id 1455",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714199, -122.435502);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1231 Geneva Ave, San Francisco, CA 94112, USA employee_id 786",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716939, -122.440305);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5103 Mission St, San Francisco, CA 94112, USA employee_id 2075",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719893, -122.441421);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1158 Cayuga Ave, San Francisco, CA 94112, USA employee_id 857",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704352, -122.450921);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "14 Alexander Ave, Daly City, CA 94014, USA employee_id 1726",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714446, -122.430587);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "799 Moscow St, San Francisco, CA 94112, USA employee_id 1313",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.713183, -122.439723);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "92 Curtis St, San Francisco, CA 94112, USA employee_id 799",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720517, -122.439912);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "65 Oneida Ave, San Francisco, CA 94112, USA employee_id 1949",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718632, -122.441273);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2099 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1669",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710187, -122.444950);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "572 Brunswick St, San Francisco, CA 94112, USA employee_id 1565",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718599, -122.440208);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "165 Bertita St, San Francisco, CA 94112, USA employee_id 699",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712163, -122.430349);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1580 Geneva Ave, San Francisco, CA 94112, USA employee_id 1296",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709124, -122.445432);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "244 Lowell St, San Francisco, CA 94112, USA employee_id 370",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712765, -122.431871);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1599 Geneva Ave, San Francisco, CA 94112, USA employee_id 768",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706122, -122.448841);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "282 Oliver St, Daly City, CA 94014, USA employee_id 1574",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.703712, -122.450675);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "724 Templeton Ave, Daly City, CA 94014, USA employee_id 1166",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710595, -122.447505);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "762 Morse St, San Francisco, CA 94112, USA employee_id 1428",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704228, -122.450034);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "702 Acton St, Daly City, CA 94014, USA employee_id 1273",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712835, -122.439143);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "141 Morse St, San Francisco, CA 94112, USA employee_id 2147",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719489, -122.429307);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "522 Moscow St, San Francisco, CA 94112, USA employee_id 1710",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712462, -122.435633);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "65 Cordova St, San Francisco, CA 94112, USA employee_id 366",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717864, -122.442716);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2200 Alemany Blvd, San Francisco, CA 94112, USA employee_id 803",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714152, -122.440631);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "91 Pope St, San Francisco, CA 94112, USA employee_id 12",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719764, -122.428460);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "491 Moscow St, San Francisco, CA 94112, USA employee_id 1205",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705499, -122.450304);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "474 Bellevue Ave, Daly City, CA 94014, USA employee_id 1323",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718873, -122.443164);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "715 Geneva Ave, San Francisco, CA 94112, USA employee_id 1426",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716644, -122.438789);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "198 Amazon Ave, San Francisco, CA 94112, USA employee_id 532",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717931, -122.439567);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5025 Mission St, San Francisco, CA 94112, USA employee_id 360",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715876, -122.438556);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "842 Lisbon St, San Francisco, CA 94112, USA employee_id 1288",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706135, -122.448492);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "398 Bellevue Ave, Daly City, CA 94014, USA employee_id 286",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705224, -122.449423);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "451 Bellevue Ave, Daly City, CA 94014, USA employee_id 1507",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710954, -122.436604);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1142 Munich St, San Francisco, CA 94112, USA employee_id 291",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709885, -122.440592);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "405 Allison St, San Francisco, CA 94112, USA employee_id 33",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706914, -122.450391);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "656 Hanover St, Daly City, CA 94014, USA employee_id 727",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704881, -122.449168);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "348 Frankfort St, Daly City, CA 94014, USA employee_id 1026",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711031, -122.448505);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "512 Ellington Ave, San Francisco, CA 94112, USA employee_id 1985",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714455, -122.432822);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "899 Moscow St, San Francisco, CA 94112, USA employee_id 1869",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715885, -122.437872);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "825 Lisbon St, San Francisco, CA 94112, USA employee_id 674",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721306, -122.428338);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "411 Athens St, San Francisco, CA 94112, USA employee_id 1604",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706803, -122.444792);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "233 Bellevue Ave, Daly City, CA 94014, USA employee_id 1898",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707122, -122.449192);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "599 Hanover St, Daly City, CA 94014, USA employee_id 937",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704842, -122.451777);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "518 Bellevue Ave, Daly City, CA 94014, USA employee_id 2124",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719418, -122.428726);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "906 Persia Ave, San Francisco, CA 94112, USA employee_id 392",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720366, -122.430688);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "644 Persia Ave, San Francisco, CA 94112, USA employee_id 665",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710629, -122.431657);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "96 S Hill Blvd, San Francisco, CA 94112, USA employee_id 283",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719798, -122.429528);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "808 Persia Ave, San Francisco, CA 94112, USA employee_id 932",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.704717, -122.451346);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "600 Templeton Ave, Daly City, CA 94014, USA employee_id 1582",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706917, -122.445008);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "238 Bellevue Ave, Daly City, CA 94014, USA employee_id 1940",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719670, -122.431357);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "560 Vienna St, San Francisco, CA 94112, USA employee_id 2187",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706005, -122.449645);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "39 Risel Ave, Daly City, CA 94014, USA employee_id 1541",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720366, -122.430688);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "644 Persia Ave, San Francisco, CA 94112, USA employee_id 1191",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720716, -122.429382);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "462 Athens St, San Francisco, CA 94112, USA employee_id 1867",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705715, -122.449672);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "448 Bellevue Ave, Daly City, CA 94014, USA employee_id 1946",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717431, -122.440698);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5060 Mission St, San Francisco, CA 94112, USA employee_id 782",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718929, -122.430824);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "582 Athens St, San Francisco, CA 94112, USA employee_id 1616",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705591, -122.451784);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "487 Templeton Ave, Daly City, CA 94014, USA employee_id 1052",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718244, -122.439399);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2 Italy Ave, San Francisco, CA 94112, USA employee_id 495",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715219, -122.437267);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "955 Madrid St, San Francisco, CA 94112, USA employee_id 434",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719787, -122.429320);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "816 Persia Ave, San Francisco, CA 94112, USA employee_id 345",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.715647, -122.439930);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "984 Geneva Ave, San Francisco, CA 94112, USA employee_id 382",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706392, -122.450598);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "671 Hanover St, Daly City, CA 94014, USA employee_id 1188",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721625, -122.442156);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "499 Otsego Ave, San Francisco, CA 94112, USA employee_id 500",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712185, -122.439025);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "167 Curtis St, San Francisco, CA 94112, USA employee_id 1550",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709885, -122.440592);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "405 Allison St, San Francisco, CA 94112, USA employee_id 1975",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720294, -122.439111);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1991 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1746",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719936, -122.440101);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2010 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1945",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705405, -122.448472);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "322 Oliver St, Daly City, CA 94014, USA employee_id 428",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705250, -122.451294);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "551 Templeton Ave, Daly City, CA 94014, USA employee_id 372",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719455, -122.443479);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "11 Navajo Ave, San Francisco, CA 94112, USA employee_id 216",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721153, -122.431377);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "531 Persia Ave, San Francisco, CA 94112, USA employee_id 1880",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717172, -122.438072);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "737 Paris St, San Francisco, CA 94112, USA employee_id 1789",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714168, -122.437490);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "243 Rolph St, San Francisco, CA 94112, USA employee_id 447",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709996, -122.445371);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "195 Lowell St, San Francisco, CA 94112, USA employee_id 2169",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718587, -122.439160);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "4987 Mission St, San Francisco, CA 94112, USA employee_id 996",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.721592, -122.429241);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "411 Vienna St, San Francisco, CA 94112, USA employee_id 885",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.716944, -122.437771);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "742 Lisbon St, San Francisco, CA 94112, USA employee_id 617",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719698, -122.431220);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "554 Vienna St, San Francisco, CA 94112, USA employee_id 278",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714185, -122.436712);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1184 Geneva Ave, San Francisco, CA 94112, USA employee_id 1194",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718716, -122.429206);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "555 Moscow St, San Francisco, CA 94112, USA employee_id 620",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712933, -122.434032);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1340 Geneva Ave, San Francisco, CA 94112, USA employee_id 1165",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711358, -122.435150);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "221 Cordova St, San Francisco, CA 94112, USA employee_id 1581",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.714428, -122.433091);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "900 Moscow St, San Francisco, CA 94112, USA employee_id 805",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712775, -122.434420);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "429 Rolph St, San Francisco, CA 94112, USA employee_id 930",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720241, -122.430874);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "516 Vienna St, San Francisco, CA 94112, USA employee_id 993",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.707244, -122.450338);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "143 Winchester St, Daly City, CA 94014, USA employee_id 1650",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720310, -122.429776);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "498 Athens St, San Francisco, CA 94112, USA employee_id 809",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711178, -122.445168);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "651 Morse St, San Francisco, CA 94112, USA employee_id 2090",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719692, -122.429305);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "818 Persia Ave, San Francisco, CA 94112, USA employee_id 824",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718396, -122.440455);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "181 Bertita St, San Francisco, CA 94112, USA employee_id 844",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.711383, -122.438534);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1250 Naples St, San Francisco, CA 94112, USA employee_id 1598",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718988, -122.430780);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "578 Athens St, San Francisco, CA 94112, USA employee_id 1939",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.710856, -122.437549);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1173 Munich St, San Francisco, CA 94112, USA employee_id 1816",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719611, -122.431402);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "562 Vienna St, San Francisco, CA 94112, USA employee_id 1649",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.706008, -122.447120);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "341 Bellevue Ave, Daly City, CA 94014, USA employee_id 2170",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719105, -122.430691);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "568 Athens St, San Francisco, CA 94112, USA employee_id 1623",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718433, -122.438972);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "15 Italy Ave, San Francisco, CA 94112, USA employee_id 1888",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718111, -122.441481);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2133 Alemany Blvd, San Francisco, CA 94112, USA employee_id 983",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717544, -122.439865);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "5059 Mission St, San Francisco, CA 94112, USA employee_id 1012",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.720460, -122.431146);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "509 Naples St, San Francisco, CA 94112, USA employee_id 1608",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.717177, -122.441098);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "875 Geneva Ave, San Francisco, CA 94112, USA employee_id 1053",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.719438, -122.440720);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "2050 Alemany Blvd, San Francisco, CA 94112, USA employee_id 1126",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.705334, -122.448473);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "330 Oliver St, Daly City, CA 94014, USA employee_id 385",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.712765, -122.431871);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/FF0000.png');
var marker = new google.maps.Marker({
title: "1599 Geneva Ave, San Francisco, CA 94112, USA employee_id 1025",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.718478, -122.439536);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/008000.png');
var marker = new google.maps.Marker({
title: "centroid",
icon: img,
position: latlng
});
marker.setMap(map);
var latlng = new google.maps.LatLng(37.709688, -122.450124);
var img = new google.maps.MarkerImage('/home/jeremy/anaconda3/lib/python3.5/site-packages/gmplot/markers/008000.png');
var marker = new google.maps.Marker({
title: "centroid",
icon: img,
position: latlng
});
marker.setMap(map);
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
| Java |
#!/bin/bash
# Created by Nahuel Barrios on 27/3/16.
# shellcheck disable=SC1091
preInstallationLog "Gnome System Tools"
sudo apt-get -fy install gnome-system-tools
postInstallationLog "Gnome System Tools"
logInfo "Available programs: network-admin, shares-admin, time-admin, users-admin"
logInfo "Installing packages to compress and extract different kind of files..."
sudo apt-get -fy install unace unrar zip unzip p7zip-full p7zip-rar sharutils rar uudeview mpack arj cabextract
preInstallationLog "GParted with NTFS support"
sudo apt-get -fy install gparted ntfs-3g
logInfo "Adding repositories for Rhythmbox and its plugins..."
sudo add-apt-repository ppa:fossfreedom/rhythmbox -y
sudo add-apt-repository ppa:fossfreedom/rhythmbox-plugins -y
sudo apt-get update
logInfo "Installing latest Rhythmbox and its plugins..."
sudo apt-get -fy install rhythmbox rhythmbox-plugin-rhythmweb rhythmbox-plugin-equalizer rhythmbox-plugin-opencontainingfolder rhythmbox-plugin-llyrics
preInstallationLog "Curl, Subdownloader, GMountISO, Sound Converter, Steam client (will update on first run) and PlayOnLinux"
sudo apt-get -fy install curl subdownloader gmountiso soundconverter steam playonlinux
postInstallationLog "Subdownloader, GMountISO, Freemind (a mind maps editor), Sound Converter, Steam client (will update on first run) and PlayOnLinux"
logInfo "Cleaning up..." &&
sudo apt-get -f install &&
sudo apt-get -y autoremove &&
sudo apt-get -y autoclean &&
sudo apt-get -y clean
logInfo "Updating installed packages..."
sudo apt-get upgrade | Java |
package com.xcode.bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@ManagedBean
@SessionScoped
public class UserAuth implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4027678448802658446L;
private String email;
public UserAuth() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();
email = auth.getName();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2016-2019 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::distributionModels::massRosinRammler
Description
Mass-based Rosin-Rammler distributionModel.
Corrected form of the Rosin-Rammler distribution taking into account the
varying number of particles per parcel for for fixed-mass parcels. This
distribution should be used when
\verbatim
parcelBasisType mass;
\endverbatim
See equation 10 in reference:
\verbatim
Yoon, S. S., Hewson, J. C., DesJardin, P. E., Glaze, D. J.,
Black, A. R., & Skaggs, R. R. (2004).
Numerical modeling and experimental measurements of a high speed
solid-cone water spray for use in fire suppression applications.
International Journal of Multiphase Flow, 30(11), 1369-1388.
\endverbatim
SourceFiles
massRosinRammler.C
\*---------------------------------------------------------------------------*/
#ifndef massRosinRammler_H
#define massRosinRammler_H
#include "distributionModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace distributionModels
{
/*---------------------------------------------------------------------------*\
Class massRosinRammler Declaration
\*---------------------------------------------------------------------------*/
class massRosinRammler
:
public distributionModel
{
// Private Data
//- Distribution minimum
scalar minValue_;
//- Distribution maximum
scalar maxValue_;
//- Characteristic droplet size
scalar d_;
//- Empirical dimensionless constant to specify the distribution width,
// sometimes referred to as the dispersion coefficient
scalar n_;
public:
//- Runtime type information
TypeName("massRosinRammler");
// Constructors
//- Construct from components
massRosinRammler(const dictionary& dict, Random& rndGen);
//- Construct copy
massRosinRammler(const massRosinRammler& p);
//- Construct and return a clone
virtual autoPtr<distributionModel> clone() const
{
return autoPtr<distributionModel>(new massRosinRammler(*this));
}
//- Destructor
virtual ~massRosinRammler();
// Member Functions
//- Sample the distributionModel
virtual scalar sample() const;
//- Return the minimum value
virtual scalar minValue() const;
//- Return the maximum value
virtual scalar maxValue() const;
//- Return the mean value
virtual scalar meanValue() const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace distributionModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Java |
/*
meowbot
Copyright (C) 2008-2009 Park Jeong Min <pjm0616_at_gmail_d0t_com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <deque>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <time.h>
#include <pcrecpp.h>
#include "defs.h"
#include "ircbot.h"
#include "luacpp.h"
/*
Lua는 다른 언어와 달리 기본적으로 순수한 언어로서의 기능만 제공하며,
기타 시스템 접근은 별도 라이브러리를 로드해서 사용.
따라서 시스템 접근이 가능한 라이브러리만 로드하지 않으면 안전.
예외인 루아 파일을 로드하는 dofile, loadfile 2가지 함수는
코드 실행 전에 삭제.
*/
///FIXME: 대충 만듬=_= 수정 필요
static int lua_safeeval_child(const char *code)
{
lua_State *L = luaL_newstate();
// 기본 라이브러리 로드
#define LOADLIB(name, func) \
lua_pushcfunction(L, func); \
lua_pushstring(L, name); \
lua_call(L, 1, 0);
LOADLIB("", luaopen_base)
LOADLIB("table", luaopen_table)
LOADLIB("string", luaopen_string)
LOADLIB("math", luaopen_math)
#undef LOADLIB
luaopen_libluapcre(L);
luaopen_libluautf8(L);
luaopen_libluahangul(L);
// 파일에 접근할 수 있는 함수 삭제
#define SETNIL(name) \
lua_pushliteral(L, name); \
lua_pushnil(L); \
lua_rawset(L, LUA_GLOBALSINDEX);
SETNIL("dofile");
SETNIL("loadfile");
#undef SETNIL
// 코드 실행
std::string codebuf(code);
codebuf += '\n';
int ret = luaL_loadstring(L, codebuf.c_str());
if(ret)
{
const char *errmsg = lua_tostring(L, -1);
printf("Error: %s\n", errmsg);
lua_pop(L, 1);
}
else
{
ret = lua_pcall(L, 0, 0, 0);
if(ret != 0)
{
const char *errmsg = lua_tostring(L, -1);
printf("Error: %s\n", errmsg);
lua_pop(L, 1);
}
}
lua_close(L);
return 0;
}
static void luaeval_child_signal_handler(int sig)
{
if(sig == SIGALRM)
puts("Timeout");
else
printf("Recieved signal %d\n", sig);
exit(1);
}
static int lua_safeeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, const char *code, const char *cparam)
{
int rdpipe[2];
pipe(rdpipe);
int pid = fork();
if(pid < 0)
{
close(rdpipe[0]);
close(rdpipe[1]);
return -1;
}
else if(pid == 0)
{
close(0);
dup2(rdpipe[1], 1);
dup2(rdpipe[1], 2);
close(rdpipe[0]);
signal(SIGALRM, luaeval_child_signal_handler);
alarm(2);
lua_safeeval_child(code);
exit(0);
}
else
{
close(rdpipe[1]);
int status, ret;
ret = waitpid(pid, &status, 0);
char buf[512*3+1];
ret = read(rdpipe[0], buf, sizeof(buf)-1);
close(rdpipe[0]);
if(ret < 0)
return -1;
buf[ret] = 0;
char *pp, *p = strtok_r(buf, "\n", &pp);
if(!p)
{
isrv->privmsg(mdest, "(No output)");
}
else
{
int lines = 3;
do
{
isrv->privmsg_nh(mdest, p);
} while((p = strtok_r(NULL, "\n", &pp)) && --lines);
}
}
return 0;
}
int cmd_cb_luaeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, std::string &cmd, std::string &carg, void *)
{
if(carg.empty())
{
isrv->privmsg(mdest, "사용법: !" + cmd + " <코드>");
}
else
{
lua_safeeval(isrv, pmsg, mdest, carg.c_str(), NULL);
}
return HANDLER_FINISHED;
}
#if 0
int cmd_cb_memeval(ircbot_conn *isrv, irc_privmsg &pmsg,
irc_msginfo &mdest, std::string &cmd, std::string &carg, void *)
{
(void)cmd;
std::string mname, marg;
if(!pcrecpp::RE("([^ ]+) ?(.*)").FullMatch(carg, &mname, &marg))
{
isrv->privmsg(mdest,
"사용법: !기억해 <기억 이름> !perl <코드> 등으로 기억시킨 후, "
"!기억실행 <기억 이름> 또는 !기억실행 <기억 이름> <파라미터> 로 실행 (단축: !.)");
isrv->privmsg(mdest,
" %nick%은 닉네임으로, %param%는 파라미터로 치환됩니다. "
"C,C++에서는 int nparam, const char *params[] 전역변수가 제공됩니다.");
}
else
{
const std::string &nick = pmsg.getnick();
// FIXME: use getremdb_v2
std::pair<std::string, std::string> (*getremdb_fxn)(const std::string &word);
getremdb_fxn = (std::pair<std::string, std::string> (*)(const std::string &))
isrv->bot->modules.dlsym("mod_remember", "getremdb");
if(!getremdb_fxn)
{
isrv->privmsg(mdest, "내부 오류: 이 명령에 필요한 모듈이 로드되지 않았습니다.");
return 0;
}
std::pair<std::string, std::string> data = getremdb_fxn(mname);
std::string cmd2, carg2;
if(data.first.empty())
{
isrv->privmsg(mdest, "오류: " + data.second);
}
else if(pcrecpp::RE("^!([^ ]+) (.+)").FullMatch(data.second, &cmd2, &carg2))
{
irc_cmd_eval_code(isrv, mdest, nick, cmd2, carg2, marg);
}
else
{
isrv->privmsgf_nh(mdest, "올바른 형식이 아닙니다: %s", data.second.c_str());
}
}
return HANDLER_FINISHED;
}
#endif
#include "main.h"
int mod_luaeval_init(ircbot *bot)
{
//bot->register_cmd("기억실행", cmd_cb_memeval);
//bot->register_cmd(".", cmd_cb_memeval);
bot->register_cmd("luaeval", cmd_cb_luaeval);
return 0;
}
int mod_luaeval_cleanup(ircbot *bot)
{
//bot->unregister_cmd("기억실행");
//bot->unregister_cmd(".");
bot->unregister_cmd("luaeval");
return 0;
}
MODULE_INFO(mod_luaeval, mod_luaeval_init, mod_luaeval_cleanup)
| Java |
import { NgModule } from "@angular/core";
import { SamplesModule } from "samples/samples.module";
import { SamplesRoutingModule } from "./samples.routing.module";
@NgModule({
imports: [
SamplesModule,
SamplesRoutingModule
]
})
export class SamplesFeatureModule {}
| Java |
package Yogibear617.mods.FuturisticCraft.CreativeTabs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
public class FCSBModCreativeTab extends CreativeTabs {
public FCSBModCreativeTab(int par1, String par2Str) {
super(par1, par2Str);
}
@SideOnly(Side.CLIENT)
public int getTabIconItemIndex() {
return Block.stoneBrick.blockID;
}
}
| Java |
/*
* Generated by class-dump 3.1.2.
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2007 by Steve Nygard.
*/
#import "_ABCreateStringWithAddressDictionary.h"
@interface _ABCreateStringWithAddressDictionary (RMStore)
- (id)rm_transaction;
- (id)rm_storeError;
- (id)rm_storeDownload;
- (id)rm_products;
- (id)rm_productIdentifier;
- (id)rm_invalidProductIdentifiers;
- (float)rm_downloadProgress;
@end
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.apache.poi.hssf.util.HSSFColor.VIOLET (POI API Documentation)</title>
<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="Uses of Class org.apache.poi.hssf.util.HSSFColor.VIOLET (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<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><a href="../../../../../../org/apache/poi/hssf/util/HSSFColor.VIOLET.html" title="class in org.apache.poi.hssf.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hssf/util//class-useHSSFColor.VIOLET.html" target="_top">FRAMES</a></li>
<li><a href="HSSFColor.VIOLET.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.poi.hssf.util.HSSFColor.VIOLET" class="title">Uses of Class<br>org.apache.poi.hssf.util.HSSFColor.VIOLET</h2>
</div>
<div class="classUseContainer">No usage of org.apache.poi.hssf.util.HSSFColor.VIOLET</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/poi/hssf/util/HSSFColor.VIOLET.html" title="class in org.apache.poi.hssf.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hssf/util//class-useHSSFColor.VIOLET.html" target="_top">FRAMES</a></li>
<li><a href="HSSFColor.VIOLET.html" target="_top">NO FRAMES</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2017 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| Java |
from ..models import Album
from ..resource import SingleResource, ListResource
from ..schemas import AlbumSchema
class SingleAlbum(SingleResource):
schema = AlbumSchema()
routes = ('/album/<int:id>/',)
model = Album
class ListAlbums(ListResource):
schema = AlbumSchema(many=True)
routes = ('/album/', '/tracklist/')
model = Album
| Java |
package com.eveningoutpost.dexdrip.Models;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
// from package info.nightscout.client.utils;
/**
* Created by mike on 30.12.2015.
*/
/**
* The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj
* with TZ
*/
public class DateUtil {
private static final String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // eg 2017-03-24T22:03:27Z
private static final String FORMAT_DATE_ISO2 = "yyyy-MM-dd'T'HH:mm:ssZ"; // eg 2017-03-27T17:38:14+0300
private static final String FORMAT_DATE_ISO3 = "yyyy-MM-dd'T'HH:mmZ"; // eg 2017-05-12T08:16-0400
/**
* Takes in an ISO date string of the following format:
* yyyy-mm-ddThh:mm:ss.ms+HoMo
*
* @param isoDateString the iso date string
* @return the date
* @throws Exception the exception
*/
private static Date fromISODateString(String isoDateString)
throws Exception {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
}
private static Date fromISODateString3(String isoDateString)
throws Exception {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO3);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
}
private static Date fromISODateString2(String isoDateString)
throws Exception {
try {
SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO2);
f.setTimeZone(TimeZone.getTimeZone("UTC"));
return f.parse(isoDateString);
} catch (java.text.ParseException e) {
return fromISODateString3(isoDateString);
}
}
public static Date tolerantFromISODateString(String isoDateString)
throws Exception {
try {
return fromISODateString(isoDateString.replaceFirst("\\.[0-9][0-9][0-9]Z$", "Z"));
} catch (java.text.ParseException e) {
return fromISODateString2(isoDateString);
}
}
/**
* Render date
*
* @param date the date obj
* @param format - if not specified, will use FORMAT_DATE_ISO
* @param tz - tz to set to, if not specified uses local timezone
* @return the iso-formatted date string
*/
public static String toISOString(Date date, String format, TimeZone tz) {
if (format == null) format = FORMAT_DATE_ISO;
if (tz == null) tz = TimeZone.getDefault();
DateFormat f = new SimpleDateFormat(format);
f.setTimeZone(tz);
return f.format(date);
}
public static String toISOString(Date date) {
return toISOString(date, FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC"));
}
public static String toISOString(long date) {
return toISOString(new Date(date), FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC"));
}
public static String toNightscoutFormat(long date) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
format.setTimeZone(TimeZone.getDefault());
return format.format(date);
}
} | Java |
"""
System plugin
Copyright (C) 2016 Walid Benghabrit
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from accmon.plugins.plugin import *
class System(Plugin):
def __init__(self):
super().__init__()
def handle_request(self, request):
res = super(System, self).handle_request(request)
if res is not None: return res
| Java |
/*
* Copyright (C) 2017 GedMarc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jwebmp.core.htmlbuilder.css.displays;
import com.jwebmp.core.base.client.CSSVersions;
import com.jwebmp.core.htmlbuilder.css.CSSEnumeration;
import com.jwebmp.core.htmlbuilder.css.annotations.CSSAnnotationType;
/**
* Definition and Usage
* <p>
* The display property defines how a certain HTML element should be displayed.
* Default value: inline Inherited: no Version:
* CSS1 JavaScript syntax: object.style.display="inline"
*
* @author GedMarc
* @version 1.0
* @since 2013/01/22
*/
@CSSAnnotationType
public enum Displays
implements CSSEnumeration<Displays>
{
/**
* Default value. Displays an element as an inline element (like <span>)
*/
Inline,
/**
* Displays an element as a block element (like
* <p>
* )
*/
Block,
/**
* Displays an element as an block_level flex container. New in CSS3
*/
Flex,
/**
* Displays an element as an inline_level flex container. New in CSS3
*/
Inline_flex,
/**
* The element is displayed as an inline_level table
*/
Inline_table,
/**
* Let the element behave like a <li> element
*/
List_item,
/**
* Displays an element as either block or inline, depending on context
*/
Run_in,
/**
* Let the element behave like a <table> element
*/
Table,
/**
* Let the element behave like a <caption> element
*/
Table_caption,
/**
* Let the element behave like a <colgroup> element
*/
Table_column_group,
/**
* Let the element behave like a <thead> element
*/
Table_header_group,
/**
* Let the element behave like a <tfoot> element
*/
Table_footer_group,
/**
* Let the element behave like a <tbody> element
*/
Table_row_group,
/**
* Let the element behave like a <td> element
*/
Table_cell,
/**
* Let the element behave like a <col> element
*/
Table_column,
/**
* Let the element behave like a <tr> element
*/
Table_row,
/**
* The element will not be displayed at all (has no effect on layout)
*/
None,
/**
* Sets this property to its default value. Read about initial
*/
Initial,
/**
* Inherits this property from its parent element. Read about inherit;
*/
Inherit,
/**
* Sets this field as not set
*/
Unset;
@Override
public String getJavascriptSyntax()
{
return "style.display";
}
@Override
public CSSVersions getCSSVersion()
{
return CSSVersions.CSS1;
}
@Override
public String getValue()
{
return name();
}
@Override
public Displays getDefault()
{
return Unset;
}
@Override
public String toString()
{
return super.toString()
.toLowerCase()
.replaceAll("_", "-");
}
}
| Java |
package com.projectreddog.machinemod.container;
import com.projectreddog.machinemod.inventory.SlotBlazePowder;
import com.projectreddog.machinemod.inventory.SlotNotBlazePowder;
import com.projectreddog.machinemod.inventory.SlotOutputOnlyTurobFurnace;
import com.projectreddog.machinemod.tileentities.TileEntityTurboFurnace;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
;
public class ContainerTurboFurnace extends Container {
protected TileEntityTurboFurnace turbofurnace;
protected int lastFuleBurnTimeRemaining = 0;
protected int lastProcessingTimeRemaining = 0;
public ContainerTurboFurnace(InventoryPlayer inventoryPlayer, TileEntityTurboFurnace turbofurnace) {
this.turbofurnace = turbofurnace;
lastFuleBurnTimeRemaining = -1;
lastProcessingTimeRemaining = -1;
// for (int i = 0; i < 1; i++) {
// for (int j = 0; j < 3; j++) {
addSlotToContainer(new SlotNotBlazePowder(turbofurnace, 0, 47, 34));
addSlotToContainer(new SlotOutputOnlyTurobFurnace(inventoryPlayer.player, turbofurnace, 1, 110, 53));
addSlotToContainer(new SlotBlazePowder(turbofurnace, 2, 47, 74));
// }
// }
// commonly used vanilla code that adds the player's inventory
bindPlayerInventory(inventoryPlayer);
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return turbofurnace.isUsableByPlayer(player);
}
protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 139 + i * 18));
}
}
for (int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 197));
}
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slot) {
ItemStack stack = ItemStack.EMPTY;
Slot slotObject = (Slot) inventorySlots.get(slot);
// null checks and checks if the item can be stacked (maxStackSize > 1)
if (slotObject != null && slotObject.getHasStack()) {
ItemStack stackInSlot = slotObject.getStack();
stack = stackInSlot.copy();
// merges the item into player inventory since its in the Entity
if (slot < 3) {
if (!this.mergeItemStack(stackInSlot, 3, this.inventorySlots.size(), true)) {
return ItemStack.EMPTY;
}
slotObject.onSlotChange(stackInSlot, stack);
}
// places it into the tileEntity is possible since its in the player
// inventory
else if (!this.mergeItemStack(stackInSlot, 0, 3, false)) {
return ItemStack.EMPTY;
}
if (stackInSlot.getCount() == 0) {
slotObject.putStack(ItemStack.EMPTY);
} else {
slotObject.onSlotChanged();
}
if (stackInSlot.getCount() == stack.getCount()) {
return ItemStack.EMPTY;
}
slotObject.onTake(player, stackInSlot);
}
return stack;
}
/**
* Looks for changes made in the container, sends them to every listener.
*/
public void detectAndSendChanges() {
super.detectAndSendChanges();
for (int i = 0; i < this.listeners.size(); ++i) {
IContainerListener icrafting = (IContainerListener) this.listeners.get(i);
if (this.lastFuleBurnTimeRemaining != this.turbofurnace.getField(0)) {
icrafting.sendWindowProperty(this, 0, this.turbofurnace.getField(0));
}
if (this.lastProcessingTimeRemaining != this.turbofurnace.getField(1)) {
icrafting.sendWindowProperty(this, 1, this.turbofurnace.getField(1));
}
}
this.lastFuleBurnTimeRemaining = this.turbofurnace.getField(0);
this.lastProcessingTimeRemaining = this.turbofurnace.getField(1);
}
@SideOnly(Side.CLIENT)
public void updateProgressBar(int id, int data) {
this.turbofurnace.setField(id, data);
}
}
| Java |
<div class="panel panel-default bio">
<div class="panel-body tight-inner">
<table class="table table-responsive table-ac-bordered table-hover">
<thead>
<tr>
<th data-bind="click: function(){sortBy('name');}" class="col-md-7">
Feature
<span data-bind="css: sortArrow('name')"></span>
</th>
<th data-bind="click: function(){sortBy('characterClass');}" class="col-md-4">
Class
<span data-bind="css: sortArrow('characterClass')"></span>
</th>
<th class="col-md-1">
<a data-toggle="modal"
data-target="#addFeature" href="#">
<i class="fa fa-plus fa-color"></i>
</a>
</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: filteredAndSortedFeatures -->
<tr class="clickable">
<td data-bind="text: name, click: $parent.editFeature" href="#"></td>
<td data-bind="text: characterClass, click: $parent.editFeature" href="#"></td>
<td class="col-content-vertical">
<a data-bind="click: $parent.removeFeature" href="#">
<i class="fa fa-trash-o fa-color-hover">
</i>
</a>
</td>
</tr>
<!-- /ko -->
<!-- ko if: filteredAndSortedFeatures().length == 0 -->
<tr class="clickable">
<td data-toggle="modal" data-target="#addFeature" href="#"
colspan="12" class="text-center">
<i class="fa fa-plus fa-color"></i>
Add a new Feature
</td>
</tr>
<!-- /ko -->
</tbody>
</table>
</div>
</div>
<!-- Add Modal -->
<div class="modal fade"
id="addFeature"
tabindex="-1"
role="dialog" data-bind="modal: {
onopen: modalFinishedOpening, onclose: modalFinishedClosing}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button"
class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title"
id="addFeatureLabel">Add a new Feature.</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="featureName"
placeholder="Rage"
data-bind='textInput: blankFeature().name,
autocomplete: { source: featuresPrePopFilter,
onselect: populateFeature }, hasFocus: firstModalElementHasFocus'>
</div>
</div>
<div class="form-group">
<label for="class" class="col-sm-2 control-label">Class</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="class"
placeholder="Barbarian"
data-bind='textInput: blankFeature().characterClass,
autocomplete: { source: classOptions,
onselect: populateClass }'>
</div>
</div>
<div class="form-group">
<label for="level" class="col-sm-2 control-label">Level</label>
<div class="col-sm-10">
<input type="number"
class="form-control"
id="class"
placeholder="1"
data-bind='textInput: blankFeature().level'>
</div>
</div>
<div class="form-group">
<label for="featureDescription" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea type="password"
class="form-control"
id="featureDescription"
rows="4"
placeholder="While you are not wearing any armor, your Armor Class..."
data-bind='textInput: blankFeature().description'>
</textarea>
</div>
</div>
<div class="form-group">
<label for="featureDescription" class="col-sm-3 control-label content-left">
<span class="fa fa-info-circle" style="cursor:pointer;"
data-bind="popover: { content: trackedPopoverText }"></span> Tracked?</label>
<div class="col-sm-7">
<input type="checkbox"
class="form-control"
id="tracked"
data-bind='checked: blankFeature().isTracked'>
</div>
</div>
<div data-bind="visible: blankFeature().isTracked">
<div class="form-group">
<div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:40px">
</div>
<label for="bonus" class="col-sm-2 control-label">Max</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="max" min="1"
data-bind='textInput: blankTracked().maxUses'>
</div>
</div>
<div class="form-group">
<div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:50px">
</div>
<label class="col-sm-2 control-label">Resets on...</label>
<div class="col-sm-9">
<div class="btn-group btn-group-justified" role="group">
<label class="btn btn-default"
data-bind="css: { active: blankTracked().resetsOn() == 'short'}">
<input type="radio" class="hide-block" name="blankresetsOnShort" value="short"
data-bind="checked: blankTracked().resetsOn"/>
<img class="action-bar-icon" data-bind="attr: { src: meditation }"></img>
Short Rest
</label>
<label class="btn btn-default"
data-bind="css: { active: blankTracked().resetsOn() == 'long'}">
<input type="radio" class="hide-block" name="blankresetsOnLong"
value="long" data-bind="checked: blankTracked().resetsOn"/>
<img class="action-bar-icon" data-bind="attr: { src: campingTent }"></img>
Long Rest
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-primary"
data-bind='click: addFeature'
data-dismiss="modal">Add</button>
<p class="text-muted text-left" data-bind='visible: shouldShowDisclaimer'>
<sm><i>This data is distributed under the
<a href='http://media.wizards.com/2016/downloads/DND/SRD-OGL_V5.1.pdf'
target='_blank'>
OGL</a><br/>
Open Game License v 1.0a Copyright 2000, Wizards of the Coast, LLC.
</i><sm>
</p>
</div>
</form>
</div> <!-- Modal Body -->
</div> <!-- Modal Content -->
</div> <!-- Modal Dialog -->
</div> <!-- Modal Fade -->
<!-- ViewEdit Modal -->
<div class="modal fade"
id="viewWeapon"
tabindex="-1"
role="dialog"
data-bind="modal: {
open: modalOpen,
onopen: modalFinishedOpening,
onclose: modalFinishedClosing
}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button"
class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Edit a Feature.</h4>
</div>
<div class="modal-body">
<!-- Begin Tabs -->
<ul class="nav nav-tabs tabs">
<li role="presentation" data-bind="click: selectPreviewTab, css: previewTabStatus">
<a href="#" aria-controls="featureModalPreview" role="tab" data-toggle="tab">
<b>Preview</b>
</a>
</li>
<li role="presentation" data-bind="click: selectEditTab, css: editTabStatus">
<a href="#" aria-controls="featureModalEdit" role="tab" data-toggle="tab">
<b>Edit</b>
</a>
</li>
</ul>
<div class="tab-content" data-bind="with: currentEditItem">
<div role="tabpanel" data-bind="css: $parent.previewTabStatus" class="tab-pane">
<div class="h3">
<span data-bind="text: name"></span>
</div>
<div class="row">
<div class="col-sm-6 col-xs-12"><b>Class: </b>
<span data-bind="text: characterClass"></span>
</div>
<div class="col-sm-6 col-xs-12"><b>Level: </b>
<span data-bind="text: level"></span>
</div>
</div>
<!-- ko if: isTracked -->
<div class="row" >
<div class="col-sm-6 col-xs-12">
<b>Max Uses:</b>
<span data-bind="text: $parent.currentEditTracked().maxUses"></span>
</div>
<div class="col-sm-6 col-xs-12">
<b>Resets on:</b>
<span data-bind="visible: $parent.currentEditTracked().resetsOn() === 'short'">
Short Rest
</span>
<span data-bind="visible: $parent.currentEditTracked().resetsOn() === 'long'">
Long Rest
</span>
</div>
</div>
<!-- /ko -->
<hr />
<div class="row row-padded">
<div class="col-xs-12 col-padded">
<div data-bind="markdownPreview: description"
class="preview-modal-overflow-sm">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-primary"
data-dismiss="modal">Done</button>
</div>
</div> <!-- End Preview Tab -->
<div role="tabpanel" data-bind="css: $parent.editTabStatus" class="tab-pane">
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="featureName"
placeholder="Rage"
data-bind='textInput: name, hasFocus: $parent.editFirstModalElementHasFocus'>
</div>
</div>
<div class="form-group">
<label for="class" class="col-sm-2 control-label">Class</label>
<div class="col-sm-10">
<input type="text"
class="form-control"
id="class"
placeholder="Barbarian"
data-bind='textInput: characterClass,
autocomplete: { source: $parent.classOptions,
onselect: $parent.populateClassEdit }'>
</div>
</div>
<div class="form-group">
<label for="level" class="col-sm-2 control-label">Level</label>
<div class="col-sm-10">
<input type="number"
class="form-control"
id="class"
placeholder="1"
data-bind='textInput: level'>
</div>
</div>
<div class="form-group">
<label for="featureDescription"
class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea type="text" rows="6"
class="form-control"
placeholder="While you are not wearing any armor, your Armor Class..."
data-bind='value: description, markdownEditor: true'></textarea>
</div>
</div>
<div class="form-group">
<label for="featureDescription" class="col-sm-2 control-label">Tracked?</label>
<div class="col-sm-10">
<input type="checkbox" class="form-control" id="tracked"
data-bind='checked: isTracked'>
</div>
</div>
<!-- ko if: isTracked -->
<div class="form-group">
<div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:40px">
</div>
<label for="bonus" class="col-sm-2 control-label">Max</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="max" min="1"
data-bind='textInput: $parent.currentEditTracked().maxUses'>
</div>
</div>
<div class="form-group">
<div class="col-sm-1 col-content-vertical" style="border-right:5px ridge #dce4ec;height:50px">
</div>
<label class="col-sm-2 control-label">Resets on...</label>
<div class="col-sm-9">
<div class="btn-group btn-group-justified" role="group">
<label class="btn btn-default"
data-bind="css: { active: $parent.currentEditTracked().resetsOn() == 'short'}">
<input type="radio" class="hide-block" name="blankresetsOnShort" value="short"
data-bind="checked: $parent.currentEditTracked().resetsOn"/>
<img class="action-bar-icon" data-bind="attr: { src: $parent.meditation }"></img>
Short Rest
</label>
<label class="btn btn-default"
data-bind="css: { active: $parent.currentEditTracked().resetsOn() != 'short'}">
<input type="radio" class="hide-block" name="blankresetsOnLong"
value="long" data-bind="checked: $parent.currentEditTracked().resetsOn"/>
<img class="action-bar-icon" data-bind="attr: { src: $parent.campingTent }"></img>
Long Rest
</label>
</div>
</div>
</div>
<!-- /ko -->
<div class="modal-footer">
<button type="button"
class="btn btn-primary"
data-dismiss="modal">Done</button>
</div>
</form>
</div>
</div>
</div> <!-- Modal Body -->
</div> <!-- Modal Content -->
</div> <!-- Modal Dialog -->
</div> <!-- Modal Fade -->
| Java |
/**
Copyright (c) 2014-2015 "M-Way Solutions GmbH"
FruityMesh - Bluetooth Low Energy mesh protocol [http://mwaysolutions.com/]
This file is part of FruityMesh
FruityMesh is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <adv_packets.h>
#include <AdvertisingController.h>
#include <AdvertisingModule.h>
#include <Logger.h>
#include <Utility.h>
#include <Storage.h>
extern "C"{
#include <app_error.h>
}
//This module allows a number of advertising messages to be configured.
//These will be broadcasted periodically
/*
TODO: Who's responsible for restoring the mesh-advertising packet? This module or the Node?
* */
AdvertisingModule::AdvertisingModule(u8 moduleId, Node* node, ConnectionManager* cm, const char* name, u16 storageSlot)
: Module(moduleId, node, cm, name, storageSlot)
{
//Register callbacks n' stuff
//Save configuration to base class variables
//sizeof configuration must be a multiple of 4 bytes
configurationPointer = &configuration;
configurationLength = sizeof(AdvertisingModuleConfiguration);
//Start module configuration loading
LoadModuleConfiguration();
}
void AdvertisingModule::ConfigurationLoadedHandler()
{
//Does basic testing on the loaded configuration
Module::ConfigurationLoadedHandler();
//Version migration can be added here
if(configuration.moduleVersion == 1){/* ... */};
//Do additional initialization upon loading the config
//Start the Module...
logt("ADVMOD", "Config set");
}
void AdvertisingModule::TimerEventHandler(u16 passedTime, u32 appTimer)
{
//Do stuff on timer...
}
void AdvertisingModule::ResetToDefaultConfiguration()
{
//Set default configuration values
configuration.moduleId = moduleId;
configuration.moduleActive = true;
configuration.moduleVersion = 1;
memset(configuration.messageData[0].messageData, 0, 31);
advStructureFlags flags;
advStructureName name;
flags.len = SIZEOF_ADV_STRUCTURE_FLAGS-1;
flags.type = BLE_GAP_AD_TYPE_FLAGS;
flags.flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
name.len = SIZEOF_ADV_STRUCTURE_NAME-1;
name.type = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME;
name.name[0] = 'A';
name.name[1] = 'B';
configuration.advertisingIntervalMs = 100;
configuration.messageCount = 1;
configuration.messageData[0].messageLength = 31;
memcpy(configuration.messageData[0].messageData, &flags, SIZEOF_ADV_STRUCTURE_FLAGS);
memcpy(configuration.messageData[0].messageData+SIZEOF_ADV_STRUCTURE_FLAGS, &name, SIZEOF_ADV_STRUCTURE_NAME);
}
void AdvertisingModule::NodeStateChangedHandler(discoveryState newState)
{
if(newState == discoveryState::BACK_OFF || newState == discoveryState::DISCOVERY_OFF){
//Activate our advertising
//This is a small packet for debugging a node's state
if(Config->advertiseDebugPackets){
u8 buffer[31];
memset(buffer, 0, 31);
advStructureFlags* flags = (advStructureFlags*)buffer;
flags->len = SIZEOF_ADV_STRUCTURE_FLAGS-1;
flags->type = BLE_GAP_AD_TYPE_FLAGS;
flags->flags = BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED;
advStructureManufacturer* manufacturer = (advStructureManufacturer*)(buffer+3);
manufacturer->len = 26;
manufacturer->type = BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA;
manufacturer->companyIdentifier = 0x24D;
AdvertisingModuleDebugMessage* msg = (AdvertisingModuleDebugMessage*)(buffer+7);
msg->debugPacketIdentifier = 0xDE;
msg->senderId = node->persistentConfig.nodeId;
msg->connLossCounter = node->persistentConfig.connectionLossCounter;
for(int i=0; i<Config->meshMaxConnections; i++){
if(cm->connections[i]->handshakeDone()){
msg->partners[i] = cm->connections[i]->partnerId;
msg->rssiVals[i] = cm->connections[i]->rssiAverage;
msg->droppedVals[i] = cm->connections[i]->droppedPackets;
} else {
msg->partners[i] = 0;
msg->rssiVals[i] = 0;
msg->droppedVals[i] = 0;
}
}
char strbuffer[200];
Logger::getInstance().convertBufferToHexString(buffer, 31, strbuffer, 200);
logt("ADVMOD", "ADV set to %s", strbuffer);
u32 err = sd_ble_gap_adv_data_set(buffer, 31, NULL, 0);
if(err != NRF_SUCCESS){
logt("ADVMOD", "Debug Packet corrupt");
}
AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH);
}
else if(configuration.messageCount > 0){
u32 err = sd_ble_gap_adv_data_set(configuration.messageData[0].messageData, configuration.messageData[0].messageLength, NULL, 0);
if(err != NRF_SUCCESS){
logt("ADVMOD", "Adv msg corrupt");
}
char buffer[200];
Logger::getInstance().convertBufferToHexString((u8*)configuration.messageData[0].messageData, 31, buffer, 200);
logt("ADVMOD", "ADV set to %s", buffer);
if(configuration.messageData[0].forceNonConnectable)
{
AdvertisingController::SetNonConnectable();
}
//Now, start advertising
//TODO: Use advertising parameters from config to advertise
AdvertisingController::SetAdvertisingState(advState::ADV_STATE_HIGH);
}
} else if (newState == discoveryState::DISCOVERY) {
//Do not trigger custom advertisings anymore, reset to node's advertising
node->UpdateJoinMePacket();
}
}
bool AdvertisingModule::TerminalCommandHandler(string commandName, vector<string> commandArgs)
{
if(commandArgs.size() >= 2 && commandArgs[1] == moduleName)
{
if(commandName == "action")
{
if(commandArgs[1] != moduleName) return false;
if(commandArgs[2] == "broadcast_debug")
{
Config->advertiseDebugPackets = !Config->advertiseDebugPackets;
logt("ADVMOD", "Debug Packets are now set to %u", Config->advertiseDebugPackets);
return true;
}
}
}
//Must be called to allow the module to get and set the config
return Module::TerminalCommandHandler(commandName, commandArgs);
}
| Java |
/*
* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R)
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
// $Id: Info.java,v 1.6 2004/09/22 14:31:39 jesper Exp $
package com.supermap.desktop.ui.docking.info;
import com.supermap.desktop.ui.docking.DockingWindowsReleaseInfo;
import net.infonode.gui.ReleaseInfoDialog;
import net.infonode.gui.laf.InfoNodeLookAndFeelReleaseInfo;
import net.infonode.tabbedpanel.TabbedPanelReleaseInfo;
import net.infonode.util.ReleaseInfo;
/**
* Program that shows InfoNode Docking Windows release information in a dialog.
*
* @author $Author: jesper $
* @version $Revision: 1.6 $
*/
public class Info {
private Info() {
}
public static final void main(String[] args) {
ReleaseInfoDialog.showDialog(new ReleaseInfo[]{DockingWindowsReleaseInfo.getReleaseInfo(),
TabbedPanelReleaseInfo.getReleaseInfo(),
InfoNodeLookAndFeelReleaseInfo.getReleaseInfo()},
null);
System.exit(0);
}
}
| Java |
<?php
/**
* @package Joomla.Plugin
* @subpackage Content.Jtf
*
* @author Guido De Gobbis <support@joomtools.de>
* @copyright (c) 2017 JoomTools.de - All rights reserved.
* @license GNU General Public License version 3 or later
*/
defined('_JEXEC') or die;
extract($displayData);
/**
* Make thing clear
*
* @var JForm $form The form instance for render the section
* @var string $basegroup The base group name
* @var string $group Current group name
* @var string $unique_subform_id Unique subform id
* @var array $buttons Array of the buttons that will be rendered
*/
$subformClass = !empty($form->getAttribute('class')) ? ' ' . $form->getAttribute('class') : ' uk-width-1-1 uk-width-1-2@s uk-width-1-4@m'; ?>
<div class="subform-repeatable-group uk-margin-large-bottom<?php echo $subformClass; ?> subform-repeatable-group-<?php echo $unique_subform_id; ?>"
data-base-name="<?php echo $basegroup; ?>" data-group="<?php echo $group; ?>">
<?php foreach ($form->getGroup('') as $field) : ?>
<?php echo $field->renderField(); ?>
<?php endforeach; ?>
<?php if (!empty($buttons)) : ?>
<div class="uk-margin-top uk-width-1-1 uk-text-right">
<div class="uk-button-group">
<?php if (!empty($buttons['add'])) : ?><a
class="group-add uk-button uk-button-small uk-button-secondary group-add-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_ADD'); ?>"><span uk-icon="plus"></span>
</a><?php endif; ?>
<?php if (!empty($buttons['remove'])) : ?><a
class="group-remove uk-button uk-button-small uk-button-danger group-remove-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_REMOVE'); ?>"><span uk-icon="minus"></span>
</a><?php endif; ?>
<?php if (!empty($buttons['move'])) : ?><a
class="group-move uk-button uk-button-small uk-button-primary group-move-<?php echo $unique_subform_id; ?>"
aria-label="<?php echo JText::_('JGLOBAL_FIELD_MOVE'); ?>"><span uk-icon="move"></span>
</a><?php endif; ?>
</div>
</div>
<?php endif; ?>
</div>
| Java |
package net.seabears.game.entities.normalmap;
import static java.util.stream.IntStream.range;
import java.io.IOException;
import java.util.List;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.joml.Vector4f;
import net.seabears.game.entities.Entity;
import net.seabears.game.entities.Light;
import net.seabears.game.shadows.ShadowShader;
import net.seabears.game.textures.ModelTexture;
import net.seabears.game.util.TransformationMatrix;
public class NormalMappingShader extends ShadowShader {
public static final int TEXTURE_SHADOW = 2;
private final int lights;
private int locationClippingPlane;
private int locationModelTexture;
private int locationNormalMap;
private int[] locationLightAttenuation;
private int[] locationLightColor;
private int[] locationLightPosition;
private int locationProjectionMatrix;
private int locationReflectivity;
private int locationShineDamper;
private int locationSkyColor;
private int locationTextureRows;
private int locationTextureOffset;
private int locationTransformationMatrix;
private int locationViewMatrix;
public NormalMappingShader(int lights) throws IOException {
super(SHADER_ROOT + "normalmap/", TEXTURE_SHADOW);
this.lights = lights;
}
@Override
protected void bindAttributes() {
super.bindAttribute(ATTR_POSITION, "position");
super.bindAttribute(ATTR_TEXTURE, "textureCoords");
super.bindAttribute(ATTR_NORMAL, "normal");
super.bindAttribute(ATTR_TANGENT, "tangent");
}
@Override
protected void getAllUniformLocations() {
super.getAllUniformLocations();
locationClippingPlane = super.getUniformLocation("clippingPlane");
locationModelTexture = super.getUniformLocation("modelTexture");
locationNormalMap = super.getUniformLocation("normalMap");
locationLightAttenuation = super.getUniformLocations("attenuation", lights);
locationLightColor = super.getUniformLocations("lightColor", lights);
locationLightPosition = super.getUniformLocations("lightPosition", lights);
locationProjectionMatrix = super.getUniformLocation("projectionMatrix");
locationReflectivity = super.getUniformLocation("reflectivity");
locationShineDamper = super.getUniformLocation("shineDamper");
locationSkyColor = super.getUniformLocation("skyColor");
locationTextureRows = super.getUniformLocation("textureRows");
locationTextureOffset = super.getUniformLocation("textureOffset");
locationTransformationMatrix = super.getUniformLocation("transformationMatrix");
locationViewMatrix = super.getUniformLocation("viewMatrix");
}
public void loadClippingPlane(Vector4f plane) {
this.loadFloat(locationClippingPlane, plane);
}
public void loadLights(final List<Light> lights, Matrix4f viewMatrix) {
range(0, this.lights)
.forEach(i -> loadLight(i < lights.size() ? lights.get(i) : OFF_LIGHT, i, viewMatrix));
}
private void loadLight(Light light, int index, Matrix4f viewMatrix) {
super.loadFloat(locationLightAttenuation[index], light.getAttenuation());
super.loadFloat(locationLightColor[index], light.getColor());
super.loadFloat(locationLightPosition[index],
getEyeSpacePosition(light.getPosition(), viewMatrix));
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(locationProjectionMatrix, matrix);
}
public void loadSky(Vector3f color) {
super.loadFloat(locationSkyColor, color);
}
public void loadNormalMap() {
// refers to texture units
// TEXTURE_SHADOW occupies one unit
super.loadInt(locationModelTexture, 0);
super.loadInt(locationNormalMap, 1);
}
public void loadTexture(ModelTexture texture) {
super.loadFloat(locationReflectivity, texture.getReflectivity());
super.loadFloat(locationShineDamper, texture.getShineDamper());
super.loadFloat(locationTextureRows, texture.getRows());
}
public void loadEntity(Entity entity) {
loadTransformationMatrix(
new TransformationMatrix(entity.getPosition(), entity.getRotation(), entity.getScale())
.toMatrix());
super.loadFloat(locationTextureOffset, entity.getTextureOffset());
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(locationTransformationMatrix, matrix);
}
public void loadViewMatrix(Matrix4f matrix) {
super.loadMatrix(locationViewMatrix, matrix);
}
private static Vector3f getEyeSpacePosition(Vector3f position, Matrix4f viewMatrix) {
final Vector4f eyeSpacePos = new Vector4f(position.x, position.y, position.z, 1.0f);
viewMatrix.transform(eyeSpacePos);
return new Vector3f(eyeSpacePos.x, eyeSpacePos.y, eyeSpacePos.z);
}
}
| Java |
'use strict'
// untuk status uploader
const STATUS_INITIAL = 0
const STATUS_SAVING = 1
const STATUS_SUCCESS = 2
const STATUS_FAILED = 3
// base url api
const BASE_URL = 'http://localhost:3000'
const app = new Vue({
el: '#app',
data: {
message: 'Hello',
currentStatus: null,
uploadError: null,
uploadFieldName: 'image',
uploadedFiles: [],
files:[]
},
computed: {
isInitial() {
return this.currentStatus === STATUS_INITIAL;
},
isSaving() {
return this.currentStatus === STATUS_SAVING;
},
isSuccess() {
return this.currentStatus === STATUS_SUCCESS;
},
isFailed() {
return this.currentStatus === STATUS_FAILED;
}
}, // computed
methods: {
// reset form to initial state
getAllFile () {
let self = this
axios.get(`${BASE_URL}/files`)
.then(response => {
self.files = response.data
})
}, // getAllFile()
deleteFile (id) {
axios.delete(`${BASE_URL}/files/${id}`)
.then(r => {
this.files.splice(id, 1)
})
},
reset() {
this.currentStatus = STATUS_INITIAL;
this.uploadedFiles = [];
this.uploadError = null;
}, // reset()
// upload data to the server
save(formData) {
console.log('save')
console.log('form data', formData)
this.currentStatus = STATUS_SAVING;
axios.post(`${BASE_URL}/files/add`, formData)
.then(up => {
// console.log('up', up)
this.uploadedFiles = [].concat(up)
this.currentStatus = STATUS_SUCCESS
})
.catch(e => {
console.log(e.response.data)
this.currentStatus = STATUS_FAILED
})
}, // save()
filesChange(fieldName, fileList) {
// handle file changes
const formData = new FormData();
formData.append('image', fileList[0])
console.log(formData)
this.save(formData);
} // filesChange()
}, // methods
mounted () {
this.reset()
},
created () {
this.getAllFile()
}
})
| Java |
Simpla CMS 2.3.8 = f8952829bab201835e255735de3774f0
| Java |
<h3>Publicaciones relacionadas</h3>
<p><b>Análisis Publicados</b></p>
<ul>
<li><a href="http://www.trcimplan.gob.mx/blog/cobertura-y-rezago-de-servicios-en-las-viviendas-de-torreon.html">Cobertura y rezago de servicios en las viviendas de Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/hacinamiento-en-torreon-marzo2020.html">La Situación de Hacinamiento en Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/caracteristicas-de-un-buen-espacio-publico-ene2020.html">Características de un Buen Espacio Público</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/nuevos-esquemas-para-acceder-a-la-vivienda-enero2020.html">Nuevos esquemas para acceder a la vivienda.</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/la-transformacion-de-la-periferia-urbana-de-torreon-dic2019.html">La Transformación de la Periferia Urbana de Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/credito-de-vivienda-en-colonias-tradicionales-dic2019.html">Créditos de Vivienda en Colonias Tradicionales como Estrategia para la Consolidación Urbana</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/suelo-mixto-como-politica-de-desarrollo-sostenible-nov2019.html">El Suelo Mixto como Política de Desarrollo Sostenible.</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/programa-parcial-desarrollo-urbano-torreon-zona-norte-marzo2020.html">Propuesta de Programa Parcial de Desarrollo Urbano de la Zona Norte de Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/planificacion-urbana-en-la-salud-publica-de-la-laguna.html">La planificación urbana, fundamental en la salud pública de los laguneros.</a></li>
<li><a href="http://www.trcimplan.gob.mx/blog/urbanismo-con-enfoque-de-genero-en-la-laguna.html">Urbanismo con enfoque de género en La Laguna</a></li>
</ul>
<p><b>Sistema Metropolitano de Indicadores</b></p>
<ul>
<li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-con-agua-entubada.html">Viviendas con Agua Entubada en Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-particulares-habitadas-que-disponen-de-energia-electrica.html">Viviendas Particulares Habitadas que Disponen de Energía Eléctrica en Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-torreon/sociedad-viviendas-particulares-habitadas-que-disponen-de-drenaje.html">Viviendas Particulares Habitadas que Disponen de Drenaje en Torreón</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-con-lineas-telefonicas-moviles.html">Viviendas con Líneas Telefónicas Móviles en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/economia-intensidad-energetica-en-la-economia.html">Intensidad energética en la economía en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-con-drenaje-solo-conexion-a-red-publica.html">Viviendas con Drenaje (sólo conexión a red pública) en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-totales.html">Viviendas Totales en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sociedad-viviendas-habitadas.html">Viviendas Habitadas en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sustentabilidad-consumo-electrico-residencial.html">Consumo eléctrico residencial en La Laguna</a></li>
<li><a href="http://www.trcimplan.gob.mx/indicadores-la-laguna/sustentabilidad-consumo-electrico-en-servicios-municipales.html">Consumo eléctrico en servicios municipales en La Laguna</a></li>
</ul>
<p><b>Sistema de Información Geográfica</b></p>
<ul>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/inventario-viviendas.html">Inventario de Viviendas</a></li>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/caracteristicas-viviendas.html">Características de las Viviendas</a></li>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/centros-atencion-adultos-mayores.html">Centros de Atención a Adultos Mayores</a></li>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/valores-catastrales-por-vialidades.html">Valores Catastrales por Vialidades</a></li>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/crecimiento-decrecimiento-poblacion.html">Crecimiento y Decrecimiento de Población</a></li>
<li><a href="http://www.trcimplan.gob.mx/sig-mapas-torreon/avance-reconversion-tecnologica-led-alumbrado-publico.html">Avance de Reconversión Tecnológica Led del Alumbrado Público</a></li>
</ul>
<p><b>Plan Estratégico Torreón</b></p>
<ul>
<li><a href="http://www.trcimplan.gob.mx/pet/cartera-proyectos-entorno-urbano.html">Cartera de Proyectos: Entorno Urbano</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-entorno-urbano.html">Diagnóstico Estratégico: Entorno Urbano</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/vision-entorno-urbano.html">Visión de Entorno Urbano 2040</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/cartera-proyectos-medio-ambiente-sustentabilidad.html">Cartera de Proyectos: Medio Ambiente y Sustentabilidad</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-medio-ambiente-sustentabilidad.html">Diagnóstico Estratégico: Medio Ambiente y Sustentabilidad</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/vision-medio-ambiente-sustentabilidad.html">Visión de Medio Ambiente y Sustentabilidad 2040</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-buen-gobierno.html">Diagnóstico Estratégico: Buen Gobierno</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-desarrollo-economico-innovacion.html">Diagnóstico Estratégico: Desarrollo Económico e Innovación</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-desarrollo-social.html">Diagnóstico Estratégico: Desarrollo Social</a></li>
<li><a href="http://www.trcimplan.gob.mx/pet/diagnostico-estrategico-movilidad-transporte.html">Diagnóstico Estratégico: Movilidad y Transporte</a></li>
</ul>
<p><b>Sala de Prensa</b></p>
<ul>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2018-10-31-decima-sesion.html">Presentan “Propuesta conceptual para el manejo sustentable del agua” en Sesión del IMPLAN.</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-02-22-conferencia-urbanizaciones-cerradas.html">IMPLAN presenta conferencia “Islas de seguridad y distinción. Las urbanizaciones cerradas en la frontera noroeste de México”.</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-04-15-comunicado-conferencias-virtuales.html">El IMPLAN Torreón y su Consejo Juvenil: Visión Metrópoli, presentarán Conferencias Virtuales</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-27-segunda-sesion-consejo-2020.html">Presentan en Segunda Sesión de Consejo el “Programa Parcial de Desarrollo Urbano para la Zona Norte de Torreón”</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-17-comunicado-enoe.html">Disminuye la tasa de desempleo en la Zona Metropolitana de La Laguna (ZML), al cuarto trimestre de 2019</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-02-06-comunicado-conferencia-imeplan.html">Postura sobre la creación de un Instituto Metropolitano de Planeación.</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2020-01-30-primer-sesion-consejo-2020.html">Primer Sesión de Consejo 2020. Se renueva el Consejo Directivo del IMPLAN.</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-26-novena-sesion-consejo.html">Novena Sesión de Consejo Implan. Presentan Resultados del Conversatorio y del Concurso “Manos a la Cebra”.</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-26-seminario-identidad-lagunera.html">Consejo Visión Metrópoli presenta Seminario de Identidad Lagunera</a></li>
<li><a href="http://www.trcimplan.gob.mx/sala-prensa/2019-09-24-manos-a-la-cebra-reporte.html">Manos a la Cebra</a></li>
</ul> | Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>P5</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<style>
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<script>
function initMap() {
var mapNode = document.getElementById('map');
var mapOptions = {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922 }
};
var map = new google.maps.Map(mapNode, mapOptions);
}
</script>
</body>
</html> | Java |
#include "../header/Base.h"
#include "../header/Decorator.h"
Decorator::Decorator() {
}
Decorator::Decorator(Base* node) {
}
Decorator::~Decorator() {
}
| Java |
/*
* Copyright (C) 2010-2021 JPEXS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jpexs.decompiler.flash.gui.timeline;
import com.jpexs.decompiler.flash.configuration.Configuration;
import com.jpexs.decompiler.flash.tags.base.CharacterTag;
import com.jpexs.decompiler.flash.tags.base.MorphShapeTag;
import com.jpexs.decompiler.flash.timeline.DepthState;
import com.jpexs.decompiler.flash.timeline.Timeline;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
import org.pushingpixels.substance.api.ColorSchemeAssociationKind;
import org.pushingpixels.substance.api.ComponentState;
import org.pushingpixels.substance.api.DecorationAreaType;
import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.internal.utils.SubstanceColorUtilities;
/**
*
* @author JPEXS
*/
public class TimelineBodyPanel extends JPanel implements MouseListener, KeyListener {
private final Timeline timeline;
public static final Color shapeTweenColor = new Color(0x59, 0xfe, 0x7c);
public static final Color motionTweenColor = new Color(0xd1, 0xac, 0xf1);
//public static final Color frameColor = new Color(0xbd, 0xd8, 0xfc);
public static final Color borderColor = Color.black;
public static final Color emptyBorderColor = new Color(0xbd, 0xd8, 0xfc);
public static final Color keyColor = Color.black;
public static final Color aColor = Color.black;
public static final Color stopColor = Color.white;
public static final Color stopBorderColor = Color.black;
public static final Color borderLinesColor = new Color(0xde, 0xde, 0xde);
//public static final Color selectedColor = new Color(113, 174, 235);
public static final int borderLinesLength = 2;
public static final float fontSize = 10.0f;
private final List<FrameSelectionListener> listeners = new ArrayList<>();
public Point cursor = null;
private enum BlockType {
EMPTY, NORMAL, MOTION_TWEEN, SHAPE_TWEEN
}
public static Color getEmptyFrameColor() {
return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.7);
}
public static Color getEmptyFrameSecondColor() {
return SubstanceColorUtilities.getLighterColor(getControlColor(), 0.9);
}
public static Color getSelectedColor() {
if (Configuration.useRibbonInterface.get()) {
return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ROLLOVER_SELECTED).getBackgroundFillColor();
} else {
return SystemColor.textHighlight;
}
}
private static Color getControlColor() {
if (Configuration.useRibbonInterface.get()) {
return SubstanceLookAndFeel.getCurrentSkin().getColorScheme(DecorationAreaType.GENERAL, ColorSchemeAssociationKind.FILL, ComponentState.ENABLED).getBackgroundFillColor();
} else {
return SystemColor.control;
}
}
public static Color getFrameColor() {
return SubstanceColorUtilities.getDarkerColor(getControlColor(), 0.1);
}
public void addFrameSelectionListener(FrameSelectionListener l) {
listeners.add(l);
}
public void removeFrameSelectionListener(FrameSelectionListener l) {
listeners.remove(l);
}
public TimelineBodyPanel(Timeline timeline) {
this.timeline = timeline;
Dimension dim = new Dimension(TimelinePanel.FRAME_WIDTH * timeline.getFrameCount() + 1, TimelinePanel.FRAME_HEIGHT * timeline.getMaxDepth());
setSize(dim);
setPreferredSize(dim);
addMouseListener(this);
addKeyListener(this);
setFocusable(true);
}
@Override
protected void paintComponent(Graphics g1) {
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(TimelinePanel.getBackgroundColor());
g.fillRect(0, 0, getWidth(), getHeight());
Rectangle clip = g.getClipBounds();
int frameWidth = TimelinePanel.FRAME_WIDTH;
int frameHeight = TimelinePanel.FRAME_HEIGHT;
int start_f = clip.x / frameWidth;
int start_d = clip.y / frameHeight;
int end_f = (clip.x + clip.width) / frameWidth;
int end_d = (clip.y + clip.height) / frameHeight;
int max_d = timeline.getMaxDepth();
if (max_d < end_d) {
end_d = max_d;
}
int max_f = timeline.getFrameCount() - 1;
if (max_f < end_f) {
end_f = max_f;
}
if (end_d - start_d + 1 < 0) {
return;
}
// draw background
for (int f = start_f; f <= end_f; f++) {
g.setColor((f + 1) % 5 == 0 ? getEmptyFrameSecondColor() : getEmptyFrameColor());
g.fillRect(f * frameWidth, start_d * frameHeight, frameWidth, (end_d - start_d + 1) * frameHeight);
g.setColor(emptyBorderColor);
for (int d = start_d; d <= end_d; d++) {
g.drawRect(f * frameWidth, d * frameHeight, frameWidth, frameHeight);
}
}
// draw selected cell
if (cursor != null) {
g.setColor(getSelectedColor());
g.fillRect(cursor.x * frameWidth + 1, cursor.y * frameHeight + 1, frameWidth - 1, frameHeight - 1);
}
g.setColor(aColor);
g.setFont(getFont().deriveFont(fontSize));
int awidth = g.getFontMetrics().stringWidth("a");
for (int f = start_f; f <= end_f; f++) {
if (!timeline.getFrame(f).actions.isEmpty()) {
g.drawString("a", f * frameWidth + frameWidth / 2 - awidth / 2, frameHeight / 2 + fontSize / 2);
}
}
Map<Integer, Integer> depthMaxFrames = timeline.getDepthMaxFrame();
for (int d = start_d; d <= end_d; d++) {
int maxFrame = depthMaxFrames.containsKey(d) ? depthMaxFrames.get(d) : -1;
if (maxFrame < 0) {
continue;
}
int end_f2 = Math.min(end_f, maxFrame);
int start_f2 = Math.min(start_f, end_f2);
// find the start frame number of the current block
DepthState dsStart = timeline.getFrame(start_f2).layers.get(d);
for (; start_f2 >= 1; start_f2--) {
DepthState ds = timeline.getFrame(start_f2 - 1).layers.get(d);
if (((dsStart == null) != (ds == null))
|| (ds != null && dsStart.characterId != ds.characterId)) {
break;
}
}
for (int f = start_f2; f <= end_f2; f++) {
DepthState fl = timeline.getFrame(f).layers.get(d);
boolean motionTween = fl == null ? false : fl.motionTween;
DepthState flNext = f < max_f ? timeline.getFrame(f + 1).layers.get(d) : null;
DepthState flPrev = f > 0 ? timeline.getFrame(f - 1).layers.get(d) : null;
CharacterTag cht = fl == null ? null : timeline.swf.getCharacter(fl.characterId);
boolean shapeTween = cht != null && (cht instanceof MorphShapeTag);
boolean motionTweenStart = !motionTween && (flNext != null && flNext.motionTween);
boolean motionTweenEnd = !motionTween && (flPrev != null && flPrev.motionTween);
//boolean shapeTweenStart = shapeTween && (flPrev == null || flPrev.characterId != fl.characterId);
//boolean shapeTweenEnd = shapeTween && (flNext == null || flNext.characterId != fl.characterId);
/*if (motionTweenStart || motionTweenEnd) {
motionTween = true;
}*/
int draw_f = f;
int num_frames = 1;
Color backColor;
BlockType blockType;
if (fl == null) {
for (; f + 1 < timeline.getFrameCount(); f++) {
fl = timeline.getFrame(f + 1).layers.get(d);
if (fl != null && fl.characterId != -1) {
break;
}
num_frames++;
}
backColor = getEmptyFrameColor();
blockType = BlockType.EMPTY;
} else {
for (; f + 1 < timeline.getFrameCount(); f++) {
fl = timeline.getFrame(f + 1).layers.get(d);
if (fl == null || fl.key) {
break;
}
num_frames++;
}
backColor = shapeTween ? shapeTweenColor : motionTween ? motionTweenColor : getFrameColor();
blockType = shapeTween ? BlockType.SHAPE_TWEEN : motionTween ? BlockType.MOTION_TWEEN : BlockType.NORMAL;
}
drawBlock(g, backColor, d, draw_f, num_frames, blockType);
}
}
if (cursor != null && cursor.x >= start_f && cursor.x <= end_f) {
g.setColor(TimelinePanel.selectedBorderColor);
g.drawLine(cursor.x * frameWidth + frameWidth / 2, 0, cursor.x * frameWidth + frameWidth / 2, getHeight());
}
}
private void drawBlock(Graphics2D g, Color backColor, int depth, int frame, int num_frames, BlockType blockType) {
int frameWidth = TimelinePanel.FRAME_WIDTH;
int frameHeight = TimelinePanel.FRAME_HEIGHT;
g.setColor(backColor);
g.fillRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight);
g.setColor(borderColor);
g.drawRect(frame * frameWidth, depth * frameHeight, num_frames * frameWidth, frameHeight);
boolean selected = false;
if (cursor != null && frame <= cursor.x && (frame + num_frames) > cursor.x && depth == cursor.y) {
selected = true;
}
if (selected) {
g.setColor(getSelectedColor());
g.fillRect(cursor.x * frameWidth + 1, depth * frameHeight + 1, frameWidth - 1, frameHeight - 1);
}
boolean isTween = blockType == BlockType.MOTION_TWEEN || blockType == BlockType.SHAPE_TWEEN;
g.setColor(keyColor);
if (isTween) {
g.drawLine(frame * frameWidth, depth * frameHeight + frameHeight * 3 / 4,
frame * frameWidth + num_frames * frameWidth - frameWidth / 2, depth * frameHeight + frameHeight * 3 / 4
);
}
if (blockType == BlockType.EMPTY) {
g.drawOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
} else {
g.fillOval(frame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
}
if (num_frames > 1) {
int endFrame = frame + num_frames - 1;
if (isTween) {
g.fillOval(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight * 3 / 4 - frameWidth / 2 / 2, frameWidth / 2, frameWidth / 2);
} else {
g.setColor(stopColor);
g.fillRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2);
g.setColor(stopBorderColor);
g.drawRect(endFrame * frameWidth + frameWidth / 4, depth * frameHeight + frameHeight / 2 - 2, frameWidth / 2, frameHeight / 2);
}
g.setColor(borderLinesColor);
for (int n = frame + 1; n < frame + num_frames; n++) {
g.drawLine(n * frameWidth, depth * frameHeight + 1, n * frameWidth, depth * frameHeight + borderLinesLength);
g.drawLine(n * frameWidth, depth * frameHeight + frameHeight - 1, n * frameWidth, depth * frameHeight + frameHeight - borderLinesLength);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
public void frameSelect(int frame, int depth) {
if (cursor != null && cursor.x == frame && (cursor.y == depth || depth == -1)) {
return;
}
if (depth == -1 && cursor != null) {
depth = cursor.y;
}
cursor = new Point(frame, depth);
for (FrameSelectionListener l : listeners) {
l.frameSelected(frame, depth);
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
p.x = p.x / TimelinePanel.FRAME_WIDTH;
p.y = p.y / TimelinePanel.FRAME_HEIGHT;
if (p.x >= timeline.getFrameCount()) {
p.x = timeline.getFrameCount() - 1;
}
int maxDepth = timeline.getMaxDepth();
if (p.y > maxDepth) {
p.y = maxDepth;
}
frameSelect(p.x, p.y);
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 37: //left
if (cursor.x > 0) {
frameSelect(cursor.x - 1, cursor.y);
}
break;
case 39: //right
if (cursor.x < timeline.getFrameCount() - 1) {
frameSelect(cursor.x + 1, cursor.y);
}
break;
case 38: //up
if (cursor.y > 0) {
frameSelect(cursor.x, cursor.y - 1);
}
break;
case 40: //down
if (cursor.y < timeline.getMaxDepth()) {
frameSelect(cursor.x, cursor.y + 1);
}
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
| Java |
//===========================================================================//
// File: memblock.hh //
// Contents: Interface specification of the memory block class //
//---------------------------------------------------------------------------//
// Copyright (C) Microsoft Corporation. All rights reserved. //
//===========================================================================//
#pragma once
#include"stuff.hpp"
namespace Stuff {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockHeader ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlockHeader
{
public:
MemoryBlockHeader
*nextBlock;
size_t
blockSize;
void
TestInstance()
{}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockBase ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlockBase
#if defined(_ARMOR)
: public Stuff::Signature
#endif
{
public:
void
TestInstance()
{Verify(blockMemory != NULL);}
static void
UsageReport();
static void
CollapseBlocks();
protected:
const char
*blockName;
MemoryBlockHeader
*blockMemory; // the first record block allocated
size_t
blockSize, // size in bytes of the current record block
recordSize, // size in bytes of the individual record
deltaSize; // size in bytes of the growth blocks
BYTE
*firstHeaderRecord, // the beginning of useful free space
*freeRecord, // the next address to allocate from the block
*deletedRecord; // the next record to reuse
MemoryBlockBase(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
);
~MemoryBlockBase();
void*
Grow();
HGOSHEAP
blockHeap;
private:
static MemoryBlockBase
*firstBlock;
MemoryBlockBase
*nextBlock,
*previousBlock;
void
Collapse();
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlock ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryBlock:
public MemoryBlockBase
{
public:
static bool
TestClass();
MemoryBlock(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlockBase(rec_size, start, delta, name, parent)
{}
void*
New();
void
Delete(void *Where);
void*
operator[](size_t Index);
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryBlockOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T> class MemoryBlockOf:
public MemoryBlock
{
public:
MemoryBlockOf(
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlock(sizeof(T), start, delta, name, parent)
{}
T*
New()
{return Cast_Pointer(T*, MemoryBlock::New());}
void
Delete(void *where)
{MemoryBlock::Delete(where);}
T*
operator[](size_t index)
{return Cast_Pointer(T*, MemoryBlock::operator[](index));}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class MemoryStack:
public MemoryBlockBase
{
public:
static bool
TestClass();
protected:
BYTE
*topOfStack;
MemoryStack(
size_t rec_size,
size_t start,
size_t delta,
const char* name,
HGOSHEAP parent = ParentClientHeap
):
MemoryBlockBase(rec_size, start, delta, name, parent)
{topOfStack = NULL;}
void*
Push(const void *What);
void*
Push();
void*
Peek()
{return topOfStack;}
void
Pop();
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MemoryStackOf ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T> class MemoryStackOf:
public MemoryStack
{
public:
MemoryStackOf(
size_t start,
size_t delta,
const char *name,
HGOSHEAP parent = ParentClientHeap
):
MemoryStack(sizeof(T), start, delta, name, parent)
{}
T*
Push(const T *what)
{return Cast_Pointer(T*, MemoryStack::Push(what));}
T*
Peek()
{return static_cast<T*>(MemoryStack::Peek());}
void
Pop()
{MemoryStack::Pop();}
};
}
| Java |
#!/usr/bin/env python
import turtle
import random
def bloom(radius):
turtle.colormode(255)
for rad in range(40, 10, -5):
for looper in range(360//rad):
turtle.up()
turtle.circle(radius+rad, rad)
turtle.begin_fill()
turtle.fillcolor((200+random.randint(0, rad),
200+random.randint(0, rad),
200+random.randint(0, rad)))
turtle.down()
turtle.circle(-rad)
turtle.end_fill()
def main():
"""Simple flower, using global turtle instance"""
turtle.speed(0)
turtle.colormode(1.0)
bloom(5)
turtle.exitonclick()
###
if __name__ == "__main__":
main()
| Java |
/*
* Orbit, a versatile image analysis software for biological image-based quantification.
* Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, Switzerland.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.actelion.research.orbit.imageprovider.tree;
import com.actelion.research.orbit.beans.RawData;
import com.actelion.research.orbit.imageprovider.ImageProviderOmero;
import com.actelion.research.orbit.utils.Logger;
import java.util.ArrayList;
import java.util.List;
public class TreeNodeProject extends AbstractOrbitTreeNode {
private static Logger logger = Logger.getLogger(TreeNodeProject.class);
private RawData project = null;
private ImageProviderOmero imageProviderOmero;
public TreeNodeProject(ImageProviderOmero imageProviderOmero, RawData project) {
this.imageProviderOmero = imageProviderOmero;
this.project = project;
}
@Override
public synchronized List<TreeNodeProject> getNodes(AbstractOrbitTreeNode parent) {
List<TreeNodeProject> nodeList = new ArrayList<>();
int group = -1;
if (parent!=null && parent instanceof TreeNodeGroup) {
TreeNodeGroup groupNode = (TreeNodeGroup) parent;
RawData rdGroup = (RawData) groupNode.getIdentifier();
group = rdGroup.getRawDataId();
}
List<RawData> rdList = loadProjects(group);
for (RawData rd : rdList) {
nodeList.add(new TreeNodeProject(imageProviderOmero, rd));
}
return nodeList;
}
@Override
public boolean isChildOf(Object parent) {
return parent instanceof TreeNodeGroup;
}
@Override
public Object getIdentifier() {
return project;
}
@Override
public String toString() {
return project != null ? project.getBioLabJournal() : "";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TreeNodeProject that = (TreeNodeProject) o;
return project != null ? project.equals(that.project) : that.project == null;
}
@Override
public int hashCode() {
return project != null ? project.hashCode() : 0;
}
private List<RawData> loadProjects(int group) {
return imageProviderOmero.loadProjects(group);
}
}
| Java |
/*=======
Image Animation Controls
=======*/
/*Image-1 timing*/
@-webkit-keyframes image-1-animation {
0% {
opacity: 0;
}
5%
{
opacity: 1;
}
29% {
opacity: 1;
}
30% {
opacity: 0;
}
100% {
opacity: 0;
}
}
/*Image-1 Text timing*/
@-webkit-keyframes text-1-animation {
0% {
opacity: 0;
}
4% {
opacity: 1;
}
27% {
opacity: 1;
}
28% {
opacity: 0;
}
100% {
opacity: 0;
}
}
/*Image-2 timing*/
@-webkit-keyframes image-2-animation {
0% {
opacity: 0;
}
30% {
opacity: 0;
}
35% {
opacity: 1;
}
60% {
opacity: 1;
}
61% {
opacity: 0;
}
100% {
opacity: 0;
}
}
/*Image-2 Text timing*/
@-webkit-keyframes text-2-animation {
0% {opacity:0;}
30% {opacity:0;}
34% {opacity:1;}
58% {opacity:1;}
59% {opacity:0;}
100% {opacity:0;}
}
/*Image-3 timing*/
@-webkit-keyframes image-3-animation {
0% {
opacity: 0;
}
61% {
opacity: 0;
}
66% {
opacity: 1;
}
99% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes image-3-animation {
0% {
opacity: 0;
}
61% {
opacity: 0;
}
66% {
opacity: 1;
}
99% {
opacity: 1;
}
100% {
opacity: 0;
}
}
/*Image-3 Text timing*/
@-webkit-keyframes text-3-animation {
0% {
opacity: 0;
}
61% {
opacity: 0;
}
64% {
opacity: 1;
}
97% {
opacity: 1;
}
98% {
opacity: 0;
}
}
/*Logo timing*/
@-webkit-keyframes logo-animation {
0% {
opacity: 0;
}
5% {
opacity: 1;
}
29% {
opacity: 1;
right: 4vh;
bottom: 4vh;
}
30% {
opacity:0;
right:4vh;
bottom:4vh;
}
31% {
right:4vh;
bottom:115vh;
}
32% {
opacity:0;
}
33% {
opacity:1;
}
98% {
opacity:1;
}
99% {
opacity:0;
right:4vh;
bottom:115vh;
}
100% {
opacity:0;
right:4vh;
bottom:4vh;
}
}
/*oniste logo timing*/
@-webkit-keyframes onsite-animation {
0% {
opacity: 0;
}
34% {
opacity: 0;
}
35% {
opacity: 1;
}
60% {
opacity: 1;
}
61% {
opacity: 0;
}
100% {
opacity:0;
}
}
/*=======
Content Styling
=======*/
body {
font-size: 20px;
font-family: "Oswald", sans-serif;
}
.image-1 {
width:100vw;
height:100vh;
position: absolute;
top:0;
left:0;
background-image:url(images/background-1.jpg);
background-size: 100% 100%;
-webkit-animation:image-1-animation 30s ease-out infinite;
animation:image-1-animation 30s ease-out infinite;
}
.image-2 {
width:100vw;
height:100vh;
position: absolute;
top:0;
left:0;
background-image:url(images/background-2.jpg);
background-size: 100% 100%;
-webkit-animation:image-2-animation 30s ease-out infinite;
animation:image-2-animation 30s ease-out infinite;
}
.image-3 {
width:100vw;
height:100vh;
position: absolute;
top:0;
left:0;
background-image:url(images/background-3.jpg);
background-size: 100% 100%;
-webkit-animation:image-3-animation 30s ease-out infinite;
animation:image-3-animation 30s ease-out infinite;
}
#content .slides{
color:red;
position: absolute;
left:5vw;
top:10vh;
z-index: 10;
opacity: 0;
}
/*Styling text for first image*/
#content .slides:nth-of-type(1){
opacity:1;
top: 15vh;
-webkit-animation:text-1-animation 30s ease-out infinite;
animation:text-1-animation 30s ease-out infinite;
}
#content .slides:nth-of-type(1) .headline-1{
color:#B5BD00;
font-size: 70px;
line-height: 1;
margin: 0;
margin-bottom: 2vh;
padding: 0;
}
#content .slides:nth-of-type(1) .headline-2{
color:#C11545;
font-size: 130px;
line-height: 1.1;
width:60%;
margin: 0;
margin-bottom: 2vh;
padding: 0;
}
#content .slides:nth-of-type(1) .body-text {
color:#636363;
font-size: 60px;
font-weight: 300;
line-height: 1.1;
color:#777;
margin: 0;
padding: 0;
width:55%;
}
/*Styling text for second image*/
#content .slides:nth-of-type(2){
opacity:0;
top: 55vh;
left:2vw;
-webkit-animation:text-2-animation 30s ease-out infinite;
animation:text-2-animation 30s ease-out infinite;
}
#content .slides:nth-of-type(2) .headline-1{
color:#B5BD00;
display: inline-block;
font-size: 80px;
font-weight: 400;
line-height: 1;
margin: 0;
margin-bottom: 2vh;
padding: 0;
}
#content .slides:nth-of-type(2) .headline-2{
display: inline-block;
color:#C11545;
font-size: 80px;
font-weight: 400;
line-height: 1;
margin: 0;
margin-left: 2vw;
margin-bottom: 2vh;
padding: 0;
}
#content .slides:nth-of-type(2) .body-text {
font-size: 43px;
font-weight: 300;
line-height: 1.1;
color:#636363;
margin: 0;
margin-top: 1vh;
padding: 0;
width:100%;
}
/*Styling text for third image*/
#content .slides:nth-of-type(3){
opacity:0;
top: 20vh;
-webkit-animation:text-3-animation 30s ease-out infinite;
animation:text-3-animation 30s ease-out infinite;
}
#content .slides:nth-of-type(3) .headline-1{
color:#C11545;
font-size: 80px;
font-weight: 700;
line-height: 1.1;
margin: 0;
padding: 0;
}
#content .slides:nth-of-type(3) .headline-2 {
color:#B5BD00;
font-size: 80px;
font-weight: 700;
width:60%;
line-height: 1.1;
margin: 0;
padding: 0;
}
#content .slides:nth-of-type(3) .body-text {
color:#C11545;
font-size: 80px;
font-weight: 700;
line-height: 1.1;
margin: 0;
padding: 0;
width:60%;
}
.logo {
width:10vw;
height:5vw;
position: absolute;
right:4vh;
bottom:4vh;
background-image:url(images/logo-onthego.png);
background-size: 100% 100%;
z-index: 10;
-webkit-animation:logo-animation 30s ease-out infinite;
animation:logo-animation 30s ease-out infinite;
}
.logo-onsite {
width:10vw;
height:10vw;
position: absolute;
right:10vw;
top:52vh;
background-image: url(images/logo-onsite.png);
background-size: 100% 100%;
z-index: 10;
-webkit-animation:onsite-animation 30s ease-out infinite;
animation:onsite-animation 30s ease-out infinite;
}
.rise-logo {
background-image: url(images/rise-icon.png);
background-size: 100% 100%;
opacity:.5;
width:5%;
height:5%;
left:5%;
top:90%;
z-index:5;
margin-left:-1%;
position:absolute;
z-index:5;
}
/* footer icons */
.github {
width:20%;
height:4%;
left:10%;
top:90%;
z-index:4;
margin-left:1%;
margin-top: 1%;
position:absolute;
z-index:4;
}
.gitbtn {
color:white;
font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;
text-decoration: none;
font-size:25px;
opacity:.5;
z-index:4;
}
@media only screen and (min-width: 1280px) {
#gitbtn {
font-size:25px;
}
}
/* 1360x768 */
@media only screen and (min-width: 1360px) {
#gitbtn {
font-size:24px;
}
}
/* 1920x1080*/
@media only screen and (min-width: 1920px) {
#gitbtn {
font-size: 34px;
}
}
/* 3840x2160 */
@media screen and (min-width: 2200px) {
#gitbtn {
font-size: 64px;
}
}
| Java |
/**
*
* Copyright 2014 Martijn Brekhof
*
* This file is part of Catch Da Stars.
*
* Catch Da Stars is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Catch Da Stars is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Catch Da Stars. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.strategames.engine.gameobject.types;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.strategames.engine.gameobject.GameObject;
import com.strategames.engine.gameobject.StaticBody;
import com.strategames.engine.utils.ConfigurationItem;
import com.strategames.engine.utils.Textures;
public class Door extends StaticBody {
public final static float WIDTH = 0.35f;
public final static float HEIGHT = 0.35f;
private Wall wall;
private boolean open;
private int[] entryLevel = new int[2]; // level this door provides access too
private int[] exitLevel = new int[2]; // level this door can be accessed from
public Door() {
super(new Vector2(WIDTH, HEIGHT));
}
@Override
protected TextureRegion createImage() {
return Textures.getInstance().passageToNextLevel;
}
@Override
protected void setupBody(Body body) {
Vector2 leftBottom = new Vector2(0, 0);
Vector2 rightBottom = new Vector2(WIDTH, 0);
Vector2 rightTop = new Vector2(WIDTH, HEIGHT);
Vector2 leftTop = new Vector2(0, HEIGHT);
ChainShape chain = new ChainShape();
chain.createLoop(new Vector2[] {leftBottom, rightBottom, rightTop, leftTop});
Fixture fixture = body.createFixture(chain, 0.0f);
fixture.setSensor(true);
}
@Override
protected void writeValues(Json json) {
json.writeArrayStart("nextLevelPosition");
json.writeValue(entryLevel[0]);
json.writeValue(entryLevel[1]);
json.writeArrayEnd();
}
@Override
protected void readValue(JsonValue jsonData) {
String name = jsonData.name();
if( name.contentEquals("nextLevelPosition")) {
this.entryLevel = jsonData.asIntArray();
}
}
@Override
public GameObject copy() {
Door door = (Door) newInstance();
door.setPosition(getX(), getY());
int[] pos = getAccessToPosition();
door.setAccessTo(pos[0], pos[1]);
return door;
}
@Override
protected GameObject newInstance() {
return new Door();
}
@Override
protected ArrayList<ConfigurationItem> createConfigurationItems() {
return null;
}
@Override
public void increaseSize() {
}
@Override
public void decreaseSize() {
}
@Override
protected void destroyAction() {
}
@Override
public void handleCollision(Contact contact, ContactImpulse impulse,
GameObject gameObject) {
}
@Override
public void loadSounds() {
}
public Wall getWall() {
return wall;
}
public void setWall(Wall wall) {
this.wall = wall;
}
public boolean isOpen() {
return open;
}
/**
* Sets the level position this door provides access too
* @param x
* @param y
*/
public void setAccessTo(int x, int y) {
this.entryLevel[0] = x;
this.entryLevel[1] = y;
}
/**
* Returns the level position this door provides access too
* @return
*/
public int[] getAccessToPosition() {
return entryLevel;
}
/**
* Sets the level position from which this door is accessible
* @param exitLevel
*/
public void setExitLevel(int[] exitLevel) {
this.exitLevel = exitLevel;
}
/**
* Returns the level position this door is accessible from
* @return
*/
public int[] getAccessFromPosition() {
return exitLevel;
}
@Override
public String toString() {
return super.toString() + ", nextLevelPosition="+entryLevel[0]+","+entryLevel[1];
}
@Override
public boolean equals(Object obj) {
Door door;
if( obj instanceof Door ) {
door = (Door) obj;
} else {
return false;
}
int[] pos = door.getAccessToPosition();
return pos[0] == entryLevel[0] && pos[1] == entryLevel[1] &&
super.equals(obj);
}
public void open() {
Gdx.app.log("Door", "open");
this.open = true;
}
public void close(){
this.open = false;
}
}
| Java |
/*
Buffer.cpp - This file is part of Element
Copyright (C) 2014 Kushview, LLC. All rights reserved.
*/
#if ELEMENT_BUFFER_FACTORY
Buffer::Buffer (DataType dataType_, uint32 subType_)
: factory (nullptr),
refs (0),
dataType (dataType_),
subType (subType_),
capacity (0),
next (nullptr)
{ }
Buffer::~Buffer() { }
void Buffer::attach (BufferFactory* owner)
{
jassert (factory == nullptr && owner != nullptr);
factory = owner;
}
void Buffer::recycle()
{
if (isManaged())
factory->recycle (this);
}
void intrusive_ptr_add_ref (Buffer* b)
{
if (b->isManaged())
++b->refs;
}
void intrusive_ptr_release (Buffer* b)
{
if (b->isManaged())
if (--b->refs == 0)
b->recycle();
}
#endif
| Java |
/*
* Decompiled with CFR 0_115.
*
* Could not load the following classes:
* android.content.BroadcastReceiver
* android.content.Context
* android.content.Intent
* android.content.IntentFilter
*/
package com.buzzfeed.android.vcr.util;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import com.buzzfeed.android.vcr.VCRConfig;
import com.buzzfeed.toolkit.util.EZUtil;
public final class VCRBitrateLimitingReceiver {
private final Context mContext;
private final BroadcastReceiver mReceiver;
public VCRBitrateLimitingReceiver(@NonNull Context context) {
this.mContext = EZUtil.checkNotNull(context, "Context must not be null.");
this.mReceiver = new ConnectivityReceiver();
}
public void register() {
this.mContext.registerReceiver(this.mReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
public void unregister() {
this.mContext.unregisterReceiver(this.mReceiver);
}
private final class ConnectivityReceiver
extends BroadcastReceiver {
private ConnectivityReceiver() {
}
public void onReceive(Context context, Intent intent) {
VCRConfig.getInstance().setAdaptiveBitrateLimitForConnection(context);
}
}
}
| Java |
namespace SandbarWorkbench
{
partial class frmOptions
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmOptions));
this.cmdOK = new System.Windows.Forms.Button();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.txtInstallationGuid = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rdo5Digits = new System.Windows.Forms.RadioButton();
this.rdo4Digits = new System.Windows.Forms.RadioButton();
this.cboStartupView = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.chkLoadLastDatabase = new System.Windows.Forms.CheckBox();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.txtMasterDatabase = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtMasterPassword = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtMasterUserName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtMasterServer = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.grdFolderPaths = new System.Windows.Forms.DataGridView();
this.tabPage4 = new System.Windows.Forms.TabPage();
this.button1 = new System.Windows.Forms.Button();
this.txtMainPy = new System.Windows.Forms.TextBox();
this.label17 = new System.Windows.Forms.Label();
this.valBenchmark = new System.Windows.Forms.NumericUpDown();
this.label16 = new System.Windows.Forms.Label();
this.valIncrement = new System.Windows.Forms.NumericUpDown();
this.label15 = new System.Windows.Forms.Label();
this.cmdBrowseGDALWarp = new System.Windows.Forms.Button();
this.txtGDALWarp = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label();
this.cmdBrowseCompExtents = new System.Windows.Forms.Button();
this.txtCompExtents = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.txtSpatialReference = new System.Windows.Forms.TextBox();
this.cboInterpolation = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.valDefaultOutputCellSize = new System.Windows.Forms.NumericUpDown();
this.valDefaultInputCellSize = new System.Windows.Forms.NumericUpDown();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.tabPage5 = new System.Windows.Forms.TabPage();
this.cmdTestAWS = new System.Windows.Forms.Button();
this.txtErrorLoggingKey = new System.Windows.Forms.TextBox();
this.lblStreamName = new System.Windows.Forms.Label();
this.chkAWSLoggingEnabled = new System.Windows.Forms.CheckBox();
this.tabPage6 = new System.Windows.Forms.TabPage();
this.cboAuditFieldDates = new System.Windows.Forms.ComboBox();
this.label12 = new System.Windows.Forms.Label();
this.cboSurveyDates = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.cboTripDates = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.tabPage7 = new System.Windows.Forms.TabPage();
this.txtPython = new System.Windows.Forms.TextBox();
this.cmdHelp = new System.Windows.Forms.Button();
this.tt = new System.Windows.Forms.ToolTip(this.components);
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).BeginInit();
this.tabPage4.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.valIncrement)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).BeginInit();
this.tabPage5.SuspendLayout();
this.tabPage6.SuspendLayout();
this.tabPage7.SuspendLayout();
this.SuspendLayout();
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.cmdOK.Location = new System.Drawing.Point(491, 373);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(75, 23);
this.cmdOK.TabIndex = 0;
this.cmdOK.Text = "Close";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// tabControl1
//
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Controls.Add(this.tabPage4);
this.tabControl1.Controls.Add(this.tabPage5);
this.tabControl1.Controls.Add(this.tabPage6);
this.tabControl1.Controls.Add(this.tabPage7);
this.tabControl1.Location = new System.Drawing.Point(12, 12);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(554, 355);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.txtInstallationGuid);
this.tabPage1.Controls.Add(this.label9);
this.tabPage1.Controls.Add(this.groupBox1);
this.tabPage1.Controls.Add(this.cboStartupView);
this.tabPage1.Controls.Add(this.label1);
this.tabPage1.Controls.Add(this.chkLoadLastDatabase);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(546, 329);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Start Up";
this.tabPage1.UseVisualStyleBackColor = true;
//
// txtInstallationGuid
//
this.txtInstallationGuid.Location = new System.Drawing.Point(122, 171);
this.txtInstallationGuid.MaxLength = 256;
this.txtInstallationGuid.Name = "txtInstallationGuid";
this.txtInstallationGuid.ReadOnly = true;
this.txtInstallationGuid.Size = new System.Drawing.Size(292, 20);
this.txtInstallationGuid.TabIndex = 5;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(29, 175);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(87, 13);
this.label9.TabIndex = 4;
this.label9.Text = "Installation GUID";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rdo5Digits);
this.groupBox1.Controls.Add(this.rdo4Digits);
this.groupBox1.Location = new System.Drawing.Point(29, 80);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(385, 79);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Sandbar Folder Identification";
//
// rdo5Digits
//
this.rdo5Digits.AutoSize = true;
this.rdo5Digits.Location = new System.Drawing.Point(27, 49);
this.rdo5Digits.Name = "rdo5Digits";
this.rdo5Digits.Size = new System.Drawing.Size(145, 17);
this.rdo5Digits.TabIndex = 1;
this.rdo5Digits.Text = "5 digit codes (e.g. 0003L)";
this.rdo5Digits.UseVisualStyleBackColor = true;
//
// rdo4Digits
//
this.rdo4Digits.AutoSize = true;
this.rdo4Digits.Checked = true;
this.rdo4Digits.Location = new System.Drawing.Point(27, 25);
this.rdo4Digits.Name = "rdo4Digits";
this.rdo4Digits.Size = new System.Drawing.Size(139, 17);
this.rdo4Digits.TabIndex = 0;
this.rdo4Digits.TabStop = true;
this.rdo4Digits.Text = "4 digit codes (e.g. 003L)";
this.rdo4Digits.UseVisualStyleBackColor = true;
//
// cboStartupView
//
this.cboStartupView.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboStartupView.FormattingEnabled = true;
this.cboStartupView.Location = new System.Drawing.Point(149, 44);
this.cboStartupView.Name = "cboStartupView";
this.cboStartupView.Size = new System.Drawing.Size(265, 21);
this.cboStartupView.TabIndex = 2;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(26, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Open view at start up";
//
// chkLoadLastDatabase
//
this.chkLoadLastDatabase.AutoSize = true;
this.chkLoadLastDatabase.Location = new System.Drawing.Point(25, 16);
this.chkLoadLastDatabase.Name = "chkLoadLastDatabase";
this.chkLoadLastDatabase.Size = new System.Drawing.Size(116, 17);
this.chkLoadLastDatabase.TabIndex = 0;
this.chkLoadLastDatabase.Text = "Load last database";
this.chkLoadLastDatabase.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.txtMasterDatabase);
this.tabPage2.Controls.Add(this.label5);
this.tabPage2.Controls.Add(this.txtMasterPassword);
this.tabPage2.Controls.Add(this.label4);
this.tabPage2.Controls.Add(this.txtMasterUserName);
this.tabPage2.Controls.Add(this.label3);
this.tabPage2.Controls.Add(this.txtMasterServer);
this.tabPage2.Controls.Add(this.label2);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(546, 329);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Master Database";
this.tabPage2.UseVisualStyleBackColor = true;
//
// txtMasterDatabase
//
this.txtMasterDatabase.Location = new System.Drawing.Point(98, 50);
this.txtMasterDatabase.Name = "txtMasterDatabase";
this.txtMasterDatabase.Size = new System.Drawing.Size(433, 20);
this.txtMasterDatabase.TabIndex = 3;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(37, 54);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 13);
this.label5.TabIndex = 2;
this.label5.Text = "Database";
//
// txtMasterPassword
//
this.txtMasterPassword.Location = new System.Drawing.Point(98, 114);
this.txtMasterPassword.Name = "txtMasterPassword";
this.txtMasterPassword.PasswordChar = '*';
this.txtMasterPassword.Size = new System.Drawing.Size(433, 20);
this.txtMasterPassword.TabIndex = 7;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(37, 118);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 13);
this.label4.TabIndex = 6;
this.label4.Text = "Password";
//
// txtMasterUserName
//
this.txtMasterUserName.Location = new System.Drawing.Point(98, 82);
this.txtMasterUserName.Name = "txtMasterUserName";
this.txtMasterUserName.Size = new System.Drawing.Size(433, 20);
this.txtMasterUserName.TabIndex = 5;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(32, 86);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 13);
this.label3.TabIndex = 4;
this.label3.Text = "User name";
//
// txtMasterServer
//
this.txtMasterServer.Location = new System.Drawing.Point(98, 18);
this.txtMasterServer.Name = "txtMasterServer";
this.txtMasterServer.Size = new System.Drawing.Size(433, 20);
this.txtMasterServer.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(52, 22);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(38, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Server";
//
// tabPage3
//
this.tabPage3.Controls.Add(this.grdFolderPaths);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(546, 329);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Folders";
this.tabPage3.UseVisualStyleBackColor = true;
//
// grdFolderPaths
//
this.grdFolderPaths.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.grdFolderPaths.Location = new System.Drawing.Point(125, 112);
this.grdFolderPaths.Name = "grdFolderPaths";
this.grdFolderPaths.Size = new System.Drawing.Size(240, 150);
this.grdFolderPaths.TabIndex = 0;
this.grdFolderPaths.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grdFolderPaths_CellClick);
//
// tabPage4
//
this.tabPage4.Controls.Add(this.button1);
this.tabPage4.Controls.Add(this.txtMainPy);
this.tabPage4.Controls.Add(this.label17);
this.tabPage4.Controls.Add(this.valBenchmark);
this.tabPage4.Controls.Add(this.label16);
this.tabPage4.Controls.Add(this.valIncrement);
this.tabPage4.Controls.Add(this.label15);
this.tabPage4.Controls.Add(this.cmdBrowseGDALWarp);
this.tabPage4.Controls.Add(this.txtGDALWarp);
this.tabPage4.Controls.Add(this.label14);
this.tabPage4.Controls.Add(this.cmdBrowseCompExtents);
this.tabPage4.Controls.Add(this.txtCompExtents);
this.tabPage4.Controls.Add(this.label13);
this.tabPage4.Controls.Add(this.groupBox2);
this.tabPage4.Controls.Add(this.cboInterpolation);
this.tabPage4.Controls.Add(this.label8);
this.tabPage4.Controls.Add(this.valDefaultOutputCellSize);
this.tabPage4.Controls.Add(this.valDefaultInputCellSize);
this.tabPage4.Controls.Add(this.label7);
this.tabPage4.Controls.Add(this.label6);
this.tabPage4.Location = new System.Drawing.Point(4, 22);
this.tabPage4.Name = "tabPage4";
this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
this.tabPage4.Size = new System.Drawing.Size(546, 329);
this.tabPage4.TabIndex = 3;
this.tabPage4.Text = "Sandbar Analysis";
this.tabPage4.UseVisualStyleBackColor = true;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.button1.Location = new System.Drawing.Point(517, 171);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(23, 23);
this.button1.TabIndex = 18;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtMainPy
//
this.txtMainPy.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtMainPy.Location = new System.Drawing.Point(176, 172);
this.txtMainPy.Name = "txtMainPy";
this.txtMainPy.ReadOnly = true;
this.txtMainPy.Size = new System.Drawing.Size(335, 20);
this.txtMainPy.TabIndex = 17;
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(39, 176);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(128, 13);
this.label17.TabIndex = 16;
this.label17.Text = "Sandbar Analysis Main.py";
//
// valBenchmark
//
this.valBenchmark.Increment = new decimal(new int[] {
1000,
0,
0,
0});
this.valBenchmark.Location = new System.Drawing.Point(420, 49);
this.valBenchmark.Maximum = new decimal(new int[] {
40000,
0,
0,
0});
this.valBenchmark.Name = "valBenchmark";
this.valBenchmark.Size = new System.Drawing.Size(120, 20);
this.valBenchmark.TabIndex = 9;
this.valBenchmark.Value = new decimal(new int[] {
8000,
0,
0,
0});
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(304, 53);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(113, 13);
this.label16.TabIndex = 8;
this.label16.Text = "Benchmark stage (cfs)";
//
// valIncrement
//
this.valIncrement.DecimalPlaces = 1;
this.valIncrement.Location = new System.Drawing.Point(420, 18);
this.valIncrement.Maximum = new decimal(new int[] {
5,
0,
0,
0});
this.valIncrement.Name = "valIncrement";
this.valIncrement.Size = new System.Drawing.Size(120, 20);
this.valIncrement.TabIndex = 7;
this.valIncrement.Value = new decimal(new int[] {
1,
0,
0,
65536});
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(300, 22);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(117, 13);
this.label15.TabIndex = 6;
this.label15.Text = "Elevation increment (m)";
//
// cmdBrowseGDALWarp
//
this.cmdBrowseGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdBrowseGDALWarp.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.cmdBrowseGDALWarp.Location = new System.Drawing.Point(517, 142);
this.cmdBrowseGDALWarp.Name = "cmdBrowseGDALWarp";
this.cmdBrowseGDALWarp.Size = new System.Drawing.Size(23, 23);
this.cmdBrowseGDALWarp.TabIndex = 15;
this.cmdBrowseGDALWarp.UseVisualStyleBackColor = true;
this.cmdBrowseGDALWarp.Click += new System.EventHandler(this.cmdBrowseGDALWarp_Click);
//
// txtGDALWarp
//
this.txtGDALWarp.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtGDALWarp.Location = new System.Drawing.Point(176, 143);
this.txtGDALWarp.Name = "txtGDALWarp";
this.txtGDALWarp.ReadOnly = true;
this.txtGDALWarp.Size = new System.Drawing.Size(335, 20);
this.txtGDALWarp.TabIndex = 14;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(55, 147);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(117, 13);
this.label14.TabIndex = 13;
this.label14.Text = "GDAL warp executable";
//
// cmdBrowseCompExtents
//
this.cmdBrowseCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdBrowseCompExtents.Image = global::SandbarWorkbench.Properties.Resources.explorer;
this.cmdBrowseCompExtents.Location = new System.Drawing.Point(517, 111);
this.cmdBrowseCompExtents.Name = "cmdBrowseCompExtents";
this.cmdBrowseCompExtents.Size = new System.Drawing.Size(23, 23);
this.cmdBrowseCompExtents.TabIndex = 12;
this.cmdBrowseCompExtents.UseVisualStyleBackColor = true;
this.cmdBrowseCompExtents.Click += new System.EventHandler(this.cmdBrowseCompExtents_Click);
//
// txtCompExtents
//
this.txtCompExtents.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtCompExtents.Location = new System.Drawing.Point(176, 112);
this.txtCompExtents.Name = "txtCompExtents";
this.txtCompExtents.ReadOnly = true;
this.txtCompExtents.Size = new System.Drawing.Size(335, 20);
this.txtCompExtents.TabIndex = 11;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(16, 116);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(156, 13);
this.label13.TabIndex = 10;
this.label13.Text = "Computational extents shapefile";
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.txtSpatialReference);
this.groupBox2.Location = new System.Drawing.Point(6, 202);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(534, 121);
this.groupBox2.TabIndex = 19;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Spatial Reference";
//
// txtSpatialReference
//
this.txtSpatialReference.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtSpatialReference.Location = new System.Drawing.Point(6, 19);
this.txtSpatialReference.Multiline = true;
this.txtSpatialReference.Name = "txtSpatialReference";
this.txtSpatialReference.Size = new System.Drawing.Size(522, 96);
this.txtSpatialReference.TabIndex = 0;
//
// cboInterpolation
//
this.cboInterpolation.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboInterpolation.FormattingEnabled = true;
this.cboInterpolation.Location = new System.Drawing.Point(176, 80);
this.cboInterpolation.Name = "cboInterpolation";
this.cboInterpolation.Size = new System.Drawing.Size(121, 21);
this.cboInterpolation.TabIndex = 5;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(33, 84);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(139, 13);
this.label8.TabIndex = 4;
this.label8.Text = "Default interpolation method";
//
// valDefaultOutputCellSize
//
this.valDefaultOutputCellSize.DecimalPlaces = 2;
this.valDefaultOutputCellSize.Location = new System.Drawing.Point(176, 49);
this.valDefaultOutputCellSize.Name = "valDefaultOutputCellSize";
this.valDefaultOutputCellSize.Size = new System.Drawing.Size(120, 20);
this.valDefaultOutputCellSize.TabIndex = 3;
//
// valDefaultInputCellSize
//
this.valDefaultInputCellSize.DecimalPlaces = 2;
this.valDefaultInputCellSize.Location = new System.Drawing.Point(176, 18);
this.valDefaultInputCellSize.Name = "valDefaultInputCellSize";
this.valDefaultInputCellSize.Size = new System.Drawing.Size(120, 20);
this.valDefaultInputCellSize.TabIndex = 1;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(12, 53);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(160, 13);
this.label7.TabIndex = 2;
this.label7.Text = "Default raster output cell size (m)";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(12, 22);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(160, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Default input text file cell size (m)";
//
// tabPage5
//
this.tabPage5.Controls.Add(this.cmdTestAWS);
this.tabPage5.Controls.Add(this.txtErrorLoggingKey);
this.tabPage5.Controls.Add(this.lblStreamName);
this.tabPage5.Controls.Add(this.chkAWSLoggingEnabled);
this.tabPage5.Location = new System.Drawing.Point(4, 22);
this.tabPage5.Name = "tabPage5";
this.tabPage5.Padding = new System.Windows.Forms.Padding(3);
this.tabPage5.Size = new System.Drawing.Size(546, 329);
this.tabPage5.TabIndex = 4;
this.tabPage5.Text = "Error Logging";
this.tabPage5.UseVisualStyleBackColor = true;
//
// cmdTestAWS
//
this.cmdTestAWS.Location = new System.Drawing.Point(11, 84);
this.cmdTestAWS.Name = "cmdTestAWS";
this.cmdTestAWS.Size = new System.Drawing.Size(156, 23);
this.cmdTestAWS.TabIndex = 8;
this.cmdTestAWS.Text = "Test AWS Message Log";
this.cmdTestAWS.UseVisualStyleBackColor = true;
this.cmdTestAWS.Visible = false;
//
// txtErrorLoggingKey
//
this.txtErrorLoggingKey.Location = new System.Drawing.Point(119, 36);
this.txtErrorLoggingKey.Name = "txtErrorLoggingKey";
this.txtErrorLoggingKey.ReadOnly = true;
this.txtErrorLoggingKey.Size = new System.Drawing.Size(407, 20);
this.txtErrorLoggingKey.TabIndex = 7;
//
// lblStreamName
//
this.lblStreamName.AutoSize = true;
this.lblStreamName.Location = new System.Drawing.Point(29, 40);
this.lblStreamName.Name = "lblStreamName";
this.lblStreamName.Size = new System.Drawing.Size(86, 13);
this.lblStreamName.TabIndex = 6;
this.lblStreamName.Text = "Error logging key";
//
// chkAWSLoggingEnabled
//
this.chkAWSLoggingEnabled.AutoSize = true;
this.chkAWSLoggingEnabled.Location = new System.Drawing.Point(11, 12);
this.chkAWSLoggingEnabled.Name = "chkAWSLoggingEnabled";
this.chkAWSLoggingEnabled.Size = new System.Drawing.Size(261, 17);
this.chkAWSLoggingEnabled.TabIndex = 5;
this.chkAWSLoggingEnabled.Text = "Share status and error information with developers";
this.chkAWSLoggingEnabled.UseVisualStyleBackColor = true;
//
// tabPage6
//
this.tabPage6.Controls.Add(this.cboAuditFieldDates);
this.tabPage6.Controls.Add(this.label12);
this.tabPage6.Controls.Add(this.cboSurveyDates);
this.tabPage6.Controls.Add(this.label11);
this.tabPage6.Controls.Add(this.cboTripDates);
this.tabPage6.Controls.Add(this.label10);
this.tabPage6.Location = new System.Drawing.Point(4, 22);
this.tabPage6.Name = "tabPage6";
this.tabPage6.Padding = new System.Windows.Forms.Padding(3);
this.tabPage6.Size = new System.Drawing.Size(546, 329);
this.tabPage6.TabIndex = 5;
this.tabPage6.Text = "Dates";
this.tabPage6.UseVisualStyleBackColor = true;
//
// cboAuditFieldDates
//
this.cboAuditFieldDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboAuditFieldDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboAuditFieldDates.FormattingEnabled = true;
this.cboAuditFieldDates.Location = new System.Drawing.Point(101, 71);
this.cboAuditFieldDates.Name = "cboAuditFieldDates";
this.cboAuditFieldDates.Size = new System.Drawing.Size(430, 21);
this.cboAuditFieldDates.TabIndex = 5;
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(36, 75);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(58, 13);
this.label12.TabIndex = 4;
this.label12.Text = "Audit fields";
//
// cboSurveyDates
//
this.cboSurveyDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboSurveyDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboSurveyDates.FormattingEnabled = true;
this.cboSurveyDates.Location = new System.Drawing.Point(101, 44);
this.cboSurveyDates.Name = "cboSurveyDates";
this.cboSurveyDates.Size = new System.Drawing.Size(430, 21);
this.cboSurveyDates.TabIndex = 3;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(25, 48);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(69, 13);
this.label11.TabIndex = 2;
this.label11.Text = "Survey dates";
//
// cboTripDates
//
this.cboTripDates.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cboTripDates.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboTripDates.FormattingEnabled = true;
this.cboTripDates.Location = new System.Drawing.Point(101, 17);
this.cboTripDates.Name = "cboTripDates";
this.cboTripDates.Size = new System.Drawing.Size(430, 21);
this.cboTripDates.TabIndex = 1;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(40, 21);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(54, 13);
this.label10.TabIndex = 0;
this.label10.Text = "Trip dates";
//
// tabPage7
//
this.tabPage7.Controls.Add(this.txtPython);
this.tabPage7.Location = new System.Drawing.Point(4, 22);
this.tabPage7.Name = "tabPage7";
this.tabPage7.Padding = new System.Windows.Forms.Padding(3);
this.tabPage7.Size = new System.Drawing.Size(546, 329);
this.tabPage7.TabIndex = 6;
this.tabPage7.Text = "Python";
this.tabPage7.UseVisualStyleBackColor = true;
//
// txtPython
//
this.txtPython.AcceptsReturn = true;
this.txtPython.Dock = System.Windows.Forms.DockStyle.Fill;
this.txtPython.Location = new System.Drawing.Point(3, 3);
this.txtPython.Multiline = true;
this.txtPython.Name = "txtPython";
this.txtPython.Size = new System.Drawing.Size(540, 323);
this.txtPython.TabIndex = 0;
//
// cmdHelp
//
this.cmdHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cmdHelp.Location = new System.Drawing.Point(16, 373);
this.cmdHelp.Name = "cmdHelp";
this.cmdHelp.Size = new System.Drawing.Size(75, 23);
this.cmdHelp.TabIndex = 2;
this.cmdHelp.Text = "Help";
this.cmdHelp.UseVisualStyleBackColor = true;
this.cmdHelp.Click += new System.EventHandler(this.cmdHelp_Click);
//
// frmOptions
//
this.AcceptButton = this.cmdOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(578, 408);
this.Controls.Add(this.cmdHelp);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.cmdOK);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "frmOptions";
this.Text = "frmOptions";
this.Load += new System.EventHandler(this.frmOptions_Load);
this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.frmOptions_HelpRequested);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.tabPage3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.grdFolderPaths)).EndInit();
this.tabPage4.ResumeLayout(false);
this.tabPage4.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.valBenchmark)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.valIncrement)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.valDefaultOutputCellSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.valDefaultInputCellSize)).EndInit();
this.tabPage5.ResumeLayout(false);
this.tabPage5.PerformLayout();
this.tabPage6.ResumeLayout(false);
this.tabPage6.PerformLayout();
this.tabPage7.ResumeLayout(false);
this.tabPage7.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.ComboBox cboStartupView;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.CheckBox chkLoadLastDatabase;
private System.Windows.Forms.TextBox txtMasterDatabase;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox txtMasterPassword;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtMasterUserName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtMasterServer;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.DataGridView grdFolderPaths;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rdo5Digits;
private System.Windows.Forms.RadioButton rdo4Digits;
private System.Windows.Forms.TabPage tabPage4;
private System.Windows.Forms.NumericUpDown valDefaultOutputCellSize;
private System.Windows.Forms.NumericUpDown valDefaultInputCellSize;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox cboInterpolation;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TabPage tabPage5;
private System.Windows.Forms.Button cmdTestAWS;
private System.Windows.Forms.TextBox txtErrorLoggingKey;
private System.Windows.Forms.Label lblStreamName;
private System.Windows.Forms.CheckBox chkAWSLoggingEnabled;
private System.Windows.Forms.TextBox txtInstallationGuid;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.TabPage tabPage6;
private System.Windows.Forms.ComboBox cboAuditFieldDates;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.ComboBox cboSurveyDates;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ComboBox cboTripDates;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button cmdHelp;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.TextBox txtSpatialReference;
private System.Windows.Forms.Button cmdBrowseCompExtents;
private System.Windows.Forms.TextBox txtCompExtents;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Button cmdBrowseGDALWarp;
private System.Windows.Forms.TextBox txtGDALWarp;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.NumericUpDown valBenchmark;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.NumericUpDown valIncrement;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.TabPage tabPage7;
private System.Windows.Forms.TextBox txtPython;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtMainPy;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.ToolTip tt;
}
} | Java |
sap.ui.jsview(ui5nameSpace, {
// define the (default) controller type for this View
getControllerName: function() {
return "my.own.controller";
},
// defines the UI of this View
createContent: function(oController) {
// button text is bound to Model, "press" action is bound to Controller's event handler
return;
}
}); | Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dh2744
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Vector;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dh2744
*/
public class CheckField {
//check that spike list and exp log exists, are correct and match
public static int checkSpkListExpLog(javax.swing.JTextField spikeListField,
javax.swing.JTextField expLogFileField,
javax.swing.JButton runButton,
javax.swing.JTextArea outputTextArea) {
int exitValue = 0;
runButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//experimental log
try {
//read in Experimental log
String csvFile = expLogFileField.getText();
String[] csvCheck1 = csvFile.split("\\.");
String csvText1 = "csv";
System.out.println("end of Exp log"+ csvCheck1[csvCheck1.length - 1] + " equals csv:" );
System.out.println(csvCheck1[csvCheck1.length - 1].equals("csv"));
//two ifs for whether string ends in "]" or not
if ( !csvCheck1[csvCheck1.length - 1].equals("csv") ){
if (!(csvCheck1[csvCheck1.length].equals("csv"))) {
logResult.add( "Exp log file chosen is not a csv file" );
ErrorHandler.errorPanel("Exp log file chosen " + '\n'
+ csvFile + '\n'
+ "Is not a csv file.");
exitValue = -1;
errorLog = true;
}
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(csvFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
String[] expLogParts = line.split(",");
if (!expLogParts[0].toUpperCase().equals("PROJECT")) {
logResult.add( "Error reading in expLog File" );
logResult.add("Exp log file lacks Project column." );
ErrorHandler.errorPanel("Exp log file lacks Project column "
+ '\n'
+ "Please re-enter exp log file");
errorLog = true;
expLogGood = false;
exitValue = -1;
} else if (!expLogParts[1].toUpperCase().equals("EXPERIMENT DATE")) {
logResult.add( "Error reading in expLog File" );
logResult.add("Exp log file lacks Experiment column." );
ErrorHandler.errorPanel("Exp log file lacks Experiment column "
+ '\n'
+ "Please re-enter exp log file");
errorLog = true;
expLogGood = false;
exitValue = -1;
} else {
LineNumberReader lnr = null;
line = bufferedReader.readLine();
Integer i = 1;
line = bufferedReader.readLine();
String[] country = line.split(",");
System.out.println("Start while loop");
while (line != null) {
System.out.println(line);
System.out.println(country[0]);
System.out.println("Current line num " + i);
i++;
line = bufferedReader.readLine();
System.out.println(line);
System.out.println("line = null? " + (line == null));
//System.out.println("line.isEmpty ? " + (line.isEmpty()) );
if (line != null) {
System.out.println("line : " + line);
System.out.println("country : " + country[0]);
country = line.split(",");
}
}
System.out.println("Current line num " + i);
System.out.println("done with while loop");
// Always close files.
bufferedReader.close();
} //end of if-else
} catch (FileNotFoundException ex) {
logResult.add( "ExpLog File not found" );
System.out.println(
"Unable to open file '"
+ csvFile + "'");
errorLog = true;
exitValue = -1;
expLogGood = false;
} catch (IOException ex) {
logResult.add( "Error reading in expLog File" );
logResult.add("IOException." );
System.out.println(
"Error reading file '"
+ csvFile + "'");
errorLog = true;
expLogGood = false;
exitValue = -1;
}
System.out.println("expLogGood : " + expLogGood);
//++++++++++++++++++++++++++++++++++++read in Spk list file
String check = spikeListField.getText();
String[] temp = check.split(",");
System.out.println("spk list chooser: " + temp[0]);
String[] spkCsvFile = temp;
if (temp.length > 1) {
System.out.println("spkCsvFile.length = " + temp.length);
for (int ind = 0; ind < temp.length; ind++) {
if (0 == ind) {
spkCsvFile[ind] = temp[ind].substring(1, temp[ind].length()).trim();
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]);
File fileCheck = new File(spkCsvFile[ind]);
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
} else if (ind == (temp.length - 1)) {
spkCsvFile[ind] = temp[ind].substring(0, temp[ind].length() - 1).trim();
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind]);
File fileCheck = new File(spkCsvFile[ind]);
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
} else {
spkCsvFile[ind] = temp[ind];
System.out.println("spkCsvFile[ind] " + spkCsvFile[ind].trim());
System.out.println("MMMMM" + spkCsvFile[ind].trim() + "MMMMMMM");
File fileCheck = new File(spkCsvFile[ind].trim());
System.out.println("exists? spkCsvFile[" + ind + "] " + fileCheck.exists());
}
}
} else if (temp.length == 1) {
System.out.println("temp.length = " + temp.length);
System.out.println("temp[0].length = " + temp.length);
System.out.println("temp[0].toString().endsWith(]) = " +
temp.toString().endsWith("]") );
System.out.println("temp[0].toString().length() "+temp[0].toString().length());
System.out.println("temp[0].substring(temp[0].toString().length()-1 ) = " +
temp[0].substring(temp[0].toString().length()-1 ).toString() );
System.out.println("temp[0].substring(temp[0].toString().length()-1 ).equals(]) "+
temp[0].substring(temp[0].toString().length()-1 ).equals("]") );
if ( temp[0].substring(temp[0].toString().length()-1 ).equals("]") ){
int len = temp[0].length();
len--;
System.out.println("temp[0].toString().substring(2,3 ) = "+
temp[0].substring(2,3) );
System.out.println("temp[0].toString().substring(1,2 ) = "+
temp[0].toString().substring(1,2 ) );
System.out.println("temp[0].toString().substring(0,1 ) = "+
temp[0].substring(0,1 ) );
if (temp[0].substring(2,3 ).equals("[")){
spkCsvFile[0] = temp[0].substring(3, len).trim();
} else if (temp[0].toString().substring(1,2 ).equals("[")){
spkCsvFile[0] = temp[0].toString().substring(2, len).trim();
} else if (temp[0].toString().substring(0,1 ).equals("[")){
spkCsvFile[0] = temp[0].toString().substring(1, len).trim();
}
System.out.println("spkCsvFile[ind] " + spkCsvFile[0]);
}
File fileCheck = new File(spkCsvFile[0]);
System.out.println("exists? spkCsvFile[" + 0 + "] " + fileCheck.exists());
}
System.out.println("Done with reading in spike-list file names ");
// check that it's csv
for (int j = 0; j < spkCsvFile.length; j++) {
String[] csvCheck = spkCsvFile[j].split("\\.");
String csvText = "csv";
System.out.println(csvCheck[csvCheck.length - 1]);
System.out.println(csvCheck[csvCheck.length - 1].equals("csv"));
if (!(csvCheck[csvCheck.length - 1].equals("csv")||
csvCheck[csvCheck.length].equals("csv")) ) {
logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] );
logResult.add("Is not a csv file." );
ErrorHandler.errorPanel("Spike-list csv file chosen "
+ spkCsvFile[j] + '\n'
+ "Is not a csv file.");
errorLog = true;
exitValue = -1;
}
// spike list file
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(spkCsvFile[j].trim());
System.out.println("file reader " + spkCsvFile[j]);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
System.out.println(line);
String[] spkListHeader = line.split(",");
String third = "Time (s)";
System.out.println(spkListHeader[2]);
// check for spike list file
System.out.println(spkListHeader[2]);
if (!(spkListHeader[2].equals("Time (s)") || spkListHeader[2].equals("Time (s) ")
|| spkListHeader[2].equals("\"Time (s)\"")
|| spkListHeader[2].equals("\"Time (s) \""))) {
logResult.add( "Spike-list csv file chosen " + spkCsvFile[j] );
logResult.add("Is not a proper spike-list file" );
logResult.add( "'Time (s)' should be third column header " );
logResult.add("Instead 3rd column is "+ spkListHeader[2].toString() );
ErrorHandler.errorPanel("Spike-list csv file chosen '" + spkCsvFile[j]+"'" + '\n'
+ "Is not a proper spike-list file" + '\n'
+ "'Time (s)' should be third column header");
exitValue = -1;
errorLog=true;
}
for (int counter2 = 1; counter2 < 5; counter2++) {
// content check
line = bufferedReader.readLine();
if (counter2 == 2) {
System.out.println(line);
String[] spkListContents = line.split(",");
//Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units
System.out.println("Time(s) " + spkListContents[2]
+ " , Electrode =" + spkListContents[3]);
}
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
logResult.add( " Unable to open file " + spkCsvFile[j] );
logResult.add(" Please select another spike list file " );
ErrorHandler.errorPanel("Unable to open file " + j + " "
+ spkCsvFile[j] + '\n'
+ "Please select another spike list file");
exitValue = -1;
errorLog = true;
} catch (IOException ex) {
logResult.add( "Error reading file " + spkCsvFile[j] );
logResult.add(" IOException " );
ErrorHandler.errorPanel(
"Error reading file '" + j + " "
+ spkCsvFile[j] + "'" + '\n' + "Please select another spike list file");
errorLog = true;
exitValue = -1;
}
} //end of loop through spike List Files
// +++++++++need to compare files
System.out.println("Starting match");
for (int j = 0; j < spkCsvFile.length; j++) {
if (expLogGood && !errorLog) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(csvFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
line = bufferedReader.readLine();
System.out.println(line);
String[] country = line.split(",");
//Project,Experiment Date,Plate SN,DIV,Well,Treatment,Size,Dose,Units
if (country.length>5 ){
System.out.println("Project " + country[0]
+ " , Exp Date=" + country[1]
+ " , Plate SN=" + country[2]
+ " , DIV= " + country[3]
+ " , Well=" + country[4]
+ " , trt=" + country[5]);
} else{
System.out.println("Project " + country[0]
+ " , Exp Date=" + country[1]
+ " , Plate SN=" + country[2]
+ " , DIV= " + country[3]
+ " , Well=" + country[4] );
}
// now compare to name of spk-list file
File spkListFile = new File(spkCsvFile[j]);
System.out.println("spkCsvFile "+spkCsvFile[j]);
System.out.println( "File.separator" + File.separator );
String name1 = spkListFile.getName().toString();
String[] partsName1 = name1.split("_");
System.out.println(partsName1[0]);
System.out.println(partsName1[1]);
System.out.println(partsName1[2]);
if (!(partsName1[0].equals(country[0].trim() ))) {
System.out.println("spkListFileNameParts " + partsName1[0].toString());
System.out.println("country " + country[0]);
logResult.add( "project in spk-list file name: " + partsName1[0] );
logResult.add("& experimental log file project: " + country[0]);
logResult.add("Do not match");
ErrorHandler.errorPanel(
"project in spk-list file name: " + partsName1[0] + '\n'
+ "& experimental log file project: " + country[0] + '\n'
+ "Do not match");
exitValue = -1;
errorLog = true;
} else if (!(partsName1[1].equals(country[1].trim() ))) {
logResult.add( "Experiment date does not match between" + '\n' + spkCsvFile[j] );
logResult.add("and experimental log file. ");
logResult.add("Please re-enter file");
ErrorHandler.errorPanel(
"Experiment date does not match between" + '\n' + spkCsvFile[j]
+ " name and experimental log file. '");
exitValue = -1;
errorLog = true;
} else if (!(partsName1[2].equals(country[2].trim() ))) {
logResult.add("No match between spk list" + spkCsvFile[j]);
logResult.add("and experimental log file. ");
ErrorHandler.errorPanel(
"No match between spk list" + spkCsvFile[j] + '\n'
+ "and experimental log file. '"
+ '\n' + "Project name do not match");
exitValue = -1;
errorLog = true;
}
// Always close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '"
+ csvFile + "'");
logResult.add(" Unable to open file ");
logResult.add("'" + csvFile + "'");
ErrorHandler.errorPanel(
"Unable to open file " + '\n'
+ "'" + csvFile + "'" + '\n'
);
exitValue = -1;
errorLog = true;
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ csvFile + "'");
ErrorHandler.errorPanel(
"Error reading file " +
"'" + csvFile + "'" + '\n'
);
logResult.add("Error reading file ");
logResult.add("'" + csvFile + "'");
errorLog = true;
exitValue = -1;
}
System.out.println("expLogGood : " + expLogGood);
System.out.println(" ");
}
System.out.println("done with match ");
System.out.println("NUMER OF TIMES THROUGH LOOP : " + j + 1);
} //end of loop through spike list files
if (!errorLog) {
runButton.setEnabled(true);
logResult.add("Files chosen are without errors");
logResult.add("They match one another");
logResult.add("proceeeding to Analysis");
}
PrintToTextArea.printToTextArea(logResult , outputTextArea);
} catch (Exception e) {
logResult.add("Try at reading the csv file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , outputTextArea);
}
return(exitValue);
}
public static int checkRObject(javax.swing.JTextField rasterFileChooserField,
javax.swing.JButton makeRasterButton,
javax.swing.JTextArea toolsTextArea) {
int exitValue = 0;
makeRasterButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//check Robject
try {
//check extension
String rObject = rasterFileChooserField.getText();
String[] rObjectCheck1 = rObject.split("\\.");
String rObjectText1 = "RData";
System.out.println(
rObject + " (-1) end in .RData? : " );
System.out.println(rObjectCheck1[rObjectCheck1.length-1 ].equals("RData"));
System.out.println(
rObject + " end in .RData? : " );
//System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData"));
//two ifs for whether string ends in "]" or not
if ( !rObjectCheck1[rObjectCheck1.length-1 ].equals("RData") ) {
System.out.println("in if statement");
ErrorHandler.errorPanel("Robject file chosen " + '\n'
+ rObject + '\n'
+ "Is not a Robject of .RData extension");
exitValue = -1;
errorLog = true;
return exitValue;
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// Query R for what's in the Robject
System.out.println(" right before SystemCall.systemCall(cmd0, outputTextArea) " );
Vector<String> envVars = new Vector<String>();
File fileWD = new File(System.getProperty("java.class.path"));
File dashDir = fileWD.getAbsoluteFile().getParentFile();
System.out.println("Dash dir " + dashDir.toString());
File systemPaths = new File( dashDir.toString() +File.separator+"Code" +
File.separator+"systemPaths.txt");
File javaClassPath = new File(System.getProperty("java.class.path"));
File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile();
String rootPath2Slash = rootPath1.toString();
rootPath2Slash = rootPath2Slash.replace("\\", "\\\\");
envVars=GetEnvVars.getEnvVars( systemPaths, toolsTextArea );
String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash +
File.separator +"Code"+ File.separator + "RobjectInfoScript.R "+
"RobjectPath="+rObject.toString();
System.out.println( "cmd0 " + cmd0 );
SystemCall.systemCall(cmd0, toolsTextArea );
System.out.println("After SystemCall in Raster " );
/// here we need code to populate raster parameter object
} catch (Exception i){
logResult.add("Try at running RobjectInfoScript.R");
logResult.add(" ");
logResult.add(" ");
i.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , toolsTextArea);
}
} catch (Exception e) {
logResult.add("Try at reading the Robject file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , toolsTextArea);
}
return(exitValue);
}
public static int checkDistFile(
javax.swing.JTextField distPlotFileField,
javax.swing.JButton plotDistrButton,
javax.swing.JTextArea distPlotTextArea) {
int exitValue = 0;
plotDistrButton.setEnabled(false);
Boolean errorLog = false;
//Vector<String> logResult = new Vector<>();
// to do java 1.6 compatibility
Vector<String> logResult = new Vector<String>();
//check Robject
try {
//check extension
String[] distPlotFile1=RemoveSqBrackets.removeSqBrackets( distPlotFileField );
String[] distPlotFileCheck1 = distPlotFile1[0].split("\\.");
String distPlotFileText1 = "csv";
System.out.println(
distPlotFile1[0] + " (-1) end in .csv? : " );
System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv"));
System.out.println(distPlotFileCheck1[distPlotFileCheck1.length-1 ] +
" =distPlotFileCheck1[distPlotFileCheck1.length-1 ]" );
//System.out.println(rObjectCheck1[rObjectCheck1.length ].equals("RData"));
//two ifs for whether string ends in "]" or not
if ( !distPlotFileCheck1[distPlotFileCheck1.length-1 ].equals("csv") ) {
System.out.println("in if statement");
ErrorHandler.errorPanel("Distribution file chosen " + '\n'
+ distPlotFile1[0] + '\n'
+ "Is not a distribution file of .csv extension");
exitValue = -1;
errorLog = true;
return exitValue;
}
// This will reference one line at a time
String line = null;
Boolean expLogGood = true;
try {
// Query R for what's in the Robject
System.out.println(" right before SystemCall.systemCall(cmd0, distPlotTextArea) " );
Vector<String> envVars = new Vector<String>();
File fileWD = new File(System.getProperty("java.class.path"));
File dashDir = fileWD.getAbsoluteFile().getParentFile();
System.out.println("Dash dir " + dashDir.toString());
File systemPaths = new File( dashDir.toString() +File.separator+"Code" +
File.separator+"systemPaths.txt");
File javaClassPath = new File(System.getProperty("java.class.path"));
File rootPath1 = javaClassPath.getAbsoluteFile().getParentFile();
String rootPath2Slash = rootPath1.toString();
rootPath2Slash = rootPath2Slash.replace("\\", "\\\\");
envVars=GetEnvVars.getEnvVars( systemPaths, distPlotTextArea );
String cmd0 = envVars.get(0).toString() + " " + rootPath2Slash +
File.separator +"Code"+ File.separator + "distFileInfoScript.R "+
"distFilePath="+distPlotFile1[0].toString();
System.out.println( "cmd0 " + cmd0 );
SystemCall.systemCall(cmd0, distPlotTextArea );
System.out.println("After SystemCall in distPlot " );
/// here we need code to populate raster parameter object
} catch (Exception i){
logResult.add("Try at running distFileInfoScript.R");
logResult.add(" ");
logResult.add(" ");
i.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult , distPlotTextArea);
}
} catch (Exception e) {
logResult.add("Try at reading the Robject file failed");
logResult.add(" ");
logResult.add(" ");
e.printStackTrace();
exitValue = -1;
PrintToTextArea.printToTextArea(logResult ,distPlotTextArea);
}
return(exitValue);
}
}
| Java |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('characters', '0011_auto_20160212_1144'),
]
operations = [
migrations.CreateModel(
name='CharacterSpells',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')),
],
options={
'verbose_name': 'Karakt\xe4rers magi',
'verbose_name_plural': 'Karakt\xe4rers magi',
},
),
migrations.AlterModelOptions(
name='spellextras',
options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'},
),
migrations.AlterModelOptions(
name='spellinfo',
options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'},
),
migrations.AddField(
model_name='spellinfo',
name='name',
field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'),
),
migrations.AlterField(
model_name='spellinfo',
name='parent',
field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'),
),
migrations.AddField(
model_name='characterspells',
name='spells',
field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'),
),
]
| Java |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2021 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "localEulerDdtScheme.H"
#include "surfaceInterpolate.H"
#include "fvMatrices.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace fv
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
template<class Type>
const volScalarField& localEulerDdtScheme<Type>::localRDeltaT() const
{
return localEulerDdt::localRDeltaT(mesh());
}
template<class Type>
const surfaceScalarField& localEulerDdtScheme<Type>::localRDeltaTf() const
{
return localEulerDdt::localRDeltaTf(mesh());
}
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const dimensioned<Type>& dt
)
{
const word ddtName("ddt(" + dt.name() + ')');
return tmp<GeometricField<Type, fvPatchField, volMesh>>
(
GeometricField<Type, fvPatchField, volMesh>::New
(
ddtName,
mesh(),
dimensioned<Type>
(
"0",
dt.dimensions()/dimTime,
Zero
),
calculatedFvPatchField<Type>::typeName
)
);
}
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
const volScalarField& rDeltaT = localRDeltaT();
const word ddtName("ddt(" + vf.name() + ')');
return tmp<GeometricField<Type, fvPatchField, volMesh>>
(
GeometricField<Type, fvPatchField, volMesh>::New
(
ddtName,
rDeltaT*(vf - vf.oldTime())
)
);
}
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const dimensionedScalar& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
const volScalarField& rDeltaT = localRDeltaT();
const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')');
return tmp<GeometricField<Type, fvPatchField, volMesh>>
(
GeometricField<Type, fvPatchField, volMesh>::New
(
ddtName,
rDeltaT*rho*(vf - vf.oldTime())
)
);
}
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
const volScalarField& rDeltaT = localRDeltaT();
const word ddtName("ddt(" + rho.name() + ',' + vf.name() + ')');
return tmp<GeometricField<Type, fvPatchField, volMesh>>
(
GeometricField<Type, fvPatchField, volMesh>::New
(
ddtName,
rDeltaT*(rho*vf - rho.oldTime()*vf.oldTime())
)
);
}
template<class Type>
tmp<GeometricField<Type, fvPatchField, volMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const volScalarField& alpha,
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
const volScalarField& rDeltaT = localRDeltaT();
const word ddtName("ddt("+alpha.name()+','+rho.name()+','+vf.name()+')');
return tmp<GeometricField<Type, fvPatchField, volMesh>>
(
GeometricField<Type, fvPatchField, volMesh>::New
(
ddtName,
rDeltaT
*(
alpha*rho*vf
- alpha.oldTime()*rho.oldTime()*vf.oldTime()
)
)
);
}
template<class Type>
tmp<GeometricField<Type, fvsPatchField, surfaceMesh>>
localEulerDdtScheme<Type>::fvcDdt
(
const GeometricField<Type, fvsPatchField, surfaceMesh>& sf
)
{
const surfaceScalarField& rDeltaT = localRDeltaTf();
const word ddtName("ddt("+sf.name()+')');
return GeometricField<Type, fvsPatchField, surfaceMesh>::New
(
ddtName,
rDeltaT*(sf - sf.oldTime())
);
}
template<class Type>
tmp<fvMatrix<Type>>
localEulerDdtScheme<Type>::fvmDdt
(
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
tmp<fvMatrix<Type>> tfvm
(
new fvMatrix<Type>
(
vf,
vf.dimensions()*dimVol/dimTime
)
);
fvMatrix<Type>& fvm = tfvm.ref();
const scalarField& rDeltaT = localRDeltaT();
fvm.diag() = rDeltaT*mesh().Vsc();
fvm.source() = rDeltaT*vf.oldTime().primitiveField()*mesh().Vsc();
return tfvm;
}
template<class Type>
tmp<fvMatrix<Type>>
localEulerDdtScheme<Type>::fvmDdt
(
const dimensionedScalar& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
tmp<fvMatrix<Type>> tfvm
(
new fvMatrix<Type>
(
vf,
rho.dimensions()*vf.dimensions()*dimVol/dimTime
)
);
fvMatrix<Type>& fvm = tfvm.ref();
const scalarField& rDeltaT = localRDeltaT();
fvm.diag() = rDeltaT*rho.value()*mesh().Vsc();
fvm.source() =
rDeltaT*rho.value()*vf.oldTime().primitiveField()*mesh().Vsc();
return tfvm;
}
template<class Type>
tmp<fvMatrix<Type>>
localEulerDdtScheme<Type>::fvmDdt
(
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
tmp<fvMatrix<Type>> tfvm
(
new fvMatrix<Type>
(
vf,
rho.dimensions()*vf.dimensions()*dimVol/dimTime
)
);
fvMatrix<Type>& fvm = tfvm.ref();
const scalarField& rDeltaT = localRDeltaT();
fvm.diag() = rDeltaT*rho.primitiveField()*mesh().Vsc();
fvm.source() = rDeltaT
*rho.oldTime().primitiveField()
*vf.oldTime().primitiveField()*mesh().Vsc();
return tfvm;
}
template<class Type>
tmp<fvMatrix<Type>>
localEulerDdtScheme<Type>::fvmDdt
(
const volScalarField& alpha,
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& vf
)
{
tmp<fvMatrix<Type>> tfvm
(
new fvMatrix<Type>
(
vf,
alpha.dimensions()*rho.dimensions()*vf.dimensions()*dimVol/dimTime
)
);
fvMatrix<Type>& fvm = tfvm.ref();
const scalarField& rDeltaT = localRDeltaT();
fvm.diag() =
rDeltaT*alpha.primitiveField()*rho.primitiveField()*mesh().Vsc();
fvm.source() = rDeltaT
*alpha.oldTime().primitiveField()
*rho.oldTime().primitiveField()
*vf.oldTime().primitiveField()*mesh().Vsc();
return tfvm;
}
/*
// Courant number limited formulation
template<class Type>
tmp<surfaceScalarField> localEulerDdtScheme<Type>::fvcDdtPhiCoeff
(
const GeometricField<Type, fvPatchField, volMesh>& U,
const fluxFieldType& phi,
const fluxFieldType& phiCorr
)
{
// Courant number limited formulation
tmp<surfaceScalarField> tddtCouplingCoeff = scalar(1)
- min
(
mag(phiCorr)*mesh().deltaCoeffs()
/(fvc::interpolate(localRDeltaT())*mesh().magSf()),
scalar(1)
);
surfaceScalarField& ddtCouplingCoeff = tddtCouplingCoeff.ref();
surfaceScalarField::Boundary& ccbf = ddtCouplingCoeff.boundaryFieldRef();
forAll(U.boundaryField(), patchi)
{
if
(
U.boundaryField()[patchi].fixesValue()
|| isA<cyclicAMIFvPatch>(mesh().boundary()[patchi])
)
{
ccbf[patchi] = 0.0;
}
}
if (debug > 1)
{
InfoInFunction
<< "ddtCouplingCoeff mean max min = "
<< gAverage(ddtCouplingCoeff.primitiveField())
<< " " << gMax(ddtCouplingCoeff.primitiveField())
<< " " << gMin(ddtCouplingCoeff.primitiveField())
<< endl;
}
return tddtCouplingCoeff;
}
*/
template<class Type>
tmp<typename localEulerDdtScheme<Type>::fluxFieldType>
localEulerDdtScheme<Type>::fvcDdtUfCorr
(
const GeometricField<Type, fvPatchField, volMesh>& U,
const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf
)
{
const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT()));
fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime());
fluxFieldType phiCorr
(
phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime())
);
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr(" + U.name() + ',' + Uf.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff(U.oldTime(), phiUf0, phiCorr)
*rDeltaT*phiCorr
)
);
}
template<class Type>
tmp<typename localEulerDdtScheme<Type>::fluxFieldType>
localEulerDdtScheme<Type>::fvcDdtPhiCorr
(
const GeometricField<Type, fvPatchField, volMesh>& U,
const fluxFieldType& phi
)
{
const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT()));
fluxFieldType phiCorr
(
phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime())
);
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr(" + U.name() + ',' + phi.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff(U.oldTime(), phi.oldTime(), phiCorr)
*rDeltaT*phiCorr
)
);
}
template<class Type>
tmp<typename localEulerDdtScheme<Type>::fluxFieldType>
localEulerDdtScheme<Type>::fvcDdtUfCorr
(
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& U,
const GeometricField<Type, fvsPatchField, surfaceMesh>& Uf
)
{
const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT()));
if
(
U.dimensions() == dimVelocity
&& Uf.dimensions() == dimDensity*dimVelocity
)
{
GeometricField<Type, fvPatchField, volMesh> rhoU0
(
rho.oldTime()*U.oldTime()
);
fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime());
fluxFieldType phiCorr(phiUf0 - fvc::dotInterpolate(mesh().Sf(), rhoU0));
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr("
+ rho.name() + ',' + U.name() + ',' + Uf.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff(rhoU0, phiUf0, phiCorr, rho.oldTime())
*rDeltaT*phiCorr
)
);
}
else if
(
U.dimensions() == dimDensity*dimVelocity
&& Uf.dimensions() == dimDensity*dimVelocity
)
{
fluxFieldType phiUf0(mesh().Sf() & Uf.oldTime());
fluxFieldType phiCorr
(
phiUf0 - fvc::dotInterpolate(mesh().Sf(), U.oldTime())
);
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr("
+ rho.name() + ',' + U.name() + ',' + Uf.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff
(
U.oldTime(),
phiUf0,
phiCorr,
rho.oldTime()
)*rDeltaT*phiCorr
)
);
}
else
{
FatalErrorInFunction
<< "dimensions of Uf are not correct"
<< abort(FatalError);
return fluxFieldType::null();
}
}
template<class Type>
tmp<typename localEulerDdtScheme<Type>::fluxFieldType>
localEulerDdtScheme<Type>::fvcDdtPhiCorr
(
const volScalarField& rho,
const GeometricField<Type, fvPatchField, volMesh>& U,
const fluxFieldType& phi
)
{
const surfaceScalarField rDeltaT(fvc::interpolate(localRDeltaT()));
if
(
U.dimensions() == dimVelocity
&& phi.dimensions() == rho.dimensions()*dimFlux
)
{
GeometricField<Type, fvPatchField, volMesh> rhoU0
(
rho.oldTime()*U.oldTime()
);
fluxFieldType phiCorr
(
phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), rhoU0)
);
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr("
+ rho.name() + ',' + U.name() + ',' + phi.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff
(
rhoU0,
phi.oldTime(),
phiCorr,
rho.oldTime()
)*rDeltaT*phiCorr
)
);
}
else if
(
U.dimensions() == rho.dimensions()*dimVelocity
&& phi.dimensions() == rho.dimensions()*dimFlux
)
{
fluxFieldType phiCorr
(
phi.oldTime() - fvc::dotInterpolate(mesh().Sf(), U.oldTime())
);
return tmp<fluxFieldType>
(
new fluxFieldType
(
IOobject
(
"ddtCorr("
+ rho.name() + ',' + U.name() + ',' + phi.name() + ')',
mesh().time().timeName(),
mesh()
),
this->fvcDdtPhiCoeff
(
U.oldTime(),
phi.oldTime(),
phiCorr,
rho.oldTime()
)*rDeltaT*phiCorr
)
);
}
else
{
FatalErrorInFunction
<< "dimensions of phi are not correct"
<< abort(FatalError);
return fluxFieldType::null();
}
}
template<class Type>
tmp<surfaceScalarField> localEulerDdtScheme<Type>::meshPhi
(
const GeometricField<Type, fvPatchField, volMesh>&
)
{
return surfaceScalarField::New
(
"meshPhi",
mesh(),
dimensionedScalar(dimVolume/dimTime, 0)
);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace fv
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| Java |
package org.emdev.ui.uimanager;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.view.View;
import android.view.Window;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.emdev.BaseDroidApp;
@TargetApi(11)
public class UIManager3x implements IUIManager {
private static final String SYS_UI_CLS = "com.android.systemui.SystemUIService";
private static final String SYS_UI_PKG = "com.android.systemui";
private static final ComponentName SYS_UI = new ComponentName(SYS_UI_PKG, SYS_UI_CLS);
private static final String SU_PATH1 = "/system/bin/su";
private static final String SU_PATH2 = "/system/xbin/su";
private static final String AM_PATH = "/system/bin/am";
private static final Map<ComponentName, Data> data = new HashMap<ComponentName, Data>() {
/**
*
*/
private static final long serialVersionUID = -6627308913610357179L;
@Override
public Data get(final Object key) {
Data existing = super.get(key);
if (existing == null) {
existing = new Data();
put((ComponentName) key, existing);
}
return existing;
}
};
@Override
public void setTitleVisible(final Activity activity, final boolean visible, final boolean firstTime) {
if (firstTime) {
try {
final Window window = activity.getWindow();
window.requestFeature(Window.FEATURE_ACTION_BAR);
window.requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
activity.setProgressBarIndeterminate(true);
activity.setProgressBarIndeterminateVisibility(true);
window.setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, 1);
} catch (final Throwable th) {
LCTX.e("Error on requestFeature call: " + th.getMessage());
}
}
try {
if (visible) {
activity.getActionBar().show();
} else {
activity.getActionBar().hide();
}
data.get(activity.getComponentName()).titleVisible = visible;
} catch (final Throwable th) {
LCTX.e("Error on requestFeature call: " + th.getMessage());
}
}
@Override
public boolean isTitleVisible(final Activity activity) {
return data.get(activity.getComponentName()).titleVisible;
}
@Override
public void setProgressSpinnerVisible(Activity activity, boolean visible) {
activity.setProgressBarIndeterminateVisibility(visible);
activity.getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, visible ? 1 : 0);
}
@Override
public void setFullScreenMode(final Activity activity, final View view, final boolean fullScreen) {
data.get(activity.getComponentName()).fullScreen = fullScreen;
if (fullScreen) {
stopSystemUI(activity);
} else {
startSystemUI(activity);
}
}
@Override
public void openOptionsMenu(final Activity activity, final View view) {
activity.openOptionsMenu();
}
@Override
public void invalidateOptionsMenu(final Activity activity) {
activity.invalidateOptionsMenu();
}
@Override
public void onMenuOpened(final Activity activity) {
if (data.get(activity.getComponentName()).fullScreen
&& data.get(activity.getComponentName()).fullScreenState.get()) {
startSystemUI(activity);
}
}
@Override
public void onMenuClosed(final Activity activity) {
if (data.get(activity.getComponentName()).fullScreen
&& !data.get(activity.getComponentName()).fullScreenState.get()) {
stopSystemUI(activity);
}
}
@Override
public void onPause(final Activity activity) {
if (data.get(activity.getComponentName()).fullScreen
&& data.get(activity.getComponentName()).fullScreenState.get()) {
startSystemUI(activity);
}
}
@Override
public void onResume(final Activity activity) {
if (data.get(activity.getComponentName()).fullScreen
&& !data.get(activity.getComponentName()).fullScreenState.get()) {
stopSystemUI(activity);
}
}
@Override
public void onDestroy(final Activity activity) {
if (data.get(activity.getComponentName()).fullScreen
&& data.get(activity.getComponentName()).fullScreenState.get()) {
startSystemUI(activity);
}
}
@Override
public boolean isTabletUi(final Activity activity) {
return true;
}
protected void startSystemUI(final Activity activity) {
if (isSystemUIRunning()) {
data.get(activity.getComponentName()).fullScreenState.set(false);
return;
}
exec(false, activity, AM_PATH, "startservice", "-n", SYS_UI.flattenToString());
}
protected void stopSystemUI(final Activity activity) {
if (!isSystemUIRunning()) {
data.get(activity.getComponentName()).fullScreenState.set(true);
return;
}
final String su = getSuPath();
if (su == null) {
data.get(activity.getComponentName()).fullScreenState.set(false);
return;
}
exec(true, activity, su, "-c", "service call activity 79 s16 " + SYS_UI_PKG);
}
protected boolean isSystemUIRunning() {
final Context ctx = BaseDroidApp.context;
final ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningServiceInfo> rsiList = am.getRunningServices(1000);
for (final RunningServiceInfo rsi : rsiList) {
LCTX.d("Service: " + rsi.service);
if (SYS_UI.equals(rsi.service)) {
LCTX.e("System UI service found");
return true;
}
}
return false;
}
protected void exec(final boolean expected, final Activity activity, final String... as) {
(new Thread(new Runnable() {
@Override
public void run() {
try {
final boolean result = execImpl(as);
data.get(activity.getComponentName()).fullScreenState.set(result ? expected : !expected);
} catch (final Throwable th) {
LCTX.e("Changing full screen mode failed: " + th.getCause());
data.get(activity.getComponentName()).fullScreenState.set(!expected);
}
}
})).start();
}
private boolean execImpl(final String... as) {
try {
LCTX.d("Execute: " + Arrays.toString(as));
final Process process = Runtime.getRuntime().exec(as);
final InputStreamReader r = new InputStreamReader(process.getInputStream());
final StringWriter w = new StringWriter();
final char ac[] = new char[8192];
int i = 0;
do {
i = r.read(ac);
if (i > 0) {
w.write(ac, 0, i);
}
} while (i != -1);
r.close();
process.waitFor();
final int exitValue = process.exitValue();
final String text = w.toString();
LCTX.d("Result code: " + exitValue);
LCTX.d("Output:\n" + text);
return 0 == exitValue;
} catch (final IOException e) {
throw new IllegalStateException(e);
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
}
private static String getSuPath() {
final File su1 = new File(SU_PATH1);
if (su1.exists() && su1.isFile() && su1.canExecute()) {
return SU_PATH1;
}
final File su2 = new File(SU_PATH2);
if (su2.exists() && su2.isFile() && su2.canExecute()) {
return SU_PATH2;
}
return null;
}
private static class Data {
boolean fullScreen = false;
boolean titleVisible = true;
final AtomicBoolean fullScreenState = new AtomicBoolean();
}
}
| Java |
/**
Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513)
This software is distributed under the terms of the GNU General Public License.
Please see COPYING for precise license information.
This file is part of Ancient Warfare.
Ancient Warfare is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ancient Warfare is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ancient Warfare. If not, see <http://www.gnu.org/licenses/>.
*/
package shadowmage.ancient_warfare.common.vehicles.types;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import shadowmage.ancient_warfare.common.config.Config;
import shadowmage.ancient_warfare.common.item.ItemLoader;
import shadowmage.ancient_warfare.common.registry.ArmorRegistry;
import shadowmage.ancient_warfare.common.registry.VehicleUpgradeRegistry;
import shadowmage.ancient_warfare.common.research.ResearchGoal;
import shadowmage.ancient_warfare.common.utils.ItemStackWrapperCrafting;
import shadowmage.ancient_warfare.common.vehicles.VehicleBase;
import shadowmage.ancient_warfare.common.vehicles.VehicleMovementType;
import shadowmage.ancient_warfare.common.vehicles.VehicleVarHelpers.BallistaVarHelper;
import shadowmage.ancient_warfare.common.vehicles.helpers.VehicleFiringVarsHelper;
import shadowmage.ancient_warfare.common.vehicles.materials.VehicleMaterial;
import shadowmage.ancient_warfare.common.vehicles.missiles.Ammo;
public class VehicleTypeBoatBallista extends VehicleType
{
/**
* @param typeNum
*/
public VehicleTypeBoatBallista(int typeNum)
{
super(typeNum);
this.configName = "boat_ballista";
this.vehicleMaterial = VehicleMaterial.materialWood;
this.materialCount = 5;
this.movementType = VehicleMovementType.WATER;
this.maxMissileWeight = 2.f;
this.validAmmoTypes.add(Ammo.ammoBallistaBolt);
this.validAmmoTypes.add(Ammo.ammoBallistaBoltFlame);
this.validAmmoTypes.add(Ammo.ammoBallistaBoltExplosive);
this.validAmmoTypes.add(Ammo.ammoBallistaBoltIron);
this.ammoBySoldierRank.put(0, Ammo.ammoBallistaBolt);
this.ammoBySoldierRank.put(1, Ammo.ammoBallistaBolt);
this.ammoBySoldierRank.put(2, Ammo.ammoBallistaBoltFlame);
this.validUpgrades.add(VehicleUpgradeRegistry.speedUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.pitchDownUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.pitchUpUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.pitchExtUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.powerUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.reloadUpgrade);
this.validUpgrades.add(VehicleUpgradeRegistry.aimUpgrade);
this.validArmors.add(ArmorRegistry.armorStone);
this.validArmors.add(ArmorRegistry.armorObsidian);
this.validArmors.add(ArmorRegistry.armorIron);
this.armorBaySize = 3;
this.upgradeBaySize = 3;
this.ammoBaySize = 6;
this.storageBaySize = 0;
this.addNeededResearchForMaterials();
this.addNeededResearch(0, ResearchGoal.vehicleTorsion1);
this.addNeededResearch(1, ResearchGoal.vehicleTorsion2);
this.addNeededResearch(2, ResearchGoal.vehicleTorsion3);
this.addNeededResearch(3, ResearchGoal.vehicleTorsion4);
this.addNeededResearch(4, ResearchGoal.vehicleTorsion5);
this.addNeededResearch(0, ResearchGoal.vehicleMobility1);
this.addNeededResearch(1, ResearchGoal.vehicleMobility2);
this.addNeededResearch(2, ResearchGoal.vehicleMobility3);
this.addNeededResearch(3, ResearchGoal.vehicleMobility4);
this.addNeededResearch(4, ResearchGoal.vehicleMobility5);
this.addNeededResearch(0, ResearchGoal.upgradeMechanics1);
this.addNeededResearch(1, ResearchGoal.upgradeMechanics2);
this.addNeededResearch(2, ResearchGoal.upgradeMechanics3);
this.addNeededResearch(3, ResearchGoal.upgradeMechanics4);
this.addNeededResearch(4, ResearchGoal.upgradeMechanics5);
this.additionalMaterials.add(new ItemStackWrapperCrafting(Item.silk, 8, false, false));
this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.torsionUnit, 2, false, false));
this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.equipmentBay, 1, false, false));
this.additionalMaterials.add(new ItemStackWrapperCrafting(ItemLoader.mobilityUnit, 1, false, false));
this.additionalMaterials.add(new ItemStackWrapperCrafting(Block.cactus, 2, false, false));
this.width = 2.7f;
this.height = 1.4f;
this.baseStrafeSpeed = 2.f;
this.baseForwardSpeed = 6.2f*0.05f;
this.turretForwardsOffset = 23*0.0625f;
this.turretVerticalOffset = 1.325f;
this.accuracy = 0.98f;
this.basePitchMax = 15;
this.basePitchMin = -15;
this.baseMissileVelocityMax = 42.f;//stand versions should have higher velocity, as should fixed version--i.e. mobile turret should have the worst of all versions
this.riderForwardsOffset = -1.0f ;
this.riderVerticalOffset = 0.7f;
this.shouldRiderSit = true;
this.isMountable = true;
this.isDrivable = true;//adjust based on isMobile or not
this.isCombatEngine = true;
this.canAdjustPitch = true;
this.canAdjustPower = false;
this.canAdjustYaw = true;
this.turretRotationMax=360.f;//adjust based on mobile/stand fixed (0), stand fixed(90'), or mobile or stand turret (360)
this.displayName = "item.vehicleSpawner.18";
this.displayTooltip.add("item.vehicleSpawner.tooltip.torsion");
this.displayTooltip.add("item.vehicleSpawner.tooltip.boat");
this.displayTooltip.add("item.vehicleSpawner.tooltip.fullturret");
}
@Override
public String getTextureForMaterialLevel(int level)
{
switch(level)
{
case 0:
return Config.texturePath + "models/boatBallista1.png";
case 1:
return Config.texturePath + "models/boatBallista2.png";
case 2:
return Config.texturePath + "models/boatBallista3.png";
case 3:
return Config.texturePath + "models/boatBallista4.png";
case 4:
return Config.texturePath + "models/boatBallista5.png";
default:
return Config.texturePath + "models/boatBallista1.png";
}
}
@Override
public VehicleFiringVarsHelper getFiringVarsHelper(VehicleBase veh)
{
return new BallistaVarHelper(veh);
}
}
| Java |
/**
* @file udp_socket.c
* @author Ricardo Tubío (rtpardavila[at]gmail.com)
* @version 0.1
*
* @section LICENSE
*
* This file is part of udpip-broadcaster.
* udpip-broadcaster is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* udpip-broadcaster is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with udpip-broadcaster. If not, see <http://www.gnu.org/licenses/>.
*/
#include "udp_socket.h"
/* new_ifreq */
ifreq_t *new_ifreq()
{
ifreq_t *s = NULL;
if ( ( s = (ifreq_t *)malloc(LEN__IFREQ) ) == NULL )
{ handle_sys_error("new_ifreq: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__IFREQ) == NULL )
{ handle_sys_error("new_ifreq: <memset> returns NULL.\n"); }
return(s);
}
/* init_ifreq */
ifreq_t *init_ifreq(const char *if_name)
{
ifreq_t *s = new_ifreq();
int if_name_len = 0;
int ifr_name_len = sizeof(s->ifr_name);
if ( ( if_name_len = strlen(if_name) ) < 0 )
{ handle_sys_error("init_ifreq: <strlen> returns < 0.\n"); }
if ( if_name_len > ifr_name_len )
{ handle_app_error("init_ifreq: if_name's length bigger than ifr's " \
"buffer.\n"); }
if ( strncpy(s->ifr_name, if_name, if_name_len) == NULL )
{ handle_sys_error("init_ifreq: <strncpy> returns NULL.\n"); }
return(s);
}
/* new_sockaddr */
sockaddr_t *new_sockaddr()
{
sockaddr_t *s = NULL;
if ( ( s = (sockaddr_t *)malloc(LEN__SOCKADDR) ) == NULL )
{ handle_sys_error("new_sockaddr: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__SOCKADDR) == NULL )
{ handle_sys_error("new_sockaddr: <memset> returns NULL.\n"); }
return(s);
}
/* new_sockaddr_in */
sockaddr_in_t *new_sockaddr_in()
{
sockaddr_in_t *s = NULL;
if ( ( s = (sockaddr_in_t *)malloc(LEN__SOCKADDR_IN) ) == NULL )
{ handle_sys_error("new_sockaddr_in: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__SOCKADDR) == NULL )
{ handle_sys_error("new_sockaddr_in: <memset> returns NULL.\n"); }
return(s);
}
/* new_iovec */
iovec_t *new_iovec()
{
iovec_t *s = NULL;
if ( ( s = (iovec_t *)malloc(LEN__IOVEC) ) == NULL )
{ handle_sys_error("new_iovec: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__IOVEC) == NULL )
{ handle_sys_error("new_iovec: <memset> returns NULL.\n"); }
return(s);
}
/* new_msg_header */
msg_header_t *new_msg_header()
{
msg_header_t *s = NULL;
if ( ( s = (msg_header_t *)malloc(LEN__MSG_HEADER) ) == NULL )
{ handle_sys_error("new_msg_header: <malloc> returns NULL.\n"); }
if ( memset(s, 0, LEN__MSG_HEADER) == NULL )
{ handle_sys_error("new_msg_header: <memset> returns NULL.\n"); }
if ( ( s->msg_control = malloc(CONTROL_BUFFER_LEN) ) == NULL )
{ handle_sys_error("init_msg_header: <malloc> returns NULL.\n"); }
if ( memset(s->msg_control, 0, CONTROL_BUFFER_LEN) == NULL )
{ handle_sys_error("init_msg_header: <memset> returns NULL.\n"); }
s->msg_controllen = CONTROL_BUFFER_LEN;
s->msg_flags = 0;
s->msg_name = new_sockaddr_in();
s->msg_namelen = LEN__SOCKADDR_IN;
s->msg_iov = new_iovec();
s->msg_iovlen = 0;
return(s);
}
/* init_msg_header */
msg_header_t *init_msg_header(void* buffer, const int buffer_len)
{
msg_header_t *s = new_msg_header();
s->msg_iovlen = 1;
s->msg_iov->iov_base = buffer;
s->msg_iov->iov_len = buffer_len;
return(s);
}
/* init_broadcast_sockaddr_in */
sockaddr_in_t *init_broadcast_sockaddr_in(const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
s->sin_addr.s_addr = htonl(INADDR_BROADCAST);
return(s);
}
/* init_any_sockaddr_in */
sockaddr_in_t *init_any_sockaddr_in(const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
s->sin_addr.s_addr = htonl(INADDR_ANY);
return(s);
}
/* init_sockaddr_in */
sockaddr_in_t *init_sockaddr_in(const char *address, const int port)
{
sockaddr_in_t *s = new_sockaddr_in();
s->sin_family = AF_INET;
s->sin_port = (in_port_t)htons(port);
printf("8\n");
// if ( ( s->sin_addr.s_addr = inet_addr(address) ) < 0 )
// {
//
// printf("entro no erro\n");
// perror("init_sockaddr_in: " \
// "<inet_addr> returns error.\n"); }
printf("9\n");
return(s);
}
/* init_if_sockaddr_in */
sockaddr_in_t *init_if_sockaddr_in(const char *if_name, const int port)
{
sockaddr_in_t *s = NULL;
struct ifaddrs *ifaddr, *ifa;
int i;
char host[NI_MAXHOST];
bool if_found = false;
if ( getifaddrs(&ifaddr) < 0 )
{
handle_sys_error("init_if_sockaddr_in: " \
"<getifaddrs> returned error. Error: ");
}
for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next )
{
if ( ifa->ifa_addr == NULL ) { continue; }
i = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in)
, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
if ( ( strcmp(ifa->ifa_name,if_name) == 0 ) &&
( ifa->ifa_addr->sa_family == AF_INET ) )
{
if ( i != 0 )
{
handle_app_error("init_if_sockaddr_in: " \
"<getnameinfo> failed: %s\n"
, gai_strerror(i));
}
s = init_sockaddr_in(host, port);
if_found = true;
}
}
freeifaddrs(ifaddr);
if ( if_found == false )
{
handle_app_error("Could not get local interface, if_name = %s.\n"
, if_name);
}
return(s);
}
/* open_receiver_udp_socket */
int open_receiver_udp_socket(const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_receiver_udp_socket: " \
"<socket> returns error. Description"); }
// 2) local address for binding
sockaddr_in_t* addr = init_any_sockaddr_in(port);
if ( bind(fd, (sockaddr_t *)addr, LEN__SOCKADDR_IN) < 0 )
{ handle_sys_error("open_receiver_udp_socket: " \
"<bind> returns error. Description"); }
// 3) for analyzing received message's headers
if ( set_msghdrs_socket(fd) < 0 )
{ handle_app_error("open_receiver_udp_socket: " \
"<set_msghdrs_socket> returns error.\n"); }
return(fd);
}
/* open_transmitter_udp_socket */
int open_transmitter_udp_socket(const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_udp_socket: <socket> returns error.\n"); }
return(fd);
}
/* open_broadcast_udp_socket */
int open_broadcast_udp_socket(const char *iface, const int port)
{
int fd = -1;
// 1) socket creation
if ( ( fd = socket(AF_INET, SOCK_DGRAM, 0) ) < 0 )
{ handle_sys_error("open_udp_socket: <socket> returns error.\n"); }
// 2) set broadcast socket options
if ( set_broadcast_socket(fd) < 0 )
{
handle_app_error("open_broadcast_udp_socket: " \
"<set_broadcast_socket> returns error.\n");
}
// 3) broadcast socket must be bound to a specific network interface
if ( set_bindtodevice_socket(iface, fd) < 0 )
{
handle_app_error("open_broadcast_udp_socket: " \
"<set_bindtodevice_socket> returns error.\n");
}
printf("saio do open_broadcast_udp_socket\n");
return(fd);
}
/* set_broadcast_socket */
int set_broadcast_socket(const int socket_fd)
{
int bcast = 1;
if ( setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &bcast, sizeof(int))
< 0 )
{ handle_sys_error("set_broadcast_socket: " \
"<setsockopt> returns error."); }
return(EX_OK);
}
/* set_bindtodevice_socket */
int set_bindtodevice_socket(const char *if_name, const int socket_fd)
{
ifreq_t *ifr = init_ifreq(if_name);
if ( setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, ifr, LEN__IFREQ)
< 0 )
{ handle_sys_error("set_bindtodevice_socket: " \
"<setsockopt> returns error"); }
return(EX_OK);
}
/* set_msghdrs_socket */
int set_msghdrs_socket(const int socket_fd)
{
ifreq_t *ifr = new_ifreq();
if ( setsockopt(socket_fd, IPPROTO_IP, IP_PKTINFO, &ifr, LEN__IFREQ)
< 0 )
{ handle_sys_error("set_generate_headers: " \
"<setsockopt> returns error"); }
return(EX_OK);
}
/* send_message */
int send_message( const sockaddr_t* dest_addr, const int socket_fd,
const void *buffer, const int len )
{
int sent_bytes = 0;
if ( ( sent_bytes = sendto(socket_fd, buffer, len
, 0, dest_addr, LEN__SOCKADDR_IN) ) < 0 )
{
log_sys_error("cb_broadcast_sendto (fd=%d): <sendto> ERROR.\n"
, socket_fd);
getchar();
return(EX_ERR);
}
if ( sent_bytes < len )
{
log_app_msg("send_message: sent %d bytes, requested %d.\n"
, sent_bytes, len);
return(EX_ERR);
}
return(sent_bytes);
}
/* recv_message */
int recv_message(const int socket_fd, void *data)
{
int rx_bytes = 0;
if ( ( rx_bytes = recvfrom(socket_fd, data, UDP_BUFFER_LEN
, 0, NULL, NULL) ) < 0 )
{
log_sys_error("recv_message: wrong <recvfrom> call. ");
return(EX_ERR);
}
return(rx_bytes);
}
/* recv_msg */
int recv_msg( const int socket_fd, msg_header_t *msg,
const in_addr_t block_ip, bool *blocked )
{
int rx_bytes = 0;
// 1) read UDP message from network level
if ( ( rx_bytes = recvmsg(socket_fd, msg, 0) ) < 0 )
{
log_sys_error("recv_msg: wrong <recvmsg> call. ");
return(EX_ERR);
}
in_addr_t src_addr = get_source_address(msg);
if ( block_ip == src_addr )
{ *blocked = true; }
else
{ *blocked = false; }
return(rx_bytes);
}
/* get_source_address */
in_addr_t get_source_address(msg_header_t *msg)
{
sockaddr_in_t *src = NULL;
// iterate through all the control headers
for (
struct cmsghdr *cmsg = CMSG_FIRSTHDR(msg);
cmsg != NULL;
cmsg = CMSG_NXTHDR(msg, cmsg)
)
{
// ignore the control headers that don't match what we want
if ( ( cmsg->cmsg_level != IPPROTO_IP ) ||
( cmsg->cmsg_type != IP_PKTINFO ) )
{ continue; }
//struct in_pktinfo *pi = CMSG_DATA(cmsg);
src = (sockaddr_in_t *)msg->msg_name;
break;
}
return(src->sin_addr.s_addr);
}
/* print_hex_data */
int print_hex_data(const char *buffer, const int len)
{
int last_byte = len - 1;
if ( len < 0 ) { return(EX_WRONG_PARAM); }
for ( int i = 0; i < len; i++ )
{
if ( ( i != 0 ) && ( ( i % BYTES_PER_LINE ) == 0 ) )
{ log_app_msg("\n\t\t\t"); }
log_app_msg("%02X", 0xFF & (unsigned int)buffer[i]);
if ( i < last_byte ) { log_app_msg(":"); }
}
return(EX_OK);
}
/* print_eth_address */
void print_eth_address(const unsigned char *eth_address)
{
printf("%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char) eth_address[0],
(unsigned char) eth_address[1],
(unsigned char) eth_address[2],
(unsigned char) eth_address[3],
(unsigned char) eth_address[4],
(unsigned char) eth_address[5]);
}
| Java |
<?php
$element = $variables['element'];
// Special handling for form elements.
if (isset($element['#array_parents'])) {
// Assign an html ID.
if (!isset($element['#attributes']['id'])) {
$element['#attributes']['id'] = $element['#id'];
}
// Add the 'form-wrapper' class.
$element['#attributes']['class'][] = 'form-wrapper';
}
print '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
?>
| Java |
#pragma strict
var playerFinalScore: int;
var Users: List.< GameObject >;
var userData: GameObject[];
var maxPlayers: int;
var gameManager: GameObject;
var currentPlayer: int;
var currentName: String;
function Awake () {
//var users :GameObject = GameObject.Find("_UserControllerFB");
userData = GameObject.FindGameObjectsWithTag("Player");
}
function Start()
{
gameManager = GameObject.Find("__GameManager");
NotificationCenter.DefaultCenter().AddObserver(this, "PlayerChanger");
}
function Update () {
if(Users.Count>0)
playerFinalScore = Users[0].GetComponent(_GameManager).playerFinalScore;
}
function PlayerChanger()
{
currentPlayer++;
for(var i: int; i<Users.Count; i++)
{
if(i!=currentPlayer)Users[i].SetActive(false);
else Users[i].SetActive(true);
}
print("Change Player");
if(currentPlayer>maxPlayers) currentPlayer=0;
}
function OnLevelWasLoaded(level: int)
{
maxPlayers = userData.Length;
gameManager = GameObject.Find("__GameManager");
for(var i: int; i< userData.Length; i++)
{
if(i!=0)Users[i].SetActive(false);
Users[i].name = userData[i].name;
currentName = Users[0].name;
Users[i].transform.parent = gameManager.transform;
}
} | Java |
<fieldset class="animated fadeIn" ng-form="employeeAuthorizationsForm">
<legend class="pull-left width-full">Authorizations</legend>
<div class="form-group">
<label class="control-label col-sm-4">
Role
<a href="#" tooltip-html="'<b>Employee:</b> An employee has basic viewing access to the schedule. They can facilitate requests on their own shifts, respond to available shifts. <br/> <b>Supervisor:</b> Has same...'">
<i class="fa fa-question-circle"></i>
</a>
</label>
<div class="col-sm-5">
<select name="role" class="form-control"
ng-model="vm.employee.role"
ng-change="vm.deleteSupervisorLocations()"
ng-options="role as role for role in vm.roles"></select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-offset-2 col-sm-8 pb5 text-left">Where can this employee work?</label>
<div class="col-sm-offset-2 col-sm-8">
<div class="checkbox">
<input id="locationCheckboxes" type="checkbox" ng-model="vm.selectedAllLocations" ng-click="vm.selectAll(vm.selectedAllLocations, 'locations')"/>
<label for="locationCheckboxes"><i>select/unselect all</i></label>
</div>
<hr class="mt5 mb5"/>
<ul class="pl0 mb0">
<li ng-repeat="location in vm.locations track by location.id" class="checkbox min-height-0" ng-class="{'pt0': $index !== 0, 'pt5': $index === 0}">
<input id="location_{{$index}}" type="checkbox"
ng-checked="vm.employee.locations.indexOf(location.id) > -1"
ng-click="vm.toggleSelection(location.id, vm.selectedAllLocations, 'locations')" />
<label for="location_{{$index}}">{{location.name}}</label>
</li>
</ul>
</div>
</div>
<div class="form-group" ng-show="vm.employee.role === vm.roles[1]">
<label class="control-label col-sm-offset-2 col-sm-8 pb5 text-left">Which locations can this supervisor manage?</label>
<div class="col-sm-offset-2 col-sm-8">
<div class="checkbox">
<input id="supervisorLocationCheckboxes" type="checkbox" ng-model="vm.selectedAllSupervisorLocations" ng-click="vm.selectAll(vm.selectedAllSupervisorLocations, 'supervisorLocations')"/>
<label for="supervisorLocationCheckboxes"><i>select/unselect all</i></label>
</div>
<hr class="mt5 mb5"/>
<ul class="pl0 mb0">
<li ng-repeat="location in vm.locations track by location.id" class="checkbox min-height-0" ng-class="{'pt0': $index !== 0, 'pt5': $index === 0}">
<input id="supervisor_location_{{$index}}" type="checkbox"
ng-checked="vm.employee.supervisorLocations.indexOf(location.id) > -1"
ng-click="vm.toggleSelection(location.id, vm.selectedAllSupervisorLocations, 'supervisorLocations')" />
<label for="supervisor_location_{{$index}}">{{location.name}}</label>
</li>
</ul>
</div>
</div>
</fieldset>
| Java |
package com.andyadc.concurrency.latch;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
/**
* @author andaicheng
* @version 2017/3/10
*/
public class LatchDemo_1 {
public static void main(String[] args) throws Exception {
int num = 10;
//发令枪只只响一次
CountDownLatch begin = new CountDownLatch(1);
//参与跑步人数
CountDownLatch end = new CountDownLatch(num);
ExecutorService es = Executors.newFixedThreadPool(num);
//记录跑步成绩
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < num; i++) {
futures.add(es.submit(new Runner(begin, end)));
}
//预备
TimeUnit.SECONDS.sleep(10);
//发令枪响
begin.countDown();
//等待跑者跑完
end.await();
int sum = 0;
for (Future<Integer> f : futures) {
sum += f.get();
}
System.out.println("平均分数: " + (float) (sum / num));
}
}
class Runner implements Callable<Integer> {
//开始信号
private CountDownLatch begin;
//结束信号
private CountDownLatch end;
public Runner(CountDownLatch begin, CountDownLatch end) {
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
//跑步成绩
int score = new Random().nextInt(10);
//等待发令枪响
begin.await();
TimeUnit.SECONDS.sleep(score);
//跑步结束
end.countDown();
System.out.println("score:" + score);
return score;
}
}
| Java |
# TimeBombs
A plugin that allows players to drop item bombs that blow up in a configurable time and strength!
[Spigot page](https://www.spigotmc.org/resources/timebombs.19012) **|** [Plugin jar download](http://shortninja.net/files/TimeBombs.jar)
| Java |
package com.infamous.performance.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.infamous.performance.R;
import com.infamous.performance.util.ActivityThemeChangeInterface;
import com.infamous.performance.util.Constants;
import com.infamous.performance.util.Helpers;
/**
* Created by h0rn3t on 09.02.2014.
* http://forum.xda-developers.com/member.php?u=4674443
*/
public class checkSU extends Activity implements Constants, ActivityThemeChangeInterface {
private boolean mIsLightTheme;
private ProgressBar wait;
private TextView info;
private ImageView attn;
SharedPreferences mPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setTheme();
setContentView(R.layout.check_su);
wait=(ProgressBar) findViewById(R.id.wait);
info=(TextView) findViewById(R.id.info);
attn=(ImageView) findViewById(R.id.attn);
if(mPreferences.getBoolean("booting",false)) {
info.setText(getString(R.string.boot_wait));
wait.setVisibility(View.GONE);
attn.setVisibility(View.VISIBLE);
}
else {
new TestSU().execute();
}
}
private class TestSU extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
SystemClock.sleep(1000);
final Boolean canSu = Helpers.checkSu();
final Boolean canBb = Helpers.binExist("busybox")!=null;
if (canSu && canBb) return "ok";
else return "nok";
}
@Override
protected void onPostExecute(String result) {
if(result.equals("nok")){
//mPreferences.edit().putBoolean("firstrun", true).commit();
info.setText(getString(R.string.su_failed_su_or_busybox));
wait.setVisibility(View.GONE);
attn.setVisibility(View.VISIBLE);
}
else{
//mPreferences.edit().putBoolean("firstrun", false).commit();
Intent returnIntent = new Intent();
returnIntent.putExtra("r",result);
setResult(RESULT_OK,returnIntent);
finish();
}
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
@Override
public boolean isThemeChanged() {
final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false);
return is_light_theme != mIsLightTheme;
}
@Override
public void setTheme() {
final boolean is_light_theme = mPreferences.getBoolean(PREF_USE_LIGHT_THEME, false);
mIsLightTheme = is_light_theme;
setTheme(is_light_theme ? R.style.Theme_Light : R.style.Theme_Dark);
}
@Override
public void onResume() {
super.onResume();
}
}
| Java |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Posix"
#include "AsynchronousCloseMonitor.h"
#include "cutils/log.h"
#include "ExecStrings.h"
#include "JNIHelp.h"
#include "JniConstants.h"
#include "JniException.h"
#include "NetworkUtilities.h"
#include "Portability.h"
#include "readlink.h"
#include "../../bionic/libc/dns/include/resolv_netid.h" // For android_getaddrinfofornet.
#include "ScopedBytes.h"
#include "ScopedLocalRef.h"
#include "ScopedPrimitiveArray.h"
#include "ScopedUtfChars.h"
#include "toStringArray.h"
#include "UniquePtr.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <pwd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#ifndef __APPLE__
#include <sys/prctl.h>
#endif
#include <sys/socket.h>
#include <sys/stat.h>
#ifdef __APPLE__
#include <sys/statvfs.h>
#endif
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#ifndef __unused
#define __unused __attribute__((__unused__))
#endif
#define TO_JAVA_STRING(NAME, EXP) \
jstring NAME = env->NewStringUTF(EXP); \
if (NAME == NULL) return NULL;
struct addrinfo_deleter {
void operator()(addrinfo* p) const {
if (p != NULL) { // bionic's freeaddrinfo(3) crashes when passed NULL.
freeaddrinfo(p);
}
}
};
/**
* Used to retry networking system calls that can be interrupted with a signal. Unlike
* TEMP_FAILURE_RETRY, this also handles the case where
* AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal a close() or
* Thread.interrupt(). Other signals that result in an EINTR result are ignored and the system call
* is retried.
*
* Returns the result of the system call though a Java exception will be pending if the result is
* -1: a SocketException if signaled via AsynchronousCloseMonitor, or ErrnoException for other
* failures.
*/
#define NET_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
return_type _rc = -1; \
do { \
bool _wasSignaled; \
int _syscallErrno; \
{ \
int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
AsynchronousCloseMonitor _monitor(_fd); \
_rc = syscall_name(_fd, __VA_ARGS__); \
_syscallErrno = errno; \
_wasSignaled = _monitor.wasSignaled(); \
} \
if (_wasSignaled) { \
jniThrowException(jni_env, "java/net/SocketException", "Socket closed"); \
_rc = -1; \
break; \
} \
if (_rc == -1 && _syscallErrno != EINTR) { \
/* TODO: with a format string we could show the arguments too, like strace(1). */ \
throwErrnoException(jni_env, # syscall_name); \
break; \
} \
} while (_rc == -1); /* _syscallErrno == EINTR && !_wasSignaled */ \
_rc; })
/**
* Used to retry system calls that can be interrupted with a signal. Unlike TEMP_FAILURE_RETRY, this
* also handles the case where AsynchronousCloseMonitor::signalBlockedThreads(fd) is used to signal
* a close() or Thread.interrupt(). Other signals that result in an EINTR result are ignored and the
* system call is retried.
*
* Returns the result of the system call though a Java exception will be pending if the result is
* -1: an IOException if the file descriptor is already closed, a InterruptedIOException if signaled
* via AsynchronousCloseMonitor, or ErrnoException for other failures.
*/
#define IO_FAILURE_RETRY(jni_env, return_type, syscall_name, java_fd, ...) ({ \
return_type _rc = -1; \
do { \
bool _wasSignaled; \
int _syscallErrno; \
{ \
int _fd = jniGetFDFromFileDescriptor(jni_env, java_fd); \
AsynchronousCloseMonitor _monitor(_fd); \
_rc = syscall_name(_fd, __VA_ARGS__); \
_syscallErrno = errno; \
_wasSignaled = _monitor.wasSignaled(); \
} \
if (_wasSignaled) { \
jniThrowException(jni_env, "java/io/InterruptedIOException", # syscall_name " interrupted"); \
_rc = -1; \
break; \
} \
if (_rc == -1 && _syscallErrno != EINTR) { \
/* TODO: with a format string we could show the arguments too, like strace(1). */ \
throwErrnoException(jni_env, # syscall_name); \
break; \
} \
} while (_rc == -1); /* && _syscallErrno == EINTR && !_wasSignaled */ \
_rc; })
static void throwException(JNIEnv* env, jclass exceptionClass, jmethodID ctor3, jmethodID ctor2,
const char* functionName, int error) {
jthrowable cause = NULL;
if (env->ExceptionCheck()) {
cause = env->ExceptionOccurred();
env->ExceptionClear();
}
ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
if (detailMessage.get() == NULL) {
// Not really much we can do here. We're probably dead in the water,
// but let's try to stumble on...
env->ExceptionClear();
}
jobject exception;
if (cause != NULL) {
exception = env->NewObject(exceptionClass, ctor3, detailMessage.get(), error, cause);
} else {
exception = env->NewObject(exceptionClass, ctor2, detailMessage.get(), error);
}
env->Throw(reinterpret_cast<jthrowable>(exception));
}
static void throwErrnoException(JNIEnv* env, const char* functionName) {
int error = errno;
static jmethodID ctor3 = env->GetMethodID(JniConstants::errnoExceptionClass,
"<init>", "(Ljava/lang/String;ILjava/lang/Throwable;)V");
static jmethodID ctor2 = env->GetMethodID(JniConstants::errnoExceptionClass,
"<init>", "(Ljava/lang/String;I)V");
throwException(env, JniConstants::errnoExceptionClass, ctor3, ctor2, functionName, error);
}
static void throwGaiException(JNIEnv* env, const char* functionName, int error) {
// Cache the methods ids before we throw, so we don't call GetMethodID with a pending exception.
static jmethodID ctor3 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>",
"(Ljava/lang/String;ILjava/lang/Throwable;)V");
static jmethodID ctor2 = env->GetMethodID(JniConstants::gaiExceptionClass, "<init>",
"(Ljava/lang/String;I)V");
if (errno != 0) {
// EAI_SYSTEM should mean "look at errno instead", but both glibc and bionic seem to
// mess this up. In particular, if you don't have INTERNET permission, errno will be EACCES
// but you'll get EAI_NONAME or EAI_NODATA. So we want our GaiException to have a
// potentially-relevant ErrnoException as its cause even if error != EAI_SYSTEM.
// http://code.google.com/p/android/issues/detail?id=15722
throwErrnoException(env, functionName);
// Deliberately fall through to throw another exception...
}
throwException(env, JniConstants::gaiExceptionClass, ctor3, ctor2, functionName, error);
}
template <typename rc_t>
static rc_t throwIfMinusOne(JNIEnv* env, const char* name, rc_t rc) {
if (rc == rc_t(-1)) {
throwErrnoException(env, name);
}
return rc;
}
template <typename ScopedT>
class IoVec {
public:
IoVec(JNIEnv* env, size_t bufferCount) : mEnv(env), mBufferCount(bufferCount) {
}
bool init(jobjectArray javaBuffers, jintArray javaOffsets, jintArray javaByteCounts) {
// We can't delete our local references until after the I/O, so make sure we have room.
if (mEnv->PushLocalFrame(mBufferCount + 16) < 0) {
return false;
}
ScopedIntArrayRO offsets(mEnv, javaOffsets);
if (offsets.get() == NULL) {
return false;
}
ScopedIntArrayRO byteCounts(mEnv, javaByteCounts);
if (byteCounts.get() == NULL) {
return false;
}
// TODO: Linux actually has a 1024 buffer limit. glibc works around this, and we should too.
// TODO: you can query the limit at runtime with sysconf(_SC_IOV_MAX).
for (size_t i = 0; i < mBufferCount; ++i) {
jobject buffer = mEnv->GetObjectArrayElement(javaBuffers, i); // We keep this local ref.
mScopedBuffers.push_back(new ScopedT(mEnv, buffer));
jbyte* ptr = const_cast<jbyte*>(mScopedBuffers.back()->get());
if (ptr == NULL) {
return false;
}
struct iovec iov;
iov.iov_base = reinterpret_cast<void*>(ptr + offsets[i]);
iov.iov_len = byteCounts[i];
mIoVec.push_back(iov);
}
return true;
}
~IoVec() {
for (size_t i = 0; i < mScopedBuffers.size(); ++i) {
delete mScopedBuffers[i];
}
mEnv->PopLocalFrame(NULL);
}
iovec* get() {
return &mIoVec[0];
}
size_t size() {
return mBufferCount;
}
private:
JNIEnv* mEnv;
size_t mBufferCount;
std::vector<iovec> mIoVec;
std::vector<ScopedT*> mScopedBuffers;
};
static jobject makeSocketAddress(JNIEnv* env, const sockaddr_storage& ss) {
jint port;
jobject inetAddress = sockaddrToInetAddress(env, ss, &port);
if (inetAddress == NULL) {
return NULL;
}
static jmethodID ctor = env->GetMethodID(JniConstants::inetSocketAddressClass, "<init>",
"(Ljava/net/InetAddress;I)V");
return env->NewObject(JniConstants::inetSocketAddressClass, ctor, inetAddress, port);
}
static jobject makeStructPasswd(JNIEnv* env, const struct passwd& pw) {
TO_JAVA_STRING(pw_name, pw.pw_name);
TO_JAVA_STRING(pw_dir, pw.pw_dir);
TO_JAVA_STRING(pw_shell, pw.pw_shell);
static jmethodID ctor = env->GetMethodID(JniConstants::structPasswdClass, "<init>",
"(Ljava/lang/String;IILjava/lang/String;Ljava/lang/String;)V");
return env->NewObject(JniConstants::structPasswdClass, ctor,
pw_name, static_cast<jint>(pw.pw_uid), static_cast<jint>(pw.pw_gid), pw_dir, pw_shell);
}
static jobject makeStructStat(JNIEnv* env, const struct stat& sb) {
static jmethodID ctor = env->GetMethodID(JniConstants::structStatClass, "<init>",
"(JJIJIIJJJJJJJ)V");
return env->NewObject(JniConstants::structStatClass, ctor,
static_cast<jlong>(sb.st_dev), static_cast<jlong>(sb.st_ino),
static_cast<jint>(sb.st_mode), static_cast<jlong>(sb.st_nlink),
static_cast<jint>(sb.st_uid), static_cast<jint>(sb.st_gid),
static_cast<jlong>(sb.st_rdev), static_cast<jlong>(sb.st_size),
static_cast<jlong>(sb.st_atime), static_cast<jlong>(sb.st_mtime),
static_cast<jlong>(sb.st_ctime), static_cast<jlong>(sb.st_blksize),
static_cast<jlong>(sb.st_blocks));
}
static jobject makeStructStatVfs(JNIEnv* env, const struct statvfs& sb) {
#if defined(__APPLE__)
// Mac OS has no f_namelen field in struct statfs.
jlong max_name_length = 255; // __DARWIN_MAXNAMLEN
#else
jlong max_name_length = static_cast<jlong>(sb.f_namemax);
#endif
static jmethodID ctor = env->GetMethodID(JniConstants::structStatVfsClass, "<init>",
"(JJJJJJJJJJJ)V");
return env->NewObject(JniConstants::structStatVfsClass, ctor,
static_cast<jlong>(sb.f_bsize),
static_cast<jlong>(sb.f_frsize),
static_cast<jlong>(sb.f_blocks),
static_cast<jlong>(sb.f_bfree),
static_cast<jlong>(sb.f_bavail),
static_cast<jlong>(sb.f_files),
static_cast<jlong>(sb.f_ffree),
static_cast<jlong>(sb.f_favail),
static_cast<jlong>(sb.f_fsid),
static_cast<jlong>(sb.f_flag),
max_name_length);
}
static jobject makeStructLinger(JNIEnv* env, const struct linger& l) {
static jmethodID ctor = env->GetMethodID(JniConstants::structLingerClass, "<init>", "(II)V");
return env->NewObject(JniConstants::structLingerClass, ctor, l.l_onoff, l.l_linger);
}
static jobject makeStructTimeval(JNIEnv* env, const struct timeval& tv) {
static jmethodID ctor = env->GetMethodID(JniConstants::structTimevalClass, "<init>", "(JJ)V");
return env->NewObject(JniConstants::structTimevalClass, ctor,
static_cast<jlong>(tv.tv_sec), static_cast<jlong>(tv.tv_usec));
}
static jobject makeStructUcred(JNIEnv* env, const struct ucred& u __unused) {
#ifdef __APPLE__
jniThrowException(env, "java/lang/UnsupportedOperationException", "unimplemented support for ucred on a Mac");
return NULL;
#else
static jmethodID ctor = env->GetMethodID(JniConstants::structUcredClass, "<init>", "(III)V");
return env->NewObject(JniConstants::structUcredClass, ctor, u.pid, u.uid, u.gid);
#endif
}
static jobject makeStructUtsname(JNIEnv* env, const struct utsname& buf) {
TO_JAVA_STRING(sysname, buf.sysname);
TO_JAVA_STRING(nodename, buf.nodename);
TO_JAVA_STRING(release, buf.release);
TO_JAVA_STRING(version, buf.version);
TO_JAVA_STRING(machine, buf.machine);
static jmethodID ctor = env->GetMethodID(JniConstants::structUtsnameClass, "<init>",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
return env->NewObject(JniConstants::structUtsnameClass, ctor,
sysname, nodename, release, version, machine);
};
static bool fillIfreq(JNIEnv* env, jstring javaInterfaceName, struct ifreq& req) {
ScopedUtfChars interfaceName(env, javaInterfaceName);
if (interfaceName.c_str() == NULL) {
return false;
}
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, interfaceName.c_str(), sizeof(req.ifr_name));
req.ifr_name[sizeof(req.ifr_name) - 1] = '\0';
return true;
}
static bool fillInetSocketAddress(JNIEnv* env, jint rc, jobject javaInetSocketAddress, const sockaddr_storage& ss) {
if (rc == -1 || javaInetSocketAddress == NULL) {
return true;
}
// Fill out the passed-in InetSocketAddress with the sender's IP address and port number.
jint port;
jobject sender = sockaddrToInetAddress(env, ss, &port);
if (sender == NULL) {
return false;
}
static jfieldID addressFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "addr", "Ljava/net/InetAddress;");
static jfieldID portFid = env->GetFieldID(JniConstants::inetSocketAddressClass, "port", "I");
env->SetObjectField(javaInetSocketAddress, addressFid, sender);
env->SetIntField(javaInetSocketAddress, portFid, port);
return true;
}
static jobject doStat(JNIEnv* env, jstring javaPath, bool isLstat) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return NULL;
}
struct stat sb;
int rc = isLstat ? TEMP_FAILURE_RETRY(lstat(path.c_str(), &sb))
: TEMP_FAILURE_RETRY(stat(path.c_str(), &sb));
if (rc == -1) {
throwErrnoException(env, isLstat ? "lstat" : "stat");
return NULL;
}
return makeStructStat(env, sb);
}
static jobject doGetSockName(JNIEnv* env, jobject javaFd, bool is_sockname) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
sockaddr_storage ss;
sockaddr* sa = reinterpret_cast<sockaddr*>(&ss);
socklen_t byteCount = sizeof(ss);
memset(&ss, 0, byteCount);
int rc = is_sockname ? TEMP_FAILURE_RETRY(getsockname(fd, sa, &byteCount))
: TEMP_FAILURE_RETRY(getpeername(fd, sa, &byteCount));
if (rc == -1) {
throwErrnoException(env, is_sockname ? "getsockname" : "getpeername");
return NULL;
}
return makeSocketAddress(env, ss);
}
class Passwd {
public:
Passwd(JNIEnv* env) : mEnv(env), mResult(NULL) {
mBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX);
mBuffer.reset(new char[mBufferSize]);
}
jobject getpwnam(const char* name) {
return process("getpwnam_r", getpwnam_r(name, &mPwd, mBuffer.get(), mBufferSize, &mResult));
}
jobject getpwuid(uid_t uid) {
return process("getpwuid_r", getpwuid_r(uid, &mPwd, mBuffer.get(), mBufferSize, &mResult));
}
struct passwd* get() {
return mResult;
}
private:
jobject process(const char* syscall, int error) {
if (mResult == NULL) {
errno = error;
throwErrnoException(mEnv, syscall);
return NULL;
}
return makeStructPasswd(mEnv, *mResult);
}
JNIEnv* mEnv;
UniquePtr<char[]> mBuffer;
size_t mBufferSize;
struct passwd mPwd;
struct passwd* mResult;
};
static jobject Posix_accept(JNIEnv* env, jobject, jobject javaFd, jobject javaInetSocketAddress) {
sockaddr_storage ss;
socklen_t sl = sizeof(ss);
memset(&ss, 0, sizeof(ss));
sockaddr* peer = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL;
socklen_t* peerLength = (javaInetSocketAddress != NULL) ? &sl : 0;
jint clientFd = NET_FAILURE_RETRY(env, int, accept, javaFd, peer, peerLength);
if (clientFd == -1 || !fillInetSocketAddress(env, clientFd, javaInetSocketAddress, ss)) {
close(clientFd);
return NULL;
}
return (clientFd != -1) ? jniCreateFileDescriptor(env, clientFd) : NULL;
}
static jboolean Posix_access(JNIEnv* env, jobject, jstring javaPath, jint mode) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return JNI_FALSE;
}
int rc = TEMP_FAILURE_RETRY(access(path.c_str(), mode));
if (rc == -1) {
throwErrnoException(env, "access");
}
return (rc == 0);
}
static void Posix_bind(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) {
sockaddr_storage ss;
socklen_t sa_len;
if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) {
return;
}
const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss);
// We don't need the return value because we'll already have thrown.
(void) NET_FAILURE_RETRY(env, int, bind, javaFd, sa, sa_len);
}
static void Posix_chmod(JNIEnv* env, jobject, jstring javaPath, jint mode) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "chmod", TEMP_FAILURE_RETRY(chmod(path.c_str(), mode)));
}
static void Posix_chown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "chown", TEMP_FAILURE_RETRY(chown(path.c_str(), uid, gid)));
}
static void Posix_close(JNIEnv* env, jobject, jobject javaFd) {
// Get the FileDescriptor's 'fd' field and clear it.
// We need to do this before we can throw an IOException (http://b/3222087).
int fd = jniGetFDFromFileDescriptor(env, javaFd);
jniSetFileDescriptorOfFD(env, javaFd, -1);
// Even if close(2) fails with EINTR, the fd will have been closed.
// Using TEMP_FAILURE_RETRY will either lead to EBADF or closing someone else's fd.
// http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
throwIfMinusOne(env, "close", close(fd));
}
static void Posix_connect(JNIEnv* env, jobject, jobject javaFd, jobject javaAddress, jint port) {
sockaddr_storage ss;
socklen_t sa_len;
if (!inetAddressToSockaddr(env, javaAddress, port, ss, sa_len)) {
return;
}
const sockaddr* sa = reinterpret_cast<const sockaddr*>(&ss);
// We don't need the return value because we'll already have thrown.
(void) NET_FAILURE_RETRY(env, int, connect, javaFd, sa, sa_len);
}
static jobject Posix_dup(JNIEnv* env, jobject, jobject javaOldFd) {
int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd);
int newFd = throwIfMinusOne(env, "dup", TEMP_FAILURE_RETRY(dup(oldFd)));
return (newFd != -1) ? jniCreateFileDescriptor(env, newFd) : NULL;
}
static jobject Posix_dup2(JNIEnv* env, jobject, jobject javaOldFd, jint newFd) {
int oldFd = jniGetFDFromFileDescriptor(env, javaOldFd);
int fd = throwIfMinusOne(env, "dup2", TEMP_FAILURE_RETRY(dup2(oldFd, newFd)));
return (fd != -1) ? jniCreateFileDescriptor(env, fd) : NULL;
}
static jobjectArray Posix_environ(JNIEnv* env, jobject) {
extern char** environ; // Standard, but not in any header file.
return toStringArray(env, environ);
}
static void Posix_execve(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv, jobjectArray javaEnvp) {
ScopedUtfChars path(env, javaFilename);
if (path.c_str() == NULL) {
return;
}
ExecStrings argv(env, javaArgv);
ExecStrings envp(env, javaEnvp);
execve(path.c_str(), argv.get(), envp.get());
throwErrnoException(env, "execve");
}
static void Posix_execv(JNIEnv* env, jobject, jstring javaFilename, jobjectArray javaArgv) {
ScopedUtfChars path(env, javaFilename);
if (path.c_str() == NULL) {
return;
}
ExecStrings argv(env, javaArgv);
execv(path.c_str(), argv.get());
throwErrnoException(env, "execv");
}
static void Posix_fchmod(JNIEnv* env, jobject, jobject javaFd, jint mode) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "fchmod", TEMP_FAILURE_RETRY(fchmod(fd, mode)));
}
static void Posix_fchown(JNIEnv* env, jobject, jobject javaFd, jint uid, jint gid) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "fchown", TEMP_FAILURE_RETRY(fchown(fd, uid, gid)));
}
static jint Posix_fcntlVoid(JNIEnv* env, jobject, jobject javaFd, jint cmd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd)));
}
static jint Posix_fcntlLong(JNIEnv* env, jobject, jobject javaFd, jint cmd, jlong arg) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
return throwIfMinusOne(env, "fcntl", TEMP_FAILURE_RETRY(fcntl(fd, cmd, arg)));
}
static jint Posix_fcntlFlock(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaFlock) {
static jfieldID typeFid = env->GetFieldID(JniConstants::structFlockClass, "l_type", "S");
static jfieldID whenceFid = env->GetFieldID(JniConstants::structFlockClass, "l_whence", "S");
static jfieldID startFid = env->GetFieldID(JniConstants::structFlockClass, "l_start", "J");
static jfieldID lenFid = env->GetFieldID(JniConstants::structFlockClass, "l_len", "J");
static jfieldID pidFid = env->GetFieldID(JniConstants::structFlockClass, "l_pid", "I");
struct flock64 lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = env->GetShortField(javaFlock, typeFid);
lock.l_whence = env->GetShortField(javaFlock, whenceFid);
lock.l_start = env->GetLongField(javaFlock, startFid);
lock.l_len = env->GetLongField(javaFlock, lenFid);
lock.l_pid = env->GetIntField(javaFlock, pidFid);
int rc = IO_FAILURE_RETRY(env, int, fcntl, javaFd, cmd, &lock);
if (rc != -1) {
env->SetShortField(javaFlock, typeFid, lock.l_type);
env->SetShortField(javaFlock, whenceFid, lock.l_whence);
env->SetLongField(javaFlock, startFid, lock.l_start);
env->SetLongField(javaFlock, lenFid, lock.l_len);
env->SetIntField(javaFlock, pidFid, lock.l_pid);
}
return rc;
}
static void Posix_fdatasync(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "fdatasync", TEMP_FAILURE_RETRY(fdatasync(fd)));
}
static jobject Posix_fstat(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct stat sb;
int rc = TEMP_FAILURE_RETRY(fstat(fd, &sb));
if (rc == -1) {
throwErrnoException(env, "fstat");
return NULL;
}
return makeStructStat(env, sb);
}
static jobject Posix_fstatvfs(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct statvfs sb;
int rc = TEMP_FAILURE_RETRY(fstatvfs(fd, &sb));
if (rc == -1) {
throwErrnoException(env, "fstatvfs");
return NULL;
}
return makeStructStatVfs(env, sb);
}
static void Posix_fsync(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "fsync", TEMP_FAILURE_RETRY(fsync(fd)));
}
static void Posix_ftruncate(JNIEnv* env, jobject, jobject javaFd, jlong length) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "ftruncate", TEMP_FAILURE_RETRY(ftruncate64(fd, length)));
}
static jstring Posix_gai_strerror(JNIEnv* env, jobject, jint error) {
return env->NewStringUTF(gai_strerror(error));
}
static jobjectArray Posix_android_getaddrinfo(JNIEnv* env, jobject, jstring javaNode,
jobject javaHints, jint netId) {
ScopedUtfChars node(env, javaNode);
if (node.c_str() == NULL) {
return NULL;
}
static jfieldID flagsFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_flags", "I");
static jfieldID familyFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_family", "I");
static jfieldID socktypeFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_socktype", "I");
static jfieldID protocolFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_protocol", "I");
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = env->GetIntField(javaHints, flagsFid);
hints.ai_family = env->GetIntField(javaHints, familyFid);
hints.ai_socktype = env->GetIntField(javaHints, socktypeFid);
hints.ai_protocol = env->GetIntField(javaHints, protocolFid);
addrinfo* addressList = NULL;
errno = 0;
int rc = android_getaddrinfofornet(node.c_str(), NULL, &hints, netId, 0, &addressList);
UniquePtr<addrinfo, addrinfo_deleter> addressListDeleter(addressList);
if (rc != 0) {
throwGaiException(env, "android_getaddrinfo", rc);
return NULL;
}
// Count results so we know how to size the output array.
int addressCount = 0;
for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
++addressCount;
} else {
ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
}
}
if (addressCount == 0) {
return NULL;
}
// Prepare output array.
jobjectArray result = env->NewObjectArray(addressCount, JniConstants::inetAddressClass, NULL);
if (result == NULL) {
return NULL;
}
// Examine returned addresses one by one, save them in the output array.
int index = 0;
for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) {
// Unknown address family. Skip this address.
ALOGE("android_getaddrinfo unexpected ai_family %i", ai->ai_family);
continue;
}
// Convert each IP address into a Java byte array.
sockaddr_storage& address = *reinterpret_cast<sockaddr_storage*>(ai->ai_addr);
ScopedLocalRef<jobject> inetAddress(env, sockaddrToInetAddress(env, address, NULL));
if (inetAddress.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(result, index, inetAddress.get());
++index;
}
return result;
}
static jint Posix_getegid(JNIEnv*, jobject) {
return getegid();
}
static jint Posix_geteuid(JNIEnv*, jobject) {
return geteuid();
}
static jint Posix_getgid(JNIEnv*, jobject) {
return getgid();
}
static jstring Posix_getenv(JNIEnv* env, jobject, jstring javaName) {
ScopedUtfChars name(env, javaName);
if (name.c_str() == NULL) {
return NULL;
}
return env->NewStringUTF(getenv(name.c_str()));
}
static jstring Posix_getnameinfo(JNIEnv* env, jobject, jobject javaAddress, jint flags) {
sockaddr_storage ss;
socklen_t sa_len;
if (!inetAddressToSockaddrVerbatim(env, javaAddress, 0, ss, sa_len)) {
return NULL;
}
char buf[NI_MAXHOST]; // NI_MAXHOST is longer than INET6_ADDRSTRLEN.
errno = 0;
int rc = getnameinfo(reinterpret_cast<sockaddr*>(&ss), sa_len, buf, sizeof(buf), NULL, 0, flags);
if (rc != 0) {
throwGaiException(env, "getnameinfo", rc);
return NULL;
}
return env->NewStringUTF(buf);
}
static jobject Posix_getpeername(JNIEnv* env, jobject, jobject javaFd) {
return doGetSockName(env, javaFd, false);
}
static jint Posix_getpid(JNIEnv*, jobject) {
return getpid();
}
static jint Posix_getppid(JNIEnv*, jobject) {
return getppid();
}
static jobject Posix_getpwnam(JNIEnv* env, jobject, jstring javaName) {
ScopedUtfChars name(env, javaName);
if (name.c_str() == NULL) {
return NULL;
}
return Passwd(env).getpwnam(name.c_str());
}
static jobject Posix_getpwuid(JNIEnv* env, jobject, jint uid) {
return Passwd(env).getpwuid(uid);
}
static jobject Posix_getsockname(JNIEnv* env, jobject, jobject javaFd) {
return doGetSockName(env, javaFd, true);
}
static jint Posix_getsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
u_char result = 0;
socklen_t size = sizeof(result);
throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size)));
return result;
}
static jobject Posix_getsockoptInAddr(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
sockaddr_storage ss;
memset(&ss, 0, sizeof(ss));
ss.ss_family = AF_INET; // This is only for the IPv4-only IP_MULTICAST_IF.
sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(&ss);
socklen_t size = sizeof(sa->sin_addr);
int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &sa->sin_addr, &size));
if (rc == -1) {
throwErrnoException(env, "getsockopt");
return NULL;
}
return sockaddrToInetAddress(env, ss, NULL);
}
static jint Posix_getsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
jint result = 0;
socklen_t size = sizeof(result);
throwIfMinusOne(env, "getsockopt", TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &result, &size)));
return result;
}
static jobject Posix_getsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct linger l;
socklen_t size = sizeof(l);
memset(&l, 0, size);
int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &l, &size));
if (rc == -1) {
throwErrnoException(env, "getsockopt");
return NULL;
}
return makeStructLinger(env, l);
}
static jobject Posix_getsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct timeval tv;
socklen_t size = sizeof(tv);
memset(&tv, 0, size);
int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &tv, &size));
if (rc == -1) {
throwErrnoException(env, "getsockopt");
return NULL;
}
return makeStructTimeval(env, tv);
}
static jobject Posix_getsockoptUcred(JNIEnv* env, jobject, jobject javaFd, jint level, jint option) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct ucred u;
socklen_t size = sizeof(u);
memset(&u, 0, size);
int rc = TEMP_FAILURE_RETRY(getsockopt(fd, level, option, &u, &size));
if (rc == -1) {
throwErrnoException(env, "getsockopt");
return NULL;
}
return makeStructUcred(env, u);
}
static jint Posix_gettid(JNIEnv* env __unused, jobject) {
#if defined(__APPLE__)
uint64_t owner;
int rc = pthread_threadid_np(NULL, &owner); // Requires Mac OS 10.6
if (rc != 0) {
throwErrnoException(env, "gettid");
return 0;
}
return static_cast<jint>(owner);
#else
// Neither bionic nor glibc exposes gettid(2).
return syscall(__NR_gettid);
#endif
}
static jint Posix_getuid(JNIEnv*, jobject) {
return getuid();
}
static jstring Posix_if_indextoname(JNIEnv* env, jobject, jint index) {
char buf[IF_NAMESIZE];
char* name = if_indextoname(index, buf);
// if_indextoname(3) returns NULL on failure, which will come out of NewStringUTF unscathed.
// There's no useful information in errno, so we don't bother throwing. Callers can null-check.
return env->NewStringUTF(name);
}
static jobject Posix_inet_pton(JNIEnv* env, jobject, jint family, jstring javaName) {
ScopedUtfChars name(env, javaName);
if (name.c_str() == NULL) {
return NULL;
}
sockaddr_storage ss;
memset(&ss, 0, sizeof(ss));
// sockaddr_in and sockaddr_in6 are at the same address, so we can use either here.
void* dst = &reinterpret_cast<sockaddr_in*>(&ss)->sin_addr;
if (inet_pton(family, name.c_str(), dst) != 1) {
return NULL;
}
ss.ss_family = family;
return sockaddrToInetAddress(env, ss, NULL);
}
static jobject Posix_ioctlInetAddress(JNIEnv* env, jobject, jobject javaFd, jint cmd, jstring javaInterfaceName) {
struct ifreq req;
if (!fillIfreq(env, javaInterfaceName, req)) {
return NULL;
}
int fd = jniGetFDFromFileDescriptor(env, javaFd);
int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &req)));
if (rc == -1) {
return NULL;
}
return sockaddrToInetAddress(env, reinterpret_cast<sockaddr_storage&>(req.ifr_addr), NULL);
}
static jint Posix_ioctlInt(JNIEnv* env, jobject, jobject javaFd, jint cmd, jobject javaArg) {
// This is complicated because ioctls may return their result by updating their argument
// or via their return value, so we need to support both.
int fd = jniGetFDFromFileDescriptor(env, javaFd);
static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I");
jint arg = env->GetIntField(javaArg, valueFid);
int rc = throwIfMinusOne(env, "ioctl", TEMP_FAILURE_RETRY(ioctl(fd, cmd, &arg)));
if (!env->ExceptionCheck()) {
env->SetIntField(javaArg, valueFid, arg);
}
return rc;
}
static jboolean Posix_isatty(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
return TEMP_FAILURE_RETRY(isatty(fd)) == 1;
}
static void Posix_kill(JNIEnv* env, jobject, jint pid, jint sig) {
throwIfMinusOne(env, "kill", TEMP_FAILURE_RETRY(kill(pid, sig)));
}
static void Posix_lchown(JNIEnv* env, jobject, jstring javaPath, jint uid, jint gid) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "lchown", TEMP_FAILURE_RETRY(lchown(path.c_str(), uid, gid)));
}
static void Posix_link(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
ScopedUtfChars oldPath(env, javaOldPath);
if (oldPath.c_str() == NULL) {
return;
}
ScopedUtfChars newPath(env, javaNewPath);
if (newPath.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "link", TEMP_FAILURE_RETRY(link(oldPath.c_str(), newPath.c_str())));
}
static void Posix_listen(JNIEnv* env, jobject, jobject javaFd, jint backlog) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "listen", TEMP_FAILURE_RETRY(listen(fd, backlog)));
}
static jlong Posix_lseek(JNIEnv* env, jobject, jobject javaFd, jlong offset, jint whence) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
return throwIfMinusOne(env, "lseek", TEMP_FAILURE_RETRY(lseek64(fd, offset, whence)));
}
static jobject Posix_lstat(JNIEnv* env, jobject, jstring javaPath) {
return doStat(env, javaPath, true);
}
static void Posix_mincore(JNIEnv* env, jobject, jlong address, jlong byteCount, jbyteArray javaVector) {
ScopedByteArrayRW vector(env, javaVector);
if (vector.get() == NULL) {
return;
}
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
unsigned char* vec = reinterpret_cast<unsigned char*>(vector.get());
throwIfMinusOne(env, "mincore", TEMP_FAILURE_RETRY(mincore(ptr, byteCount, vec)));
}
static void Posix_mkdir(JNIEnv* env, jobject, jstring javaPath, jint mode) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "mkdir", TEMP_FAILURE_RETRY(mkdir(path.c_str(), mode)));
}
static void Posix_mkfifo(JNIEnv* env, jobject, jstring javaPath, jint mode) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "mkfifo", TEMP_FAILURE_RETRY(mkfifo(path.c_str(), mode)));
}
static void Posix_mlock(JNIEnv* env, jobject, jlong address, jlong byteCount) {
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
throwIfMinusOne(env, "mlock", TEMP_FAILURE_RETRY(mlock(ptr, byteCount)));
}
static jlong Posix_mmap(JNIEnv* env, jobject, jlong address, jlong byteCount, jint prot, jint flags, jobject javaFd, jlong offset) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
void* suggestedPtr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
void* ptr = mmap(suggestedPtr, byteCount, prot, flags, fd, offset);
if (ptr == MAP_FAILED) {
throwErrnoException(env, "mmap");
}
return static_cast<jlong>(reinterpret_cast<uintptr_t>(ptr));
}
static void Posix_msync(JNIEnv* env, jobject, jlong address, jlong byteCount, jint flags) {
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
throwIfMinusOne(env, "msync", TEMP_FAILURE_RETRY(msync(ptr, byteCount, flags)));
}
static void Posix_munlock(JNIEnv* env, jobject, jlong address, jlong byteCount) {
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
throwIfMinusOne(env, "munlock", TEMP_FAILURE_RETRY(munlock(ptr, byteCount)));
}
static void Posix_munmap(JNIEnv* env, jobject, jlong address, jlong byteCount) {
void* ptr = reinterpret_cast<void*>(static_cast<uintptr_t>(address));
throwIfMinusOne(env, "munmap", TEMP_FAILURE_RETRY(munmap(ptr, byteCount)));
}
static jobject Posix_open(JNIEnv* env, jobject, jstring javaPath, jint flags, jint mode) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return NULL;
}
int fd = throwIfMinusOne(env, "open", TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode)));
return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL;
}
static jobjectArray Posix_pipe(JNIEnv* env, jobject) {
int fds[2];
throwIfMinusOne(env, "pipe", TEMP_FAILURE_RETRY(pipe(&fds[0])));
jobjectArray result = env->NewObjectArray(2, JniConstants::fileDescriptorClass, NULL);
if (result == NULL) {
return NULL;
}
for (int i = 0; i < 2; ++i) {
ScopedLocalRef<jobject> fd(env, jniCreateFileDescriptor(env, fds[i]));
if (fd.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(result, i, fd.get());
if (env->ExceptionCheck()) {
return NULL;
}
}
return result;
}
static jint Posix_poll(JNIEnv* env, jobject, jobjectArray javaStructs, jint timeoutMs) {
static jfieldID fdFid = env->GetFieldID(JniConstants::structPollfdClass, "fd", "Ljava/io/FileDescriptor;");
static jfieldID eventsFid = env->GetFieldID(JniConstants::structPollfdClass, "events", "S");
static jfieldID reventsFid = env->GetFieldID(JniConstants::structPollfdClass, "revents", "S");
// Turn the Java android.system.StructPollfd[] into a C++ struct pollfd[].
size_t arrayLength = env->GetArrayLength(javaStructs);
UniquePtr<struct pollfd[]> fds(new struct pollfd[arrayLength]);
memset(fds.get(), 0, sizeof(struct pollfd) * arrayLength);
size_t count = 0; // Some trailing array elements may be irrelevant. (See below.)
for (size_t i = 0; i < arrayLength; ++i) {
ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i));
if (javaStruct.get() == NULL) {
break; // We allow trailing nulls in the array for caller convenience.
}
ScopedLocalRef<jobject> javaFd(env, env->GetObjectField(javaStruct.get(), fdFid));
if (javaFd.get() == NULL) {
break; // We also allow callers to just clear the fd field (this is what Selector does).
}
fds[count].fd = jniGetFDFromFileDescriptor(env, javaFd.get());
fds[count].events = env->GetShortField(javaStruct.get(), eventsFid);
++count;
}
std::vector<AsynchronousCloseMonitor*> monitors;
for (size_t i = 0; i < count; ++i) {
monitors.push_back(new AsynchronousCloseMonitor(fds[i].fd));
}
int rc = poll(fds.get(), count, timeoutMs);
for (size_t i = 0; i < monitors.size(); ++i) {
delete monitors[i];
}
if (rc == -1) {
throwErrnoException(env, "poll");
return -1;
}
// Update the revents fields in the Java android.system.StructPollfd[].
for (size_t i = 0; i < count; ++i) {
ScopedLocalRef<jobject> javaStruct(env, env->GetObjectArrayElement(javaStructs, i));
if (javaStruct.get() == NULL) {
return -1;
}
env->SetShortField(javaStruct.get(), reventsFid, fds[i].revents);
}
return rc;
}
static void Posix_posix_fallocate(JNIEnv* env, jobject, jobject javaFd __unused,
jlong offset __unused, jlong length __unused) {
#ifdef __APPLE__
jniThrowException(env, "java/lang/UnsupportedOperationException",
"fallocate doesn't exist on a Mac");
#else
int fd = jniGetFDFromFileDescriptor(env, javaFd);
errno = TEMP_FAILURE_RETRY(posix_fallocate64(fd, offset, length));
if (errno != 0) {
throwErrnoException(env, "posix_fallocate");
}
#endif
}
static jint Posix_prctl(JNIEnv* env, jobject, jint option __unused, jlong arg2 __unused,
jlong arg3 __unused, jlong arg4 __unused, jlong arg5 __unused) {
#ifdef __APPLE__
jniThrowException(env, "java/lang/UnsupportedOperationException", "prctl doesn't exist on a Mac");
return 0;
#else
int result = prctl(static_cast<int>(option),
static_cast<unsigned long>(arg2), static_cast<unsigned long>(arg3),
static_cast<unsigned long>(arg4), static_cast<unsigned long>(arg5));
return throwIfMinusOne(env, "prctl", result);
#endif
}
static jint Posix_preadBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jlong offset) {
ScopedBytesRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, pread64, javaFd, bytes.get() + byteOffset, byteCount, offset);
}
static jint Posix_pwriteBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount, jlong offset) {
ScopedBytesRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, pwrite64, javaFd, bytes.get() + byteOffset, byteCount, offset);
}
static jint Posix_readBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount) {
ScopedBytesRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, read, javaFd, bytes.get() + byteOffset, byteCount);
}
static jstring Posix_readlink(JNIEnv* env, jobject, jstring javaPath) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return NULL;
}
std::string result;
if (!readlink(path.c_str(), result)) {
throwErrnoException(env, "readlink");
return NULL;
}
return env->NewStringUTF(result.c_str());
}
static jint Posix_readv(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
IoVec<ScopedBytesRW> ioVec(env, env->GetArrayLength(buffers));
if (!ioVec.init(buffers, offsets, byteCounts)) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, readv, javaFd, ioVec.get(), ioVec.size());
}
static jint Posix_recvfromBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetSocketAddress) {
ScopedBytesRW bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
sockaddr_storage ss;
socklen_t sl = sizeof(ss);
memset(&ss, 0, sizeof(ss));
sockaddr* from = (javaInetSocketAddress != NULL) ? reinterpret_cast<sockaddr*>(&ss) : NULL;
socklen_t* fromLength = (javaInetSocketAddress != NULL) ? &sl : 0;
jint recvCount = NET_FAILURE_RETRY(env, ssize_t, recvfrom, javaFd, bytes.get() + byteOffset, byteCount, flags, from, fromLength);
fillInetSocketAddress(env, recvCount, javaInetSocketAddress, ss);
return recvCount;
}
static void Posix_remove(JNIEnv* env, jobject, jstring javaPath) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "remove", TEMP_FAILURE_RETRY(remove(path.c_str())));
}
static void Posix_rename(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
ScopedUtfChars oldPath(env, javaOldPath);
if (oldPath.c_str() == NULL) {
return;
}
ScopedUtfChars newPath(env, javaNewPath);
if (newPath.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "rename", TEMP_FAILURE_RETRY(rename(oldPath.c_str(), newPath.c_str())));
}
static jlong Posix_sendfile(JNIEnv* env, jobject, jobject javaOutFd, jobject javaInFd, jobject javaOffset, jlong byteCount) {
int outFd = jniGetFDFromFileDescriptor(env, javaOutFd);
int inFd = jniGetFDFromFileDescriptor(env, javaInFd);
static jfieldID valueFid = env->GetFieldID(JniConstants::mutableLongClass, "value", "J");
off_t offset = 0;
off_t* offsetPtr = NULL;
if (javaOffset != NULL) {
// TODO: fix bionic so we can have a 64-bit off_t!
offset = env->GetLongField(javaOffset, valueFid);
offsetPtr = &offset;
}
jlong result = throwIfMinusOne(env, "sendfile", TEMP_FAILURE_RETRY(sendfile(outFd, inFd, offsetPtr, byteCount)));
if (javaOffset != NULL) {
env->SetLongField(javaOffset, valueFid, offset);
}
return result;
}
static jint Posix_sendtoBytes(JNIEnv* env, jobject, jobject javaFd, jobject javaBytes, jint byteOffset, jint byteCount, jint flags, jobject javaInetAddress, jint port) {
ScopedBytesRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
sockaddr_storage ss;
socklen_t sa_len = 0;
if (javaInetAddress != NULL && !inetAddressToSockaddr(env, javaInetAddress, port, ss, sa_len)) {
return -1;
}
const sockaddr* to = (javaInetAddress != NULL) ? reinterpret_cast<const sockaddr*>(&ss) : NULL;
return NET_FAILURE_RETRY(env, ssize_t, sendto, javaFd, bytes.get() + byteOffset, byteCount, flags, to, sa_len);
}
static void Posix_setegid(JNIEnv* env, jobject, jint egid) {
throwIfMinusOne(env, "setegid", TEMP_FAILURE_RETRY(setegid(egid)));
}
static void Posix_setenv(JNIEnv* env, jobject, jstring javaName, jstring javaValue, jboolean overwrite) {
ScopedUtfChars name(env, javaName);
if (name.c_str() == NULL) {
return;
}
ScopedUtfChars value(env, javaValue);
if (value.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "setenv", setenv(name.c_str(), value.c_str(), overwrite));
}
static void Posix_seteuid(JNIEnv* env, jobject, jint euid) {
throwIfMinusOne(env, "seteuid", TEMP_FAILURE_RETRY(seteuid(euid)));
}
static void Posix_setgid(JNIEnv* env, jobject, jint gid) {
throwIfMinusOne(env, "setgid", TEMP_FAILURE_RETRY(setgid(gid)));
}
static jint Posix_setsid(JNIEnv* env, jobject) {
return throwIfMinusOne(env, "setsid", TEMP_FAILURE_RETRY(setsid()));
}
static void Posix_setsockoptByte(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
u_char byte = value;
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &byte, sizeof(byte))));
}
static void Posix_setsockoptIfreq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jstring javaInterfaceName) {
struct ifreq req;
if (!fillIfreq(env, javaInterfaceName, req)) {
return;
}
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))));
}
static void Posix_setsockoptInt(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
}
#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED < 1070
// Mac OS didn't support modern multicast APIs until 10.7.
static void Posix_setsockoptIpMreqn(JNIEnv*, jobject, jobject, jint, jint, jint) { abort(); }
static void Posix_setsockoptGroupReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); }
static void Posix_setsockoptGroupSourceReq(JNIEnv*, jobject, jobject, jint, jint, jobject) { abort(); }
#else
static void Posix_setsockoptIpMreqn(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jint value) {
ip_mreqn req;
memset(&req, 0, sizeof(req));
req.imr_ifindex = value;
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req))));
}
static void Posix_setsockoptGroupReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupReq) {
struct group_req req;
memset(&req, 0, sizeof(req));
static jfieldID grInterfaceFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_interface", "I");
req.gr_interface = env->GetIntField(javaGroupReq, grInterfaceFid);
// Get the IPv4 or IPv6 multicast address to join or leave.
static jfieldID grGroupFid = env->GetFieldID(JniConstants::structGroupReqClass, "gr_group", "Ljava/net/InetAddress;");
ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupReq, grGroupFid));
socklen_t sa_len;
if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gr_group, sa_len)) {
return;
}
int fd = jniGetFDFromFileDescriptor(env, javaFd);
int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)));
if (rc == -1 && errno == EINVAL) {
// Maybe we're a 32-bit binary talking to a 64-bit kernel?
// glibc doesn't automatically handle this.
// http://sourceware.org/bugzilla/show_bug.cgi?id=12080
struct group_req64 {
uint32_t gr_interface;
uint32_t my_padding;
sockaddr_storage gr_group;
};
group_req64 req64;
req64.gr_interface = req.gr_interface;
memcpy(&req64.gr_group, &req.gr_group, sizeof(req.gr_group));
rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64)));
}
throwIfMinusOne(env, "setsockopt", rc);
}
static void Posix_setsockoptGroupSourceReq(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaGroupSourceReq) {
socklen_t sa_len;
struct group_source_req req;
memset(&req, 0, sizeof(req));
static jfieldID gsrInterfaceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_interface", "I");
req.gsr_interface = env->GetIntField(javaGroupSourceReq, gsrInterfaceFid);
// Get the IPv4 or IPv6 multicast address to join or leave.
static jfieldID gsrGroupFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_group", "Ljava/net/InetAddress;");
ScopedLocalRef<jobject> javaGroup(env, env->GetObjectField(javaGroupSourceReq, gsrGroupFid));
if (!inetAddressToSockaddrVerbatim(env, javaGroup.get(), 0, req.gsr_group, sa_len)) {
return;
}
// Get the IPv4 or IPv6 multicast address to add to the filter.
static jfieldID gsrSourceFid = env->GetFieldID(JniConstants::structGroupSourceReqClass, "gsr_source", "Ljava/net/InetAddress;");
ScopedLocalRef<jobject> javaSource(env, env->GetObjectField(javaGroupSourceReq, gsrSourceFid));
if (!inetAddressToSockaddrVerbatim(env, javaSource.get(), 0, req.gsr_source, sa_len)) {
return;
}
int fd = jniGetFDFromFileDescriptor(env, javaFd);
int rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req, sizeof(req)));
if (rc == -1 && errno == EINVAL) {
// Maybe we're a 32-bit binary talking to a 64-bit kernel?
// glibc doesn't automatically handle this.
// http://sourceware.org/bugzilla/show_bug.cgi?id=12080
struct group_source_req64 {
uint32_t gsr_interface;
uint32_t my_padding;
sockaddr_storage gsr_group;
sockaddr_storage gsr_source;
};
group_source_req64 req64;
req64.gsr_interface = req.gsr_interface;
memcpy(&req64.gsr_group, &req.gsr_group, sizeof(req.gsr_group));
memcpy(&req64.gsr_source, &req.gsr_source, sizeof(req.gsr_source));
rc = TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &req64, sizeof(req64)));
}
throwIfMinusOne(env, "setsockopt", rc);
}
#endif
static void Posix_setsockoptLinger(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaLinger) {
static jfieldID lOnoffFid = env->GetFieldID(JniConstants::structLingerClass, "l_onoff", "I");
static jfieldID lLingerFid = env->GetFieldID(JniConstants::structLingerClass, "l_linger", "I");
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct linger value;
value.l_onoff = env->GetIntField(javaLinger, lOnoffFid);
value.l_linger = env->GetIntField(javaLinger, lLingerFid);
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
}
static void Posix_setsockoptTimeval(JNIEnv* env, jobject, jobject javaFd, jint level, jint option, jobject javaTimeval) {
static jfieldID tvSecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_sec", "J");
static jfieldID tvUsecFid = env->GetFieldID(JniConstants::structTimevalClass, "tv_usec", "J");
int fd = jniGetFDFromFileDescriptor(env, javaFd);
struct timeval value;
value.tv_sec = env->GetLongField(javaTimeval, tvSecFid);
value.tv_usec = env->GetLongField(javaTimeval, tvUsecFid);
throwIfMinusOne(env, "setsockopt", TEMP_FAILURE_RETRY(setsockopt(fd, level, option, &value, sizeof(value))));
}
static void Posix_setuid(JNIEnv* env, jobject, jint uid) {
throwIfMinusOne(env, "setuid", TEMP_FAILURE_RETRY(setuid(uid)));
}
static void Posix_shutdown(JNIEnv* env, jobject, jobject javaFd, jint how) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "shutdown", TEMP_FAILURE_RETRY(shutdown(fd, how)));
}
static jobject Posix_socket(JNIEnv* env, jobject, jint domain, jint type, jint protocol) {
int fd = throwIfMinusOne(env, "socket", TEMP_FAILURE_RETRY(socket(domain, type, protocol)));
return fd != -1 ? jniCreateFileDescriptor(env, fd) : NULL;
}
static void Posix_socketpair(JNIEnv* env, jobject, jint domain, jint type, jint protocol, jobject javaFd1, jobject javaFd2) {
int fds[2];
int rc = throwIfMinusOne(env, "socketpair", TEMP_FAILURE_RETRY(socketpair(domain, type, protocol, fds)));
if (rc != -1) {
jniSetFileDescriptorOfFD(env, javaFd1, fds[0]);
jniSetFileDescriptorOfFD(env, javaFd2, fds[1]);
}
}
static jobject Posix_stat(JNIEnv* env, jobject, jstring javaPath) {
return doStat(env, javaPath, false);
}
static jobject Posix_statvfs(JNIEnv* env, jobject, jstring javaPath) {
ScopedUtfChars path(env, javaPath);
if (path.c_str() == NULL) {
return NULL;
}
struct statvfs sb;
int rc = TEMP_FAILURE_RETRY(statvfs(path.c_str(), &sb));
if (rc == -1) {
throwErrnoException(env, "statvfs");
return NULL;
}
return makeStructStatVfs(env, sb);
}
static jstring Posix_strerror(JNIEnv* env, jobject, jint errnum) {
char buffer[BUFSIZ];
const char* message = jniStrError(errnum, buffer, sizeof(buffer));
return env->NewStringUTF(message);
}
static jstring Posix_strsignal(JNIEnv* env, jobject, jint signal) {
return env->NewStringUTF(strsignal(signal));
}
static void Posix_symlink(JNIEnv* env, jobject, jstring javaOldPath, jstring javaNewPath) {
ScopedUtfChars oldPath(env, javaOldPath);
if (oldPath.c_str() == NULL) {
return;
}
ScopedUtfChars newPath(env, javaNewPath);
if (newPath.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "symlink", TEMP_FAILURE_RETRY(symlink(oldPath.c_str(), newPath.c_str())));
}
static jlong Posix_sysconf(JNIEnv* env, jobject, jint name) {
// Since -1 is a valid result from sysconf(3), detecting failure is a little more awkward.
errno = 0;
long result = sysconf(name);
if (result == -1L && errno == EINVAL) {
throwErrnoException(env, "sysconf");
}
return result;
}
static void Posix_tcdrain(JNIEnv* env, jobject, jobject javaFd) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "tcdrain", TEMP_FAILURE_RETRY(tcdrain(fd)));
}
static void Posix_tcsendbreak(JNIEnv* env, jobject, jobject javaFd, jint duration) {
int fd = jniGetFDFromFileDescriptor(env, javaFd);
throwIfMinusOne(env, "tcsendbreak", TEMP_FAILURE_RETRY(tcsendbreak(fd, duration)));
}
static jint Posix_umaskImpl(JNIEnv*, jobject, jint mask) {
return umask(mask);
}
static jobject Posix_uname(JNIEnv* env, jobject) {
struct utsname buf;
if (TEMP_FAILURE_RETRY(uname(&buf)) == -1) {
return NULL; // Can't happen.
}
return makeStructUtsname(env, buf);
}
static void Posix_unsetenv(JNIEnv* env, jobject, jstring javaName) {
ScopedUtfChars name(env, javaName);
if (name.c_str() == NULL) {
return;
}
throwIfMinusOne(env, "unsetenv", unsetenv(name.c_str()));
}
static jint Posix_waitpid(JNIEnv* env, jobject, jint pid, jobject javaStatus, jint options) {
int status;
int rc = throwIfMinusOne(env, "waitpid", TEMP_FAILURE_RETRY(waitpid(pid, &status, options)));
if (rc != -1) {
static jfieldID valueFid = env->GetFieldID(JniConstants::mutableIntClass, "value", "I");
env->SetIntField(javaStatus, valueFid, status);
}
return rc;
}
static jint Posix_writeBytes(JNIEnv* env, jobject, jobject javaFd, jbyteArray javaBytes, jint byteOffset, jint byteCount) {
ScopedBytesRO bytes(env, javaBytes);
if (bytes.get() == NULL) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, write, javaFd, bytes.get() + byteOffset, byteCount);
}
static jint Posix_writev(JNIEnv* env, jobject, jobject javaFd, jobjectArray buffers, jintArray offsets, jintArray byteCounts) {
IoVec<ScopedBytesRO> ioVec(env, env->GetArrayLength(buffers));
if (!ioVec.init(buffers, offsets, byteCounts)) {
return -1;
}
return IO_FAILURE_RETRY(env, ssize_t, writev, javaFd, ioVec.get(), ioVec.size());
}
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Posix, accept, "(Ljava/io/FileDescriptor;Ljava/net/InetSocketAddress;)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, access, "(Ljava/lang/String;I)Z"),
NATIVE_METHOD(Posix, android_getaddrinfo, "(Ljava/lang/String;Landroid/system/StructAddrinfo;I)[Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
NATIVE_METHOD(Posix, chmod, "(Ljava/lang/String;I)V"),
NATIVE_METHOD(Posix, chown, "(Ljava/lang/String;II)V"),
NATIVE_METHOD(Posix, close, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, connect, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"),
NATIVE_METHOD(Posix, dup, "(Ljava/io/FileDescriptor;)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, dup2, "(Ljava/io/FileDescriptor;I)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, environ, "()[Ljava/lang/String;"),
NATIVE_METHOD(Posix, execv, "(Ljava/lang/String;[Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, execve, "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, fchmod, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, fchown, "(Ljava/io/FileDescriptor;II)V"),
NATIVE_METHOD(Posix, fcntlVoid, "(Ljava/io/FileDescriptor;I)I"),
NATIVE_METHOD(Posix, fcntlLong, "(Ljava/io/FileDescriptor;IJ)I"),
NATIVE_METHOD(Posix, fcntlFlock, "(Ljava/io/FileDescriptor;ILandroid/system/StructFlock;)I"),
NATIVE_METHOD(Posix, fdatasync, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, fstat, "(Ljava/io/FileDescriptor;)Landroid/system/StructStat;"),
NATIVE_METHOD(Posix, fstatvfs, "(Ljava/io/FileDescriptor;)Landroid/system/StructStatVfs;"),
NATIVE_METHOD(Posix, fsync, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, ftruncate, "(Ljava/io/FileDescriptor;J)V"),
NATIVE_METHOD(Posix, gai_strerror, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, getegid, "()I"),
NATIVE_METHOD(Posix, geteuid, "()I"),
NATIVE_METHOD(Posix, getgid, "()I"),
NATIVE_METHOD(Posix, getenv, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(Posix, getnameinfo, "(Ljava/net/InetAddress;I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, getpeername, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
NATIVE_METHOD(Posix, getpid, "()I"),
NATIVE_METHOD(Posix, getppid, "()I"),
NATIVE_METHOD(Posix, getpwnam, "(Ljava/lang/String;)Landroid/system/StructPasswd;"),
NATIVE_METHOD(Posix, getpwuid, "(I)Landroid/system/StructPasswd;"),
NATIVE_METHOD(Posix, getsockname, "(Ljava/io/FileDescriptor;)Ljava/net/SocketAddress;"),
NATIVE_METHOD(Posix, getsockoptByte, "(Ljava/io/FileDescriptor;II)I"),
NATIVE_METHOD(Posix, getsockoptInAddr, "(Ljava/io/FileDescriptor;II)Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, getsockoptInt, "(Ljava/io/FileDescriptor;II)I"),
NATIVE_METHOD(Posix, getsockoptLinger, "(Ljava/io/FileDescriptor;II)Landroid/system/StructLinger;"),
NATIVE_METHOD(Posix, getsockoptTimeval, "(Ljava/io/FileDescriptor;II)Landroid/system/StructTimeval;"),
NATIVE_METHOD(Posix, getsockoptUcred, "(Ljava/io/FileDescriptor;II)Landroid/system/StructUcred;"),
NATIVE_METHOD(Posix, gettid, "()I"),
NATIVE_METHOD(Posix, getuid, "()I"),
NATIVE_METHOD(Posix, if_indextoname, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, inet_pton, "(ILjava/lang/String;)Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, ioctlInetAddress, "(Ljava/io/FileDescriptor;ILjava/lang/String;)Ljava/net/InetAddress;"),
NATIVE_METHOD(Posix, ioctlInt, "(Ljava/io/FileDescriptor;ILandroid/util/MutableInt;)I"),
NATIVE_METHOD(Posix, isatty, "(Ljava/io/FileDescriptor;)Z"),
NATIVE_METHOD(Posix, kill, "(II)V"),
NATIVE_METHOD(Posix, lchown, "(Ljava/lang/String;II)V"),
NATIVE_METHOD(Posix, link, "(Ljava/lang/String;Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, listen, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, lseek, "(Ljava/io/FileDescriptor;JI)J"),
NATIVE_METHOD(Posix, lstat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
NATIVE_METHOD(Posix, mincore, "(JJ[B)V"),
NATIVE_METHOD(Posix, mkdir, "(Ljava/lang/String;I)V"),
NATIVE_METHOD(Posix, mkfifo, "(Ljava/lang/String;I)V"),
NATIVE_METHOD(Posix, mlock, "(JJ)V"),
NATIVE_METHOD(Posix, mmap, "(JJIILjava/io/FileDescriptor;J)J"),
NATIVE_METHOD(Posix, msync, "(JJI)V"),
NATIVE_METHOD(Posix, munlock, "(JJ)V"),
NATIVE_METHOD(Posix, munmap, "(JJ)V"),
NATIVE_METHOD(Posix, open, "(Ljava/lang/String;II)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, pipe, "()[Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, poll, "([Landroid/system/StructPollfd;I)I"),
NATIVE_METHOD(Posix, posix_fallocate, "(Ljava/io/FileDescriptor;JJ)V"),
NATIVE_METHOD(Posix, prctl, "(IJJJJ)I"),
NATIVE_METHOD(Posix, preadBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, pwriteBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIJ)I"),
NATIVE_METHOD(Posix, readBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
NATIVE_METHOD(Posix, readlink, "(Ljava/lang/String;)Ljava/lang/String;"),
NATIVE_METHOD(Posix, readv, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
NATIVE_METHOD(Posix, recvfromBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetSocketAddress;)I"),
NATIVE_METHOD(Posix, remove, "(Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, rename, "(Ljava/lang/String;Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, sendfile, "(Ljava/io/FileDescriptor;Ljava/io/FileDescriptor;Landroid/util/MutableLong;J)J"),
NATIVE_METHOD(Posix, sendtoBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;IIILjava/net/InetAddress;I)I"),
NATIVE_METHOD(Posix, setegid, "(I)V"),
NATIVE_METHOD(Posix, setenv, "(Ljava/lang/String;Ljava/lang/String;Z)V"),
NATIVE_METHOD(Posix, seteuid, "(I)V"),
NATIVE_METHOD(Posix, setgid, "(I)V"),
NATIVE_METHOD(Posix, setsid, "()I"),
NATIVE_METHOD(Posix, setsockoptByte, "(Ljava/io/FileDescriptor;III)V"),
NATIVE_METHOD(Posix, setsockoptIfreq, "(Ljava/io/FileDescriptor;IILjava/lang/String;)V"),
NATIVE_METHOD(Posix, setsockoptInt, "(Ljava/io/FileDescriptor;III)V"),
NATIVE_METHOD(Posix, setsockoptIpMreqn, "(Ljava/io/FileDescriptor;III)V"),
NATIVE_METHOD(Posix, setsockoptGroupReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupReq;)V"),
NATIVE_METHOD(Posix, setsockoptGroupSourceReq, "(Ljava/io/FileDescriptor;IILandroid/system/StructGroupSourceReq;)V"),
NATIVE_METHOD(Posix, setsockoptLinger, "(Ljava/io/FileDescriptor;IILandroid/system/StructLinger;)V"),
NATIVE_METHOD(Posix, setsockoptTimeval, "(Ljava/io/FileDescriptor;IILandroid/system/StructTimeval;)V"),
NATIVE_METHOD(Posix, setuid, "(I)V"),
NATIVE_METHOD(Posix, shutdown, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, socket, "(III)Ljava/io/FileDescriptor;"),
NATIVE_METHOD(Posix, socketpair, "(IIILjava/io/FileDescriptor;Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, stat, "(Ljava/lang/String;)Landroid/system/StructStat;"),
NATIVE_METHOD(Posix, statvfs, "(Ljava/lang/String;)Landroid/system/StructStatVfs;"),
NATIVE_METHOD(Posix, strerror, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, strsignal, "(I)Ljava/lang/String;"),
NATIVE_METHOD(Posix, symlink, "(Ljava/lang/String;Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, sysconf, "(I)J"),
NATIVE_METHOD(Posix, tcdrain, "(Ljava/io/FileDescriptor;)V"),
NATIVE_METHOD(Posix, tcsendbreak, "(Ljava/io/FileDescriptor;I)V"),
NATIVE_METHOD(Posix, umaskImpl, "(I)I"),
NATIVE_METHOD(Posix, uname, "()Landroid/system/StructUtsname;"),
NATIVE_METHOD(Posix, unsetenv, "(Ljava/lang/String;)V"),
NATIVE_METHOD(Posix, waitpid, "(ILandroid/util/MutableInt;I)I"),
NATIVE_METHOD(Posix, writeBytes, "(Ljava/io/FileDescriptor;Ljava/lang/Object;II)I"),
NATIVE_METHOD(Posix, writev, "(Ljava/io/FileDescriptor;[Ljava/lang/Object;[I[I)I"),
};
void register_libcore_io_Posix(JNIEnv* env) {
jniRegisterNativeMethods(env, "libcore/io/Posix", gMethods, NELEM(gMethods));
}
| Java |
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package MJDecompiler;
import java.io.IOException;
// Referenced classes of package MJDecompiler:
// bm, bf, bh, bj,
// bc
final class as extends CpField
{
as(ClazzInputStream bc, ClassFile bj1)
throws IOException
{
super(bc, bj1);
}
final void writeBytecode(ByteCodeOutput bf1)
throws IOException
{
bf1.writeByte(9);
bf1.writeUshort(super.b);
bf1.writeUshort(super.o);
}
final String type()
{
return super.a.getConstant(super.o).type();
}
final String a(ClassFile bj1)
{
return "FieldRef(" + super.b + ":" + bj1.getConstant(super.b).a(bj1) + ", " + super.o + ":" + bj1.getConstant(super.o).a(bj1) + ")";
}
}
| Java |
package com.zalthrion.zylroth.handler;
import net.minecraft.client.settings.KeyBinding;
import org.lwjgl.input.Keyboard;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class KeyHandler {
@SideOnly(Side.CLIENT) public static KeyBinding openSummonGui;
public static void init() {
openSummonGui = new KeyBinding("key.zylroth:summongui", Keyboard.KEY_Z, "key.categories.zylroth");
ClientRegistry.registerKeyBinding(openSummonGui);
}
} | Java |
/*
* Copyright (c) 2014 Ian Bondoc
*
* This file is part of Jen8583
*
* Jen8583 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the License, or(at your option) any later version.
*
* Jen8583 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
package org.chiknrice.iso.codec;
import org.chiknrice.iso.config.ComponentDef.Encoding;
import java.nio.ByteBuffer;
/**
* The main contract for a codec used across encoding and decoding of message components. Each field/component of the
* ISO message would have its own instance of codec which contains the definition of how the value should be
* encoded/decoded. The codec should be designed to be thread safe as the instance would live throughout the life of the
* IsoMessageDef. Any issues encountered during encoding/decoding should be throwing a CodecException. Any issues
* encountered during codec configuration/construction the constructor should throw a ConfigException. A ConfigException
* should generally happen during startup while CodecException happens when the Codec is being used.
*
* @author <a href="mailto:chiknrice@gmail.com">Ian Bondoc</a>
*/
public interface Codec<T> {
/**
* The implementation should define how the value T should be decoded from the ByteBuffer provided. The
* implementation could either decode the value from a certain number of bytes or consume the whole ByteBuffer.
*
* @param buf
* @return the decoded value
*/
T decode(ByteBuffer buf);
/**
* The implementation should define how the value T should be encoded to the ByteBuffer provided. The ByteBuffer
* assumes the value would be encoded from the current position.
*
* @param buf
* @param value the value to be encoded
*/
void encode(ByteBuffer buf, T value);
/**
* Defines how the value should be encoded/decoded.
*
* @return the encoding defined for the value.
*/
Encoding getEncoding();
}
| Java |
#!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Miscellaneous network utility code."""
from __future__ import absolute_import, division, print_function, with_statement
import errno
import os
import re
import socket
import ssl
import stat
from lib.tornado.concurrent import dummy_executor, run_on_executor
from lib.tornado.ioloop import IOLoop
from lib.tornado.platform.auto import set_close_exec
from lib.tornado.util import Configurable
def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None):
"""Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if
the given address maps to multiple IP addresses, which is most common
for mixed IPv4 and IPv6 use).
Address may be either an IP address or hostname. If it's a hostname,
the server will listen on all IP addresses associated with the
name. Address may be an empty string or None to listen on all
available interfaces. Family may be set to either `socket.AF_INET`
or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
both will be used if available.
The ``backlog`` argument has the same meaning as for
`socket.listen() <socket.socket.listen>`.
``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
"""
sockets = []
if address == "":
address = None
if not socket.has_ipv6 and family == socket.AF_UNSPEC:
# Python can be compiled with --disable-ipv6, which causes
# operations on AF_INET6 sockets to fail, but does not
# automatically exclude those results from getaddrinfo
# results.
# http://bugs.python.org/issue16208
family = socket.AF_INET
if flags is None:
flags = socket.AI_PASSIVE
for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
0, flags)):
af, socktype, proto, canonname, sockaddr = res
sock = socket.socket(af, socktype, proto)
set_close_exec(sock.fileno())
if os.name != 'nt':
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if af == socket.AF_INET6:
# On linux, ipv6 sockets accept ipv4 too by default,
# but this makes it impossible to bind to both
# 0.0.0.0 in ipv4 and :: in ipv6. On other systems,
# separate sockets *must* be used to listen for both ipv4
# and ipv6. For consistency, always disable ipv4 on our
# ipv6 sockets and use a separate ipv4 socket when needed.
#
# Python 2.x on windows doesn't have IPPROTO_IPV6.
if hasattr(socket, "IPPROTO_IPV6"):
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
sock.setblocking(0)
sock.bind(sockaddr)
sock.listen(backlog)
sockets.append(sock)
return sockets
if hasattr(socket, 'AF_UNIX'):
def bind_unix_socket(file, mode=0o600, backlog=128):
"""Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted.
If any other file with that name exists, an exception will be
raised.
Returns a socket object (not a list of socket objects like
`bind_sockets`)
"""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
set_close_exec(sock.fileno())
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
try:
st = os.stat(file)
except OSError as err:
if err.errno != errno.ENOENT:
raise
else:
if stat.S_ISSOCK(st.st_mode):
os.remove(file)
else:
raise ValueError("File %s exists and is not a socket", file)
sock.bind(file)
os.chmod(file, mode)
sock.listen(backlog)
return sock
def add_accept_handler(sock, callback, io_loop=None):
"""Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the connection). Note that this signature
is different from the ``callback(fd, events)`` signature used for
`.IOLoop` handlers.
"""
if io_loop is None:
io_loop = IOLoop.current()
def accept_handler(fd, events):
while True:
try:
connection, address = sock.accept()
except socket.error as e:
if e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN):
return
raise
callback(connection, address)
io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ)
def is_valid_ip(ip):
"""Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6.
"""
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM,
0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if e.args[0] == socket.EAI_NONAME:
return False
raise
return True
class Resolver(Configurable):
"""Configurable asynchronous DNS resolver interface.
By default, a blocking implementation is used (which simply calls
`socket.getaddrinfo`). An alternative implementation can be
chosen with the `Resolver.configure <.Configurable.configure>`
class method::
Resolver.configure('tornado.netutil.ThreadedResolver')
The implementations of this interface included with Tornado are
* `tornado.netutil.BlockingResolver`
* `tornado.netutil.ThreadedResolver`
* `tornado.netutil.OverrideResolver`
* `tornado.platform.twisted.TwistedResolver`
* `tornado.platform.caresresolver.CaresResolver`
"""
@classmethod
def configurable_base(cls):
return Resolver
@classmethod
def configurable_default(cls):
return BlockingResolver
def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
"""Resolves an address.
The ``host`` argument is a string which may be a hostname or a
literal IP address.
Returns a `.Future` whose result is a list of (family,
address) pairs, where address is a tuple suitable to pass to
`socket.connect <socket.socket.connect>` (i.e. a ``(host,
port)`` pair for IPv4; additional fields may be present for
IPv6). If a ``callback`` is passed, it will be run with the
result as an argument when it is complete.
"""
raise NotImplementedError()
class ExecutorResolver(Resolver):
def initialize(self, io_loop=None, executor=None):
self.io_loop = io_loop or IOLoop.current()
self.executor = executor or dummy_executor
@run_on_executor
def resolve(self, host, port, family=socket.AF_UNSPEC):
addrinfo = socket.getaddrinfo(host, port, family)
results = []
for family, socktype, proto, canonname, address in addrinfo:
results.append((family, address))
return results
class BlockingResolver(ExecutorResolver):
"""Default `Resolver` implementation, using `socket.getaddrinfo`.
The `.IOLoop` will be blocked during the resolution, although the
callback will not be run until the next `.IOLoop` iteration.
"""
def initialize(self, io_loop=None):
super(BlockingResolver, self).initialize(io_loop=io_loop)
class ThreadedResolver(ExecutorResolver):
"""Multithreaded non-blocking `Resolver` implementation.
Requires the `concurrent.futures` package to be installed
(available in the standard library since Python 3.2,
installable with ``pip install futures`` in older versions).
The thread pool size can be configured with::
Resolver.configure('tornado.netutil.ThreadedResolver',
num_threads=10)
"""
def initialize(self, io_loop=None, num_threads=10):
from concurrent.futures import ThreadPoolExecutor
super(ThreadedResolver, self).initialize(
io_loop=io_loop, executor=ThreadPoolExecutor(num_threads))
class OverrideResolver(Resolver):
"""Wraps a resolver with a mapping of overrides.
This can be used to make local DNS changes (e.g. for testing)
without modifying system-wide settings.
The mapping can contain either host strings or host-port pairs.
"""
def initialize(self, resolver, mapping):
self.resolver = resolver
self.mapping = mapping
def resolve(self, host, port, *args, **kwargs):
if (host, port) in self.mapping:
host, port = self.mapping[(host, port)]
elif host in self.mapping:
host = self.mapping[host]
return self.resolver.resolve(host, port, *args, **kwargs)
# These are the keyword arguments to ssl.wrap_socket that must be translated
# to their SSLContext equivalents (the other arguments are still passed
# to SSLContext.wrap_socket).
_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',
'cert_reqs', 'ca_certs', 'ciphers'])
def ssl_options_to_context(ssl_options):
"""Try to convert an ``ssl_options`` dictionary to an
`~ssl.SSLContext` object.
The ``ssl_options`` dictionary contains keywords to be passed to
`ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can
be used instead. This function converts the dict form to its
`~ssl.SSLContext` equivalent, and may be used when a component which
accepts both forms needs to upgrade to the `~ssl.SSLContext` version
to use features like SNI or NPN.
"""
if isinstance(ssl_options, dict):
assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
if (not hasattr(ssl, 'SSLContext') or
isinstance(ssl_options, ssl.SSLContext)):
return ssl_options
context = ssl.SSLContext(
ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))
if 'certfile' in ssl_options:
context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))
if 'cert_reqs' in ssl_options:
context.verify_mode = ssl_options['cert_reqs']
if 'ca_certs' in ssl_options:
context.load_verify_locations(ssl_options['ca_certs'])
if 'ciphers' in ssl_options:
context.set_ciphers(ssl_options['ciphers'])
return context
def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
"""Returns an ``ssl.SSLSocket`` wrapping the given socket.
``ssl_options`` may be either a dictionary (as accepted by
`ssl_options_to_context`) or an `ssl.SSLContext` object.
Additional keyword arguments are passed to ``wrap_socket``
(either the `~ssl.SSLContext` method or the `ssl` module function
as appropriate).
"""
context = ssl_options_to_context(ssl_options)
if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext):
if server_hostname is not None and getattr(ssl, 'HAS_SNI'):
# Python doesn't have server-side SNI support so we can't
# really unittest this, but it can be manually tested with
# python3.2 -m tornado.httpclient https://sni.velox.ch
return context.wrap_socket(socket, server_hostname=server_hostname,
**kwargs)
else:
return context.wrap_socket(socket, **kwargs)
else:
return ssl.wrap_socket(socket, **dict(context, **kwargs))
if hasattr(ssl, 'match_hostname'): # python 3.2+
ssl_match_hostname = ssl.match_hostname
SSLCertificateError = ssl.CertificateError
else:
# match_hostname was added to the standard library ssl module in python 3.2.
# The following code was backported for older releases and copied from
# https://bitbucket.org/brandon/backports.ssl_match_hostname
class SSLCertificateError(ValueError):
pass
def _dnsname_to_pat(dn):
pats = []
for frag in dn.split(r'.'):
if frag == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append('[^.]+')
else:
# Otherwise, '*' matches any dotless fragment.
frag = re.escape(frag)
pats.append(frag.replace(r'\*', '[^.]*'))
return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
def ssl_match_hostname(cert, hostname):
"""Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
are mostly followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
returns nothing.
"""
if not cert:
raise ValueError("empty or no certificate")
dnsnames = []
san = cert.get('subjectAltName', ())
for key, value in san:
if key == 'DNS':
if _dnsname_to_pat(value).match(hostname):
return
dnsnames.append(value)
if not san:
# The subject is only checked when subjectAltName is empty
for sub in cert.get('subject', ()):
for key, value in sub:
# XXX according to RFC 2818, the most specific Common Name
# must be used.
if key == 'commonName':
if _dnsname_to_pat(value).match(hostname):
return
dnsnames.append(value)
if len(dnsnames) > 1:
raise SSLCertificateError("hostname %r "
"doesn't match either of %s"
% (hostname, ', '.join(map(repr, dnsnames))))
elif len(dnsnames) == 1:
raise SSLCertificateError("hostname %r "
"doesn't match %r"
% (hostname, dnsnames[0]))
else:
raise SSLCertificateError("no appropriate commonName or "
"subjectAltName fields were found")
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MiniQuick.Events
{
public class BaseEvent : IEvent
{
private int _MaxRetryCount = 3;
private TimeSpan _timeinterval = TimeSpan.FromMilliseconds(1000);
public string CommandId
{
get;
set;
}
public int RetryCount
{
get { return this._MaxRetryCount; }
}
public TimeSpan Timeinterval
{
get { return this._timeinterval; }
}
}
}
| Java |
/************************************************************************
Copyright 2008 Mark Pictor
This file is part of RS274NGC.
RS274NGC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RS274NGC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RS274NGC. If not, see <http://www.gnu.org/licenses/>.
This software is based on software that was produced by the National
Institute of Standards and Technology (NIST).
************************************************************************/
#include "stdafx.h"
extern CANON_TOOL_TABLE _tools[]; /* in canon.cc */
extern int _tool_max; /* in canon.cc */
extern char _parameter_file_name[100]; /* in canon.cc */
FILE * _outfile; /* where to print, set in main */
/*
This file contains the source code for an emulation of using the six-axis
rs274 interpreter from the EMC system.
*/
/*********************************************************************/
/* report_error
Returned Value: none
Side effects: an error message is printed on stderr
Called by:
interpret_from_file
interpret_from_keyboard
main
This
1. calls rs274ngc_error_text to get the text of the error message whose
code is error_code and prints the message,
2. calls rs274ngc_line_text to get the text of the line on which the
error occurred and prints the text, and
3. if print_stack is on, repeatedly calls rs274ngc_stack_name to get
the names of the functions on the function call stack and prints the
names. The first function named is the one that sent the error
message.
*/
void report_error( /* ARGUMENTS */
int error_code, /* the code number of the error message */
int print_stack) /* print stack if ON, otherwise not */
{
char buffer[RS274NGC_TEXT_SIZE];
int k;
rs274ngc_error_text(error_code, buffer, sizeof(buffer), 5); /* for coverage of code */
rs274ngc_error_text(error_code, buffer, sizeof(buffer), RS274NGC_TEXT_SIZE);
fprintf(stderr, "%s\n",
((buffer[0] IS 0) ? "Unknown error, bad error code" : buffer));
rs274ngc_line_text(buffer, RS274NGC_TEXT_SIZE);
fprintf(stderr, "%s\n", buffer);
if (print_stack IS ON)
{
for (k SET_TO 0; ; k++)
{
rs274ngc_stack_name(k, buffer, RS274NGC_TEXT_SIZE);
if (buffer[0] ISNT 0)
fprintf(stderr, "%s\n", buffer);
else
break;
}
}
}
/***********************************************************************/
/* interpret_from_keyboard
Returned Value: int (0)
Side effects:
Lines of NC code entered by the user are interpreted.
Called by:
interpret_from_file
main
This prompts the user to enter a line of rs274 code. When the user
hits <enter> at the end of the line, the line is executed.
Then the user is prompted to enter another line.
Any canonical commands resulting from executing the line are printed
on the monitor (stdout). If there is an error in reading or executing
the line, an error message is printed on the monitor (stderr).
To exit, the user must enter "quit" (followed by a carriage return).
*/
int interpret_from_keyboard( /* ARGUMENTS */
int block_delete, /* switch which is ON or OFF */
int print_stack) /* option which is ON or OFF */
{
char line[RS274NGC_TEXT_SIZE];
int status;
for(; ;)
{
printf("READ => ");
fgets(line, sizeof(line), stdin);
if (strcmp (line, "quit") IS 0)
return 0;
status SET_TO rs274ngc_read(line);
if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON));
else if (status IS RS274NGC_ENDFILE);
else if ((status ISNT RS274NGC_EXECUTE_FINISH) AND
(status ISNT RS274NGC_OK))
report_error(status, print_stack);
else
{
status SET_TO rs274ngc_execute();
if ((status IS RS274NGC_EXIT) OR
(status IS RS274NGC_EXECUTE_FINISH));
else if (status ISNT RS274NGC_OK)
report_error(status, print_stack);
}
}
}
/*********************************************************************/
/* interpret_from_file
Returned Value: int (0 or 1)
If any of the following errors occur, this returns 1.
Otherwise, it returns 0.
1. rs274ngc_read returns something other than RS274NGC_OK or
RS274NGC_EXECUTE_FINISH, no_stop is off, and the user elects
not to continue.
2. rs274ngc_execute returns something other than RS274NGC_OK,
EXIT, or RS274NGC_EXECUTE_FINISH, no_stop is off, and the user
elects not to continue.
Side Effects:
An open NC-program file is interpreted.
Called By:
main
This emulates the way the EMC system uses the interpreter.
If the do_next argument is 1, this goes into MDI mode if an error is
found. In that mode, the user may (1) enter code or (2) enter "quit" to
get out of MDI. Once out of MDI, this asks the user whether to continue
interpreting the file.
If the do_next argument is 0, an error does not stop interpretation.
If the do_next argument is 2, an error stops interpretation.
*/
int interpret_from_file( /* ARGUMENTS */
int do_next, /* what to do if error */
int block_delete, /* switch which is ON or OFF */
int print_stack) /* option which is ON or OFF */
{
int status;
char line[RS274NGC_TEXT_SIZE];
for(; ;)
{
status SET_TO rs274ngc_read(NULL);
if ((status IS RS274NGC_EXECUTE_FINISH) AND (block_delete IS ON))
continue;
else if (status IS RS274NGC_ENDFILE)
break;
if ((status ISNT RS274NGC_OK) AND // should not be EXIT
(status ISNT RS274NGC_EXECUTE_FINISH))
{
report_error(status, print_stack);
if ((status IS NCE_FILE_ENDED_WITH_NO_PERCENT_SIGN) OR
(do_next IS 2)) /* 2 means stop */
{
status SET_TO 1;
break;
}
else if (do_next IS 1) /* 1 means MDI */
{
fprintf(stderr, "starting MDI\n");
interpret_from_keyboard(block_delete, print_stack);
fprintf(stderr, "continue program? y/n =>");
fgets(line, sizeof(line), stdin);
if (line[0] ISNT 'y')
{
status SET_TO 1;
break;
}
else
continue;
}
else /* if do_next IS 0 -- 0 means continue */
continue;
}
status SET_TO rs274ngc_execute();
if ((status ISNT RS274NGC_OK) AND
(status ISNT RS274NGC_EXIT) AND
(status ISNT RS274NGC_EXECUTE_FINISH))
{
report_error(status, print_stack);
status SET_TO 1;
if (do_next IS 1) /* 1 means MDI */
{
fprintf(stderr, "starting MDI\n");
interpret_from_keyboard(block_delete, print_stack);
fprintf(stderr, "continue program? y/n =>");
fgets(line,sizeof(line), stdin);
if (line[0] ISNT 'y')
break;
}
else if (do_next IS 2) /* 2 means stop */
break;
}
else if (status IS RS274NGC_EXIT)
break;
}
return ((status IS 1) ? 1 : 0);
}
/************************************************************************/
/* read_tool_file
Returned Value: int
If any of the following errors occur, this returns 1.
Otherwise, it returns 0.
1. The file named by the user cannot be opened.
2. No blank line is found.
3. A line of data cannot be read.
4. A tool slot number is less than 1 or >= _tool_max
Side Effects:
Values in the tool table of the machine setup are changed,
as specified in the file.
Called By: main
Tool File Format
-----------------
Everything above the first blank line is read and ignored, so any sort
of header material may be used.
Everything after the first blank line should be data. Each line of
data should have four or more items separated by white space. The four
required items are slot, tool id, tool length offset, and tool diameter.
Other items might be the holder id and tool description, but these are
optional and will not be read. Here is a sample line:
20 1419 4.299 1.0 1 inch carbide end mill
The tool_table is indexed by slot number.
*/
int read_tool_file( /* ARGUMENTS */
char * file_name) /* name of tool file */
{
FILE * tool_file_port;
char buffer[1000];
int slot;
int tool_id;
double offset;
double diameter;
if (file_name[0] IS 0) /* ask for name if given name is empty string */
{
fprintf(stderr, "name of tool file => ");
fgets(buffer, sizeof(buffer), stdin);
fopen_s(&tool_file_port,buffer, "r");
}
else
fopen_s(&tool_file_port,file_name, "r");
if (tool_file_port IS NULL)
{
fprintf(stderr, "Cannot open %s\n",
((file_name[0] IS 0) ? buffer : file_name));
return 1;
}
for(;;) /* read and discard header, checking for blank line */
{
if (fgets(buffer, 1000, tool_file_port) IS NULL)
{
fprintf(stderr, "Bad tool file format\n");
return 1;
}
else if (buffer[0] IS '\n')
break;
}
for (slot SET_TO 0; slot <= _tool_max; slot++)/* initialize */
{
_tools[slot].id SET_TO -1;
_tools[slot].length SET_TO 0;
_tools[slot].diameter SET_TO 0;
}
for (; (fgets(buffer, 1000, tool_file_port) ISNT NULL); )
{
if (sscanf_s(buffer, "%d %d %lf %lf", &slot,
&tool_id, &offset, &diameter) < 4)
{
fprintf(stderr, "Bad input line \"%s\" in tool file\n", buffer);
return 1;
}
if ((slot < 0) OR (slot > _tool_max)) /* zero and max both OK */
{
fprintf(stderr, "Out of range tool slot number %d\n", slot);
return 1;
}
_tools[slot].id SET_TO tool_id;
_tools[slot].length SET_TO offset;
_tools[slot].diameter SET_TO diameter;
}
fclose(tool_file_port);
return 0;
}
/************************************************************************/
/* designate_parameter_file
Returned Value: int
If any of the following errors occur, this returns 1.
Otherwise, it returns 0.
1. The file named by the user cannot be opened.
Side Effects:
The name of a parameter file given by the user is put in the
file_name string.
Called By: main
*/
int designate_parameter_file(char * file_name, size_t length)
{
FILE * test_port;
unsigned int ilength;
ilength = (int)length;
fprintf(stderr, "name of parameter file => ");
fgets(file_name, ilength, stdin);
fopen_s(&test_port,file_name, "r");
if (test_port IS NULL)
{
fprintf(stderr, "Cannot open %s\n", file_name);
return 1;
}
fclose(test_port);
return 0;
}
/************************************************************************/
/* adjust_error_handling
Returned Value: int (0)
Side Effects:
The values of print_stack and do_next are set.
Called By: main
This function allows the user to set one or two aspects of error handling.
By default the driver does not print the function stack in case of error.
This function always allows the user to turn stack printing on if it is off
or to turn stack printing off if it is on.
When interpreting from the keyboard, the driver always goes ahead if there
is an error.
When interpreting from a file, the default behavior is to stop in case of
an error. If the user is interpreting from a file (indicated by args being
2 or 3), this lets the user change what it does on an error.
If the user has not asked for output to a file (indicated by args being 2),
the user can choose any of three behaviors in case of an error (1) continue,
(2) stop, (3) go into MDI mode. This function allows the user to cycle among
the three.
If the user has asked for output to a file (indicated by args being 3),
the user can choose any of two behaviors in case of an error (1) continue,
(2) stop. This function allows the user to toggle between the two.
*/
int adjust_error_handling(
int args,
int * print_stack,
int * do_next)
{
char buffer[80];
int choice;
for(;;)
{
fprintf(stderr, "enter a number:\n");
fprintf(stderr, "1 = done with error handling\n");
fprintf(stderr, "2 = %sprint stack on error\n",
((*print_stack IS ON) ? "do not " : ""));
if (args IS 3)
{
if (*do_next IS 0) /* 0 means continue */
fprintf(stderr,
"3 = stop on error (do not continue)\n");
else /* if do_next IS 2 -- 2 means stopping on error */
fprintf(stderr,
"3 = continue on error (do not stop)\n");
}
else if (args IS 2)
{
if (*do_next IS 0) /* 0 means continue */
fprintf(stderr,
"3 = mdi on error (do not continue or stop)\n");
else if (*do_next IS 1) /* 1 means MDI */
fprintf(stderr,
"3 = stop on error (do not mdi or continue)\n");
else /* if do_next IS 2 -- 2 means stopping on error */
fprintf(stderr,
"3 = continue on error (do not stop or mdi)\n");
}
fprintf(stderr, "enter choice => ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf_s(buffer, "%d", &choice) ISNT 1)
continue;
if (choice IS 1)
break;
else if (choice IS 2)
*print_stack SET_TO ((*print_stack IS OFF) ? ON : OFF);
else if ((choice IS 3) AND (args IS 3))
*do_next SET_TO ((*do_next IS 0) ? 2 : 0);
else if ((choice IS 3) AND (args IS 2))
*do_next SET_TO ((*do_next IS 2) ? 0 : (*do_next + 1));
}
return 0;
}
/************************************************************************/
/* main
The executable exits with either 0 (under all conditions not listed
below) or 1 (under the following conditions):
1. A fatal error occurs while interpreting from a file.
2. Read_tool_file fails.
3. An error occurs in rs274ngc_init.
***********************************************************************
Here are three ways in which the rs274abc executable may be called.
Any other sort of call to the executable will cause an error message
to be printed and the interpreter will not run. Other executables
may be called similarly.
1. If the rs274abc stand-alone executable is called with no arguments,
input is taken from the keyboard, and an error in the input does not
cause the rs274abc executable to exit.
EXAMPLE:
1A. To interpret from the keyboard, enter:
rs274abc
***********************************************************************
2. If the executable is called with one argument, the argument is
taken to be the name of an NC file and the file is interpreted as
described in the documentation of interpret_from_file.
EXAMPLES:
2A. To interpret the file "cds.abc" and read the results on the
screen, enter:
rs274abc cds.abc
2B. To interpret the file "cds.abc" and print the results in the file
"cds.prim", enter:
rs274abc cds.abc > cds.prim
***********************************************************************
Whichever way the executable is called, this gives the user several
choices before interpretation starts
1 = start interpreting
2 = choose parameter file
3 = read tool file ...
4 = turn block delete switch ON
5 = adjust error handling...
Interpretation starts when option 1 is chosen. Until that happens, the
user is repeatedly given the five choices listed above. Item 4
toggles between "turn block delete switch ON" and "turn block delete
switch OFF". See documentation of adjust_error_handling regarding
what option 5 does.
User instructions are printed to stderr (with fprintf) so that output
can be redirected to a file. When output is redirected and user
instructions are printed to stdout (with printf), the instructions get
redirected and the user does not see them.
*/
int main (int argc, char ** argv)
{
int status;
int choice;
int do_next; /* 0=continue, 1=mdi, 2=stop */
int block_delete;
char buffer[80];
int tool_flag;
int gees[RS274NGC_ACTIVE_G_CODES];
int ems[RS274NGC_ACTIVE_M_CODES];
double sets[RS274NGC_ACTIVE_SETTINGS];
char default_name[] SET_TO "rs274ngc.var";
int print_stack;
if (argc > 3)
{
fprintf(stderr, "Usage \"%s\"\n", argv[0]);
fprintf(stderr, " or \"%s <input file>\"\n", argv[0]);
fprintf(stderr, " or \"%s <input file> <output file>\"\n", argv[0]);
exit(1);
}
do_next SET_TO 2; /* 2=stop */
block_delete SET_TO OFF;
print_stack SET_TO OFF;
tool_flag SET_TO 0;
strcpy_s(_parameter_file_name, sizeof(_parameter_file_name), default_name);
_outfile SET_TO stdout; /* may be reset below */
for(; ;)
{
fprintf(stderr, "enter a number:\n");
fprintf(stderr, "1 = start interpreting\n");
fprintf(stderr, "2 = choose parameter file ...\n");
fprintf(stderr, "3 = read tool file ...\n");
fprintf(stderr, "4 = turn block delete switch %s\n",
((block_delete IS OFF) ? "ON" : "OFF"));
fprintf(stderr, "5 = adjust error handling...\n");
fprintf(stderr, "enter choice => ");
fgets(buffer, sizeof(buffer), stdin);
if (sscanf_s(buffer,"%d", &choice) ISNT 1)
continue;
if (choice IS 1)
break;
else if (choice IS 2)
{
if (designate_parameter_file(_parameter_file_name,sizeof(_parameter_file_name)) ISNT 0)
exit(1);
}
else if (choice IS 3)
{
if (read_tool_file("") ISNT 0)
exit(1);
tool_flag SET_TO 1;
}
else if (choice IS 4)
block_delete SET_TO ((block_delete IS OFF) ? ON : OFF);
else if (choice IS 5)
adjust_error_handling(argc, &print_stack, &do_next);
}
fprintf(stderr, "executing\n");
if (tool_flag IS 0)
{
if (read_tool_file("rs274ngc.tool_default") ISNT 0)
exit(1);
}
if (argc IS 3)
{
fopen_s(&_outfile ,argv[2], "w");
if (_outfile IS NULL)
{
fprintf(stderr, "could not open output file %s\n", argv[2]);
exit(1);
}
}
if ((status SET_TO rs274ngc_init()) ISNT RS274NGC_OK)
{
report_error(status, print_stack);
exit(1);
}
if (argc IS 1)
status SET_TO interpret_from_keyboard(block_delete, print_stack);
else /* if (argc IS 2 or argc IS 3) */
{
status SET_TO rs274ngc_open(argv[1]);
if (status ISNT RS274NGC_OK) /* do not need to close since not open */
{
report_error(status, print_stack);
exit(1);
}
status SET_TO interpret_from_file(do_next, block_delete, print_stack);
rs274ngc_file_name(buffer, 5); /* called to exercise the function */
rs274ngc_file_name(buffer, 79); /* called to exercise the function */
rs274ngc_close();
}
rs274ngc_line_length(); /* called to exercise the function */
rs274ngc_sequence_number(); /* called to exercise the function */
rs274ngc_active_g_codes(gees); /* called to exercise the function */
rs274ngc_active_m_codes(ems); /* called to exercise the function */
rs274ngc_active_settings(sets); /* called to exercise the function */
rs274ngc_exit(); /* saves parameters */
exit(status);
}
/***********************************************************************/
| Java |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head prefix="og: http://ogp.me/ns# dc: http://purl.org/dc/terms/">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="//oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<title>Fan page: B. Stanis</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<style type="text/css">
#top{
width: 100%;
float: left;
}
#place{
width: 100%;
float: left;
}
#address{
width: 15%;
float: left;
}
#sgvzl{
width: 80%;
float: left;
}
#credits{
width: 100%;
float: left;
clear: both;
}
#location-marker{
width: 1em;
}
#male-glyph{
width: 1em;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" id="sgvzlr_script" src="http://mgskjaeveland.github.io/sgvizler/v/0.6/sgvizler.min.js"></script>
<script type="text/javascript">
sgvizler
.defaultEndpointURL("http://bibfram.es/fuseki/cobra/query");
//// Leave this as is. Ready, steady, go!
$(document).ready(sgvizler.containerDrawAll);
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<meta name="title" content="B. Stanis">
<meta property="dc:title" content="B. Stanis">
<meta property="og:title" content="B. Stanis">
<meta name="author" content="B. Stanis">
<meta name="dc:creator" content="B. Stanis">
</head>
<body prefix="cbo: http://comicmeta.org/cbo/ dc: http://purl.org/dc/elements/1.1/ dcterms: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/ oa: http://www.w3.org/ns/oa# rdf: http://www.w3.org/1999/02/22-rdf-syntax-ns# schema: http://schema.org/ skos: http://www.w3.org/2004/02/skos/core# xsd: http://www.w3.org/2001/XMLSchema#">
<div id="wrapper" class="container" about="http://ivmooc-cobra2.github.io/resources/fan/1403" typeof="http://comicmeta.org/cbo/Fan">
<div id="top">
<h1>
<span property="http://schema.org/name">B. Stanis</span>
</h1>
<dl>
<dt>
<label for="http://comicmeta.org/cbo/Fan">
<span>type</span>
</label>
</dt>
<dd>
<span>http://comicmeta.org/cbo/Fan</span>
</dd>
</dl>
<dl>
<dt>
<label for="http://schema.org/name">
<span>
<a href="http://schema.org/name">name</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/name">B. Stanis</span>
</dd>
</dl>
</div>
<div id="place" rel="http://schema.org/address" resource="http://ivmooc-cobra2.github.io/resources/place/1341" typeof="http://schema.org/Place">
<h2>Location <a href="http://ivmooc-cobra2.github.io/resources/place/1341">
<img id="location-marker" src="/static/resources/img/location.svg" alt="location marker glyph">
</a>
</h2>
<div id="address" rel="http://schema.org/address" typeof="http://schema.org/PostalAddress" resource="http://ivmooc-cobra2.github.io/resources/place/1341/address">
<dl>
<dt>
<label for="http://schema.org/streetAddress">
<span>
<a href="http://schema.org/streetAddress">Street address</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/streetAddress">NULL</span>
</dd>
</dl>
<dl>
<dt>
<label for="http://schema.org/addressLocality">
<span>
<a href="http://schema.org/addressLocality">Address locality</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/addressLocality">Waterbury</span>
</dd>
</dl>
<dl>
<dt>
<label for="http://schema.org/addressRegion">
<span>
<a href="http://schema.org/addressRegion">Address region</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/addressRegion">CT</span>
</dd>
</dl>
<dl>
<dt>
<label for="http://schema.org/postalCode">
<span>
<a href="http://schema.org/postalCode">Postal code</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/postalCode">NULL</span>
</dd>
</dl>
<dl>
<dt>
<label for="http://schema.org/addressCountry">
<span>
<a href="http://schema.org/addressCountry">Address country</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/addressCountry">US</span>
</dd>
</dl>
</div>
<div id="sgvzl" data-sgvizler-endpoint="http://bibfram.es/fuseki/cobra/query" data-sgvizler-query="PREFIX dc: <http://purl.org/dc/elements/1.1/> 
PREFIX cbo: <http://comicmeta.org/cbo/> 
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX schema: <http://schema.org/>
SELECT ?lat ?long 
WHERE {
 ?fan schema:address ?Place .
 ?Place schema:geo ?Geo .
 ?Geo schema:latitude ?lat .
 ?Geo schema:longitude ?long .
 FILTER(?fan = <http://ivmooc-cobra2.github.io/resources/fan/1403>)
}" data-sgvizler-chart="google.visualization.GeoChart" data-sgvizler-loglevel="2" style="width:800px; height:400px;"></div>
</div>
<div id="letter" rel="http://purl.org/dc/elements/1.1/creator" resource="http://ivmooc-cobra2.github.io/resources/letter/1515">
<dl>
<dt>
<label for="http://schema.org/streetAddress">
<span>
<a href="http://schema.org/streetAddress">Street address</a>
</span>
</label>
</dt>
<dd>
<span property="http://schema.org/streetAddress">NULL</span>
</dd>
</dl>
</div>
<div id="credits">Icons made by <a href="http://www.flaticon.com/authors/simpleicon" title="SimpleIcon">SimpleIcon</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>
</div>
</div>
</body>
</html> | Java |
#!/bin/sh
STAGING_DIR=$PWD/9ML-toolkit.d
mkdir -p $STAGING_DIR
mkdir -p $STAGING_DIR/bin
${CHICKEN_HOME}/bin/chicken-install -init $STAGING_DIR
rm $STAGING_DIR/setup-download.* $STAGING_DIR/tcp.* $STAGING_DIR/srfi-18.*
$CHICKEN_HOME/bin/chicken-install -deploy -prefix $STAGING_DIR \
datatype typeclass regex make bind vector-lib iset rb-tree easyffi flsim format-graph getopt-long input-parse lalr matchable mathh miniML static-modules \
numbers object-graph random-mtzig dyn-vector signal-diagram silex sxml-transforms ssax sxpath defstruct uri-generic utf8 ersatz
$CHICKEN_HOME/bin/chicken-install -deploy -prefix $STAGING_DIR 9ML-toolkit
mv $STAGING_DIR/bin/9ML-network/9ML-network $STAGING_DIR
mv $STAGING_DIR/bin/9ML-ivp/9ML-ivp $STAGING_DIR
rm -rf $STAGING_DIR/bin
| Java |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using Redzen.Numerics;
using SharpNeat.Utility;
namespace SharpNeat.Network
{
/// <summary>
/// Gaussian activation function. Output range is 0 to 1, that is, the tails of the gaussian
/// distribution curve tend towards 0 as abs(x) -> Infinity and the gaussian's peak is at x = 0.
/// </summary>
public class RbfGaussian : IActivationFunction
{
/// <summary>
/// Default instance provided as a public static field.
/// </summary>
public static readonly IActivationFunction __DefaultInstance = new RbfGaussian(0.1, 0.1);
double _auxArgsMutationSigmaCenter;
double _auxArgsMutationSigmaRadius;
#region Constructor
/// <summary>
/// Construct with the specified radial basis function auxiliary arguments.
/// </summary>
/// <param name="auxArgsMutationSigmaCenter">Radial basis function center.</param>
/// <param name="auxArgsMutationSigmaRadius">Radial basis function radius.</param>
public RbfGaussian(double auxArgsMutationSigmaCenter, double auxArgsMutationSigmaRadius)
{
_auxArgsMutationSigmaCenter = auxArgsMutationSigmaCenter;
_auxArgsMutationSigmaRadius = auxArgsMutationSigmaRadius;
}
#endregion
/// <summary>
/// Gets the unique ID of the function. Stored in network XML to identify which function a network or neuron
/// is using.
/// </summary>
public string FunctionId
{
get { return this.GetType().Name; }
}
/// <summary>
/// Gets a human readable string representation of the function. E.g 'y=1/x'.
/// </summary>
public string FunctionString
{
get { return "y = e^(-((x-center)*epsilon)^2)"; }
}
/// <summary>
/// Gets a human readable verbose description of the activation function.
/// </summary>
public string FunctionDescription
{
get { return "Gaussian.\r\nEffective yrange->[0,1]"; }
}
/// <summary>
/// Gets a flag that indicates if the activation function accepts auxiliary arguments.
/// </summary>
public bool AcceptsAuxArgs
{
get { return true; }
}
/// <summary>
/// Calculates the output value for the specified input value and activation function auxiliary arguments.
/// </summary>
public double Calculate(double x, double[] auxArgs)
{
// auxArgs[0] - RBF center.
// auxArgs[1] - RBF gaussian epsilon.
double d = (x-auxArgs[0]) * Math.Sqrt(auxArgs[1]) * 4.0;
return Math.Exp(-(d*d));
}
/// <summary>
/// Calculates the output value for the specified input value and activation function auxiliary arguments.
/// This single precision overload of Calculate() will be used in neural network code
/// that has been specifically written to use floats instead of doubles.
/// </summary>
public float Calculate(float x, float[] auxArgs)
{
// auxArgs[0] - RBF center.
// auxArgs[1] - RBF gaussian epsilon.
float d = (x-auxArgs[0]) * (float)Math.Sqrt(auxArgs[1]) * 4f;
return (float)Math.Exp(-(d*d));
}
/// <summary>
/// For activation functions that accept auxiliary arguments; generates random initial values for aux arguments for newly
/// added nodes (from an 'add neuron' mutation).
/// </summary>
public double[] GetRandomAuxArgs(XorShiftRandom rng, double connectionWeightRange)
{
double[] auxArgs = new double[2];
auxArgs[0] = (rng.NextDouble()-0.5) * 2.0;
auxArgs[1] = rng.NextDouble();
return auxArgs;
}
/// <summary>
/// Genetic mutation for auxiliary argument data.
/// </summary>
public void MutateAuxArgs(double[] auxArgs, XorShiftRandom rng, ZigguratGaussianSampler gaussianSampler, double connectionWeightRange)
{
// Mutate center.
// Add gaussian ditribution sample and clamp result to +-connectionWeightRange.
double tmp = auxArgs[0] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaCenter);
if(tmp < -connectionWeightRange) {
auxArgs[0] = -connectionWeightRange;
}
else if(tmp > connectionWeightRange) {
auxArgs[0] = connectionWeightRange;
}
else {
auxArgs[0] = tmp;
}
// Mutate radius.
// Add gaussian ditribution sample and clamp result to [0,1]
tmp = auxArgs[1] + gaussianSampler.NextSample(0, _auxArgsMutationSigmaRadius);
if(tmp < 0.0) {
auxArgs[1] = 0.0;
}
else if(tmp > 1.0) {
auxArgs[1] = 1.0;
}
else {
auxArgs[1] = tmp;
}
}
}
}
| Java |
'use strict';
/*global require, after, before*/
var async = require('async'),
assert = require('assert'),
db = require('../mocks/databasemock');
describe('Set methods', function() {
describe('setAdd()', function() {
it('should add to a set', function(done) {
db.setAdd('testSet1', 5, function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
it('should add an array to a set', function(done) {
db.setAdd('testSet1', [1, 2, 3, 4], function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
});
describe('getSetMembers()', function() {
before(function(done) {
db.setAdd('testSet2', [1,2,3,4,5], done);
});
it('should return an empty set', function(done) {
db.getSetMembers('doesnotexist', function(err, set) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(set), true);
assert.equal(set.length, 0);
done();
});
});
it('should return a set with all elements', function(done) {
db.getSetMembers('testSet2', function(err, set) {
assert.equal(err, null);
assert.equal(set.length, 5);
set.forEach(function(value) {
assert.notEqual(['1', '2', '3', '4', '5'].indexOf(value), -1);
});
done();
});
});
});
describe('setsAdd()', function() {
it('should add to multiple sets', function(done) {
db.setsAdd(['set1', 'set2'], 'value', function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
done();
});
});
});
describe('getSetsMembers()', function() {
before(function(done) {
db.setsAdd(['set3', 'set4'], 'value', done);
});
it('should return members of two sets', function(done) {
db.getSetsMembers(['set3', 'set4'], function(err, sets) {
assert.equal(err, null);
assert.equal(Array.isArray(sets), true);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(sets[0]) && Array.isArray(sets[1]), true);
assert.strictEqual(sets[0][0], 'value');
assert.strictEqual(sets[1][0], 'value');
done();
});
});
});
describe('isSetMember()', function() {
before(function(done) {
db.setAdd('testSet3', 5, done);
});
it('should return false if element is not member of set', function(done) {
db.isSetMember('testSet3', 10, function(err, isMember) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(isMember, false);
done();
});
});
it('should return true if element is a member of set', function(done) {
db.isSetMember('testSet3', 5, function(err, isMember) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(isMember, true);
done();
});
});
});
describe('isSetMembers()', function() {
before(function(done) {
db.setAdd('testSet4', [1, 2, 3, 4, 5], done);
});
it('should return an array of booleans', function(done) {
db.isSetMembers('testSet4', ['1', '2', '10', '3'], function(err, members) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(members), true);
assert.deepEqual(members, [true, true, false, true]);
done();
});
});
});
describe('isMemberOfSets()', function() {
before(function(done) {
db.setsAdd(['set1', 'set2'], 'value', done);
});
it('should return an array of booleans', function(done) {
db.isMemberOfSets(['set1', 'testSet1', 'set2', 'doesnotexist'], 'value', function(err, members) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(members), true);
assert.deepEqual(members, [true, false, true, false]);
done();
});
});
});
describe('setCount()', function() {
before(function(done) {
db.setAdd('testSet5', [1,2,3,4,5], done);
});
it('should return the element count of set', function(done) {
db.setCount('testSet5', function(err, count) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.strictEqual(count, 5);
done();
});
});
});
describe('setsCount()', function() {
before(function(done) {
async.parallel([
async.apply(db.setAdd, 'set5', [1,2,3,4,5]),
async.apply(db.setAdd, 'set6', 1),
async.apply(db.setAdd, 'set7', 2)
], done);
});
it('should return the element count of sets', function(done) {
db.setsCount(['set5', 'set6', 'set7', 'doesnotexist'], function(err, counts) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
assert.equal(Array.isArray(counts), true);
assert.deepEqual(counts, [5, 1, 1, 0]);
done();
});
});
});
describe('setRemove()', function() {
before(function(done) {
db.setAdd('testSet6', [1, 2], done);
});
it('should remove a element from set', function(done) {
db.setRemove('testSet6', '2', function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
db.isSetMember('testSet6', '2', function(err, isMember) {
assert.equal(err, null);
assert.equal(isMember, false);
done();
});
});
});
});
describe('setsRemove()', function() {
before(function(done) {
db.setsAdd(['set1', 'set2'], 'value', done);
});
it('should remove a element from multiple sets', function(done) {
db.setsRemove(['set1', 'set2'], 'value', function(err) {
assert.equal(err, null);
assert.equal(arguments.length, 1);
db.isMemberOfSets(['set1', 'set2'], 'value', function(err, members) {
assert.equal(err, null);
assert.deepEqual(members, [false, false]);
done();
});
});
});
});
describe('setRemoveRandom()', function() {
before(function(done) {
db.setAdd('testSet7', [1,2,3,4,5], done);
});
it('should remove a random element from set', function(done) {
db.setRemoveRandom('testSet7', function(err, element) {
assert.equal(err, null);
assert.equal(arguments.length, 2);
db.isSetMember('testSet', element, function(err, ismember) {
assert.equal(err, null);
assert.equal(ismember, false);
done();
});
});
});
});
after(function(done) {
db.flushdb(done);
});
});
| Java |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// zmoelnig@iem.kug.ac.at
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglTexParameteri.h"
CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexParameteri , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglViewport
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglTexParameteri :: GEMglTexParameteri (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) :
target(static_cast<GLenum>(arg0)),
pname(static_cast<GLenum>(arg1)),
param(static_cast<GLint>(arg2))
{
m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("target"));
m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("pname"));
m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("param"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglTexParameteri :: ~GEMglTexParameteri () {
inlet_free(m_inlet[0]);
inlet_free(m_inlet[1]);
inlet_free(m_inlet[2]);
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglTexParameteri :: render(GemState *state) {
glTexParameteri (target, pname, param);
}
/////////////////////////////////////////////////////////
// Variables
//
void GEMglTexParameteri :: targetMess (t_float arg1) { // FUN
target = static_cast<GLenum>(arg1);
setModified();
}
void GEMglTexParameteri :: pnameMess (t_float arg1) { // FUN
pname = static_cast<GLenum>(arg1);
setModified();
}
void GEMglTexParameteri :: paramMess (t_float arg1) { // FUN
param = static_cast<GLint>(arg1);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglTexParameteri :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::targetMessCallback), gensym("target"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::pnameMessCallback), gensym("pname"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexParameteri::paramMessCallback), gensym("param"), A_DEFFLOAT, A_NULL);
};
void GEMglTexParameteri :: targetMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->targetMess ( static_cast<t_float>(arg0));
}
void GEMglTexParameteri :: pnameMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->pnameMess ( static_cast<t_float>(arg0));
}
void GEMglTexParameteri :: paramMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->paramMess ( static_cast<t_float>(arg0));
}
| Java |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Linq.Expressions;
namespace BusinessLogic.Repositories
{
public class Repository<T> : IRepository<T> where T : class
{
private readonly DbContext _context;
private readonly DbSet<T> _dbSet;
public Repository(DbContext context)
{
this._context = context;
this._dbSet = context.Set<T>();
}
public virtual void Add(T entity)
{
this._dbSet.Add(entity);
this._context.SaveChanges();
}
public virtual void Delete(int id, string userID)
{
var entry = this._dbSet.Find(id);
this._dbSet.Remove(entry);
this._context.SaveChanges();
}
public IQueryable<T> GetAll()
{
return this._dbSet.AsQueryable();
}
public T GetByID(int? id, string userID)
{
return this._dbSet.Find(id);
}
public void Edit(T entity)
{
this._context.Set<T>().AddOrUpdate(entity);
this._context.SaveChanges();
}
public void Edit(List<T> entities)
{
foreach (var entity in entities)
Edit(entity);
}
public int GetCount()
{
return this._dbSet.Count();
}
private IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return this._dbSet.Where(predicate);
}
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.