code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package com.thundergemios10.survivalgames.util; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import com.thundergemios10.survivalgames.Game; import com.thundergemios10.survivalgames.GameManager; import com.thundergemios10.survivalgames.SurvivalGames; public class ThirstManager implements Listener { ThirstManager instance = new ThirstManager(); public ThirstManager getInstance() { return instance; } @SuppressWarnings("deprecation") public void startThirst() { Bukkit.getServer().getScheduler().scheduleAsyncRepeatingTask(new SurvivalGames(), new Runnable() { public void run() { for (Game g : GameManager.getInstance().getGames()) { for (Player p : g.getAllPlayers()) { removeThirst(p, 1); } } } }, 60L, 200L); } public void removeThirst(Player p, int amount) { p.setLevel(p.getLevel() - amount); } public void addThirst(Player p, int amount) { p.setLevel(p.getLevel() + amount); } public void startThirst(Player p) { p.setLevel(30); } @SuppressWarnings("deprecation") @EventHandler public void onPlayerDrinkWater(PlayerInteractEvent e) { if (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) { if (e.getPlayer().getItemInHand() == new ItemStack(Material.POTION)) { e.getPlayer().getInventory().removeItem(new ItemStack(Material.POTION, 1)); addThirst(e.getPlayer(), 5); e.getPlayer().sendMessage(ChatColor.GREEN + "You drank water."); } } } }
ThunderGemios10/Survival-Games
src/main/java/com/thundergemios10/survivalgames/util/ThirstManager.java
Java
gpl-3.0
1,766
<!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_65) on Tue Apr 08 03:36:46 MDT 2014 --> <TITLE> SortingControllerTest </TITLE> <META NAME="date" CONTENT="2014-04-08"> <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="SortingControllerTest"; } } </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="../../../ca/cmput301w14t09/test/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SortingControllerTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../ca/cmput301w14t09/test/ServerTest.html" title="class in ca.cmput301w14t09.test"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../ca/cmput301w14t09/test/ThreadAdapterTest.html" title="class in ca.cmput301w14t09.test"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?ca/cmput301w14t09/test/SortingControllerTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SortingControllerTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> ca.cmput301w14t09.test</FONT> <BR> Class SortingControllerTest</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><any> <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>ca.cmput301w14t09.test.SortingControllerTest</B> </PRE> <HR> <DL> <DT><PRE>public class <B>SortingControllerTest</B><DT>extends <any></DL> </PRE> <P> <DL> <DT><B>Author:</B></DT> <DD>Chun-Han Lee Testing Sorting for comments</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../ca/cmput301w14t09/test/SortingControllerTest.html#SortingControllerTest()">SortingControllerTest</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../ca/cmput301w14t09/test/SortingControllerTest.html#testSortingCommentsByLocation()">testSortingCommentsByLocation</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create two comments with to unique location, create a third location (0,0) and make a comparison based on that gps location</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../ca/cmput301w14t09/test/SortingControllerTest.html#testSortingPicture()">testSortingPicture</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates two unique comments and puts them into a list, it now simply runs the list through the sorting picture algorithm and returns another list in the right order of pictures being sorted or not.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="SortingControllerTest()"><!-- --></A><H3> SortingControllerTest</H3> <PRE> public <B>SortingControllerTest</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="testSortingCommentsByLocation()"><!-- --></A><H3> testSortingCommentsByLocation</H3> <PRE> public void <B>testSortingCommentsByLocation</B>()</PRE> <DL> <DD>Create two comments with to unique location, create a third location (0,0) and make a comparison based on that gps location <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="testSortingPicture()"><!-- --></A><H3> testSortingPicture</H3> <PRE> public void <B>testSortingPicture</B>()</PRE> <DL> <DD>Creates two unique comments and puts them into a list, it now simply runs the list through the sorting picture algorithm and returns another list in the right order of pictures being sorted or not. <P> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../ca/cmput301w14t09/test/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SortingControllerTest.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../ca/cmput301w14t09/test/ServerTest.html" title="class in ca.cmput301w14t09.test"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../ca/cmput301w14t09/test/ThreadAdapterTest.html" title="class in ca.cmput301w14t09.test"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?ca/cmput301w14t09/test/SortingControllerTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SortingControllerTest.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
cntnboys/CMPUT301W14T09-GPSForm
CMPUT301W14T09Test/doc/ca/cmput301w14t09/test/SortingControllerTest.html
HTML
gpl-3.0
10,991
<div class="cover header"> <div class="navbar navbar-cover navbar-material-blue-700 "> <div class="container-fluid"> <span> <a href="#/"> <img src="img/logo-icon.jpg" style="height:80; float:left"> <span class="lokayat-title" style="float:left; margin-right:10px;">LOKAYAT</span> </a> </span> <div class="menu"> <ul class="nav navbar-nav navbar-left" style="font-size:120%; "> <li class="navbar-item"> <a href="#/">Home</a> </li> <li class="navbar-item"> <a href="#/news">News</a> </li> <li class="navbar-item"> <a href="#/publication">Publications</a> </li> <li class="navbar-item"> <a href="#/media" class="dropdown">Media</a> </li> <li class="navbar-item"> <a href="#/join">Join Us</a> </li> </ul> </div> </div> </div> </div>
atulkhairnar/libre
scripts/directives/headpanel.html
HTML
gpl-3.0
1,225
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateContentsTable extends Migration { public function up() { Schema::create('contents', function(Blueprint $table) { $table->increments('id'); $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP')); $table->string('name', 60)->unique(); $table->string('title', 255)->nullable(); $table->text('content')->nullable(); $table->integer('doctor_id')->unsigned()->nullable(); }); } public function down() { Schema::drop('contents'); } }
RobinMarechal/Kine
database/migrations/2017_07_12_011701_create_contents_table.php
PHP
gpl-3.0
657
/* global sch, sb, map */ function AnimationManager () { this.bkgStep = 150 this.bkgPosition = 0 this.setAnimationSpeed = (speed) => { document.body.style.setProperty('--animation-pace', speed) } this.stopRunning = () => { sch.setPace(750) this.getLight().style.setProperty('transform', `scale(1.0) translateX(${this.bkgPosition}px)`) this.getHands().style.setProperty('bottom', '-5%') } this.startRunning = () => { sch.setPace(350) this.getLight().style.setProperty('transform', `scale(1.3) translateX(${this.bkgPosition}px)`) this.getHands().style.setProperty('bottom', '-25%') } this.updateDirection = () => { this.getLight().style.setProperty('transform', `translateX(${this.bkgPosition}px)`) } this.setBkgPosition = (p) => { this.bkgPosition += p } this.moveRight = () => { this.setBkgPosition(-this.bkgStep) map.movePlayerRight() } this.moveLeft = () => { this.setBkgPosition(this.bkgStep) map.movePlayerLeft() } this.getLight = () => { return this.light || (this.light = document.querySelector('.light')) } this.getHands = () => { return this.hands || (this.hands = document.querySelector('.hands')) } const keyPresses = {} window.onkeydown = (e) => { keyPresses[e.keyCode] = true } window.onkeyup = (e) => { delete keyPresses[e.keyCode] } // const KEY_W = 87 // const KEY_S = 83 const KEY_A = 65 const KEY_D = 68 // const KEY_UP = 38 // const KEY_DN = 40 const KEY_LFT = 37 const KEY_RGT = 39 sch.add(() => { let hasMoved = false if (keyPresses[KEY_D] || keyPresses[KEY_RGT]) { this.moveRight() hasMoved = true } if (keyPresses[KEY_A] || keyPresses[KEY_LFT]) { this.moveLeft() hasMoved = true } if (hasMoved) { if (map.player.dir > 2 * Math.PI || map.player.dir < 0) { this.getLight().classList.remove('light') this.setBkgPosition(-2 * this.bkgPosition) this.updateDirection() sb.add('Wraped around') } this.getLight().classList.add('light') this.updateDirection() sb.add(`Direction: ${map.player.dir.toFixed(1)}rad`) } }) } window.am = new AnimationManager()
lopis/hoosdere
src/animation.js
JavaScript
gpl-3.0
2,247
package com.bukkit.gemo.FalseBook.Block.commands; import com.bukkit.gemo.FalseBook.Block.FalseBookBlockCore; import com.bukkit.gemo.FalseBook.Block.Areas.Area; import com.bukkit.gemo.FalseBook.Block.Areas.AreaSelection; import com.bukkit.gemo.FalseBook.Block.Mechanics.MechanicArea; import com.bukkit.gemo.commands.Command; import com.bukkit.gemo.utils.ChatUtils; import com.bukkit.gemo.utils.UtilPermissions; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class cmdFArea extends Command { public cmdFArea(String pluginName, String syntax, String arguments, String node) { super(pluginName, syntax, arguments, node); this.description = "Save area"; } public void execute(String[] args, CommandSender sender) { if(!(sender instanceof Player)) { ChatUtils.printError(sender, this.pluginName, "This is only an ingame command."); } else { Player player = (Player)sender; if(!UtilPermissions.playerCanUseCommand(player, "falsebook.blocks.area")) { ChatUtils.printError(player, this.pluginName, "You are not allowed to use this command."); } else { MechanicArea mechanic = (MechanicArea)FalseBookBlockCore.getInstance().getMechanicHandler().getMechanic("AREA"); boolean f = false; String aName = args[0]; for(int selectionFound = 0; selectionFound < mechanic.getAreas().size(); ++selectionFound) { if(((Area)mechanic.getAreas().get(selectionFound)).getAreaName().equalsIgnoreCase(aName)) { f = true; } } boolean var10 = false; for(int i = 0; i < mechanic.getSelections().size(); ++i) { if(((AreaSelection)mechanic.getSelections().get(i)).player.getName().equalsIgnoreCase(player.getName())) { var10 = true; if(((AreaSelection)mechanic.getSelections().get(i)).selP1 != null && ((AreaSelection)mechanic.getSelections().get(i)).selP2 != null) { Area newArea = new Area(player.getWorld(), aName, ((AreaSelection)mechanic.getSelections().get(i)).selP1, ((AreaSelection)mechanic.getSelections().get(i)).selP2); newArea.initArea(); mechanic.getAreas().add(newArea); mechanic.saveAreas(aName, true); ChatUtils.printSuccess(player, this.pluginName, "Area saved as: \'" + aName + "\'"); if(f) { ChatUtils.printInfo(player, this.pluginName, ChatColor.GRAY, "WARNING: Area created, but there are multiple areas with that name!"); } return; } ChatUtils.printError(player, this.pluginName, "Please define an area first! (Rightclick with Selectiontool.)"); return; } } if(!var10) { ChatUtils.printError(player, this.pluginName, "Please define an area first! (Rightclick with Selectiontool.)"); } } } } }
Escapecraft/FalseBook
src/main/java/com/bukkit/gemo/FalseBook/Block/commands/cmdFArea.java
Java
gpl-3.0
3,199
// // some mobile-oriented app config overrides // if(typeof(config) == 'undefined') config = {}; Object.merge(config, { api_url: 'https://api.turtl.it/v2', client: 'mobile-ubuntu', version: cordova_app_version, cookie_login: true, base_url: window.location.toString().replace(/\/(index\.html)?$/, '/app'), has_autologin: true });
cibersheep/turtl-ut
www/config.js
JavaScript
gpl-3.0
339
package com.goltzkiste.guessaday; /** * Created by mo on 3/6/16. see http://stackoverflow.com/questions/4216082 */ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.View; import android.widget.DatePicker; import android.os.Build; public class DatePreference extends DialogPreference { private int lastDate = 1; private int lastMonth = 0; private int lastYear = 0; private String dateval; private CharSequence mSummary; private DatePicker picker = null; public static int getYear(String dateval) { String[] pieces = dateval.split("-"); return (Integer.parseInt(pieces[0])); } public static int getMonth(String dateval) { String[] pieces = dateval.split("-"); return (Integer.parseInt(pieces[1])); } public static int getDate(String dateval) { String[] pieces = dateval.split("-"); return (Integer.parseInt(pieces[2])); } public DatePreference(Context ctxt, AttributeSet attrs) { super(ctxt, attrs); setPositiveButtonText(R.string.str_set); setNegativeButtonText(R.string.str_cancel); } @Override protected View onCreateDialogView() { picker = new DatePicker(getContext()); // setCalendarViewShown(false) attribute is only available from API level 11 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { picker.setCalendarViewShown(false); } return (picker); } @Override protected void onBindDialogView(View v) { super.onBindDialogView(v); SharedPreferences SP=this.getSharedPreferences(); //SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(this.getDialog().getBaseContext()); TimeZone MyTimezone = TimeZone.getTimeZone("UTC"); Calendar cal = new GregorianCalendar(MyTimezone); if (this.getKey().equals("startdate")){ cal.set(1, 0, 1); picker.setMinDate(cal.getTimeInMillis()); String enddate=SP.getString("enddate", "2050-12-31"); String[] spieces = enddate.split("-"); cal.set(Integer.parseInt(spieces[0]), Integer.parseInt(spieces[1])-1, Integer.parseInt(spieces[2])); picker.setMaxDate(cal.getTimeInMillis()); } if (this.getKey().equals("enddate")) { String startdate=SP.getString("startdate", "1900-01-01"); String[] spieces = startdate.split("-"); cal.set(Integer.parseInt(spieces[0]), Integer.parseInt(spieces[1])-1, Integer.parseInt(spieces[2])); picker.setMinDate(cal.getTimeInMillis()); cal.set(lastYear + 1000, 11, 31); picker.setMaxDate(cal.getTimeInMillis()); } picker.updateDate(lastYear, lastMonth-1, lastDate); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult) { lastYear = picker.getYear(); lastMonth = (picker.getMonth()+1); lastDate = picker.getDayOfMonth(); String dateval = String.valueOf(lastYear) + "-" + String.format("%02d",lastMonth) + "-" + String.format("%02d",lastDate); if (callChangeListener(dateval)) { persistString(dateval); } } } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return (a.getString(index)); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { dateval = null; if (restoreValue) { if (defaultValue == null) { Calendar cal = Calendar.getInstance(); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); String formatted = format1.format(cal.getTime()); dateval = getPersistedString(formatted); } else { dateval = getPersistedString(defaultValue.toString()); } } else { dateval = defaultValue.toString(); } lastYear = getYear(dateval); lastMonth = getMonth(dateval); lastDate = getDate(dateval); setSummary(dateval); } public void setText(String text) { final boolean wasBlocking = shouldDisableDependents(); dateval = text; persistString(text); final boolean isBlocking = shouldDisableDependents(); if (isBlocking != wasBlocking) { notifyDependencyChange(isBlocking); } } public String getText() { return dateval; } public CharSequence getSummary() { return mSummary; } public void setSummary(CharSequence summary) { if (summary == null && mSummary != null || summary != null && !summary.equals(mSummary)) { mSummary = summary; notifyChanged(); } } }
mo271/guessaday
app/src/main/java/com/goltzkiste/guessaday/DatePreference.java
Java
gpl-3.0
5,318
#region License /* Copyright 2014 - 2015 Nikita Bernthaler Update.cs is part of SFXWallJumpSpot. SFXWallJumpSpot 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. SFXWallJumpSpot 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 SFXWallJumpSpot. If not, see <http://www.gnu.org/licenses/>. */ #endregion License #region using System; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using LeagueSharp.Common; using Version = System.Version; #endregion namespace SFXWallJumpSpot.Library { public class Update { public static void Check(string name, Version version, string path, int displayTime) { try { Task.Factory.StartNew( () => { try { using (var client = new WebClient()) { var data = client.DownloadString( string.Format( "https://raw.githubusercontent.com/{0}/Properties/AssemblyInfo.cs", path)); var gVersion = Version.Parse( new Regex("AssemblyFileVersion\\((\"(.+?)\")\\)").Match(data).Groups[1].Value .Replace("\"", "")); if (gVersion > version) { CustomEvents.Game.OnGameLoad += delegate { Notifications.AddNotification( string.Format( "[{0}] Update available: {1} => {2}!", name, version, gVersion), displayTime); }; } } } catch (Exception ex) { Console.WriteLine(ex); } }); } catch (Exception ex) { Console.WriteLine(ex); } } } }
Lizzaran/LeagueSharp-Standalones
SFXUtility/SFXWallJumpSpot/Library/Update.cs
C#
gpl-3.0
2,931
<p>List group items may be buttons instead of list items (that also means a parent <code>&lt;div&gt;</code> instead of an <code>&lt;ul&gt;</code>). No need for individual parents around each element. <strong class="text-danger">Don't use the standard <code>.btn</code> classes here.</strong></p> <div class="bs-example" data-example-id="list-group-btns"> <div class="list-group"> <button type="button" class="list-group-item">Cras justo odio</button> <button type="button" class="list-group-item">Dapibus ac facilisis in</button> <button type="button" class="list-group-item">Morbi leo risus</button> <button type="button" class="list-group-item">Porta ac consectetur ac</button> <button type="button" class="list-group-item">Vestibulum at eros</button> </div> </div> {% highlight html %} <div class="list-group"> <button type="button" class="list-group-item">Cras justo odio</button> <button type="button" class="list-group-item">Dapibus ac facilisis in</button> <button type="button" class="list-group-item">Morbi leo risus</button> <button type="button" class="list-group-item">Porta ac consectetur ac</button> <button type="button" class="list-group-item">Vestibulum at eros</button> </div> {% endhighlight %}
grvpanchal/bootstrap-essentials
docs/_includes/fulldocs/components/list-group/list-group-buttons.html
HTML
gpl-3.0
1,265
/* Copyright (c) 2012-2015 Todd Freed <todd.freed@gmail.com> This file is part of fab. fab 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. fab 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 fab. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _LOGGER_FILTER_INTERNAL_H #define _LOGGER_FILTER_INTERNAL_H #include "xapi.h" #include "filter.h" struct narrator; struct list; typedef struct filter { uint64_t v; // tag char u; // unknown, whether the tag text has any unrecognized components char o; // operation, '+' or '-' } filter; xapi filter_clone(filter * const restrict A, filter ** const restrict B) __attribute__((nonnull)); /// filter_free // // SUMMARY // free a filter with free semantics // void filter_free(filter * filterp); /// filter_ifree // // SUMMARY // free a filter with iwfree semantics // void filter_ifree(filter ** const restrict filterp) __attribute__((nonnull)); /// filter_say // // SUMMARY // // xapi filter_say(filter * filterp, struct narrator * N) __attribute__((nonnull)); /// filter_would // // SUMMARY // returns a boolean value indicating whether a log is passed by the filter // // PARAMETERS // filters - // ids - category ids // int filters_would(const struct list * const restrict filters, const uint64_t ids) __attribute__((nonnull)); #endif
hossbeast/fab
liblogger/filter/filter.internal.h
C
gpl-3.0
1,809
/** * This file is part of ankus. * * ankus 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. * * ankus 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 ankus. If not, see <http://www.gnu.org/licenses/>. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.11.30 at 02:11:34 오후 KST // package org.ankus.model.workflow; import org.eclipse.persistence.oxm.annotations.XmlCDATA; import javax.xml.bind.annotation.*; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="path" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="script" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="working" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element ref="{http://www.openankus.org/schema/workflow}args" minOccurs="0"/> * &lt;element ref="{http://www.openankus.org/schema/workflow}envs" minOccurs="0"/> * &lt;element ref="{http://www.openankus.org/schema/workflow}command" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "path", "script", "working", "args", "envs", "command" }) @XmlRootElement(name = "shell") public class Shell { @XmlElement(required = true) protected String path; @XmlElement(required = true) @XmlCDATA protected String script; @XmlElement(required = true) protected String working; protected Args args; protected Envs envs; protected Command command; /** * Gets the value of the path property. * * @return * possible object is * {@link String } * */ public String getPath() { return path; } /** * Sets the value of the path property. * * @param value * allowed object is * {@link String } * */ public void setPath(String value) { this.path = value; } /** * Gets the value of the script property. * * @return * possible object is * {@link String } * */ public String getScript() { return script; } /** * Sets the value of the script property. * * @param value * allowed object is * {@link String } * */ public void setScript(String value) { this.script = value; } /** * Gets the value of the working property. * * @return * possible object is * {@link String } * */ public String getWorking() { return working; } /** * Sets the value of the working property. * * @param value * allowed object is * {@link String } * */ public void setWorking(String value) { this.working = value; } /** * Gets the value of the args property. * * @return * possible object is * {@link Args } * */ public Args getArgs() { return args; } /** * Sets the value of the args property. * * @param value * allowed object is * {@link Args } * */ public void setArgs(Args value) { this.args = value; } /** * Gets the value of the envs property. * * @return * possible object is * {@link Envs } * */ public Envs getEnvs() { return envs; } /** * Sets the value of the envs property. * * @param value * allowed object is * {@link Envs } * */ public void setEnvs(Envs value) { this.envs = value; } /** * Gets the value of the command property. * * @return * possible object is * {@link Command } * */ public Command getCommand() { return command; } /** * Sets the value of the command property. * * @param value * allowed object is * {@link Command } * */ public void setCommand(Command value) { this.command = value; } }
onycom-ankus/ankus_analyzer_G
trunk_web/ankus-web-services/src/main/java/org/ankus/model/workflow/Shell.java
Java
gpl-3.0
5,280
// Source Code Begins Here #include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> void Initial(char board[3][3]){ // Function to Initialize board with value 1,2,3....9 int i,j,k = 1; for(i=0;i<3;i++){ for(j=0;j<3;j++){ board[i][j] = '0'+k; k++; } } } void View(char board[3][3]){ // Function to View to board for(int i=0;i<3;i++){ for(int j=0;j<3;j++) printf("%c\t",board[i][j]); printf("\n\n"); } } bool WinningCheck(char board[3][3],char mark){ // Checking Winning Conditions if(board[0][0]==mark && board[0][1]==mark && board[0][2]==mark) return true; else if(board[1][0]==mark && board[1][1]==mark && board[1][2]==mark) return true; else if(board[2][0]==mark && board[2][1]==mark && board[2][2]==mark) return true; else if(board[0][0]==mark && board[1][0]==mark && board[2][0]==mark) return true; else if(board[0][1]==mark && board[1][1]==mark && board[2][1]==mark) return true; else if(board[0][2]==mark && board[1][2]==mark && board[2][2]==mark) return true; else if(board[0][0]==mark && board[1][1]==mark && board[2][2]==mark) return true; else if(board[0][2]==mark && board[1][1]==mark && board[2][0]==mark) return true; return false; } int TieCheck(char board[3][3]){ // Function to Check Tie Case int i,j,k = 1; for(i=0;i<3;i++){ for(j=0;j<3;j++){ if(board[i][j]=='0'+k) return 1; k++; } } return 0; } bool AssignValue(char board[3][3],int value,char mark){ // Function to checking value assigning validity if(value==1 && board[0][0]=='1') { board[0][0] = mark; return false; } else if(value==2 && board[0][1]=='2') { board[0][1] = mark; return false; } else if(value==3 && board[0][2]=='3') { board[0][2] = mark; return false; } else if(value==4 && board[1][0]=='4') { board[1][0] = mark; return false; } else if(value==5 && board[1][1]=='5') { board[1][1] = mark; return false; } else if(value==6 && board[1][2]=='6') { board[1][2] = mark; return false; } else if(value==7 && board[2][0]=='7') { board[2][0] = mark; return false; } else if(value==8 && board[2][1]=='8') { board[2][1] = mark; return false; } else if(value==9 && board[2][2]=='9') { board[2][2] = mark; return false; } return true; } int Play(int run,char board[3][3],char pname[]){ // TIK TOK TOE Begins int ch; bool ok = true; run = TieCheck(board); if(!run){ printf("Match Tied\n\n"); printf("Press Any Key to Continue...\n"); getchar(); } if(run){ system("clear"); View(board); while(ok){ printf("%s , Enter Your Choice ( 1 - 9 ) : ",pname); scanf("%d",&ch); getchar(); ok = AssignValue(board,ch,'X'); if(ok){ printf("Wrong Input. PLease Enter a valid one\n"); } } if(WinningCheck(board,'X')){ system("clear"); View(board); printf("Congrats %s , You Win The Match :D ^_^\n\n",pname); printf("Press Any Key to Continue...\n"); getchar(); return 0; } run = TieCheck(board); if(!run){ printf("Match Tied\n\n"); printf("Press Any Key to Continue...\n"); getchar(); } ok = true; system("clear"); View(board); while(ok && run){ ch = 1 + rand()%9; ok = AssignValue(board,ch,'O'); } if(WinningCheck(board,'O')){ system("clear"); View(board); printf("Sorry %s , You Loss The Match :'(\n\n",pname); printf("Press Any Key to Continue...\n"); getchar(); return 0; } Play(run,board,pname); } } int main(){ // Main Function srand(time(NULL)); char pname[30]; char board[3][3]; int choice; while(1){ Initial(board); system("clear"); printf("Welcome 2 TIK TOK TOE\n\n"); printf("Please Choice A Option +++\n\n"); printf("1. Play\n2. Exit\n\n"); scanf("%d",&choice); getchar(); if(choice==1){ printf("Please Enter Your Name : "); // Getting Player Name gets(pname); Play(1,board,pname); // Game begining call } else if(choice==2) break; else { printf("Wrong Choice. Enter a valid one please.\n"); getchar(); system("clear"); } } return 0; } // Source Code Ends Here
s4kibs4mi/CnCPP
tik_tok_toe_rebuild.cpp
C++
gpl-3.0
3,963
// Copyright 2010-2011 Dmitri Nikulin, Enzo Reyes. // // This file is part of clamity. // // clamity 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. // // clamity 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 clamity. If not, see <http://www.gnu.org/licenses/>. #include "ClamityMath.hh" #include <stdint.h> #include <stdio.h> #include <time.h> #include <stdlib.h> #include <limits.h> #include <cmath> /* for std::abs(double) */ static bool isEqual(double x, double y, double epsilonErrorMargin) { return std::abs(x - y) <= epsilonErrorMargin * std::abs(x); } static bool CheckResults(cl_float * data, cl_float * wanted, unsigned int vecCount, Logger &log, double epsilonErrorMargin) { using boost::format; using boost::str; for (size_t i = 0; i < vecCount; i++) { const cl_float have = data[i]; const cl_float want = wanted[i]; if (!isEqual(have, want, epsilonErrorMargin)) { log(LOG_ERROR,str(format("Test Failed --- Incorrect value at %d (GPU has: %f - CPU Has: %f diff: %f Epsilon: %f)") % i \ % have % want %(have-want) % epsilonErrorMargin)); return false; } } return true; } void ClamityMath::basicALU(Clamity &subject) { using boost::format; using boost::str; Logger &log = subject.log; cl::Device &device = subject.device; cl::Context &context(subject.context); cl::CommandQueue queue(context, device); size_t memSize = subject.deviceMemoryAvail(device) ;//device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); size_t memAlloc = subject.maxMemoryAllocation (device); //device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); size_t maxBuff = subject.recommendMemory(memAlloc,memSize,3) / subject.memoryPoolFraction; // Work out group size size_t vecCount = maxBuff / sizeof(cl_float); // Is the max alloc size a multiple of 4? size_t maxAllocMultiple = memSize / memAlloc; unsigned long memorySize = vecCount * sizeof(cl_float); log(LOG_INFO,"Basic ALU tests"); log(LOG_INFO,"Testing for A = A + (B * C) - Executing over 65535 iterations"); log(LOG_INFO,str(format("Math Global size : %d - Max Alloc Size: %d Buffer Size: %d") % memSize % memAlloc % maxBuff)); if (device.getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU) { log(LOG_INFO,"CPU device detected skipping.... "); return; } if (maxAllocMultiple != 4) log(LOG_WARN,"CL_DEVICE_MAX_MEM_ALLOC_SIZE not a multiple of 4"); cl::Program program; subject.compile(program, ClamityMathCL); cl::Kernel kern_membasic(program, "testALU"); std::vector<cl_float> data(vecCount); std::vector<cl_float> dataA(vecCount); std::vector<cl_float> dataB(vecCount); for (size_t i = 0; i < vecCount; i++) { data[i] = rand() % UINT_MAX; dataA[i] = rand() % (UINT_MAX / 2) ; dataB[i] = rand() % (UINT_MAX / 2) ; } cl::Buffer memoryA(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryB(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryC(context, CL_MEM_WRITE_ONLY, memorySize); log(LOG_INFO,"Executing test kernel "); try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, dataA.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, dataB.data()); queue.enqueueWriteBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.finish(); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC, str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); return; } log(LOG_INFO," Test Passed"); } void ClamityMath::basicFMAD(Clamity &subject) { using boost::format; using boost::str; Logger &log = subject.log; cl::Device &device = subject.device; cl::Context &context(subject.context); cl::CommandQueue queue(context, device); double epsilonErrorMargin = subject.epsilonErrorMargin; size_t memSize = subject.deviceMemoryAvail(device) ;//device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); size_t memAlloc = subject.maxMemoryAllocation (device); //device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); size_t maxBuff = subject.recommendMemory(memAlloc,memSize,3) / subject.memoryPoolFraction; // Work out group size size_t vecCount = maxBuff / sizeof(cl_float); // Is the max alloc size a multiple of 4? size_t maxAllocMultiple = memSize / memAlloc; unsigned long memorySize = vecCount * sizeof(cl_float); log(LOG_INFO,"Basic ALU tests"); log(LOG_INFO,"Testing for A = A + (B * C)"); log(LOG_INFO,str(format("Math Global size : %d - Max Alloc Size: %d Buffer Size: %d") % memSize % memAlloc % maxBuff)); if (maxAllocMultiple != 4) log(LOG_WARN,"CL_DEVICE_MAX_MEM_ALLOC_SIZE not a multiple of 4"); cl::Program program; subject.compile(program, ClamityMathCL); cl::Kernel kern_membasic(program, "BasicFMAD"); std::vector<cl_float> data(vecCount); std::vector<cl_float> dataA(vecCount); std::vector<cl_float> dataB(vecCount); std::vector<cl_float> results(vecCount); log(LOG_INFO,"Creating results table"); for (size_t i = 0; i < vecCount; i++) { data[i] = rand() % UINT_MAX; dataA[i] = rand() % ( UINT_MAX /2 ) ; dataB[i] = rand() % ( UINT_MAX /2 ) ; results[i] = data[i] + ( dataA[i] * dataB[i]); //Verify against the CPU results } cl::Buffer memoryA(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryB(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryC(context, CL_MEM_WRITE_ONLY, memorySize); log(LOG_INFO,"Executing test kernel "); try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, dataA.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, dataB.data()); queue.enqueueWriteBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC, str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); testLevel = TEST_PANIC; errorReported = getErrorType(error.err()); testPassed=false; return; } log(LOG_INFO,"Verifying results"); if (!CheckResults(data.data(), results.data(), vecCount, log,epsilonErrorMargin)) { testPassed = false; testLevel = TEST_ERROR; log(LOG_ERROR," Test Failed!"); } else { log(LOG_INFO," Test Passed"); testPassed = true; } } void ClamityMath::basicADD(Clamity &subject) { using boost::format; using boost::str; Logger &log = subject.log; cl::Device &device = subject.device; cl::Context &context(subject.context); cl::CommandQueue queue(context, device); double epsilonErrorMargin = subject.epsilonErrorMargin; size_t memSize = subject.deviceMemoryAvail(device) ;//device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); size_t memAlloc = subject.maxMemoryAllocation (device); //device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); size_t maxBuff = subject.recommendMemory(memAlloc,memSize,3) / subject.memoryPoolFraction; // Work out group size size_t vecCount = maxBuff / sizeof(cl_float); // Is the max alloc size a multiple of 4? size_t maxAllocMultiple = memSize / memAlloc; unsigned long memorySize = vecCount * sizeof(cl_float); log(LOG_INFO,"Basic ALU tests"); log(LOG_INFO,"Testing for A = B + C"); log(LOG_INFO,str(format("Math Global size : %d - Max Alloc Size: %d Buffer Size: %d") % memSize % memAlloc % maxBuff)); if (maxAllocMultiple != 4) log(LOG_WARN,"CL_DEVICE_MAX_MEM_ALLOC_SIZE not a multiple of 4"); cl::Program program; subject.compile(program, ClamityMathCL); cl::Kernel kern_membasic(program, "BasicADD"); std::vector<cl_float> data(vecCount); for (size_t i = 0; i < vecCount; i++) { data[i] = 1; } cl::Buffer memoryA(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryB(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryC(context, CL_MEM_WRITE_ONLY, memorySize); try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, data.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, data.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC,str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); testLevel = TEST_PANIC; errorReported = getErrorType(error.err()); testPassed=false; return; } bool good = true; for (size_t i = 0; i < vecCount; i++) { const cl_float have = data[i]; const cl_float want = 2.0f; if (!isEqual(have,want,epsilonErrorMargin)) { good = false; log(LOG_ERROR,str(format("Test Failed --- Incorrect value at %d (have: %f want: %f diff: %f epsilon: %f)") % i \ % have % want %(have-want ) % epsilonErrorMargin)); testPassed = false; testLevel = TEST_ERROR; return; } } std::vector<cl_float> dataA(vecCount); std::vector<cl_float> dataB(vecCount); std::vector<cl_float> results(vecCount); log(LOG_INFO,"Testing Random ADD operation "); for (size_t i = 0; i < vecCount; i++) { dataA[i] = rand() % (UINT_MAX / 2); dataB[i] = rand() % (UINT_MAX / 2); results[i] = dataA[i] + dataB[i]; //Verify against the CPU results } try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, dataA.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, dataB.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC,str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); testLevel = TEST_PANIC; errorReported = getErrorType(error.err()); testPassed=false; return; } if (!CheckResults(data.data(), results.data(), vecCount, log, epsilonErrorMargin)) { testPassed = false; log(LOG_ERROR," Test Failed!"); testLevel = TEST_ERROR; } else { log(LOG_INFO," Test Passed"); testPassed = true; } } void ClamityMath::basicMULT(Clamity &subject) { using boost::format; using boost::str; Logger &log = subject.log; cl::Device &device = subject.device; cl::Context &context(subject.context); cl::CommandQueue queue(context, device); double epsilonErrorMargin = subject.epsilonErrorMargin; size_t memSize = subject.deviceMemoryAvail(device) ;//device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>(); size_t memAlloc = subject.maxMemoryAllocation (device); //device.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>(); size_t maxBuff = subject.recommendMemory(memAlloc,memSize,3) / subject.memoryPoolFraction; // Work out group size size_t vecCount = maxBuff / sizeof(cl_float); // Is the max alloc size a multiple of 4? size_t maxAllocMultiple = memSize / memAlloc; unsigned long memorySize = vecCount * sizeof(cl_float); log(LOG_INFO,"Basic ALU tests"); log(LOG_INFO,"Testing for A = B * C"); log(LOG_INFO,str(format("Math Global size : %d - Max Alloc Size: %d Buffer Size: %d") % memSize % memAlloc % maxBuff)); if (maxAllocMultiple != 4) log(LOG_INFO,"CL_DEVICE_MAX_MEM_ALLOC_SIZE not a multiple of 4"); cl::Program program; subject.compile(program, ClamityMathCL); cl::Kernel kern_membasic(program, "BasicMUL"); std::vector<cl_float> data(vecCount); std::vector<cl_float> dataA(vecCount); std::vector<cl_float> dataB(vecCount); std::vector<cl_float> results(vecCount); for (size_t i = 0; i < vecCount; i++) { dataA[i] = 1; dataB[i] = 1; } cl::Buffer memoryA(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryB(context, CL_MEM_READ_ONLY, memorySize); cl::Buffer memoryC(context, CL_MEM_WRITE_ONLY, memorySize); try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, dataA.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, dataB.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC,str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); testLevel = TEST_PANIC; errorReported = getErrorType(error.err()); testPassed=false; return; } bool good = true; for (size_t i = 0; i < vecCount; i++) { const cl_float have = data[i]; const cl_float want = 1.0f ; // (i % modulo) << shiftSize; if (!isEqual(have,want,epsilonErrorMargin)) { good = false; log(LOG_ERROR,str(format("Test Failed --- Incorrect value at %d (have: %f want: %f diff: %f epsilon: %f)") % i \ % have % want %(have-want ) % epsilonErrorMargin)); testPassed = false; testLevel = TEST_ERROR; return; } } log(LOG_INFO,"Testing Random MULT operation "); for (size_t i = 0; i < vecCount; i++) { dataA[i] = rand() % (UINT_MAX / 2); dataB[i] = rand() % (UINT_MAX / 2); results[i] = dataA[i] * dataB[i]; //Verify against the CPU results } try { queue.enqueueWriteBuffer(memoryA, CL_TRUE, 0, memorySize, dataA.data()); queue.enqueueWriteBuffer(memoryB, CL_TRUE, 0, memorySize, dataB.data()); kern_membasic.setArg(0, memoryC); kern_membasic.setArg(1, memoryA); kern_membasic.setArg(2, memoryB); queue.enqueueNDRangeKernel(kern_membasic, cl::NullRange, cl::NDRange(vecCount), cl::NullRange); queue.enqueueReadBuffer(memoryC, CL_TRUE, 0, memorySize, data.data()); } catch (cl::Error error) { log(LOG_PANIC,str(format("Test Failed --- %s '( %s)'") % error.what() % error.err())); testLevel = TEST_PANIC; errorReported = getErrorType(error.err()); testPassed=false; return; } if (!CheckResults(data.data(), results.data(), vecCount, log, epsilonErrorMargin)) { testPassed = false; log(LOG_ERROR," Test Failed!"); testLevel = TEST_ERROR; } else { log(LOG_INFO," Test Passed"); testPassed = true; } }
dnikulin/clamity
ClamityMath/Arithmetic.cc
C++
gpl-3.0
16,234
import latinize from 'latinize'; export function urlify(m) { return m.toLowerCase().replace(/[^a-z0-9]/g, ''); } // remove all html tags export function textify(m) { return m.replace(/<\/?[^>]+(>|$)/g, '').replace(/\s{2,}/g, ' '); } export function sanitize(str) { return textify(latinize(str.toLowerCase())); } export function simplify(str) { return str.replace(/<\/em>( )*<em>/ig, (match, p1) => p1 ? ' ' : ''); } export function elipses({ text, maxLength }) { if (text.length < maxLength) { return text; } return `${text.substring(0, maxLength)}…`; } export function stemify(str) { return latinize(textify(str).toLowerCase()).replace(/[^a-z]/, ''); }
pzhine/derribase
src/lib/_helpers.js
JavaScript
gpl-3.0
682
<?php /* # Copyright (C) 2002 <Gregory Hinton Nietsky> # Copyright (C) 2005 <ZA Telecomunications> # # 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 */ include "auth.inc"; if ((isset($pbxupdate)) && ($sdpos != "") && ($sdnumber != "") && ((($sdpos >= 0) && ($sdpos < 30)) || ($sdpos == "*") || ($sdpos == "#"))) { pg_query($db,"INSERT INTO astdb (family,key,value) VALUES ('" . $PHP_AUTH_USER . "','speed-" . $sdpos . "','" . $sdnumber . "')"); } $gdbquery="SELECT lpad(substr(key,7),2,'0'),value FROM astdb WHERE family='" . $PHP_AUTH_USER . "' AND key ~ '^speed\-([0-9]+)|([*#])' ORDER BY lpad(substr(key,7),2,'0')"; $qgetdata=pg_query($db,$gdbquery); ?> <CENTER> <link rel="stylesheet" type="text/css" href="/style.php?style=<?php print $style;?>"> <FORM METHOD=POST> <TABLE WIDTH=90% CELLPADDING=0 CELLSPACING=0> <TR CLASS=list-color2> <TH CLASS=heading-body COLSPAN=3>Snom Speed Dials</TH> </TR> <TR CLASS=list-color1> <TH CLASS=heading-body2 WIDTH=10%>Delete</TH> <TH CLASS=heading-body2 WIDTH=50%>Position</TH> <TH CLASS=heading-body2 WIDTH=30%>Number</TH> </TR> <?php $rcnt=0; $dnum=pg_num_rows($qgetdata); for($i=0;$i<$dnum;$i++){ $getdata=pg_fetch_array($qgetdata,$i); $sdtodel="sddel" . $getdata[0]; if (($getdata[0][1] != "*") && ($getdata[0][1] != "#")) { $sdpos=sprintf("%d",$getdata[0]); } else { $sdpos=$getdata[0][1]; } if ((isset($pbxupdate)) && (${$sdtodel} == "on")) { pg_query($db,"DELETE FROM astdb WHERE family='" . $PHP_AUTH_USER . "' AND key='speed-" . $sdpos . "'"); } else { if ($rcnt % 2 == 0) { $bcolor="CLASS=list-color2"; } else { $bcolor="CLASS=list-color1"; } print "<TR " . $bcolor . "><TD>"; print "<INPUT TYPE=CHECKBOX NAME=\"sddel" . $getdata[0] . "\">"; print "</TD><TD>" . $sdpos . "</TD><TD>" . $getdata[1] . "</TD><TD>" . $getdata[2] . "</TD></TR>\n"; $rcnt++; } } if ($rcnt % 2 == 0) { $bcol[0]="CLASS=list-color2"; $bcol[1]="CLASS=list-color1"; } else { $bcol[0]="CLASS=list-color1"; $bcol[1]="CLASS=list-color2"; } ?> </TR> <?php if ($rcnt < 100) { ?> <TR <?php print $bcol[0];?>> <TH COLSPAN=3 CLASS=heading-body2>Add New Entry</TH></TR> <TR <?php print $bcol[1];?>> <TD>&nbsp;</TD> <TD><INPUT NAME=sdpos VALUE=""></TD> <TD><INPUT NAME=sdnumber></TD></TR> <?php } ?> <TR <?php print $bcol[0];?>> <TD ALIGN=MIDDLE COLSPAN=3> <INPUT TYPE=SUBMIT NAME=pbxupdate VALUE="Save Changes"> <INPUT TYPE=RESET> </TD> </TR> <TR <?php print $bcol[1];?>> <TD ALIGN=MIDDLE COLSPAN=3> <A HREF=/reception/vladmin.php?style=<?php print $style;?>>Account Configuration</A> </TD> </TR> </TABLE> </FORM>
Distrotech/distrotech-core
sysroot/var/spool/apache/htdocs/reception/sdial.php
PHP
gpl-3.0
3,350
' ' * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved. ' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' Namespace javax.swing.event ''' <summary> ''' ListDataListener ''' ''' @author Hans Muller ''' </summary> Public Interface ListDataListener Inherits java.util.EventListener ''' <summary> ''' Sent after the indices in the index0,index1 ''' interval have been inserted in the data model. ''' The new interval includes both index0 and index1. ''' </summary> ''' <param name="e"> a <code>ListDataEvent</code> encapsulating the ''' event information </param> Sub intervalAdded(ByVal e As ListDataEvent) ''' <summary> ''' Sent after the indices in the index0,index1 interval ''' have been removed from the data model. The interval ''' includes both index0 and index1. ''' </summary> ''' <param name="e"> a <code>ListDataEvent</code> encapsulating the ''' event information </param> Sub intervalRemoved(ByVal e As ListDataEvent) ''' <summary> ''' Sent when the contents of the list has changed in a way ''' that's too complex to characterize with the previous ''' methods. For example, this is sent when an item has been ''' replaced. Index0 and index1 bracket the change. ''' </summary> ''' <param name="e"> a <code>ListDataEvent</code> encapsulating the ''' event information </param> Sub contentsChanged(ByVal e As ListDataEvent) End Interface End Namespace
amethyst-asuka/java_dotnet
javax/swing/event/ListDataListener.vb
Visual Basic
gpl-3.0
1,571
<?php /** * Settings > Tools view * * @package ConvertKit * @author ConvertKit */ ?> <div class="metabox-holder"> <div class="postbox"> <h3><span><?php esc_html_e( 'Debug Log', 'convertkit' ); ?></span></h3> <div class="inside"> <p class="description"> <?php esc_html_e( 'Use this tool to help debug ConvertKit plugin functionality.', 'convertkit' ); ?><br /> <?php esc_html_e( 'For performance, the last 500 lines of the log are displayed. Use the Download Log option to review the full log.', 'convertkit' ); ?><br /> </p> <textarea readonly="readonly" id="debug-log-textarea" class="large-text convertkit-monospace" rows="15"><?php echo esc_textarea( $log->read() ); ?></textarea> <?php if ( $log->exists() ) { ?> <p class="submit"> <?php submit_button( __( 'Download Log', 'convertkit' ), 'primary', 'convertkit-download-debug-log', false ); submit_button( __( 'Clear Log', 'convertkit' ), 'secondary', 'convertkit-clear-debug-log', false ); ?> </p> <p><?php esc_html_e( 'Log file', 'convertkit' ); ?>: <code><?php echo esc_attr( $log->get_filename() ); ?></code></p> <?php } ?> </div><!-- .inside --> </div><!-- .postbox --> <div class="postbox"> <h3><span><?php esc_html_e( 'System Info', 'convertkit' ); ?></span></h3> <div class="inside"> <p><?php esc_html_e( 'Use this tool to send system info to support when necessary.', 'convertkit' ); ?></p> <textarea readonly="readonly" id="system-info-textarea" class="large-text convertkit-monospace" rows="15"><?php echo esc_textarea( $system_info->get() ); ?></textarea> <p class="submit"> <?php submit_button( __( 'Download System Info', 'convertkit' ), 'primary', 'convertkit-download-system-info', false ); ?> </p> </div><!-- .inside --> <?php // Nonce for Log and System Info actions. wp_nonce_field( 'convertkit-settings-tools', '_convertkit_settings_tools_nonce' ); ?> </div><!-- .postbox --> </div><!-- .metabox-holder -->
ConvertKit/ConvertKit-WordPress
views/backend/settings/tools.php
PHP
gpl-3.0
2,096
package com.taobao.api.request; import java.util.Date; import java.util.Map; import com.taobao.api.ApiRuleException; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.RequestCheckUtils; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.InventoryOccupyAdjustResponse; /** * TOP API: taobao.inventory.occupy.adjust request * * @author auto create * @since 1.0, 2014-11-02 16:51:11 */ public class InventoryOccupyAdjustRequest implements TaobaoRequest<InventoryOccupyAdjustResponse> { /** * 商家外部订单号 */ private String bizUniqueCode; private Map<String, String> headerMap = new TaobaoHashMap(); /** * 商品初始库存信息: [{ "TBOrderCode":"淘宝交易号","TBSubOrderCode ":"淘宝子交易单号", * "originalStoreCode" :"交易下单的仓库编码","storeCode":"要切换占用到的商家仓库编码", * " scItemId " * :"商品后端ID","scItemCode":"商品商家编码","inventoryType":"仓储类型","quantity": * "新仓库的占用数量,如果不传,则取用原先的占用数"}] */ private String items; /** * 业务操作时间 */ private Date operateTime; /** * 订单类型:B2C、B2B */ private String tbOrderType; private Long timestamp; private TaobaoHashMap udfParams; // add user-defined text parameters @Override public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(bizUniqueCode, "bizUniqueCode"); RequestCheckUtils.checkNotEmpty(items, "items"); RequestCheckUtils.checkNotEmpty(operateTime, "operateTime"); RequestCheckUtils.checkNotEmpty(tbOrderType, "tbOrderType"); } @Override public String getApiMethodName() { return "taobao.inventory.occupy.adjust"; } public String getBizUniqueCode() { return this.bizUniqueCode; } @Override public Map<String, String> getHeaderMap() { return headerMap; } public String getItems() { return this.items; } public Date getOperateTime() { return this.operateTime; } @Override public Class<InventoryOccupyAdjustResponse> getResponseClass() { return InventoryOccupyAdjustResponse.class; } public String getTbOrderType() { return this.tbOrderType; } @Override public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("biz_unique_code", this.bizUniqueCode); txtParams.put("items", this.items); txtParams.put("operate_time", this.operateTime); txtParams.put("tb_order_type", this.tbOrderType); if (this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void putOtherTextParam(String key, String value) { if (this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public void setBizUniqueCode(String bizUniqueCode) { this.bizUniqueCode = bizUniqueCode; } public void setItems(String items) { this.items = items; } public void setOperateTime(Date operateTime) { this.operateTime = operateTime; } public void setTbOrderType(String tbOrderType) { this.tbOrderType = tbOrderType; } @Override public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
kuiwang/my-dev
src/main/java/com/taobao/api/request/InventoryOccupyAdjustRequest.java
Java
gpl-3.0
3,664
Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 

 Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note. Note: You may assume that both strings contain only lowercase letters. ~~~ canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true ~~~
zqfan/leetcode
algorithms/383. Ransom Note/readme.md
Markdown
gpl-3.0
646
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.design; import net.sf.jasperreports.engine.ExpressionReturnValue; import net.sf.jasperreports.engine.JRConstants; import net.sf.jasperreports.engine.JRExpression; import net.sf.jasperreports.engine.util.JRCloneUtils; /** * Implementation of {@link net.sf.jasperreports.engine.ExpressionReturnValue ExpressionReturnValue} * to be used for report design purposes. * * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class DesignExpressionReturnValue extends DesignCommonReturnValue implements ExpressionReturnValue { /** * */ private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; public static final String PROPERTY_EXPRESSION = "expression"; /** * The expression producing the value to copy. */ protected JRExpression expression; /** * Returns the expression whose value should be copied. * * @return the expression whose value should be copied. */ @Override public JRExpression getExpression() { return expression; } /** * Sets the expression. * * @param expression the expression * @see net.sf.jasperreports.engine.ExpressionReturnValue#getExpression() */ public void setExpression(JRExpression expression) { Object old = this.expression; this.expression = expression; getEventSupport().firePropertyChange(PROPERTY_EXPRESSION, old, this.expression); } @Override public Object clone() { DesignExpressionReturnValue clone = (DesignExpressionReturnValue)super.clone(); clone.expression = JRCloneUtils.nullSafeClone(expression); return clone; } }
MHTaleb/Encologim
lib/JasperReport/src/net/sf/jasperreports/engine/design/DesignExpressionReturnValue.java
Java
gpl-3.0
2,583
package io.github.thebusybiscuit.slimefun4.core.guide; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import io.github.thebusybiscuit.cscorelib2.chat.ChatColors; import io.github.thebusybiscuit.cscorelib2.inventory.ItemUtils; import io.github.thebusybiscuit.cscorelib2.item.CustomItem; import me.mrCookieSlime.CSCoreLibPlugin.PlayerRunnable; import me.mrCookieSlime.CSCoreLibPlugin.general.Chat.TellRawMessage; import me.mrCookieSlime.CSCoreLibPlugin.general.Chat.TellRawMessage.HoverAction; import me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.CustomBookOverlay; import me.mrCookieSlime.Slimefun.SlimefunGuide; import me.mrCookieSlime.Slimefun.SlimefunPlugin; import me.mrCookieSlime.Slimefun.Objects.Category; import me.mrCookieSlime.Slimefun.Objects.LockedCategory; import me.mrCookieSlime.Slimefun.Objects.Research; import me.mrCookieSlime.Slimefun.Objects.SeasonalCategory; import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.SlimefunItem; import me.mrCookieSlime.Slimefun.api.GuideHandler; import me.mrCookieSlime.Slimefun.api.PlayerProfile; import me.mrCookieSlime.Slimefun.api.Slimefun; public class BookSlimefunGuide implements ISlimefunGuide { @Override public SlimefunGuideLayout getLayout() { return SlimefunGuideLayout.BOOK; } @Override public ItemStack getItem() { return new CustomItem(new ItemStack(Material.ENCHANTED_BOOK), "&aSlimefun Guide &7(Book GUI)", "", "&eRight Click &8\u21E8 &7Browse Items", "&eShift + Right Click &8\u21E8 &7Open Settings / Credits"); } @Override public void openMainMenu(PlayerProfile profile, boolean survival, int page) { Player p = profile.getPlayer(); if (p == null) return; if (survival) { profile.getGuideHistory().clear(); } List<TellRawMessage> pages = new ArrayList<>(); List<String> texts = new ArrayList<>(); List<String> tooltips = new ArrayList<>(); List<PlayerRunnable> actions = new ArrayList<>(); int tier = 0; for (final Category category: Category.list()) { boolean locked = true; for (SlimefunItem item: category.getItems()) { if (Slimefun.isEnabled(p, item, false)) { locked = false; break; } } if (!locked) { if (tier < category.getTier()) { if (survival) { for (GuideHandler handler : Slimefun.getGuideHandlers(tier)) { handler.addEntry(texts, tooltips); actions.add(new PlayerRunnable(2) { @Override public void run(Player p) { handler.run(p, survival, true); } }); } } tier = category.getTier(); if (tier > 1) { for (int i = 0; i < 10; i++) { if (texts.size() % 10 == 0) break; texts.add(" "); tooltips.add(null); actions.add(null); } } texts.add(ChatColors.color("&8\u21E8 &6Tier " + tier)); tooltips.add(null); actions.add(null); } if (category instanceof LockedCategory && !((LockedCategory) category).hasUnlocked(p, profile)) { StringBuilder parents = new StringBuilder(ChatColors.color("&4&lLOCKED\n\n&7In order to unlock this Category,\n&7you need to unlock all Items from\n&7the following Categories first:\n")); for (Category parent : ((LockedCategory) category).getParents()) { parents.append(ChatColors.color("\n&c" + ItemUtils.getItemName(parent.getItem()))); } texts.add(ChatColors.color(shorten("&c" , ItemUtils.getItemName(category.getItem())))); tooltips.add(parents.toString()); actions.add(null); } else if (category instanceof SeasonalCategory) { if (((SeasonalCategory) category).isUnlocked()) { texts.add(ChatColors.color(shorten("&a", ItemUtils.getItemName(category.getItem())))); tooltips.add(ChatColors.color("&eClick to open the following Category:\n" + ItemUtils.getItemName(category.getItem()))); actions.add(new PlayerRunnable(1) { @Override public void run(final Player p) { Slimefun.runSync(() -> openCategory(profile, category, survival, 1), 1L); } }); } } else { texts.add(ChatColors.color(shorten("&a", ItemUtils.getItemName(category.getItem())))); tooltips.add(ChatColors.color("&eClick to open the following Category:\n" + ItemUtils.getItemName(category.getItem()))); actions.add(new PlayerRunnable(1) { @Override public void run(final Player p) { Slimefun.runSync(() -> openCategory(profile, category, survival, 1), 1L); } }); } } } if (survival) { for (GuideHandler handler : Slimefun.getGuideHandlers(tier)) { handler.addEntry(texts, tooltips); actions.add(new PlayerRunnable(2) { @Override public void run(Player p) { handler.run(p, survival, true); } }); } } for (int i = 0; i < texts.size(); i = i + 10) { TellRawMessage pageMessage = new TellRawMessage(); pageMessage.addText(ChatColors.color("&b&l- Slimefun Guide -\n\n")); for (int j = i; j < texts.size() && j < i + 10; j++) { pageMessage.addText(texts.get(j) + "\n"); if (tooltips.get(j) != null) pageMessage.addHoverEvent(HoverAction.SHOW_TEXT, tooltips.get(j)); if (actions.get(j) != null) pageMessage.addClickEvent(actions.get(j)); } pages.add(pageMessage); } new CustomBookOverlay("Slimefun Guide", "TheBusyBiscuit", pages.toArray(new TellRawMessage[0])).open(p); } @Override public void openCategory(PlayerProfile profile, Category category, boolean survival, int page) { Player p = profile.getPlayer(); if (p == null) return; if (category.getItems().size() < 250) { if (survival) { profile.getGuideHistory().add(category); } List<TellRawMessage> pages = new ArrayList<>(); List<String> texts = new ArrayList<>(); List<String> tooltips = new ArrayList<>(); List<PlayerRunnable> actions = new ArrayList<>(); for (SlimefunItem item : category.getItems()) { if (Slimefun.hasPermission(p, item, false)) { if (Slimefun.isEnabled(p, item, false)) { if (survival && !Slimefun.hasUnlocked(p, item, false) && item.getResearch() != null) { Research research = item.getResearch(); texts.add(ChatColors.color(shorten("&7", item.getItemName()))); tooltips.add(ChatColors.color(item.getItemName() + "\n&c&lLOCKED\n\n&7Cost: " + (p.getLevel() >= research.getCost() ? "&b": "&4") + research.getCost() + " Levels\n\n&a> Click to unlock")); actions.add(new PlayerRunnable(2) { @Override public void run(final Player p) { if (!Research.isResearching(p)) { if (research.canUnlock(p)) { if (profile.hasUnlocked(research)) { openCategory(profile, category, true, page); } else { if (!(p.getGameMode() == GameMode.CREATIVE && SlimefunPlugin.getSettings().researchesFreeInCreative)) { p.setLevel(p.getLevel() - research.getCost()); } if (p.getGameMode() == GameMode.CREATIVE) { research.unlock(p, true); Slimefun.runSync(() -> openCategory(profile, category, survival, page), 1L); } else { research.unlock(p, false); Slimefun.runSync(() -> openCategory(profile, category, survival, page), 103L); } } } else SlimefunPlugin.getLocal().sendMessage(p, "messages.not-enough-xp", true); } } }); } else { texts.add(ChatColors.color(shorten("&a", item.getItemName()))); StringBuilder tooltip = new StringBuilder(); tooltip.append(item.getItemName()); if (item.getItem().hasItemMeta() && item.getItem().getItemMeta().hasLore()) { for (String line : item.getItem().getItemMeta().getLore()) { tooltip.append("\n" + line); } } tooltip.append(ChatColors.color("\n\n&e&oClick for more Info")); tooltips.add(tooltip.toString()); actions.add(new PlayerRunnable(2) { @Override public void run(Player p) { displayItem(profile, item, true); } }); } } } else { texts.add(ChatColors.color(shorten("&4", ItemUtils.getItemName(item.getItem())))); tooltips.add(ChatColors.color("&cNo Permission!")); actions.add(null); } } for (int i = 0; i < texts.size(); i = i + 10) { TellRawMessage pageMessage = new TellRawMessage(); pageMessage.addText(ChatColors.color("&b&l- Slimefun Guide -\n\n")); for (int j = i; j < texts.size() && j < i + 10; j++) { pageMessage.addText(texts.get(j) + "\n"); if (tooltips.get(j) != null) pageMessage.addHoverEvent(HoverAction.SHOW_TEXT, tooltips.get(j)); if (actions.get(j) != null) pageMessage.addClickEvent(actions.get(j)); } pageMessage.addText("\n"); pageMessage.addText(ChatColors.color("&6\u21E6 &lBack")); pageMessage.addHoverEvent(HoverAction.SHOW_TEXT, ChatColors.color("&eClick to go back to the Category Overview")); pageMessage.addClickEvent(new PlayerRunnable(2) { @Override public void run(final Player p) { openMainMenu(profile, survival, 1); } }); pages.add(pageMessage); } new CustomBookOverlay("Slimefun Guide", "TheBusyBiscuit", pages.toArray(new TellRawMessage[0])).open(p); } else { p.sendMessage(ChatColor.RED + "That Category is too big to open :/"); } } @Override public void openSearch(PlayerProfile profile, String input, boolean survival, boolean addToHistory) { SlimefunGuide.openSearch(profile, input, survival, addToHistory); } @Override public void displayItem(PlayerProfile profile, ItemStack item, boolean addToHistory) { SlimefunGuide.displayItem(profile, item, addToHistory); } @Override public void displayItem(PlayerProfile profile, SlimefunItem item, boolean addToHistory) { SlimefunGuide.displayItem(profile, item, addToHistory); } }
AlexLander123/Slimefun4
src/main/java/io/github/thebusybiscuit/slimefun4/core/guide/BookSlimefunGuide.java
Java
gpl-3.0
10,060
Nautilus ================== Nautilus is a console tool to store informations about a (source) server in a database. [![PHP version](https://badge.fury.io/ph/undeadbrains%2Fnautilus.svg)](https://badge.fury.io/ph/undeadbrains%2Fnautilus) [![GitHub version](https://badge.fury.io/gh/UndeadbrainsDE%2Fnautilus.svg)](https://badge.fury.io/gh/UndeadbrainsDE%2Fnautilus) [![Code Climate](https://codeclimate.com/github/UndeadbrainsDE/nautilus/badges/gpa.svg)](https://codeclimate.com/github/UndeadbrainsDE/nautilus) [![Build Status](https://travis-ci.org/UndeadbrainsDE/nautilus.svg?branch=master)](https://travis-ci.org/UndeadbrainsDE/nautilus) ---------------------------
UndeadbrainsDE/nautilus
readme.md
Markdown
gpl-3.0
672
<?php /** * br – line break. * * The br element represents a line break. * * @author Sergey Baigudin, baigudin@mail.ru * @copyright 2012-2016 Sergey Baigudin * @license http://baigudin.software/license/ * @link http://baigudin.software * @see https://www.w3.org/TR/html-markup/br.html */ namespace DomBuilder\Element; class Br extends \DomBuilder\Core\Element\Single { /** * Constructor. */ function __construct() { parent::__construct(); $this->_tagName('br'); } }
baigudin/PhpDomBuilder.revision.2
DomBuilder/Element/Br.php
PHP
gpl-3.0
520
// **************************************************************************************** /* iDisk - Intel-Hex Disk image Loader - S250317 Disk images loader for the Z80-MBC (HW ref: A041116) NOTE 1: Required IOS S221116 R180217 (or following until otherwise stated) NOTE 2: Required Virtual Disk Module (HW ref: A110417) NOTE 3: When compiling with SDDC the option "--data-loc 0x6000" *MUST* be used. (e.g., sdcc -mz80 --data-loc 0x6000 <input_source.c> -o <output_file.hex>) Compiled with SDDC 3.6.0 */ // **************************************************************************************** #include <stdio.h> // Z80-MBC I/O ports definition __sfr __at 0x09 SELDISK; // Disk emulation I/O (write) __sfr __at 0x0A SELTRACK; __sfr __at 0x0B SELSECT; __sfr __at 0x0C WRITESECT; __sfr __at 0x05 ERRDISK; // Disk emulation I/O (read) __sfr __at 0x06 READSECT; #define dataBuffSize 0x8000 // Input data buffer size #define diskSectors 1024 // Sectors (128 byte) in a disk unsigned char dataBuff[dataBuffSize]; // Input data buffer unsigned int byteCount; // Data bytes counter unsigned int dataBuffIdx; // Index used to write data from buffer to the virtual disk unsigned int lowAddr; unsigned int hiAddr, ii; unsigned long addr; // Current data address unsigned long startAddr; // Starting data address unsigned char magic; // Just4Fun "magic" code :-) unsigned char errFlag; unsigned char writeFlag; unsigned char writeDoneFlag; // Current segment write status (0 = not done, 1 = done) unsigned char writeErrorCode; // Disc write error code (0 = no errors) unsigned char boundFillFlag; unsigned char i, targetDisk; unsigned int sectors; unsigned char segment; // Current EEPROM segment (one segment = 32kB) [0..3] unsigned char D0SegDone[4], D1SegDone[4]; // Status of disks segments ( 0 = untouched, 1 = written) unsigned char firstTrack, lastTrack, track; // [0..31] unsigned char sector, lastSector; // [1..32] char c; char upperCase(unsigned char c) // Change a charcter in upper case if in [a..z] range { if ((c >96) && (c < 123)) c = c - 32; return c; } void printErr(unsigned char errCode) // Print the meaning of an ERRDISK error code // // error code: 0: no errors // 1: data too long to fit in transmit buffer (I2C) // 2: received NACK on transmit of address (I2C) // 3: received NACK on transmit of data (I2C) // 4: other error (I2C) // 8: WRITESECT error (I/O byte counter overrun) // 9: READSECT error (I/O byte counter overrun) // 10: data read error (I2C) // 11: invalid disk number // 12: invalid track number // 13: invalid sector number // 14: virtual disk module not found { if (errCode != 0) { printf("\n\nDisk error %03u: ", errCode); switch (errCode) { case 1: printf("data too long to fit in transmit buffer (I2C)"); break; case 2: printf("received NACK on transmit of address (I2C)"); break; case 3: printf("received NACK on transmit of data (I2C)"); break; case 4: printf("other error (I2C)"); break; case 8: printf("write error (I/O byte counter overrun)"); break; case 9: printf("read error (I/O byte counter overrun)"); break; case 10: printf("data read error (I2C)"); break; case 11: printf("invalid disk number"); break; case 12: printf("invalid track number"); break; case 13: printf("invalid sector number"); break; case 14: printf("virtual disk module not found"); break; default: printf("unknown error"); break; } printf("\n"); } } char getOneChar() // Read one char from the input stream and return it. CR and LF are ignored, anyway CR is echoed with a LF. { char inChar; do { inChar = getchar(); if ((inChar != 13) || (inChar != 11)) putchar(inChar); else if (inChar != 13) { putchar(13); // CR + LF putchar(11); } } while ((inChar == 13) || (inChar == 11)); // Loop until a valid char is read return inChar; } unsigned char readHexByte(unsigned char *byte) // Read an hex byte from the input stream. // Return values: 0 = ok, 1 = syntax error { char inChar; signed char i; *byte = 0; for (i = 1; i >= 0; i--) { inChar = getOneChar(); // Get a char if ((inChar > 96) && (inChar < 103)) inChar = inChar - 32; // a - f to upper case if ((inChar > 47) && (inChar < 58)) inChar = inChar - 48; // 0 - 9 else if ((inChar > 64) && (inChar < 71)) inChar = inChar - 55; // A - F else return 1; // Illegal char: syntax error *byte = *byte | (inChar << (i * 4)); // Byte in binary } return 0; // No errors } unsigned char readOneLine() // Read and parse one intel-hex ASCII record (one input line). // Return values: 0 = data record, 1 = EOF record, 4 = extended linear address record, 9 = Just4Fun "magic" record :-), // 10 = syntax error, 11 = illegal record type, 12 = expected "0000" address in type 04 record, // 13 = checksum error, 14 = illegal starting address, 15 = data address not in sequence, // 16 = data buffer full { unsigned char retValue, byte, recLenght, recType, checksum, sum, i; char inChar; inChar = getOneChar(); if (inChar != ':') return 10; // Read first char = ':' if (readHexByte(&recLenght) > 0) return 10; // Read record lenght sum = recLenght; if (readHexByte(&byte) > 0) return 10; // Read 16 bit address MSB sum = sum + byte; lowAddr = ((unsigned int) byte) << 8; if (readHexByte(&byte) > 0) return 10; // Read 16 bit address LSB sum = sum + byte; lowAddr = lowAddr | byte; if (readHexByte(&recType) > 0) return 10; // Read record type sum = sum + recType; switch (recType) { case 0: // Data record addr = (((unsigned long) hiAddr) << 16 ) | lowAddr; if (byteCount == 0) // First address in the input stream { if ((addr != 0) && (addr != 0x8000) && (addr != 0x10000) && (addr != 0x18000)) return 14; // Verify starting address startAddr = addr; // Save starting address segment = (unsigned char) (addr / 0x8000); // Calculate the EEPROM segment to write } for (i = 0; i < recLenght; i++) // Read the data bytes inside the data record { if (readHexByte(&byte) > 0) return 10; // Read a data byte sum = sum + byte; if ((addr + i) == (startAddr + byteCount)) { if (byteCount >= dataBuffSize) return 16;// Data buffer full dataBuff[byteCount] = byte; byteCount++; } else return 15; // Data address not in sequence } retValue = 0; break; case 1: // EOF record retValue = 1; break; case 4: // Extended linear address record if (lowAddr !=0) return 12; // Expected "0000" address in type 04 record if (readHexByte(&byte) > 0) return 10; // Read 16 bit extended address MSB sum = sum + byte; hiAddr = ((unsigned int) byte) << 8; if (readHexByte(&byte) > 0) return 10; // Read 16 bit extended address LSB i = sum + byte; // Splitted to avoid a strange SDDC "liverange" warning sum = i; hiAddr = hiAddr | byte; retValue = 4; break; case 9: // Just4Fun "magic" record :-) magic = (unsigned char) lowAddr; retValue = 9; break; default: // Illegal record type return 11; } if (readHexByte(&checksum) > 0) return 10; // Read checksum byte sum = 1 + ~sum; // Calculate checksum if (sum != checksum) return 13; // Validate checksum return retValue; } unsigned char verifyDiskSect(unsigned char disk, unsigned char track, unsigned char sector, unsigned int *buffIndex ) // verify a sector into on the given track of the selected virtual disk, comparing with data buffer content. // The index to the first byte to write from data buffer is "dataBuffIdx". // Returns error code (0 = no errors, 1 = do not match). // NOTE: disk [0..1], track [0..31], sector [1..32] { unsigned int ii; unsigned char notEqual = 0; SELDISK = disk; // Disk number SELTRACK = track; // Track LSB SELTRACK = 0; // Track MSB SELSECT = sector; // Sector LSB SELSECT = 0; // Sector MSB for (ii =0; ii < 128; ii++) // Write selected sector { if (READSECT != dataBuff[*buffIndex]) notEqual = 1; (*buffIndex)++; } return notEqual; } unsigned char writeDiskSect(unsigned char disk, unsigned char track, unsigned char sector, unsigned int *buffIndex ) // Write a sector into on the given track of the selected virtual disk. // The index to the first byte to write from data buffer is "dataBuffIdx". // Returns write error code (0 = no errors). // NOTE: disk [0..1], track [0..31], sector [1..32] { unsigned int ii; SELDISK = disk; // Disk number SELTRACK = track; // Track LSB SELTRACK = 0; // Track MSB SELSECT = sector; // Sector LSB SELSECT = 0; // Sector MSB for (ii =0; ii < 128; ii++) // Write selected sector { WRITESECT = dataBuff[*buffIndex]; (*buffIndex)++; } return ERRDISK; } void main() { printf("\n\niDisk - Intel-Hex Disk image Loader - S250317"); for (i = 0; i < 4; i++) D0SegDone[i] = 0; // Initialize disk 0 segments status for (i = 0; i < 4; i++) D1SegDone[i] = 0; // Initialize disk 1 segments status if (ERRDISK == 14) { printf("\n"); printErr(14); printf("\n* Program aborted *\n"); return; } do { for (ii = 0; ii < dataBuffSize; ii++) dataBuff[ii] = 0xe5; // Initialize data buffer byteCount = 0; // Initialize read bytes counter hiAddr = 0; startAddr = 0; magic = 0xff; dataBuffIdx = 0; errFlag = 0; writeFlag = 0; boundFillFlag = 0; writeErrorCode = 0; writeDoneFlag = 0; printf("\n\nDisk segments write status: D0["); for (i = 0; i < 4; i++) { if (D0SegDone[i] == 0) printf("."); else printf("%01u", i); } printf("] - D1["); for (i = 0; i < 4; i++) { if (D1SegDone[i] == 0) printf("."); else printf("%01u", i); } printf("]\n\nWaiting input stream...\n"); do // Read the input intel-hex stream until EOF or an error { i = readOneLine(); printf("\n"); } while ((i != 1) && (i < 10)); if (i > 9) // Error detected reading hex stream { errFlag = 1; printf("\nERROR: "); switch (i) { case 10: printf("syntax error"); break; case 11: printf("illegal record type"); break; case 12: printf("expected address 0000 in type 04 record"); break; case 13: printf("checksum error"); break; case 14: printf("illegal starting address"); break; case 15: printf("data address not in sequence"); break; case 16: printf("data buffer full"); break; } printf("\nPress ESC to continue..."); do c = getchar(); while (c != 27); } else // No errors detected. Print a summary of the received data and ask the target virtual disk // if needed { printf("\nRead bytes count: %u", byteCount); printf("\nEEPROM first addr to write: 0x%05lX", startAddr); printf("\nEEPROM current 32kB segment: %01u", segment); firstTrack = (diskSectors / 128) * segment; // Calculate first track to write printf("\nFirst Track/Sector to write: %02u/01", firstTrack); sectors = byteCount / 128; // Calculate how many contiguous sectors to write if ((byteCount % 128) != 0) // Check if sector filling is needed { sectors++; boundFillFlag = 1; } printf("\nContiguous sectors to write: %03u", sectors); if (sectors > 0) lastTrack = firstTrack + ((sectors - 1) / 32); else lastTrack = firstTrack; printf("\nLast Track/Sector to write: %02u", lastTrack); if (sectors < 2) lastSector = 1; else lastSector = ((sectors - 1) % 32) +1; printf("/%02u", lastSector); printf("\nLast sector boundary fill: "); // Sector boudary fill if (!boundFillFlag) printf("not needed"); else printf("yes"); if (byteCount > 0) { if (magic < 2) targetDisk = magic; else // Ask the target virtual disk { printf("\n\nEnter the target virtual disk [0/1] >"); do { c = getchar(); if ((c == '0') || (c == '1')) putchar(c); targetDisk = c - 48; } while ((c != '0') && (c != '1')); } printf("\nTarget virtual disk: %u", targetDisk); } else printf("\nNothing to do..."); } if ((byteCount > 0) && !errFlag) // Write the received data into the EEPROM { printf("\n\nPress W to write or A to abort [W/A] >"); do c = upperCase(getchar()); while ((c != 'W') && (c != 'A')); putchar(c); if (c == 'W') { printf("\n\n* WARNING * ALL PREVIOUS DATA IN THE TARGET SECTORS WILL BE OVERWRITTEN!"); printf("\n\nAre you sure [Y/N]? >"); do c = upperCase(getchar()); while ((c != 'Y') && (c != 'N')); putchar(c); if (c == 'Y') writeFlag = 1; } if (!writeFlag) printf("\nWrite operation cancelled!"); else { track = firstTrack; sector = 1; for (ii = 0; ii < sectors; ii++) // Write a sector to virtualdisk { printf("\n#%03u: writing... ", ii+1); printf(" Disk: %01u", targetDisk); printf(" - Track: %02u", track); printf(" - Sector: %02u", sector); writeErrorCode = writeDiskSect(targetDisk, track, sector, &dataBuffIdx); if (writeErrorCode > 0) break; // Abort write operation if an error occurred if (sector < 32) sector++; else { sector = 1; track++; } } printErr(writeErrorCode); // Print write error (if any) if (writeErrorCode > 0) printf("\n* WRITE ABORTED! *"); } } // Verify the written data if no write error occurred if ((writeErrorCode == 0) && writeFlag) { dataBuffIdx = 0; track = firstTrack; sector = 1; writeDoneFlag = 1; printf("\n"); for (ii = 0; ii < sectors; ii++) // Verify a sector { printf("\n#%03u: verifying...", ii+1); printf(" Disk: %01u", targetDisk); printf(" - Track: %02u", track); printf(" - Sector: %02u", sector); if (verifyDiskSect(targetDisk, track, sector, &dataBuffIdx)) // Abort verify on error and print a message { printf("\n\n* FOUND MISMATCH - VERIFY FAILED! *\n"); writeDoneFlag = 0; break; } else printf(" -> OK"); if (sector < 32) sector++; else { sector = 1; track++; } } if (writeDoneFlag) {if (targetDisk == 0) D0SegDone[segment] = 1; else D1SegDone[segment] = 1;} } } while (1); }
SuperFabius/Z80-MBC
iDisk - S250317.c
C
gpl-3.0
18,728
package cc.lovesq.controller; import cc.lovesq.query.PagerQuery; /** * @author YHJ create at 2014年3月4日 上午11:08:08 * @Described:基础控制层 * @ClassNmae com.aliyun.houyi.compass.v2.core.controller.BaseController */ public class BaseController { protected int totalCounts;//总记录条数 protected int pageSize;//每页大小 protected int totalPages;//总页数 protected int pageNum; //当前的页 protected boolean showFirst; //是否显示首页 protected boolean showLast; //是否显示尾页 protected boolean showNext; //是否显示下一页 protected boolean showPrevious; //是否显示上一页 /** * 初始化分页信息 * * @Author YHJ create at 2014年3月4日 上午11:08:59 */ protected void initPages(PagerQuery pagerQuery, int totalCounts) { this.pageSize = pagerQuery.getPageSize(); this.pageNum = pagerQuery.getPageNum(); this.totalCounts = totalCounts; totalPages = (totalCounts % pageSize == 0) ? totalCounts / pageSize : (totalCounts / pageSize + 1); if (totalPages > 0) { //当totalPages <=0时 表明没有任何记录 所有上一页 下一页 首页 末页标签取默认值 不显示 pageNum = (pageNum <= 0) ? 1 : pageNum; pageNum = (pageNum > totalPages) ? totalPages : pageNum; showFirst = (pageNum == 1) ? false : true; showLast = (pageNum == totalPages) ? false : true; showPrevious = (pageNum == 1) ? false : true; showNext = (pageNum == totalPages) ? false : true; pagerQuery.setFirstRow(pageSize * (pageNum - 1)); } else { pageNum = 0; } } public int getTotalCounts() { return totalCounts; } public void setTotalCounts(int totalCounts) { this.totalCounts = totalCounts; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public boolean isShowFirst() { return showFirst; } public void setShowFirst(boolean showFirst) { this.showFirst = showFirst; } public boolean isShowLast() { return showLast; } public void setShowLast(boolean showLast) { this.showLast = showLast; } public boolean isShowNext() { return showNext; } public void setShowNext(boolean showNext) { this.showNext = showNext; } public boolean isShowPrevious() { return showPrevious; } public void setShowPrevious(boolean showPrevious) { this.showPrevious = showPrevious; } }
shuqin/ALLIN
src/main/java/cc/lovesq/controller/BaseController.java
Java
gpl-3.0
3,155
# Copyright (C) 2001 Steve Howell # You must read the file called INFO.txt before distributing this code. # --- # Worlds for Karel are defined with simple text files that we parse out # in this module. See the worlds folder for examples. from world import NORTH,SOUTH,EAST,WEST from utils import trace_error import re,gettext # Use this to be able to extract strings for translation by pygettext.py try: #print "current _", _ old_ = _ except Exception,info: print >> sys.stderr, "in gvrparser locale switch:\n",info _ = gettext.gettext KEYWORDS = ( _('ROBOT'), _('WALL'), _('BEEPERS'), _('SIZE')) DIRECTIONS = (NORTH,SOUTH,EAST,WEST) ####################### Start I18N part ##################################### # Now we install a gettext file in the builtin namespace # If this fails the bogus '_()' function is used and we end up with a english - english # look-up table :-( # A possible solution would be to test for locales but i think it won't matter much in speed. _ = old_ #print _ # get a list with the translated strings trans_commands, org_commands = [],[] words = KEYWORDS for i in words: trans_commands.append(_(i)) org_commands.append(i) # this is the english one # With this we build a look-up dictionary that is used in the Program class. # The look-up dict: {'beweeg':'move','rechtsaf':turnright',....} # the keys are the gettext strings and the vals are the original names. lookup_dict = {} for k,v in map(None,trans_commands,org_commands): lookup_dict[k] = v lookup_dir_dict = {_('N'):'N',_('S'):'S',_('E'):'E',_('W'):'W'}# class WorldMapException(Exception): def __init__(self, line, str): self.line = line self.str = str def __str__(self): return self.str def checkDirection(line, dir): if dir not in lookup_dir_dict.values(): raise WorldMapException(line, _("In line %d:\n%s is not a valid direction -- use N, S, E, or W") % (line, dir)) def removeComment(line): foundComment = False for i in range(len(line)): if line[i] == "#": foundComment = True break if foundComment: return line[:i] else: return line def readWorld(lines, world): definedRobot = 0 useGuido = False linenumber = 0 worldSize = None #print "worldMap lines",lines for line in lines: linenumber += 1 try: if re.search("\S", line) and not re.match("\s*#", line): line = removeComment(line) tokens = line.split() tokens = [x.upper() for x in tokens] keyword = tokens[0] if lookup_dict.has_key(keyword): keyword = lookup_dict[keyword] dir = tokens[3] if lookup_dir_dict.has_key(dir): dir = lookup_dir_dict[dir] tokens[3] = dir if keyword ==_('WALL') or keyword == 'WALL': tokens[0] = keyword #print "wall",tokens checkDirection(linenumber, dir) #print "tokens",tokens world.setWall(*tokens[1:]) elif keyword == _('ROBOT') or keyword == 'ROBOT': if definedRobot: raise WorldMapException(linenumber, _('You may only have one robot definition.')) definedRobot = 1 tokens = [x.upper() for x in tokens] if len(tokens) == 5: x, y, dir, numBeepers = tokens[1:] else: x, y, dir = tokens[1:] numBeepers = 0 robotX, robotY = int(x), int(y) world.positionRobot(robotX, robotY, dir) if numBeepers == "unlimited": world.unlimitedBeepers = True numBeepers = 0 world.setRobotBeepers(int(numBeepers)) elif keyword == _('BEEPERS') or keyword == 'BEEPERS': x, y, numBeepers = tokens[1:] world.setBeepers(int(x), int(y), int(numBeepers)) elif keyword == 'BDFL': useGuido = True elif keyword == _('SIZE') or keyword == 'SIZE': if worldSize: raise WorldMapException(linenumber, _('You may only have one size statement')) try: avenues, streets = [int(coord) for coord in tokens[1:]] except ValueError: raise WorldMapException(linenumber, _('Size statement should have 2 integers')) if avenues < 7 or streets < 7: raise WorldMapException(linenumber, _('Size coordinates must be at least 7')) worldSize = (avenues, streets) else: raise WorldMapException(linenumber,_("Cannot understand: %s") % line) except Exception,info: info = _("Error in line %s:\n%s\nCheck your world file for syntax errors") % (linenumber,line) raise WorldMapException(linenumber, info) if not definedRobot: raise WorldMapException(linenumber, _("The world map seems to be missing information.")) world.useGuido = useGuido return worldSize
cristian99garcia/guido-van-robot-activity
worldMap.py
Python
gpl-3.0
5,535
/* Grammatical Evolution in Java Release: GEVA-v1.2.zip Copyright (C) 2008 Michael O'Neill, Erik Hemberg, Anthony Brabazon, Conor Gilligan Contributors Patrick Middleburgh, Eliott Bartley, Jonathan Hugosson, Jeff Wrigh Separate licences for asm, bsf, antlr, groovy, jscheme, commons-logging, jsci is included in the lib folder. Separate licence for rieps is included in src/com folder. This licence refers to GEVA-v1.2. This software is distributed under the terms of the GNU General Public License. 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 geva.FitnessEvaluation.SantaFeAntTrail; import geva.FitnessEvaluation.SantaFeAntTrail.SantaFeAntTrailInterpreter; import geva.FitnessEvaluation.SantaFeAntTrail.Trail; import geva.Helpers.IndividualMaker; import geva.Individuals.GEIndividual; import geva.Individuals.Phenotype; import geva.Mapper.Symbol; import geva.Util.Enums; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author erikhemberg */ public class SantaFeAntTrailInterpreterTest { public SantaFeAntTrailInterpreterTest() { } @Before public void setUp() { } @Test public void testGetTrail() { System.out.println("* SantaFeAntTrailInterpreter: getTrail"); //SFA SantaFeAntTrailInterpreter instance = new SantaFeAntTrailInterpreter(); String trail_type = "geva.FitnessEvaluation.SantaFeAntTrail.Trail"; Trail trail = instance.getTrail(trail_type); assertEquals(true, trail.getClass().getName().equals(trail_type)); //SM instance = new SantaFeAntTrailInterpreter(); trail_type = "geva.FitnessEvaluation.SantaFeAntTrail.SanMateoTrail"; trail = instance.getTrail(trail_type); assertEquals(true, trail.getClass().getName().equals(trail_type)); //LA instance = new SantaFeAntTrailInterpreter(); trail_type = "geva.FitnessEvaluation.SantaFeAntTrail.LosAltosTrail"; trail = instance.getTrail(trail_type); assertEquals(true, trail.getClass().getName().equals(trail_type)); //Exception instance = new SantaFeAntTrailInterpreter(); trail_type = "geva.FitnessEvaluation.SantaFeAntTrail.Grr"; trail = null; try { trail = instance.getTrail(trail_type); } catch(IllegalArgumentException e) { assertTrue(true); } assertEquals(true, trail == null); } /** * Test of getFitness method, of class SantaFeAntTrailInterpreter. */ @Test public void testGetFitness() { System.out.println("*SantaFeAntTrailInterpreter: getFitness"); GEIndividual individual = IndividualMaker.makeIndividual(); Phenotype p = IndividualMaker.getPhenotype("move();"); individual.setPhenotype(p); SantaFeAntTrailInterpreter instance = new SantaFeAntTrailInterpreter(); instance.setTrail_type("geva.FitnessEvaluation.SantaFeAntTrail.Trail"); instance.getFitness(individual); assertEquals((int) individual.getFitness().getDouble(), 86); individual = IndividualMaker.makeIndividual(); p.clear(); p.add(new Symbol(SantaFeAntTrailInterpreter.IF,Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.IF, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.MOVE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.LEFT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.RIGHT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); individual.setPhenotype(p); instance = new SantaFeAntTrailInterpreter(); instance.setTrail_type("geva.FitnessEvaluation.SantaFeAntTrail.Trail"); instance.getFitness(individual); assertEquals((int) individual.getFitness().getDouble(), 78); individual = IndividualMaker.makeIndividual(); p.clear(); p.add(new Symbol(SantaFeAntTrailInterpreter.IF,Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.MOVE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.LEFT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.MOVE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.RIGHT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); individual.setPhenotype(p); instance = new SantaFeAntTrailInterpreter(); instance.setTrail_type("geva.FitnessEvaluation.SantaFeAntTrail.Trail"); instance.getFitness(individual); assertEquals((int) individual.getFitness().getDouble(), 72); individual = IndividualMaker.makeIndividual(); p.clear(); p.add(new Symbol(SantaFeAntTrailInterpreter.IF,Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.MOVE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.IF,Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.RIGHT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.LEFT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.RIGHT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.IF,Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.RIGHT, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.ELSE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.MOVE, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); p.add(new Symbol(SantaFeAntTrailInterpreter.END_IF, Enums.SymbolType.TSymbol)); individual.setPhenotype(p); instance = new SantaFeAntTrailInterpreter(); instance.setTrail_type("geva.FitnessEvaluation.SantaFeAntTrail.Trail"); instance.getFitness(individual); assertEquals((int) individual.getFitness().getDouble(), 85); } }
cdorrat/geva-clj
geva-core/src/test/java/geva/FitnessEvaluation/SantaFeAntTrail/SantaFeAntTrailInterpreterTest.java
Java
gpl-3.0
7,485
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PracticeConsole { public class InternalClass { internal int owais; void functionname () { } } public class owaisshahab { static void MainMethod() { } } }
owaisshahab1/Practice
PracticeConsole/General Concepts/Internal.cs
C#
gpl-3.0
381
#include "common.h" #define DEBUG_FLAG SEAFILE_DEBUG_HTTP #include "log.h" #include <getopt.h> #include <fcntl.h> #include <event.h> #include <evhtp.h> #include <json-glib/json-glib.h> #include <pthread.h> #include <ccnet.h> #include "seafile-object.h" #include "seafile.h" #include "utils.h" #include "seafile-session.h" #include "httpserver.h" #include "upload-file.h" #define SEAF_HTTP_RES_BADFILENAME 440 #define SEAF_HTTP_RES_EXISTS 441 #define SEAF_HTTP_RES_NOT_EXISTS 441 #define SEAF_HTTP_RES_TOOLARGE 442 #define SEAF_HTTP_RES_NOQUOTA 443 enum RecvState { RECV_INIT, RECV_HEADERS, RECV_CONTENT, RECV_ERROR, }; enum UploadError { ERROR_FILENAME, ERROR_EXISTS, ERROR_NOT_EXIST, ERROR_SIZE, ERROR_QUOTA, ERROR_RECV, ERROR_INTERNAL, }; typedef struct Progress { gint64 uploaded; gint64 size; } Progress; typedef struct RecvFSM { int state; char *repo_id; char *user; char *boundary; /* boundary of multipart form-data. */ char *input_name; /* input name of the current form field. */ evbuf_t *line; /* buffer for a line */ GHashTable *form_kvs; /* key/value of form fields */ GList *filenames; /* uploaded file names */ GList *files; /* paths for completely uploaded tmp files. */ gboolean recved_crlf; /* Did we recv a CRLF when write out the last line? */ char *file_name; char *tmp_file; int fd; GList *tmp_files; /* tmp files for each uploading file */ /* For upload progress. */ char *progress_id; Progress *progress; } RecvFSM; #define MAX_CONTENT_LINE 10240 static GHashTable *upload_progress; static pthread_mutex_t pg_lock; /* IE8 will set filename to the full path of the uploaded file. * So we need to strip out the basename from it. */ static char * get_basename (const char *path) { int i = strlen(path) - 1; while (i >= 0) { if (path[i] == '/' || path[i] == '\\') break; --i; } if (i < 0) return g_strdup(path); return g_strdup(&path[i+1]); } static void redirect_to_upload_error (evhtp_request_t *req, const char *repo_id, const char *parent_dir, const char *filename, int error_code) { char *seahub_url, *escaped_path, *escaped_fn = NULL; char url[1024]; seahub_url = seaf->session->base.service_url; escaped_path = g_uri_escape_string (parent_dir, NULL, FALSE); if (filename) { escaped_fn = g_uri_escape_string (filename, NULL, FALSE); snprintf(url, 1024, "%s/repo/upload_error/%s?p=%s&fn=%s&err=%d", seahub_url, repo_id, escaped_path, escaped_fn, error_code); } else { snprintf(url, 1024, "%s/repo/upload_error/%s?p=%s&err=%d", seahub_url, repo_id, escaped_path, error_code); } g_free (escaped_path); g_free (escaped_fn); evhtp_headers_add_header(req->headers_out, evhtp_header_new("Location", url, 1, 1)); evhtp_headers_add_header(req->headers_out, evhtp_header_new("Content-Length", "0", 1, 1)); evhtp_send_reply(req, EVHTP_RES_SEEOTHER); } static void redirect_to_update_error (evhtp_request_t *req, const char *repo_id, const char *target_file, int error_code) { char *seahub_url, *escaped_path; char url[1024]; seahub_url = seaf->session->base.service_url; escaped_path = g_uri_escape_string (target_file, NULL, FALSE); snprintf(url, 1024, "%s/repo/update_error/%s?p=%s&err=%d", seahub_url, repo_id, escaped_path, error_code); g_free (escaped_path); evhtp_headers_add_header(req->headers_out, evhtp_header_new("Location", url, 1, 1)); evhtp_headers_add_header(req->headers_out, evhtp_header_new("Content-Length", "0", 1, 1)); evhtp_send_reply(req, EVHTP_RES_SEEOTHER); } static void redirect_to_success_page (evhtp_request_t *req, const char *repo_id, const char *parent_dir) { char *seahub_url, *escaped_path; char url[1024]; seahub_url = seaf->session->base.service_url; escaped_path = g_uri_escape_string (parent_dir, NULL, FALSE); snprintf(url, 1024, "%s/repo/%s?p=%s", seahub_url, repo_id, escaped_path); g_free (escaped_path); evhtp_headers_add_header(req->headers_out, evhtp_header_new("Location", url, 1, 1)); /* Firefox expects Content-Length header. */ evhtp_headers_add_header(req->headers_out, evhtp_header_new("Content-Length", "0", 1, 1)); evhtp_send_reply(req, EVHTP_RES_SEEOTHER); } static gboolean check_tmp_file_list (GList *tmp_files, int *error_code) { GList *ptr; char *tmp_file; SeafStat st; gint64 total_size = 0; for (ptr = tmp_files; ptr; ptr = ptr->next) { tmp_file = ptr->data; if (seaf_stat (tmp_file, &st) < 0) { seaf_warning ("[upload] Failed to stat temp file %s.\n", tmp_file); *error_code = ERROR_RECV; return FALSE; } total_size += (gint64)st.st_size; } if (total_size > seaf->max_upload_size) { seaf_warning ("[upload] File size is too large.\n"); *error_code = ERROR_SIZE; return FALSE; } return TRUE; } static char * file_list_to_json (GList *files) { JsonNode *root; JsonArray *array; GList *ptr; char *file; JsonGenerator *gen; char *json_data; gsize len; root = json_node_new (JSON_NODE_ARRAY); array = json_array_new (); for (ptr = files; ptr; ptr = ptr->next) { file = ptr->data; json_array_add_string_element (array, file); } json_node_set_array (root, array); gen = json_generator_new (); json_generator_set_root (gen, root); json_data = json_generator_to_data (gen, &len); json_node_free (root); g_object_unref (gen); return json_data; } static void upload_cb(evhtp_request_t *req, void *arg) { RecvFSM *fsm = arg; SearpcClient *rpc_client = NULL; char *parent_dir; GError *error = NULL; int error_code = ERROR_INTERNAL; char *err_file = NULL; char *filenames_json, *tmp_files_json; /* After upload_headers_cb() returns an error, libevhtp may still * receive data from the web browser and call into this cb. * In this case fsm will be NULL. */ if (!fsm || fsm->state == RECV_ERROR) return; if (!fsm->files) { seaf_warning ("[upload] No file uploaded.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } parent_dir = g_hash_table_lookup (fsm->form_kvs, "parent_dir"); if (!parent_dir) { seaf_warning ("[upload] No parent dir given.\n"); evbuffer_add_printf(req->buffer_out, "Invalid URL.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } if (!check_tmp_file_list (fsm->files, &error_code)) goto error; rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool, NULL, "seafserv-threaded-rpcserver"); if (seafile_check_quota (rpc_client, fsm->repo_id, NULL) < 0) { seaf_warning ("[upload] Out of quota.\n"); error_code = ERROR_QUOTA; goto error; } filenames_json = file_list_to_json (fsm->filenames); tmp_files_json = file_list_to_json (fsm->files); seafile_post_multi_files (rpc_client, fsm->repo_id, parent_dir, filenames_json, tmp_files_json, fsm->user, &error); g_free (filenames_json); g_free (tmp_files_json); if (error) { if (error->code == POST_FILE_ERR_FILENAME) { error_code = ERROR_FILENAME; err_file = g_strdup(error->message); } g_clear_error (&error); goto error; } ccnet_rpc_client_free (rpc_client); /* Redirect to repo dir page after upload finishes. */ redirect_to_success_page (req, fsm->repo_id, parent_dir); return; error: if (rpc_client) ccnet_rpc_client_free (rpc_client); redirect_to_upload_error (req, fsm->repo_id, parent_dir, err_file, error_code); g_free (err_file); } static void upload_api_cb(evhtp_request_t *req, void *arg) { RecvFSM *fsm = arg; SearpcClient *rpc_client = NULL; char *parent_dir; GError *error = NULL; int error_code = ERROR_INTERNAL; char *filenames_json, *tmp_files_json; /* After upload_headers_cb() returns an error, libevhtp may still * receive data from the web browser and call into this cb. * In this case fsm will be NULL. */ if (!fsm || fsm->state == RECV_ERROR) return; if (!fsm->files) { seaf_warning ("[upload] No file uploaded.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } parent_dir = g_hash_table_lookup (fsm->form_kvs, "parent_dir"); if (!parent_dir) { seaf_warning ("[upload] No parent dir given.\n"); evbuffer_add_printf(req->buffer_out, "Invalid URL.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } if (!check_tmp_file_list (fsm->files, &error_code)) goto error; rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool, NULL, "seafserv-threaded-rpcserver"); if (seafile_check_quota (rpc_client, fsm->repo_id, NULL) < 0) { seaf_warning ("[upload] Out of quota.\n"); error_code = ERROR_QUOTA; goto error; } filenames_json = file_list_to_json (fsm->filenames); tmp_files_json = file_list_to_json (fsm->files); seafile_post_multi_files (rpc_client, fsm->repo_id, parent_dir, filenames_json, tmp_files_json, fsm->user, &error); g_free (filenames_json); g_free (tmp_files_json); if (error) { if (error->code == POST_FILE_ERR_FILENAME) { error_code = ERROR_FILENAME; seaf_warning ("[upload] Bad filename.\n"); } g_clear_error (&error); goto error; } ccnet_rpc_client_free (rpc_client); evhtp_send_reply (req, EVHTP_RES_OK); return; error: if (rpc_client) ccnet_rpc_client_free (rpc_client); switch (error_code) { case ERROR_FILENAME: evbuffer_add_printf(req->buffer_out, "Invalid filename.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_BADFILENAME); break; case ERROR_EXISTS: evbuffer_add_printf(req->buffer_out, "File already exists.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_EXISTS); break; case ERROR_SIZE: evbuffer_add_printf(req->buffer_out, "File size is too large.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_TOOLARGE); break; case ERROR_QUOTA: evbuffer_add_printf(req->buffer_out, "Out of quota.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_NOQUOTA); break; case ERROR_RECV: case ERROR_INTERNAL: evhtp_send_reply (req, EVHTP_RES_SERVERR); break; } } static void update_cb(evhtp_request_t *req, void *arg) { RecvFSM *fsm = arg; SearpcClient *rpc_client = NULL; char *target_file, *parent_dir = NULL, *filename = NULL; const char *head_id = NULL; GError *error = NULL; int error_code = ERROR_INTERNAL; if (!fsm || fsm->state == RECV_ERROR) return; if (!fsm->files) { seaf_warning ("[update] No file uploaded.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } target_file = g_hash_table_lookup (fsm->form_kvs, "target_file"); if (!target_file) { seaf_warning ("[Update] No target file given.\n"); evbuffer_add_printf(req->buffer_out, "Invalid URL.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } parent_dir = g_path_get_dirname (target_file); filename = g_path_get_basename (target_file); if (!check_tmp_file_list (fsm->files, &error_code)) goto error; head_id = evhtp_kv_find (req->uri->query, "head"); rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool, NULL, "seafserv-threaded-rpcserver"); if (seafile_check_quota (rpc_client, fsm->repo_id, NULL) < 0) { seaf_warning ("[update] Out of quota.\n"); error_code = ERROR_QUOTA; goto error; } seafile_put_file (rpc_client, fsm->repo_id, (char *)(fsm->files->data), parent_dir, filename, fsm->user, head_id, &error); if (error) { if (g_strcmp0 (error->message, "file does not exist") == 0) { error_code = ERROR_NOT_EXIST; } if (error->message) seaf_warning ("%s\n", error->message); g_clear_error (&error); goto error; } ccnet_rpc_client_free (rpc_client); /* Redirect to repo dir page after upload finishes. */ redirect_to_success_page (req, fsm->repo_id, parent_dir); g_free (parent_dir); g_free (filename); return; error: if (rpc_client) ccnet_rpc_client_free (rpc_client); redirect_to_update_error (req, fsm->repo_id, target_file, error_code); g_free (parent_dir); g_free (filename); } static void update_api_cb(evhtp_request_t *req, void *arg) { RecvFSM *fsm = arg; SearpcClient *rpc_client = NULL; char *target_file, *parent_dir = NULL, *filename = NULL; const char *head_id = NULL; GError *error = NULL; int error_code = ERROR_INTERNAL; char *new_file_id = NULL; if (!fsm || fsm->state == RECV_ERROR) return; if (!fsm->files) { seaf_warning ("[update] No file uploaded.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } target_file = g_hash_table_lookup (fsm->form_kvs, "target_file"); if (!target_file) { seaf_warning ("[Update] No target file given.\n"); evbuffer_add_printf(req->buffer_out, "Invalid URL.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } parent_dir = g_path_get_dirname (target_file); filename = g_path_get_basename (target_file); if (!check_tmp_file_list (fsm->files, &error_code)) goto error; head_id = evhtp_kv_find (req->uri->query, "head"); rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool, NULL, "seafserv-threaded-rpcserver"); if (seafile_check_quota (rpc_client, fsm->repo_id, NULL) < 0) { seaf_warning ("[update] Out of quota.\n"); error_code = ERROR_QUOTA; goto error; } new_file_id = seafile_put_file (rpc_client, fsm->repo_id, (char *)(fsm->files->data), parent_dir, filename, fsm->user, head_id, &error); g_free (parent_dir); g_free (filename); if (error) { if (g_strcmp0 (error->message, "file does not exist") == 0) { error_code = ERROR_NOT_EXIST; } if (error->message) seaf_warning ("%s\n", error->message); g_clear_error (&error); goto error; } ccnet_rpc_client_free (rpc_client); /* Send back the new file id, so that the mobile client can update local cache */ evbuffer_add(req->buffer_out, new_file_id, strlen(new_file_id)); evhtp_send_reply (req, EVHTP_RES_OK); g_free (new_file_id); return; error: if (rpc_client) ccnet_rpc_client_free (rpc_client); switch (error_code) { case ERROR_FILENAME: evbuffer_add_printf(req->buffer_out, "Invalid filename.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_BADFILENAME); break; case ERROR_EXISTS: evbuffer_add_printf(req->buffer_out, "File already exists.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_EXISTS); break; case ERROR_SIZE: evbuffer_add_printf(req->buffer_out, "File size is too large.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_TOOLARGE); break; case ERROR_QUOTA: evbuffer_add_printf(req->buffer_out, "Out of quota.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_NOQUOTA); break; case ERROR_NOT_EXIST: evbuffer_add_printf(req->buffer_out, "File does not exist.\n"); evhtp_send_reply (req, SEAF_HTTP_RES_NOT_EXISTS); break; case ERROR_RECV: case ERROR_INTERNAL: default: evhtp_send_reply (req, EVHTP_RES_SERVERR); break; } } static evhtp_res upload_finish_cb (evhtp_request_t *req, void *arg) { RecvFSM *fsm = arg; GList *ptr; if (!fsm) return EVHTP_RES_OK; /* Clean up FSM struct no matter upload succeed or not. */ g_free (fsm->repo_id); g_free (fsm->user); g_free (fsm->boundary); g_free (fsm->input_name); g_hash_table_destroy (fsm->form_kvs); g_free (fsm->file_name); if (fsm->tmp_file) { close (fsm->fd); } g_free (fsm->tmp_file); for (ptr = fsm->tmp_files; ptr; ptr = ptr->next) g_unlink ((char *)(ptr->data)); string_list_free (fsm->tmp_files); string_list_free (fsm->filenames); string_list_free (fsm->files); evbuffer_free (fsm->line); if (fsm->progress_id) { pthread_mutex_lock (&pg_lock); g_hash_table_remove (upload_progress, fsm->progress_id); pthread_mutex_unlock (&pg_lock); /* fsm->progress has been free'd by g_hash_table_remove(). */ g_free (fsm->progress_id); } g_free (fsm); return EVHTP_RES_OK; } static char * get_mime_header_param_value (const char *param) { char *first_quote, *last_quote; char *value; first_quote = strchr (param, '\"'); last_quote = strrchr (param, '\"'); if (!first_quote || !last_quote || first_quote == last_quote) { seaf_warning ("[upload] Invalid mime param %s.\n", param); return NULL; } value = g_strndup (first_quote + 1, last_quote - first_quote - 1); return value; } static int parse_mime_header (char *header, RecvFSM *fsm) { char *colon; char **params, **p; colon = strchr (header, ':'); if (!colon) { seaf_warning ("[upload] bad mime header format.\n"); return -1; } *colon = 0; if (strcmp (header, "Content-Disposition") == 0) { params = g_strsplit (colon + 1, ";", 0); for (p = params; *p != NULL; ++p) *p = g_strstrip (*p); if (!params || g_strv_length (params) < 2) { seaf_warning ("[upload] Too little params for mime header.\n"); g_strfreev (params); return -1; } if (strcasecmp (params[0], "form-data") != 0) { seaf_warning ("[upload] Invalid Content-Disposition\n"); g_strfreev (params); return -1; } for (p = params; *p != NULL; ++p) { if (strncasecmp (*p, "name", strlen("name")) == 0) { fsm->input_name = get_mime_header_param_value (*p); break; } } if (!fsm->input_name) { seaf_warning ("[upload] No input-name given.\n"); g_strfreev (params); return -1; } if (strcmp (fsm->input_name, "file") == 0) { for (p = params; *p != NULL; ++p) { if (strncasecmp (*p, "filename", strlen("filename")) == 0) { fsm->file_name = get_mime_header_param_value (*p); break; } } if (!fsm->file_name) { seaf_warning ("[upload] No filename given.\n"); g_strfreev (params); return -1; } } g_strfreev (params); } return 0; } static int open_temp_file (RecvFSM *fsm) { GString *temp_file = g_string_new (NULL); g_string_printf (temp_file, "%s/%sXXXXXX", seaf->http_temp_dir, get_basename(fsm->file_name)); fsm->fd = g_mkstemp (temp_file->str); if (fsm->fd < 0) { g_string_free (temp_file, TRUE); return -1; } fsm->tmp_file = g_string_free (temp_file, FALSE); /* For clean up later. */ fsm->tmp_files = g_list_prepend (fsm->tmp_files, g_strdup(fsm->tmp_file)); return 0; } static evhtp_res recv_form_field (RecvFSM *fsm, gboolean *no_line) { char *line; size_t len; *no_line = FALSE; line = evbuffer_readln (fsm->line, &len, EVBUFFER_EOL_CRLF_STRICT); if (line != NULL) { if (strstr (line, fsm->boundary) != NULL) { seaf_debug ("[upload] form field ends.\n"); g_free (fsm->input_name); fsm->input_name = NULL; fsm->state = RECV_HEADERS; } else { seaf_debug ("[upload] form field is %s.\n", line); g_hash_table_insert (fsm->form_kvs, g_strdup(fsm->input_name), g_strdup(line)); } free (line); } else { *no_line = TRUE; } return EVHTP_RES_OK; } static void add_uploaded_file (RecvFSM *fsm) { fsm->filenames = g_list_prepend (fsm->filenames, get_basename(fsm->file_name)); fsm->files = g_list_prepend (fsm->files, g_strdup(fsm->tmp_file)); g_free (fsm->file_name); g_free (fsm->tmp_file); close (fsm->fd); fsm->file_name = NULL; fsm->tmp_file = NULL; fsm->recved_crlf = FALSE; } static evhtp_res recv_file_data (RecvFSM *fsm, gboolean *no_line) { char *line; size_t len; *no_line = FALSE; line = evbuffer_readln (fsm->line, &len, EVBUFFER_EOL_CRLF_STRICT); if (!line) { /* If we haven't read an entire line, but the line * buffer gets too long, flush the content to file. * It should be safe to assume the boundary line is * no longer than 10240 bytes. */ if (evbuffer_get_length (fsm->line) >= MAX_CONTENT_LINE) { seaf_debug ("[upload] recv file data %d bytes.\n", evbuffer_get_length(fsm->line)); if (fsm->recved_crlf) { if (writen (fsm->fd, "\r\n", 2) < 0) { seaf_warning ("[upload] Failed to write temp file: %s.\n", strerror(errno)); return EVHTP_RES_SERVERR; } } size_t size = evbuffer_get_length (fsm->line); char *buf = g_new (char, size); evbuffer_remove (fsm->line, buf, size); if (writen (fsm->fd, buf, size) < 0) { seaf_warning ("[upload] Failed to write temp file: %s.\n", strerror(errno)); g_free (buf); return EVHTP_RES_SERVERR; } g_free (buf); fsm->recved_crlf = FALSE; } *no_line = TRUE; } else if (strstr (line, fsm->boundary) != NULL) { seaf_debug ("[upload] file data ends.\n"); add_uploaded_file (fsm); g_free (fsm->input_name); fsm->input_name = NULL; fsm->state = RECV_HEADERS; free (line); } else { seaf_debug ("[upload] recv file data %d bytes.\n", len + 2); if (fsm->recved_crlf) { if (writen (fsm->fd, "\r\n", 2) < 0) { seaf_warning ("[upload] Failed to write temp file: %s.\n", strerror(errno)); return EVHTP_RES_SERVERR; } } if (writen (fsm->fd, line, len) < 0) { seaf_warning ("[upload] Failed to write temp file: %s.\n", strerror(errno)); free (line); return EVHTP_RES_SERVERR; } free (line); fsm->recved_crlf = TRUE; } return EVHTP_RES_OK; } /* Example multipart form-data request content format: --AaB03x Content-Disposition: form-data; name="submit-name" Larry --AaB03x Content-Disposition: form-data; name="file"; filename="file1.txt" Content-Type: text/plain ... contents of file1.txt ... --AaB03x-- */ static evhtp_res upload_read_cb (evhtp_request_t *req, evbuf_t *buf, void *arg) { RecvFSM *fsm = arg; char *line; size_t len; gboolean no_line = FALSE; int res = EVHTP_RES_OK; if (fsm->state == RECV_ERROR) return EVHTP_RES_OK; /* Update upload progress. */ if (fsm->progress) { fsm->progress->uploaded += (gint64)evbuffer_get_length(buf); seaf_debug ("progress: %lld/%lld\n", fsm->progress->uploaded, fsm->progress->size); } evbuffer_add_buffer (fsm->line, buf); /* Drain the buffer so that evhtp don't copy it to another buffer * after this callback returns. */ evbuffer_drain (buf, evbuffer_get_length (buf)); while (!no_line) { switch (fsm->state) { case RECV_INIT: line = evbuffer_readln (fsm->line, &len, EVBUFFER_EOL_CRLF_STRICT); if (line != NULL) { seaf_debug ("[upload] boundary line: %s.\n", line); if (!strstr (line, fsm->boundary)) { seaf_warning ("[upload] no boundary found in the first line.\n"); free (line); res = EVHTP_RES_BADREQ; goto out; } else { fsm->state = RECV_HEADERS; free (line); } } else { no_line = TRUE; } break; case RECV_HEADERS: line = evbuffer_readln (fsm->line, &len, EVBUFFER_EOL_CRLF_STRICT); if (line != NULL) { seaf_debug ("[upload] mime header line: %s.\n", line); if (len == 0) { /* Read an blank line, headers end. */ free (line); if (g_strcmp0 (fsm->input_name, "file") == 0) { if (open_temp_file (fsm) < 0) { seaf_warning ("[upload] Failed open temp file.\n"); res = EVHTP_RES_SERVERR; goto out; } } seaf_debug ("[upload] Start to recv %s.\n", fsm->input_name); fsm->state = RECV_CONTENT; } else if (parse_mime_header (line, fsm) < 0) { free (line); res = EVHTP_RES_BADREQ; goto out; } else { free (line); } } else { no_line = TRUE; } break; case RECV_CONTENT: if (g_strcmp0 (fsm->input_name, "file") == 0) res = recv_file_data (fsm, &no_line); else res = recv_form_field (fsm, &no_line); if (res != EVHTP_RES_OK) goto out; break; } } out: if (res != EVHTP_RES_OK) { /* Don't receive any data before the connection is closed. */ evhtp_request_pause (req); /* Set keepalive to 0. This will cause evhtp to close the * connection after sending the reply. */ req->keepalive = 0; fsm->state = RECV_ERROR; } if (res == EVHTP_RES_BADREQ) { evhtp_send_reply (req, EVHTP_RES_BADREQ); } else if (res == EVHTP_RES_SERVERR) { evbuffer_add_printf (req->buffer_out, "Internal server error\n"); evhtp_send_reply (req, EVHTP_RES_SERVERR); } return EVHTP_RES_OK; } static char * get_http_header_param_value (const char *param) { char *equal; char *value; equal = strchr (param, '='); if (!equal) { seaf_warning ("[upload] Invalid http header param %s.\n", param); return NULL; } value = g_strdup (equal + 1); return value; } static char * get_boundary (evhtp_headers_t *hdr) { const char *content_type; char **params, **p; char *boundary = NULL; content_type = evhtp_kv_find (hdr, "Content-Type"); if (!content_type) { seaf_warning ("[upload] Missing Content-Type header\n"); return boundary; } params = g_strsplit (content_type, ";", 0); for (p = params; *p != NULL; ++p) *p = g_strstrip (*p); if (!params || g_strv_length (params) < 2) { seaf_warning ("[upload] Too little params Content-Type header\n"); g_strfreev (params); return boundary; } if (strcasecmp (params[0], "multipart/form-data") != 0) { seaf_warning ("[upload] Invalid Content-Type\n"); g_strfreev (params); return boundary; } for (p = params; *p != NULL; ++p) { if (strncasecmp (*p, "boundary", strlen("boundary")) == 0) { boundary = get_http_header_param_value (*p); break; } } g_strfreev (params); if (!boundary) { seaf_warning ("[upload] boundary not given\n"); } return boundary; } static int check_access_token (SearpcClient *rpc, const char *token, char **repo_id, char **user) { SeafileWebAccess *webaccess; webaccess = (SeafileWebAccess *) seafile_web_query_access_token (rpc, token, NULL); if (!webaccess) return -1; *repo_id = g_strdup (seafile_web_access_get_repo_id (webaccess)); *user = g_strdup (seafile_web_access_get_username (webaccess)); g_object_unref (webaccess); return 0; } static int get_progress_info (evhtp_request_t *req, evhtp_headers_t *hdr, gint64 *content_len, char **progress_id) { const char *content_len_str; const char *uuid; uuid = evhtp_kv_find (req->uri->query, "X-Progress-ID"); /* If progress id is not given, we don't need content-length either. */ if (!uuid) return 0; *progress_id = g_strdup(uuid); content_len_str = evhtp_kv_find (hdr, "Content-Length"); if (!content_len_str) { seaf_warning ("[upload] Content-Length not found.\n"); return -1; } *content_len = strtoll (content_len_str, NULL, 10); return 0; } static evhtp_res upload_headers_cb (evhtp_request_t *req, evhtp_headers_t *hdr, void *arg) { SearpcClient *rpc_client = NULL; char *token, *repo_id = NULL, *user = NULL; char *boundary = NULL; gint64 content_len; char *progress_id = NULL; char *err_msg = NULL; RecvFSM *fsm = NULL; Progress *progress = NULL; /* URL format: http://host:port/[upload|update]/<token>?X-Progress-ID=<uuid> */ token = req->uri->path->file; if (!token) { seaf_warning ("[upload] No token in url.\n"); err_msg = "Invalid URL"; goto err; } rpc_client = ccnet_create_pooled_rpc_client (seaf->client_pool, NULL, "seafserv-rpcserver"); if (check_access_token (rpc_client, token, &repo_id, &user) < 0) { seaf_warning ("[upload] Invalid token.\n"); err_msg = "Access denied"; goto err; } boundary = get_boundary (hdr); if (!boundary) { goto err; } if (get_progress_info (req, hdr, &content_len, &progress_id) < 0) goto err; if (progress_id != NULL) { pthread_mutex_lock (&pg_lock); if (g_hash_table_lookup (upload_progress, progress_id)) { pthread_mutex_unlock (&pg_lock); err_msg = "Duplicate progress id.\n"; goto err; } pthread_mutex_unlock (&pg_lock); } fsm = g_new0 (RecvFSM, 1); fsm->boundary = boundary; fsm->repo_id = repo_id; fsm->user = user; fsm->line = evbuffer_new (); fsm->form_kvs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); if (progress_id != NULL) { progress = g_new0 (Progress, 1); progress->size = content_len; fsm->progress_id = progress_id; fsm->progress = progress; pthread_mutex_lock (&pg_lock); g_hash_table_insert (upload_progress, g_strdup(progress_id), progress); pthread_mutex_unlock (&pg_lock); } /* Set up per-request hooks, so that we can read file data piece by piece. */ evhtp_set_hook (&req->hooks, evhtp_hook_on_read, upload_read_cb, fsm); evhtp_set_hook (&req->hooks, evhtp_hook_on_request_fini, upload_finish_cb, fsm); /* Set arg for upload_cb or update_cb. */ req->cbarg = fsm; ccnet_rpc_client_free (rpc_client); return EVHTP_RES_OK; err: /* Don't receive any data before the connection is closed. */ evhtp_request_pause (req); /* Set keepalive to 0. This will cause evhtp to close the * connection after sending the reply. */ req->keepalive = 0; if (err_msg) evbuffer_add_printf (req->buffer_out, "%s\n", err_msg); evhtp_send_reply (req, EVHTP_RES_BADREQ); if (rpc_client) ccnet_rpc_client_free (rpc_client); g_free (repo_id); g_free (user); g_free (boundary); g_free (progress_id); return EVHTP_RES_OK; } static void upload_progress_cb(evhtp_request_t *req, void *arg) { const char *progress_id; const char *callback; Progress *progress; GString *buf; progress_id = evhtp_kv_find (req->uri->query, "X-Progress-ID"); if (!progress_id) { seaf_warning ("[get pg] Progress id not found in url.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } callback = evhtp_kv_find (req->uri->query, "callback"); if (!callback) { seaf_warning ("[get pg] callback not found in url.\n"); evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } pthread_mutex_lock (&pg_lock); progress = g_hash_table_lookup (upload_progress, progress_id); pthread_mutex_unlock (&pg_lock); if (!progress) { /* seaf_warning ("[get pg] No progress found for %s.\n", progress_id); */ evhtp_send_reply (req, EVHTP_RES_BADREQ); return; } /* Return JSONP formated data. */ buf = g_string_new (NULL); g_string_append_printf (buf, "%s({\"uploaded\": %"G_GINT64_FORMAT", \"length\": %"G_GINT64_FORMAT"});", callback, progress->uploaded, progress->size); evbuffer_add (req->buffer_out, buf->str, buf->len); seaf_debug ("JSONP: %s\n", buf->str); evhtp_send_reply (req, EVHTP_RES_OK); g_string_free (buf, TRUE); } int upload_file_init (evhtp_t *htp) { evhtp_callback_t *cb; if (g_mkdir_with_parents (seaf->http_temp_dir, 0777) < 0) { seaf_warning ("Failed to create temp file dir %s.\n", seaf->http_temp_dir); return -1; } cb = evhtp_set_regex_cb (htp, "^/upload/.*", upload_cb, NULL); /* upload_headers_cb() will be called after evhtp parsed all http headers. */ evhtp_set_hook(&cb->hooks, evhtp_hook_on_headers, upload_headers_cb, NULL); cb = evhtp_set_regex_cb (htp, "^/upload-api/.*", upload_api_cb, NULL); evhtp_set_hook(&cb->hooks, evhtp_hook_on_headers, upload_headers_cb, NULL); cb = evhtp_set_regex_cb (htp, "^/update/.*", update_cb, NULL); evhtp_set_hook(&cb->hooks, evhtp_hook_on_headers, upload_headers_cb, NULL); cb = evhtp_set_regex_cb (htp, "^/update-api/.*", update_api_cb, NULL); evhtp_set_hook(&cb->hooks, evhtp_hook_on_headers, upload_headers_cb, NULL); evhtp_set_regex_cb (htp, "^/upload_progress.*", upload_progress_cb, NULL); upload_progress = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); pthread_mutex_init (&pg_lock, NULL); return 0; }
utlemming/seafile
httpserver/upload-file.c
C
gpl-3.0
37,321
# Prism for Mega Drive Collection of useful routines for use in Mega Drive assembly development. For use, include `wrapper.asm` at the beginning of your project. Does basic setup and jumps to a `__main` label, which is where your game should start. Expects a file called `header.asm` where the Mega Drive file header is declared. Expects a folder structure where prism is located in ../addons/prism, similar to a KallistiOS setup. Expects a label called `__end` at the end of your game. Defines a label called `gLibrarySentinel`, after which variables can be placed in RAM. ### Tools used for Mega Drive development: [__BMP2Tile__](http://gendev.spritesmind.net/page-b2t) [__Megadrive Map Maker__](http://gendev.spritesmind.net/page-mmm.html) [__Hex Editor HxD__](https://mh-nexus.de/de/hxd/) [__ASM68k Assembler__](http://retrocdn.net/File:ASM68k.7z) Made possible in part due to [BigEvilCorp's cool Mega Drive dev blog](https://bigevilcorporation.co.uk/), so check that out as well if you're interested in Mega Drive development.
CaptainDreamcast/libtari
other/md/README.md
Markdown
gpl-3.0
1,056
using System.Web; using System.Web.Mvc; namespace ProjetoRole { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
mariofraga84/ProjetoRole
ProjetoRole/ProjetoRole/App_Start/FilterConfig.cs
C#
gpl-3.0
266
package l2s.gameserver.model.entity.events.impl; import l2s.commons.collections.MultiValueSet; import l2s.gameserver.model.entity.events.objects.SiegeClanObject; import l2s.gameserver.model.entity.residence.ClanHall; import l2s.gameserver.model.pledge.Clan; import l2s.gameserver.network.l2.components.SystemMsg; import l2s.gameserver.network.l2.s2c.PlaySoundPacket; import l2s.gameserver.network.l2.s2c.SystemMessagePacket; /** * @author VISTALL * @date 18:26/03.03.2011 */ public class ClanHallNpcSiegeEvent extends SiegeEvent<ClanHall, SiegeClanObject> { public ClanHallNpcSiegeEvent(MultiValueSet<String> set) { super(set); } @Override public void startEvent() { if(!_isInProgress.compareAndSet(false, true)) return; _oldOwner = getResidence().getOwner(); broadcastInZone(new SystemMessagePacket(SystemMsg.THE_SIEGE_TO_CONQUER_S1_HAS_BEGUN).addResidenceName(getResidence())); super.startEvent(); } @Override public void stopEvent(boolean step) { if(!_isInProgress.compareAndSet(true, false)) return; Clan newOwner = getResidence().getOwner(); if(newOwner != null) { if(_oldOwner != newOwner) { newOwner.broadcastToOnlineMembers(PlaySoundPacket.SIEGE_VICTORY); newOwner.incReputation(1700, false, toString()); if(_oldOwner != null) _oldOwner.incReputation(-1700, false, toString()); } broadcastInZone(new SystemMessagePacket(SystemMsg.S1_CLAN_HAS_DEFEATED_S2).addString(newOwner.getName()).addResidenceName(getResidence())); broadcastInZone(new SystemMessagePacket(SystemMsg.THE_SIEGE_OF_S1_IS_FINISHED).addResidenceName(getResidence())); } else broadcastInZone(new SystemMessagePacket(SystemMsg.THE_SIEGE_OF_S1_HAS_ENDED_IN_A_DRAW).addResidenceName(getResidence())); super.stopEvent(step); _oldOwner = null; } @Override public void processStep(Clan clan) { if(clan != null) getResidence().changeOwner(clan); stopEvent(true); } @Override public void loadSiegeClans() { // } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/model/entity/events/impl/ClanHallNpcSiegeEvent.java
Java
gpl-3.0
1,993
/* ** Copyright 2013-2021 Double Precision, Inc. ** See COPYING for distribution information. */ #ifndef x_tls_sessioncacheobj_H #define x_tls_sessioncacheobj_H #include <x/namespace.h> #include <x/obj.H> #include <x/exception.H> #include <x/gnutls/datumwrapper.H> #include <x/gnutls/init.H> #include <x/logger.H> namespace LIBCXX_NAMESPACE::gnutls { class sessioncacheObj; #if 0 }; #endif //! An object that implement TLS/SSL session caching class sessioncacheObj : virtual public obj { //! Logger LOG_CLASS_SCOPE; public: friend class sessionObj; //! Constructor sessioncacheObj(); //! Destructor ~sessioncacheObj(); private: //! Session ticket datum_t ticket; //! Store a session //! store() must be thread-safe in the implementing subclass. virtual void store(const gnutls::datum_t &key, const gnutls::datum_t &data)=0; //! Remove a session //! remove() must be thread-safe in the implementing subclass. virtual void remove(const gnutls::datum_t &key)=0; //! Retrieve a session //! retr() must be thread-safe in the implementing subclass. virtual gnutls::datumptr_t retr(const gnutls::datum_t &key)=0; public: class LIBCXX_HIDDEN basic_implObj; //! Callback installed by gnutls_db_set_store_function //! \internal //! //! ptr is a sessioncacheObj, invokes ptr->store() static int store_func(void *ptr, gnutls_datum_t key, gnutls_datum_t data) LIBCXX_HIDDEN; //! Callback installed by gnutls_db_set_remove_function //! \internal //! //! ptr is a sessioncacheObj, invokes ptr->store() static int remove_func(void *ptr, gnutls_datum_t key) LIBCXX_HIDDEN; //! Callback installed by gnutls_db_set_retrieve_function //! \internal //! //! ptr is a sessioncacheObj, invokes ptr->store() static gnutls_datum_t retr_func(void *ptr, gnutls_datum_t key) LIBCXX_HIDDEN; }; #if 0 { #endif } #endif
svarshavchik/libcxx
includes/x/gnutls/sessioncacheobj.H
C++
gpl-3.0
1,871
/** */ package io.getgauge.spec.util; import io.getgauge.spec.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see io.getgauge.spec.SpecPackage * @generated */ public class SpecSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static SpecPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SpecSwitch() { if (modelPackage == null) { modelPackage = SpecPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case SpecPackage.MODEL: { Model model = (Model)theEObject; T result = caseModel(model); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.ELEMENT: { Element element = (Element)theEObject; T result = caseElement(element); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.SPEC: { Spec spec = (Spec)theEObject; T result = caseSpec(spec); if (result == null) result = caseElement(spec); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.SCENARIO: { Scenario scenario = (Scenario)theEObject; T result = caseScenario(scenario); if (result == null) result = caseElement(scenario); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.STEP: { Step step = (Step)theEObject; T result = caseStep(step); if (result == null) result = caseElement(step); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.STEP_DEFINITION: { StepDefinition stepDefinition = (StepDefinition)theEObject; T result = caseStepDefinition(stepDefinition); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.STATIC_PARAM: { StaticParam staticParam = (StaticParam)theEObject; T result = caseStaticParam(staticParam); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.DYNAMIC_PARAM: { DynamicParam dynamicParam = (DynamicParam)theEObject; T result = caseDynamicParam(dynamicParam); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.TAGS: { Tags tags = (Tags)theEObject; T result = caseTags(tags); if (result == null) result = caseElement(tags); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.COMMENT: { Comment comment = (Comment)theEObject; T result = caseComment(comment); if (result == null) result = caseElement(comment); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.TABLE: { Table table = (Table)theEObject; T result = caseTable(table); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.TABLE_ROW: { TableRow tableRow = (TableRow)theEObject; T result = caseTableRow(tableRow); if (result == null) result = defaultCase(theEObject); return result; } case SpecPackage.TABLE_CELL: { TableCell tableCell = (TableCell)theEObject; T result = caseTableCell(tableCell); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Model</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Model</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseModel(Model object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseElement(Element object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Spec</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Spec</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSpec(Spec object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Scenario</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Scenario</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseScenario(Scenario object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Step</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Step</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStep(Step object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Step Definition</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Step Definition</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStepDefinition(StepDefinition object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Static Param</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Static Param</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseStaticParam(StaticParam object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Dynamic Param</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Dynamic Param</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDynamicParam(DynamicParam object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Tags</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Tags</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTags(Tags object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Comment</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Comment</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseComment(Comment object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Table</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Table</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTable(Table object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Table Row</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Table Row</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTableRow(TableRow object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Table Cell</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Table Cell</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTableCell(TableCell object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //SpecSwitch
getgauge/Gauge-Eclipse
io.getgauge/src-gen/io/getgauge/spec/util/SpecSwitch.java
Java
gpl-3.0
12,786
from aquarius.objects.Book import Book class GetBookByTitleAndAuthor(object): def __init__(self, connection): self.__connection = connection def execute(self, book): b = Book() sql = "SELECT Id, Title, Author FROM Book WHERE Title=? AND Author=?" r = list(self.__connection.execute_sql_fetch_all_with_params(sql, (book.title, book.author))) if len(r) > 0: self.map_resultset_to_book(b, r) return b def map_resultset_to_book(self, book, resultset): book.id = resultset[0][0] book.title = resultset[0][1] book.author = resultset[0][2]
jeroanan/Aquarius
aquarius/persistence/sqlitepersistence/GetBookByTitleAndAuthor.py
Python
gpl-3.0
634
from django.contrib import admin from comments.models import Comment # Register your models here. admin.site.register(Comment)
awwong1/CMPUT410-Project
dogenode/comments/admin.py
Python
gpl-3.0
130
<?php function nxs_webmethod_geturl() { extract($_REQUEST); $result = array(); if ($destination == "") { nxs_webmethod_return_nack("destination niet meegegeven"); } if ($destination == "header") { if ($nxsrefurlspecial == "") { nxs_webmethod_return_nack("nxsrefurlspecial niet meegegeven"); } if ($postid == "") { nxs_webmethod_return_nack("postid niet meegegeven"); } $url = get_home_url() . "/?nxs_header=" . urlencode(nxs_getslug_for_postid($postid)) . "&nxsrefurlspecial=" . $nxsrefurlspecial; $result["url"] = $url; } else if ($destination == "footer") { if ($nxsrefurlspecial == "") { nxs_webmethod_return_nack("nxsrefurlspecial niet meegegeven"); } if ($postid == "") { nxs_webmethod_return_nack("postid niet meegegeven"); } $url = get_home_url() . "/?nxs_footer=" . urlencode(nxs_getslug_for_postid($postid)) . "&nxsrefurlspecial=" . $nxsrefurlspecial; $result["url"] = $url; } else if ($destination == "sidebar") { if ($nxsrefurlspecial == "") { nxs_webmethod_return_nack("nxsrefurlspecial niet meegegeven"); } if ($postid == "") { nxs_webmethod_return_nack("postid niet meegegeven"); } $url = get_home_url() . "/?nxs_sidebar=" . urlencode(nxs_getslug_for_postid($postid)) . "&nxsrefurlspecial=" . $nxsrefurlspecial; $result["url"] = $url; } else if ($destination == "pagelet") { if ($nxsrefurlspecial == "") { nxs_webmethod_return_nack("nxsrefurlspecial niet meegegeven"); } if ($postid == "") { nxs_webmethod_return_nack("postid niet meegegeven"); } $url = get_home_url() . "/?containerpostid=" . $containerpostid . "&nxs_pagelet=" . urlencode(nxs_getslug_for_postid($postid)) . "&nxsrefurlspecial=" . $nxsrefurlspecial; $result["url"] = $url; } else if ($destination == "postid") { if ($postid == "") { nxs_webmethod_return_nack("postid niet meegegeven"); } $url = nxs_geturl_for_postid($postid); $result["url"] = $url; } else { nxs_webmethod_return_nack("destination not supported;" . $destination); } nxs_webmethod_return_ok($result); } function nxs_dataprotection_nexusframework_webmethod_geturl_getprotecteddata($args) { return nxs_dataprotection_factor_createprotecteddata("webmethod-none"); } ?>
nexusthemes/nexusframework
nexusframework/nexuscore/webservices/webmethods/geturl/geturl_webmethod.php
PHP
gpl-3.0
2,345
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> ExEmbedAtom (POI API Documentation) </TITLE> <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="ExEmbedAtom (POI API Documentation)"; } } </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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ExEmbedAtom.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/hslf/record/ExEmbed.html" title="class in org.apache.poi.hslf.record"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/hslf/record/ExHyperlink.html" title="class in org.apache.poi.hslf.record"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/hslf/record/ExEmbedAtom.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ExEmbedAtom.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.poi.hslf.record</FONT> <BR> Class ExEmbedAtom</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">org.apache.poi.hslf.record.Record</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">org.apache.poi.hslf.record.RecordAtom</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.hslf.record.ExEmbedAtom</B> </PRE> <HR> <DL> <DT><PRE>public class <B>ExEmbedAtom</B><DT>extends <A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">RecordAtom</A></DL> </PRE> <P> The atom that holds metadata on a specific embedded object in the document. <!-- 0 sint4 followColorScheme This field indicates how the object follows the color scheme. Valid values are: 0 - doesn't follow the color scheme 1 - follows the entire color scheme 2 - follows the text and background scheme 4 bool1 cantLockServerB Set if the embedded server can not be locked 5 bool1 noSizeToServerB Set if don't need to send the dimension to the embedded object 6 Bool1 isTable Set if the object is a Word table --> <P> <P> <DL> <DT><B>Author:</B></DT> <DD>Daniel Noll</DD> </DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#DOES_NOT_FOLLOW_COLOR_SCHEME">DOES_NOT_FOLLOW_COLOR_SCHEME</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Embedded document does not follow the color scheme.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#FOLLOWS_ENTIRE_COLOR_SCHEME">FOLLOWS_ENTIRE_COLOR_SCHEME</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Embedded document follows the entire color scheme.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#FOLLOWS_TEXT_AND_BACKGROUND_SCHEME">FOLLOWS_TEXT_AND_BACKGROUND_SCHEME</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Embedded document follows the text and background scheme.</TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.poi.hslf.record.Record"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Fields inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#logger">logger</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected </CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#ExEmbedAtom()">ExEmbedAtom</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Constructs a brand new embedded object atom record.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected </CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#ExEmbedAtom(byte[], int, int)">ExEmbedAtom</A></B>(byte[]&nbsp;source, int&nbsp;start, int&nbsp;len)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Constructs the embedded object atom record from its source data.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#getCantLockServerB()">getCantLockServerB</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets whether the embedded server cannot be locked.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#getFollowColorScheme()">getFollowColorScheme</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets whether the object follows the color scheme.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#getIsTable()">getIsTable</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Getswhether the object is a Word table.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#getNoSizeToServerB()">getNoSizeToServerB</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets whether it is not required to send the dimensions to the embedded object.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;long</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#getRecordType()">getRecordType</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the record type.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#setCantLockServerB(boolean)">setCantLockServerB</A></B>(boolean&nbsp;cantBeLocked)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#writeOut(java.io.OutputStream)">writeOut</A></B>(java.io.OutputStream&nbsp;out)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Write the contents of the record back, so it can be written to disk</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.poi.hslf.record.RecordAtom"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html" title="class in org.apache.poi.hslf.record">RecordAtom</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html#getChildRecords()">getChildRecords</A>, <A HREF="../../../../../org/apache/poi/hslf/record/RecordAtom.html#isAnAtom()">isAnAtom</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.poi.hslf.record.Record"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.apache.poi.hslf.record.<A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#buildRecordAtOffset(byte[], int)">buildRecordAtOffset</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#createRecordForType(long, byte[], int, int)">createRecordForType</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#findChildRecords(byte[], int, int)">findChildRecords</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeLittleEndian(int, java.io.OutputStream)">writeLittleEndian</A>, <A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeLittleEndian(short, java.io.OutputStream)">writeLittleEndian</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="DOES_NOT_FOLLOW_COLOR_SCHEME"><!-- --></A><H3> DOES_NOT_FOLLOW_COLOR_SCHEME</H3> <PRE> public static final int <B>DOES_NOT_FOLLOW_COLOR_SCHEME</B></PRE> <DL> <DD>Embedded document does not follow the color scheme. <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../constant-values.html#org.apache.poi.hslf.record.ExEmbedAtom.DOES_NOT_FOLLOW_COLOR_SCHEME">Constant Field Values</A></DL> </DL> <HR> <A NAME="FOLLOWS_ENTIRE_COLOR_SCHEME"><!-- --></A><H3> FOLLOWS_ENTIRE_COLOR_SCHEME</H3> <PRE> public static final int <B>FOLLOWS_ENTIRE_COLOR_SCHEME</B></PRE> <DL> <DD>Embedded document follows the entire color scheme. <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../constant-values.html#org.apache.poi.hslf.record.ExEmbedAtom.FOLLOWS_ENTIRE_COLOR_SCHEME">Constant Field Values</A></DL> </DL> <HR> <A NAME="FOLLOWS_TEXT_AND_BACKGROUND_SCHEME"><!-- --></A><H3> FOLLOWS_TEXT_AND_BACKGROUND_SCHEME</H3> <PRE> public static final int <B>FOLLOWS_TEXT_AND_BACKGROUND_SCHEME</B></PRE> <DL> <DD>Embedded document follows the text and background scheme. <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../../../constant-values.html#org.apache.poi.hslf.record.ExEmbedAtom.FOLLOWS_TEXT_AND_BACKGROUND_SCHEME">Constant Field Values</A></DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="ExEmbedAtom()"><!-- --></A><H3> ExEmbedAtom</H3> <PRE> protected <B>ExEmbedAtom</B>()</PRE> <DL> <DD>Constructs a brand new embedded object atom record. <P> </DL> <HR> <A NAME="ExEmbedAtom(byte[], int, int)"><!-- --></A><H3> ExEmbedAtom</H3> <PRE> protected <B>ExEmbedAtom</B>(byte[]&nbsp;source, int&nbsp;start, int&nbsp;len)</PRE> <DL> <DD>Constructs the embedded object atom record from its source data. <P> <DL> <DT><B>Parameters:</B><DD><CODE>source</CODE> - the source data as a byte array.<DD><CODE>start</CODE> - the start offset into the byte array.<DD><CODE>len</CODE> - the length of the slice in the byte array.</DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getFollowColorScheme()"><!-- --></A><H3> getFollowColorScheme</H3> <PRE> public int <B>getFollowColorScheme</B>()</PRE> <DL> <DD>Gets whether the object follows the color scheme. <P> <DD><DL> <DT><B>Returns:</B><DD>one of <A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#DOES_NOT_FOLLOW_COLOR_SCHEME"><CODE>DOES_NOT_FOLLOW_COLOR_SCHEME</CODE></A>, <A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#FOLLOWS_ENTIRE_COLOR_SCHEME"><CODE>FOLLOWS_ENTIRE_COLOR_SCHEME</CODE></A>, or <A HREF="../../../../../org/apache/poi/hslf/record/ExEmbedAtom.html#FOLLOWS_TEXT_AND_BACKGROUND_SCHEME"><CODE>FOLLOWS_TEXT_AND_BACKGROUND_SCHEME</CODE></A>.</DL> </DD> </DL> <HR> <A NAME="getCantLockServerB()"><!-- --></A><H3> getCantLockServerB</H3> <PRE> public boolean <B>getCantLockServerB</B>()</PRE> <DL> <DD>Gets whether the embedded server cannot be locked. <P> <DD><DL> <DT><B>Returns:</B><DD><code>true</code> if the embedded server cannot be locked.</DL> </DD> </DL> <HR> <A NAME="setCantLockServerB(boolean)"><!-- --></A><H3> setCantLockServerB</H3> <PRE> public void <B>setCantLockServerB</B>(boolean&nbsp;cantBeLocked)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getNoSizeToServerB()"><!-- --></A><H3> getNoSizeToServerB</H3> <PRE> public boolean <B>getNoSizeToServerB</B>()</PRE> <DL> <DD>Gets whether it is not required to send the dimensions to the embedded object. <P> <DD><DL> <DT><B>Returns:</B><DD><code>true</code> if the embedded server does not require the object dimensions.</DL> </DD> </DL> <HR> <A NAME="getIsTable()"><!-- --></A><H3> getIsTable</H3> <PRE> public boolean <B>getIsTable</B>()</PRE> <DL> <DD>Getswhether the object is a Word table. <P> <DD><DL> <DT><B>Returns:</B><DD><code>true</code> if the object is a Word table.</DL> </DD> </DL> <HR> <A NAME="getRecordType()"><!-- --></A><H3> getRecordType</H3> <PRE> public long <B>getRecordType</B>()</PRE> <DL> <DD>Gets the record type. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#getRecordType()">getRecordType</A></CODE> in class <CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the record type.</DL> </DD> </DL> <HR> <A NAME="writeOut(java.io.OutputStream)"><!-- --></A><H3> writeOut</H3> <PRE> public void <B>writeOut</B>(java.io.OutputStream&nbsp;out) throws java.io.IOException</PRE> <DL> <DD>Write the contents of the record back, so it can be written to disk <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html#writeOut(java.io.OutputStream)">writeOut</A></CODE> in class <CODE><A HREF="../../../../../org/apache/poi/hslf/record/Record.html" title="class in org.apache.poi.hslf.record">Record</A></CODE></DL> </DD> <DD><DL> <DT><B>Parameters:</B><DD><CODE>out</CODE> - the output stream to write to. <DT><B>Throws:</B> <DD><CODE>java.io.IOException</CODE> - if an error occurs.</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ExEmbedAtom.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/hslf/record/ExEmbed.html" title="class in org.apache.poi.hslf.record"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/hslf/record/ExHyperlink.html" title="class in org.apache.poi.hslf.record"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/hslf/record/ExEmbedAtom.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ExEmbedAtom.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
jmemmons/university-assignments
CSC 445 WebCentric Programming/Final Project/poi-3.14/docs/apidocs/org/apache/poi/hslf/record/ExEmbedAtom.html
HTML
gpl-3.0
23,583
# -*- coding: utf-8 -*- """ Created on Tue Dec 08 13:25:40 2015 @author: J. Alejandro Cardona """ from Board import * import pygame UP, LEFT, DOWN, RIGHT = 1, 2, 3, 4 juego = Board() _2 = pygame.image.load("2.jpg"); _2re = _2.get_rect() _4 = pygame.image.load("4.jpg"); _4re = _4.get_rect() _8 = pygame.image.load("8.jpg"); _8re = _8.get_rect() _16 = pygame.image.load("16.jpg"); _16re = _16.get_rect() _32 = pygame.image.load("32.jpg"); _32re = _32.get_rect() _64 = pygame.image.load("64.jpg"); _64re = _64.get_rect() _128 = pygame.image.load("128.jpg"); _128re = _128.get_rect() _256 = pygame.image.load("256.jpg"); _256re = _256.get_rect() _512 = pygame.image.load("512.jpg"); _512re = _512.get_rect() _1024 = pygame.image.load("1024.jpg"); _1024re = _1024.get_rect() _2048 = pygame.image.load("2048.jpg"); _2048re = _2048.get_rect() figs = {2:(_2, _2re), 4:(_4,_4re), 8:(_8,_8re), 16:(_16,_16re), 32:(_32,_32re), 64:(_64,_64re), 128:(_128,_128re), 256:(_256,_256re), 512:(_512,_512re), 1024:(_1024,_1024re), 2048:(_2048,_2048re)} def read_key(key): # Este metodo se usa solo para jugar en modo consola if key == 'w': juego.move(UP) elif key == 's': juego.move(DOWN) elif key == 'a': juego.move(LEFT) elif key == 'd': juego.move(RIGHT)
Alecardv/College-projects
2048/Control.py
Python
gpl-3.0
1,336
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package _tk */ get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php endwhile; // end of the loop. ?> <?php //get_sidebar(); ?> <?php get_footer(); ?>
thomas-gordon/troiano-wordpress-theme
page.php
PHP
gpl-3.0
491
--- layout: politician2 title: tariq mirza profile: party: RPI constituency: Chandni Chowk state: National Capital Territory Of Delhi education: level: 8th Pass details: 7th std. photo: sex: caste: religion: current-office-title: crime-accusation-instances: 0 date-of-birth: 1986 profession: networth: assets: 1,10,000 liabilities: pan: twitter: website: youtube-interview: wikipedia: candidature: - election: Lok Sabha 2014 myneta-link: http://myneta.info/ls2014/candidate.php?candidate_id=989 affidavit-link: expenses-link: constituency: Chandni Chowk party: RPI criminal-cases: 0 assets: 1,10,000 liabilities: result: crime-record: date: 2014-01-28 version: 0.0.5 tags: --- ##Summary ##Education {% include "education.html" %} ##Political Career {% include "political-career.html" %} ##Criminal Record {% include "criminal-record.html" %} ##Personal Wealth {% include "personal-wealth.html" %} ##Public Office Track Record {% include "track-record.html" %} ##References {% include "references.html" %}
vaibhavb/wisevoter
site/politicians/_posts/2014-04-09-tariq-mirza.md
Markdown
gpl-3.0
1,135
from __future__ import division import numpy as np import argparse import matplotlib.pyplot as plt from matplotlib.colors import colorConverter from mpl_toolkits.axes_grid1 import ImageGrid import matplotlib.cm as cm from amitgroup.stats import bernoullimm def main(args): means = np.load('%s_means.npy' % args.save_path) S_clusters = np.load('%s_S_clusters.npy' % args.save_path) means = means.reshape( *( S_clusters.shape + ( int(means.size/S_clusters.size),))) if True: plt.close('all') fig = plt.figure(1, (6, 6)) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols = (means.shape[0],means.shape[-1]+1 ), # creates 2x2 grid of axes axes_pad=0.001, # pad between axes in inch. ) ncols = means.shape[-1] + 1 for i in xrange(S_clusters.shape[0]): try: grid[i*ncols].imshow(S_clusters[i],cmap=cm.binary,interpolation='nearest') grid[i*ncols].spines['bottom'].set_color('red') grid[i*ncols].spines['top'].set_color('red') grid[i*ncols].spines['left'].set_color('red') grid[i*ncols].spines['right'].set_color('red') for a in grid[i*ncols].axis.values(): a.toggle(all=False) except: import pdb; pdb.set_trace() for j in xrange(ncols-1): try: grid[i*ncols+j+1].imshow(means[i,:,:,j],cmap=cm.binary,interpolation='nearest') grid[i*ncols+j+1].spines['bottom'].set_color('red') grid[i*ncols+j+1].spines['top'].set_color('red') grid[i*ncols+j+1].spines['left'].set_color('red') grid[i*ncols+j+1].spines['right'].set_color('red') for a in grid[i*ncols+j+1].axis.values(): a.toggle(all=False) except: import pdb; pdb.set_trace() plt.savefig('%s' % args.display_bernoulli_parts ,bbox_inches='tight') if __name__ == "__main__": parser = argparse.ArgumentParser("""Clustering and output for bernoulli data with paired spectrum data""") parser.add_argument('--save_path',type=str,default='',help='path to save the trained models to') parser.add_argument('--patches',type=str,default='',help='path to the patches') parser.add_argument('--spec_patches',type=str,default='',help='path to the spectrogram patches') parser.add_argument('--n_components',type=int,default=20,help='number of parts') parser.add_argument('-v',action='store_true',help='whether it is verbose') parser.add_argument('--display_bernoulli_parts',type=str,default=None,help='path to save the learned parts to') main(parser.parse_args())
markstoehr/spectral_features
local/display_bernoulli_model.py
Python
gpl-3.0
2,936
``` ______ _____ ______ __ | ____| | __ \| _ \ \ / / | |__ _ __ ___ ___| |__) | |_) \ V / | __| '__/ _ \/ _ \ ___/| _ < > < | | | | | __/ __/ | | |_) / . \ |_| |_| \___|\___|_| |____/_/ \_\ Your Open Source Asterisk PBX GUI Solution ``` ### What? donotdisturb This is a module for [FreePBX©](http://www.freepbx.org/ "FreePBX Home Page"). [FreePBX](http://www.freepbx.org/ "FreePBX Home Page") is an open source GUI (graphical user interface) that controls and manages [Asterisk©](http://www.asterisk.org/ "Asterisk Home Page") (PBX). FreePBX is licensed under GPL. [FreePBX](http://www.freepbx.org/ "FreePBX Home Page") is a completely modular GUI for Asterisk written in PHP and Javascript. Meaning you can easily write any module you can think of and distribute it free of cost to your clients so that they can take advantage of beneficial features in [Asterisk](http://www.asterisk.org/ "Asterisk Home Page") ### Setting up a FreePBX system [See our WIKI](http://wiki.freepbx.org/display/FOP/Install+FreePBX) ### License [This modules code is licensed as GPLv3+](http://www.gnu.org/licenses/gpl-3.0.txt) ### Contributing To contribute code or modules back into the [FreePBX](http://www.freepbx.org/ "FreePBX Home Page") ecosystem you must fully read our Code License Agreement. We are not able to look at or accept patches or code of any kind until this document is filled out. Please take a look at [http://wiki.freepbx.org/display/DC/Code+License+Agreement](http://wiki.freepbx.org/display/DC/Code+License+Agreement) for more information ### Issues Please file bug reports at http://issues.freepbx.org
FreePBX/donotdisturb
README.md
Markdown
gpl-3.0
1,653
/* * Generated by asn1c-0.9.28 (http://lionet.info/asn1c) * From ASN.1 module "PMCPDLCAPDUsVersion1" * found in "../../../dumpvdl2.asn1/atn-b1_cpdlc-v1.asn1" * `asn1c -fcompound-names -fincludes-quoted -gen-PER` */ #include "CPDLCMessage.h" int CPDLCMessage_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { /* Replace with underlying type checker */ td->check_constraints = asn_DEF_BIT_STRING.check_constraints; return td->check_constraints(td, sptr, ctfailcb, app_key); } /* * This type is implemented using BIT_STRING, * so here we adjust the DEF accordingly. */ static void CPDLCMessage_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_BIT_STRING.free_struct; td->print_struct = asn_DEF_BIT_STRING.print_struct; td->check_constraints = asn_DEF_BIT_STRING.check_constraints; td->ber_decoder = asn_DEF_BIT_STRING.ber_decoder; td->der_encoder = asn_DEF_BIT_STRING.der_encoder; td->xer_decoder = asn_DEF_BIT_STRING.xer_decoder; td->xer_encoder = asn_DEF_BIT_STRING.xer_encoder; td->uper_decoder = asn_DEF_BIT_STRING.uper_decoder; td->uper_encoder = asn_DEF_BIT_STRING.uper_encoder; if(!td->per_constraints) td->per_constraints = asn_DEF_BIT_STRING.per_constraints; td->elements = asn_DEF_BIT_STRING.elements; td->elements_count = asn_DEF_BIT_STRING.elements_count; td->specifics = asn_DEF_BIT_STRING.specifics; } void CPDLCMessage_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { CPDLCMessage_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int CPDLCMessage_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t CPDLCMessage_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t CPDLCMessage_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t CPDLCMessage_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t CPDLCMessage_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } asn_dec_rval_t CPDLCMessage_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); } asn_enc_rval_t CPDLCMessage_encode_uper(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *structure, asn_per_outp_t *per_out) { CPDLCMessage_1_inherit_TYPE_descriptor(td); return td->uper_encoder(td, constraints, structure, per_out); } static const ber_tlv_tag_t asn_DEF_CPDLCMessage_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (3 << 2)) }; asn_TYPE_descriptor_t asn_DEF_CPDLCMessage = { "CPDLCMessage", "CPDLCMessage", CPDLCMessage_free, CPDLCMessage_print, CPDLCMessage_constraint, CPDLCMessage_decode_ber, CPDLCMessage_encode_der, CPDLCMessage_decode_xer, CPDLCMessage_encode_xer, CPDLCMessage_decode_uper, CPDLCMessage_encode_uper, 0, /* Use generic outmost tag fetcher */ asn_DEF_CPDLCMessage_tags_1, sizeof(asn_DEF_CPDLCMessage_tags_1) /sizeof(asn_DEF_CPDLCMessage_tags_1[0]), /* 1 */ asn_DEF_CPDLCMessage_tags_1, /* Same as above */ sizeof(asn_DEF_CPDLCMessage_tags_1) /sizeof(asn_DEF_CPDLCMessage_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ 0, 0, /* No members */ 0 /* No specifics */ };
szpajder/dumpvdl2
src/asn1/CPDLCMessage.c
C
gpl-3.0
4,445
/* *************************************************************************** * * Author: Teunis van Beelen * * Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Teunis van Beelen * * Email: teuniz@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/>. * *************************************************************************** */ #ifndef PRINT_SCREEN_TO_EDF_H #define PRINT_SCREEN_TO_EDF_H #include <QtGlobal> #include <QApplication> #include <QFileDialog> #include <QMessageBox> #include <QString> #include <QCursor> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "global.h" #include "mainwindow.h" #include "filter.h" #include "utc_date_time.h" #include "edf_helper.h" #include "edf_annot_list.h" #include "third_party/fidlib/fidlib.h" class UI_Mainwindow; void print_screen_to_edf(UI_Mainwindow *); #endif // PRINT_SCREEN_TO_EDF_H
Teuniz/EDFbrowser
print_to_edf.h
C
gpl-3.0
1,579
<!-- Header --> <div id="header-wrapper"> <div id="header"> <!-- Logo --> <a href="/"><img style="margin-bottom:20px;" src="/theme/images/logo.png"/></a> <!-- Nav --> <nav id="nav"> <ul> <!-- <li {% if output_file == 'index.html' %}class="current"{% endif %}><a href="/">Home</a></li>--> {% if DISPLAY_PAGES_ON_MENU -%} {% for p in pages|sort(attribute='menuindex') %} {% if p.parent is none %} <li {% if page and ( (p.url != "" and page.url.startswith(p.url)) or (p.url == "" and page.url == "") ) %}class="current"{% endif %}><a href="{{ SITEURL }}/{{ p.url }}">{{ p.title }}</a></li> {% if loop.index == loop.length %} <li {% if output_file == "blog/index.html" or output_file.startswith("20") %}class="current"{% endif %}><a href="{{ SITEURL }}/blog/index.html">Blog</a></li> {% endif %} {% endif %} {% endfor %} {% endif %} </ul> </nav> {% block header_extras %} {% endblock %} </div> </div>
ubrew-it/ubrew-site
themes/dopetrope/templates/header.html
HTML
gpl-3.0
1,159
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.18"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Sequoia: sequoia::testing::detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt; Struct Template Reference</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../jquery.js"></script> <script type="text/javascript" src="../../dynsections.js"></script> <link href="../../search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../../search/searchdata.js"></script> <script type="text/javascript" src="../../search/search.js"></script> <link href="../../doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Sequoia </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.18 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "../../search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="../../menudata.js"></script> <script type="text/javascript" src="../../menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('../../',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>sequoia</b></li><li class="navelem"><a class="el" href="../../dd/da8/namespacesequoia_1_1testing.html">testing</a></li><li class="navelem"><a class="el" href="../../d0/d90/structsequoia_1_1testing_1_1detailed__equality__checker_3_01maths_1_1heterogeneous__static__grapad2ef5d4b25a83120c3272a44fd7117f.html">detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt;</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="../../da/d66/structsequoia_1_1testing_1_1detailed__equality__checker_3_01maths_1_1heterogeneous__static__grap02fcbac4fad4deaa3458764a31336b39.html">List of all members</a> </div> <div class="headertitle"> <div class="title">sequoia::testing::detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt; Struct Template Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for sequoia::testing::detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt;:</div> <div class="dyncontent"> <div class="center"> <img src="../../d0/d90/structsequoia_1_1testing_1_1detailed__equality__checker_3_01maths_1_1heterogeneous__static__grapad2ef5d4b25a83120c3272a44fd7117f.png" usemap="#sequoia::testing::detailed_5Fequality_5Fchecker_3C_20maths::heterogeneous_5Fstatic_5Fgraph_3C_20Directedness_2C_20Size_2C_20Order_2C_20EdgeWeight_2C_20NodeWeights..._20_3E_20_3E_map" alt=""/> <map id="sequoia::testing::detailed_5Fequality_5Fchecker_3C_20maths::heterogeneous_5Fstatic_5Fgraph_3C_20Directedness_2C_20Size_2C_20Order_2C_20EdgeWeight_2C_20NodeWeights..._20_3E_20_3E_map" name="sequoia::testing::detailed_5Fequality_5Fchecker_3C_20maths::heterogeneous_5Fstatic_5Fgraph_3C_20Directedness_2C_20Size_2C_20Order_2C_20EdgeWeight_2C_20NodeWeights..._20_3E_20_3E_map"> <area href="../../db/d49/structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker.html" alt="sequoia::testing::impl::graph_detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt;" shape="rect" coords="0,0,885,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pub_types_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td colspan="2" onclick="javascript:toggleInherit('pub_types_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker')"><img src="../../closed.png" alt="-"/>&#160;Public Types inherited from <a class="el" href="../../db/d49/structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker.html">sequoia::testing::impl::graph_detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt;</a></td></tr> <tr class="memitem:a8730f1f7bf68c72d335565cd807385e7 inherit pub_types_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td class="memItemLeft" align="right" valign="top"><a id="a8730f1f7bf68c72d335565cd807385e7"></a> using&#160;</td><td class="memItemRight" valign="bottom"><b>type</b> = <a class="el" href="../../d2/dba/classsequoia_1_1maths_1_1heterogeneous__static__graph.html">maths::heterogeneous_static_graph</a>&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt;</td></tr> <tr class="separator:a8730f1f7bf68c72d335565cd807385e7 inherit pub_types_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_static_methods_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker')"><img src="../../closed.png" alt="-"/>&#160;Static Public Member Functions inherited from <a class="el" href="../../db/d49/structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker.html">sequoia::testing::impl::graph_detailed_equality_checker&lt; maths::heterogeneous_static_graph&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &gt;</a></td></tr> <tr class="memitem:a61829dc88cff3fe3297d12304ede8ab9 inherit pub_static_methods_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td class="memItemLeft" align="right" valign="top"><a id="a61829dc88cff3fe3297d12304ede8ab9"></a> static void&#160;</td><td class="memItemRight" valign="bottom"><b>check</b> (<a class="el" href="../../df/d20/classsequoia_1_1testing_1_1test__logger.html">test_logger</a>&lt; Mode &gt; &amp;logger, const <a class="el" href="../../d2/dba/classsequoia_1_1maths_1_1heterogeneous__static__graph.html">maths::heterogeneous_static_graph</a>&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &amp;graph, const <a class="el" href="../../d2/dba/classsequoia_1_1maths_1_1heterogeneous__static__graph.html">maths::heterogeneous_static_graph</a>&lt; Directedness, Size, Order, EdgeWeight, NodeWeights... &gt; &amp;prediction)</td></tr> <tr class="separator:a61829dc88cff3fe3297d12304ede8ab9 inherit pub_static_methods_structsequoia_1_1testing_1_1impl_1_1graph__detailed__equality__checker"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li>/Users/Claire/Dropbox/Sequoia/Tests/Maths/Graph/<a class="el" href="../../d1/d39/HeterogeneousGraphTestingUtilities_8hpp_source.html">HeterogeneousGraphTestingUtilities.hpp</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="../../doxygen.png" alt="doxygen"/> </a> 1.8.18 </small></address> </body> </html>
ojrosten/sequoia
docs/html/d0/d90/structsequoia_1_1testing_1_1detailed__equality__checker_3_01maths_1_1heterogeneous__static__grapad2ef5d4b25a83120c3272a44fd7117f.html
HTML
gpl-3.0
8,768
# Owade Reborn [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FCarlosLannister%2FOwadeReborn.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2FCarlosLannister%2FOwadeReborn?ref=badge_shield) * carlos.cilleruelo@edu.uah.es * david.martinb@edu.uah.es * alvaro.schuller@edu.uah.es * jmartinez@lazarus.es ## What is OwadeReborn? OwadeReborn is a forensic tool for extract offline data from a Windows 7 and 8.1 NTFS disc image. This project is a fork from Owade project,https://bitbucket.org/Elie/owade/wiki/Home. This project was presented at the Blackhat USA 2011. This first project was made for Windows XP and is now deprecated. ## Install OwadeReborn Owade provide a http website for control check the Wiki for tutorials and how install the project. https://github.com/CarlosLannister/OwadeReborn/wiki ## Functions The aplication gets: * Chrome passwords * Chrome history and downloads * Firefox passwords * Firefox hystory and downloads * IE passwords * IE history and downloads * Outlook passwords * Wifi SSIDs and passwords * Local user passwords * iCloud Apple token decripted * Skype passwords * Dropbox passwords The main target for this tool is helping forensic community who knows little or nothing about computing and makes faster the process of extract evidences. ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FCarlosLannister%2FOwadeReborn.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FCarlosLannister%2FOwadeReborn?ref=badge_large)
CarlosLannister/OwadeReborn
README.md
Markdown
gpl-3.0
1,551
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.uks.tickets.service; import com.uks.tickets.model.Event; import com.uks.tickets.model.Order1; import com.uks.tickets.model.User; import javax.mail.MessagingException; import javax.naming.NamingException; /** * * @author Borko */ public interface EmailService { public String sendEmailConfirmation(User user); public String sendOrderConfirmation(Order1 order); public String sendResetPWD(User user); public String contactFormEmail(String name, String email, String msg); public boolean sendEventRecommend(User user,Event event,User receiver); public void sendEmail(String msgBody, String subject, String emailTo, String emailFrom) throws NamingException, MessagingException; }
bostefan/ticket-guru
src/main/java/com/uks/tickets/service/EmailService.java
Java
gpl-3.0
817
import os from django import template from django.conf import settings from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag() def custom_css(): theme_path = os.path.join( settings.MEDIA_ROOT, "overrides.css" ) if os.path.exists(theme_path): return mark_safe( '<link rel="stylesheet" type="text/css" href="{}" />'.format( os.path.join(settings.MEDIA_URL, "overrides.css") ) ) return "" @register.simple_tag() def custom_js(): theme_path = os.path.join( settings.MEDIA_ROOT, "overrides.js" ) if os.path.exists(theme_path): return mark_safe( '<script src="{}"></script>'.format( os.path.join(settings.MEDIA_URL, "overrides.js") ) ) return ""
danielquinn/paperless
src/documents/templatetags/customisation.py
Python
gpl-3.0
865
#include <stdio.h> int main () { int arr[1000] = {0}, p, i, j, count; for (i = 2; i * i < 1000; i++) if (!arr[i]) for (j = i * 2; j < 1000; j += i) arr[j] = 1; printf ("The prime numbers between 1 and 999 are:\n"); for (i = 2, count = 0; i < 1000; i++) if (!arr[i]) { printf ("%d", i); count++; if (count % 5) printf ("\t"); else printf ("\n"); } return 0; }
BOT-Man-JL/BUPT-Projects
1-1-Introduction-to-Computing/6-15-8/6-15-8-2.c
C
gpl-3.0
399
## ## This file is part of ACADO Toolkit. ## ## ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization. ## Copyright (C) 2008-2009 by Boris Houska and Hans Joachim Ferreau, K.U.Leuven. ## Developed within the Optimization in Engineering Center (OPTEC) under ## supervision of Moritz Diehl. All rights reserved. ## ## ACADO Toolkit 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. ## ## ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## ## ## Filename: examples/getting_started/Makefile ## Author: Boris Houska and Hans Joachim Ferreau ## Date: 2008 ## ## ## include global settings ## LOCAL_PATH_PREFIX = ../.. include ${LOCAL_PATH_PREFIX}/include/acado/include.mk ## ## flags ## IFLAGS = ${HEADER_PATHS} CPPFLAGS = ${CPP_GLOBAL_FLAGS} ${NO_PARENTHESES_WARNING} LIBS = ${TOOLKIT_LIBS} SRCS = \ Wimmer_nx4_COPcte_cel_nopeak.cpp DEV_SRCS = OBJS = $(SRCS:.cpp=.${OBJEXT}) EXECS = $(SRCS:.cpp=${EXE}) DEV_OBJS = $(DEV_SRCS:.cpp=.${OBJEXT}) DEV_EXECS = $(DEV_SRCS:.cpp=${EXE}) ## ## targets ## ifeq ($(VERBOSE),NO) .SILENT: endif all: ${EXECS} developer: ${EXECS} ${DEV_EXECS} ${EXECS} : %${EXE} : %.${OBJEXT} @echo "Creating" $@ ${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${LIBS} ${DEV_EXECS} : %${EXE} : %.${OBJEXT} @echo "Creating" $@ ${CPP} ${DEF_TARGET} ${CPPFLAGS} $< ${LIBS} ${OBJS} : %.${OBJEXT}: %.cpp ${CPP} ${DEF_TARGET} -c ${IFLAGS} ${CPPFLAGS} $< ${DEV_OBJS} : %.${OBJEXT}: %.cpp ${CPP} ${DEF_TARGET} -c ${IFLAGS} ${CPPFLAGS} $< clean: ${RM} -f ${OBJS} ${EXECS} ${DEV_OBJS} ${DEV_EXECS} clobber: clean ## ## end of file ##
rtkg/acado
examples/my_examples/Makefile
Makefile
gpl-3.0
2,278
/* 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 <AP_Math/AP_Math.h> #include <AP_HAL/AP_HAL.h> #include "AR_AttitudeControl.h" extern const AP_HAL::HAL& hal; const AP_Param::GroupInfo AR_AttitudeControl::var_info[] = { // @Param: _STR_RAT_P // @DisplayName: Steering control rate P gain // @Description: Steering control rate P gain. Converts the turn rate error (in radians/sec) to a steering control output (in the range -1 to +1) // @Range: 0.000 2.000 // @Increment: 0.01 // @User: Standard // @Param: _STR_RAT_I // @DisplayName: Steering control I gain // @Description: Steering control I gain. Corrects long term error between the desired turn rate (in rad/s) and actual // @Range: 0.000 2.000 // @Increment: 0.01 // @User: Standard // @Param: _STR_RAT_IMAX // @DisplayName: Steering control I gain maximum // @Description: Steering control I gain maximum. Constraings the steering output (range -1 to +1) that the I term will generate // @Range: 0.000 1.000 // @Increment: 0.01 // @User: Standard // @Param: _STR_RAT_D // @DisplayName: Steering control D gain // @Description: Steering control D gain. Compensates for short-term change in desired turn rate vs actual // @Range: 0.000 0.400 // @Increment: 0.001 // @User: Standard // @Param: _STR_RAT_FF // @DisplayName: Steering control feed forward // @Description: Steering control feed forward // @Range: 0.000 3.000 // @Increment: 0.001 // @User: Standard // @Param: _STR_RAT_FILT // @DisplayName: Steering control filter frequency // @Description: Steering control input filter. Lower values reduce noise but add delay. // @Range: 0.000 100.000 // @Increment: 0.1 // @Units: Hz // @User: Standard AP_SUBGROUPINFO(_steer_rate_pid, "_STR_RAT_", 1, AR_AttitudeControl, AC_PID), // @Param: _SPEED_P // @DisplayName: Speed control P gain // @Description: Speed control P gain. Converts the error between the desired speed (in m/s) and actual speed to a motor output (in the range -1 to +1) // @Range: 0.010 2.000 // @Increment: 0.01 // @User: Standard // @Param: _SPEED_I // @DisplayName: Speed control I gain // @Description: Speed control I gain. Corrects long term error between the desired speed (in m/s) and actual speed // @Range: 0.000 2.000 // @User: Standard // @Param: _SPEED_IMAX // @DisplayName: Speed control I gain maximum // @Description: Speed control I gain maximum. Constraings the maximum motor output (range -1 to +1) that the I term will generate // @Range: 0.000 1.000 // @Increment: 0.01 // @User: Standard // @Param: _SPEED_D // @DisplayName: Speed control D gain // @Description: Speed control D gain. Compensates for short-term change in desired speed vs actual // @Range: 0.000 0.400 // @Increment: 0.001 // @User: Standard // @Param: _SPEED_FF // @DisplayName: Speed control feed forward // @Description: Speed control feed forward // @Range: 0.000 0.500 // @Increment: 0.001 // @User: Standard // @Param: _SPEED_FILT // @DisplayName: Speed control filter frequency // @Description: Speed control input filter. Lower values reduce noise but add delay. // @Range: 0.000 100.000 // @Increment: 0.1 // @Units: Hz // @User: Standard AP_SUBGROUPINFO(_throttle_speed_pid, "_SPEED_", 2, AR_AttitudeControl, AC_PID), // @Param: _ACCEL_MAX // @DisplayName: Speed control acceleration (and deceleration) maximum in m/s/s // @Description: Speed control acceleration (and deceleration) maximum in m/s/s. 0 to disable acceleration limiting // @Range: 0.0 10.0 // @Increment: 0.1 // @Units: m/s/s // @User: Standard AP_GROUPINFO("_ACCEL_MAX", 3, AR_AttitudeControl, _throttle_accel_max, AR_ATTCONTROL_THR_ACCEL_MAX), // @Param: _BRAKE // @DisplayName: Speed control brake enable/disable // @Description: Speed control brake enable/disable. Allows sending a reversed output to the motors to slow the vehicle. // @Values: 0:Disable,1:Enable // @User: Standard AP_GROUPINFO("_BRAKE", 4, AR_AttitudeControl, _brake_enable, 0), // @Param: _STOP_SPEED // @DisplayName: Speed control stop speed // @Description: Speed control stop speed. Motor outputs to zero once vehicle speed falls below this value // @Range: 0.00 0.50 // @Increment: 0.01 // @Units: m/s // @User: Standard AP_GROUPINFO("_STOP_SPEED", 5, AR_AttitudeControl, _stop_speed, AR_ATTCONTROL_STOP_SPEED_DEFAULT), // @Param: _STR_ANG_P // @DisplayName: Steering control angle P gain // @Description: Steering control angle P gain. Converts the error between the desired heading/yaw (in radians) and actual heading/yaw to a desired turn rate (in rad/sec) // @Range: 1.000 10.000 // @Increment: 0.1 // @User: Standard AP_SUBGROUPINFO(_steer_angle_p, "_STR_ANG_", 6, AR_AttitudeControl, AC_P), // @Param: _STR_ACC_MAX // @DisplayName: Steering control angular acceleration maximum // @Description: Steering control angular acceleartion maximum (in deg/s/s). 0 to disable acceleration limiting // @Range: 0 1000 // @Increment: 0.1 // @Units: deg/s/s // @User: Standard AP_GROUPINFO("_STR_ACC_MAX", 7, AR_AttitudeControl, _steer_accel_max, AR_ATTCONTROL_STEER_ACCEL_MAX), // @Param: _STR_RAT_MAX // @DisplayName: Steering control rotation rate maximum // @Description: Steering control rotation rate maximum in deg/s. 0 to remove rate limiting // @Range: 0 1000 // @Increment: 0.1 // @Units: deg/s // @User: Standard AP_GROUPINFO("_STR_RAT_MAX", 8, AR_AttitudeControl, _steer_rate_max, AR_ATTCONTROL_STEER_RATE_MAX), AP_GROUPEND }; AR_AttitudeControl::AR_AttitudeControl(AP_AHRS &ahrs) : _ahrs(ahrs), _steer_angle_p(AR_ATTCONTROL_STEER_ANG_P), _steer_rate_pid(AR_ATTCONTROL_STEER_RATE_P, AR_ATTCONTROL_STEER_RATE_I, AR_ATTCONTROL_STEER_RATE_D, AR_ATTCONTROL_STEER_RATE_IMAX, AR_ATTCONTROL_STEER_RATE_FILT, AR_ATTCONTROL_DT, AR_ATTCONTROL_STEER_RATE_FF), _throttle_speed_pid(AR_ATTCONTROL_THR_SPEED_P, AR_ATTCONTROL_THR_SPEED_I, AR_ATTCONTROL_THR_SPEED_D, AR_ATTCONTROL_THR_SPEED_IMAX, AR_ATTCONTROL_THR_SPEED_FILT, AR_ATTCONTROL_DT) { AP_Param::setup_object_defaults(this, var_info); } // return a steering servo output from -1.0 to +1.0 given a desired lateral acceleration rate in m/s/s. // positive lateral acceleration is to the right. float AR_AttitudeControl::get_steering_out_lat_accel(float desired_accel, bool skid_steering, bool motor_limit_left, bool motor_limit_right, bool reversed) { // record desired accel for reporting purposes _steer_lat_accel_last_ms = AP_HAL::millis(); _desired_lat_accel = desired_accel; // get speed forward float speed; if (!get_forward_speed(speed)) { // we expect caller will not try to control heading using rate control without a valid speed estimate // on failure to get speed we do not attempt to steer return 0.0f; } // only use positive speed. Use reverse flag instead of negative speeds. speed = fabsf(speed); // enforce minimum speed to stop oscillations when first starting to move if (speed < AR_ATTCONTROL_STEER_SPEED_MIN) { speed = AR_ATTCONTROL_STEER_SPEED_MIN; } // Calculate the desired steering rate given desired_accel and speed float desired_rate = desired_accel / speed; // invert rate if we are going backwards if (reversed) { desired_rate *= -1.0f; } return get_steering_out_rate(desired_rate, skid_steering, motor_limit_left, motor_limit_right, reversed); } // return a steering servo output from -1 to +1 given a heading in radians float AR_AttitudeControl::get_steering_out_heading(float heading_rad, bool skid_steering, bool motor_limit_left, bool motor_limit_right, bool reversed) { // calculate heading error (in radians) const float yaw_error = wrap_PI(heading_rad - _ahrs.yaw); // Calculate the desired turn rate (in radians) from the angle error (also in radians) const float desired_rate = _steer_angle_p.get_p(yaw_error); return get_steering_out_rate(desired_rate, skid_steering, motor_limit_left, motor_limit_right, reversed); } // return a steering servo output from -1 to +1 given a // desired yaw rate in radians/sec. Positive yaw is to the right. float AR_AttitudeControl::get_steering_out_rate(float desired_rate, bool skid_steering, bool motor_limit_left, bool motor_limit_right, bool reversed) { // calculate dt const uint32_t now = AP_HAL::millis(); float dt = (now - _steer_turn_last_ms) / 1000.0f; if ((_steer_turn_last_ms == 0) || (dt > (AR_ATTCONTROL_TIMEOUT_MS / 1000.0f))) { dt = 0.0f; _steer_rate_pid.reset_filter(); // reset desired turn rate to actual turn rate for accel limiting _desired_turn_rate = _ahrs.get_yaw_rate_earth(); } else { _steer_rate_pid.set_dt(dt); } _steer_turn_last_ms = now; // acceleration limit desired turn rate const float change_max = radians(_steer_accel_max) * dt; if (is_positive(dt) && is_positive(change_max)) { desired_rate = constrain_float(desired_rate, _desired_turn_rate - change_max, _desired_turn_rate + change_max); } _desired_turn_rate = desired_rate; // rate limit desired turn rate if (is_positive(_steer_rate_max)) { _desired_turn_rate = constrain_float(_desired_turn_rate, -_steer_rate_max, _steer_rate_max); } float scaler = 1.0f; bool low_speed = false; // scaler to linearize output because turn rate increases as vehicle speed increases on non-skid steering vehicles if (!skid_steering) { // get speed forward float speed; if (!get_forward_speed(speed)) { // we expect caller will not try to control heading using rate control without a valid speed estimate // on failure to get speed we do not attempt to steer return 0.0f; } // only use positive speed. Use reverse flag instead of negative speeds. speed = fabsf(speed); // enforce minimum speed to stop oscillations when first starting to move if (speed < AR_ATTCONTROL_STEER_SPEED_MIN) { low_speed = true; speed = AR_ATTCONTROL_STEER_SPEED_MIN; } scaler = 1.0f / fabsf(speed); } // Calculate the steering rate error (rad/sec) and apply gain scaler // We do this in earth frame to allow for rover leaning over in hard corners float yaw_rate_earth = _ahrs.get_yaw_rate_earth(); // check if reversing if (reversed) { yaw_rate_earth *= -1.0f; } const float rate_error = (desired_rate - yaw_rate_earth) * scaler; // record desired rate for logging purposes only _steer_rate_pid.set_desired_rate(desired_rate); // pass error to PID controller _steer_rate_pid.set_input_filter_all(rate_error); // get feed-forward const float ff = _steer_rate_pid.get_ff(desired_rate * scaler); // get p const float p = _steer_rate_pid.get_p(); // get i unless non-skid-steering rover at low speed or steering output has hit a limit float i = _steer_rate_pid.get_integrator(); if ((!low_speed || skid_steering) && ((is_negative(rate_error) && !motor_limit_left) || (is_positive(rate_error) && !motor_limit_right))) { i = _steer_rate_pid.get_i(); } // get d const float d = _steer_rate_pid.get_d(); // constrain and return final output return constrain_float(ff + p + i + d, -1.0f, 1.0f); } // get latest desired turn rate in rad/sec (recorded during calls to get_steering_out_rate) float AR_AttitudeControl::get_desired_turn_rate() const { // return zero if no recent calls to turn rate controller if ((_steer_turn_last_ms == 0) || ((AP_HAL::millis() - _steer_turn_last_ms) > AR_ATTCONTROL_TIMEOUT_MS)) { return 0.0f; } return _desired_turn_rate; } // get latest desired lateral acceleration in m/s/s (recorded during calls to get_steering_out_lat_accel) float AR_AttitudeControl::get_desired_lat_accel() const { // return zero if no recent calls to lateral acceleration controller if ((_steer_lat_accel_last_ms == 0) || ((AP_HAL::millis() - _steer_lat_accel_last_ms) > AR_ATTCONTROL_TIMEOUT_MS)) { return 0.0f; } return _desired_lat_accel; } // get actual lateral acceleration in m/s/s. returns true on success bool AR_AttitudeControl::get_lat_accel(float &lat_accel) const { float speed; if (!get_forward_speed(speed)) { return false; } lat_accel = speed * _ahrs.get_yaw_rate_earth(); return true; } // return a throttle output from -1 to +1 given a desired speed in m/s (use negative speeds to travel backwards) // motor_limit should be true if motors have hit their upper or lower limits // cruise speed should be in m/s, cruise throttle should be a number from -1 to +1 float AR_AttitudeControl::get_throttle_out_speed(float desired_speed, bool motor_limit_low, bool motor_limit_high, float cruise_speed, float cruise_throttle) { // get speed forward float speed; if (!get_forward_speed(speed)) { // we expect caller will not try to control heading using rate control without a valid speed estimate // on failure to get speed we do not attempt to steer return 0.0f; } // calculate dt const uint32_t now = AP_HAL::millis(); float dt = (now - _speed_last_ms) / 1000.0f; if ((_speed_last_ms == 0) || (dt > (AR_ATTCONTROL_TIMEOUT_MS / 1000.0f))) { dt = 0.0f; _throttle_speed_pid.reset_filter(); } else { _throttle_speed_pid.set_dt(dt); } _speed_last_ms = now; // acceleration limit desired speed if (is_positive(_throttle_accel_max)) { // reset desired speed to current speed on first iteration if (!is_positive(dt)) { desired_speed = speed; } else { const float speed_change_max = _throttle_accel_max * dt; desired_speed = constrain_float(desired_speed, _desired_speed - speed_change_max, _desired_speed + speed_change_max); } } // record desired speed for next iteration _desired_speed = desired_speed; // calculate speed error and pass to PID controller const float speed_error = desired_speed - speed; _throttle_speed_pid.set_input_filter_all(speed_error); // record desired speed for logging purposes only _throttle_speed_pid.set_desired_rate(desired_speed); // get feed-forward const float ff = _throttle_speed_pid.get_ff(desired_speed); // get p const float p = _throttle_speed_pid.get_p(); // get i unless moving at low speed or motors have hit a limit float i = _throttle_speed_pid.get_integrator(); if ((is_negative(speed_error) && !motor_limit_low && !_throttle_limit_low) || (is_positive(speed_error) && !motor_limit_high && !_throttle_limit_high)) { i = _throttle_speed_pid.get_i(); } // get d const float d = _throttle_speed_pid.get_d(); // calculate base throttle (protect against divide by zero) float throttle_base = 0.0f; if (is_positive(cruise_speed) && is_positive(cruise_throttle)) { throttle_base = desired_speed * (cruise_throttle / cruise_speed); } // calculate final output float throttle_out = (ff+p+i+d+throttle_base); // clear local limit flags used to stop i-term build-up as we stop reversed outputs going to motors _throttle_limit_low = false; _throttle_limit_high = false; // protect against reverse output being sent to the motors unless braking has been enabled if (!_brake_enable) { // if both desired speed and actual speed are positive, do not allow negative values if ((desired_speed >= 0.0f) && (throttle_out <= 0.0f)) { throttle_out = 0.0f; _throttle_limit_low = true; } if ((desired_speed <= 0.0f) && (throttle_out >= 0.0f)) { throttle_out = 0.0f; _throttle_limit_high = true; } } // final output throttle in range -1 to 1 return throttle_out; } // return a throttle output from -1 to +1 to perform a controlled stop. returns true once the vehicle has stopped float AR_AttitudeControl::get_throttle_out_stop(bool motor_limit_low, bool motor_limit_high, float cruise_speed, float cruise_throttle, bool &stopped) { // get current system time const uint32_t now = AP_HAL::millis(); // if we were stopped in the last 300ms, assume we are still stopped bool _stopped = (_stop_last_ms != 0) && (now - _stop_last_ms) < 300; // get speed forward float speed; if (!get_forward_speed(speed)) { // could not get speed so assume stopped _stopped = true; } else { // if vehicle drops below _stop_speed consider it stopped if (fabsf(speed) <= fabsf(_stop_speed)) { _stopped = true; } } // set stopped status for caller stopped = _stopped; // if stopped return zero if (stopped) { // update last time we thought we were stopped _stop_last_ms = now; return 0.0f; } else { // clear stopped system time _stop_last_ms = 0; // run speed controller to bring vehicle to stop return get_throttle_out_speed(0.0f, motor_limit_low, motor_limit_high, cruise_speed, cruise_throttle); } } // get forward speed in m/s (earth-frame horizontal velocity but only along vehicle x-axis). returns true on success bool AR_AttitudeControl::get_forward_speed(float &speed) const { Vector3f velocity; if (!_ahrs.get_velocity_NED(velocity)) { // use less accurate GPS, assuming entire length is along forward/back axis of vehicle if (AP::gps().status() >= AP_GPS::GPS_OK_FIX_3D) { if (labs(wrap_180_cd(_ahrs.yaw_sensor - AP::gps().ground_course_cd())) <= 9000) { speed = AP::gps().ground_speed(); } else { speed = -AP::gps().ground_speed(); } return true; } else { return false; } } // calculate forward speed velocity into body frame speed = velocity.x*_ahrs.cos_yaw() + velocity.y*_ahrs.sin_yaw(); return true; } // get latest desired speed recorded during call to get_throttle_out_speed. For reporting purposes only float AR_AttitudeControl::get_desired_speed() const { // return zero if no recent calls to speed controller if ((_speed_last_ms == 0) || ((AP_HAL::millis() - _speed_last_ms) > AR_ATTCONTROL_TIMEOUT_MS)) { return 0.0f; } return _desired_speed; } // get minimum stopping distance (in meters) given a speed (in m/s) float AR_AttitudeControl::get_stopping_distance(float speed) { // get maximum vehicle deceleration const float accel_max = get_accel_max(); // avoid divide by zero if ((accel_max <= 0.0f) || is_zero(speed)) { return 0.0f; } // assume linear deceleration return 0.5f * sq(speed) / accel_max; }
sharescience/ardupilot
libraries/APM_Control/AR_AttitudeControl.cpp
C++
gpl-3.0
19,898
/** * TrackerMap * * @author Alexey Grebenshchikov * @copyright (c) 2008, by Alexey Grebenshchikov * @date 14 october 2010 * @version 0.1 * * @license login.js is licensed under the terms of the Open Source * LGPL 3.0 license. Commercial use is permitted to the extent that the * code/component(s) do NOT become part of another Open Source or Commercially * licensed development library or toolkit without explicit permission. * * License details: http://www.gnu.org/licenses/lgpl.html */ /* TrackerMap - map wrapper */ Ext.ns('Application'); Application.TrackerMap = Ext.extend(Object, { map : null, // map object baseLayer : null, // base layer devicesLayer : null, // layer fo devices markers viewProjection : new OpenLayers.Projection("EPSG:4326"), // default view projection devicesMarkers : {}, // array of markers /** * constructor */ constructor: function() { var options = { projection: new OpenLayers.Projection('EPSG:900913'), displayProjection: new OpenLayers.Projection('EPSG:4326'), units: 'dd', minResolution: 'auto', maxResolution: 'auto', controls: [ new OpenLayers.Control.OverviewMap(), new OpenLayers.Control.MousePosition(), new OpenLayers.Control.Navigation(), new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.Attribution() ] }; this.map = new OpenLayers.Map('map', options); this.baseLayer = new OpenLayers.Layer.OSM.Mapnik('Mapnik'); var planeStyleMap = new OpenLayers.StyleMap({ externalGraphic: "/images/marker.png", graphicWidth: 21, graphicHeight: 25, fillOpacity: 0.60, rotation: "${angle}" }); this.devicesLayer = new OpenLayers.Layer.Vector('Devices', { projection: new OpenLayers.Projection("EPSG:4326"), visibility: true, displayInLayerSwitcher: false, styleMap: planeStyleMap }); this.map.addLayers([this.baseLayer, this.devicesLayer]); this.setCenter(37.650417, 55.757276, 5); }, // eo constructor /** * set center of map */ setCenter: function(lon, lat, zoom) { var lonlat = new OpenLayers.LonLat(lon, lat); this.map.setCenter(lonlat.transform(this.viewProjection, this.map.projection), zoom); }, // eo setCenter /* * call when click on device in grid */ refreshMarker: function(record) { var imei = record.data['imei']; var lat = parseFloat(record.data['latitude']); var lon = parseFloat(record.data['longitude']); var marker = null; var zoom = this.map.getZoom(); if(this.devicesMarkers[imei] == null) { //marker = new OpenLayers.Marker(lonlat); var geometry = new OpenLayers.Geometry.Point(lon, lat).transform(this.viewProjection, this.map.projection); marker = new OpenLayers.Feature.Vector(geometry, { angle: 0, poppedup: false }); this.devicesMarkers[imei] = marker; this.devicesLayer.addFeatures(marker); this.setCenter(lon, lat, zoom); } else { var lonlat = new OpenLayers.LonLat(lon, lat).transform(this.viewProjection, this.map.projection); marker = this.devicesMarkers[imei]; marker.move(lonlat); this.setCenter(lon, lat, zoom); } }, /* * get all devices markers */ getDevicesMarkers: function() { return this.devicesMarkers; } }); // eo TrackerMap
LiveStalker/phermes
tracker/media/js/Application.TrackerMap.js
JavaScript
gpl-3.0
3,922
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Watts</title> <!-- Latest compiled and minified CSS --> {{ Html::style('css/bootstrap.min.css') }} <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- Referencing Bootstrap JS that is hosted locally --> {{ Html::script('js/bootstrap.min.js') }} <link rel="stylesheet" type="text/css" href="css/sweetalert.css"> <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" > <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet" type="text/css"> <!-- Styles --> <style type="text/css"> h3 { font-family: 'Pacifico'; font-size: 60px; } .input-group { margin-top: 20px; margin-bottom: 20px; margin-left: 20px; margin-right: 20px; } .btn { margin-bottom: 20px; width: 350px; } .container { margin-top: 140px; } .col-sm-4 { margin-left: 390px; } hr { width: 180px; } </style> </head> <body> <div class="container" align="center"> <script src="js/sweetalert.min.js"></script> <script> @if (notify()->ready()) swal({ title: "{!! notify()->message() !!}", text: "{!! notify()->option('text') !!}", type: "{{ notify()->type() }}", timer: 2000, showConfirmButton: false }); @endif </script> <h3>Watts</h3> <hr> <form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}"> {{ csrf_field() }} <div class="col-sm-4"> <div class="panel panel-default"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input id="email" type="text" class="form-control" name="email" placeholder="Email" required autofocus> </div> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> <input id="password" type="password" class="form-control" name="password" placeholder="Password" required autofocus> </div> </div> <button type="submit" class="btn btn-primary">Log In</button> <button class="btn btn-default" onclick='window.location="signup"'>Sign Up</button> </div> </form> </div> </body> </html>
warezjack/Watts
resources/views/login.blade.php
PHP
gpl-3.0
2,590
/* * Process Hacker - * Process properties: Token page * * Copyright (C) 2009-2016 wj32 * * This file is part of Process Hacker. * * Process Hacker 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. * * Process Hacker 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 Process Hacker. If not, see <http://www.gnu.org/licenses/>. */ #include <phapp.h> #include <procprp.h> #include <procprpp.h> NTSTATUS NTAPI PhpOpenProcessTokenForPage( _Out_ PHANDLE Handle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ PVOID Context ) { NTSTATUS status; HANDLE processHandle; if (!NT_SUCCESS(status = PhOpenProcess( &processHandle, ProcessQueryAccess, (HANDLE)Context ))) return status; status = PhOpenProcessToken(processHandle, DesiredAccess, Handle); NtClose(processHandle); return status; } INT_PTR CALLBACK PhpProcessTokenHookProc( _In_ HWND hwndDlg, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { switch (uMsg) { case WM_DESTROY: { RemoveProp(hwndDlg, PhMakeContextAtom()); } break; case WM_SHOWWINDOW: { if (!GetProp(hwndDlg, PhMakeContextAtom())) // LayoutInitialized { PPH_LAYOUT_ITEM dialogItem; HWND groupsLv; HWND privilegesLv; // This is a big violation of abstraction... dialogItem = PhAddPropPageLayoutItem(hwndDlg, hwndDlg, PH_PROP_PAGE_TAB_CONTROL_PARENT, PH_ANCHOR_ALL); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_USER), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_USERSID), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_VIRTUALIZED), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_APPCONTAINERSID), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_GROUPS), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_PRIVILEGES), dialogItem, PH_ANCHOR_ALL); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_INSTRUCTION), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_BOTTOM); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_INTEGRITY), dialogItem, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM); PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_ADVANCED), dialogItem, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM); PhDoPropPageLayout(hwndDlg); groupsLv = GetDlgItem(hwndDlg, IDC_GROUPS); privilegesLv = GetDlgItem(hwndDlg, IDC_PRIVILEGES); if (ListView_GetItemCount(groupsLv) != 0) { ListView_SetColumnWidth(groupsLv, 0, LVSCW_AUTOSIZE); ExtendedListView_SetColumnWidth(groupsLv, 1, ELVSCW_AUTOSIZE_REMAININGSPACE); } if (ListView_GetItemCount(privilegesLv) != 0) { ListView_SetColumnWidth(privilegesLv, 0, LVSCW_AUTOSIZE); ListView_SetColumnWidth(privilegesLv, 1, LVSCW_AUTOSIZE); ExtendedListView_SetColumnWidth(privilegesLv, 2, ELVSCW_AUTOSIZE_REMAININGSPACE); } SetProp(hwndDlg, PhMakeContextAtom(), (HANDLE)TRUE); } } break; } return FALSE; }
Ritan/processhacker2
ProcessHacker/prpgtok.c
C
gpl-3.0
4,407
/* * Copyright (C) 2015 Aaron Lucia * * 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 filesync.engine; import filesync.SyncIndex; import filesync.SyncStats; import filesync.engine.DirectoryCrawler.CrawlState; import java.util.EventObject; /** * * @author Aaron Lucia * @version Dec 16, 2014 */ public class SyncEvent extends EventObject { private final CrawlState state; private final SyncStats stats; private final SyncIndex index; public SyncEvent(Object source, CrawlState state, SyncStats stats, SyncIndex index) { super(source); this.state = state; this.stats = stats; this.index = index; } public CrawlState getState() { return state; } public SyncStats getStats() { return stats; } public SyncIndex getIndex() { return index; } }
engineal/FileSync
src/filesync/engine/SyncEvent.java
Java
gpl-3.0
1,460
NODE_ENV=production ./node_modules/.bin/browserify -t [ babelify --presets [ react es2015 ] ] main.jsx | ./node_modules/uglifyify/node_modules/.bin/uglifyjs -c > bundle.js
vipoo/iRacingReplayOverlay.net
DeploymentSite/build-prod.sh
Shell
gpl-3.0
173
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_todolists_ap_session'
eddygarcas/ruby_course
first_app/todolists_ap/config/initializers/session_store.rb
Ruby
gpl-3.0
144
FROM alpine:latest MAINTAINER ClusterboxCloud <clusterbox@clusterboxcloud.com> # global environment settings ENV RCLONE_VERSION="current" ENV PLATFORM_ARCH="amd64" # s6 environment settings ENV S6_BEHAVIOUR_IF_STAGE2_FAILS=2 ENV S6_KEEP_ENV=1 # install packages RUN \ apk update && \ apk add --no-cache \ ca-certificates # Install Node.js RUN apk add --update nodejs nodejs-npm && npm install npm@latest -g # Install CURL RUN apk add --update curl # Install CURL RUN apk add --update nano # Install Bash RUN apk add --update bash && rm -rf /var/cache/apk/* # install build packages RUN \ apk add --no-cache --virtual=build-dependencies \ wget \ curl \ unzip && \ cd tmp && \ wget -q http://downloads.rclone.org/rclone-${RCLONE_VERSION}-linux-${PLATFORM_ARCH}.zip && \ unzip /tmp/rclone-${RCLONE_VERSION}-linux-${PLATFORM_ARCH}.zip && \ mv /tmp/rclone-*-linux-${PLATFORM_ARCH}/rclone /usr/bin && \ apk add --no-cache --repository http://nl.alpinelinux.org/alpine/edge/community \ shadow && \ # cleanup apk del --purge \ build-dependencies && \ rm -rf \ /tmp/* \ /var/tmp/* \ /var/cache/apk/* # create abc user RUN \ mkdir -p /config /app /defaults /data && \ touch /var/lock/rclone.lock # add local files COPY root/ / # Install express.js RUN npm install VOLUME ["/config"] EXPOSE 8080 #ENTRYPOINT ["/init"] CMD ["node", "server.js"]
clusterbox/docker-rclone
Dockerfile
Dockerfile
gpl-3.0
1,372
/* * Copyright (C) 2010-2012 Taylor Leese (tleese22@gmail.com) * * This file is part of jappstart. * * jappstart 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. * * jappstart 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 jappstart. If not, see <http://www.gnu.org/licenses/>. */ /** * The <code>com.assetmanager.form</code> package contains the various * form beans. */ package com.assetmanager.form;
igloooooo/asset-manager
src/main/java/com/assetmanager/form/package-info.java
Java
gpl-3.0
905
CREATE TABLE "table_3_fy2013_percent_change_in_base_operating_drg_payment_amount" ( "change_in_medicare_payments" text, "number_of_hospitals_receiving_this_change" real );
talos/docker4data
data/socrata/data.medicare.gov/table_3_fy2013_percent_change_in_base_operating_drg_payment_amount/schema.sql
SQL
gpl-3.0
174
package com.idkjava.thelements; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Register extends Activity{ // This is the screen for registering the user Button SaveDetails; EditText Username; EditText Password; EditText Phone; EditText Email; SharedPreferences sharedpreferences; public static final String PREFS_NAME = "RegisterUser" ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register_user); Username = (EditText)findViewById(R.id.edt_username); Password = (EditText)findViewById(R.id.edt_password); Phone = (EditText)findViewById(R.id.edt_email); Email = (EditText)findViewById(R.id.edt_phone); SaveDetails= (Button) findViewById(R.id.SaveDetails); } public void SaveDetails(View view){ sharedpreferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE); //sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString("Username", Username.getText().toString()); editor.putString("Password", Password.getText().toString()); editor.putString("Phone", Phone.getText().toString()); editor.putString("Email", Email.getText().toString()); editor.commit(); Toast.makeText(getApplicationContext(), "You have Registered successfully.Enter details to Login...", Toast.LENGTH_LONG).show(); //editor.clear(); Intent intent = new Intent(Register.this, Login.class); startActivity(intent); } }
Keerthanava/The-Elements
TheElements-dev/src/com/idkjava/thelements/Register.java
Java
gpl-3.0
1,927
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Thu Feb 05 20:10:23 EST 2015 --> <title>cpw.mods.fml.relauncher (Forge API)</title> <meta name="date" content="2015-02-05"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../cpw/mods/fml/relauncher/package-summary.html" target="classFrame">cpw.mods.fml.relauncher</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="IFMLCallHook.html" title="interface in cpw.mods.fml.relauncher" target="classFrame"><i>IFMLCallHook</i></a></li> <li><a href="IFMLLoadingPlugin.html" title="interface in cpw.mods.fml.relauncher" target="classFrame"><i>IFMLLoadingPlugin</i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="CoreModManager.html" title="class in cpw.mods.fml.relauncher" target="classFrame">CoreModManager</a></li> <li><a href="FileListHelper.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FileListHelper</a></li> <li><a href="FMLCorePlugin.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLCorePlugin</a></li> <li><a href="FMLInjectionData.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLInjectionData</a></li> <li><a href="FMLLaunchHandler.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLLaunchHandler</a></li> <li><a href="FMLRelaunchLog.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLRelaunchLog</a></li> <li><a href="FMLSecurityManager.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLSecurityManager</a></li> <li><a href="ModListHelper.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ModListHelper</a></li> <li><a href="ModListHelper.JsonModList.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ModListHelper.JsonModList</a></li> <li><a href="ReflectionHelper.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ReflectionHelper</a></li> <li><a href="ServerLaunchWrapper.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ServerLaunchWrapper</a></li> </ul> <h2 title="Enums">Enums</h2> <ul title="Enums"> <li><a href="Side.html" title="enum in cpw.mods.fml.relauncher" target="classFrame">Side</a></li> </ul> <h2 title="Exceptions">Exceptions</h2> <ul title="Exceptions"> <li><a href="FMLSecurityManager.ExitTrappedException.html" title="class in cpw.mods.fml.relauncher" target="classFrame">FMLSecurityManager.ExitTrappedException</a></li> <li><a href="ReflectionHelper.UnableToAccessFieldException.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ReflectionHelper.UnableToAccessFieldException</a></li> <li><a href="ReflectionHelper.UnableToFindClassException.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ReflectionHelper.UnableToFindClassException</a></li> <li><a href="ReflectionHelper.UnableToFindFieldException.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ReflectionHelper.UnableToFindFieldException</a></li> <li><a href="ReflectionHelper.UnableToFindMethodException.html" title="class in cpw.mods.fml.relauncher" target="classFrame">ReflectionHelper.UnableToFindMethodException</a></li> </ul> <h2 title="Annotation Types">Annotation Types</h2> <ul title="Annotation Types"> <li><a href="IFMLLoadingPlugin.DependsOn.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">IFMLLoadingPlugin.DependsOn</a></li> <li><a href="IFMLLoadingPlugin.MCVersion.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">IFMLLoadingPlugin.MCVersion</a></li> <li><a href="IFMLLoadingPlugin.Name.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">IFMLLoadingPlugin.Name</a></li> <li><a href="IFMLLoadingPlugin.SortingIndex.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">IFMLLoadingPlugin.SortingIndex</a></li> <li><a href="IFMLLoadingPlugin.TransformerExclusions.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">IFMLLoadingPlugin.TransformerExclusions</a></li> <li><a href="SideOnly.html" title="annotation in cpw.mods.fml.relauncher" target="classFrame">SideOnly</a></li> </ul> </div> </body> </html>
Foghrye4/ihl
javadoc/cpw/mods/fml/relauncher/package-frame.html
HTML
gpl-3.0
4,428
<?php session_start(); $selectedPage="layout"; include "class/db.class.php"; if(isset($_POST) && isset($_FILES['userfile']) && $_FILES['userfile']) { include "class/upload.fn.php"; $filename = basename($_FILES['userfile']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); $ext = strtolower($ext); // uploadFile(file,folderPath,fileName,overwriteFlag) $val = uploadFile($_FILES['userfile'],"images/uploads/","background_roomID".$_POST['roomID'].".".$ext,1); if($val==1) { // find the size of the uploaded image if possible // if its > 700x700 then save its dimentions to the config for the canvas size // else default to a 1500x1500 canvas $imageSize = getimagesize('images/uploads/background_roomID'.$_POST['roomID'].".".$ext); if(is_numeric($imageSize[0]) && $imageSize[0] >= 700) $sizeX=$imageSize[0]; else $sizeX=1500; if(is_numeric($imageSize[1]) && $imageSize[1] >= 700) $sizeY=$imageSize[1]; else $sizeY=1500; $config = new config; $config->setItem('buildingCanvasX',$sizeX); $config->setItem('buildingCanvasY',$sizeY); header("Location: roomlayout.php?room=".$_POST['roomID']."&upload=complete"); } else { echo "<b>Error Uploading</b><br/>"; switch($val) { case "error_uploading_moving": echo "There was an error while trying to transfer the file on the server. Please check that you have permissions to write the file to the server"; break; case "file_size_or_ext": echo "The file was not accepted for upload, please check the size and extension"; break; case "no_file_provided": echo "Oops..<br/>We couldn't find the file you wanted to upload, please check the form and try again"; break; default; echo $val; break; }; } } // simple function to delete a building background IMG elseif(isset($_GET['action']) && $_GET['action'] == 'removeBG' && is_numeric($_GET['room'])) { $deleted=0; if(file_exists('images/uploads/background_roomID'.$_GET['room'].'.jpg')) if(unlink('images/uploads/background_roomID'.$_GET['room'].'.jpg')) $deleted=1; if(file_exists('images/uploads/background_roomID'.$_GET['room'].'.jpeg')) if(unlink('images/uploads/background_roomID'.$_GET['room'].'.jpeg')) $deleted=1; if(file_exists('images/uploads/background_roomID'.$_GET['room'].'.png')) if(unlink('images/uploads/background_roomID'.$_GET['room'].'.png')) $deleted=1; if(file_exists('images/uploads/background_roomID'.$_GET['room'].'.gif')) if(unlink('images/uploads/background_roomID'.$_GET['room'].'.gif')) $deleted=1; if($deleted) header("location: ".$_SERVER['PHP_SELF']."?action=deletedBackground&room=".$_GET['room']); else header("Location: ".$_SERVER['PHP_SELF']."?error=cannotDelBG&room=".$_GET['room']); } else { $room=false; $floor=false; $building=false; // check the user was requesting a valid room if(isset($_GET['room']) && is_numeric($_GET['room'])) { $room = new room($_GET['room']); $floor = new floor($room->floorID); $building = new building($floor->buildingID); } if(!$room && !$floor && !$building) header("Location: buildings.php"); $globalTopic="Room Layout"; $floors = new floors; $rooms = new rooms; $buildings = new buildings; $logs = new logs; $racks = new racks; $owners = new owners; $header = "<link rel='stylesheet' type='text/css' href='theme/room.css' /> <script type='text/javascript'> var roomID = ". $_GET['room'] ."; </script> <script type='text/javascript' src='theme/js/mapbox.min.js'></script> <script type='text/javascript' src='theme/js/rotate.js'></script> <script type='text/javascript' src='theme/roomlayout.js'></script>"; include "theme/" . $theme . "/top.php"; ?> <script type="text/javascript"> $(document).ready(function() { resizeCanvas("#viewPortal"); $('#viewPortal').mapbox({pan: true, zoom: false,defaultX:0,defaultY:0}); <?php $config = new config; $lockFloorTiles=$config->returnItem('lockFloorTiles'); if($lockFloorTiles==1) { echo '$.lockedTiles = "locked";'; echo 'lockFloorTiles(); '; } ?> }); </script> <style> .mapContent { <?php if(isset($_GET['room']) && is_numeric($_GET['room'])) if(file_exists("images/uploads/background_roomID".$_GET['room'].".jpg")) echo " background: #ffffff url('images/uploads/background_roomID".$_GET['room'].".jpg') no-repeat;"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".jpeg")) echo " background: #ffffff url('images/uploads/background_roomID".$_GET["room"].".jpeg') no-repeat;"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".png")) echo " background: #ffffff url('images/uploads/background_roomID".$_GET["room"].".png') no-repeat;"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".gif")) echo " background: #ffffff url('images/uploads/background_roomID".$_GET['room'].".gif') no-repeat;"; else echo " background: #ffffff;"; ?> } </style> <div id="main"> <div id="left"> <div class="module" id="breadcrumb" > <span style="float:left"><strong><a href="buildings.php">Buildings</a> &#187; <?php echo $building->name; ?> &#187; <a href="rooms.php?floor=<?php echo $floor->floorID; ?>">Level: <?php echo $floor->name; ?></a> &#187; <a href="room.php?room=<?php echo $room->roomID; ?>"><?php echo $room->name; ?></a> &#187; Layout</strong></span> <span id='links' style='float: right;' ><a href="room.php?room=<?php echo $_GET['room']; ?>" >Back to Room</a> - <a href="http://help.racksmith.net/guide.php?guide=managelayout" target="_help">Help</a></span> </div> <div class="module" id='canvasHolder' > <div id="viewPortal" > <div> <div class="mapContent" style="height: 2000px;width: 2000px;border: 2px solid #000000;" ></div> </div> </div> </div> <div class="module" id="createRack" style="display: none"> <div class="sectionHeader" > <strong>Create a new Rack</strong> <a href="#" class="closeLink closeDOMWindow"><img src="images/icons/close_module.gif" border="0" alt="Close" /></a> </div> <div class="form" id="createRackForm"> <p> <form method="post" > <table width="80%" class="formTable"> <colgroup align="left" class="tblfirstRow"></colgroup> <tr> <td><label for="name" >Name:</label></td> <td colspan="3"><input name="name" type="text" id="name" size="16"/><input type="hidden" id="room" name="room" value="<?php echo $_GET['room']; ?>" /><input name="posx" type="hidden" id="posx" value="" /><input name="posy" type="hidden" id="posy" value="" /></td> </tr> <tr> <td><label for="ownerID" >Owner:</label></td> <td colspan="3"> <select name="ownerID"> <?php foreach($owners->getAll() as $owner) { ?> <option value="<?php echo$owner->ownerID; ?>" ><?php echo $owner->name; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><label for="model" >Model:</label></td> <td colspan="3"><input name="model" type="text" id="model" size="30" /></td> </tr> <tr> <td><label for="RU" >RU:</label></td> <td><input name="RU" type="text" id="RU" size="2" /> <i>rack units</i></td> <td class="tblfirstRow"><label for="width" >Width:</label></td> <td><input name="width" type="text" id="width" value="19" size="3" /> <i>inch</i></td> </tr> <tr> <td><label for="depth" >Depth:</label></td><td> <select name="depth" id="depth" > <option value="450" >450mm</option> <option value="600" SELECTED>600mm</option> <option value="800" >800mm</option> <option value="900" >900mm</option> <option value="1000" >1000mm</option> </select> </td> <td class="tblfirstRow"><label for="height" >Height:</label></td> <td><input name="height" type="text" id="height" value="" size="3" /> <i>inch</i></td> </tr> <tr><td>Side Mountable Objects:</td> <td><select name="sideMountable" > <option value="0" >None</option> <option value="1" >Left</option> <option value="2" >Right</option> <option value="3" >Both</option> </select> </td></tr> <tr> <td><label for="notes" >Notes:</label></td> <td colspan="3"><textarea name='notes' style='width: 550px;height: 60px;'></textarea></td> </tr> <tr> <td></td> <td colspan="3"> <input type="submit" value="Submit" class="rackCreateSubmit" /> <div class="error" style="display:none;" ></div> </td> </tr> </table> </form> <div class="success" style="display: none;" >Rack Created</div> </p> </div> </div> <div class="module" id="uploadBackground" style="display:none;"> <div class="sectionHeader" > <strong>Upload a background</strong> <a href="#" class="closeLink closeDOMWindow"><img src="images/icons/close_module.gif" border="0" alt="Close" /></a> </div> <p> <div id="uploadBackgroundForm" class="popupModule"> <?php if(is_writable('images/uploads/')) { ?> If you have a room layout or detail drawing you can upload it as a background.<br/> This means when using the racks page browsing content will seem more intuitive. Images much be in PNG, GIF or JPG format and we suggest having it 1000X1000px or larger.<br/><br/><hr/> <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data"> <input type="file" name="userfile" size="40" maxlength="100"><hr/> <input type="submit" name="submit" value="Start Uploading"> <input name="name" type="hidden" id="name" value="" /> <input name="roomID" type="hidden" id="roomID" value="<?php echo $room->roomID; ?>" /> <?php if(isset($_GET['room']) && is_numeric($_GET['room'])) if(file_exists("images/uploads/background_roomID".$_GET['room'].".jpg")) $filename = "images/uploads/background_roomID".$_GET['room'].".jpg"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".jpeg")) $filename = "images/uploads/background_roomID".$_GET["room"].".jpeg"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".png")) $filename = "images/uploads/background_roomID".$_GET["room"].".png"; else if(file_exists("images/uploads/background_roomID".$_GET['room'].".gif")) $filename = "images/uploads/background_roomID".$_GET['room'].".gif"; else $filename = ""; if(file_exists($filename)) echo '<hr/> <a href="#" onclick="if (confirm(\'Are you sure you wish to delete the existing background?\')) { location.href = \''.$_SERVER["PHP_SELF"].'?action=removeBG&room='.$room->roomID.'\'; } "><img src="images/icons/delete_small.gif" /> Remove current background</a> <p><center> <img src="'.$filename.'" alt="Racksmith Room Background" width="650px" style="border: 4px solid #cccccc" /> </center></p>'; ?> </form> <?php } else echo "<div class='notice' >/images/uploads/ is not writable<br/>A background image cannot be uploaded in this state. Please contact your system administrator or read more at <a href='http://help.racksmith.net/guide.php?search=upload+background' target='_help' >help.racksmith.net</a></div> <br/><br/><a href='#' class='closeDOMWindow'><img src='images/icons/close_module.gif' border='0' alt='Close' />Close this window</a><br/>"; ?> </div> </p> </div> </div> <div id="right"> <div class="module"> <strong>Views &amp; Controls</strong> <p> <table class="dataTable"> <tr><td valign="top"> <input type="checkbox" checked id="floortiles" /> <label for='floortiles' >Show Floor Tiles</label><br /> <input type="checkbox" checked id="racks" /> <label for='racks' >Show Racks</label><br /> <input type="checkbox" checked id="cabletrays" /> <label for='cabletrays' >Show Cable Trays</label></td> <td valign="top"> <input type="checkbox" id="lockfloortiles" <?php if($lockFloorTiles==1) { echo 'checked'; }?>/> <label for='lockfloortiles' >Lock Floor Tiles</label> </td> </tr> </table> </p> <strong>Static Items</strong> <p> <div class="roomInventory inventoryHolder"> <a href="#" class='inventoryTitle'>Racks (1)</a> <div class="inventory"> <table style="width:auto;" > <tr> <td width="40px"><img class="toolbaritem rack newRack" style='z-index:999;' id="newRack" title="Server Rack" src="images/tiles/rack01.gif" />Generic</td> </tr> </table> </div> <a href="#" class='inventoryTitle'>Floor Tiles (3)</a> <div class="inventory" style="height: 60px;"> <table style="width:auto;" class="tileTbl"> <tr> <td width="40px"><img class="toolbaritem floortile" id="floortile1" title="Raised Floor" src="images/tiles/floortile2.gif" />Aluminium 600x600</td> <td width="40px"><img class="toolbaritem floortile" id="floortile3" title="Concrete" src="images/tiles/concrete.gif" />Concrete 32x32</td> <td width="40px"><img class="toolbaritem floortile" id="floortile2" title="Unusable" src="images/tiles/floortile3.gif" />Other 600x600</td> </tr> </table> </div> <a href="#" class='inventoryTitle'>Cable Trays (3)</a> <div class="inventory" > <table style="width:auto;"> <tr> <td width="25"><div class="toolbaritem cabletray" id="cabletray1" title="Cable Tray"></div></td> <td width="25"><div class="toolbaritem cabletray" id="cabletray2" title="Cable Tray"></div></td> <td width="25"><div class="toolbaritem cabletray" id="cabletray3" title="Cable Tray"></div></td> </tr> </table> </div> <a href="#" class='inventoryTitle'>Misc (3)</a> <div class="inventory" > <table style="width:auto;"> <tr> <td width="50px"><div class="toolbaritem floortile hotAisle" id="hotAisle" title="Hot Aisle"></div>Hot Aisle</td> <td width="50px"><div class="toolbaritem floortile coldAisle" id="coldAisle" title="Cold Aisle"></div>Cold Aisle</td> <td width="50px"><img class="toolbaritem floortile" id="floortile4" title="Power" src="images/tiles/power1.jpg" />Power</td> <td width="50px"><img class="toolbaritem floortile" id="floortile5" title="Administration" src="images/tiles/admin1.jpg" />Admin</td> </tr> </table> </div> </div></p> <?php $deviceTypesClass = new deviceTypes(); $deviceTypes = $deviceTypesClass->getAll(); $templatesClass = new templates; $templates = $templatesClass->getByCategory(FLOOR_DEVICE); if(is_array($templates)) { echo ' <strong>Floor Devices</strong> <p> <div class="roomInventory inventoryHolder">'; foreach($templates as $key=>$deviceType) { ?> <a href="#" class='inventoryTitle'><?php if(isset($deviceTypes[$key]->name)) { echo $deviceTypes[$key]->name; } else { echo "** error with name**"; } ?> (<?php echo count($deviceType); ?>)</a> <div class="inventory" style="padding: 0px;"> <ul> <li class="search"><div>Search: <input class='inventorySearchField' type='text' size='20'/> <img src='images/icons/close_module.gif' style='display:none;' alt='clear search' class='inventoryClearSearch' /></div></li> <?php foreach($deviceType as $template) { if($template->deleted!=1) echo '<li class="item"><div class="toolbaritem newDevice" href="#'.$template->templateID.'"><span>'.ucwords($template->getMeta(12,1)) . ' ' . $template->name.'</span></div></li>'; } echo "<li class='inventoryAdd' ><a href='manageTemplates.php?deviceType=".$key."' >Create new template</a></li> </ul></div>"; } ?> <a href="#" class='inventoryTitle'>Inventory</a> <div id="floorPageInventory" class="inventory" > <ul> <!-- removed <li class="search"><div>Search: <input class='inventorySearchField' type='text' size='20'/> <img src='images/icons/close_module.gif' style='display:none;' alt='clear search' class='inventoryClearSearch' /></div></li>--> <?php foreach($racks->getByParent(0, "room") as $rack) { ?> <li class="item"><div class="item rack rackID<?php echo $rack->rackID; ?>" id="rack<?php echo $rack->rackID; ?>" title="<?php echo $rack->depth; ?>"><?php echo $rack->name; ?></div></li> <?php } $devices=new devices; foreach($devices->getByParent(0, "room") as $device) echo "<li class='toolbaritem item inventoryDevice' id='device".$device->deviceID."'>".$device->name."</li>"; ?> </ul> </div><?php echo ' </div></p>'; } ?> <hr/> <div style="text-align:right;" > <strong><a href="#uploadBackground" class="newDOMWindow">Adjust the Background</a></strong><br/> <strong><a href="templates.php">Manage Templates</a></strong> </div> </div> <div class="inventoryHelper" style="display:none;height:32px;background-color:#000000"></div> <div class="module" > <strong>Last Highlighted Item</strong> <div class="layoutItemInfo" > <p> <h5>General</h5> <table class="metaData"> <tr><td width="60px" align="right"><em>Name:</em></td><td><span id="highlightedName" ></span></td></tr> <tr><td align="right"><em>Type:</em></td><td><span id="highlightedDevType" ></span></td></tr> </table> <h5>Dimensions</h5> <table class="metaData"> <tr><td align="right" width="60px"><em>Width:</em></td><td><span id="resizeWidth" >###</span> <span style="font-style:italic;"> floor tile/s</span></td></tr> <tr><td align="right"><em>Depth:</em></td><td><span id="resizeHeight" >###</span></td></tr> </table> </p> </div> </div> </div> </div> <div id='menus' ></div> <?php include "theme/" . $theme . "/base.php"; } ?>
jifilis/racksmith
roomlayout.php
PHP
gpl-3.0
20,849
--- layout: politician2 title: pillelli sunil profile: party: BSP constituency: Eluru state: Andhra Pradesh education: level: details: not given photo: sex: caste: religion: current-office-title: crime-accusation-instances: 0 date-of-birth: 1975 profession: networth: assets: liabilities: pan: twitter: website: youtube-interview: wikipedia: candidature: - election: Lok Sabha 2009 myneta-link: http://myneta.info/ls2009/candidate.php?candidate_id=4372 affidavit-link: http://myneta.info/candidate.php?candidate_id=4372&scan=original expenses-link: constituency: Eluru party: BSP criminal-cases: 0 assets: liabilities: result: crime-record: date: 2014-01-28 version: 0.0.5 tags: --- ##Summary ##Education {% include "education.html" %} ##Political Career {% include "political-career.html" %} ##Criminal Record {% include "criminal-record.html" %} ##Personal Wealth {% include "personal-wealth.html" %} ##Public Office Track Record {% include "track-record.html" %} ##References {% include "references.html" %}
vaibhavb/wisevoter
site/politicians/_posts/2013-12-18-pillelli-sunil.md
Markdown
gpl-3.0
1,143
Bitrix 16.5 Business Demo = 227cf5da6708ef97f99b7b2feb22d99b
gohdan/DFC
known_files/hashes/bitrix/modules/main/install/components/bitrix/menu/templates/tree/style.css
CSS
gpl-3.0
61
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> CTScale2D (POI API Documentation) </TITLE> <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="CTScale2D (POI API Documentation)"; } } </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>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CTScale2D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRelativeRect.html" title="class in org.apache.poi.sl.draw.binding"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTSchemeColor.html" title="class in org.apache.poi.sl.draw.binding"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/sl/draw/binding/CTScale2D.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CTScale2D.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.poi.sl.draw.binding</FONT> <BR> Class CTScale2D</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.sl.draw.binding.CTScale2D</B> </PRE> <HR> <DL> <DT><PRE>public class <B>CTScale2D</B><DT>extends java.lang.Object</DL> </PRE> <P> <p>Java class for CT_Scale2D complex type. <p>The following schema fragment specifies the expected content contained within this class. <pre> &lt;complexType name="CT_Scale2D"> &lt;complexContent> &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> &lt;sequence> &lt;element name="sx" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Ratio"/> &lt;element name="sy" type="{http://schemas.openxmlformats.org/drawingml/2006/main}CT_Ratio"/> &lt;/sequence> &lt;/restriction> &lt;/complexContent> &lt;/complexType> </pre> <P> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#sx">sx</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#sy">sy</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#CTScale2D()">CTScale2D</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#getSx()">getSx</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the value of the sx property.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#getSy()">getSy</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the value of the sy property.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#isSetSx()">isSetSx</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#isSetSy()">isSetSy</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#setSx(org.apache.poi.sl.draw.binding.CTRatio)">setSx</A></B>(<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the value of the sx property.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTScale2D.html#setSy(org.apache.poi.sl.draw.binding.CTRatio)">setSy</A></B>(<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the value of the sy property.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="sx"><!-- --></A><H3> sx</H3> <PRE> protected <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A> <B>sx</B></PRE> <DL> <DL> </DL> </DL> <HR> <A NAME="sy"><!-- --></A><H3> sy</H3> <PRE> protected <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A> <B>sy</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="CTScale2D()"><!-- --></A><H3> CTScale2D</H3> <PRE> public <B>CTScale2D</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getSx()"><!-- --></A><H3> getSx</H3> <PRE> public <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A> <B>getSx</B>()</PRE> <DL> <DD>Gets the value of the sx property. <P> <DD><DL> <DT><B>Returns:</B><DD>possible object is <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding"><CODE>CTRatio</CODE></A></DL> </DD> </DL> <HR> <A NAME="setSx(org.apache.poi.sl.draw.binding.CTRatio)"><!-- --></A><H3> setSx</H3> <PRE> public void <B>setSx</B>(<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A>&nbsp;value)</PRE> <DL> <DD>Sets the value of the sx property. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>value</CODE> - allowed object is <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding"><CODE>CTRatio</CODE></A></DL> </DD> </DL> <HR> <A NAME="isSetSx()"><!-- --></A><H3> isSetSx</H3> <PRE> public boolean <B>isSetSx</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getSy()"><!-- --></A><H3> getSy</H3> <PRE> public <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A> <B>getSy</B>()</PRE> <DL> <DD>Gets the value of the sy property. <P> <DD><DL> <DT><B>Returns:</B><DD>possible object is <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding"><CODE>CTRatio</CODE></A></DL> </DD> </DL> <HR> <A NAME="setSy(org.apache.poi.sl.draw.binding.CTRatio)"><!-- --></A><H3> setSy</H3> <PRE> public void <B>setSy</B>(<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding">CTRatio</A>&nbsp;value)</PRE> <DL> <DD>Sets the value of the sy property. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>value</CODE> - allowed object is <A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRatio.html" title="class in org.apache.poi.sl.draw.binding"><CODE>CTRatio</CODE></A></DL> </DD> </DL> <HR> <A NAME="isSetSy()"><!-- --></A><H3> isSetSy</H3> <PRE> public boolean <B>isSetSy</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/CTScale2D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTRelativeRect.html" title="class in org.apache.poi.sl.draw.binding"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/sl/draw/binding/CTSchemeColor.html" title="class in org.apache.poi.sl.draw.binding"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/sl/draw/binding/CTScale2D.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CTScale2D.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
jmemmons/university-assignments
CSC 445 WebCentric Programming/Final Project/poi-3.14/docs/apidocs/org/apache/poi/sl/draw/binding/CTScale2D.html
HTML
gpl-3.0
17,325
""" Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return the maximum enemies you can kill using one bomb. The bomb kills all the enemies in the same row and column from the planted point until it hits the wall since the wall is too strong to be destroyed. Note that you can only put the bomb at an empty cell. Example: For the given grid 0 E 0 0 E 0 W E 0 E 0 0 return 3. (Placing a bomb at (1,1) kills 3 enemies) """ def max_killed_enemies(grid): if not grid: return 0 m, n = len(grid), len(grid[0]) max_killed = 0 row_e, col_e = 0, [0] * n # iterates over all cells in the grid for i in range(m): for j in range(n): # makes sure we are next to a wall. if j == 0 or grid[i][j - 1] == 'W': row_e = row_kills(grid, i, j) # makes sure we are next to a wall. if i == 0 or grid[i - 1][j] == 'W': col_e[j] = col_kills(grid, i, j) # makes sure the cell contains a 0 if grid[i][j] == '0': # updates the variable max_killed = max(max_killed, row_e + col_e[j]) return max_killed # calculate killed enemies for row i from column j def row_kills(grid, i, j): num = 0 len_row = len(grid[0]) while j < len_row and grid[i][j] != 'W': if grid[i][j] == 'E': num += 1 j += 1 return num # calculate killed enemies for column j from row i def col_kills(grid, i, j): num = 0 len_col = len(grid) while i < len_col and grid[i][j] != 'W': if grid[i][j] == 'E': num += 1 i += 1 return num # ----------------- TESTS ------------------------- """ Testsuite for the project """ import unittest class TestBombEnemy(unittest.TestCase): def test_3x4(self): grid1 = [["0", "E", "0", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"]] self.assertEqual(3, max_killed_enemies(grid1)) def test_4x4(self): grid1 = [ ["0", "E", "0", "E"], ["E", "E", "E", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"]] grid2 = [ ["0", "0", "0", "E"], ["E", "0", "0", "0"], ["E", "0", "W", "E"], ["0", "E", "0", "0"]] self.assertEqual(5, max_killed_enemies(grid1)) self.assertEqual(3, max_killed_enemies(grid2)) if __name__ == "__main__": unittest.main()
marcosfede/algorithms
matrix/bomb_enemy.py
Python
gpl-3.0
2,524
package com.bendude56.bencmd.advanced; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.Player; import com.bendude56.bencmd.BenCmd; import com.bendude56.bencmd.Commands; import com.bendude56.bencmd.User; public class AdvancedCommands implements Commands { public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { User user = User.getUser(sender); if (commandLabel.equalsIgnoreCase("write")) { Write(args, user); return true; } else if (commandLabel.equalsIgnoreCase("inv") && user.hasPerm("bencmd.inv.look")) { Inv(args, user); return true; } return false; } public void Write(String[] args, User user) { if (user.isServer()) { BenCmd.getLocale().sendMessage(user, "basic.noServerUse"); return; } if (((Player) user.getHandle()).getTargetBlock(null, 4).getType() != Material.BOOKSHELF) { BenCmd.getLocale().sendMessage(user, "command.write.notAShelf"); return; } Location l = ((Player) user.getHandle()).getTargetBlock(null, 4).getLocation(); if (!BenCmd.getLots().canBuildHere(((Player) user.getHandle()), l)) { BenCmd.getLocale().sendMessage(user, "command.write.notAllowed"); return; } String message = ""; for (int i = 0; i < args.length; i++) { String word = args[i]; if (message == "") { message += word; } else { message += " " + word; } } BenCmd.getShelfFile().addShelf(new Shelf(((Player) user.getHandle()).getTargetBlock(null, 4).getLocation(), message)); BenCmd.getLocale().sendMessage(user, "command.write.success"); BenCmd.log(BenCmd.getLocale().getString("log.write.success", user.getName(), l.getX() + "", l.getY() + "", l.getZ() + "", l.getWorld().getName(), message)); } public void Inv(String[] args, User user) { if (user.isServer()) { BenCmd.getLocale().sendMessage(user, "basic.noServerUse"); return; } if (args.length != 1) { BenCmd.showUse(user, "inv"); return; } User target; if ((target = User.matchUserAllowPartial(args[0])) == null) { BenCmd.getLocale().sendMessage(user, "basic.userNotFound", args[0]); return; } if (target.hasPerm("bencmd.inv.protect") && !user.hasPerm("bencmd.inv.all")) { BenCmd.getLocale().sendMessage(user, "command.inv.protected", args[0]); return; } if (!(((CraftPlayer) target.getHandle()).getHandle().inventory instanceof ViewableInventory)) { ViewableInventory.replInv((CraftPlayer) target.getHandle()); } BenCmd.log(BenCmd.getLocale().getString("log.inv.look", user.getName(), target.getName())); ((CraftPlayer) user.getHandle()).getHandle().openContainer(((CraftPlayer) target.getHandle()).getHandle().inventory); } }
BenCmd/BenCmd
src/com/bendude56/bencmd/advanced/AdvancedCommands.java
Java
gpl-3.0
2,794
<?php //http://php.net/manual/fr/language.variables.superglobals.php //TODO must be completed namespace framework\utility; class Superglobals { const GLOBALS = 0; // all superglobals const SERVER = 1; const GET = 2; const POST = 3; const FILES = 4; const COOKIE = 5; const SESSION = 6; const REQUEST = 7; const ENV = 8; } ?>
eric-burel/twentyparts
framework/utility/Superglobals.class.php
PHP
gpl-3.0
387
/* Copyright (C) 2014 Andrew Pratt View the README */ #pragma once #include "quadcore.h" void clear_correction(struct quad_state *curr); void accel_correction(struct quad_state *curr, struct quad_state *past, struct quad_static *stat); void mag_correction(struct quad_state *curr, struct quad_state *past, struct quad_static *stat);
andrewdipper/quadrotor_v1
quadcore/correct.h
C
gpl-3.0
336
/** ****************************************************************************** * @file Examples_MIX/DMA/DMA_FLASHToRAM/Inc/stm32f0xx_it.h * @author MCD Application Team * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_IT_H #define __STM32F0xx_IT_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void SVC_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); void DMA_INSTANCE_IRQHANDLER(void); #ifdef __cplusplus } #endif #endif /* __STM32F0xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Fdepraetre/Handmouse
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Projects/STM32F072RB-Nucleo/Examples_MIX/DMA/DMA_FLASHToRAM/Inc/stm32f0xx_it.h
C
gpl-3.0
2,967
require 'package' class Libxdmcp < Package description 'The libXdmcp package contains a library implementing the X Display Manager Control Protocol.' homepage 'http://www.x.org' @_ver = '1.1.3' version "#{@_ver}-2" license 'MIT' compatibility 'all' source_url 'https://gitlab.freedesktop.org/xorg/lib/libxdmcp.git' git_hashtag "libXdmcp-#{@_ver}" binary_url({ aarch64: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/libxdmcp/1.1.3-2_armv7l/libxdmcp-1.1.3-2-chromeos-armv7l.tpxz', armv7l: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/libxdmcp/1.1.3-2_armv7l/libxdmcp-1.1.3-2-chromeos-armv7l.tpxz', i686: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/libxdmcp/1.1.3-2_i686/libxdmcp-1.1.3-2-chromeos-i686.tpxz', x86_64: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/libxdmcp/1.1.3-2_x86_64/libxdmcp-1.1.3-2-chromeos-x86_64.tpxz' }) binary_sha256({ aarch64: 'a1540e554724bfb3f0eb2525e332c6a5b47d15827596c5d163af7b6efb7c16dd', armv7l: 'a1540e554724bfb3f0eb2525e332c6a5b47d15827596c5d163af7b6efb7c16dd', i686: 'c638d631e3b94580f8e4060a561bf1867e9daaf3ea05d3015469a982bf88b1ca', x86_64: '7567bb45cc60b081c21b72c1526ffb3f9b5bb1016bb3737405bbcd5a4a85a3b7' }) depends_on 'xorg_proto' def self.build system './autogen.sh' system "./configure #{CREW_OPTIONS}" system 'make' end def self.install system 'make', "DESTDIR=#{CREW_DEST_DIR}", 'install' end end
skycocker/chromebrew
packages/libxdmcp.rb
Ruby
gpl-3.0
1,505
from distutils.core import setup # Dummy setup.py to install libtorrent for python 2.7 using pip setup( name='libtorrent', version='1.0.9', packages=['libtorrent',], data_files=[('Lib', ['libtorrent/libtorrent.pyd']),], ) # Install in "editable mode" for development: # pip install -e .
overfl0/Bulletproof-Arma-Launcher
dependencies/libtorrent/setup.py
Python
gpl-3.0
303
{"address":["NLix (Hilversum, Netherlands)","Sumatralaan 45","Hilversum, Netherlands"],"buildings":[{"latitude":"52.2351344","longitude":"5.1726535","address":["Sumatralaan 45","Hilversum, Netherlands"],"offset":"background:url('images/markers.png') no-repeat -22px 0;","id":15145}],"name":"NLix (Hilversum, Netherlands)","exchange_info":[{"onclick":null,"link":null,"value":"31 70 365 36 88"},{"onclick":null,"link":"mailto:info@nl-ix.net","value":"info@nl-ix.net"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.nl-ix.net","value":"Website"},{"onclick":null,"link":null,"value":"Online since: April 2002"}],"id":"nlix-hilversum-netherlands"}
brangerbriz/webroutes
nw-app/telegeography-data/internetexchanges/internet-exchanges/nlix-hilversum-netherlands.js
JavaScript
gpl-3.0
681
/******************************************************************************* * This file is part of RedReader. * * RedReader 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. * * RedReader 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 RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.lol.reddit.common; import java.util.HashSet; import java.util.LinkedList; public class UniqueSynchronizedQueue<E> { private final HashSet<E> set = new HashSet<E>(); private final LinkedList<E> queue = new LinkedList<E>(); public synchronized void enqueue(E object) { if (set.add(object)) { queue.addLast(object); } } public synchronized E dequeue() { if (queue.isEmpty()) return null; final E result = queue.removeFirst(); set.remove(result); return result; } }
derekwang2012/rrr
src/main/java/org/lol/reddit/common/UniqueSynchronizedQueue.java
Java
gpl-3.0
1,403
<!DOCTYPE html> <html> <head> <title>Bootstrap Tree View</title> <link rel="stylesheet" href=" ../../../Styles/commonLibs/bootstrap/v3.3.7/bootstrap.min.css"> <!-- <link href="./css/bootstrap-treeview.css" rel="stylesheet"> --> </head> <body> <div class="container"> <h1>Bootstrap Tree View</h1> <br> <div class="row"> <div class="col-sm-4"> <h2>Default</h2> <div id="treeview1" class=""></div> </div> <div class="col-sm-4"> <h2>Collapsed</h2> <div id="treeview2" class=""></div> </div> <div class="col-sm-4"> <h2>Expanded</h2> <div id="treeview3" class=""></div> </div> </div> <div class="row"> <div class="col-sm-4"> <h2>Blue Theme</h2> <div id="treeview4" class=""></div> </div> <div class="col-sm-4"> <h2>Custom Icons</h2> <div id="treeview5" class=""></div> </div> <div class="col-sm-4"> <h2>Tags as Badges</h2> <div id="treeview6" class=""></div> </div> </div> <div class="row"> <div class="col-sm-4"> <h2>No Border</h2> <div id="treeview7" class=""></div> </div> <div class="col-sm-4"> <h2>Colourful</h2> <div id="treeview8" class=""></div> </div> <div class="col-sm-4"> <h2>Node Overrides</h2> <div id="treeview9" class=""></div> </div> </div> <div class="row"> <div class="col-sm-4"> <h2>Link enabled, or</h2> <div id="treeview10" class=""></div> </div> <div class="col-sm-4"> </div> <div class="col-sm-4"> </div> </div> <div class="row"> <hr> <h2>Searchable Tree</h2> <div class="col-sm-4"> <h2>Input</h2> <!-- <form> --> <div class="form-group"> <label for="input-search" class="sr-only">Search Tree:</label> <input type="input" class="form-control" id="input-search" placeholder="Type to search..." value=""> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-ignore-case" value="false"> Ignore Case </label> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-exact-match" value="false"> Exact Match </label> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-reveal-results" value="false"> Reveal Results </label> </div> <button type="button" class="btn btn-success" id="btn-search">Search</button> <button type="button" class="btn btn-default" id="btn-clear-search">Clear</button> <!-- </form> --> </div> <div class="col-sm-4"> <h2>Tree</h2> <div id="treeview-searchable" class=""></div> </div> <div class="col-sm-4"> <h2>Results</h2> <div id="search-output"></div> </div> </div> <div class="row"> <hr> <h2>Selectable Tree</h2> <div class="col-sm-4"> <h2>Input</h2> <div class="form-group"> <label for="input-select-node" class="sr-only">Search Tree:</label> <input type="input" class="form-control" id="input-select-node" placeholder="Identify node..." value="Parent 1"> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-select-multi" value="false"> Multi Select </label> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-select-silent" value="false"> Silent (No events) </label> </div> <div class="form-group"> <button type="button" class="btn btn-success select-node" id="btn-select-node">Select Node</button> </div> <div class="form-group"> <button type="button" class="btn btn-danger select-node" id="btn-unselect-node">Unselect Node</button> </div> <div class="form-group"> <button type="button" class="btn btn-primary select-node" id="btn-toggle-selected">Toggle Node</button> </div> </div> <div class="col-sm-4"> <h2>Tree</h2> <div id="treeview-selectable" class=""></div> </div> <div class="col-sm-4"> <h2>Events</h2> <div id="selectable-output"></div> </div> </div> <div class="row"> <hr> <h2>Expandible Tree</h2> <div class="col-sm-4"> <h2>Input</h2> <div class="form-group"> <label for="input-expand-node" class="sr-only">Search Tree:</label> <input type="input" class="form-control" id="input-expand-node" placeholder="Identify node..." value="Parent 1"> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-expand-silent" value="false"> Silent (No events) </label> </div> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success expand-node" id="btn-expand-node">Expand Node</button> </div> <div class="col-sm-6"> <select class="form-control" id="select-expand-node-levels"> <option>1</option> <option>2</option> </select> </div> </div> <div class="form-group"> <button type="button" class="btn btn-danger expand-node" id="btn-collapse-node">Collapse Node</button> </div> <div class="form-group"> <button type="button" class="btn btn-primary expand-node" id="btn-toggle-expanded">Toggle Node</button> </div> <hr> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success" id="btn-expand-all">Expand All</button> </div> <div class="col-sm-6"> <select class="form-control" id="select-expand-all-levels"> <option>1</option> <option>2</option> </select> </div> </div> <button type="button" class="btn btn-danger" id="btn-collapse-all">Collapse All</button> </div> <div class="col-sm-4"> <h2>Tree</h2> <div id="treeview-expandible" class=""></div> </div> <div class="col-sm-4"> <h2>Events</h2> <div id="expandible-output"></div> </div> </div> <div class="row"> <hr> <h2>Checkable Tree</h2> <div class="col-sm-4"> <h2>Input</h2> <div class="form-group"> <label for="input-check-node" class="sr-only">Search Tree:</label> <input type="input" class="form-control" id="input-check-node" placeholder="Identify node..." value="Parent 1"> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-check-silent" value="false"> Silent (No events) </label> </div> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success check-node" id="btn-check-node">Check Node</button> </div> </div> <div class="form-group"> <button type="button" class="btn btn-danger check-node" id="btn-uncheck-node">Uncheck Node</button> </div> <div class="form-group"> <button type="button" class="btn btn-primary check-node" id="btn-toggle-checked">Toggle Node</button> </div> <hr> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success" id="btn-check-all">Check All</button> </div> </div> <button type="button" class="btn btn-danger" id="btn-uncheck-all">Uncheck All</button> </div> <div class="col-sm-4"> <h2>Tree</h2> <div id="treeview-checkable" class=""></div> </div> <div class="col-sm-4"> <h2>Events</h2> <div id="checkable-output"></div> </div> </div> <div class="row"> <hr> <h2>Disabled Tree</h2> <div class="col-sm-4"> <h2>Input</h2> <div class="form-group"> <label for="input-disable-node" class="sr-only">Search Tree:</label> <input type="input" class="form-control" id="input-disable-node" placeholder="Identify node..." value="Parent 1"> </div> <div class="checkbox"> <label> <input type="checkbox" class="checkbox" id="chk-disable-silent" value="false"> Silent (No events) </label> </div> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success disable-node" id="btn-disable-node">Disable Node</button> </div> </div> <div class="form-group"> <button type="button" class="btn btn-danger disable-node" id="btn-enable-node">Enable Node</button> </div> <div class="form-group"> <button type="button" class="btn btn-primary disable-node" id="btn-toggle-disabled">Toggle Node</button> </div> <hr> <div class="form-group row"> <div class="col-sm-6"> <button type="button" class="btn btn-success" id="btn-disable-all">Disable All</button> </div> </div> <button type="button" class="btn btn-danger" id="btn-enable-all">Enable All</button> </div> <div class="col-sm-4"> <h2>Tree</h2> <div id="treeview-disabled" class=""></div> </div> <div class="col-sm-4"> <h2>Events</h2> <div id="disabled-output"></div> </div> </div> <div class="row"> <hr> <h2>Data</h2> <div class="col-sm-4"> <h2>JSON Data</h2> <div id="treeview12" class=""></div> </div> <div class="col-sm-4"> <h2></h2> <div id="treeview13" class=""></div> </div> <div class="col-sm-4"> <h2></h2> <div id="treeview14"></div> </div> </div> <br/> <br/> <br/> <br/> </div> <script src="../../common/jquery/v3.2.1/jquery-3.2.1.min.js"></script> <script src="./bootstrap-treeview.js"></script> <script type="text/javascript"> $(function() { var defaultData = [{ text: 'Parent 1', href: '#parent1', tags: ['4'], nodes: [{ text: 'Child 1', href: '#child1', tags: ['2'], nodes: [{ text: 'Grandchild 1', href: '#grandchild1', tags: ['0'] }, { text: 'Grandchild 2', href: '#grandchild2', tags: ['0'] }] }, { text: 'Child 2', href: '#child2', tags: ['0'] }] }, { text: 'Parent 2', href: '#parent2', tags: ['0'] }, { text: 'Parent 3', href: '#parent3', tags: ['0'] }, { text: 'Parent 4', href: '#parent4', tags: ['0'] }, { text: 'Parent 5', href: '#parent5', tags: ['0'] }]; var alternateData = [{ text: 'Parent 1', tags: ['2'], nodes: [{ text: 'Child 1', tags: ['3'], nodes: [{ text: 'Grandchild 1', tags: ['6'] }, { text: 'Grandchild 2', tags: ['3'] }] }, { text: 'Child 2', tags: ['3'] }] }, { text: 'Parent 2', tags: ['7'] }, { text: 'Parent 3', icon: 'glyphicon glyphicon-earphone', href: '#demo', tags: ['11'] }, { text: 'Parent 4', icon: 'glyphicon glyphicon-cloud-download', href: '/demo.html', tags: ['19'], selected: true }, { text: 'Parent 5', icon: 'glyphicon glyphicon-certificate', color: 'pink', backColor: 'red', href: 'http://www.tesco.com', tags: ['available', '0'] }]; var json = '[' + '{' + '"text": "Parent 1",' + '"nodes": [' + '{' + '"text": "Child 1",' + '"nodes": [' + '{' + '"text": "Grandchild 1"' + '},' + '{' + '"text": "Grandchild 2"' + '}' + ']' + '},' + '{' + '"text": "Child 2"' + '}' + ']' + '},' + '{' + '"text": "Parent 2"' + '},' + '{' + '"text": "Parent 3"' + '},' + '{' + '"text": "Parent 4"' + '},' + '{' + '"text": "Parent 5"' + '}' + ']'; $('#treeview1').treeview({ data: defaultData }); $('#treeview2').treeview({ levels: 1, data: defaultData }); $('#treeview3').treeview({ levels: 99, data: defaultData }); $('#treeview4').treeview({ color: "#428bca", data: defaultData }); $('#treeview5').treeview({ color: "#428bca", expandIcon: 'glyphicon glyphicon-chevron-right', collapseIcon: 'glyphicon glyphicon-chevron-down', nodeIcon: 'glyphicon glyphicon-bookmark', data: defaultData }); $('#treeview6').treeview({ color: "#428bca", expandIcon: "glyphicon glyphicon-stop", collapseIcon: "glyphicon glyphicon-unchecked", nodeIcon: "glyphicon glyphicon-user", showTags: true, data: defaultData }); $('#treeview7').treeview({ color: "#428bca", showBorder: false, data: defaultData }); $('#treeview8').treeview({ expandIcon: "glyphicon glyphicon-stop", collapseIcon: "glyphicon glyphicon-unchecked", nodeIcon: "glyphicon glyphicon-user", color: "yellow", backColor: "purple", onhoverColor: "orange", borderColor: "red", showBorder: false, showTags: true, highlightSelected: true, selectedColor: "yellow", selectedBackColor: "darkorange", data: defaultData }); $('#treeview9').treeview({ expandIcon: "glyphicon glyphicon-stop", collapseIcon: "glyphicon glyphicon-unchecked", nodeIcon: "glyphicon glyphicon-user", color: "yellow", backColor: "purple", onhoverColor: "orange", borderColor: "red", showBorder: false, showTags: true, highlightSelected: true, selectedColor: "yellow", selectedBackColor: "darkorange", data: alternateData }); $('#treeview10').treeview({ color: "#428bca", enableLinks: true, data: defaultData }); var $searchableTree = $('#treeview-searchable').treeview({ data: defaultData, }); var search = function(e) { var pattern = $('#input-search').val(); var options = { ignoreCase: $('#chk-ignore-case').is(':checked'), exactMatch: $('#chk-exact-match').is(':checked'), revealResults: $('#chk-reveal-results').is(':checked') }; var results = $searchableTree.treeview('search', [pattern, options]); var output = '<p>' + results.length + ' matches found</p>'; $.each(results, function(index, result) { output += '<p>- ' + result.text + '</p>'; }); $('#search-output').html(output); } $('#btn-search').on('click', search); $('#input-search').on('keyup', search); $('#btn-clear-search').on('click', function(e) { $searchableTree.treeview('clearSearch'); $('#input-search').val(''); $('#search-output').html(''); }); var initSelectableTree = function() { return $('#treeview-selectable').treeview({ data: defaultData, multiSelect: $('#chk-select-multi').is(':checked'), onNodeSelected: function(event, node) { $('#selectable-output').prepend('<p>' + node.text + ' was selected</p>'); }, onNodeUnselected: function(event, node) { $('#selectable-output').prepend('<p>' + node.text + ' was unselected</p>'); } }); }; var $selectableTree = initSelectableTree(); var findSelectableNodes = function() { return $selectableTree.treeview('search', [$('#input-select-node').val(), { ignoreCase: false, exactMatch: false }]); }; var selectableNodes = findSelectableNodes(); $('#chk-select-multi:checkbox').on('change', function() { console.log('multi-select change'); $selectableTree = initSelectableTree(); selectableNodes = findSelectableNodes(); }); // Select/unselect/toggle nodes $('#input-select-node').on('keyup', function(e) { selectableNodes = findSelectableNodes(); $('.select-node').prop('disabled', !(selectableNodes.length >= 1)); }); $('#btn-select-node.select-node').on('click', function(e) { $selectableTree.treeview('selectNode', [selectableNodes, { silent: $('#chk-select-silent').is(':checked') }]); }); $('#btn-unselect-node.select-node').on('click', function(e) { $selectableTree.treeview('unselectNode', [selectableNodes, { silent: $('#chk-select-silent').is(':checked') }]); }); $('#btn-toggle-selected.select-node').on('click', function(e) { $selectableTree.treeview('toggleNodeSelected', [selectableNodes, { silent: $('#chk-select-silent').is(':checked') }]); }); var $expandibleTree = $('#treeview-expandible').treeview({ data: defaultData, onNodeCollapsed: function(event, node) { $('#expandible-output').prepend('<p>' + node.text + ' was collapsed</p>'); }, onNodeExpanded: function(event, node) { $('#expandible-output').prepend('<p>' + node.text + ' was expanded</p>'); } }); var findExpandibleNodess = function() { return $expandibleTree.treeview('search', [$('#input-expand-node').val(), { ignoreCase: false, exactMatch: false }]); }; var expandibleNodes = findExpandibleNodess(); // Expand/collapse/toggle nodes $('#input-expand-node').on('keyup', function(e) { expandibleNodes = findExpandibleNodess(); $('.expand-node').prop('disabled', !(expandibleNodes.length >= 1)); }); $('#btn-expand-node.expand-node').on('click', function(e) { var levels = $('#select-expand-node-levels').val(); $expandibleTree.treeview('expandNode', [expandibleNodes, { levels: levels, silent: $('#chk-expand-silent').is(':checked') }]); }); $('#btn-collapse-node.expand-node').on('click', function(e) { $expandibleTree.treeview('collapseNode', [expandibleNodes, { silent: $('#chk-expand-silent').is(':checked') }]); }); $('#btn-toggle-expanded.expand-node').on('click', function(e) { $expandibleTree.treeview('toggleNodeExpanded', [expandibleNodes, { silent: $('#chk-expand-silent').is(':checked') }]); }); // Expand/collapse all $('#btn-expand-all').on('click', function(e) { var levels = $('#select-expand-all-levels').val(); $expandibleTree.treeview('expandAll', { levels: levels, silent: $('#chk-expand-silent').is(':checked') }); }); $('#btn-collapse-all').on('click', function(e) { $expandibleTree.treeview('collapseAll', { silent: $('#chk-expand-silent').is(':checked') }); }); var $checkableTree = $('#treeview-checkable').treeview({ data: defaultData, showIcon: false, showCheckbox: true, onNodeChecked: function(event, node) { $('#checkable-output').prepend('<p>' + node.text + ' was checked</p>'); }, onNodeUnchecked: function(event, node) { $('#checkable-output').prepend('<p>' + node.text + ' was unchecked</p>'); } }); var findCheckableNodess = function() { return $checkableTree.treeview('search', [$('#input-check-node').val(), { ignoreCase: false, exactMatch: false }]); }; var checkableNodes = findCheckableNodess(); // Check/uncheck/toggle nodes $('#input-check-node').on('keyup', function(e) { checkableNodes = findCheckableNodess(); $('.check-node').prop('disabled', !(checkableNodes.length >= 1)); }); $('#btn-check-node.check-node').on('click', function(e) { $checkableTree.treeview('checkNode', [checkableNodes, { silent: $('#chk-check-silent').is(':checked') }]); }); $('#btn-uncheck-node.check-node').on('click', function(e) { $checkableTree.treeview('uncheckNode', [checkableNodes, { silent: $('#chk-check-silent').is(':checked') }]); }); $('#btn-toggle-checked.check-node').on('click', function(e) { $checkableTree.treeview('toggleNodeChecked', [checkableNodes, { silent: $('#chk-check-silent').is(':checked') }]); }); // Check/uncheck all $('#btn-check-all').on('click', function(e) { $checkableTree.treeview('checkAll', { silent: $('#chk-check-silent').is(':checked') }); }); $('#btn-uncheck-all').on('click', function(e) { $checkableTree.treeview('uncheckAll', { silent: $('#chk-check-silent').is(':checked') }); }); var $disabledTree = $('#treeview-disabled').treeview({ data: defaultData, onNodeDisabled: function(event, node) { $('#disabled-output').prepend('<p>' + node.text + ' was disabled</p>'); }, onNodeEnabled: function(event, node) { $('#disabled-output').prepend('<p>' + node.text + ' was enabled</p>'); }, onNodeCollapsed: function(event, node) { $('#disabled-output').prepend('<p>' + node.text + ' was collapsed</p>'); }, onNodeUnchecked: function(event, node) { $('#disabled-output').prepend('<p>' + node.text + ' was unchecked</p>'); }, onNodeUnselected: function(event, node) { $('#disabled-output').prepend('<p>' + node.text + ' was unselected</p>'); } }); var findDisabledNodes = function() { return $disabledTree.treeview('search', [$('#input-disable-node').val(), { ignoreCase: false, exactMatch: false }]); }; var disabledNodes = findDisabledNodes(); // Expand/collapse/toggle nodes $('#input-disable-node').on('keyup', function(e) { disabledNodes = findDisabledNodes(); $('.disable-node').prop('disabled', !(disabledNodes.length >= 1)); }); $('#btn-disable-node.disable-node').on('click', function(e) { $disabledTree.treeview('disableNode', [disabledNodes, { silent: $('#chk-disable-silent').is(':checked') }]); }); $('#btn-enable-node.disable-node').on('click', function(e) { $disabledTree.treeview('enableNode', [disabledNodes, { silent: $('#chk-disable-silent').is(':checked') }]); }); $('#btn-toggle-disabled.disable-node').on('click', function(e) { $disabledTree.treeview('toggleNodeDisabled', [disabledNodes, { silent: $('#chk-disable-silent').is(':checked') }]); }); // Expand/collapse all $('#btn-disable-all').on('click', function(e) { $disabledTree.treeview('disableAll', { silent: $('#chk-disable-silent').is(':checked') }); }); $('#btn-enable-all').on('click', function(e) { $disabledTree.treeview('enableAll', { silent: $('#chk-disable-silent').is(':checked') }); }); var $tree = $('#treeview12').treeview({ data: json }); }); </script> </body> </html>
alexperusso/Screen
WebContent/Scripts/common/bootstrap-treeview/Bootstrap Tree View.html
HTML
gpl-3.0
29,915
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIgnoreListTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ignore_list', function (Blueprint $table) { $table->bigIncrements('ignore_list_id'); $table->integer("user_id"); $table->integer("anti_friend_id"); $table->unique(["user_id", "anti_friend_id"]); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ignore_list'); } }
jcsston/CosmoMongerPHP
database/migrations/2019_08_31_035424_create_ignore_list_table.php
PHP
gpl-3.0
764
from pyFTS.common import FuzzySet, Membership import numpy as np from scipy.spatial import KDTree import matplotlib.pylab as plt import logging class Partitioner(object): """ Universe of Discourse partitioner. Split data on several fuzzy sets """ def __init__(self, **kwargs): """ Universe of Discourse partitioner scheme. Split data on several fuzzy sets """ self.name = kwargs.get('name',"") """partitioner name""" self.partitions = kwargs.get('npart', 10) """The number of universe of discourse partitions, i.e., the number of fuzzy sets that will be created""" self.sets = {} self.membership_function = kwargs.get('func', Membership.trimf) """Fuzzy membership function (pyFTS.common.Membership)""" self.setnames = kwargs.get('names', None) """list of partitions names. If None is given the partitions will be auto named with prefix""" self.prefix = kwargs.get('prefix', 'A') """prefix of auto generated partition names""" self.transformation = kwargs.get('transformation', None) """data transformation to be applied on data""" self.indexer = kwargs.get('indexer', None) self.variable = kwargs.get('variable', None) """In a multivariate context, the variable that contains this partitioner""" self.type = kwargs.get('type', 'common') """The type of fuzzy sets that are generated by this partitioner""" self.ordered_sets = None """A ordered list of the fuzzy sets names, sorted by their middle point""" self.kdtree = None """A spatial index to help in fuzzyfication""" self.margin = kwargs.get("margin", 0.1) """The upper and lower exceeding margins for the known UoD. The default value is .1""" self.lower_margin = kwargs.get("lower_margin", self.margin) """Specific lower exceeding margins for the known UoD. The default value is the self.margin parameter""" self.upper_margin = kwargs.get("lower_margin", self.margin) """Specific upper exceeding margins for the known UoD. The default value is the self.margin parameter""" if kwargs.get('preprocess',True): data = kwargs.get('data',[None]) if self.indexer is not None: ndata = self.indexer.get_data(data) else: ndata = data if self.transformation is not None: ndata = self.transformation.apply(ndata) else: ndata = data if self.indexer is not None: ndata = self.indexer.get_data(ndata) _min = np.nanmin(ndata) if _min == -np.inf: ndata[ndata == -np.inf] = 0 _min = np.nanmin(ndata) self.min = float(_min * (1 + self.lower_margin) if _min < 0 else _min * (1 - self.lower_margin)) _max = np.nanmax(ndata) self.max = float(_max * (1 + self.upper_margin) if _max > 0 else _max * (1 - self.upper_margin)) self.sets = self.build(ndata) self.partitions = len(self.sets) if self.ordered_sets is None and self.setnames is not None: self.ordered_sets = self.setnames[:len(self.sets)] else: self.ordered_sets = FuzzySet.set_ordered(self.sets) del(ndata) def extractor(self,x): """Extract a single primitive type from an structured instance""" return x def build(self, data): """ Perform the partitioning of the Universe of Discourse :param data: training data :return: """ pass def get_name(self, counter): """ Find the name of the fuzzy set given its counter id. :param counter: The number of the fuzzy set :return: String """ return self.prefix + str(counter) if self.setnames is None else self.setnames[counter] def lower_set(self): """ Return the fuzzy set on lower bound of the universe of discourse. :return: Fuzzy Set """ return self.sets[self.ordered_sets[0]] def upper_set(self): """ Return the fuzzy set on upper bound of the universe of discourse. :return: Fuzzy Set """ return self.sets[self.ordered_sets[-1]] def build_index(self): points = [] #self.index = {} for ct, key in enumerate(self.ordered_sets): fset = self.sets[key] points.append([fset.lower, fset.centroid, fset.upper]) #self.index[ct] = fset.name import sys sys.setrecursionlimit(100000) self.kdtree = KDTree(points) sys.setrecursionlimit(1000) def fuzzyfy(self, data, **kwargs): """ Fuzzyfy the input data according to this partitioner fuzzy sets. :param data: input value to be fuzzyfied :keyword alpha_cut: the minimal membership value to be considered on fuzzyfication (only for mode='sets') :keyword method: the fuzzyfication method (fuzzy: all fuzzy memberships, maximum: only the maximum membership) :keyword mode: the fuzzyfication mode (sets: return the fuzzy sets names, vector: return a vector with the membership values for all fuzzy sets, both: return a list with tuples (fuzzy set, membership value) ) :returns a list with the fuzzyfied values, depending on the mode """ if isinstance(data, (tuple, list, np.ndarray)): ret = [] for inst in data: mv = self.fuzzyfy(inst, **kwargs) ret.append(mv) return ret alpha_cut = kwargs.get('alpha_cut', 0.) mode = kwargs.get('mode', 'sets') method = kwargs.get('method', 'fuzzy') nearest = self.search(data, type='index') mv = np.zeros(self.partitions) for ix in nearest: tmp = self[ix].membership(data) mv[ix] = tmp if tmp >= alpha_cut else 0. ix = np.ravel(np.argwhere(mv > 0.)) if ix.size == 0: mv[self.check_bounds(data)] = 1. if method == 'fuzzy' and mode == 'vector': return mv elif method == 'fuzzy' and mode == 'sets': try: ix = np.ravel(np.argwhere(mv > 0.)) sets = [self.ordered_sets[i] for i in ix if i < self.partitions] return sets except Exception as ex: return None elif method == 'maximum' and mode == 'sets': mx = max(mv) ix = np.ravel(np.argwhere(mv == mx)) return self.ordered_sets[ix[0]] elif mode == 'both': ix = np.ravel(np.argwhere(mv > 0.)) sets = [(self.ordered_sets[i], mv[i]) for i in ix] return sets def defuzzyfy(self, values, mode='both'): if not isinstance(values, list): values = [values] num = [] den = [] for val in values: fset = val[0] mv = val[1] if mode == 'both': num.append( self.sets[fset].centroid * mv ) den.append(mv) elif mode == 'sets': num.append(self.sets[fset].centroid) elif mode == 'vector': num.append(self.sets[self.ordered_sets[fset]].centroid * mv) den.append(mv) else: raise Exception('Unknown deffuzyfication mode') if mode in ('both','vector'): return np.nansum(num) / np.nansum(den) else: return np.nanmean(num) def check_bounds(self, data): """ Check if the input data is outside the known Universe of Discourse and, if it is, round it to the closest fuzzy set. :param data: input data to be verified :return: the index of the closest fuzzy set when data is outside de universe of discourse or None if the data is inside the UoD. """ if data < self.min: return 0 elif data > self.max: return self.partitions-1 def search(self, data, **kwargs): """ Perform a search for the nearest fuzzy sets of the point 'data'. This function were designed to work with several overlapped fuzzy sets. :param data: the value to search for the nearest fuzzy sets :param type: the return type: 'index' for the fuzzy set indexes or 'name' for fuzzy set names. :param results: the number of nearest fuzzy sets to return :return: a list with the nearest fuzzy sets """ if self.kdtree is None: self.build_index() type = kwargs.get('type','index') results = kwargs.get('results', 3) _, ix = self.kdtree.query([data, data, data], results) if type == 'name': return [self.ordered_sets[k] for k in sorted(ix)] else: return sorted(ix) def plot(self, ax, rounding=0): """ Plot the partitioning using the Matplotlib axis ax :param ax: Matplotlib axis """ ax.set_title(self.name) ax.set_ylim([0, 1.1]) ax.set_xlim([self.min, self.max]) ticks = [] x = [] for key in self.sets.keys(): s = self.sets[key] if s.type == 'common': self.plot_set(ax, s) elif s.type == 'composite': for ss in s.sets: self.plot_set(ax, ss) ticks.append(str(round(s.centroid,rounding))+'\n'+s.name) x.append(s.centroid) ax.xaxis.set_ticklabels(ticks) ax.xaxis.set_ticks(x) def plot_set(self, ax, s): """ Plot an isolate fuzzy set on Matplotlib axis :param ax: Matplotlib axis :param s: Fuzzy Set """ if s.mf == Membership.trimf: ax.plot([s.parameters[0], s.parameters[1], s.parameters[2]], [0, s.alpha, 0]) elif s.mf in (Membership.gaussmf, Membership.bellmf, Membership.sigmf): tmpx = np.linspace(s.lower, s.upper, 100) tmpy = [s.membership(kk) for kk in tmpx] ax.plot(tmpx, tmpy) elif s.mf == Membership.trapmf: ax.plot(s.parameters, [0, s.alpha, s.alpha, 0]) elif s.mf == Membership.singleton: ax.plot([s.parameters[0],s.parameters[0]], [0, s.alpha]) def __str__(self): """ Return a string representation of the partitioner, the list of fuzzy sets and their parameters :return: """ tmp = self.name + ":\n" for key in self.sets.keys(): tmp += str(self.sets[key])+ "\n" return tmp def __len__(self): """ Return the number of partitions :return: number of partitions """ return self.partitions def __getitem__(self, item): """ Return a fuzzy set by its order or its name. :param item: If item is an integer then it represents the fuzzy set index (order), if it was a string then it represents the fuzzy set name. :return: the fuzzy set """ if isinstance(item, (int, np.int, np.int8, np.int16, np.int32, np.int64)): if item < 0 or item >= self.partitions: raise ValueError("The fuzzy set index must be between 0 and {}.".format(self.partitions)) return self.sets[self.ordered_sets[item]] elif isinstance(item, str): if item not in self.sets: raise ValueError("The fuzzy set with name {} does not exist.".format(item)) return self.sets[item] else: raise ValueError("The parameter 'item' must be an integer or a string and the value informed was {} of type {}!".format(item, type(item))) def __iter__(self): """ Iterate over the fuzzy sets, ordered by its midpoints. :return: An iterator over the fuzzy sets. """ for key in self.ordered_sets: yield self.sets[key]
petroniocandido/pyFTS
pyFTS/partitioners/partitioner.py
Python
gpl-3.0
12,188
( function( window ) { "use strict"; window.innerWidth = 600; window.innerHeight = 400; window.gadget = window.gadget || {}; window.gadget.settings = { "params": {}, "additionalParams": { "interactivity": { "interactive": false, "scrollbars": false }, "refresh": 0, "region": { "showRegion": "page", "horizontal": 0, "vertical": 0 }, "unload": false, "url": "http://www.risevision.com", "zoom": "1" } }; } )( window );
Rise-Vision/widget-web-page
test/data/webpage-unload.js
JavaScript
gpl-3.0
532
package wire import ( "bytes" "fmt" "reflect" "testing" "time" . "github.com/eris-ltd/mint-client/Godeps/_workspace/src/github.com/tendermint/tendermint/common" ) type SimpleStruct struct { String string Bytes []byte Time time.Time } type Animal interface{} const ( AnimalTypeCat = byte(0x01) AnimalTypeDog = byte(0x02) AnimalTypeSnake = byte(0x03) AnimalTypeViper = byte(0x04) ) // Implements Animal type Cat struct { SimpleStruct } // Implements Animal type Dog struct { SimpleStruct } // Implements Animal type Snake []byte // Implements Animal type Viper struct { Bytes []byte } var _ = RegisterInterface( struct{ Animal }{}, ConcreteType{Cat{}, AnimalTypeCat}, ConcreteType{Dog{}, AnimalTypeDog}, ConcreteType{Snake{}, AnimalTypeSnake}, ConcreteType{&Viper{}, AnimalTypeViper}, ) func TestAnimalInterface(t *testing.T) { var foo Animal // Type of pointer to Animal rt := reflect.TypeOf(&foo) fmt.Printf("rt: %v\n", rt) // Type of Animal itself. // NOTE: normally this is acquired through other means // like introspecting on method signatures, or struct fields. rte := rt.Elem() fmt.Printf("rte: %v\n", rte) // Get a new pointer to the interface // NOTE: calling .Interface() is to get the actual value, // instead of reflection values. ptr := reflect.New(rte).Interface() fmt.Printf("ptr: %v", ptr) // Make a binary byteslice that represents a *snake. foo = Snake([]byte("snake")) snakeBytes := BinaryBytes(foo) snakeReader := bytes.NewReader(snakeBytes) // Now you can read it. n, err := new(int64), new(error) it := ReadBinary(foo, snakeReader, n, err).(Animal) fmt.Println(it, reflect.TypeOf(it)) } //------------------------------------- type Constructor func() interface{} type Instantiator func() (o interface{}, ptr interface{}) type Validator func(o interface{}, t *testing.T) type TestCase struct { Constructor Instantiator Validator } //------------------------------------- func constructBasic() interface{} { cat := Cat{ SimpleStruct{ String: "String", Bytes: []byte("Bytes"), Time: time.Unix(123, 0), }, } return cat } func instantiateBasic() (interface{}, interface{}) { return Cat{}, &Cat{} } func validateBasic(o interface{}, t *testing.T) { cat := o.(Cat) if cat.String != "String" { t.Errorf("Expected cat.String == 'String', got %v", cat.String) } if string(cat.Bytes) != "Bytes" { t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) } if cat.Time.Unix() != 123 { t.Errorf("Expected cat.Time == 'Unix(123)', got %v", cat.Time) } } //------------------------------------- type NilTestStruct struct { IntPtr *int CatPtr *Cat Animal Animal } func constructNilTestStruct() interface{} { return NilTestStruct{} } func instantiateNilTestStruct() (interface{}, interface{}) { return NilTestStruct{}, &NilTestStruct{} } func validateNilTestStruct(o interface{}, t *testing.T) { nts := o.(NilTestStruct) if nts.IntPtr != nil { t.Errorf("Expected nts.IntPtr to be nil, got %v", nts.IntPtr) } if nts.CatPtr != nil { t.Errorf("Expected nts.CatPtr to be nil, got %v", nts.CatPtr) } if nts.Animal != nil { t.Errorf("Expected nts.Animal to be nil, got %v", nts.Animal) } } //------------------------------------- type ComplexStruct struct { Name string Animal Animal } func constructComplex() interface{} { c := ComplexStruct{ Name: "Complex", Animal: constructBasic(), } return c } func instantiateComplex() (interface{}, interface{}) { return ComplexStruct{}, &ComplexStruct{} } func validateComplex(o interface{}, t *testing.T) { c2 := o.(ComplexStruct) if cat, ok := c2.Animal.(Cat); ok { validateBasic(cat, t) } else { t.Errorf("Expected c2.Animal to be of type cat, got %v", reflect.ValueOf(c2.Animal).Elem().Type()) } } //------------------------------------- type ComplexStruct2 struct { Cat Cat Dog *Dog Snake Snake Snake2 *Snake Viper Viper Viper2 *Viper } func constructComplex2() interface{} { snake_ := Snake([]byte("hiss")) snakePtr_ := &snake_ c := ComplexStruct2{ Cat: Cat{ SimpleStruct{ String: "String", Bytes: []byte("Bytes"), }, }, Dog: &Dog{ SimpleStruct{ String: "Woof", Bytes: []byte("Bark"), }, }, Snake: Snake([]byte("hiss")), Snake2: snakePtr_, Viper: Viper{Bytes: []byte("hizz")}, Viper2: &Viper{Bytes: []byte("hizz")}, } return c } func instantiateComplex2() (interface{}, interface{}) { return ComplexStruct2{}, &ComplexStruct2{} } func validateComplex2(o interface{}, t *testing.T) { c2 := o.(ComplexStruct2) cat := c2.Cat if cat.String != "String" { t.Errorf("Expected cat.String == 'String', got %v", cat.String) } if string(cat.Bytes) != "Bytes" { t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) } dog := c2.Dog if dog.String != "Woof" { t.Errorf("Expected dog.String == 'Woof', got %v", dog.String) } if string(dog.Bytes) != "Bark" { t.Errorf("Expected dog.Bytes == 'Bark', got %X", dog.Bytes) } snake := c2.Snake if string(snake) != "hiss" { t.Errorf("Expected string(snake) == 'hiss', got %v", string(snake)) } snake2 := c2.Snake2 if string(*snake2) != "hiss" { t.Errorf("Expected string(snake2) == 'hiss', got %v", string(*snake2)) } viper := c2.Viper if string(viper.Bytes) != "hizz" { t.Errorf("Expected string(viper.Bytes) == 'hizz', got %v", string(viper.Bytes)) } viper2 := c2.Viper2 if string(viper2.Bytes) != "hizz" { t.Errorf("Expected string(viper2.Bytes) == 'hizz', got %v", string(viper2.Bytes)) } } //------------------------------------- type ComplexStructArray struct { Animals []Animal Bytes [5]byte Ints [5]int Array SimpleArray } func constructComplexArray() interface{} { c := ComplexStructArray{ Animals: []Animal{ Cat{ SimpleStruct{ String: "String", Bytes: []byte("Bytes"), }, }, Dog{ SimpleStruct{ String: "Woof", Bytes: []byte("Bark"), }, }, Snake([]byte("hiss")), &Viper{ Bytes: []byte("hizz"), }, }, Bytes: [5]byte{1, 10, 50, 100, 200}, Ints: [5]int{1, 2, 3, 4, 5}, Array: SimpleArray([5]byte{1, 10, 50, 100, 200}), } return c } func instantiateComplexArray() (interface{}, interface{}) { return ComplexStructArray{}, &ComplexStructArray{} } func validateComplexArray(o interface{}, t *testing.T) { c2 := o.(ComplexStructArray) if cat, ok := c2.Animals[0].(Cat); ok { if cat.String != "String" { t.Errorf("Expected cat.String == 'String', got %v", cat.String) } if string(cat.Bytes) != "Bytes" { t.Errorf("Expected cat.Bytes == 'Bytes', got %X", cat.Bytes) } } else { t.Errorf("Expected c2.Animals[0] to be of type cat, got %v", reflect.ValueOf(c2.Animals[0]).Elem().Type()) } if dog, ok := c2.Animals[1].(Dog); ok { if dog.String != "Woof" { t.Errorf("Expected dog.String == 'Woof', got %v", dog.String) } if string(dog.Bytes) != "Bark" { t.Errorf("Expected dog.Bytes == 'Bark', got %X", dog.Bytes) } } else { t.Errorf("Expected c2.Animals[1] to be of type dog, got %v", reflect.ValueOf(c2.Animals[1]).Elem().Type()) } if snake, ok := c2.Animals[2].(Snake); ok { if string(snake) != "hiss" { t.Errorf("Expected string(snake) == 'hiss', got %v", string(snake)) } } else { t.Errorf("Expected c2.Animals[2] to be of type Snake, got %v", reflect.ValueOf(c2.Animals[2]).Elem().Type()) } if viper, ok := c2.Animals[3].(*Viper); ok { if string(viper.Bytes) != "hizz" { t.Errorf("Expected string(viper.Bytes) == 'hizz', got %v", string(viper.Bytes)) } } else { t.Errorf("Expected c2.Animals[3] to be of type *Viper, got %v", reflect.ValueOf(c2.Animals[3]).Elem().Type()) } } //----------------------------------------------------------------------------- var testCases = []TestCase{} func init() { testCases = append(testCases, TestCase{constructBasic, instantiateBasic, validateBasic}) testCases = append(testCases, TestCase{constructComplex, instantiateComplex, validateComplex}) testCases = append(testCases, TestCase{constructComplex2, instantiateComplex2, validateComplex2}) testCases = append(testCases, TestCase{constructComplexArray, instantiateComplexArray, validateComplexArray}) testCases = append(testCases, TestCase{constructNilTestStruct, instantiateNilTestStruct, validateNilTestStruct}) } func TestBinary(t *testing.T) { for i, testCase := range testCases { log.Notice(fmt.Sprintf("Running test case %v", i)) // Construct an object o := testCase.Constructor() // Write the object data := BinaryBytes(o) t.Logf("Binary: %X", data) instance, instancePtr := testCase.Instantiator() // Read onto a struct n, err := new(int64), new(error) res := ReadBinary(instance, bytes.NewReader(data), n, err) if *err != nil { t.Fatalf("Failed to read into instance: %v", *err) } // Validate object testCase.Validator(res, t) // Read onto a pointer n, err = new(int64), new(error) res = ReadBinaryPtr(instancePtr, bytes.NewReader(data), n, err) if *err != nil { t.Fatalf("Failed to read into instance: %v", *err) } if res != instancePtr { t.Errorf("Expected pointer to pass through") } // Validate object testCase.Validator(reflect.ValueOf(res).Elem().Interface(), t) } } func TestJSON(t *testing.T) { for i, testCase := range testCases { log.Notice(fmt.Sprintf("Running test case %v", i)) // Construct an object o := testCase.Constructor() // Write the object data := JSONBytes(o) t.Logf("JSON: %v", string(data)) instance, instancePtr := testCase.Instantiator() // Read onto a struct err := new(error) res := ReadJSON(instance, data, err) if *err != nil { t.Fatalf("Failed to read cat: %v", *err) } // Validate object testCase.Validator(res, t) // Read onto a pointer res = ReadJSON(instancePtr, data, err) if *err != nil { t.Fatalf("Failed to read cat: %v", *err) } if res != instancePtr { t.Errorf("Expected pointer to pass through") } // Validate object testCase.Validator(reflect.ValueOf(res).Elem().Interface(), t) } } //------------------------------------------------------------------------------ type Foo struct { FieldA string `json:"fieldA"` // json field name is "fieldA" FieldB string // json field name is "FieldB" fieldC string // not exported, not serialized. } func TestJSONFieldNames(t *testing.T) { for i := 0; i < 20; i++ { // Try to ensure deterministic success. foo := Foo{"a", "b", "c"} stringified := string(JSONBytes(foo)) expected := `{"fieldA":"a","FieldB":"b"}` if stringified != expected { t.Fatalf("JSONFieldNames error: expected %v, got %v", expected, stringified) } } } //------------------------------------------------------------------------------ func TestBadAlloc(t *testing.T) { n, err := new(int64), new(error) instance := new([]byte) data := RandBytes(100 * 1024) b := new(bytes.Buffer) // this slice of data claims to be much bigger than it really is WriteUvarint(uint(10000000000000000), b, n, err) b.Write(data) res := ReadBinary(instance, b, n, err) fmt.Println(res, *err) } //------------------------------------------------------------------------------ type SimpleArray [5]byte func TestSimpleArray(t *testing.T) { var foo SimpleArray // Type of pointer to array rt := reflect.TypeOf(&foo) fmt.Printf("rt: %v\n", rt) // *binary.SimpleArray // Type of array itself. // NOTE: normally this is acquired through other means // like introspecting on method signatures, or struct fields. rte := rt.Elem() fmt.Printf("rte: %v\n", rte) // binary.SimpleArray // Get a new pointer to the array // NOTE: calling .Interface() is to get the actual value, // instead of reflection values. ptr := reflect.New(rte).Interface() fmt.Printf("ptr: %v\n", ptr) // &[0 0 0 0 0] // Make a simple int aray fooArray := SimpleArray([5]byte{1, 10, 50, 100, 200}) fooBytes := BinaryBytes(fooArray) fooReader := bytes.NewReader(fooBytes) // Now you can read it. n, err := new(int64), new(error) it := ReadBinary(foo, fooReader, n, err).(SimpleArray) if !bytes.Equal(it[:], fooArray[:]) { t.Errorf("Expected %v but got %v", fooArray, it) } }
alist/mint-client
Godeps/_workspace/src/github.com/tendermint/tendermint/wire/reflect_test.go
GO
gpl-3.0
12,198
/* Traverse a file hierarchy. Copyright (C) 2004-2009 Free Software Foundation, Inc. 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/>. */ /*- * Copyright (c) 1990, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <config.h> #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94"; #endif /* LIBC_SCCS and not lint */ #include "fts_.h" #if HAVE_SYS_PARAM_H || defined _LIBC # include <sys/param.h> #endif #ifdef _LIBC # include <include/sys/stat.h> #else # include <sys/stat.h> #endif #include <fcntl.h> #include <errno.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #if ! _LIBC # include "fcntl--.h" # include "dirent--.h" # include "unistd--.h" /* FIXME - use fcntl(F_DUPFD_CLOEXEC)/openat(O_CLOEXEC) once they are supported. */ # include "cloexec.h" # include "openat.h" # include "same-inode.h" #endif #include <dirent.h> #ifndef _D_EXACT_NAMLEN # define _D_EXACT_NAMLEN(dirent) strlen ((dirent)->d_name) #endif #if HAVE_STRUCT_DIRENT_D_TYPE /* True if the type of the directory entry D is known. */ # define DT_IS_KNOWN(d) ((d)->d_type != DT_UNKNOWN) /* True if the type of the directory entry D must be T. */ # define DT_MUST_BE(d, t) ((d)->d_type == (t)) # define D_TYPE(d) ((d)->d_type) #else # define DT_IS_KNOWN(d) false # define DT_MUST_BE(d, t) false # define D_TYPE(d) DT_UNKNOWN # undef DT_UNKNOWN # define DT_UNKNOWN 0 /* Any nonzero values will do here, so long as they're distinct. Undef any existing macros out of the way. */ # undef DT_BLK # undef DT_CHR # undef DT_DIR # undef DT_FIFO # undef DT_LNK # undef DT_REG # undef DT_SOCK # define DT_BLK 1 # define DT_CHR 2 # define DT_DIR 3 # define DT_FIFO 4 # define DT_LNK 5 # define DT_REG 6 # define DT_SOCK 7 #endif #ifndef S_IFLNK # define S_IFLNK 0 #endif #ifndef S_IFSOCK # define S_IFSOCK 0 #endif enum { NOT_AN_INODE_NUMBER = 0 }; #ifdef D_INO_IN_DIRENT # define D_INO(dp) (dp)->d_ino #else /* Some systems don't have inodes, so fake them to avoid lots of ifdefs. */ # define D_INO(dp) NOT_AN_INODE_NUMBER #endif /* If there are more than this many entries in a directory, and the conditions mentioned below are satisfied, then sort the entries on inode number before any further processing. */ #ifndef FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD # define FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD 10000 #endif enum { _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD = FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD }; enum Fts_stat { FTS_NO_STAT_REQUIRED = 1, FTS_STAT_REQUIRED = 2 }; #ifdef _LIBC # undef close # define close __close # undef closedir # define closedir __closedir # undef fchdir # define fchdir __fchdir # undef open # define open __open # undef opendir # define opendir __opendir # undef readdir # define readdir __readdir #else # undef internal_function # define internal_function /* empty */ #endif #ifndef __set_errno # define __set_errno(Val) errno = (Val) #endif #ifndef __attribute__ # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) # define __attribute__(x) /* empty */ # endif #endif #ifndef ATTRIBUTE_UNUSED # define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) #endif /* If this host provides the openat function, then we can avoid attempting to open "." in some initialization code below. */ #ifdef HAVE_OPENAT # define HAVE_OPENAT_SUPPORT 1 #else # define HAVE_OPENAT_SUPPORT 0 #endif #ifdef NDEBUG # define fts_assert(expr) ((void) 0) #else # define fts_assert(expr) \ do \ { \ if (!(expr)) \ abort (); \ } \ while (false) #endif static FTSENT *fts_alloc (FTS *, const char *, size_t) internal_function; static FTSENT *fts_build (FTS *, int) internal_function; static void fts_lfree (FTSENT *) internal_function; static void fts_load (FTS *, FTSENT *) internal_function; static size_t fts_maxarglen (char * const *) internal_function; static void fts_padjust (FTS *, FTSENT *) internal_function; static bool fts_palloc (FTS *, size_t) internal_function; static FTSENT *fts_sort (FTS *, FTSENT *, size_t) internal_function; static unsigned short int fts_stat (FTS *, FTSENT *, bool) internal_function; static int fts_safe_changedir (FTS *, FTSENT *, int, const char *) internal_function; #if GNULIB_FTS # include "fts-cycle.c" #else static bool enter_dir (FTS *fts, FTSENT *ent) { return true; } static void leave_dir (FTS *fts, FTSENT *ent) {} static bool setup_dir (FTS *fts) { return true; } static void free_dir (FTS *fts) {} #endif #ifndef MAX # define MAX(a,b) ((a) > (b) ? (a) : (b)) #endif #ifndef SIZE_MAX # define SIZE_MAX ((size_t) -1) #endif #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2]))) #define STREQ(a, b) (strcmp ((a), (b)) == 0) #define CLR(opt) (sp->fts_options &= ~(opt)) #define ISSET(opt) (sp->fts_options & (opt)) #define SET(opt) (sp->fts_options |= (opt)) /* FIXME: make this a function */ #define RESTORE_INITIAL_CWD(sp) \ (fd_ring_clear (&((sp)->fts_fd_ring)), \ FCHDIR ((sp), (ISSET (FTS_CWDFD) ? AT_FDCWD : (sp)->fts_rfd))) /* FIXME: FTS_NOCHDIR is now misnamed. Call it FTS_USE_FULL_RELATIVE_FILE_NAMES instead. */ #define FCHDIR(sp, fd) \ (!ISSET(FTS_NOCHDIR) && (ISSET(FTS_CWDFD) \ ? (cwd_advance_fd ((sp), (fd), true), 0) \ : fchdir (fd))) /* fts_build flags */ /* FIXME: make this an enum */ #define BCHILD 1 /* fts_children */ #define BNAMES 2 /* fts_children, names only */ #define BREAD 3 /* fts_read */ #if FTS_DEBUG # include <inttypes.h> # include <stdint.h> # include <stdio.h> # include "getcwdat.h" bool fts_debug = false; # define Dprintf(x) do { if (fts_debug) printf x; } while (false) #else # define Dprintf(x) # define fd_ring_check(x) # define fd_ring_print(a, b, c) #endif #define LEAVE_DIR(Fts, Ent, Tag) \ do \ { \ Dprintf ((" %s-leaving: %s\n", Tag, (Ent)->fts_path)); \ leave_dir (Fts, Ent); \ fd_ring_check (Fts); \ } \ while (false) static void fd_ring_clear (I_ring *fd_ring) { while ( ! i_ring_empty (fd_ring)) { int fd = i_ring_pop (fd_ring); if (0 <= fd) close (fd); } } /* Overload the fts_statp->st_size member (otherwise unused, when fts_info is FTS_NSOK) to indicate whether fts_read should stat this entry or not. */ static void fts_set_stat_required (FTSENT *p, bool required) { fts_assert (p->fts_info == FTS_NSOK); p->fts_statp->st_size = (required ? FTS_STAT_REQUIRED : FTS_NO_STAT_REQUIRED); } /* file-descriptor-relative opendir. */ /* FIXME: if others need this function, move it into lib/openat.c */ static inline DIR * internal_function opendirat (int fd, char const *dir) { int new_fd = openat (fd, dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK); DIR *dirp; if (new_fd < 0) return NULL; set_cloexec_flag (new_fd, true); dirp = fdopendir (new_fd); if (dirp == NULL) { int saved_errno = errno; close (new_fd); errno = saved_errno; } return dirp; } /* Virtual fchdir. Advance SP's working directory file descriptor, SP->fts_cwd_fd, to FD, and push the previous value onto the fd_ring. CHDIR_DOWN_ONE is true if FD corresponds to an entry in the directory open on sp->fts_cwd_fd; i.e., to move the working directory one level down. */ static void internal_function cwd_advance_fd (FTS *sp, int fd, bool chdir_down_one) { int old = sp->fts_cwd_fd; fts_assert (old != fd || old == AT_FDCWD); if (chdir_down_one) { /* Push "old" onto the ring. If the displaced file descriptor is non-negative, close it. */ int prev_fd_in_slot = i_ring_push (&sp->fts_fd_ring, old); fd_ring_print (sp, stderr, "post-push"); if (0 <= prev_fd_in_slot) close (prev_fd_in_slot); /* ignore any close failure */ } else if ( ! ISSET (FTS_NOCHDIR)) { if (0 <= old) close (old); /* ignore any close failure */ } sp->fts_cwd_fd = fd; } /* Open the directory DIR if possible, and return a file descriptor. Return -1 and set errno on failure. It doesn't matter whether the file descriptor has read or write access. */ static inline int internal_function diropen (FTS const *sp, char const *dir) { int open_flags = (O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK | (ISSET (FTS_PHYSICAL) ? O_NOFOLLOW : 0)); int fd = (ISSET (FTS_CWDFD) ? openat (sp->fts_cwd_fd, dir, open_flags) : open (dir, open_flags)); if (0 <= fd) set_cloexec_flag (fd, true); return fd; } FTS * fts_open (char * const *argv, register int options, int (*compar) (FTSENT const **, FTSENT const **)) { register FTS *sp; register FTSENT *p, *root; register size_t nitems; FTSENT *parent = NULL; FTSENT *tmp = NULL; /* pacify gcc */ size_t len; bool defer_stat; /* Options check. */ if (options & ~FTS_OPTIONMASK) { __set_errno (EINVAL); return (NULL); } if ((options & FTS_NOCHDIR) && (options & FTS_CWDFD)) { __set_errno (EINVAL); return (NULL); } if ( ! (options & (FTS_LOGICAL | FTS_PHYSICAL))) { __set_errno (EINVAL); return (NULL); } /* Allocate/initialize the stream */ if ((sp = malloc(sizeof(FTS))) == NULL) return (NULL); memset(sp, 0, sizeof(FTS)); sp->fts_compar = compar; sp->fts_options = options; /* Logical walks turn on NOCHDIR; symbolic links are too hard. */ if (ISSET(FTS_LOGICAL)) { SET(FTS_NOCHDIR); CLR(FTS_CWDFD); } /* Initialize fts_cwd_fd. */ sp->fts_cwd_fd = AT_FDCWD; if ( ISSET(FTS_CWDFD) && ! HAVE_OPENAT_SUPPORT) { /* While it isn't technically necessary to open "." this early, doing it here saves us the trouble of ensuring later (where it'd be messier) that "." can in fact be opened. If not, revert to FTS_NOCHDIR mode. */ int fd = open (".", O_RDONLY); if (fd < 0) { /* Even if `.' is unreadable, don't revert to FTS_NOCHDIR mode on systems like Linux+PROC_FS, where our openat emulation is good enough. Note: on a system that emulates openat via /proc, this technique can still fail, but only in extreme conditions, e.g., when the working directory cannot be saved (i.e. save_cwd fails) -- and that happens on Linux only when "." is unreadable and the CWD would be longer than PATH_MAX. FIXME: once Linux kernel openat support is well established, replace the above open call and this entire if/else block with the body of the if-block below. */ if ( openat_needs_fchdir ()) { SET(FTS_NOCHDIR); CLR(FTS_CWDFD); } } else { close (fd); } } /* * Start out with 1K of file name space, and enough, in any case, * to hold the user's file names. */ #ifndef MAXPATHLEN # define MAXPATHLEN 1024 #endif { size_t maxarglen = fts_maxarglen(argv); if (! fts_palloc(sp, MAX(maxarglen, MAXPATHLEN))) goto mem1; } /* Allocate/initialize root's parent. */ if (*argv != NULL) { if ((parent = fts_alloc(sp, "", 0)) == NULL) goto mem2; parent->fts_level = FTS_ROOTPARENTLEVEL; } /* The classic fts implementation would call fts_stat with a new entry for each iteration of the loop below. If the comparison function is not specified or if the FTS_DEFER_STAT option is in effect, don't stat any entry in this loop. This is an attempt to minimize the interval between the initial stat/lstat/fstatat and the point at which a directory argument is first opened. This matters for any directory command line argument that resides on a file system without genuine i-nodes. If you specify FTS_DEFER_STAT along with a comparison function, that function must not access any data via the fts_statp pointer. */ defer_stat = (compar == NULL || ISSET(FTS_DEFER_STAT)); /* Allocate/initialize root(s). */ for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) { /* Don't allow zero-length file names. */ if ((len = strlen(*argv)) == 0) { __set_errno (ENOENT); goto mem3; } if ((p = fts_alloc(sp, *argv, len)) == NULL) goto mem3; p->fts_level = FTS_ROOTLEVEL; p->fts_parent = parent; p->fts_accpath = p->fts_name; /* Even when defer_stat is true, be sure to stat the first command line argument, since fts_read (at least with FTS_XDEV) requires that. */ if (defer_stat && root != NULL) { p->fts_info = FTS_NSOK; fts_set_stat_required(p, true); } else { p->fts_info = fts_stat(sp, p, false); } /* * If comparison routine supplied, traverse in sorted * order; otherwise traverse in the order specified. */ if (compar) { p->fts_link = root; root = p; } else { p->fts_link = NULL; if (root == NULL) tmp = root = p; else { tmp->fts_link = p; tmp = p; } } } if (compar && nitems > 1) root = fts_sort(sp, root, nitems); /* * Allocate a dummy pointer and make fts_read think that we've just * finished the node before the root(s); set p->fts_info to FTS_INIT * so that everything about the "current" node is ignored. */ if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL) goto mem3; sp->fts_cur->fts_link = root; sp->fts_cur->fts_info = FTS_INIT; if (! setup_dir (sp)) goto mem3; /* * If using chdir(2), grab a file descriptor pointing to dot to ensure * that we can get back here; this could be avoided for some file names, * but almost certainly not worth the effort. Slashes, symbolic links, * and ".." are all fairly nasty problems. Note, if we can't get the * descriptor we run anyway, just more slowly. */ if (!ISSET(FTS_NOCHDIR) && !ISSET(FTS_CWDFD) && (sp->fts_rfd = diropen (sp, ".")) < 0) SET(FTS_NOCHDIR); i_ring_init (&sp->fts_fd_ring, -1); return (sp); mem3: fts_lfree(root); free(parent); mem2: free(sp->fts_path); mem1: free(sp); return (NULL); } static void internal_function fts_load (FTS *sp, register FTSENT *p) { register size_t len; register char *cp; /* * Load the stream structure for the next traversal. Since we don't * actually enter the directory until after the preorder visit, set * the fts_accpath field specially so the chdir gets done to the right * place and the user can access the first node. From fts_open it's * known that the file name will fit. */ len = p->fts_pathlen = p->fts_namelen; memmove(sp->fts_path, p->fts_name, len + 1); if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) { len = strlen(++cp); memmove(p->fts_name, cp, len + 1); p->fts_namelen = len; } p->fts_accpath = p->fts_path = sp->fts_path; } int fts_close (FTS *sp) { register FTSENT *freep, *p; int saved_errno = 0; /* * This still works if we haven't read anything -- the dummy structure * points to the root list, so we step through to the end of the root * list which has a valid parent pointer. */ if (sp->fts_cur) { for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) { freep = p; p = p->fts_link != NULL ? p->fts_link : p->fts_parent; free(freep); } free(p); } /* Free up child linked list, sort array, file name buffer. */ if (sp->fts_child) fts_lfree(sp->fts_child); free(sp->fts_array); free(sp->fts_path); if (ISSET(FTS_CWDFD)) { if (0 <= sp->fts_cwd_fd) if (close (sp->fts_cwd_fd)) saved_errno = errno; } else if (!ISSET(FTS_NOCHDIR)) { /* Return to original directory, save errno if necessary. */ if (fchdir(sp->fts_rfd)) saved_errno = errno; /* If close fails, record errno only if saved_errno is zero, so that we report the probably-more-meaningful fchdir errno. */ if (close (sp->fts_rfd)) if (saved_errno == 0) saved_errno = errno; } fd_ring_clear (&sp->fts_fd_ring); #if GNULIB_FTS if (sp->fts_leaf_optimization_works_ht) hash_free (sp->fts_leaf_optimization_works_ht); #endif free_dir (sp); /* Free up the stream pointer. */ free(sp); /* Set errno and return. */ if (saved_errno) { __set_errno (saved_errno); return (-1); } return (0); } #if defined __linux__ \ && HAVE_SYS_VFS_H && HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE #include <sys/vfs.h> /* Linux-specific constants from coreutils' src/fs.h */ # define S_MAGIC_TMPFS 0x1021994 # define S_MAGIC_NFS 0x6969 # define S_MAGIC_REISERFS 0x52654973 # define S_MAGIC_PROC 0x9FA0 /* Return false if it is easy to determine the file system type of the directory on which DIR_FD is open, and sorting dirents on inode numbers is known not to improve traversal performance with that type of file system. Otherwise, return true. */ static bool dirent_inode_sort_may_be_useful (int dir_fd) { /* Skip the sort only if we can determine efficiently that skipping it is the right thing to do. The cost of performing an unnecessary sort is negligible, while the cost of *not* performing it can be O(N^2) with a very large constant. */ struct statfs fs_buf; /* If fstatfs fails, assume sorting would be useful. */ if (fstatfs (dir_fd, &fs_buf) != 0) return true; /* FIXME: what about when f_type is not an integral type? deal with that if/when it's encountered. */ switch (fs_buf.f_type) { case S_MAGIC_TMPFS: case S_MAGIC_NFS: /* On a file system of any of these types, sorting is unnecessary, and hence wasteful. */ return false; default: return true; } } /* Given a file descriptor DIR_FD open on a directory D, return true if it is valid to apply the leaf-optimization technique of counting directories in D via stat.st_nlink. */ static bool leaf_optimization_applies (int dir_fd) { struct statfs fs_buf; /* If fstatfs fails, assume we can't use the optimization. */ if (fstatfs (dir_fd, &fs_buf) != 0) return false; /* FIXME: do we need to detect AFS mount points? I doubt it, unless fstatfs can report S_MAGIC_REISERFS for such a directory. */ switch (fs_buf.f_type) { /* List here the file system types that lack useable dirent.d_type info, yet for which the optimization does apply. */ case S_MAGIC_REISERFS: return true; case S_MAGIC_PROC: /* Explicitly listing this or any other file system type for which the optimization is not applicable is not necessary, but we leave it here to document the risk. Per http://bugs.debian.org/143111, /proc may have bogus stat.st_nlink values. */ /* fall through */ default: return false; } } #else static bool dirent_inode_sort_may_be_useful (int dir_fd) { return true; } static bool leaf_optimization_applies (int dir_fd) { return false; } #endif #if GNULIB_FTS /* link-count-optimization entry: map an stat.st_dev number to a boolean: leaf_optimization_works */ struct LCO_ent { dev_t st_dev; bool opt_ok; }; /* Use a tiny initial size. If a traversal encounters more than a few devices, the cost of growing/rehashing this table will be rendered negligible by the number of inodes processed. */ enum { LCO_HT_INITIAL_SIZE = 13 }; static size_t LCO_hash (void const *x, size_t table_size) { struct LCO_ent const *ax = x; return (uintmax_t) ax->st_dev % table_size; } static bool LCO_compare (void const *x, void const *y) { struct LCO_ent const *ax = x; struct LCO_ent const *ay = y; return ax->st_dev == ay->st_dev; } /* Ask the same question as leaf_optimization_applies, but query the cache first (FTS.fts_leaf_optimization_works_ht), and if necessary, update that cache. */ static bool link_count_optimize_ok (FTSENT const *p) { FTS *sp = p->fts_fts; Hash_table *h = sp->fts_leaf_optimization_works_ht; struct LCO_ent tmp; struct LCO_ent *ent; bool opt_ok; struct LCO_ent *t2; /* If we're not in CWDFD mode, don't bother with this optimization, since the caller is not serious about performance. */ if (!ISSET(FTS_CWDFD)) return false; /* map st_dev to the boolean, leaf_optimization_works */ if (h == NULL) { h = sp->fts_leaf_optimization_works_ht = hash_initialize (LCO_HT_INITIAL_SIZE, NULL, LCO_hash, LCO_compare, free); if (h == NULL) return false; } tmp.st_dev = p->fts_statp->st_dev; ent = hash_lookup (h, &tmp); if (ent) return ent->opt_ok; /* Look-up failed. Query directly and cache the result. */ t2 = malloc (sizeof *t2); if (t2 == NULL) return false; /* Is it ok to perform the optimization in the dir, FTS_CWD_FD? */ opt_ok = leaf_optimization_applies (sp->fts_cwd_fd); t2->opt_ok = opt_ok; t2->st_dev = p->fts_statp->st_dev; ent = hash_insert (h, t2); if (ent == NULL) { /* insertion failed */ free (t2); return false; } fts_assert (ent == t2); return opt_ok; } #endif /* * Special case of "/" at the end of the file name so that slashes aren't * appended which would cause file names to be written as "....//foo". */ #define NAPPEND(p) \ (p->fts_path[p->fts_pathlen - 1] == '/' \ ? p->fts_pathlen - 1 : p->fts_pathlen) FTSENT * fts_read (register FTS *sp) { register FTSENT *p, *tmp; register unsigned short int instr; register char *t; /* If finished or unrecoverable error, return NULL. */ if (sp->fts_cur == NULL || ISSET(FTS_STOP)) return (NULL); /* Set current node pointer. */ p = sp->fts_cur; /* Save and zero out user instructions. */ instr = p->fts_instr; p->fts_instr = FTS_NOINSTR; /* Any type of file may be re-visited; re-stat and re-turn. */ if (instr == FTS_AGAIN) { p->fts_info = fts_stat(sp, p, false); return (p); } Dprintf (("fts_read: p=%s\n", p->fts_info == FTS_INIT ? "" : p->fts_path)); /* * Following a symlink -- SLNONE test allows application to see * SLNONE and recover. If indirecting through a symlink, have * keep a pointer to current location. If unable to get that * pointer, follow fails. */ if (instr == FTS_FOLLOW && (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) { p->fts_info = fts_stat(sp, p, true); if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) { if ((p->fts_symfd = diropen (sp, ".")) < 0) { p->fts_errno = errno; p->fts_info = FTS_ERR; } else p->fts_flags |= FTS_SYMFOLLOW; } goto check_for_dir; } /* Directory in pre-order. */ if (p->fts_info == FTS_D) { /* If skipped or crossed mount point, do post-order visit. */ if (instr == FTS_SKIP || (ISSET(FTS_XDEV) && p->fts_statp->st_dev != sp->fts_dev)) { if (p->fts_flags & FTS_SYMFOLLOW) (void)close(p->fts_symfd); if (sp->fts_child) { fts_lfree(sp->fts_child); sp->fts_child = NULL; } p->fts_info = FTS_DP; LEAVE_DIR (sp, p, "1"); return (p); } /* Rebuild if only read the names and now traversing. */ if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) { CLR(FTS_NAMEONLY); fts_lfree(sp->fts_child); sp->fts_child = NULL; } /* * Cd to the subdirectory. * * If have already read and now fail to chdir, whack the list * to make the names come out right, and set the parent errno * so the application will eventually get an error condition. * Set the FTS_DONTCHDIR flag so that when we logically change * directories back to the parent we don't do a chdir. * * If haven't read do so. If the read fails, fts_build sets * FTS_STOP or the fts_info field of the node. */ if (sp->fts_child != NULL) { if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) { p->fts_errno = errno; p->fts_flags |= FTS_DONTCHDIR; for (p = sp->fts_child; p != NULL; p = p->fts_link) p->fts_accpath = p->fts_parent->fts_accpath; } } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) { if (ISSET(FTS_STOP)) return (NULL); /* If fts_build's call to fts_safe_changedir failed because it was not able to fchdir into a subdirectory, tell the caller. */ if (p->fts_errno && p->fts_info != FTS_DNR) p->fts_info = FTS_ERR; LEAVE_DIR (sp, p, "2"); return (p); } p = sp->fts_child; sp->fts_child = NULL; goto name; } /* Move to the next node on this level. */ next: tmp = p; if ((p = p->fts_link) != NULL) { sp->fts_cur = p; free(tmp); /* * If reached the top, return to the original directory (or * the root of the tree), and load the file names for the next * root. */ if (p->fts_level == FTS_ROOTLEVEL) { if (RESTORE_INITIAL_CWD(sp)) { SET(FTS_STOP); return (NULL); } free_dir(sp); fts_load(sp, p); setup_dir(sp); goto check_for_dir; } /* * User may have called fts_set on the node. If skipped, * ignore. If followed, get a file descriptor so we can * get back if necessary. */ if (p->fts_instr == FTS_SKIP) goto next; if (p->fts_instr == FTS_FOLLOW) { p->fts_info = fts_stat(sp, p, true); if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) { if ((p->fts_symfd = diropen (sp, ".")) < 0) { p->fts_errno = errno; p->fts_info = FTS_ERR; } else p->fts_flags |= FTS_SYMFOLLOW; } p->fts_instr = FTS_NOINSTR; } name: t = sp->fts_path + NAPPEND(p->fts_parent); *t++ = '/'; memmove(t, p->fts_name, p->fts_namelen + 1); check_for_dir: sp->fts_cur = p; if (p->fts_info == FTS_NSOK) { if (p->fts_statp->st_size == FTS_STAT_REQUIRED) { FTSENT *parent = p->fts_parent; if (FTS_ROOTLEVEL < p->fts_level /* ->fts_n_dirs_remaining is not valid for command-line-specified names. */ && parent->fts_n_dirs_remaining == 0 && ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL) && link_count_optimize_ok (parent)) { /* nothing more needed */ } else { p->fts_info = fts_stat(sp, p, false); if (S_ISDIR(p->fts_statp->st_mode) && p->fts_level != FTS_ROOTLEVEL && parent->fts_n_dirs_remaining) parent->fts_n_dirs_remaining--; } } else fts_assert (p->fts_statp->st_size == FTS_NO_STAT_REQUIRED); } if (p->fts_info == FTS_D) { /* Now that P->fts_statp is guaranteed to be valid, if this is a command-line directory, record its device number, to be used for FTS_XDEV. */ if (p->fts_level == FTS_ROOTLEVEL) sp->fts_dev = p->fts_statp->st_dev; Dprintf ((" entering: %s\n", p->fts_path)); if (! enter_dir (sp, p)) { __set_errno (ENOMEM); return NULL; } } return p; } /* Move up to the parent node. */ p = tmp->fts_parent; sp->fts_cur = p; free(tmp); if (p->fts_level == FTS_ROOTPARENTLEVEL) { /* * Done; free everything up and set errno to 0 so the user * can distinguish between error and EOF. */ free(p); __set_errno (0); return (sp->fts_cur = NULL); } fts_assert (p->fts_info != FTS_NSOK); /* NUL terminate the file name. */ sp->fts_path[p->fts_pathlen] = '\0'; /* * Return to the parent directory. If at a root node, restore * the initial working directory. If we came through a symlink, * go back through the file descriptor. Otherwise, move up * one level, via "..". */ if (p->fts_level == FTS_ROOTLEVEL) { if (RESTORE_INITIAL_CWD(sp)) { p->fts_errno = errno; SET(FTS_STOP); } } else if (p->fts_flags & FTS_SYMFOLLOW) { if (FCHDIR(sp, p->fts_symfd)) { int saved_errno = errno; (void)close(p->fts_symfd); __set_errno (saved_errno); p->fts_errno = errno; SET(FTS_STOP); } (void)close(p->fts_symfd); } else if (!(p->fts_flags & FTS_DONTCHDIR) && fts_safe_changedir(sp, p->fts_parent, -1, "..")) { p->fts_errno = errno; SET(FTS_STOP); } p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP; if (p->fts_errno == 0) LEAVE_DIR (sp, p, "3"); return ISSET(FTS_STOP) ? NULL : p; } /* * Fts_set takes the stream as an argument although it's not used in this * implementation; it would be necessary if anyone wanted to add global * semantics to fts using fts_set. An error return is allowed for similar * reasons. */ /* ARGSUSED */ int fts_set(FTS *sp ATTRIBUTE_UNUSED, FTSENT *p, int instr) { if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW && instr != FTS_NOINSTR && instr != FTS_SKIP) { __set_errno (EINVAL); return (1); } p->fts_instr = instr; return (0); } FTSENT * fts_children (register FTS *sp, int instr) { register FTSENT *p; int fd; if (instr != 0 && instr != FTS_NAMEONLY) { __set_errno (EINVAL); return (NULL); } /* Set current node pointer. */ p = sp->fts_cur; /* * Errno set to 0 so user can distinguish empty directory from * an error. */ __set_errno (0); /* Fatal errors stop here. */ if (ISSET(FTS_STOP)) return (NULL); /* Return logical hierarchy of user's arguments. */ if (p->fts_info == FTS_INIT) return (p->fts_link); /* * If not a directory being visited in pre-order, stop here. Could * allow FTS_DNR, assuming the user has fixed the problem, but the * same effect is available with FTS_AGAIN. */ if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */) return (NULL); /* Free up any previous child list. */ if (sp->fts_child != NULL) fts_lfree(sp->fts_child); if (instr == FTS_NAMEONLY) { SET(FTS_NAMEONLY); instr = BNAMES; } else instr = BCHILD; /* * If using chdir on a relative file name and called BEFORE fts_read * does its chdir to the root of a traversal, we can lose -- we need to * chdir into the subdirectory, and we don't know where the current * directory is, so we can't get back so that the upcoming chdir by * fts_read will work. */ if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' || ISSET(FTS_NOCHDIR)) return (sp->fts_child = fts_build(sp, instr)); if ((fd = diropen (sp, ".")) < 0) return (sp->fts_child = NULL); sp->fts_child = fts_build(sp, instr); if (ISSET(FTS_CWDFD)) { cwd_advance_fd (sp, fd, true); } else { if (fchdir(fd)) { int saved_errno = errno; close (fd); __set_errno (saved_errno); return NULL; } close (fd); } return (sp->fts_child); } /* A comparison function to sort on increasing inode number. For some file system types, sorting either way makes a huge performance difference for a directory with very many entries, but sorting on increasing values is slightly better than sorting on decreasing values. The difference is in the 5% range. */ static int fts_compare_ino (struct _ftsent const **a, struct _ftsent const **b) { return (a[0]->fts_statp->st_ino < b[0]->fts_statp->st_ino ? -1 : b[0]->fts_statp->st_ino < a[0]->fts_statp->st_ino ? 1 : 0); } /* Map the dirent.d_type value, DTYPE, to the corresponding stat.st_mode S_IF* bit and set ST.st_mode, thus clearing all other bits in that field. */ static void set_stat_type (struct stat *st, unsigned int dtype) { mode_t type; switch (dtype) { case DT_BLK: type = S_IFBLK; break; case DT_CHR: type = S_IFCHR; break; case DT_DIR: type = S_IFDIR; break; case DT_FIFO: type = S_IFIFO; break; case DT_LNK: type = S_IFLNK; break; case DT_REG: type = S_IFREG; break; case DT_SOCK: type = S_IFSOCK; break; default: type = 0; } st->st_mode = type; } /* * This is the tricky part -- do not casually change *anything* in here. The * idea is to build the linked list of entries that are used by fts_children * and fts_read. There are lots of special cases. * * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is * set and it's a physical walk (so that symbolic links can't be directories), * we can do things quickly. First, if it's a 4.4BSD file system, the type * of the file is in the directory entry. Otherwise, we assume that the number * of subdirectories in a node is equal to the number of links to the parent. * The former skips all stat calls. The latter skips stat calls in any leaf * directories and for any files after the subdirectories in the directory have * been found, cutting the stat calls by about 2/3. */ static FTSENT * internal_function fts_build (register FTS *sp, int type) { register struct dirent *dp; register FTSENT *p, *head; register size_t nitems; FTSENT *cur, *tail; DIR *dirp; void *oldaddr; int saved_errno; bool descend; bool doadjust; ptrdiff_t level; nlink_t nlinks; bool nostat; size_t len, maxlen, new_len; char *cp; /* Set current node pointer. */ cur = sp->fts_cur; /* * Open the directory for reading. If this fails, we're done. * If being called from fts_read, set the fts_info field. */ #if defined FTS_WHITEOUT && 0 if (ISSET(FTS_WHITEOUT)) oflag = DTF_NODUP|DTF_REWIND; else oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND; #else # define __opendir2(file, flag) \ ( ! ISSET(FTS_NOCHDIR) && ISSET(FTS_CWDFD) \ ? opendirat(sp->fts_cwd_fd, file) \ : opendir(file)) #endif if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) { if (type == BREAD) { cur->fts_info = FTS_DNR; cur->fts_errno = errno; } return (NULL); } /* Rather than calling fts_stat for each and every entry encountered in the readdir loop (below), stat each directory only right after opening it. */ if (cur->fts_info == FTS_NSOK) cur->fts_info = fts_stat(sp, cur, false); /* * Nlinks is the number of possible entries of type directory in the * directory if we're cheating on stat calls, 0 if we're not doing * any stat calls at all, (nlink_t) -1 if we're statting everything. */ if (type == BNAMES) { nlinks = 0; /* Be quiet about nostat, GCC. */ nostat = false; } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) { nlinks = (cur->fts_statp->st_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2)); nostat = true; } else { nlinks = -1; nostat = false; } /* * If we're going to need to stat anything or we want to descend * and stay in the directory, chdir. If this fails we keep going, * but set a flag so we don't chdir after the post-order visit. * We won't be able to stat anything, but we can still return the * names themselves. Note, that since fts_read won't be able to * chdir into the directory, it will have to return different file * names than before, i.e. "a/b" instead of "b". Since the node * has already been visited in pre-order, have to wait until the * post-order visit to return the error. There is a special case * here, if there was nothing to stat then it's not an error to * not be able to stat. This is all fairly nasty. If a program * needed sorted entries or stat information, they had better be * checking FTS_NS on the returned nodes. */ if (nlinks || type == BREAD) { int dir_fd = dirfd(dirp); if (ISSET(FTS_CWDFD) && 0 <= dir_fd) { dir_fd = dup (dir_fd); set_cloexec_flag (dir_fd, true); } if (dir_fd < 0 || fts_safe_changedir(sp, cur, dir_fd, NULL)) { if (nlinks && type == BREAD) cur->fts_errno = errno; cur->fts_flags |= FTS_DONTCHDIR; descend = false; closedir(dirp); if (ISSET(FTS_CWDFD) && 0 <= dir_fd) close (dir_fd); dirp = NULL; } else descend = true; } else descend = false; /* * Figure out the max file name length that can be stored in the * current buffer -- the inner loop allocates more space as necessary. * We really wouldn't have to do the maxlen calculations here, we * could do them in fts_read before returning the name, but it's a * lot easier here since the length is part of the dirent structure. * * If not changing directories set a pointer so that can just append * each new component into the file name. */ len = NAPPEND(cur); if (ISSET(FTS_NOCHDIR)) { cp = sp->fts_path + len; *cp++ = '/'; } else { /* GCC, you're too verbose. */ cp = NULL; } len++; maxlen = sp->fts_pathlen - len; level = cur->fts_level + 1; /* Read the directory, attaching each entry to the `link' pointer. */ doadjust = false; for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) { bool is_dir; if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name)) continue; if ((p = fts_alloc (sp, dp->d_name, _D_EXACT_NAMLEN (dp))) == NULL) goto mem1; if (_D_EXACT_NAMLEN (dp) >= maxlen) { /* include space for NUL */ oldaddr = sp->fts_path; if (! fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) { /* * No more memory. Save * errno, free up the current structure and the * structures already allocated. */ mem1: saved_errno = errno; free(p); fts_lfree(head); closedir(dirp); cur->fts_info = FTS_ERR; SET(FTS_STOP); __set_errno (saved_errno); return (NULL); } /* Did realloc() change the pointer? */ if (oldaddr != sp->fts_path) { doadjust = true; if (ISSET(FTS_NOCHDIR)) cp = sp->fts_path + len; } maxlen = sp->fts_pathlen - len; } new_len = len + _D_EXACT_NAMLEN (dp); if (new_len < len) { /* * In the unlikely event that we would end up * with a file name longer than SIZE_MAX, free up * the current structure and the structures already * allocated, then error out with ENAMETOOLONG. */ free(p); fts_lfree(head); closedir(dirp); cur->fts_info = FTS_ERR; SET(FTS_STOP); __set_errno (ENAMETOOLONG); return (NULL); } p->fts_level = level; p->fts_parent = sp->fts_cur; p->fts_pathlen = new_len; #if defined FTS_WHITEOUT && 0 if (dp->d_type == DT_WHT) p->fts_flags |= FTS_ISW; #endif /* Store dirent.d_ino, in case we need to sort entries before processing them. */ p->fts_statp->st_ino = D_INO (dp); /* Build a file name for fts_stat to stat. */ if (ISSET(FTS_NOCHDIR)) { p->fts_accpath = p->fts_path; memmove(cp, p->fts_name, p->fts_namelen + 1); } else p->fts_accpath = p->fts_name; if (sp->fts_compar == NULL || ISSET(FTS_DEFER_STAT)) { /* Record what fts_read will have to do with this entry. In many cases, it will simply fts_stat it, but we can take advantage of any d_type information to optimize away the unnecessary stat calls. I.e., if FTS_NOSTAT is in effect and we're not following symlinks (FTS_PHYSICAL) and d_type indicates this is *not* a directory, then we won't have to stat it at all. If it *is* a directory, then (currently) we stat it regardless, in order to get device and inode numbers. Some day we might optimize that away, too, for directories where d_ino is known to be valid. */ bool skip_stat = (ISSET(FTS_PHYSICAL) && ISSET(FTS_NOSTAT) && DT_IS_KNOWN(dp) && ! DT_MUST_BE(dp, DT_DIR)); p->fts_info = FTS_NSOK; /* Propagate dirent.d_type information back to caller, when possible. */ set_stat_type (p->fts_statp, D_TYPE (dp)); fts_set_stat_required(p, !skip_stat); is_dir = (ISSET(FTS_PHYSICAL) && DT_MUST_BE(dp, DT_DIR)); } else { p->fts_info = fts_stat(sp, p, false); is_dir = (p->fts_info == FTS_D || p->fts_info == FTS_DC || p->fts_info == FTS_DOT); } /* Decrement link count if applicable. */ if (nlinks > 0 && is_dir) nlinks -= nostat; /* We walk in directory order so "ls -f" doesn't get upset. */ p->fts_link = NULL; if (head == NULL) head = tail = p; else { tail->fts_link = p; tail = p; } ++nitems; } if (dirp) closedir(dirp); /* * If realloc() changed the address of the file name, adjust the * addresses for the rest of the tree and the dir list. */ if (doadjust) fts_padjust(sp, head); /* * If not changing directories, reset the file name back to original * state. */ if (ISSET(FTS_NOCHDIR)) { if (len == sp->fts_pathlen || nitems == 0) --cp; *cp = '\0'; } /* * If descended after called from fts_children or after called from * fts_read and nothing found, get back. At the root level we use * the saved fd; if one of fts_open()'s arguments is a relative name * to an empty directory, we wind up here with no other way back. If * can't get back, we're done. */ if (descend && (type == BCHILD || !nitems) && (cur->fts_level == FTS_ROOTLEVEL ? RESTORE_INITIAL_CWD(sp) : fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) { cur->fts_info = FTS_ERR; SET(FTS_STOP); fts_lfree(head); return (NULL); } /* If didn't find anything, return NULL. */ if (!nitems) { if (type == BREAD) cur->fts_info = FTS_DP; fts_lfree(head); return (NULL); } /* If there are many entries, no sorting function has been specified, and this file system is of a type that may be slow with a large number of entries, then sort the directory entries on increasing inode numbers. */ if (nitems > _FTS_INODE_SORT_DIR_ENTRIES_THRESHOLD && !sp->fts_compar && ISSET (FTS_CWDFD) && dirent_inode_sort_may_be_useful (sp->fts_cwd_fd)) { sp->fts_compar = fts_compare_ino; head = fts_sort (sp, head, nitems); sp->fts_compar = NULL; } /* Sort the entries. */ if (sp->fts_compar && nitems > 1) head = fts_sort(sp, head, nitems); return (head); } #if FTS_DEBUG /* Walk ->fts_parent links starting at E_CURR, until the root of the current hierarchy. There should be a directory with dev/inode matching those of AD. If not, print a lot of diagnostics. */ static void find_matching_ancestor (FTSENT const *e_curr, struct Active_dir const *ad) { FTSENT const *ent; for (ent = e_curr; ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent) { if (ad->ino == ent->fts_statp->st_ino && ad->dev == ent->fts_statp->st_dev) return; } printf ("ERROR: tree dir, %s, not active\n", ad->fts_ent->fts_accpath); printf ("active dirs:\n"); for (ent = e_curr; ent->fts_level >= FTS_ROOTLEVEL; ent = ent->fts_parent) printf (" %s(%"PRIuMAX"/%"PRIuMAX") to %s(%"PRIuMAX"/%"PRIuMAX")...\n", ad->fts_ent->fts_accpath, (uintmax_t) ad->dev, (uintmax_t) ad->ino, ent->fts_accpath, (uintmax_t) ent->fts_statp->st_dev, (uintmax_t) ent->fts_statp->st_ino); } void fts_cross_check (FTS const *sp) { FTSENT const *ent = sp->fts_cur; FTSENT const *t; if ( ! ISSET (FTS_TIGHT_CYCLE_CHECK)) return; Dprintf (("fts-cross-check cur=%s\n", ent->fts_path)); /* Make sure every parent dir is in the tree. */ for (t = ent->fts_parent; t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) { struct Active_dir ad; ad.ino = t->fts_statp->st_ino; ad.dev = t->fts_statp->st_dev; if ( ! hash_lookup (sp->fts_cycle.ht, &ad)) printf ("ERROR: active dir, %s, not in tree\n", t->fts_path); } /* Make sure every dir in the tree is an active dir. But ENT is not necessarily a directory. If so, just skip this part. */ if (ent->fts_parent->fts_level >= FTS_ROOTLEVEL && (ent->fts_info == FTS_DP || ent->fts_info == FTS_D)) { struct Active_dir *ad; for (ad = hash_get_first (sp->fts_cycle.ht); ad != NULL; ad = hash_get_next (sp->fts_cycle.ht, ad)) { find_matching_ancestor (ent, ad); } } } static bool same_fd (int fd1, int fd2) { struct stat sb1, sb2; return (fstat (fd1, &sb1) == 0 && fstat (fd2, &sb2) == 0 && SAME_INODE (sb1, sb2)); } static void fd_ring_print (FTS const *sp, FILE *stream, char const *msg) { I_ring const *fd_ring = &sp->fts_fd_ring; unsigned int i = fd_ring->fts_front; char *cwd = getcwdat (sp->fts_cwd_fd, NULL, 0); fprintf (stream, "=== %s ========== %s\n", msg, cwd); free (cwd); if (i_ring_empty (fd_ring)) return; while (true) { int fd = fd_ring->fts_fd_ring[i]; if (fd < 0) fprintf (stream, "%d: %d:\n", i, fd); else { char *wd = getcwdat (fd, NULL, 0); fprintf (stream, "%d: %d: %s\n", i, fd, wd); free (wd); } if (i == fd_ring->fts_back) break; i = (i + I_RING_SIZE - 1) % I_RING_SIZE; } } /* Ensure that each file descriptor on the fd_ring matches a parent, grandparent, etc. of the current working directory. */ static void fd_ring_check (FTS const *sp) { if (!fts_debug) return; /* Make a writable copy. */ I_ring fd_w = sp->fts_fd_ring; int cwd_fd = sp->fts_cwd_fd; cwd_fd = dup (cwd_fd); char *dot = getcwdat (cwd_fd, NULL, 0); error (0, 0, "===== check ===== cwd: %s", dot); free (dot); while ( ! i_ring_empty (&fd_w)) { int fd = i_ring_pop (&fd_w); if (0 <= fd) { int parent_fd = openat (cwd_fd, "..", O_RDONLY); if (parent_fd < 0) { // Warn? break; } if (!same_fd (fd, parent_fd)) { char *cwd = getcwdat (fd, NULL, 0); error (0, errno, "ring : %s", cwd); char *c2 = getcwdat (parent_fd, NULL, 0); error (0, errno, "parent: %s", c2); free (cwd); free (c2); fts_assert (0); } close (cwd_fd); cwd_fd = parent_fd; } } close (cwd_fd); } #endif static unsigned short int internal_function fts_stat(FTS *sp, register FTSENT *p, bool follow) { struct stat *sbp = p->fts_statp; int saved_errno; if (p->fts_level == FTS_ROOTLEVEL && ISSET(FTS_COMFOLLOW)) follow = true; #if defined FTS_WHITEOUT && 0 /* check for whiteout */ if (p->fts_flags & FTS_ISW) { memset(sbp, '\0', sizeof (*sbp)); sbp->st_mode = S_IFWHT; return (FTS_W); } #endif /* * If doing a logical walk, or application requested FTS_FOLLOW, do * a stat(2). If that fails, check for a non-existent symlink. If * fail, set the errno from the stat call. */ if (ISSET(FTS_LOGICAL) || follow) { if (stat(p->fts_accpath, sbp)) { saved_errno = errno; if (errno == ENOENT && lstat(p->fts_accpath, sbp) == 0) { __set_errno (0); return (FTS_SLNONE); } p->fts_errno = saved_errno; goto err; } } else if (fstatat(sp->fts_cwd_fd, p->fts_accpath, sbp, AT_SYMLINK_NOFOLLOW)) { p->fts_errno = errno; err: memset(sbp, 0, sizeof(struct stat)); return (FTS_NS); } if (S_ISDIR(sbp->st_mode)) { p->fts_n_dirs_remaining = (sbp->st_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2)); if (ISDOT(p->fts_name)) { /* Command-line "." and ".." are real directories. */ return (p->fts_level == FTS_ROOTLEVEL ? FTS_D : FTS_DOT); } #if !GNULIB_FTS { /* * Cycle detection is done by brute force when the directory * is first encountered. If the tree gets deep enough or the * number of symbolic links to directories is high enough, * something faster might be worthwhile. */ FTSENT *t; for (t = p->fts_parent; t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) if (sbp->st_ino == t->fts_statp->st_ino && sbp->st_dev == t->fts_statp->st_dev) { p->fts_cycle = t; return (FTS_DC); } } #endif return (FTS_D); } if (S_ISLNK(sbp->st_mode)) return (FTS_SL); if (S_ISREG(sbp->st_mode)) return (FTS_F); return (FTS_DEFAULT); } static int fts_compar (void const *a, void const *b) { /* Convert A and B to the correct types, to pacify the compiler, and for portability to bizarre hosts where "void const *" and "FTSENT const **" differ in runtime representation. The comparison function cannot modify *a and *b, but there is no compile-time check for this. */ FTSENT const **pa = (FTSENT const **) a; FTSENT const **pb = (FTSENT const **) b; return pa[0]->fts_fts->fts_compar (pa, pb); } static FTSENT * internal_function fts_sort (FTS *sp, FTSENT *head, register size_t nitems) { register FTSENT **ap, *p; /* On most modern hosts, void * and FTSENT ** have the same run-time representation, and one can convert sp->fts_compar to the type qsort expects without problem. Use the heuristic that this is OK if the two pointer types are the same size, and if converting FTSENT ** to long int is the same as converting FTSENT ** to void * and then to long int. This heuristic isn't valid in general but we don't know of any counterexamples. */ FTSENT *dummy; int (*compare) (void const *, void const *) = ((sizeof &dummy == sizeof (void *) && (long int) &dummy == (long int) (void *) &dummy) ? (int (*) (void const *, void const *)) sp->fts_compar : fts_compar); /* * Construct an array of pointers to the structures and call qsort(3). * Reassemble the array in the order returned by qsort. If unable to * sort for memory reasons, return the directory entries in their * current order. Allocate enough space for the current needs plus * 40 so don't realloc one entry at a time. */ if (nitems > sp->fts_nitems) { FTSENT **a; sp->fts_nitems = nitems + 40; if (SIZE_MAX / sizeof *a < sp->fts_nitems || ! (a = realloc (sp->fts_array, sp->fts_nitems * sizeof *a))) { free(sp->fts_array); sp->fts_array = NULL; sp->fts_nitems = 0; return (head); } sp->fts_array = a; } for (ap = sp->fts_array, p = head; p; p = p->fts_link) *ap++ = p; qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), compare); for (head = *(ap = sp->fts_array); --nitems; ++ap) ap[0]->fts_link = ap[1]; ap[0]->fts_link = NULL; return (head); } static FTSENT * internal_function fts_alloc (FTS *sp, const char *name, register size_t namelen) { register FTSENT *p; size_t len; /* * The file name is a variable length array. Allocate the FTSENT * structure and the file name in one chunk. */ len = sizeof(FTSENT) + namelen; if ((p = malloc(len)) == NULL) return (NULL); /* Copy the name and guarantee NUL termination. */ memmove(p->fts_name, name, namelen); p->fts_name[namelen] = '\0'; p->fts_namelen = namelen; p->fts_fts = sp; p->fts_path = sp->fts_path; p->fts_errno = 0; p->fts_flags = 0; p->fts_instr = FTS_NOINSTR; p->fts_number = 0; p->fts_pointer = NULL; return (p); } static void internal_function fts_lfree (register FTSENT *head) { register FTSENT *p; /* Free a linked list of structures. */ while ((p = head)) { head = head->fts_link; free(p); } } /* * Allow essentially unlimited file name lengths; find, rm, ls should * all work on any tree. Most systems will allow creation of file * names much longer than MAXPATHLEN, even though the kernel won't * resolve them. Add the size (not just what's needed) plus 256 bytes * so don't realloc the file name 2 bytes at a time. */ static bool internal_function fts_palloc (FTS *sp, size_t more) { char *p; size_t new_len = sp->fts_pathlen + more + 256; /* * See if fts_pathlen would overflow. */ if (new_len < sp->fts_pathlen) { free(sp->fts_path); sp->fts_path = NULL; __set_errno (ENAMETOOLONG); return false; } sp->fts_pathlen = new_len; p = realloc(sp->fts_path, sp->fts_pathlen); if (p == NULL) { free(sp->fts_path); sp->fts_path = NULL; return false; } sp->fts_path = p; return true; } /* * When the file name is realloc'd, have to fix all of the pointers in * structures already returned. */ static void internal_function fts_padjust (FTS *sp, FTSENT *head) { FTSENT *p; char *addr = sp->fts_path; #define ADJUST(p) do { \ if ((p)->fts_accpath != (p)->fts_name) { \ (p)->fts_accpath = \ (char *)addr + ((p)->fts_accpath - (p)->fts_path); \ } \ (p)->fts_path = addr; \ } while (0) /* Adjust the current set of children. */ for (p = sp->fts_child; p; p = p->fts_link) ADJUST(p); /* Adjust the rest of the tree, including the current level. */ for (p = head; p->fts_level >= FTS_ROOTLEVEL;) { ADJUST(p); p = p->fts_link ? p->fts_link : p->fts_parent; } } static size_t internal_function fts_maxarglen (char * const *argv) { size_t len, max; for (max = 0; *argv; ++argv) if ((len = strlen(*argv)) > max) max = len; return (max + 1); } /* * Change to dir specified by fd or file name without getting * tricked by someone changing the world out from underneath us. * Assumes p->fts_statp->st_dev and p->fts_statp->st_ino are filled in. * If FD is non-negative, expect it to be used after this function returns, * and to be closed eventually. So don't pass e.g., `dirfd(dirp)' and then * do closedir(dirp), because that would invalidate the saved FD. * Upon failure, close FD immediately and return nonzero. */ static int internal_function fts_safe_changedir (FTS *sp, FTSENT *p, int fd, char const *dir) { int ret; bool is_dotdot = dir && STREQ (dir, ".."); int newfd; /* This clause handles the unusual case in which FTS_NOCHDIR is specified, along with FTS_CWDFD. In that case, there is no need to change even the virtual cwd file descriptor. However, if FD is non-negative, we do close it here. */ if (ISSET (FTS_NOCHDIR)) { if (ISSET (FTS_CWDFD) && 0 <= fd) close (fd); return 0; } if (fd < 0 && is_dotdot && ISSET (FTS_CWDFD)) { /* When possible, skip the diropen and subsequent fstat+dev/ino comparison. I.e., when changing to parent directory (chdir ("..")), use a file descriptor from the ring and save the overhead of diropen+fstat, as well as avoiding failure when we lack "x" access to the virtual cwd. */ if ( ! i_ring_empty (&sp->fts_fd_ring)) { int parent_fd; fd_ring_print (sp, stderr, "pre-pop"); parent_fd = i_ring_pop (&sp->fts_fd_ring); is_dotdot = true; if (0 <= parent_fd) { fd = parent_fd; dir = NULL; } } } newfd = fd; if (fd < 0 && (newfd = diropen (sp, dir)) < 0) return -1; /* The following dev/inode check is necessary if we're doing a `logical' traversal (through symlinks, a la chown -L), if the system lacks O_NOFOLLOW support, or if we're changing to ".." (but not via a popped file descriptor). When changing to the name "..", O_NOFOLLOW can't help. In general, when the target is not "..", diropen's use of O_NOFOLLOW ensures we don't mistakenly follow a symlink, so we can avoid the expense of this fstat. */ if (ISSET(FTS_LOGICAL) || ! HAVE_WORKING_O_NOFOLLOW || (dir && STREQ (dir, ".."))) { struct stat sb; if (fstat(newfd, &sb)) { ret = -1; goto bail; } if (p->fts_statp->st_dev != sb.st_dev || p->fts_statp->st_ino != sb.st_ino) { __set_errno (ENOENT); /* disinformation */ ret = -1; goto bail; } } if (ISSET(FTS_CWDFD)) { cwd_advance_fd (sp, newfd, ! is_dotdot); return 0; } ret = fchdir(newfd); bail: if (fd < 0) { int oerrno = errno; (void)close(newfd); __set_errno (oerrno); } return ret; }
hpc/Parallel-coreutils
lib/fts.c
C
gpl-3.0
56,570
/* * COPYRIGHT (C) 2017-2021, zhllxt * * author : zhllxt * email : 37792738@qq.com * * Distributed under the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 * (See accompanying file LICENSE or see <http://www.gnu.org/licenses/>) */ /* Perfect capture in C++20 template <typename ... Args> auto f(Args&& args){ return [... args = std::forward<Args>(args)]{ // use args }; } C++17 and C++14 workaround In C++17 we can use a workaround with tuples: template <typename ... Args> auto f(Args&& ... args){ return [args = std::make_tuple(std::forward<Args>(args) ...)]()mutable{ return std::apply([](auto&& ... args){ // use args }, std::move(args)); }; } */ #ifndef __ASIO2_RPC_CALL_COMPONENT_HPP__ #define __ASIO2_RPC_CALL_COMPONENT_HPP__ #if defined(_MSC_VER) && (_MSC_VER >= 1200) #pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <cstdint> #include <memory> #include <chrono> #include <functional> #include <atomic> #include <string> #include <string_view> #include <queue> #include <any> #include <future> #include <tuple> #include <unordered_map> #include <type_traits> #include <map> #include <asio2/3rd/asio.hpp> #include <asio2/base/error.hpp> #include <asio2/base/detail/function_traits.hpp> #include <asio2/rpc/detail/rpc_serialization.hpp> #include <asio2/rpc/detail/rpc_protocol.hpp> #include <asio2/rpc/detail/rpc_invoker.hpp> namespace asio2::detail { template<class derived_t, class args_t = void> class rpc_call_cp { public: /** * @constructor */ rpc_call_cp(io_t&, rpc_serializer& sr, rpc_deserializer& dr) : sr_(sr), dr_(dr) { } /** * @destructor */ ~rpc_call_cp() = default; protected: template<class derive_t> struct sync_call_op { template<class return_t, class Rep, class Period, class ...Args> inline static return_t exec(derive_t& derive, error_code* ec_ptr, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args) { if (ec_ptr) { ec_ptr->clear(); } error_code ec; std::shared_ptr<typename rpc_result_t<return_t>::type> result = std::make_shared<typename rpc_result_t<return_t>::type>(); try { if (!derive.is_started()) asio::detail::throw_error(asio::error::not_connected); rpc_header::id_type id = derive.mkid(); rpc_request<Args...> req(id, std::move(name), std::forward<Args>(args)...); std::shared_ptr<std::promise<error_code>> promise = std::make_shared<std::promise<error_code>>(); std::future<error_code> future = promise->get_future(); auto ex = [&derive, result, id, pm = std::move(promise)] (error_code ec, std::string_view data) mutable { detail::ignore_unused(data); ASIO2_ASSERT(derive.io().strand().running_in_this_thread()); if (!ec) { try { derive.dr_ >> ec; if constexpr (!std::is_void_v<return_t>) { if (!ec) derive.dr_ >> (*result); } else { std::ignore = result; } } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } } set_last_error(ec); pm->set_value(ec); derive.reqs_.erase(id); }; derive.post([&derive, req = std::move(req), ex = std::move(ex)]() mutable { derive.reqs_.emplace(req.id(), std::move(ex)); derive.async_send((derive.sr_.reset() << req).str(), [&derive, id = req.id()]() mutable { if (get_last_error()) // send data failed with error { auto iter = derive.reqs_.find(id); if (iter != derive.reqs_.end()) { auto& ex = iter->second; ex(get_last_error(), std::string_view{}); } } }); }); // Whether we run on the strand if (!derive.io().strand().running_in_this_thread()) { std::future_status status = future.wait_for(timeout); if (status == std::future_status::ready) { ec = future.get(); } else { ec = asio::error::timed_out; derive.post([&derive, id]() mutable { derive.reqs_.erase(id); }); } } else { // If invoke synchronization rpc call function in communication thread, it will degenerates // into async_call and the return value is empty. derive.post([&derive, id]() mutable { derive.reqs_.erase(id); }); ec = asio::error::in_progress; } } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } set_last_error(ec); if (ec_ptr) { *ec_ptr = ec; } else { // [20210818] don't throw an error, you can use get_last_error() to check // is there any exception. //asio::detail::throw_error(ec); } if constexpr (!std::is_void_v<return_t>) { return std::move(*result); } else { std::ignore = true; } } }; template<class derive_t> struct async_call_op { template<class return_t, class Callback> inline static std::function<void(error_code, std::string_view)> make_callback(derive_t& derive, Callback&& cb) { return async_call_op<derive_t>::template make_callback_impl<return_t>( derive, std::forward<Callback>(cb)); } template<class Callback> inline static std::function<void(error_code, std::string_view)> make_callback(derive_t& derive, Callback&& cb) { using fun_traits_type = function_traits<std::remove_cv_t<std::remove_reference_t<Callback>>>; return async_call_op<derive_t>::template make_callback_argc<fun_traits_type::argc>( derive, std::forward<Callback>(cb)); } template<std::size_t Argc, class Callback> typename std::enable_if_t<Argc == 1, std::function<void(error_code, std::string_view)>> inline static make_callback_argc(derive_t& derive, Callback&& cb) { return async_call_op<derive_t>::template make_callback_impl<void>( derive, std::forward<Callback>(cb)); } template<std::size_t Argc, class Callback> typename std::enable_if_t<Argc == 2, std::function<void(error_code, std::string_view)>> inline static make_callback_argc(derive_t& derive, Callback&& cb) { using fun_traits_type = function_traits<std::remove_cv_t<std::remove_reference_t<Callback>>>; using return_type = typename fun_traits_type::template args<1>::type; static_assert(!std::is_same_v<return_type, void>); return async_call_op<derive_t>::template make_callback_impl<return_type>( derive, std::forward<Callback>(cb)); } template<class return_t, class Callback> typename std::enable_if_t<std::is_same_v<return_t, void>, std::function<void(error_code, std::string_view)>> inline static make_callback_impl(derive_t& derive, Callback&& cb) { return std::function<void(error_code, std::string_view)> { [&derive, cb = std::forward<Callback>(cb)](auto ec, std::string_view) mutable { try { if (!ec) derive.dr_ >> ec; } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } set_last_error(ec); cb(ec); } }; } template<class return_t, class Callback> typename std::enable_if_t<!std::is_same_v<return_t, void>, std::function<void(error_code, std::string_view)>> inline static make_callback_impl(derive_t& derive, Callback&& cb) { return std::function<void(error_code, std::string_view)> { [&derive, cb = std::forward<Callback>(cb)](auto ec, std::string_view data) mutable { detail::ignore_unused(data); typename rpc_result_t<return_t>::type result{}; try { if (!ec) derive.dr_ >> ec; if (!ec) derive.dr_ >> result; } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } set_last_error(ec); cb(ec, std::move(result)); } }; } template<class Req> inline static void exec(derive_t& derive, Req&& req) { ASIO2_ASSERT(!req.id()); error_code ec; try { if (!derive.is_started()) asio::detail::throw_error(asio::error::not_connected); derive.post([&derive, req = std::forward<Req>(req)]() mutable { derive.async_send((derive.sr_.reset() << req).str()); }); return; } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } set_last_error(ec); } template<class Callback, class Rep, class Period, class Req> inline static void exec(derive_t& derive, rpc_header::id_type id, std::chrono::duration<Rep, Period> timeout, Callback&& cb, Req&& req) { ASIO2_ASSERT(id); error_code ec; req.id(id); // 2020-12-03 Fix possible bug: move the "timer->async_wait" into the io_context thread. // otherwise the "derive.send" maybe has't called, the "timer->async_wait" has called // already. std::shared_ptr<asio::steady_timer> timer = std::make_shared<asio::steady_timer>(derive.io().context()); auto ex = [&derive, id, timer, cb = std::forward<Callback>(cb)] (error_code ec, std::string_view data) mutable { ASIO2_ASSERT(derive.io().strand().running_in_this_thread()); error_code ec_ignore{}; timer->cancel(ec_ignore); if (cb) { cb(ec, data); } derive.reqs_.erase(id); }; try { if (!derive.is_started()) asio::detail::throw_error(asio::error::not_connected); // 2019-11-28 fixed the bug of issue #6 : task() cannot be called directly // 2021-12-10 : can't save the request id in async_send's callback. // The following will occurs when using async_send with callback : // 1. call async_send with callback // 2. recv response by rpc_recv_op // 3. the callback was called // It means that : The callback function of async_send may be called after // recved response data. derive.post( [&derive, timer = std::move(timer), timeout, req = std::forward<Req>(req), ex = std::move(ex)] () mutable { // 1. first, save the request id derive.reqs_.emplace(req.id(), std::move(ex)); // 2. second, start the timeout timer. // note : cannot put "start timer" after "async_send", beacust the async_send // maybe failed immediately with the "derive.is_started() == false", then the // callback of async_send will be called immediately, and the "ex" will be called, // and the timer will be canceled, but at this time, the timer has't start yet, // when async_send is return, the timer will be begin "async_wait", but the timer // "cancel" is called already, so this will cause some small problem. // must start a timeout timer, othwise if not recved response, it will cause the // request id in the map forever. auto this_ptr = derive.selfptr(); timer->expires_after(timeout); timer->async_wait(asio::bind_executor(derive.io().strand(), [this_ptr = std::move(this_ptr), &derive, id = req.id()] (const error_code& ec) mutable { if (ec == asio::error::operation_aborted) return; auto iter = derive.reqs_.find(id); if (iter != derive.reqs_.end()) { auto& ex = iter->second; ex(asio::error::timed_out, std::string_view{}); } })); // 3. third, send request. derive.async_send((derive.sr_.reset() << req).str(), [&derive, id = req.id()]() mutable { if (get_last_error()) // send data failed with error { auto iter = derive.reqs_.find(id); if (iter != derive.reqs_.end()) { auto& ex = iter->second; ex(get_last_error(), std::string_view{}); } } }); }); return; } catch (cereal::exception& ) { ec = asio::error::no_data; } catch (system_error & e) { ec = e.code(); } catch (std::exception & ) { ec = asio::error::eof; } set_last_error(ec); // bug fixed : can't call ex(...) directly, it will // cause "reqs_.erase(id)" be called in multithread derive.post([ec, ex = std::move(ex)]() mutable { set_last_error(ec); ex(ec, std::string_view{}); }); } }; template<class derive_t> class sync_caller { template <class, class> friend class rpc_call_cp; protected: sync_caller(derive_t& d) : derive(d), id_(0), tm_(d.default_timeout()) {} sync_caller(sync_caller&& o) : derive(o.derive) , id_(std::move(o.id_)), tm_(std::move(o.tm_)), ec_(std::move(o.ec_)) {} sync_caller(const sync_caller&) = delete; sync_caller& operator=(sync_caller&&) = delete; sync_caller& operator=(const sync_caller&) = delete; public: ~sync_caller() = default; template<class Rep, class Period> inline sync_caller& timeout(std::chrono::duration<Rep, Period> timeout) { this->tm_ = std::move(timeout); return (*this); } inline sync_caller& errcode(error_code& ec) { this->ec_ = &ec; return (*this); } // If invoke synchronization rpc call function in communication thread, it will degenerates // into async_call and the return value is empty. template<class return_t, class ...Args> inline return_t call(std::string name, Args&&... args) { return sync_call_op<derive_t>::template exec<return_t>( derive, ec_, tm_, std::move(name), std::forward<Args>(args)...); } protected: derive_t& derive; rpc_header::id_type id_; asio::steady_timer::duration tm_; error_code* ec_ = nullptr; }; template<class derive_t> class async_caller { template <class, class> friend class rpc_call_cp; protected: async_caller(derive_t& d) : derive(d), id_(0), tm_(d.default_timeout()) {} async_caller(async_caller&& o) : derive(o.derive) , id_(std::move(o.id_)), tm_(std::move(o.tm_)) , cb_(std::move(o.cb_)), fn_(std::move(o.fn_)) {} async_caller(const async_caller&) = delete; async_caller& operator=(async_caller&&) = delete; async_caller& operator=(const async_caller&) = delete; using defer_fn = std::function<void(rpc_header::id_type, asio::steady_timer::duration, std::function<void(error_code, std::string_view)>)>; public: ~async_caller() { if (this->fn_) { (this->fn_)(std::move(this->id_), std::move(this->tm_), std::move(this->cb_)); } } template<class Rep, class Period> inline async_caller& timeout(std::chrono::duration<Rep, Period> timeout) { this->tm_ = timeout; return (*this); } template<class Callback> inline async_caller& response(Callback&& cb) { this->id_ = derive.mkid(); this->cb_ = async_call_op<derive_t>::template make_callback( derive, std::forward<Callback>(cb)); return (*this); } template<class ...Args> inline async_caller& async_call(std::string name, Args&&... args) { derive_t& deriv = derive; this->fn_ = [&deriv, req = rpc_request<Args...>{ std::move(name),std::forward<Args>(args)... }] (rpc_header::id_type id, asio::steady_timer::duration timeout, std::function<void(error_code, std::string_view)> cb) mutable { if (!id) { async_call_op<derive_t>::template exec(deriv, std::move(req)); } else { async_call_op<derive_t>::template exec(deriv, std::move(id), std::move(timeout), std::move(cb), std::move(req)); } }; return (*this); } protected: derive_t& derive; rpc_header::id_type id_; asio::steady_timer::duration tm_; std::function<void(error_code, std::string_view)> cb_; defer_fn fn_; }; template<class derive_t> class base_caller { template <class, class> friend class rpc_call_cp; protected: base_caller(derive_t& d) : derive(d), tm_(d.default_timeout()) {} base_caller(base_caller&& o) : derive(o.derive), tm_(std::move(o.tm_)), ec_(std::move(o.ec_)) {} base_caller& operator=(base_caller&&) = delete; base_caller(const base_caller&) = delete; base_caller& operator=(const base_caller&) = delete; public: ~base_caller() = default; template<class Rep, class Period> inline base_caller& timeout(std::chrono::duration<Rep, Period> timeout) { this->tm_ = std::move(timeout); return (*this); } inline sync_caller<derive_t> errcode(error_code& ec) { sync_caller<derive_t> caller{ derive }; caller.timeout(std::move(this->tm_)); caller.errcode(ec); return std::move(caller); } template<class Callback> inline async_caller<derive_t> response(Callback&& cb) { async_caller<derive_t> caller{ derive }; caller.timeout(std::move(this->tm_)); caller.response(std::forward<Callback>(cb)); return std::move(caller); } // If invoke synchronization rpc call function in communication thread, it will degenerates // into async_call and the return value is empty. template<class return_t, class ...Args> inline return_t call(std::string name, Args&&... args) { return sync_call_op<derive_t>::template exec<return_t>(derive, this->ec_, this->tm_, std::move(name), std::forward<Args>(args)...); } template<class ...Args> inline async_caller<derive_t> async_call(std::string name, Args&&... args) { async_caller<derive_t> caller{ derive }; caller.timeout(std::move(this->tm_)); caller.async_call(std::move(name), std::forward<Args>(args)...); return std::move(caller); } protected: derive_t& derive; asio::steady_timer::duration tm_; error_code* ec_ = nullptr; }; public: /** * @function : call a rpc function * If invoke synchronization rpc call function in communication thread, it will degenerates * into async_call and the return value is empty. */ template<class return_t, class Rep, class Period, class ...Args> inline return_t call(std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); return sync_call_op<derived_t>::template exec<return_t>(derive, nullptr, timeout, std::move(name), std::forward<Args>(args)...); } /** * @function : call a rpc function * If invoke synchronization rpc call function in communication thread, it will degenerates * into async_call and the return value is empty. */ template<class return_t, class Rep, class Period, class ...Args> inline return_t call(error_code& ec, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); return sync_call_op<derived_t>::template exec<return_t>(derive, &ec, timeout, std::move(name), std::forward<Args>(args)...); } /** * @function : call a rpc function * If invoke synchronization rpc call function in communication thread, it will degenerates * into async_call and the return value is empty. */ template<class return_t, class ...Args> inline return_t call(std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); return sync_call_op<derived_t>::template exec<return_t>(derive, nullptr, derive.default_timeout(), std::move(name), std::forward<Args>(args)...); } /** * @function : call a rpc function * If invoke synchronization rpc call function in communication thread, it will degenerates * into async_call and the return value is empty. */ template<class return_t, class ...Args> inline return_t call(error_code& ec, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); return sync_call_op<derived_t>::template exec<return_t>(derive, &ec, derive.default_timeout(), std::move(name), std::forward<Args>(args)...); } /** * @function : asynchronous call a rpc function * Callback signature : void(asio::error_code ec, int result) * if result type is void, the Callback signature is : void(asio::error_code ec) * Because the result value type is not specified in the first template parameter, * so the result value type must be specified in the Callback lambda. */ template<class Callback, class ...Args> inline typename std::enable_if_t<is_callable_v<Callback>, void> async_call(Callback&& cb, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); async_call_op<derived_t>::template exec(derive, derive.mkid(), derive.default_timeout(), async_call_op<derived_t>::template make_callback(derive, std::forward<Callback>(cb)), rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... }); } /** * @function : asynchronous call a rpc function * Callback signature : void(asio::error_code ec, int result) * if result type is void, the Callback signature is : void(asio::error_code ec) * Because the result value type is not specified in the first template parameter, * so the result value type must be specified in the Callback lambda */ template<class Callback, class Rep, class Period, class ...Args> inline typename std::enable_if_t<is_callable_v<Callback>, void> async_call(Callback&& cb, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); async_call_op<derived_t>::template exec(derive, derive.mkid(), timeout, async_call_op<derived_t>::template make_callback(derive, std::forward<Callback>(cb)), rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... }); } /** * @function : asynchronous call a rpc function * Callback signature : void(asio::error_code ec, return_t result) the return_t * is the first template parameter. * if result type is void, the Callback signature is : void(asio::error_code ec) */ template<class return_t, class Callback, class ...Args> inline typename std::enable_if_t<is_template_callable_v<Callback, error_code, return_t>, void> async_call(Callback&& cb, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); async_call_op<derived_t>::template exec(derive, derive.mkid(), derive.default_timeout(), async_call_op<derived_t>::template make_callback<return_t>( derive, std::forward<Callback>(cb)), rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... }); } /** * @function : asynchronous call a rpc function * Callback signature : void(asio::error_code ec, return_t result) the return_t * is the first template parameter. * if result type is void, the Callback signature is : void(asio::error_code ec) */ template<class return_t, class Callback, class Rep, class Period, class ...Args> inline typename std::enable_if_t<is_template_callable_v<Callback, error_code, return_t>, void> async_call(Callback&& cb, std::chrono::duration<Rep, Period> timeout, std::string name, Args&&... args) { derived_t& derive = static_cast<derived_t&>(*this); async_call_op<derived_t>::template exec(derive, derive.mkid(), timeout, async_call_op<derived_t>::template make_callback<return_t>( derive, std::forward<Callback>(cb)), rpc_request<Args...>{ std::move(name), std::forward<Args>(args)... }); } /** * @function : asynchronous call a rpc function */ template<class ...Args> inline async_caller<derived_t> async_call(std::string name, Args&&... args) { async_caller<derived_t> caller{ static_cast<derived_t&>(*this) }; caller.async_call(std::move(name), std::forward<Args>(args)...); return std::move(caller); } template<class Rep, class Period> inline base_caller<derived_t> timeout(std::chrono::duration<Rep, Period> timeout) { base_caller<derived_t> caller{ static_cast<derived_t&>(*this) }; caller.timeout(timeout); return std::move(caller); } inline sync_caller<derived_t> errcode(error_code& ec) { sync_caller<derived_t> caller{ static_cast<derived_t&>(*this) }; caller.errcode(ec); return std::move(caller); } template<class Callback> inline async_caller<derived_t> response(Callback&& cb) { async_caller<derived_t> caller{ static_cast<derived_t&>(*this) }; caller.response(std::forward<Callback>(cb)); return std::move(caller); } protected: rpc_serializer & sr_; rpc_deserializer & dr_; std::map<rpc_header::id_type, std::function<void(error_code, std::string_view)>> reqs_; }; } #endif // !__ASIO2_RPC_CALL_COMPONENT_HPP__
zhllxt/asio2
asio2/rpc/component/rpc_call_cp.hpp
C++
gpl-3.0
25,540
/* Winegame - small utility to prepare Wine and install win32 apps in it. Copyright (C) 2010 Pavel Zinin <pzinin@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/>. */ #include "about.h" #include "ui_about.h" About::About(QWidget *parent) : QDialog(parent), ui(new Ui::About) { ui->setupUi(this); } About::~About() { delete ui; } void About::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void About::on_label_linkActivated(QString link) { //open url QDesktopServices::openUrl(QUrl(link)); } void About::on_textBrowser_2_anchorClicked(QUrl url) { QDesktopServices::openUrl(url); }
pashazz/winegame
src/about.cpp
C++
gpl-3.0
1,378
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AIbehaviorComparisonExpressionDefinition : AIbehaviorPassiveExpressionDefinition { [Ordinal(0)] [RED("leftHandSide")] public CHandle<AIbehaviorExpressionSocket> LeftHandSide { get; set; } [Ordinal(1)] [RED("operator")] public CEnum<EComparisonType> Operator { get; set; } [Ordinal(2)] [RED("rightHandSide")] public CHandle<AIbehaviorExpressionSocket> RightHandSide { get; set; } public AIbehaviorComparisonExpressionDefinition(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/AIbehaviorComparisonExpressionDefinition.cs
C#
gpl-3.0
655
/* * Copyright (C) 2017 i.leontyev81@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/>. */ package atc.gui.admin.zk.viewmodel; import java.util.List; import org.zkoss.bind.annotation.Init; import org.zkoss.zk.ui.select.annotation.VariableResolver; import org.zkoss.zk.ui.select.annotation.WireVariable; import atc.gui.admin.zk.transition.PathPart; import atc.gui.admin.zk.transition.impl.EditPathPart; import atc.gui.admin.domain.model.UserEntry; import atc.gui.admin.domain.service.repository.UserRepository; import atc.gui.admin.zk.viewmodel.base.BaseEntitiesVM; import atc.gui.admin.zk.viewmodel.export.DataSource; import atc.gui.admin.zk.viewmodel.export.DataSourceFactory; @VariableResolver(org.zkoss.spring.DelegatingVariableResolver.class) @Init(superclass=true) public class UsersVM extends BaseEntitiesVM<UserEntry> implements DataSourceFactory<UserEntry> { private UserRepository repository; @WireVariable("userRepository") public void setUserRepository(UserRepository repository) { this.repository = repository; } @Override protected PathPart getEditPathPart(UserEntry entity) { return new EditPathPart("user", entity.getId()); } @Override protected void remove(UserEntry entity) { repository.removeUser(entity.getId()); } @Override protected void initDataList(List<UserEntry> dataList) { dataList.addAll(repository.getUserList()); } @Override public DataSource<UserEntry> createDataSource() { return new DataSource<UserEntry>(repository.getUserList()); } @Override public Class<UserEntry> getType() { return getEntityClass(); } }
ileontyev81/admin_atc_zk
src/main/java/atc/gui/admin/zk/viewmodel/UsersVM.java
Java
gpl-3.0
2,201
// staff-global.js if ( KOHA === undefined ) var KOHA = {}; function _(s) { return s; } // dummy function for gettext // http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery/5341855#5341855 String.prototype.format = function() { return formatstr(this, arguments) } function formatstr(str, col) { col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1); var idx = 0; return str.replace(/%%|%s|%(\d+)\$s/g, function (m, n) { if (m == "%%") { return "%"; } if (m == "%s") { return col[idx++]; } return col[n]; }); }; // http://stackoverflow.com/questions/14859281/select-tab-by-name-in-jquery-ui-1-10-0/16550804#16550804 $.fn.tabIndex = function () { return $(this).parent().children('div').index(this); }; $.fn.selectTabByID = function (tabID) { $(this).tabs("option", "active", $(tabID).tabIndex()); }; $(document).ready(function() { $('#header_search').tabs().on( "tabsactivate", function(e, ui) { $(this).find("div:visible").find('input').eq(0).focus(); }); $(".close").click(function(){ window.close(); }); if($("#header_search #checkin_search").length > 0){ shortcut.add('Alt+r',function (){ $("#header_search").selectTabByID("#checkin_search"); $("#ret_barcode").focus(); }); } else { shortcut.add('Alt+r',function (){ location.href="/cgi-bin/koha/circ/returns.pl"; }); } if($("#header_search #circ_search").length > 0){ shortcut.add('Alt+u',function (){ $("#header_search").selectTabByID("#circ_search"); $("#findborrower").focus(); }); } else { shortcut.add('Alt+u',function(){ location.href="/cgi-bin/koha/circ/circulation.pl"; }); } if($("#header_search #catalog_search").length > 0){ shortcut.add('Alt+q',function (){ $("#header_search").selectTabByID("#catalog_search"); $("#search-form").focus(); }); } else { shortcut.add('Alt+q',function(){ location.href="/cgi-bin/koha/catalogue/search.pl"; }); } $(".focus").focus(); $(".validated").each(function() { $(this).validate(); }); $("#logout").on("click",function(){ logOut(); }); $("#helper").on("click",function(){ openHelp(); return false; }); $("body").on("keypress", ".noEnterSubmit", function(e){ return checkEnter(e); }); }); // http://jennifermadden.com/javascript/stringEnterKeyDetector.html function checkEnter(e){ //e is event object passed from function invocation var characterCode; // literal character code will be stored in this variable if(e && e.which){ //if which property of event object is supported (NN4) characterCode = e.which; //character code is contained in NN4's which property } else { characterCode = e.keyCode; //character code is contained in IE's keyCode property } if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key) return false; } else { return true; } } function clearHoldFor(){ $.removeCookie("holdfor", { path: '/' }); } function logOut(){ if( typeof delBasket == 'function' ){ delBasket('main', true); } clearHoldFor(); } function openHelp(){ openWindow("/cgi-bin/koha/help.pl","KohaHelp",600,600); } jQuery.fn.preventDoubleFormSubmit = function() { jQuery(this).submit(function() { $("body, form input[type='submit'], form button[type='submit'], form a").addClass('waiting'); if (this.beenSubmitted) return false; else this.beenSubmitted = true; }); }; function openWindow(link,name,width,height) { name = (typeof name == "undefined")?'popup':name; width = (typeof width == "undefined")?'600':width; height = (typeof height == "undefined")?'400':height; //IE <= 9 can't handle a "name" with whitespace try { var newin=window.open(link,name,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top'); } catch(e) { var newin=window.open(link,null,'width='+width+',height='+height+',resizable=yes,toolbar=false,scrollbars=yes,top'); } } // Use this function to remove the focus from any element for // repeated scanning actions on errors so the librarian doesn't // continue scanning and miss the error. function removeFocus() { $(':focus').blur(); } function toUC(f) { var x=f.value.toUpperCase(); f.value=x; return true; } function confirmDelete(message) { return (confirm(message) ? true : false); } function playSound( sound ) { if ( ! ( sound.indexOf('http://') == 0 || sound.indexOf('https://') == 0 ) ) { sound = AUDIO_ALERT_PATH + sound; } document.getElementById("audio-alert").innerHTML = '<audio src="' + sound + '" autoplay="autoplay" autobuffer="autobuffer"></audio>'; }
misilot/Koha
koha-tmpl/intranet-tmpl/prog/en/js/staff-global.js
JavaScript
gpl-3.0
4,787
''' command_line.py Utility functions for reading command line arguments. Author: Martin Norbury Novemeber 2013 ''' import inspect import argparse def command_line(fn): ''' A decorator for functions intented to be run from the command line. This decorator introspects the method signature of the wrapped function to configures and parses command line arguments. Positional arguments translate to required command line arguments. Arguments with defaults supplied are assumed to be optional e.g. def myfunction(a,b=1): ... Can be called from the command line as:- > myfunction <a> [--b=value] All arguments are assumed to be strings at this point. ''' def wrapper_fn(*args, **kwargs): # Get the original function's method signature arguments, varargs, kwargs, defaults = inspect.getargspec(fn) # Get required and optional arguments required_length = -len(defaults) if defaults else len(arguments) required_arguments = arguments[:required_length] optional_arguments = arguments[required_length:] # Create a list of optional arguments of the form (name, value) optional_arguments_with_defaults = [] if optional_arguments: optional_arguments_with_defaults = zip(optional_arguments, defaults) # Create a command line parser parser = argparse.ArgumentParser() # Configure required arguments for argument in required_arguments: parser.add_argument('{0}'.format(argument)) # Configure optional arguments, setting defaults appropriately. for argument, default in optional_arguments_with_defaults: parser.add_argument('--{0}'.format(argument), type=type(default), default=default) # Parse the command line arguments args = parser.parse_args() # Call the original function with command line supplied arguments result = fn(**dict(args._get_kwargs())) return result return wrapper_fn
mnorbury/scriptutil
src/scriptutil/command_line.py
Python
gpl-3.0
2,055
// Copyright (c) The University of Dundee 2018-2019 // This file is part of the Research Data Management Platform (RDMP). // RDMP 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. // RDMP 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 RDMP. If not, see <https://www.gnu.org/licenses/>. namespace Rdmp.Core.CommandExecution { /// <summary> /// Describes an executable command that is available to the user (or assembled and executed in code). ICommandExecution instances are allowed to be in /// illegal states (IsImpossible = true) and this should be respected by Execute i.e. it will throw an exception if Executed. /// </summary> public interface ICommandExecution { /// <summary> /// True if the command's current state means that it cannot be succesfully executed. This should ideally be set in the constructor logic /// but must be set before <see cref="Execute"/> is called. /// /// <para>If determining a given error state is expensive and therefore not desireable to do in the constructor you should just determine /// it in <see cref="Execute"/> and throw at that point</para> /// </summary> bool IsImpossible { get; } /// <summary> /// The reason <see cref="IsImpossible"/> is true. Should be null if <see cref="IsImpossible"/> is false /// </summary> string ReasonCommandImpossible { get; } /// <summary> /// Runs the command, this should normally only be called once then the command discarded. Always ensure when overriding that you call base members /// because they can include logic such as <see cref="IsImpossible"/> etc. /// </summary> void Execute(); /// <summary> /// The user friendly name for the command, this is what is rendered in UIs/menus etc if the command is being shown in one /// </summary> /// <returns></returns> string GetCommandName(); /// <summary> /// User understandable description of what the command does in it's current state. This can change depending on constructor arguments etc. /// </summary> /// <returns></returns> string GetCommandHelp(); } }
HicServices/RDMP
Rdmp.Core/CommandExecution/ICommandExecution.cs
C#
gpl-3.0
2,687
package com.abstractedsheep.shuttletracker; public class FavoriteStop { public final String stopId; public final int routeId; public FavoriteStop(int routeId, String stopId) { this.routeId = routeId; this.stopId = stopId; } public String getUniqueId() { return stopId + String.valueOf(routeId); } @Override public boolean equals(Object o) { if (o == null) return false; try { FavoriteStop s = (FavoriteStop) o; return this.stopId.equals(s.stopId) && this.routeId == s.routeId; } catch (ClassCastException e) { return false; } } @Override public int hashCode() { return stopId.hashCode() ^ routeId; } }
AbstractedSheep/Shuttle-Tracker
android/shuttle-tracker-android/src/com/abstractedsheep/shuttletracker/FavoriteStop.java
Java
gpl-3.0
701
/** * Copyright Intermesh * * This file is part of Group-Office. You should have received a copy of the * Group-Office license along with Group-Office. See the file /LICENSE.TXT * * If you have questions write an e-mail to info@intermesh.nl * * @version $Id: EventPanel.js 22112 2018-01-12 07:59:41Z mschering $ * @copyright Copyright Intermesh * @author Merijn Schering <mschering@intermesh.nl> */ GO.calendar.EventPanel = Ext.extend(GO.DisplayPanel,{ model_name : "GO\\Calendar\\Model\\Event", stateId : 'cal-event-panel', editGoDialogId : 'event', editHandler : function(){ GO.calendar.showEventDialog({event_id: this.link_id}); }, updateToolbar : function(){ GO.calendar.EventPanel.superclass.updateToolbar.call(this); this.editButton.setDisabled(!this.data.is_organizer); }, initComponent : function(){ this.loadUrl=('calendar/event/display'); this.template = '<table class="display-panel" cellpadding="0" cellspacing="0" border="0">'+ // '<tr>'+ // '<td colspan="2" class="display-panel-heading">'+t("Event", "calendar")+': {name}</td>'+ // '</tr>'+ // '<tr>'+ // '<td colspan="2"><table><tr><td>'+t("Calendar", "calendar")+': </td><td>{calendar_name}</td></tr></table></td>'+ // '</tr>'+ '<tr>'+ '<td colspan="2">{event_html}</td>'+ '</tr>'+ '</table>'; this.template +=GO.customfields.displayPanelTemplate; if(go.Modules.isAvailable("legacy", "workflow")){ this.template +=GO.workflow.WorkflowTemplate; } GO.calendar.EventPanel.superclass.initComponent.call(this); } });
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.3/modules/calendar/EventPanel.js
JavaScript
gpl-3.0
1,612
#!/usr/bin/perl # # Make a crude tally of main courses in a specified meal. # # [created. -- rgr, 14-Dec-19.] # use strict; use warnings; use Getopt::Long; use lib '.'; use Food::Meal; my $recipe_file_name = 'recipes.text'; my $meal_name = 'dinner'; GetOptions('meal=s' => \$meal_name, 'recipe-file=s' => \$recipe_file_name); # Read the item/recipe database. Food::Item->parse_recipes($recipe_file_name); # Read the meal files. my $n_meals = 0; my %tally_from_name; for my $file (@ARGV) { # Find meals. my $meals = Food::Meal->parse_meals($file); for my $meal (@$meals) { next unless $meal->meal eq $meal_name; # Find the "main course." This will be a recipe over an ingredient, # and the one with the greater number of calories if there is more than # one of a kind. my $ingredients = $meal->ingredients; my $main_course = $ingredients->[0]; for my $ingredient (@{$meal->ingredients}) { $main_course = $ingredient if $ingredient->better_main_course_p($main_course); } my $item = $main_course->item; # print $meal->date, ": $item => ", $item->name, "\n"; $tally_from_name{$item->name}++; $n_meals++; } } for my $name (sort(keys(%tally_from_name))) { printf("%7d\t%s\n", $tally_from_name{$name}, $name); }
rgrjr/meals
tally-meals.pl
Perl
gpl-3.0
1,265
#include <QDebug> #include <QPointer> #include <QtPlugin> #include <QIcon> #include <QApplication> #include <QWidget> #include <ExtensionSystemConstants> #include "PraalineCore/Corpus/Corpus.h" #include "PraalineCore/Datastore/CorpusRepository.h" #include "PraalineCore/Datastore/AnnotationDatastore.h" #include "AnalyserDisfluencies.h" #include "StatisticsPluginDisfluencies.h" #include "AnalyserDisfluenciesWidget.h" using namespace Qtilities::ExtensionSystem; using namespace Praaline::Plugins; namespace Praaline { namespace Plugins { namespace StatisticsPluginDisfluencies { struct StatisticsPluginDisfluenciesData { StatisticsPluginDisfluenciesData() : analyser(0) {} AnalyserDisfluencies *analyser; }; StatisticsPluginDisfluencies::StatisticsPluginDisfluencies(QObject* parent) : QObject(parent), d(new StatisticsPluginDisfluenciesData) { setObjectName(pluginName()); d->analyser = new AnalyserDisfluencies(this); } StatisticsPluginDisfluencies::~StatisticsPluginDisfluencies() { delete d; } bool StatisticsPluginDisfluencies::initialize(const QStringList &arguments, QStringList *error_strings) { Q_UNUSED(arguments) Q_UNUSED(error_strings) return true; } bool StatisticsPluginDisfluencies::initializeDependencies(QStringList *error_strings) { Q_UNUSED(error_strings) return true; } void StatisticsPluginDisfluencies::finalize() { } QString StatisticsPluginDisfluencies::pluginName() const { return "Fluency Profile"; } QtilitiesCategory StatisticsPluginDisfluencies::pluginCategory() const { return QtilitiesCategory("Statistical Analysis"); } Qtilities::Core::VersionInformation StatisticsPluginDisfluencies::pluginVersionInformation() const { VersionInformation version_info(1, 0, 0); return version_info; } QString StatisticsPluginDisfluencies::pluginPublisher() const { return "George Christodoulides"; } QString StatisticsPluginDisfluencies::pluginPublisherWebsite() const { return "http://www.praaline.org"; } QString StatisticsPluginDisfluencies::pluginPublisherContact() const { return "info@praaline.org"; } QString StatisticsPluginDisfluencies::pluginDescription() const { return tr("Statistical analysis of Disfluencies speech measures."); } QString StatisticsPluginDisfluencies::pluginCopyright() const { return QString(tr("Copyright") + " 2016-2017, George Christodoulides"); } QString StatisticsPluginDisfluencies::pluginLicense() const { return tr("GPL v.3"); } QStringList StatisticsPluginDisfluencies::analyserIDs() { QStringList analyserIDs; analyserIDs << "MeasuresTable"; return analyserIDs; } QString StatisticsPluginDisfluencies::analyserName(const QString &analyserID) { if (analyserID == "MeasuresTable") return "Disfluency Measures"; return QString(); } QWidget *StatisticsPluginDisfluencies::analyser(const QString &analyserID, CorpusRepository *repository, QWidget *parent) { if (analyserID == "MeasuresTable") return new AnalyserDisfluenciesWidget(repository, d->analyser, parent); return new QWidget(parent); } } // namespace StatisticsPluginDisfluencies } // namespace Plugins } // namespace Praaline
praaline/Praaline
app/statistics/disfluencies/StatisticsPluginDisfluencies.cpp
C++
gpl-3.0
3,190
/* Minetest Copyright (C) 2013 sapier, <sapier AT gmx DOT net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef CPP_API_ASYNC_EVENTS_HEADER #define CPP_API_ASYNC_EVENTS_HEADER #include <vector> #include <deque> #include <map> #include "threading/thread.h" #include "threading/mutex.h" #include "threading/semaphore.h" #include "debug.h" #include "lua.h" #include "cpp_api/s_base.h" // Forward declarations class AsyncEngine; // Declarations // Data required to queue a job struct LuaJobInfo { // Function to be called in async environment std::string serializedFunction; // Parameter to be passed to function std::string serializedParams; // Result of function call std::string serializedResult; // JobID used to identify a job and match it to callback unsigned int id; bool valid; }; // Asynchronous working environment class AsyncWorkerThread : public Thread, public ScriptApiBase { public: AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name); virtual ~AsyncWorkerThread(); void *run(); private: AsyncEngine *jobDispatcher; }; // Asynchornous thread and job management class AsyncEngine { friend class AsyncWorkerThread; public: AsyncEngine(); ~AsyncEngine(); /** * Register function to be used within engine * @param name Function name to be used within Lua environment * @param func C function to be called */ bool registerFunction(const char* name, lua_CFunction func); /** * Create async engine tasks and lock function registration * @param numEngines Number of async threads to be started */ void initialize(unsigned int numEngines); /** * Queue an async job * @param func Serialized lua function * @param params Serialized parameters * @return jobid The job is queued */ unsigned int queueAsyncJob(std::string func, std::string params); /** * Engine step to process finished jobs * the engine step is one way to pass events back, PushFinishedJobs another * @param L The Lua stack */ void step(lua_State *L); /** * Push a list of finished jobs onto the stack * @param L The Lua stack */ void pushFinishedJobs(lua_State *L); protected: /** * Get a Job from queue to be processed * this function blocks until a job is ready * @return a job to be processed */ LuaJobInfo getJob(); /** * Put a Job result back to result queue * @param result result of completed job */ void putJobResult(LuaJobInfo result); /** * Initialize environment with current registred functions * this function adds all functions registred by registerFunction to the * passed lua stack * @param L Lua stack to initialize * @param top Stack position */ void prepareEnvironment(lua_State* L, int top); private: // Variable locking the engine against further modification bool initDone; // Internal store for registred functions UNORDERED_MAP<std::string, lua_CFunction> functionList; // Internal counter to create job IDs unsigned int jobIdCounter; // Mutex to protect job queue Mutex jobQueueMutex; // Job queue std::deque<LuaJobInfo> jobQueue; // Mutex to protect result queue Mutex resultQueueMutex; // Result queue std::deque<LuaJobInfo> resultQueue; // List of current worker threads std::vector<AsyncWorkerThread*> workerThreads; // Counter semaphore for job dispatching Semaphore jobQueueCounter; }; #endif // CPP_API_ASYNC_EVENTS_HEADER
dicebox/minetest-france
minetest/src/script/cpp_api/s_async.h
C
gpl-3.0
4,053
<!DOCTYPE html> <html> <head> <title>Financial Table Widget</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8" /> <link rel="stylesheet" href="css/widget.min.css"/> </head> <body> <div id="container"> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.11.7/TweenLite.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.11.7/plugins/CSSPlugin.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.11.7/utils/Draggable.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/gsap/1.11.7/plugins/ScrollToPlugin.min.js"></script> <script src="//s3.amazonaws.com/rise-common/scripts/greensock/ThrowPropsPlugin.min.js"></script> <script src="//datejs.googlecode.com/svn/trunk/build/date.js"></script> <!-- build:e2emockData --> <!-- build:e2egadgets --> <script src="//rvashow2.appspot.com/gadgets/gadgets.min.js"></script> <script src="js/widget.min.js"></script> <!-- build:e2eVisualization --> <script type="text/javascript" src="//www.google.com/jsapi"></script> </body> </html>
Rise-Vision/widget-financial-table
dist/widget.html
HTML
gpl-3.0
1,221
/*! \brief The view controller for the crossword entry table. */ #pragma once #include <QModelIndex> #include <QTableView> namespace ui { class CrosswordEntryTableViewController : public QTableView { Q_OBJECT public: explicit CrosswordEntryTableViewController(QWidget* parent = 0); void sortEntriesByIdentifierAscending(); void sortByAlphabeticalOrderOfClue(); public slots: void conflictingWordError(); void reportGuessAccepted(QString guess); void reportGuessAmended(QString removedLetters); void reportGuessErased(); void reportGuessAmendationRejected(); signals: void guessSubmitted(QString guess, QModelIndex index); void guessAmendationRequested(QString guess, QModelIndex index); void guessErasureRequested(QModelIndex index); void modelIndexChanged(const QModelIndex& selected, const QModelIndex& deselected); protected: void keyPressEvent(QKeyEvent* event); void currentChanged(const QModelIndex& current, const QModelIndex& previous); int sizeHintForColumn(int column) const; void keyboardSearch(const QString& search); private: bool enterGuess(); bool amendGuess(); bool eraseGuess(); bool validateInput(QString guess, unsigned int requiredLength); void readCurrentIdentifier(); void readCurrentEntryNumber(); void readCurrentGuess(); void readCurrentClue(); void readWordLengths(); void sortEntries(); }; }
Tw1ddle/Blind-Crossword-3D
sources/ui/crosswordentrytableviewcontroller.h
C
gpl-3.0
1,450
from django.http import HttpResponseRedirect, JsonResponse from django.views.generic import CreateView, UpdateView from django.contrib.messages.views import SuccessMessageMixin from .models import HistoriaClinica, Patologia from .forms import HistoriaClinicaForms from apps.afiliados.models import Titular, Adherente from apps.personas.models import Persona class HistoriaClinicaCreate(SuccessMessageMixin, CreateView): model = HistoriaClinica form_class = HistoriaClinicaForms template_name = 'historias_clinicas/historia_clinica_form.html' success_url = '/historia/clinica/alta/' success_message = 'La historia clínica se guardo con exito' def form_valid(self, form): form.instance.persona = Persona.objects.get(pk=self.kwargs['pk']) self.success_url = '/historia/clinica/redireccion/%s' % str(Persona.objects.get(pk=self.kwargs['pk']).id) return super(HistoriaClinicaCreate, self).form_valid(form) def get_context_data(self, **kwargs): context = super(HistoriaClinicaCreate, self).get_context_data(**kwargs) context['persona'] = Persona.objects.get(pk=self.kwargs['pk']) return context def redireccion(request, id): titular = Titular.objects.filter(id=id) if titular.exists(): persona = Persona.objects.filter(titular=titular) historia_clinica = HistoriaClinica.objects.filter(persona=persona) if historia_clinica.exists(): return HttpResponseRedirect('/historia/clinica/modi/' + str(historia_clinica[0].id)) else: return HttpResponseRedirect('/historia/clinica/alta/' + str(persona[0].id)) else: adherente = Adherente.objects.filter(id=id) if adherente.exists(): persona = Persona.objects.filter(adherente=adherente) historia_clinica = HistoriaClinica.objects.filter(persona=persona) if historia_clinica.exists(): return HttpResponseRedirect('/historia/clinica/modi/' + str(historia_clinica[0].id)) else: return HttpResponseRedirect('/historia/clinica/alta/' + str(persona[0].id)) class HistoriaClinicaUpdate(SuccessMessageMixin, UpdateView): model = HistoriaClinica form_class = HistoriaClinicaForms template_name = 'historias_clinicas/historia_clinica_form.html' success_url = '/historia/clinica/alta/' success_message = 'La historia clínica se guardo con exito' def form_valid(self, form): form.instance.persona = Persona.objects.get(pk=HistoriaClinica.objects.get(pk=self.kwargs['pk']).persona.id) self.success_url = '/historia/clinica/redireccion/%s' % str(HistoriaClinica.objects.get( pk=self.kwargs['pk']).persona.id) return super(HistoriaClinicaUpdate, self).form_valid(form) def get_context_data(self, **kwargs): context = super(HistoriaClinicaUpdate, self).get_context_data(**kwargs) context['persona'] = Persona.objects.get(pk=HistoriaClinica.objects.get(pk=self.kwargs['pk']).persona.id) return context # Ajax ###### def patologia_create_ajax(request): if request.method == 'POST': if request.is_ajax(): id = '' patologia = Patologia(nombre_enfermedad=request.POST.get('id_nombre_enfermedad_patologia_ajax'), fecha_deteccion=request.POST.get('id_fecha_deteccion_patologia_ajax')) patologia.save() patologia = Patologia.objects.filter( nombre_enfermedad=request.POST.get('id_nombre_enfermedad_patologia_ajax'), fecha_deteccion=request.POST.get('id_fecha_deteccion_patologia_ajax')) for indice in patologia.values('id'): for valor in indice: id = indice[valor] for indice in patologia.values('nombre_enfermedad'): for valor in indice: nombre_enfermedad = indice[valor] return JsonResponse({'id': id, 'nombre_enfermedad': nombre_enfermedad})
montenegroariel/sigos
apps/historias_clinicas/views.py
Python
gpl-3.0
4,039
/* File: expreval.c Auth: Brian Allen Vanderburg II Date: Wednesday, April 30, 2003 Desc: Evaluation routines for the ExprEval library This file is part of ExprEval. */ /* Includes */ #include "exprincl.h" #include "exprpriv.h" /* Defines for error checking */ #include <errno.h> #if (EXPR_ERROR_LEVEL >= EXPR_ERROR_LEVEL_CHECK) #define EXPR_RESET_ERR() errno = 0 #define EXPR_CHECK_ERR() if (errno) return EXPR_ERROR_OUTOFRANGE #else #define EXPR_RESET_ERR() #define EXPR_CHECK_ERR() #endif /* This routine will evaluate an expression */ int exprEval(exprObj * obj, EXPRTYPE * val) { EXPRTYPE dummy; if (val == NULL) val = &dummy; /* Make sure it was parsed successfully */ if (!obj->parsedbad && obj->parsedgood && obj->headnode) { /* Do NOT reset the break count. Let is accumulate between calls until breaker function is called */ return exprEvalNode(obj, obj->headnode, 0, val); } else return EXPR_ERROR_BADEXPR; } /* Evaluate a node */ int exprEvalNode(exprObj * obj, exprNode * nodes, int curnode, EXPRTYPE * val) { int err; int pos; EXPRTYPE d1, d2; if (obj == NULL || nodes == NULL) return EXPR_ERROR_NULLPOINTER; /* Update n to point to correct node */ nodes += curnode; /* Check breaker count */ if (obj->breakcur-- <= 0) { /* Reset count before returning */ obj->breakcur = obj->breakcount; if (exprGetBreakResult(obj)) { return EXPR_ERROR_BREAK; } } switch (nodes->type) { case EXPR_NODETYPE_MULTI: { /* Multi for multiple expressions in one string */ for (pos = 0; pos < nodes->data.oper.nodecount; pos++) { err = exprEvalNode(obj, nodes->data.oper.nodes, pos, val); if (err) return err; } break; } case EXPR_NODETYPE_ADD: { /* Addition */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) err = exprEvalNode(obj, nodes->data.oper.nodes, 1, &d2); if (!err) *val = d1 + d2; else return err; break; } case EXPR_NODETYPE_SUBTRACT: { /* Subtraction */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) err = exprEvalNode(obj, nodes->data.oper.nodes, 1, &d2); if (!err) *val = d1 - d2; else return err; break; } case EXPR_NODETYPE_MULTIPLY: { /* Multiplication */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) err = exprEvalNode(obj, nodes->data.oper.nodes, 1, &d2); if (!err) *val = d1 * d2; else return err; break; } case EXPR_NODETYPE_DIVIDE: { /* Division */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) err = exprEvalNode(obj, nodes->data.oper.nodes, 1, &d2); if (!err) { if (d2 != 0.0) *val = d1 / d2; else { #if (EXPR_ERROR_LEVEL >= EXPR_ERROR_LEVEL_CHECK) return EXPR_ERROR_DIVBYZERO; #else *val = 0.0; return EXPR_ERROR_NOERROR; #endif } } else return err; break; } case EXPR_NODETYPE_EXPONENT: { /* Exponent */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) err = exprEvalNode(obj, nodes->data.oper.nodes, 1, &d2); if (!err) { EXPR_RESET_ERR(); *val = pow(d1, d2); EXPR_CHECK_ERR(); } else return err; break; } case EXPR_NODETYPE_NEGATE: { /* Negative value */ err = exprEvalNode(obj, nodes->data.oper.nodes, 0, &d1); if (!err) *val = -d1; else return err; break; } case EXPR_NODETYPE_VALUE: { /* Directly access the value */ *val = nodes->data.value.value; break; } case EXPR_NODETYPE_VARIABLE: { /* Directly access the variable or constant */ *val = *(nodes->data.variable.vaddr); break; } case EXPR_NODETYPE_ASSIGN: { /* Evaluate assignment subnode */ err = exprEvalNode(obj, nodes->data.assign.node, 0, val); if (!err) { /* Directly assign the variable */ *(nodes->data.assign.vaddr) = *val; } else return err; break; } case EXPR_NODETYPE_FUNCTION: { /* Evaluate the function */ if (nodes->data.function.fptr == NULL) { /* No function pointer means we are not using function solvers. See if the function has a type to solve directly. */ switch (nodes->data.function.type) { /* This is to keep the file from being too crowded. See exprilfs.h for the definitions. */ #include "exprilfs.h" default: { return EXPR_ERROR_UNKNOWN; } } } else { /* Call the correct function */ return (*(nodes->data.function.fptr)) (obj, nodes->data.function.nodes, nodes->data.function.nodecount, nodes->data.function.refs, nodes->data.function.refcount, val); } break; } default: { /* Unknown node type */ return EXPR_ERROR_UNKNOWN; } } return EXPR_ERROR_NOERROR; }
satishagrwal/Assignment
freeswitch_git/mod/applications/mod_expr/expreval.c
C
gpl-3.0
4,838