answer
stringlengths
15
1.25M
<?php /** * ManagerController * All the stuff related to managers */ namespace InsaLan\TournamentBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\<API key>\Configuration\Route; use Sensio\Bundle\<API key>\Configuration\Method; use Sensio\Bundle\<API key>\Configuration\Template; use Payum\Core\Model\Order; use Payum\Core\Reply\HttpRedirect; use Payum\Core\Reply\HttpResponse; use Payum\Core\Request\Capture; use Payum\Core\Request\GetHumanStatus; use Payum\Offline\PaymentFactory as <API key>; use Payum\Paypal\ExpressCheckout\Nvp\Api; use InsaLan\TournamentBundle\Form\SetManagerName; use InsaLan\TournamentBundle\Form\SetPlayerName; use InsaLan\TournamentBundle\Form\TeamLoginType; use InsaLan\TournamentBundle\Exception\ControllerException; use InsaLan\TournamentBundle\Entity\Manager; use InsaLan\TournamentBundle\Entity\Participant; use InsaLan\TournamentBundle\Entity\Player; use InsaLan\TournamentBundle\Entity\Tournament; use InsaLan\TournamentBundle\Entity\Team; use InsaLan\TournamentBundle\Entity; use InsaLan\UserBundle\Entity\PaymentDetails; /** * ManagerController * All the stuff realted to managers management * @Route("/manager") */ class ManagerController extends Controller { /** * Manage all steps for registering into a tournament as manager * @Route("/{tournament}/user/enroll") */ public function enrollAction(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); if ($manager === null) return $this->redirect($this->generateUrl('<API key>',array('tournament' => $tournament->getId()))); else if ($tournament->getParticipantType() === 'team' && $manager->getParticipant() === null) return $this->redirect($this->generateUrl('<API key>',array('tournament' => $tournament->getId()))); else if (!$manager->getPaymentDone()) return $this->redirect($this->generateUrl('<API key>',array('tournament' => $tournament->getId()))); else return $this->redirect($this->generateUrl('<API key>',array('tournament' => $tournament->getId()))); } /** * Create a new manager related to a tournament * @Route("/{tournament}/user/set") * @Template() */ public function setNameAction(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em->getRepository('<API key>:Manager')-><API key>($usr, $tournament); // TODO Map managers like players into the tournament entity ? This will make counting easier $countManagers = count($em->getRepository('<API key>:Manager')->findByTournament($tournament)); if($tournament->getMaxManager() != null && $countManagers >= $tournament->getMaxManager()) { $this->get('session')->getFlashBag()->add('error', "Il ne reste plus de places manager sur ce tournois !"); return $this->redirect($this->generateUrl('<API key>')); } if ($manager === null) { $manager = new Manager(); $manager->setUser($usr); $manager->setTournament($tournament); } $form = $this->createForm(SetManagerName::class, $manager, array( 'method' => 'POST', 'action' => $this->generateUrl('<API key>', array('tournament' => $tournament->getId())), 'attr' => array('id' => 'step1') )); $form->handleRequest($request); if ($form->isValid()) { $em->persist($manager); $em->flush(); if($tournament->getParticipantType() === "team") return $this->redirect( $this->generateUrl('<API key>', array('tournament' => $tournament->getId())) ); else // solo tournaments return $this->redirect( $this->generateUrl('<API key>', array('tournament' => $tournament->getId())) ); } return array('form' => $form->createView(), 'selectedGame' => $tournament->getType(), 'tournamentId' => $tournament->getId()); } /** * Allow a manager to join a player in a solo tournament * @Route("/{tournament}/user/joinplayer") * @Template() */ public function <API key>(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); // handle only solo tournaments if($tournament->getParticipantType() !== "player") throw new ControllerException("Joueurs solo non acceptées dans ce tournois"); // check if there is already a pending manager for this user and tournament $manager = $em->getRepository('<API key>:Manager') -><API key>($usr, $tournament); if($manager === null) return $this->redirect($this->generateUrl('<API key>', array('tournament' => $tournament->getId()))); $form_player = new Player(); $form = $this->createForm(SetPlayerName::class, $form_player, array( 'method' => 'POST', 'action' => $this->generateUrl('<API key>', array('tournament' => $tournament->getId())), 'attr' => array('id' => 'step3') )); // fill player gamename $form->handleRequest($request); $error_details = null; if ($form->isValid()) { try { // find the targeted player related to the manager $player = $em ->getRepository('<API key>:Player') ->findOneBy(array( 'gameName' => $form_player->getGameName(), 'tournament' => $tournament)); if ($player === null) throw new ControllerException("Joueur introuvable !"); if ($player->getManager() != null) throw new ControllerException("Le joueur possède déjà un manager !"); $manager->setParticipant($player); $player->setManager($manager); $em->persist($manager); $em->persist($player); $em->flush(); return $this->redirect($this->generateUrl('<API key>', array('tournament' => $tournament->getId()))); } catch (ControllerException $e) { $error_details = $e->getMessage(); } } return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'error' => $error_details, 'form' => $form->createView()); } /** * Allow a new manager to join a team with name and password * @Route("/{tournament}/user/jointeam") * @Template() */ public function <API key>(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); // handle only team tournaments if($tournament->getParticipantType() !== "team") throw new ControllerException("Équipes non acceptées dans ce tournois"); // check if there is already a pending manager for this user and tournament $manager = $em->getRepository('<API key>:Manager') -><API key>($usr, $tournament); if($manager === null) return $this->redirect($this->generateUrl('<API key>', array('tournament' => $tournament->getId()))); $form_team = new Team(); $form = $this->createForm(TeamLoginType::class, $form_team, array( 'method' => 'POST', 'action' => $this->generateUrl('<API key>', array('tournament' => $tournament->getId())), 'attr' => array('id' => 'step4') )); // fill name and plainPassword $form->handleRequest($request); // inspired by UserController::joinExistingTeam // TODO rework this by putting the password hash into the request ? $error_details = null; if ($form->isValid()) { try { // hash password $factory = $this->get('security.encoder_factory'); $encoder = $factory->getEncoder($usr); $team = $em ->getRepository('<API key>:Team') -><API key>($form_team->getName(), $tournament); if ($team === null || $team->getTournament()->getId() !== $tournament->getId()) throw new ControllerException("Équipe invalide"); $form_team->setPassword($encoder->encodePassword($form_team->getPlainPassword(), $team->getPasswordSalt())); if ($team->getPassword() === $form_team->getPassword()) { // denied if there is already a manager in the team if ($team->getManager() != null) throw new ControllerException("L'équipe a déjà un manager"); // Because PHP don't support polymorphism, we must get the corresponding Participant object $team_participant = $em ->getRepository('<API key>:Participant')-> findOneById($team->getId()); $manager->setParticipant($team_participant); $team->setManager($manager); $em->persist($manager); $em->persist($team); $em->flush(); return $this->redirect($this->generateUrl('<API key>', array('tournament' => $tournament->getId()))); } else throw new ControllerException("Mot de passe invalide"); } catch (ControllerException $e) { $error_details = $e->getMessage(); } } return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'error' => $error_details, 'form' => $form->createView()); } /** * Allow a new manager to join a team with a specific token * @Route("/team/{team}/enroll/{authToken}") */ public function joinTeamWithToken() { # code ... } /** * Payement doing and details for managers * @Route("/{tournament}/user/pay/details") * @Template() */ public function payAction(Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); if($tournament->isFree()) { $manager->setPaymentDone(true); $em->persist($manager); $em->flush(); return $this->redirect($this->generateUrl('<API key>', array("tournament" => $tournament->getId()))); } return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager); } /** * Paypal stuff * @Route("/{tournament}/user/pay/paypal_ec") */ public function payPaypalECAction(Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); $price = ($manager::ONLINE_PRICE + $tournament-><API key>()); $payment = $this->get("insalan.user.payment"); $order = $payment->getOrder($tournament->getCurrency(), $price); $order->setUser($usr); $order->setRawPrice($manager::ONLINE_PRICE); $order->setPlace(PaymentDetails::PLACE_WEB); $order->setType(PaymentDetails::TYPE_PAYPAL); $order->addPaymentDetail('Place manager pour le tournoi '.$tournament->getName(), $manager::ONLINE_PRICE, ''); $order->addPaymentDetail('Majoration paiement en ligne', $tournament-><API key>(), 'Frais de gestion du paiement'); return $this->redirect( $payment->getTargetUrl( $order, '<API key>', array('tournament' => $tournament->getId()) ) ); } /** * Payment sum up * @Route("/{tournament}/user/pay/done") * @Template() */ public function payDoneAction(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); // Get global variables $globalVars = array(); $globalKeys = ['helpPhoneNumber']; $globalVars = $em->getRepository('InsaLanBundle:GlobalVars')->getGlobalVars($globalKeys); return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'globalVars' => $globalVars); } /** * Perform payment validation * @Route("/{tournament}/user/pay/done_temp") */ public function payDoneTempAction(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $player = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); $payment = $this->get("insalan.user.payment"); if ($payment->check($request, true)) { $player->setPaymentDone(true); $em->persist($player); $em->flush(); } return $this->redirect($this->generateUrl('<API key>', array('tournament' => $tournament->getId()))); } /** * Offer offline payment choices * @Route("/{tournament}/user/pay/offline") * @Template() */ public function payOfflineAction(Request $request, Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); // Get global variables $globalVars = array(); $globalKeys = ['payCheckAddress']; $globalVars = $em->getRepository('InsaLanBundle:GlobalVars')->getGlobalVars($globalKeys); return array('tournament' => $tournament, 'user' => $usr, 'manager' => $manager, 'globalVars' => $globalVars); } /** * Allow a manager to drop a pending tournament registration if not managed by team * TODO add flashbag confirmation * @Route("/{tournament}/user/leave") */ public function leaveAction(Entity\Tournament $tournament) { $em = $this->getDoctrine()->getManager(); $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $tournament); if($manager->getTournament()->getParticipantType() !== "player") throw new ControllerException("Not Allowed"); // must be a player only tournament // not allowed if he paid something if(!$tournament->isFree() && $manager->getPaymentDone()){ $this->get('session')->getFlashBag()->add('error', "Vous avez payé votre place, merci de contacter l'InsaLan si vous souhaitez vous désister."); return $this->redirect($this->generateUrl('<API key>')); } // not allowed either if registration are closed if(!$tournament->isOpenedNow()) return $this->redirect($this->generateUrl('<API key>')); $manager->getParticipant()->setManager(null); $manager->setParticipant(null); $em->remove($manager); $em->flush(); return $this->redirect($this->generateUrl('<API key>')); } /** * Allow a manager to drop a pending tournament registration managed by teams * TODO add flashbag confirmation * @Route("/user/leave/team/{teamId}") */ public function leaveTeamAction($teamId) { $em = $this->getDoctrine()->getManager(); $team = $em ->getRepository('<API key>:Team') ->findOneById($teamId); if($team === null) return $this->redirect($this->generateUrl('<API key>')); // get targeted manager $usr = $this->get('security.token_storage')->getToken()->getUser(); $manager = $em ->getRepository('<API key>:Manager') -><API key>($usr, $team->getTournament()); // is he part of the team roster ? if($team->getManager() != $manager) return $this->redirect($this->generateUrl('<API key>')); // not allowed if he paid something if(!$team->getTournament()->isFree() && $manager->getPaymentDone()){ $this->get('session')->getFlashBag()->add('error', "Vous avez payé votre place, merci de contacter l'InsaLan si vous souhaitez vous désister."); return $this->redirect($this->generateUrl('<API key>')); } // not allowed either if registration are closed if(!$team->getTournament()->isOpenedNow()) return $this->redirect($this->generateUrl('<API key>')); $manager->setParticipant(null); $team->setManager(null); $em->persist($team); $em->remove($manager); $em->flush(); return $this->redirect($this->generateUrl('<API key>')); } } ?>
Mersenne Twister written in PHP ============================ This library contains pure PHP implementations of the Mersenne Twister pseudo-random number generation algorithm. There are 3 classes available `MersenneTwister\MT` This is the Mersenne Twister algorithm as defined by the algorithm authors. It works on both 32 and 64 bit builds of PHP and outputs 32 bit integers. php $mt = new \MersenneTwister\MT(); $mt->init(1234); // mt_srand(1234); $mt->int31(); // int31() per mt19937ar.c, positive values only $mt->int32(); // int32() per mt19937ar.c, high bit sets sign `MersenneTwister\MT64` This is the 64-bit Mersenne Twister algorithm as defined by the algorithm authors. It works **only on 64 bit builds of PHP** and outputs 64 bit integers. php $mt = new \MersenneTwister\MT64(); $mt->init(1234); $mt->int63(); // int63() per mt19937-64.c, positive values only $mt->int64(); // int64() per mt19937-64.c, high bit sets sign `MersenneTwister\PHPVariant` This is the Mersenne Twister algorithm as defined in PHP 5.2.1+. It is slightly different from the original algorithm and outputs a different set of numbers It works on both 32 and 64 bit builds of PHP and outputs 32 bit integers. php $mt = new \MersenneTwister\MT(); $mt->init(1234); // mt_srand(1234); $mt->int31(); // mt_rand(); // Breaks on huge ranges (i.e. PHP_INT_MIN, PHP_INT_MAX) // PHP also breaks on huge ranges, but breaks differently. $mt->rand(min, max); // mt_rand(min, max);
package iso20022 // Payment processes required to transfer cash from the debtor to the creditor. type <API key> struct { // Amount of money to be transferred between the debtor and creditor before bank transaction charges. SettlementAmount *<API key> `xml:"SttlmAmt,omitempty"` // Date on which the first agent expects the cash to be available to the final agent. SettlementDate *ISODate `xml:"SttlmDt,omitempty"` // Choice between types of payment instrument, ie, cheque, credit transfer, direct debit, investment account or payment card. PaymentInstrument *<API key> `xml:"PmtInstrm,omitempty"` } func (p *<API key>) SetSettlementAmount(value, currency string) { p.SettlementAmount = <API key>(value, currency) } func (p *<API key>) SetSettlementDate(value string) { p.SettlementDate = (*ISODate)(&value) } func (p *<API key>) <API key>() *<API key> { p.PaymentInstrument = new(<API key>) return p.PaymentInstrument }
'use strict' const co = require('co') const cli = require('heroku-cli-util') const pg = require('@heroku-cli/plugin-pg-v5') function * run (context, heroku) { const db = yield pg.fetcher(heroku).database(context.app, context.args.database) const query = ` SELECT c.relname AS name, pg_size_pretty(<API key>(c.oid)) AS size FROM pg_class c LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace) WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname !~ '^pg_toast' AND c.relkind='r' ORDER BY <API key>(c.oid) DESC; ` const output = yield pg.psql.exec(db, query) process.stdout.write(output) } const cmd = { topic: 'pg', description: 'show the size of the tables (including indexes), descending by size', needsApp: true, needsAuth: true, args: [{ name: 'database', optional: true }], run: cli.command({ preauth: true }, co.wrap(run)) } module.exports = [ Object.assign({ command: 'total-table-size' }, cmd), Object.assign({ command: 'total_table_size', hidden: true }, cmd) ]
using System.Collections.Generic; using PlacesToVisit.ServiceModel.Types; namespace Recipe1.Test { public class PlaceSeedData { public static List<Place> GetSeedPlaces() { var places = new List<Place>(); places.Add(new Place { Name = "Canberra", Description = "Capital city of Australia" }); places.Add(new Place { Name = "Sydney", Description = "Largest city in Australia" }); places.Add(new Place { Name = "Ottawa", Description = "Capital city of Canada" }); places.Add(new Place { Name = "Toronto", Description = "Most populated city in Canada" }); return places; } } }
# The Mithril Diaries Account of experiences finding/using the [Mithril](https://mithril.js.org/) javascript framework Please see the [wiki](https://github.com/pakx/the-mithril-diaries/wiki) for articles.
<?php if ( !defined( 'ABSPATH' ) ) exit( 'No direct script access allowed' ); // Exit if accessed directly // check if field has rows of data if ( have_rows("events") ) { ?> <div class="container"> <span class="divider divider-black divider-full"></span> <div class="row section-header-2"> <div class="col-xs-12"> <h2><?php _e("We do events", THEME_DOMAIN); ?>:</h2> </div> </div> </div> <div class="container-fluid events-container"> <?php $events = get_field("events"); // loop through the rows of data foreach ( $events as $key => $single_post ) { include ( locate_template("templates/post/grid-events-thumb.php" ) ); } ?> </div> </div> <?php } ?>
<?php $steps->Then('/^Request method is (.*)$/', function($world, $method) { assertEquals($method, $world->getClient()->getRequest()->getMethod()); }); $steps->Then('/^Request has cookie "([^"]*)"$/', function($world, $cookie) { assertTrue($world->getClient()->getRequest()->cookies->has($cookie)); }); $steps->Then('/^Request has not cookie "([^"]*)"$/', function($world, $cookie) { assertFalse($world->getClient()->getRequest()->cookies->has($cookie)); }); $steps->Then('/^Request cookie "([^"]*)" is "([^"]*)"$/', function($world, $cookie, $val) { assertEquals($val, $world->getClient()->getRequest()->cookies->get($cookie)); });
define(['Charts/BarChart'], function(BarChart) { 'use strict'; var <API key> = function() { return { singleAxisValue: 'Month', updateSingleAxis: function(event) { var selectedValue = event.sender.value(); this.barChart.update(selectedValue, this.barChart.multiAxis); }, multiAxisValues: ['RBI', 'H', 'HR'], updateMultiAxis: function(event) { var selectedValue = event.sender.value(); this.barChart.update(this.barChart.singleAxis, selectedValue); } } } var _initBindings = function(barChart) { var view = $("body"); var viewModel = kendo.observable({ barChartObservable: <API key>() }); kendo.bind(view, viewModel); viewModel.barChart = barChart; return viewModel; } var initApp = function() { var barChart = new BarChart("barChart"); var viewModel = _initBindings(barChart); var playerDataUrl = "http://richhildebrand.github.io/Jason-Kipnis/Data/kipnis2015.json"; var data = $.getJSON(playerDataUrl, function(playerData) { barChart.init(playerData, viewModel.barChartObservable.singleAxisValue, viewModel.barChartObservable.multiAxisValues); }); }(); });
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length, n = matrix[0].length; int l = 0, r = m - 1, t = 0; while (l <= r) { int mid = l + (r - l)/2; if (target > matrix[mid][n-1]) { l = mid + 1; } else { if (target > matrix[mid][0]) { return find(matrix, mid, n, target); } else if (target < matrix[mid][0]) { r = mid - 1; } else { return true; } } } return false; } private boolean find(int[][] matrix, int row, int n, int target) { int l = 0, r = n - 1; while (l <= r) { int mid = l + (r-l)/2; if (target > matrix[row][mid]) { l = mid + 1; } else if (target < matrix[row][mid]) { r = mid - 1; } else return true; } return false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace GorokuEdit { <summary> JumpToWindow.xaml </summary> public partial class JumpToWindow:Window { private <API key> viewModel; public JumpToWindow(Tuple<int,int[]>[] threads) { InitializeComponent(); viewModel=new <API key>(threads); DataContext=viewModel; } private void <API key>(object sender,KeyEventArgs e) { if(e.Key==Key.Enter){ DialogResult=true; Close(); } } public static Tuple<int,int> GetJumpPosition(Tuple<int,int[]>[] threads) { var window=new JumpToWindow(threads); window.Owner=App.Current.MainWindow; if(window.ShowDialog().Value) return Tuple.Create(window.viewModel.SelectedThread.Item1,window.viewModel.SelectedResNumber); else return null; } } }
package hudson.triggers; import antlr.ANTLRException; import hudson.Util; import hudson.Extension; import hudson.console.AnnotatedLargeText; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.Cause; import hudson.util.IOUtils; import jenkins.model.Jenkins; import hudson.model.Item; import hudson.model.Project; import hudson.model.SCMedItem; import hudson.model.<API key>; import hudson.model.Run; import hudson.util.<API key>; import hudson.util.FormValidation; import hudson.util.NamingThreadFactory; import hudson.util.StreamTaskListener; import hudson.util.TimeUnit2; import hudson.util.<API key>; import org.apache.commons.io.FileUtils; import org.apache.commons.jelly.XMLOutput; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.<API key>; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.Charset; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import java.text.DateFormat; import java.util.concurrent.ThreadFactory; import net.sf.json.JSONObject; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerResponse; import static java.util.logging.Level.*; import jenkins.model.RunAction2; /** * {@link Trigger} that checks for SCM updates periodically. * * You can add UI elements under the SCM section by creating a * config.jelly or config.groovy in the resources area for * your class that inherits from SCMTrigger and has the * @{@link hudson.model.Extension} annotation. The UI should * be wrapped in an f:section element to denote it. * * @author Kohsuke Kawaguchi */ public class SCMTrigger extends Trigger<SCMedItem> { private boolean <API key>; public SCMTrigger(String scmpoll_spec) throws ANTLRException { this(scmpoll_spec, false); } @<API key> public SCMTrigger(String scmpoll_spec, boolean <API key>) throws ANTLRException { super(scmpoll_spec); this.<API key> = <API key>; } /** * This trigger wants to ignore post-commit hooks. * <p> * SCM plugins must respect this and not run this trigger for post-commit notifications. * * @since 1.493 */ public boolean <API key>() { return this.<API key>; } @Override public void run() { run(null); } /** * Run the SCM trigger with additional build actions. Used by <API key> * to trigger a build at a specific revisionn number. * * @param additionalActions * @since 1.375 */ public void run(Action[] additionalActions) { if(Jenkins.getInstance().isQuietingDown()) return; // noop DescriptorImpl d = getDescriptor(); LOGGER.fine("Scheduling a polling for "+job); if (d.synchronousPolling) { LOGGER.fine("Running the trigger directly without threading, " + "as it's already taken care of by Trigger.Cron"); new Runner(additionalActions).run(); } else { // schedule the polling. // even if we end up submitting this too many times, that's OK. // the real exclusion control happens inside Runner. LOGGER.fine("scheduling the trigger to (asynchronously) run"); d.queue.execute(new Runner(additionalActions)); d.clogCheck(); } } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } @Override public Collection<? extends Action> getProjectActions() { return Collections.singleton(new SCMAction()); } /** * Returns the file that records the last/current polling activity. */ public File getLogFile() { return new File(job.getRootDir(),"scm-polling.log"); } @Extension public static class DescriptorImpl extends TriggerDescriptor { private static ThreadFactory threadFactory() { return new NamingThreadFactory(Executors.<API key>(), "SCMTrigger"); } private transient final <API key> queue = new <API key>(Executors.<API key>(threadFactory())); /** * Whether the projects should be polled all in one go in the order of dependencies. The default behavior is * that each project polls for changes independently. */ public boolean synchronousPolling = false; /** * Max number of threads for SCM polling. * 0 for unbounded. */ private int maximumThreads; public DescriptorImpl() { load(); resizeThreadPool(); } public boolean isApplicable(Item item) { return item instanceof SCMedItem; } public ExecutorService getExecutor() { return queue.getExecutors(); } /** * Returns true if the SCM polling thread queue has too many jobs * than it can handle. */ public boolean isClogged() { return queue.isStarving(<API key>); } /** * Checks if the queue is clogged, and if so, * activate {@link <API key>}. */ public void clogCheck() { <API key>.all().get(<API key>.class).on = isClogged(); } /** * Gets the snapshot of {@link Runner}s that are performing polling. */ public List<Runner> getRunners() { return Util.filter(queue.getInProgress(),Runner.class); } /** * Gets the snapshot of {@link SCMedItem}s that are being polled at this very moment. */ public List<SCMedItem> getItemsBeingPolled() { List<SCMedItem> r = new ArrayList<SCMedItem>(); for (Runner i : getRunners()) r.add(i.getTarget()); return r; } public String getDisplayName() { return Messages.<API key>(); } /** * Gets the number of concurrent threads used for polling. * * @return * 0 if unlimited. */ public int <API key>() { return maximumThreads; } /** * Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly * @param n number of concurrent threads, zero or less means unlimited, maximum is 100 */ public void <API key>(int n) { // fool proof if(n<0) n=0; if(n>100) n=100; maximumThreads = n; resizeThreadPool(); } @Restricted(NoExternalUse.class) public boolean <API key>() { // unless you have a fair number of projects, this option is likely pointless. // so let's hide this option for new users to avoid confusing them // unless it was already changed return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10 || <API key>() != 0; } /** * Update the {@link ExecutorService} instance. */ /*package*/ synchronized void resizeThreadPool() { queue.setExecutors( (maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory()))); } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { String t = json.optString("pollingThreadCount",null); if(t==null || t.length()==0) <API key>(0); else <API key>(Integer.parseInt(t)); // Save configuration save(); return true; } public FormValidation <API key>(@QueryParameter String value) { if (value != null && "".equals(value.trim())) return FormValidation.ok(); return FormValidation.<API key>(value); } } @Extension public static final class <API key> extends <API key> { private boolean on; public boolean isActivated() { return on; } } /** * Associated with {@link AbstractBuild} to show the polling log * that triggered that build. * * @since 1.376 */ public static class BuildAction implements RunAction2 { public transient /*final*/ AbstractBuild build; public BuildAction(AbstractBuild build) { this.build = build; } /** * Polling log that triggered the build. */ public File getPollingLogFile() { return new File(build.getRootDir(),"polling.log"); } public String getIconFileName() { return "clipboard.png"; } public String getDisplayName() { return Messages.<API key>(); } public String getUrlName() { return "pollingLog"; } /** * Sends out the raw polling log output. */ public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException { rsp.setContentType("text/plain;charset=UTF-8"); // Prevent jelly from flushing stream so Content-Length header can be added afterwards <API key> out = new <API key>(rsp.<API key>(req)); try { getPollingLogText().writeLogTo(0, out); } finally { IOUtils.closeQuietly(out); } } public AnnotatedLargeText getPollingLogText() { return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this); } /** * Used from <tt>polling.jelly</tt> to write annotated polling log to the given output. */ public void writePollingLogTo(long offset, XMLOutput out) throws IOException { // TODO: resurrect compressed log file support getPollingLogText().writeHtmlTo(offset, out.asWriter()); } @Override public void onAttached(Run<?, ?> r) { // unnecessary, existing constructor does this } @Override public void onLoad(Run<?, ?> r) { build = (AbstractBuild) r; } } /** * Action object for {@link Project}. Used to display the last polling log. */ public final class SCMAction implements Action { public AbstractProject<?,?> getOwner() { return job.asProject(); } public String getIconFileName() { return "clipboard.png"; } public String getDisplayName() { return Messages.<API key>(job.getScm().getDescriptor().getDisplayName()); } public String getUrlName() { return "scmPollLog"; } public String getLog() throws IOException { return Util.loadFile(getLogFile()); } /** * Writes the annotated log to the given output. * @since 1.350 */ public void writeLogTo(XMLOutput out) throws IOException { new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter()); } } private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName()); /** * {@link Runnable} that actually performs polling. */ public class Runner implements Runnable { /** * When did the polling start? */ private volatile long startTime; private Action[] additionalActions; public Runner() { additionalActions = new Action[0]; } public Runner(Action[] actions) { if (actions == null) { additionalActions = new Action[0]; } else { additionalActions = actions; } } /** * Where the log file is written. */ public File getLogFile() { return SCMTrigger.this.getLogFile(); } /** * For which {@link Item} are we polling? */ public SCMedItem getTarget() { return job; } /** * When was this polling started? */ public long getStartTime() { return startTime; } /** * Human readable string of when this polling is started. */ public String getDuration() { return Util.getTimeSpanString(System.currentTimeMillis()-startTime); } private boolean runPolling() { try { // to make sure that the log file contains up-to-date text, // don't do buffering. StreamTaskListener listener = new StreamTaskListener(getLogFile()); try { PrintStream logger = listener.getLogger(); long start = System.currentTimeMillis(); logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date())); boolean result = job.poll(listener).hasChanges(); logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start)); if(result) logger.println("Changes found"); else logger.println("No changes"); return result; } catch (Error e) { e.printStackTrace(listener.error("Failed to record SCM polling for "+job)); LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e); throw e; } catch (RuntimeException e) { e.printStackTrace(listener.error("Failed to record SCM polling for "+job)); LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e); throw e; } finally { listener.close(); } } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e); return false; } } public void run() { String threadName = Thread.currentThread().getName(); Thread.currentThread().setName("SCM polling for "+job); try { startTime = System.currentTimeMillis(); if(runPolling()) { AbstractProject p = job.asProject(); String name = " #"+p.getNextBuildNumber(); SCMTriggerCause cause; try { cause = new SCMTriggerCause(getLogFile()); } catch (IOException e) { LOGGER.log(WARNING, "Failed to parse the polling log",e); cause = new SCMTriggerCause(); } if(p.scheduleBuild(p.getQuietPeriod(), cause, additionalActions)) { LOGGER.info("SCM changes detected in "+ job.getName()+". Triggering "+name); } else { LOGGER.info("SCM changes detected in "+ job.getName()+". Job is already in the queue"); } } } finally { Thread.currentThread().setName(threadName); } } private SCMedItem job() { return job; } // as per the requirement of <API key>, value equality is necessary @Override public boolean equals(Object that) { return that instanceof Runner && job()==((Runner)that).job(); } @Override public int hashCode() { return job.hashCode(); } } public static class SCMTriggerCause extends Cause { /** * Only used while ths cause is in the queue. * Once attached to the build, we'll move this into a file to reduce the memory footprint. */ private String pollingLog; public SCMTriggerCause(File logFile) throws IOException { // TODO: charset of this log file? this(FileUtils.readFileToString(logFile)); } public SCMTriggerCause(String pollingLog) { this.pollingLog = pollingLog; } /** * @deprecated * Use {@link #SCMTrigger.SCMTriggerCause(String)}. */ public SCMTriggerCause() { this(""); } @Override public void onAddedTo(AbstractBuild build) { try { BuildAction a = new BuildAction(build); FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog); build.replaceAction(a); } catch (IOException e) { LOGGER.log(WARNING,"Failed to persist the polling log",e); } pollingLog = null; } @Override public String getShortDescription() { return Messages.<API key>(); } @Override public boolean equals(Object o) { return o instanceof SCMTriggerCause; } @Override public int hashCode() { return 3; } } /** * How long is too long for a polling activity to be in the queue? */ public static long <API key> =Long.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1)); }
package eu.verdelhan.ta4j.indicators.trackers; import static eu.verdelhan.ta4j.TATestsUtils.assertDecimalEquals; import eu.verdelhan.ta4j.Tick; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; import eu.verdelhan.ta4j.indicators.simple.MaxPriceIndicator; import eu.verdelhan.ta4j.indicators.simple.MinPriceIndicator; import eu.verdelhan.ta4j.mocks.MockTick; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; public class <API key> { private TimeSeries data; @Before public void setUp() { List<Tick> ticks = new ArrayList<Tick>(); ticks.add(new MockTick(44.98, 45.05, 45.17, 44.96)); ticks.add(new MockTick(45.05, 45.10, 45.15, 44.99)); ticks.add(new MockTick(45.11, 45.19, 45.32, 45.11)); ticks.add(new MockTick(45.19, 45.14, 45.25, 45.04)); ticks.add(new MockTick(45.12, 45.15, 45.20, 45.10)); ticks.add(new MockTick(45.15, 45.14, 45.20, 45.10)); ticks.add(new MockTick(45.13, 45.10, 45.16, 45.07)); ticks.add(new MockTick(45.12, 45.15, 45.22, 45.10)); ticks.add(new MockTick(45.15, 45.22, 45.27, 45.14)); ticks.add(new MockTick(45.24, 45.43, 45.45, 45.20)); ticks.add(new MockTick(45.43, 45.44, 45.50, 45.39)); ticks.add(new MockTick(45.43, 45.55, 45.60, 45.35)); ticks.add(new MockTick(45.58, 45.55, 45.61, 45.39)); data = new TimeSeries(ticks); } @Test public void <API key>() { WilliamsRIndicator wr = new WilliamsRIndicator(new ClosePriceIndicator(data), 5, new MaxPriceIndicator(data), new MinPriceIndicator(data)); assertDecimalEquals(wr.getValue(4), -47.2222); assertDecimalEquals(wr.getValue(5), -54.5454); assertDecimalEquals(wr.getValue(6), -78.5714); assertDecimalEquals(wr.getValue(7), -47.6190); assertDecimalEquals(wr.getValue(8), -25d); assertDecimalEquals(wr.getValue(9), -5.2632); assertDecimalEquals(wr.getValue(10), -13.9535); } @Test public void <API key>() { WilliamsRIndicator wr = new WilliamsRIndicator(new ClosePriceIndicator(data), 10, new MaxPriceIndicator(data), new MinPriceIndicator(data)); assertDecimalEquals(wr.getValue(9), -4.0816); assertDecimalEquals(wr.getValue(10), -11.7647); assertDecimalEquals(wr.getValue(11), -8.9286); assertDecimalEquals(wr.getValue(12), -10.5263); } @Test public void <API key>() { WilliamsRIndicator wr = new WilliamsRIndicator(new ClosePriceIndicator(data), 100, new MaxPriceIndicator(data), new MinPriceIndicator(data)); assertDecimalEquals(wr.getValue(0), -100d * (0.12 / 0.21)); assertDecimalEquals(wr.getValue(1), -100d * (0.07 / 0.21)); assertDecimalEquals(wr.getValue(2), -100d * (0.13 / 0.36)); assertDecimalEquals(wr.getValue(3), -100d * (0.18 / 0.36)); } }
const fa_file_picture_o = 'M1596 380q28 28 48 76t20 88v1152q0 40-28 68t-68 28h-1344q-40 <API key> 28-68t68-28h896q40 0 88 20t76 <API key> 1528v-1024h-416q-40 <API key> 128 128 <API key> 0-136-56t-56-136 56-136 136-56 136 56 56 136-56 136-136 56z' export default fa_file_picture_o
//= require callback //= require jquery //= require ../utils/xml if (!com.jivatechnology.Badger.Channel) { com.jivatechnology.Badger.Channel = {}; } (function(){ var XML = com.jivatechnology.Badger.Utils.XML; this.Atom = (function(){ return function(opts){ var that = this; var options = opts || {}; // Handle polling var polls = {}; var poll = function(node){ var success = function(body){ if(isPending(node)||isRetrying(node)){ addSubscription(node); that.onSubscribeSuccess.handle(node); } process(node, body); // Queue next poll polls[node] = setTimeout(function(){ poll(node); }, that.delay()); }; var failure = function(s){ var previouslyRetrying = isRetrying(node); if(s.readyState === 0){ // Server unavailable, network? <API key>(node); polls[node] = setTimeout(function(){ poll(node); }, that.retryDelay()); } else { removeSubscription(node); } if(!previouslyRetrying){ that.onSubscribeFailure.handle(node); } }; var url = that.urlFor(node); var settings = {headers: {Accept: "application/atom+xml"}, dataType: "text"}; var jqxhr = $.ajax( url, settings ).done( success ).fail( failure ); }; var clearPoll = function(node){ clearTimeout(polls[node]); }; // Process requests var processedItems = {}; var process = function(node, body){ var oldDataCache = processedItems[node] || {}; // Extract data var newDataCache = {}; var payloads = {}; var entries = $(XML.stringToXML(body)).find("entry"); entries.each(function(i,e){ var $e = $(e); var id = XML.XMLContentsToString($e.find("id")[0]); var updated = XML.XMLContentsToString($e.find("updated")[0]); // Store the updated value to help us compare for changes newDataCache[id] = updated; // Store the body so we can process it if there are changes payloads[id] = XML.XMLToString(e); }); var id; // Whats been added or updated for(id in newDataCache){ if(newDataCache.hasOwnProperty(id)){ if(oldDataCache[id] != newDataCache[id]){ var payload = that.parser().parse(payloads[id]); that.onMessage.handle(node, id, "update", payload); } } } // Whats been removed for(id in oldDataCache){ if(oldDataCache.hasOwnProperty(id)){ if(!newDataCache.hasOwnProperty(id)){ that.onMessage.handle(node, id, "remove"); } } } // Update store processedItems[node] = newDataCache; }; // Track subscriptions var subscriptions = {}; var isPending = function(node){ return subscriptions[node] == "pending"; }; var isRetrying = function(node){ return subscriptions[node] == "retrying"; }; var isSubscribed = function(node){ return subscriptions.hasOwnProperty(node); }; var <API key> = function(node){ subscriptions[node] = "pending"; }; var <API key> = function(node){ subscriptions[node] = "retrying"; }; var addSubscription = function(node){ subscriptions[node] = "subscribed"; }; var removeSubscription = function(node){ delete subscriptions[node]; }; // Public methods this.name = 'Atom'; this.parser = function(){ return options.parser; }; this.delay = function(){ return options.delay || 3000; }; this.retryDelay = function(){ return options.retryDelay || 10000; }; this.urlFor = function(node){ return node; }; // Used if we have extra information that a node is likely to have been // updated - will cause a poll to happen immediately this.hint = function(node){ if(isSubscribed(node)){ clearPoll(node); poll(node); } }; this.subscriptions = function(){ var <API key> = []; for(var n in subscriptions){ if(subscriptions.hasOwnProperty(n) && subscriptions[n] == "subscribed"){ <API key>.push(n); } } return <API key>; }; this.subscribe = function(node){ if(!isSubscribed(node)){ <API key>(node); poll(node); } }; this.unsubscribe = function(node){ if(isSubscribed(node)){ removeSubscription(node); that.<API key>.handle(node); clearPoll(node); } }; // Callbacks var CallbackList = com.jivatechnology.CallbackList; this.onSubscribeSuccess = new CallbackList({must_keep:true}); this.onSubscribeFailure = new CallbackList({must_keep:true}); this.<API key> = new CallbackList({must_keep:true}); this.<API key> = new CallbackList({must_keep:true}); this.onMessage = new CallbackList({must_keep:true}); }; })(); }).call( com.jivatechnology.Badger.Channel );
import socket import threading import email.mime.text import email.mime.image import email.mime.multipart import email.header import bminterface import re import select import logging class <API key>(object): END = "\r\n" def __init__(self, conn): self.conn = conn def __getattr__(self, name): return getattr(self.conn, name) def sendall(self, data, END=END): data += END self.conn.sendall(data) def recvall(self, END=END): data = [] while True: chunk = self.conn.recv(4096) if END in chunk: data.append(chunk[:chunk.index(END)]) break data.append(chunk) if len(data) > 1: pair = data[-2] + data[-1] if END in pair: data[-2] = pair[:pair.index(END)] data.pop() break return "".join(data) def handleUser(data): d = data.split() logging.debug("data:%s" % d) username = d[-1] if username[:3] == 'BM-': logging.debug("Only showing messages for %s" % username) bminterface.registerAddress(username) else: logging.debug("Showing all messages in the inbox") bminterface.registerAddress(None) return "+OK user accepted" def handlePass(data): return "+OK pass accepted" def _getMsgSizes(): msgCount = bminterface.listMsgs() msgSizes = [] for msgID in range(msgCount): logging.debug("Parsing msg %i of %i" % (msgID+1, msgCount)) dateTime, toAddress, fromAddress, subject, body = bminterface.get(msgID) msgSizes.append(len(makeEmail(dateTime, toAddress, fromAddress, subject, body))) return msgSizes def handleStat(data): msgSizes = _getMsgSizes() msgCount = len(msgSizes) msgSizeTotal = 0 for msgSize in msgSizes: msgSizeTotal += msgSize returnData = '+OK %i %i' % (msgCount, msgSizeTotal) logging.debug("Answering STAT: %i %i" % (msgCount, msgSizeTotal)) return returnData def handleList(data): dataList = data.split() cmd = dataList[0] msgSizes = _getMsgSizes() if len(dataList) > 1: msgId = dataList[1] # means the server wants a single message response i = int(msgId) - 1 if i >= len(msgSizes): return "-ERR no such message" else: msgSize = msgSizes[i] return "+OK %s %s" % (msgId, msgSize) msgCount = 0 returnDataPart2 = '' msgSizeTotal = 0 for msgSize in msgSizes: msgSizeTotal += msgSize msgCount += 1 returnDataPart2 += '%i %i\r\n' % (msgCount, msgSize) returnDataPart2 += '.' returnDataPart1 = '+OK %i messages (%i octets)\r\n' % (msgCount, msgSizeTotal) returnData = returnDataPart1 + returnDataPart2 logging.debug("Answering LIST: %i %i" % (msgCount, msgSizeTotal)) logging.debug(returnData) return returnData def handleTop(data): msg = 'test' logging.debug(data.split()) cmd, msgID, lines = data.split() msgID = int(msgID)-1 lines = int(lines) logging.debug(lines) dateTime, toAddress, fromAddress, subject, body = bminterface.get(msgID) logging.debug(subject) msg = makeEmail(dateTime, toAddress, fromAddress, subject, body) top, bot = msg.split("\n\n", 1) #text = top + "\r\n\r\n" + "\r\n".join(bot[:lines]) return "+OK top of message follows\r\n%s\r\n." % top def handleRetr(data): logging.debug(data.split()) msgID = int(data.split()[1])-1 dateTime, toAddress, fromAddress, subject, body = bminterface.get(msgID) msg = makeEmail(dateTime, toAddress, fromAddress, subject, body) return "+OK %i octets\r\n%s\r\n." % (len(msg), msg) def handleDele(data): msgID = int(data.split()[1])-1 bminterface.markForDelete(msgID) return "+OK I'll try..." def handleNoop(data): return "+OK" def handleQuit(data): bminterface.cleanup() return "+OK just pretend I'm gone" def handleCapa(data): returnData = "+OK List of capabilities follows\r\n" for k in dispatch: returnData += "%s\r\n" % k returnData += "." return returnData def handleUIDL(data): data = data.split() logging.debug(data) if len(data) == 1: refdata = bminterface.getUIDLforAll() logging.debug(refdata) returnData = '+OK\r\n' for msgID, d in enumerate(refdata): returnData += "%s %s\r\n" % (msgID+1, d) returnData += '.' else: refdata = bminterface.getUIDLforSingle(int(data[1])-1) logging.debug(refdata) returnData = '+OK ' + data[0] + str(refdata[0]) return returnData def makeEmail(dateTime, toAddress, fromAddress, subject, body): body = parseBody(body) msgType = len(body) if msgType == 1: msg = email.mime.text.MIMEText(body[0], 'plain', 'UTF-8') else: msg = email.mime.multipart.MIMEMultipart('mixed') bodyText = email.mime.text.MIMEText(body[0], 'plain', 'UTF-8') body = body[1:] msg.attach(bodyText) for item in body: img = 0 itemType, itemData = [0], [0] try: itemType, itemData = item.split(';', 1) itemType = itemType.split('/', 1) except: logging.warning("Could not parse message type") pass if itemType[0] == 'image': try: itemDataFinal = itemData.lstrip('base64,').strip(' ').strip('\n').decode('base64') img = email.mime.image.MIMEImage(itemDataFinal) except: #Some images don't auto-detect type correctly with email.mime.image #Namely, jpegs with embeded color profiles look problematic #Trying to set it manually... try: itemDataFinal = itemData.lstrip('base64,').strip(' ').strip('\n').decode('base64') img = email.mime.image.MIMEImage(itemDataFinal, _subtype=itemType[1]) except: logging.warning("Failed to parse image data. This could be an image.") logging.warning("This could be from an image tag filled with junk data.") logging.warning("It could also be a python email.mime.image problem.") if img: img.add_header('Content-Disposition', 'attachment') msg.attach(img) msg['To'] = toAddress msg['From'] = fromAddress msg['Subject'] = email.header.Header(subject, 'UTF-8') msg['Date'] = dateTime return msg.as_string() def parseBody(body): returnData = [] text = '' searchString = '<img[^>]*' attachment = re.search(searchString, body) while attachment: imageCode = body[attachment.start():attachment.end()] imageDataRange = re.search('src=[\"\'][^\"\']*[\"\']', imageCode) imageData='' if imageDataRange: try: imageData = imageCode[imageDataRange.start()+5:imageDataRange.end()-1].lstrip('data:') except: pass if imageData: returnData.append(imageData) body = body[:attachment.start()] + body[attachment.end()+1:] attachment = re.search(searchString, body) text = body returnData = [text] + returnData return returnData dispatch = dict( USER=handleUser, PASS=handlePass, STAT=handleStat, LIST=handleList, TOP=handleTop, RETR=handleRetr, DELE=handleDele, NOOP=handleNoop, QUIT=handleQuit, CAPA=handleCapa, UIDL=handleUIDL, ) def incomingServer(host, port, run_event): popthread = threading.Thread(target=incomingServer_main, args=(host, port, run_event)) popthread.daemon = True popthread.start() return popthread def incomingServer_main(host, port, run_event): sock = None try: while run_event.is_set(): if sock is None: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) ready = select.select([sock], [], [], .2) if ready[0]: conn, addr = sock.accept() # stop listening, one client only sock.close() sock = None try: conn = <API key>(conn) conn.sendall("+OK server ready") while run_event.is_set(): data = conn.recvall() logging.debug("Answering %s" % data) command = data.split(None, 1)[0] try: cmd = dispatch[command] except KeyError: conn.sendall("-ERR unknown command") else: conn.sendall(cmd(data)) if cmd is handleQuit: break finally: conn.close() except (SystemExit, KeyboardInterrupt): pass except Exception, ex: raise finally: if sock is not None: sock.close()
package com.koushikdutta.async.http; import android.net.Uri; import android.util.Log; import com.koushikdutta.async.AsyncSSLException; import com.koushikdutta.async.http.body.<API key>; import com.koushikdutta.async.http.libcore.RawHeaders; import com.koushikdutta.async.http.libcore.RequestHeaders; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpRequest; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.message.BasicHeader; import org.apache.http.params.HttpParams; import java.util.List; import java.util.Map; public class AsyncHttpRequest { public RequestLine getRequestLine() { return new RequestLine() { @Override public String getUri() { return AsyncHttpRequest.this.getUri().toString(); } @Override public ProtocolVersion getProtocolVersion() { return new ProtocolVersion("HTTP", 1, 1); } @Override public String getMethod() { return mMethod; } @Override public String toString() { String path = AsyncHttpRequest.this.getUri().getEncodedPath(); if (path == null || path.length() == 0) path = "/"; String query = AsyncHttpRequest.this.getUri().getEncodedQuery(); if (query != null && query.length() != 0) { path += "?" + query; } return String.format("%s %s HTTP/1.1", mMethod, path); } }; } public RequestLine getProxyRequestLine() { return new RequestLine() { @Override public String getUri() { return AsyncHttpRequest.this.getUri().toString(); } @Override public ProtocolVersion getProtocolVersion() { return new ProtocolVersion("HTTP", 1, 1); } @Override public String getMethod() { return mMethod; } @Override public String toString() { return String.format("%s %s HTTP/1.1", mMethod, AsyncHttpRequest.this.getUri()); } }; } protected static String getDefaultUserAgent() { String agent = System.getProperty("http.agent"); return agent != null ? agent : ("Java" + System.getProperty("java.version")); } private String mMethod; public String getMethod() { return mMethod; } public AsyncHttpRequest setMethod(String method) { if (getClass() != AsyncHttpRequest.class) throw new <API key>("can't change method on a subclass of AsyncHttpRequest"); mMethod = method; mRawHeaders.setStatusLine(getRequestLine().toString()); return this; } public AsyncHttpRequest(Uri uri, String method) { this(uri, method, null); } public static void setDefaultHeaders(RawHeaders ret, Uri uri) { if (uri != null) { String host = uri.getHost(); if (uri.getPort() != -1) host = host + ":" + uri.getPort(); if (host != null) ret.set("Host", host); } ret.set("User-Agent", getDefaultUserAgent()); ret.set("Accept-Encoding", "gzip, deflate"); ret.set("Connection", "keep-alive"); ret.set("Accept", "*/*"); } public AsyncHttpRequest(Uri uri, String method, RawHeaders headers) { assert uri != null; mMethod = method; if (headers == null) mRawHeaders = new RawHeaders(); else mRawHeaders = headers; if (headers == null) setDefaultHeaders(mRawHeaders, uri); mHeaders = new RequestHeaders(uri, mRawHeaders); mRawHeaders.setStatusLine(getRequestLine().toString()); } public Uri getUri() { return mHeaders.getUri(); } private RawHeaders mRawHeaders = new RawHeaders(); private RequestHeaders mHeaders; public RequestHeaders getHeaders() { return mHeaders; } public String getRequestString() { return mRawHeaders.toHeaderString(); } private boolean mFollowRedirect = true; public boolean getFollowRedirect() { return mFollowRedirect; } public AsyncHttpRequest setFollowRedirect(boolean follow) { mFollowRedirect = follow; return this; } private <API key> mBody; public void setBody(<API key> body) { mBody = body; } public <API key> getBody() { return mBody; } public void <API key>(AsyncSSLException e) { } public static final int DEFAULT_TIMEOUT = 30000; int mTimeout = DEFAULT_TIMEOUT; public int getTimeout() { return mTimeout; } public AsyncHttpRequest setTimeout(int timeout) { mTimeout = timeout; return this; } public static AsyncHttpRequest create(HttpRequest request) { AsyncHttpRequest ret = new AsyncHttpRequest(Uri.parse(request.getRequestLine().getUri()), request.getRequestLine().getMethod()); for (Header header: request.getAllHeaders()) { ret.getHeaders().getHeaders().add(header.getName(), header.getValue()); } return ret; } private static class HttpRequestWrapper implements HttpRequest { AsyncHttpRequest request; @Override public RequestLine getRequestLine() { return request.getRequestLine(); } public HttpRequestWrapper(AsyncHttpRequest request) { this.request = request; } @Override public void addHeader(Header header) { request.getHeaders().getHeaders().add(header.getName(), header.getValue()); } @Override public void addHeader(String name, String value) { request.getHeaders().getHeaders().add(name, value); } @Override public boolean containsHeader(String name) { return request.getHeaders().getHeaders().get(name) != null; } @Override public Header[] getAllHeaders() { Header[] ret = new Header[request.getHeaders().getHeaders().length()]; for (int i = 0; i < ret.length; i++) { String name = request.getHeaders().getHeaders().getFieldName(i); String value = request.getHeaders().getHeaders().getValue(i); ret[i] = new BasicHeader(name, value); } return ret; } @Override public Header getFirstHeader(String name) { String value = request.getHeaders().getHeaders().get(name); if (value == null) return null; return new BasicHeader(name, value); } @Override public Header[] getHeaders(String name) { Map<String, List<String>> map = request.getHeaders().getHeaders().toMultimap(); List<String> vals = map.get(name); if (vals == null) return new Header[0]; Header[] ret = new Header[vals.size()]; for (int i = 0; i < ret.length; i++) ret[i] = new BasicHeader(name, vals.get(i)); return ret; } @Override public Header getLastHeader(String name) { Header[] vals = getHeaders(name); if (vals.length == 0) return null; return vals[vals.length - 1]; } HttpParams params; @Override public HttpParams getParams() { return params; } @Override public ProtocolVersion getProtocolVersion() { return new ProtocolVersion("HTTP", 1, 1); } @Override public HeaderIterator headerIterator() { assert false; return null; } @Override public HeaderIterator headerIterator(String name) { assert false; return null; } @Override public void removeHeader(Header header) { request.getHeaders().getHeaders().removeAll(header.getName()); } @Override public void removeHeaders(String name) { request.getHeaders().getHeaders().removeAll(name); } @Override public void setHeader(Header header) { setHeader(header.getName(), header.getValue()); } @Override public void setHeader(String name, String value) { request.getHeaders().getHeaders().set(name, value); } @Override public void setHeaders(Header[] headers) { for (Header header: headers) setHeader(header); } @Override public void setParams(HttpParams params) { this.params = params; } } public HttpRequest asHttpRequest() { return new HttpRequestWrapper(this); } public AsyncHttpRequest setHeader(String name, String value) { getHeaders().getHeaders().set(name, value); return this; } public AsyncHttpRequest addHeader(String name, String value) { getHeaders().getHeaders().add(name, value); return this; } String proxyHost; int proxyPort = -1; public void enableProxy(String host, int port) { proxyHost = host; proxyPort = port; } public void disableProxy() { proxyHost = null; proxyPort = -1; } public String getProxyHost() { return proxyHost; } public int getProxyPort() { return proxyPort; } public void setLogging(String tag, int level) { LOGTAG = tag; logLevel = level; } // request level logging String LOGTAG; int logLevel; public int getLogLevel() { return logLevel; } public String getLogTag() { return LOGTAG; } long executionTime; private String getLogMessage(String message) { long elapsed; if (executionTime != 0) elapsed = System.currentTimeMillis() - executionTime; else elapsed = 0; return String.format("(%d ms) %s: %s", elapsed, getUri(), message); } public void logi(String message) { if (LOGTAG == null) return; if (logLevel > Log.INFO) return; Log.i(LOGTAG, getLogMessage(message)); } public void logv(String message) { if (LOGTAG == null) return; if (logLevel > Log.VERBOSE) return; Log.v(LOGTAG, getLogMessage(message)); } public void logw(String message) { if (LOGTAG == null) return; if (logLevel > Log.WARN) return; Log.w(LOGTAG, getLogMessage(message)); } public void logd(String message) { if (LOGTAG == null) return; if (logLevel > Log.DEBUG) return; Log.d(LOGTAG, getLogMessage(message)); } public void logd(String message, Exception e) { if (LOGTAG == null) return; if (logLevel > Log.DEBUG) return; Log.d(LOGTAG, getLogMessage(message)); Log.d(LOGTAG, e.getMessage(), e); } public void loge(String message) { if (LOGTAG == null) return; if (logLevel > Log.ERROR) return; Log.e(LOGTAG, getLogMessage(message)); } public void loge(String message, Exception e) { if (LOGTAG == null) return; if (logLevel > Log.ERROR) return; Log.e(LOGTAG, getLogMessage(message)); Log.e(LOGTAG, e.getMessage(), e); } }
namespace DivineInject.Test.DummyModel { public class <API key> : IDomainObject { public <API key>(IDatabase database) { Database = database; } public IDatabase Database { get; private set; } } }
using Caps.Consumer.Localization; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Caps.Consumer.Model { public class <API key> : ILocalizedResource { public int SiteMapNodeId { get; set; } public String Language { get; set; } public String Title { get; set; } public String Keywords { get; set; } public String Description { get; set; } public int? <API key> { get; set; } public DbFileVersion PictureFileVersion { get; set; } } }
// This file is automatically generated. package adila.db; /* * Samsung Galaxy Tab S 10.5 * * DEVICE: chagalllteatt * MODEL: SAMSUNG-SM-T807A */ final class chagalllteatt { public static final String DATA = "Samsung|Galaxy Tab S 10.5|Galaxy Tab"; }
import ant from "antd/lib/index.css"; import fa from "<API key>"; import b from './base.scss';
using System.Web.Mvc; using TeachersDiary.Clients.Mvc.Infrastructure.Filters; using TeachersDiary.Services; namespace TeachersDiary.Clients.Mvc { public class FilterConfig { public static void <API key>(<API key> filters) { filters.Add(new <API key>(new LoggingService())); } } }
<?php // Declare ext ID, path define('EXTID_PORTAL', 111); define('PATH_EXT_PORTAL', PATH_EXT . '/portal'); require_once( PATH_EXT_PORTAL . '/config/constants.php' ); ?>
using <API key>; using System; using System.Collections.Generic; using System.Linq; namespace kpmShell { internal class Program { private static void Main(string[] args) { Dictionary<string, string> shortCmd = new Dictionary<string, string>(); shortCmd.Add("lm", "load-manager"); shortCmd.Add("sm", "save-manager"); shortCmd.Add("ip", "install-package"); shortCmd.Add("lip", "<API key>"); shortCmd.Add("ua", "update-all"); shortCmd.Add("e", "exit"); shortCmd.Add("q", "quit"); Manager.Load(); Console.Clear(); while (true) { PrintHelp(); Console.Write("="); string cmd = Console.ReadLine(); Console.WriteLine(); var sCmd = cmd.Split(' '); if (shortCmd.ContainsKey(sCmd[0])) { cmd = shortCmd[sCmd[0]] + cmd.Substring(sCmd[0].Length); sCmd[0] = shortCmd[sCmd[0]]; } sCmd[0] = sCmd[0].ToLower(); if (sCmd[0] == "load-manager") Manager.Load(); if (sCmd[0] == "save-manager") Manager.Save(); if (sCmd[0] == "install-package") { Manager.Resolve(cmd.Substring("install-package ".Length).Trim()).DownloadAndInstall(); Manager.Save(); //Save after install } if (sCmd[0] == "<API key>") { Manager.InstalledPackages = (from pkg in Manager.InstalledPackages orderby pkg.Name select pkg).ToList(); foreach (var pkg in Manager.InstalledPackages) Console.WriteLine(pkg); } if (sCmd[0] == "update-all") { var packages = Manager.InstalledPackages; foreach (Package pkg in packages) new UnresolvedPackage(pkg.Name).Resolve().DownloadAndInstall(); } if (sCmd[0] == "exit" || sCmd[0] == "quit") break; } Manager.Save(); } private static void PrintHelp() { Console.WriteLine("Commands: "); Console.WriteLine("install-package:\t\tInstall package"); Console.WriteLine("update-all:\t\t\tUpdate all packages"); Console.WriteLine("<API key>:\tList installed packages"); Console.WriteLine("load-manager:\t\t\tLoad manager state from disk"); Console.WriteLine("save-manager:\t\t\tSave manager state to disk"); Console.WriteLine("exit:\t\t\t\texit"); Console.WriteLine("quit:\t\t\t\tquit"); } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_102-google-v7) on Wed Jan 11 15:17:54 PST 2017 --> <title>AccessibilityUtil</title> <meta name="date" content="2017-01-11"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AccessibilityUtil"; } } catch(err) { } var methods = {"i0":9,"i1":9,"i2":41,"i3":9,"i4":9,"i5":9,"i6":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"],32:["t6","Deprecated Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../org/robolectric/util/ActivityController.html" title="class in org.robolectric.util"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/util/AccessibilityUtil.html" target="_top">Frames</a></li> <li><a href="AccessibilityUtil.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <div class="subTitle">org.robolectric.util</div> <h2 title="Class AccessibilityUtil" class="title">Class AccessibilityUtil</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.robolectric.util.AccessibilityUtil</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">AccessibilityUtil</span> extends java.lang.Object</pre> <div class="block">Utility class for checking Views for accessibility. This class is used by <code>ShadowView.checkedPerformClick</code> to check for accessibility problems. There is some subtlety to checking a UI for accessibility when it hasn't been rendered. The better initialized the View, the more accurate the checking will be. At a minimum, the view should be attached to a proper view hierarchy similar to what's checked for in:q <code>ShadowView.checkedPerformClick</code>.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.summary"> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t6" class="tableTab"><span><a href="javascript:show(32);">Deprecated Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static java.util.List&lt;com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#checkView-android.view.View-">checkView</a></span>(android.view.View&nbsp;view)</code> <div class="block">Check a hierarchy of <code>View</code>s for accessibility, based on currently set options.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static java.util.List&lt;com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>.view.View-"><API key></a></span>(android.view.View&nbsp;view)</code> <div class="block">Check a hierarchy of <code>View</code>s for accessibility.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>.view.View-"><API key></a></span>(android.view.View&nbsp;view)</code> <div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>.robolectric.annotation.AccessibilityChecks.<API key>-"><API key></a></span>(<a href="../../../org/robolectric/annotation/AccessibilityChecks.<API key>.html" title="enum in org.robolectric.annotation">AccessibilityChecks.<API key></a>&nbsp;forVersion)</code> <div class="block">Specify that a specific subset of accessibility checks be run.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>-"><API key></a></span>(boolean&nbsp;<API key>)</code> <div class="block">Specify that accessibility checks should be run for all views in the hierarchy whenever a single view's accessibility is asserted.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>.hamcrest.Matcher-"><API key></a></span>(org.hamcrest.Matcher&lt;? super com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;&nbsp;matcher)</code> <div class="block">Suppress all results that match the given matcher.</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/util/AccessibilityUtil.html#<API key>-"><API key></a></span>(boolean&nbsp;<API key>)</code> <div class="block">Control whether or not to throw exceptions when accessibility errors are found.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method.detail"> </a> <h3>Method Detail</h3> <a name="<API key>.view.View-"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;java.util.List&lt;com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;&nbsp;<API key>(android.view.View&nbsp;view)</pre> <div class="block">Check a hierarchy of <code>View</code>s for accessibility. Only performs checks if (in decreasing priority order) accessibility checking is enabled using an <a href="../../../org/robolectric/annotation/AccessibilityChecks.html" title="annotation in org.robolectric.annotation"><code>AccessibilityChecks</code></a> annotation, if the system property <code>robolectric.accessibility.enablechecks</code> is set to <code>true</code>, or if the environment variable <code>robolectric.accessibility.enablechecks</code> is set to <code>true</code>.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>view</code> - The <code>View</code> to examine</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>A list of results from the check. If there are no results or checking is disabled, the list is empty.</dd> </dl> </li> </ul> <a name="checkView-android.view.View-"> </a> <ul class="blockList"> <li class="blockList"> <h4>checkView</h4> <pre>public static&nbsp;java.util.List&lt;com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;&nbsp;checkView(android.view.View&nbsp;view)</pre> <div class="block">Check a hierarchy of <code>View</code>s for accessibility, based on currently set options.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>view</code> - The <code>View</code> to examine</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>A list of results from the check. If there are no results, the list is empty.</dd> </dl> </li> </ul> <a name="<API key>.view.View-"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>@Deprecated public static&nbsp;boolean&nbsp;<API key>(android.view.View&nbsp;view)</pre> <div class="block"><span class="deprecatedLabel">Deprecated.</span>&nbsp;</div> <div class="block">Check a hierarchy of <code>View</code>s for accessibility. Only performs checks if (in decreasing priority order) accessibility checking is enabled using an <a href="../../../org/robolectric/annotation/AccessibilityChecks.html" title="annotation in org.robolectric.annotation"><code>AccessibilityChecks</code></a> annotation, if the system property <code>robolectric.accessibility.enablechecks</code> is set to <code>true</code>, or if the environment variable <code>robolectric.accessibility.enablechecks</code> is set to <code>true</code>. Implicitly calls {code <API key>(false)} to disable exception throwing. This method is deprecated, both because of this side effect and because the other methods offer more control over execution.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>view</code> - The <code>View</code> to examine</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>A list of results from the check. If there are no results or checking is disabled, the list is empty.</dd> </dl> </li> </ul> <a name="<API key>.robolectric.annotation.AccessibilityChecks.<API key>-"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;void&nbsp;<API key>(<a href="../../../org/robolectric/annotation/AccessibilityChecks.<API key>.html" title="enum in org.robolectric.annotation">AccessibilityChecks.<API key></a>&nbsp;forVersion)</pre> <div class="block">Specify that a specific subset of accessibility checks be run. The subsets are specified based on which Robolectric version particular checks were released with. By default, all checks are run (<a href="../../../org/robolectric/annotation/AccessibilityChecks.<API key>.html" title="enum in org.robolectric.annotation"><code>AccessibilityChecks.<API key></code></a>. <p> If you call this method, the value you pass will take precedence over any value in any annotations.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>forVersion</code> - The version of checks to run for. If <code>null</code>, throws away the current value and falls back on the annotation or default.</dd> </dl> </li> </ul> <a name="<API key>-"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;void&nbsp;<API key>(boolean&nbsp;<API key>)</pre> <div class="block">Specify that accessibility checks should be run for all views in the hierarchy whenever a single view's accessibility is asserted.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code><API key></code> - <code>true</code> if all views in the hierarchy should be checked.</dd> </dl> </li> </ul> <a name="<API key>.hamcrest.Matcher-"> </a> <ul class="blockList"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;void&nbsp;<API key>(org.hamcrest.Matcher&lt;? super com.google.android.apps.common.testing.accessibility.framework.<API key>&gt;&nbsp;matcher)</pre> <div class="block">Suppress all results that match the given matcher. Suppressed results will not be included in any logs or cause any <code>Exception</code> to be thrown. This capability is useful if there are known issues, but checks should still look for regressions.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>matcher</code> - A matcher to match a <code><API key></code>. <code>null</code> disables suppression and is the default.</dd> </dl> </li> </ul> <a name="<API key>-"> </a> <ul class="blockListLast"> <li class="blockList"> <h4><API key></h4> <pre>public static&nbsp;void&nbsp;<API key>(boolean&nbsp;<API key>)</pre> <div class="block">Control whether or not to throw exceptions when accessibility errors are found.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code><API key></code> - <code>true</code> to throw an <code><API key></code> when there is at least one error result. Default: <code>true</code>.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../org/robolectric/util/ActivityController.html" title="class in org.robolectric.util"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/util/AccessibilityUtil.html" target="_top">Frames</a></li> <li><a href="AccessibilityUtil.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
function SimpleView() { if (SimpleView.prototype.instance) { console.log("An instance of SimpleView already exists."); return SimpleView.prototype.instance; } SimpleView.prototype.instance = this; var cvs , ctx , peek = defaultPeek , requestType = { peek : true, spectrum : false, updateTime : false} , requiredCVS = 1 , width = 400 , height = 200 , xpad = 10 , ypad = 10 , semiMajorAxis = width / 6 , semiMinorAxis = height / 3 , cx = width / 2 , cy = height / 2 , x = width - (semiMajorAxis + 2 * xpad) , verticalSepX = cx + xpad , verticalSepBY = height - ypad , noteFontMaxWidth = cx - xpad , noteFontSize = height - 2 * ypad , freqFontSize = 0.2 * height , baseColor = "rgb(58,58,58)" /* almost black */ , bgColor = "white" , tunedColor = "rgb(122,153,66)" /* green */ , notTunedColor = "rgb(140,46,46)" /* red */ , noteFontName = "sans-serif" , freqFontName = "sans-serif" , noteFont = fontStringPX(noteFontSize,noteFontName) , freqFont = fontStringPX(freqFontSize,freqFontName) , startID ; function ctxStyleSetup() { ctx.fillStyle = baseColor; ctx.strokeStyle = baseColor; } function drawArrow(direction) { var y = cy + (freqFontSize / 2 * direction) , dir = semiMinorAxis * direction , rpoint = y + (dir / 2) ; ctx.beginPath(); ctx.moveTo(x - semiMajorAxis,y); ctx.lineTo(x,y + dir); ctx.lineTo(x + semiMajorAxis, y); ctx.bezierCurveTo(x, rpoint, x, rpoint, x - semiMajorAxis, y); ctx.fill(); } function drawNoteName() { ctx.save(); ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.font = noteFont; ctx.fillText(peek.note.name, xpad, cy, noteFontMaxWidth); ctx.restore(); } function drawFrequency() { var cents = Math.abs(peek.cents); ctx.save(); ctx.fillStyle = cents - 5 <= 5 ? tunedColor : notTunedColor; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = freqFont; ctx.fillText(peek.frequency.toFixed(2), x, cy); ctx.restore(); } function drawSeparator(x0, y0, x1, y1) { ctx.save(); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x1, y1); ctx.lineCap = "round"; ctx.stroke(); ctx.restore(); } Object.defineProperties(this, { "setCVS" : { enumerable : false , configurable : false , set : function (cvs) { cvs = cvs[0]; ctx = cvs.getContext("2d"); cvs.id = "gtunerView"; cvs.width = width; cvs.height = height; cvs.style.background = bgColor; ctxStyleSetup(); } } , "width" : { enumerable : true , configurable : false , get : function () { return width; } , set : function (val) { width = val; cvs.width = width; semiMajorAxis = width / 6; cx = width / 2; x = width - (semiMajorAxis + xpad); noteFontMaxWidth = cx - xpad; verticalSepX = cx + xpad; ctxStyleSetup(); } } , "height" : { enumerable : true , configurable : false , get : function () { return height; } , set : function (val) { height = val; cy = height / 2; cvs.height = height; semiMinorAxis = height / 3; verticalSepBY = height - ypad; noteFontSize = 0.6 * height; freqFontSize = 0.2 * height; ctxStyleSetup(); } } , "peek" : { value : peek , configurable : false , enumerable : false , writable : false } , "requestType" : { value : requestType , configurable : false , enumerable : true , writable : false } , "requiredCVS" : { value : requiredCVS , configurable : false , enumerable : true , writable : false } , "baseColor" : { configurable : false , enumerable : true , get : function () { return baseColor; } , set : function (value) { baseColor = value; ctxStyleSetup(); } } , "bgColor" : { configurable : false , enumerable : true , get : function () { return bgColor; } , set : function (value) { bgColor = value; cvs.style.background = bgColor; } } , "tunedColor" : { configurable : false , enumerable : true , get : function () { return tunedColor; } , set : function (value) { tunedColor = value; } } , "notTunedColor" : { configurable : false , enumerable : true , get : function () { return notTunedColor; } , set : function (value) { notTunedColor = value; } } , "noteFont" : { configurable : false , enumerable : false , get : function () { return noteFont; } } , "freqFont" : { configurable : false , enumerable : false , get : function () { return freqFont; } } , "noteFontSize" : { configurable : false , enumerable : true , set : function (val) { noteFontSize = val; noteFont = fontStringPX(noteFontSize,noteFontName); } , get : function () { return noteFontSize; } } , "freqFontSize" : { configurable : false , enumerable : true , set : function (val) { freqFontSize = val; freqFont = fontStringPX(freqFontSize,freqFontName); } , get : function () { return freqFontSize; } } , "noteFontName" : { configurable : false , enumerable : true , set : function (val) { noteFontName = val; noteFont = fontStringPX(noteFontSize,noteFontName); } , get : function () { return noteFontName; } } , "freqFontName" : { configurable : false , enumerable : true , set : function (val) { freqFontName = val; freqFont = fontStringPX(freqFontSize,freqFontName); } , get : function () { return freqFontName; } } , "start" : { value : function () { var cents = peek.cents , tuneDir = cents > 0 ? 1 : -1 ; ctx.clearRect(0, 0, width, height); drawSeparator(verticalSepX, ypad, verticalSepX, verticalSepBY); drawArrow(tuneDir); drawFrequency(); drawNoteName(); startID = window.<API key>(this.start.bind(this)); } , enumerable : false , configurable : false , writable : false } , "update" : { value : function (element) { if(!startID){ throw new ReferenceError("Start the view before calling update."); } if (element.peek) { peek = element.peek; } } , enumerable : false , configurable : false , writable : false } }); }
<!doctype html> <html lang="en"> <head> <title>Code coverage report for source/api/packet</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../../prettify.css" /> <link rel="stylesheet" href="../../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../../index.html">All files</a> source/api/packet </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Statements</span> <span class='fraction'>5/5</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Branches</span> <span class='fraction'>0/0</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Functions</span> <span class='fraction'>0/0</span> </div> <div class='fl pad1y space-right2'> <span class="strong">100% </span> <span class="quiet">Lines</span> <span class='fraction'>5/5</span> </div> </div> </div> <div class='status-line high'></div> <div class="pad1"> <table class="coverage-summary"> <thead> <tr> <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> </tr> </thead> <tbody><tr> <td class="file high" data-value="index.js"><a href="index.js.html">index.js</a></td> <td data-value="100" class="pic high"><div class="chart"><div class="cover-fill cover-full" style="width: 100%;"></div><div class="cover-empty" style="width:0%;"></div></div></td> <td data-value="100" class="pct high">100%</td> <td data-value="5" class="abs high">5/5</td> <td data-value="100" class="pct high">100%</td> <td data-value="0" class="abs high">0/0</td> <td data-value="100" class="pct high">100%</td> <td data-value="0" class="abs high">0/0</td> <td data-value="100" class="pct high">100%</td> <td data-value="5" class="abs high">5/5</td> </tr> </tbody> </table> </div><div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Fri Nov 18 2016 22:09:55 GMT+1000 (AEST) </div> </div> <script src="../../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../../sorter.js"></script> </body> </html>
import math import random from direct.showbase.PythonUtil import * from direct.showbase.DirectObject import DirectObject from direct.task import Task from pandac.PandaModules import * from direct.fsm import FSM from direct.distributed import <API key> from otp.avatar import ShadowCaster from otp.otpbase import OTPGlobals from toontown.racing.FlyingGag import FlyingGag from toontown.battle import MovieUtil class Piejectile(DirectObject, FlyingGag): <API key> = 60 maxPhysicsDt = 1.0 physicsDt = 1.0 / float(<API key>) maxPhysicsFrames = maxPhysicsDt * <API key> def __init__(self, sourceId, targetId, type, name): FlyingGag.__init__(self, 'flyingGag', base.race.pie) self.billboard = False self.race = base.race self.scale = 1 self.imHitMult = 1 self.wallCollideTrack = None self.curSpeed = 0 self.acceleration = 0 self.count = 0 self.name = name self.physicsObj = None self.ownerId = sourceId self.targetId = targetId self.ownerAv = None self.ownerKart = None self.hasTarget = 0 self.deleting = 0 self.d2t = 0 self.lastD2t = 0 self.startTime = globalClock.getFrameTime() self.timeRatio = 0 self.maxTime = 8 self.rotH = randFloat(-360, 360) self.rotP = randFloat(-90, 90) self.rotR = randFloat(-90, 90) print 'generating Pie %s' % self.name self.ownerKart = base.cr.doId2do.get(base.race.kartMap.get(sourceId, None), None) if targetId != 0: self.targetKart = base.cr.doId2do.get(base.race.kartMap.get(targetId, None), None) self.hasTarget = 1 if self.ownerId == localAvatar.doId: startPos = self.ownerKart.getPos(render) else: startPos = self.ownerKart.getPos(render) self.setPos(startPos[0], startPos[1], startPos[2]) self.__setupCollisions() self.setupPhysics() self.__enableCollisions() self.forward = NodePath('forward') self.forward.setPos(0, 1, 0) self.splatTaskName = 'splatTask %s' % self.name if self.hasTarget: self.splatTask = taskMgr.doMethodLater(self.maxTime, self.splat, self.splatTaskName) else: self.splatTask = taskMgr.doMethodLater(self.maxTime / 2.5, self.splat, self.splatTaskName) self.reparentTo(render) return def delete(self): print 'removing piejectile' taskMgr.remove(self.taskName) self.__undoCollisions() self.physicsMgr.clearLinearForces() FlyingGag.delete(self) self.deleting = 1 self.ignoreAll() def remove(self): self.delete() def setAvId(self, avId): self.avId = avId def setRace(self, doId): self.race = base.cr.doId2do.get(doId) def setOwnerId(self, ownerId): self.ownerId = ownerId def setType(self, type): self.type = type def setPos(self, x, y, z): <API key>.<API key>.setPos(self, x, y, z) def getVelocity(self): return self.actorNode.getPhysicsObject().getVelocity() def setupPhysics(self): self.physicsMgr = PhysicsManager() self.physicsEpoch = globalClock.getFrameTime() self.lastPhysicsFrame = 0 integrator = <API key>() self.physicsMgr.<API key>(integrator) fn = ForceNode('windResistance') fnp = NodePath(fn) fnp.reparentTo(render) windResistance = LinearFrictionForce(0.2) fn.addForce(windResistance) self.physicsMgr.addLinearForce(windResistance) self.windResistance = windResistance fn = ForceNode('engine') fnp = NodePath(fn) fnp.reparentTo(self) engine = LinearVectorForce(0, 0, 3) fn.addForce(engine) self.physicsMgr.addLinearForce(engine) self.engine = engine self.physicsMgr.attachPhysicalNode(self.node()) self.physicsObj = self.actorNode.getPhysicsObject() ownerAv = base.cr.doId2do[self.ownerId] ownerVel = self.ownerKart.getVelocity() ownerSpeed = ownerVel.length() rotMat = Mat3.rotateMatNormaxis(self.ownerKart.getH(), Vec3.up()) ownerHeading = rotMat.xform(Vec3.forward()) throwSpeed = 50 throwVel = ownerHeading * throwSpeed throwVelCast = Vec3(throwVel[0], throwVel[1], throwVel[2] + 50) self.actorNode.getPhysicsObject().setVelocity(self.ownerKart.getVelocity() + throwVelCast) lookPoint = render.getRelativePoint(self.ownerKart, Point3(0, 10, 0)) self.lookAt(lookPoint) self.taskName = 'updatePhysics%s' % self.name taskMgr.add(self.__updatePhysics, self.taskName, priority=25) def checkTargetDistance(self): if self.hasTarget: return self.getDistance(self.targetKart) else: return 0 def splatTarget(self): if self.targetId == base.localAvatar.getDoId() and base.race.localKart: base.race.localKart.splatPie() self.race.effectManager.addSplatEffect(spawner=self.targetKart, parent=self.targetKart) taskMgr.remove(self.splatTaskName) self.removeNode() def splat(self, optional = None): self.race.effectManager.addSplatEffect(spawner=self) taskMgr.remove(self.splatTaskName) self.removeNode() def __updatePhysics(self, task): if self.deleting: return Task.done self.timeRatio = (globalClock.getFrameTime() - self.startTime) / self.maxTime self.windResistance.setCoef(0.2 + 0.8 * self.timeRatio) if base.cr.doId2do.get(self.targetId) == None: self.hasTarget = 0 self.lastD2t = self.d2t self.d2t = self.checkTargetDistance() if self.hasTarget: targetDistance = self.d2t distMax = 100 if self.d2t > distMax: targetDistance = distMax targetVel = self.targetKart.getVelocity() targetPos = self.targetKart.getPos() targetAim = Point3(targetPos[0] + targetVel[0] * (targetDistance / distMax), targetPos[1] + targetVel[1] * (targetDistance / distMax), targetPos[2] + targetVel[2] * (targetDistance / distMax)) self.lookAt(targetPos) if self.d2t < 7 and self.hasTarget: self.splatTarget() return Task.done self.count += 1 dt = globalClock.getDt() physicsFrame = int((globalClock.getFrameTime() - self.physicsEpoch) * self.<API key>) numFrames = min(physicsFrame - self.lastPhysicsFrame, self.maxPhysicsFrames) self.lastPhysicsFrame = physicsFrame if self.hasTarget: targetVel = self.targetKart.getVelocity() targetSpeed = targetVel.length() if self.d2t - 10 * self.physicsDt > self.lastD2t: self.engine.setVector(Vec3(0, 150 + 150 * self.timeRatio + targetSpeed * (1.0 + 1.0 * self.timeRatio) + self.d2t * (1.0 + 1.0 * self.timeRatio), 12)) else: self.engine.setVector(Vec3(0, 10 + 10 * self.timeRatio + targetSpeed * (0.5 + 0.5 * self.timeRatio) + self.d2t * (0.5 + 0.5 * self.timeRatio), 12)) else: self.engine.setVector(Vec3(0, 100, 3)) for i in xrange(int(numFrames)): pitch = self.gagNode.getP() self.gagNode.setP(pitch + self.rotH * self.physicsDt) roll = self.gagNode.getR() self.gagNode.setR(roll + self.rotP * self.physicsDt) heading = self.gagNode.getH() self.gagNode.setH(heading + self.rotR * self.physicsDt) self.physicsMgr.doPhysics(self.physicsDt) if self.count % 60 == 0: pass return Task.cont def __setupCollisions(self): self.cWallTrav = CollisionTraverser('ProjectileWall') self.cWallTrav.<API key>(True) self.collisionNode = CollisionNode(self.name) self.collisionNode.setFromCollideMask(OTPGlobals.WallBitmask) self.collisionNode.setIntoCollideMask(BitMask32.allOff()) cs = CollisionSphere(0, 0, 0, 7) self.collisionNode.addSolid(cs) sC = self.attachNewNode(self.collisionNode) self.collisionNodePath = NodePath(self.collisionNode) self.wallHandler = <API key>() base.cTrav.addCollider(sC, self.wallHandler) self.wallHandler.addCollider(self.collisionNodePath, self) cRay = CollisionRay(0.0, 0.0, 40000.0, 0.0, 0.0, -1.0) pieFloorRayName = 'pieFloorRay%s' % self.name cRayNode = CollisionNode(pieFloorRayName) cRayNode.addSolid(cRay) cRayNode.setFromCollideMask(OTPGlobals.FloorBitmask) cRayNode.setIntoCollideMask(BitMask32.allOff()) self.cRayNodePath = self.attachNewNode(cRayNode) self.lifter = <API key>() self.lifter.setGravity(32.174 * 3.0) self.lifter.setOffset(OTPGlobals.FloorOffset) self.lifter.setReach(40.0) self.lifter.addCollider(self.cRayNodePath, self) base.cTrav.addCollider(self.cRayNodePath, self.lifter) def __undoCollisions(self): base.cTrav.removeCollider(self.cRayNodePath) def __enableCollisions(self): self.cQueue = [] self.cRays = NodePath('<API key>') self.cRays.reparentTo(self.gag) x = self.gag.getX() y = self.gag.getY() rayNode = CollisionNode('floorcast') ray = CollisionRay(x, y, 40000.0, 0.0, 0.0, -1.0) rayNode.addSolid(ray) rayNode.setFromCollideMask(OTPGlobals.FloorBitmask) rayNode.setIntoCollideMask(BitMask32.allOff()) rayNodePath = self.cRays.attachNewNode(rayNode) cQueue = <API key>() self.cWallTrav.addCollider(rayNodePath, cQueue) self.cQueue.append(cQueue) self.collisionNodePath.reparentTo(self)
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using Uncas.BuildPipeline.Models; using Uncas.BuildPipeline.Repositories; using Uncas.Core.Data; namespace Uncas.BuildPipeline.Tests.Integration.Repositories { [TestFixture] public class <API key> : WithBootstrapping<<API key>> { private int AddPipeline() { var pipeline = new Pipeline(1, "Bla", "1", "bla", DateTime.Now, "bla", "bla"); Resolve<IPipelineRepository>().AddPipeline(pipeline); return pipeline.PipelineId; } [Test] public void <API key>() { const int environmentId = 1; int pipelineId = AddPipeline(); var deployment = new Deployment(pipelineId, environmentId); Sut.AddDeployment(deployment); IEnumerable<Deployment> result = Sut.GetDeployments(pipelineId); Assert.True(result.Any()); } [Test] public void GetByEnvironment_X() { Sut.GetByEnvironment(1); } [Test] public void GetDueDeployments_X() { Sut.GetDueDeployments(new PagingInfo(10)); } [Test] public void <API key>() { int pipelineId = AddPipeline(); var added = new Deployment(pipelineId, 1); Sut.AddDeployment(added); Thread.Sleep(10); added.MarkAsStarted(); int deploymentId = added.DeploymentId.Value; Sut.UpdateDeployment(added); Deployment updated = Sut.GetDeployment(deploymentId); Assert.NotNull(updated.Started); Assert.True(updated.Started > added.Created); } } }
import sys import unittest import six from conans.errors import ConanException from conans.model.options import Options, OptionsValues, PackageOptionValues, PackageOptions, \ <API key> from conans.model.ref import ConanFileReference class OptionsTest(unittest.TestCase): def setUp(self): package_options = PackageOptions.loads("""{static: [True, False], optimized: [2, 3, 4], path: ANY}""") values = PackageOptionValues() values.add_option("static", True) values.add_option("optimized", 3) values.add_option("path", "NOTDEF") package_options.values = values self.sut = Options(package_options) def test_int(self): self.assertEqual(3, int(self.sut.optimized)) def test_in(self): package_options = PackageOptions.loads("{static: [True, False]}") sut = Options(package_options) self.assertTrue("static" in sut) self.assertFalse("shared" in sut) self.assertTrue("shared" not in sut) self.assertFalse("static" not in sut) def <API key>(self): """ Not assigning a value to options will raise an error at validate() step """ package_options = PackageOptions.loads("""{ path: ANY}""") with six.assertRaisesRegex(self, ConanException, <API key>("path")): package_options.validate() package_options.path = "Something" package_options.validate() def <API key>(self): """ The value None is allowed as default, not necessary to default to it """ package_options = PackageOptions.loads('{path: [None, "Other"]}') package_options.validate() package_options = PackageOptions.loads('{path: ["None", "Other"]}') package_options.validate() def items_test(self): self.assertEqual(self.sut.items(), [("optimized", "3"), ("path", "NOTDEF"), ("static", "True")]) self.assertEqual(self.sut.items(), [("optimized", "3"), ("path", "NOTDEF"), ("static", "True")]) def change_test(self): self.sut.path = "C:/MyPath" self.assertEqual(self.sut.items(), [("optimized", "3"), ("path", "C:/MyPath"), ("static", "True")]) self.assertEqual(self.sut.items(), [("optimized", "3"), ("path", "C:/MyPath"), ("static", "True")]) with six.assertRaisesRegex(self, ConanException, "'5' is not a valid 'options.optimized' value"): self.sut.optimized = 5 def boolean_test(self): self.sut.static = False self.assertFalse(self.sut.static) self.assertTrue(not self.sut.static) self.assertTrue(self.sut.static == False) self.assertFalse(self.sut.static == True) self.assertFalse(self.sut.static != False) self.assertTrue(self.sut.static != True) self.assertTrue(self.sut.static == "False") self.assertTrue(self.sut.static != "True") def basic_test(self): boost_values = PackageOptionValues() boost_values.add_option("static", False) boost_values.add_option("thread", True) boost_values.add_option("thread.multi", "off") poco_values = PackageOptionValues() poco_values.add_option("deps_bundled", True) hello1_values = PackageOptionValues() hello1_values.add_option("static", False) hello1_values.add_option("optimized", 4) options = {"Boost": boost_values, "Poco": poco_values, "Hello1": hello1_values} down_ref = ConanFileReference.loads("Hello0/0.1@diego/testing") own_ref = ConanFileReference.loads("Hello1/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "4"), ("path", "NOTDEF"), ("static", "False"), ("Boost:static", "False"), ("Boost:thread", "True"), ("Boost:thread.multi", "off"), ("Poco:deps_bundled", "True")]) boost_values = PackageOptionValues() boost_values.add_option("static", 2) boost_values.add_option("thread", "Any") boost_values.add_option("thread.multi", "on") poco_values = PackageOptionValues() poco_values.add_option("deps_bundled", "What") hello1_values = PackageOptionValues() hello1_values.add_option("static", True) hello1_values.add_option("optimized", "2") options2 = {"Boost": boost_values, "Poco": poco_values, "Hello1": hello1_values} down_ref = ConanFileReference.loads("Hello2/0.1@diego/testing") with six.assertRaisesRegex(self, ConanException, "Hello2/0.1@diego/testing tried to change " "Hello1/0.1@diego/testing option optimized to 2"): self.sut.propagate_upstream(options2, down_ref, own_ref) self.assertEqual(self.sut.values.dumps(), """optimized=4 path=NOTDEF static=False Boost:static=False Boost:thread=True Boost:thread.multi=off Poco:deps_bundled=True""") def <API key>(self): boost_values = PackageOptionValues() boost_values.add_option("static", False) boost_values.add_option("path", "FuzzBuzz") options = {"Boost.*": boost_values} own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "3"), ("path", "FuzzBuzz"), ("static", "False"), ("Boost.*:path", "FuzzBuzz"), ("Boost.*:static", "False"), ]) def multi_pattern_test(self): boost_values = PackageOptionValues() boost_values.add_option("static", False) boost_values.add_option("path", "FuzzBuzz") boost_values2 = PackageOptionValues() boost_values2.add_option("optimized", 2) options = {"Boost.*": boost_values, "*": boost_values2} own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "2"), ("path", "FuzzBuzz"), ("static", "False"), ('*:optimized', '2'), ("Boost.*:path", "FuzzBuzz"), ("Boost.*:static", "False"), ]) def <API key>(self): boost_values = PackageOptionValues() boost_values.add_option("optimized", 4) boost_values2 = PackageOptionValues() boost_values2.add_option("optimized", 2) options = {"Boost.*": boost_values, "*": boost_values2} own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [('optimized', '4'), ('path', 'NOTDEF'), ('static', 'True'), ('*:optimized', '2'), ('Boost.*:optimized', '4')]) def all_positive_test(self): boost_values = PackageOptionValues() boost_values.add_option("static", False) boost_values.add_option("path", "FuzzBuzz") options = {"*": boost_values} own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "3"), ("path", "FuzzBuzz"), ("static", "False"), ("*:path", "FuzzBuzz"), ("*:static", "False"), ]) def pattern_ignore_test(self): boost_values = PackageOptionValues() boost_values.add_option("fake_option", "FuzzBuzz") options = {"Boost.*": boost_values} down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing") own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "3"), ("path", "NOTDEF"), ("static", "True"), ("Boost.*:fake_option", "FuzzBuzz"), ]) def <API key>(self): boost_values = PackageOptionValues() boost_values.add_option("fake_option", "FuzzBuzz") options = {"OpenSSL.*": boost_values} down_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") self.sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(self.sut.values.as_list(), [("optimized", "3"), ("path", "NOTDEF"), ("static", "True"), ("OpenSSL.*:fake_option", "FuzzBuzz"), ]) class <API key>(unittest.TestCase): def <API key>(self): package_options = PackageOptions.loads("""{opt: [None, "a", "b"],}""") values = PackageOptionValues() values.add_option("opt", "a") package_options.values = values sut = Options(package_options) other_options = PackageOptionValues() other_options.add_option("opt", None) options = {"whatever.*": other_options} down_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing") sut.propagate_upstream(options, down_ref, own_ref) self.assertEqual(sut.values.as_list(), [("opt", "a"), ("whatever.*:opt", "None"), ]) def <API key>(self): package_options = PackageOptions.loads("""{opt: [None, "a", "b"],}""") values = PackageOptionValues() package_options.values = values package_options.propagate_upstream({'opt': None}, None, None, []) self.assertEqual(package_options.values.items(), [('opt', 'None'), ]) class OptionsValuesTest(unittest.TestCase): def setUp(self): self.sut = OptionsValues.loads("""static=True optimized=3 Poco:deps_bundled=True Boost:static=False Boost:thread=True Boost:thread.multi=off """) def test_from_list(self): option_values = OptionsValues(self.sut.as_list()) self.assertEqual(option_values.dumps(), self.sut.dumps()) def test_from_dict(self): options_as_dict = dict([item.split('=') for item in self.sut.dumps().splitlines()]) option_values = OptionsValues(options_as_dict) self.assertEqual(option_values.dumps(), self.sut.dumps()) def test_consistency(self): def _check_equal(hs1, hs2, hs3, hs4): opt_values1 = OptionsValues(hs1) opt_values2 = OptionsValues(hs2) opt_values3 = OptionsValues(hs3) opt_values4 = OptionsValues(hs4) self.assertEqual(opt_values1.dumps(), opt_values2.dumps()) self.assertEqual(opt_values1.dumps(), opt_values3.dumps()) self.assertEqual(opt_values1.dumps(), opt_values4.dumps()) # Check that all possible input options give the same result _check_equal([('opt', 3)], [('opt', '3'), ], ('opt=3', ), {'opt': 3}) _check_equal([('opt', True)], [('opt', 'True'), ], ('opt=True', ), {'opt': True}) _check_equal([('opt', False)], [('opt', 'False'), ], ('opt=False', ), {'opt': False}) _check_equal([('opt', None)], [('opt', 'None'), ], ('opt=None', ), {'opt': None}) _check_equal([('opt', 0)], [('opt', '0'), ], ('opt=0', ), {'opt': 0}) _check_equal([('opt', '')], [('opt', ''), ], ('opt=', ), {'opt': ''}) # Check for leading and trailing spaces _check_equal([(' opt ', 3)], [(' opt ', '3'), ], (' opt =3', ), {' opt ': 3}) _check_equal([('opt', ' value ')], [('opt', ' value '), ], ('opt= value ', ), {'opt': ' value '}) # This is expected behaviour: self.assertNotEqual(OptionsValues([('opt', ''), ]).dumps(), OptionsValues(('opt=""', )).dumps()) def test_dumps(self): self.assertEqual(self.sut.dumps(), "\n".join(["optimized=3", "static=True", "Boost:static=False", "Boost:thread=True", "Boost:thread.multi=off", "Poco:deps_bundled=True"])) def test_sha_constant(self): self.assertEqual(self.sut.sha, "<SHA1-like>") self.sut.new_option = False self.sut["Boost"].new_option = "off" self.sut["Poco"].new_option = 0 self.assertEqual(self.sut.dumps(), "\n".join(["new_option=False", "optimized=3", "static=True", "Boost:new_option=off", "Boost:static=False", "Boost:thread=True", "Boost:thread.multi=off", "Poco:deps_bundled=True", "Poco:new_option=0"])) self.assertEqual(self.sut.sha, "<SHA1-like>") def <API key>(self): emsg = "not enough values to unpack" if six.PY3 and sys.version_info.minor > 4 \ else "need more than 1 value to unpack" with six.assertRaisesRegex(self, ValueError, emsg): OptionsValues.loads("a=2\nconfig\nb=3") with six.assertRaisesRegex(self, ValueError, emsg): OptionsValues.loads("config\na=2\ncommit\nb=3") def <API key>(self): emsg = "not enough values to unpack" if six.PY3 and sys.version_info.minor > 4 \ else "need more than 1 value to unpack" with six.assertRaisesRegex(self, ValueError, emsg): OptionsValues("a=2\nconfig\nb=3") with six.assertRaisesRegex(self, ValueError, emsg): OptionsValues(("a=2", "config")) with six.assertRaisesRegex(self, ValueError, emsg): OptionsValues([('a', 2), ('config', ), ]) def <API key>(self): try: OptionsValues.loads("a=2\na=12\nb=3").dumps() OptionsValues(("a=2", "b=23", "a=12")) OptionsValues([('a', 2), ('b', True), ('a', '12')]) except Exception as e: self.fail("Not expected exception: {}".format(e)) def <API key>(self): self.assertEqual(OptionsValues([('pck2:opt', 50), ]).dumps(), OptionsValues([('pck2 :opt', 50), ]).dumps())
package brave.example; import okhttp3.OkHttpClient; import org.springframework.boot.web.client.<API key>; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.<API key>; import org.springframework.web.client.RestTemplate; /** The application is simple, it only uses Web MVC and a {@linkplain RestTemplate}. */ @Configuration public class <API key> { @Bean <API key> useOkHttpClient(final OkHttpClient okHttpClient) { return new <API key>() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(new <API key>(okHttpClient)); } }; } }
#!/bin/sh # CYBERWATCH SAS - 2016 # Security fix for RHSA-2009:0457 # Operating System: Red Hat 5 # Architecture: x86_64 # - libwmf.x86_64:0.2.8.3-5.8 # - libwmf-debuginfo.x86_64:0.2.8.3-5.8 # - libwmf-devel.x86_64:0.2.8.3-5.8 # - libwmf.x86_64:0.2.8.4-10.2 # - libwmf-debuginfo.x86_64:0.2.8.4-10.2 # - libwmf-devel.x86_64:0.2.8.4-10.2 # - libwmf.i386:0.2.8.3-5.8 # - libwmf-debuginfo.i386:0.2.8.3-5.8 # - libwmf.i386:0.2.8.4-10.2 # - libwmf-debuginfo.i386:0.2.8.4-10.2 # - libwmf-devel.i386:0.2.8.4-10.2 # Last versions recommanded by security team: # - libwmf.x86_64:0.2.8.4-10.2 # - libwmf-debuginfo.x86_64:0.2.8.4-10.2 # - libwmf-devel.x86_64:0.2.8.4-10.2 # - libwmf.x86_64:0.2.8.4-10.2 # - libwmf-debuginfo.x86_64:0.2.8.4-10.2 # - libwmf-devel.x86_64:0.2.8.4-10.2 # - libwmf.i386:0.2.8.4-10.2 # - libwmf-debuginfo.i386:0.2.8.4-10.2 # - libwmf.i386:0.2.8.4-10.2 # - libwmf-debuginfo.i386:0.2.8.4-10.2 # - libwmf-devel.i386:0.2.8.4-10.2 # CVE List: # - CVE-2009-1364 # More details: sudo yum install libwmf.x86_64-0.2.8.4 -y sudo yum install libwmf-debuginfo.x86_64-0.2.8.4 -y sudo yum install libwmf-devel.x86_64-0.2.8.4 -y sudo yum install libwmf.x86_64-0.2.8.4 -y sudo yum install libwmf-debuginfo.x86_64-0.2.8.4 -y sudo yum install libwmf-devel.x86_64-0.2.8.4 -y sudo yum install libwmf.i386-0.2.8.4 -y sudo yum install libwmf-debuginfo.i386-0.2.8.4 -y sudo yum install libwmf.i386-0.2.8.4 -y sudo yum install libwmf-debuginfo.i386-0.2.8.4 -y sudo yum install libwmf-devel.i386-0.2.8.4 -y
# Scrup [<img src="http: Take a screenshot in OS X and have a URL to the picture in your pasteboard a second later. *A free and open source version of the different commercial variants (GrabUp, Tiny Grab, etc).* For Mac OS X 10.6 Snow Leopard. ## Download & install - [Download Scrup](http://hunch.se/scrup/dist/scrup-1.3.2.zip) - Move Scrup to your Applications folder and double-click the bastard. - Scrup appears in the top right corner of your screen and looks like a twirly hand with and arrow. Click it and select "Preferences..." - In the "Receiver URL" text field, enter the URL to something which receives files. For instance a copy of [`recv.php`](http://github.com/rsms/scrup/blob/master/recv.php) which you have uploaded to your server. - Please note that the recv.php requires php5 to work, since it's using the PHP5-only <API key>() function to grab the image data stream. - Take a screenshot and you should see the Scrup icon turning into a check mark, indicating success. (If you see a red badge something failed. Open Console.app and look what Scrup says.) ## Receivers & extensions - **[django-scrup](http://github.com/idangazit/django-scrup/)** is a Django-based web receiver which stores screen captures on Amazon S3. - **[Indexr](http: ## Alternate versions There are a few forks (alternate versions) of Scrup (e.g. adding Growl support, playing sounds, etc) which might be interesting. Check out [the fork network](http://github.com/rsms/scrup/network) for a list of these variants. ## Details - Lives in the menu bar (up there to your right, where the clock is). - When a screenshot is taken, Scrup simply performs a `HTTP POST`, sending the image. - After the screenshot has been sent, the server replies with the URL to the newly uploaded file. - The URL is placed in the pasteboard, ready for you to ⌘V somewhere. There is an example PHP implementation called [`recv.php`](http://github.com/rsms/scrup/blob/master/recv.php) which you can use and/or modify to setup your receiver. Make sure to set your URL in the preferences. ## Building You'll need libpngcrush to build Scrup. libpngcrush is an external submodule of Scrup which you'll need to update after you've checked out the scrup source: cd scrup-source git submodule update --init pngcrush You only need to do this once. Now, build Scrup in Xcode. ## Authors - Rasmus Andersson <http://hunch.se/> Open source licensed under MIT (see _LICENSE_ file for details).
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { mc1 Console.WriteLine("Hi GitGraken"); Console.WriteLine("Hi Again"); Console.WriteLine("master change"); master change2; branch3 change1 <<<< HEAD b4 c1 Console.ReadLine();b ==== Console.ReadLine(); >>>> parent of e2d696c... b4c1 } } }
<?php namespace MilesAsylum\Schnoop; use MilesAsylum\Schnoop\Exception\SchnoopException; use MilesAsylum\Schnoop\Inspector\InspectorInterface; use MilesAsylum\Schnoop\Inspector\MySQLInspector; use MilesAsylum\Schnoop\SchemaAdapter\MySQL\Database; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Column\ColumnFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Constraint\ForeignKeyFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Constraint\IndexFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Database\DatabaseFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\DataType\DataTypeFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Routine\FunctionFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Routine\ParametersFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Routine\ParametersLexer; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Routine\ParametersParser; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Routine\ProcedureFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\SchemaBuilder; use MilesAsylum\Schnoop\SchemaFactory\MySQL\<API key>; use MilesAsylum\Schnoop\SchemaFactory\MySQL\SetVar\SqlModeFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Table\TableFactory; use MilesAsylum\Schnoop\SchemaFactory\MySQL\Trigger\TriggerFactory; use PDO; class Schnoop { /** * @var InspectorInterface */ protected $dbInspector; /** * @var <API key> */ protected $dbBuilder; /** * @var Database[] */ protected $loadedDatabase = []; /** * Schnoop constructor. */ public function __construct( InspectorInterface $dbInspector, <API key> $dbBuilder ) { $this->dbInspector = $dbInspector; $this->dbBuilder = $dbBuilder; $this->dbBuilder->setSchnoop($this); } /** * Get the list of database names on the server. * * @return array database names */ public function getDatabaseList() { return $this->dbInspector->fetchDatabaseList(); } /** * Check if the named database exists on the server. * * @param string $databaseName * * @return bool true if the database exists */ public function hasDatabase($databaseName) { return in_array($databaseName, $this->dbInspector->fetchDatabaseList()); } /** * Get a database from the server. * * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return Database * * @throws SchnoopException */ public function getDatabase($databaseName = null) { if (null === $databaseName) { $databaseName = $this-><API key>(); } if (!isset($this->loadedDatabase[$databaseName])) { if ($this->hasDatabase($databaseName)) { $this->loadedDatabase[$databaseName] = $this->dbBuilder->fetchDatabase($databaseName); } } return isset($this->loadedDatabase[$databaseName]) ? $this->loadedDatabase[$databaseName] : null; } /** * The the list of table names for the database. * * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return array Table names */ public function getTableList($databaseName = null) { $tableList = null; $databaseName = $this-><API key>($databaseName); $tableList = $this->dbInspector->fetchTableList($databaseName); return $this->dbInspector->fetchTableList($databaseName); } /** * Get a table from the database. * * @param string $tableName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return SchemaAdapter\MySQL\TableInterface */ public function getTable($tableName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return $this->dbBuilder->fetchTable($tableName, $databaseName); } /** * Check if a table exists in the database. * * @param string $tableName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return bool true if the table exists */ public function hasTable($tableName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return in_array($tableName, $this->dbInspector->fetchTableList($databaseName)); } /** * Check if a table has any triggers. * * @param string $tableName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return bool true if the table has triggers */ public function hasTriggers($tableName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); $this->ensureTableExists($tableName, $databaseName); return (bool) count($this->dbInspector->fetchTriggerList($databaseName, $tableName)); } /** * Get all the triggers for a table. * * @param string $tableName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return SchemaAdapter\MySQL\TriggerInterface[] */ public function getTriggers($tableName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); $this->ensureTableExists($tableName, $databaseName); return $this->dbBuilder->fetchTriggers($tableName, $databaseName); } /** * Check if the function exists in the database. * * @param string $functionName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return bool true if the function exists */ public function hasFunction($functionName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return in_array($functionName, $this->dbInspector->fetchFunctionList($databaseName)); } /** * Get a function from the database. * * @param string $functionName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return SchemaAdapter\MySQL\<API key> */ public function getFunction($functionName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return $this->dbBuilder->fetchFunction($functionName, $databaseName); } /** * Check if the named procedure exists in the database. * * @param string $procedureName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return bool true if the named procedure exists */ public function hasProcedure($procedureName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return in_array($procedureName, $this->dbInspector->fetchProcedureList($databaseName)); } /** * Get the named procedure from the database. * * @param string $procedureName * @param string|null $databaseName The database name. Do not supply a name to get the currently active database. * * @return SchemaAdapter\MySQL\<API key> */ public function getProcedure($procedureName, $databaseName = null) { $databaseName = $this-><API key>($databaseName); return $this->dbBuilder->fetchProcedure($procedureName, $databaseName); } /** * Get the PDO connection used to schnoop the database. * * @return PDO */ public function getPDO() { return $this->dbInspector->getPDO(); } /** * Factory for constructing this object. * * @return Schnoop */ public static function createSelf(PDO $pdo) { $dataTypeFactory = DataTypeFactory::createSelf(); $sqlModeFactory = new SqlModeFactory(); $paramsFactory = new ParametersFactory( new ParametersParser(new ParametersLexer()), $dataTypeFactory ); return new self( new MySQLInspector( $pdo ), new SchemaBuilder( new DatabaseFactory($pdo), new TableFactory($pdo), new ColumnFactory($pdo, $dataTypeFactory), new IndexFactory($pdo), new ForeignKeyFactory($pdo), new TriggerFactory($pdo, $sqlModeFactory), new FunctionFactory($pdo, $paramsFactory, $sqlModeFactory, $dataTypeFactory), new ProcedureFactory($pdo, $paramsFactory, $sqlModeFactory) ) ); } /** * Checks if the current database exists and throw an exception if it does * not. If a database is not supplied it will check for an active database * and throw an exception if one is not set. * * @param string|null $databaseName * * @return string the supplied database name, or the active database if a database name is not supplied */ protected function <API key>($databaseName = null) { if (null === $databaseName) { $databaseName = $this-><API key>(); } else { $this-><API key>($databaseName); } return $databaseName; } /** * Fetch the name of the active/selected database, and throw an exception if a database is not selected. * * @return string name of the active/selected database * * @throws SchnoopException */ protected function <API key>() { $databaseName = $this->dbInspector->fetchActiveDatabase(); if (empty($databaseName)) { throw new SchnoopException('Database not specified and an active database has not been set.'); } return $databaseName; } /** * Checks if the named database exists on the server and throw an exception if it does not. * * @param string $databaseName * * @throws SchnoopException */ protected function <API key>($databaseName) { if (!$this->hasDatabase($databaseName)) { throw new SchnoopException("A database named '$databaseName' does not exist."); } } /** * Checks if the named table exists in the database and throw an exception if it does not. * * @param string $tableName * @param string $databaseName * * @throws SchnoopException */ protected function ensureTableExists($tableName, $databaseName) { if (!$this->hasTable($tableName, $databaseName)) { throw new SchnoopException("A table named '$tableName' does not exist in database '$databaseName'."); } } }
/** * Lists all the projects on the system. * @param req * @param res */ exports.list = function(req, res) { res.render('project/index', { title: 'Express' }); } /** * Create a new project */ exports.add = function(req, res) {} /** * Delete an existing project */ exports.delete = function(req, res) {}
#modal-content { position: fixed; top: 50px; border: solid 1px #DEDEDE; width: 100%; height: 300px; right: 0px; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); border-radius: 4px; } #modal-content .header { position: absolute; top: 0px; left: 0px; width: 100%; height: 50px; padding: 20px 20px; background-color: #fff; border-bottom: 1px solid #e4eaec; } #modal-content .header .title { position: absolute; } #modal-content .header .news span { border-radius: 1em; border: 1px solid #57c7d4; padding: 2px; font-weight: bold; font-size: smaller; color: white; background-color: #57c7d4; } #modal-content .header .news { position: absolute; right: 0px; top: 20px; padding-right: 10px; } #modal-content .content { position: absolute; top: 50px; left: 0px; width: 100%; } #modal-content .footer { background-color: #f3f7f9; border-top: 1px solid #e4eaec; padding: 20px 20px; position: absolute; bottom: 0px; left: 0px; width: 100%; height: 50px; } #modal-content .footer a { color: #89A7BB; } @media (min-width: 992px) { #modal-content { width: 300px; top: 65px; } }
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { Provider } from 'react-redux'; import { RouterContext, match } from 'react-router'; import * as eventService from './api/service/event'; import configureStore from '../universal/store'; import routes from '../universal/routes'; import DevTools from '../universal/containers/devTools'; const isDev = (process.env.NODE_ENV !== 'production'); export function handleRender(req, res) { console.log(' [x] Request for', req.url); eventService.getEvents() .then(initialEvents => { let initialState = {pulseApp: { events: initialEvents, userId: 'baseUser'} }; const store = configureStore(req, initialState); // Wire up routing based upon routes match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { if (error || !renderProps) { if (req.url === '/bundle.js') { console.log(' | Hold up, are you sure you are hitting the app at http://localhost:3001?'); console.log(' | On development bundle.js is served by the Webpack Dev Server and so you need to hit the app on port 3001, not port 3000.'); } console.log((error) ? error : 'Error: No matching universal route found'); res.status(400); res.send((error) ? error : 'Error: No matching universal route found'); return; } if (redirectLocation) { res.redirect(redirectLocation); return; } const devTools = (isDev) ? <DevTools /> : null; // Render the component to a string const html = ReactDOMServer.renderToString( <Provider store={store}> <div> <RouterContext {...renderProps} /> {devTools} </div> </Provider> ); // Send the rendered page back to the client with the initial state res.render('index', { isProd: (!isDev), html: html, initialState: JSON.stringify(store.getState()) }); }); }); }
using System; using System.Collections.Generic; using Blocks; using spaar.ModLoader; using spaar.Mods.Automatron.Actions; using TheGuysYouDespise; using UnityEngine; namespace spaar.Mods.Automatron { public class AutomatronMod : BlockMod { public override string Name { get; } = "automatron"; public override string DisplayName { get; } = "Automatron"; public override string Author { get; } = "spaar"; public override Version Version { get; } = new Version(1, 1, 7); public override string VersionExtra { get; } = ""; public override string BesiegeVersion { get; } = "v0.45"; public override bool CanBeUnloaded { get; } = false; public override bool Preload { get; } = false; private Block automatronBlock = new Block() .ID(410) .BlockName("Automatron") .Obj(new List<Obj> { new Obj("Automatron.obj", "Automatron.png", new VisualOffset(new Vector3(0.48f, 0.48f, 0.48f), new Vector3(0.0f, 0.0f, 0.5f), new Vector3(180f, 180f, 0f))) }) .IconOffset(new Icon( new Vector3(1.0f, 1.0f, 1.0f), new Vector3(0.0f, 0f, 0f), new Vector3(360f, 70f, 300f))) .Components(new[] { typeof(AutomatronBlock) }) .Properties(new BlockProperties().SearchKeywords(new[] { "Automatron", "Automation" })) .Mass(1.5f) .ShowCollider(false) .CompoundCollider(new List<ColliderComposite> { ColliderComposite.Box(new Vector3(1.00f, 1.00f, 1.00f), new Vector3(0, 0, 0.5f), new Vector3(0, 0, 0)) }) .<API key>() .NeededResources(new List<NeededResource>()) .AddingPoints(new List<AddingPoint>()); public override void OnLoad() { LoadBlock(automatronBlock); ActionPressKey.StartKeySim(); } public override void OnUnload() { Configuration.Save(); ActionPressKey.StopKeySim(); } } }
# bench_tool Bench_tool is a small script that helps you perform small benchmarks for testing the performance of your applications. The applications can be written in any language, provided there is a Makefile that is able to build the application. It measures both the CPU time and the memory usage. Version: 1.1 Copyright (c) 2015, Lucian Radu Teodorescu. ## Using the bench_tool To use this tool one must carefully arrange the tests/programs in a specified folder structure, providing enough information on how the programs should be run. If the proper folder structure is followed, the tool will run smoothly without any additional input from the user. There are three main concepts that the user needs to know when using this tool: - **tests**: these are independents sets of things that should be benchmarked in isolation; different tests will not have any connection between them; each test will be represented by a directory - **programs**; the actual executables that will be run in order to do the benchmark measurements; a test typically contains multiple programs; the list of programs is specified in a file named `programs.in` for each test directory - **run arguments**: this will contain the list of parameters that need to be applied to the programs when they are executed; a test will typically contain one or more sets of run arguments; the run arguments are specified in a file named `args.in` for each test directory Folder structure To use the tool, certain folder structure rules may be followed. Here is a typical folder structure for a benchmark consisting of different tests: - **bench_tool** - **results** - **tmp** - ... - results_testA.csv - results_testA.log - results_testB.csv - results_testB.log - **tests** - **testA** - args.in - programs.in - prog1.c - prog1.out - prog2.cpp - prog2.out - Makefile - **testB** - args.in - programs.in - prog1.c - prog1.out - prog2.cpp - prog2.out - Makefile - bench_tool.py - config.py # The `tests` folder The **tests** folder is the folder in which the tests and programs should be placed. The tool is able to run multiple tests, each containing a set of programs to be tested. Different tests typically consists of different sets of programs, so the measurements are aggregated per test. The tests in the example folder are `testA` and `testB`. To add a new test, create a new folder inside the `tests` folder. Each test folder should contain at least two files: `programs.in` and `args.in`. The first contains the programs that will be invoked for the test and the latter contains the set of arguments needed. Each line of the `programs.in` file will contain a program to be invoked. This does not need to be an executable, it can also be a command line. For example, to invoke a Java program, one can add a line that looks as following: `java -server -Xss15500k -classpath src/main MainProgram`. The format of the file should look like the following: ./progam1.out ./progam2.out # A comment line starts with '#' (must be first character, no spaces allowed before it) complex command line program_name:command As seen, from the previous examples one can add comments if the first character of the line is `#`. Also, if the command line becomes too complex one can give names to programs. Similarly, int the `args.in` file one needs to specify the running arguments of the programs, one set of arguments per line. Comments are also possible with the `#` characters, but names cannot be given to argument sets. For each test the tool will try to *build* the programs before running them. For this it will invoke a `make` command in the test directory, so therefore a `Makefile` file needs to be provided. Based on the configuration parameters, the tool will typically invoke `make clean` before `make`. If there is only one test in the benchmark, the user may choose not to create a dedicated test folder, and put the test data (`run` folder, programs and makefile) directly under the main `tests` folder. # The `results` folder The **results** folder will contain the results of the benchmark execution. It will contain the compilation logs, the execution logs and the timing results. The benchmark will record both the execution time and the maximum memory usage. For each test _X_, the aggregated timing results will be put in the `results_X.csv` file. This file will contain the average of execution of each program with each set of arguments for multiple runs, together with the standard deviation (both for execution time and memory). The execution time and used memory for each program run will be placed in the `results_X.log` file The compilation log can be found in file `tmp/comp_testName.log`. The output for each program execution (each program x each argument set x number of runs) will be placed in the `tmp` folder as well, inside files ending in `.run.log`. # Configuration file Near the `bench_tool.py` script, there is a special script called `config.py` containing configuration parameters. One can set here the number of program run repetitions, the timeout for each program execution and whether to perform a `make clean` before building the programs. Ignoring tests, programs and run arguments To ignore a test from running in the benchmark, simply rename the test and make it start with a dot (e.g., `.testA`). The tool will not consider the test at all.
<?php namespace App\Models; use App\Models\Task; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get all of the tasks for the user. */ public function tasks() { return $this->hasMany(Task::class); } }
using Microsoft.Win32; using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; using System; using System.Diagnostics; namespace PdfReportHandling { public class ReportHandler { private static Document document; private static string filename; public static void GenerateReport() { document = ReportDocument.CreateDocument(); PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always); renderer.Document = document; renderer.RenderDocument(); // Save the document... SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = "Transportation report - " + DateTime.Now.ToShortDateString(); // Default file name dlg.DefaultExt = ".pdf"; // Default file extension dlg.Filter = "PDF documents (.pdf)|*.pdf"; // Filter files by extension // Show save file dialog box bool? result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Save document filename = dlg.FileName; } try { renderer.PdfDocument.Save(filename); Process.Start(filename); } catch (Exception) { } // ...and start a viewer. } } }
require 'active_record' require 'yaml' require 'cgi' require 'riddle' require 'thinking_sphinx/auto_version' require 'thinking_sphinx/core/array' require 'thinking_sphinx/core/string' require 'thinking_sphinx/property' require 'thinking_sphinx/active_record' require 'thinking_sphinx/association' require 'thinking_sphinx/attribute' require 'thinking_sphinx/configuration' require 'thinking_sphinx/context' require 'thinking_sphinx/excerpter' require 'thinking_sphinx/facet' require 'thinking_sphinx/class_facet' require 'thinking_sphinx/facet_search' require 'thinking_sphinx/field' require 'thinking_sphinx/index' require 'thinking_sphinx/source' require 'thinking_sphinx/rails_additions' require 'thinking_sphinx/search' require 'thinking_sphinx/search_methods' require 'thinking_sphinx/deltas' require 'thinking_sphinx/adapters/abstract_adapter' require 'thinking_sphinx/adapters/mysql_adapter' require 'thinking_sphinx/adapters/postgresql_adapter' ActiveRecord::Base.send(:include, ThinkingSphinx::ActiveRecord) Merb::Plugins.add_rakefiles( File.join(File.dirname(__FILE__), "thinking_sphinx", "tasks") ) if defined?(Merb) module ThinkingSphinx # A ConnectionError will get thrown when a connection to Sphinx can't be # made. class ConnectionError < StandardError end # A StaleIdsException is thrown by Collection.<API key> if there # are records in Sphinx but not in the database, so the search can be retried. class StaleIdsException < StandardError attr_accessor :ids def initialize(ids) self.ids = ids end end # The current version of Thinking Sphinx. # @return [String] The version number as a string def self.version open(File.join(File.dirname(__FILE__), '../VERSION')) { |f| f.read.strip } end # The collection of indexed models. Keep in mind that Rails lazily loads # its classes, so this may not actually be populated with _all_ the models # that have Sphinx indexes. def self.context if Thread.current[:<API key>].nil? Thread.current[:<API key>] = ThinkingSphinx::Context.new Thread.current[:<API key>].prepare end Thread.current[:<API key>] end def self.reset_context! Thread.current[:<API key>] = nil end def self.<API key>(offset = nil) "* #{context.indexed_models.size} + #{offset || 0}" end # Check if index definition is disabled. def self.define_indexes? if Thread.current[:<API key>].nil? Thread.current[:<API key>] = true end Thread.current[:<API key>] end # Enable/disable indexes - you may want to do this while migrating data. # ThinkingSphinx.define_indexes = false def self.define_indexes=(value) Thread.current[:<API key>] = value end # Check if delta indexing is enabled. def self.deltas_enabled? if Thread.current[:<API key>].nil? Thread.current[:<API key>] = ( ThinkingSphinx::Configuration.environment != "test" ) end Thread.current[:<API key>] end # Enable/disable all delta indexing. # ThinkingSphinx.deltas_enabled = false def self.deltas_enabled=(value) Thread.current[:<API key>] = value end # Check if updates are enabled. True by default, unless within the test # environment. def self.updates_enabled? if Thread.current[:<API key>].nil? Thread.current[:<API key>] = ( ThinkingSphinx::Configuration.environment != "test" ) end Thread.current[:<API key>] end # Enable/disable updates to Sphinx # ThinkingSphinx.updates_enabled = false def self.updates_enabled=(value) Thread.current[:<API key>] = value end def self.<API key>? Thread.current[:<API key>] ||= false end def self.<API key>=(value) Thread.current[:<API key>] = value end # Checks to see if MySQL will allow simplistic GROUP BY statements. If not, # or if not using MySQL, this will return false. def self.<API key>? if Thread.current[:<API key>].nil? Thread.current[:<API key>] = !!( mysql? && ::ActiveRecord::Base.connection.select_all( "SELECT @@global.sql_mode, @@session.sql_mode;" ).all? { |key,value| value.nil? || value[/ONLY_FULL_GROUP_BY/].nil? } ) end Thread.current[:<API key>] end # An indication of whether Sphinx is running on a remote machine instead of # the same machine. def self.remote_sphinx? Thread.current[:<API key>] ||= false end # Tells Thinking Sphinx that Sphinx is running on a different machine, and # thus it can't reliably guess whether it is running or not (ie: the # #sphinx_running? method), and so just assumes it is. # Useful for multi-machine deployments. Set it in your production.rb file. # ThinkingSphinx.remote_sphinx = true def self.remote_sphinx=(value) Thread.current[:<API key>] = value end # Check if Sphinx is running. If remote_sphinx is set to true (indicating # Sphinx is on a different machine), this will always return true, and you # will have to handle any connection errors yourself. def self.sphinx_running? remote_sphinx? || <API key>? end # Check if Sphinx is actually running, provided the pid is on the same # machine as this code. def self.<API key>? !!sphinx_pid && pid_active?(sphinx_pid) end def self.sphinx_pid if File.exists?(ThinkingSphinx::Configuration.instance.pid_file) File.read(ThinkingSphinx::Configuration.instance.pid_file)[/\d+/] else nil end end def self.pid_active?(pid) !!Process.kill(0, pid.to_i) rescue Exception => e false end def self.microsoft? RUBY_PLATFORM =~ /mswin/ end def self.jruby? defined?(JRUBY_VERSION) end def self.mysql? ::ActiveRecord::Base.connection.class.name.demodulize == "MysqlAdapter" || ::ActiveRecord::Base.connection.class.name.demodulize == "MysqlplusAdapter" || ( jruby? && ::ActiveRecord::Base.connection.config[:adapter] == "jdbcmysql" ) end extend ThinkingSphinx::SearchMethods::ClassMethods end ThinkingSphinx::AutoVersion.detect
package org.sittingbull.gt.util; /** * * Compute the machine epsilon for the float and double types, the largest positive * floating-point value that, when added to 1, results in a value equal to 1 due to * roundoff. * * Reference: Java Number Cruncher * The Java Programmer's Guide to Numerical Computing (By Ronald Mak) * Chapter 3.9: The Machine Epsilon * */ public final class MachineEpsilon { private static final float floatEpsilon; private static final double doubleEpsilon; static { // Loop to compute the float epsilon value. float fTemp = 0.5f; while (1 + fTemp > 1) fTemp /= 2; floatEpsilon = fTemp; // Loop to compute the double epsilon value. double dTemp = 0.5; while (1 + dTemp > 1) dTemp /= 2; doubleEpsilon = dTemp; }; /** * Return the float epsilon value. * @returns the value */ public static float floatValue() { return floatEpsilon; } /** * Return the double epsilon value. * @returns the value */ public static double doubleValue() { return doubleEpsilon; } }
package net.instant.util.argparse; /* This interface adorns Processor with a type variable to allow the "typesafe * map" pattern to be used in ParseResult; at the same time, it neatly * distinguishes those Processor subclasses that can be usefully used as * ParseResult keys. */ public interface ValueProcessor<T> extends Processor {}
package localEngine import ( "github.com/microscaling/microscaling/demand" ) func scalingCalculation(tasks *demand.Tasks) (demandChanged bool) { delta := 0 demandChanged = false // Work out the ideal scale for all the services for _, t := range tasks.Tasks { t.IdealContainers = t.Running + t.Target.Delta(t.Metric.Current()) log.Debugf(" [scale] ideal for %s priority %d would be %d. %d running, %d requested", t.Name, t.Priority, t.IdealContainers, t.Running, t.Requested) } available := tasks.CheckCapacity() log.Debugf(" [scale] available space: %d", available) // Look for services we could scale down, in reverse priority order tasks.PrioritySort(true) for _, t := range tasks.Tasks { if !t.IsScalable || t.Requested == t.MinContainers { // Can't scale this service down continue } if t.Running != t.Requested { // There's a scale operation in progress log.Debugf(" [scale] %s already scaling: running %d, requested %d", t.Name, t.Running, t.Requested) continue } // For scaling down, delta should be negative delta = t.ScaleDownCount() if delta < 0 { t.Demand = t.Running + delta demandChanged = true available += (-delta) log.Debugf(" [scale] scaling %s down by %d", t.Name, delta) } } // Now look for tasks we need to scale up tasks.PrioritySort(false) for p, t := range tasks.Tasks { if !t.IsScalable { continue } if t.Running != t.Requested { // There's a scale operation in progress log.Debugf(" [scale] %s already scaling: running %d, requested %d", t.Name, t.Running, t.Requested) continue } delta = t.ScaleUpCount() if delta <= 0 { continue } log.Debugf(" [scale] would like to scale up %s by %d - available %d", t.Name, delta, available) if available < delta { // If this is a task that fills the remainder, there's no need to exceed capacity if !t.IsRemainder() { log.Debugf(" [scale] looking for %d additional capacity by scaling down:", delta-available) index := len(tasks.Tasks) freedCapacity := available for index > p+1 && freedCapacity < delta { // Kill off lower priority services if we need to index <API key> := tasks.Tasks[index] if <API key>.Priority > t.Priority { log.Debugf(" [scale] looking for capacity from %s: running %d requested %d demand %d", <API key>.Name, <API key>.Running, <API key>.Requested, <API key>.Demand) scaleDownBy := <API key>.CanScaleDown() if scaleDownBy > 0 { if scaleDownBy > (delta - freedCapacity) { scaleDownBy = delta - freedCapacity } <API key>.Demand = <API key>.Running - scaleDownBy demandChanged = true log.Debugf(" [scale] Service %s priority %d scaling down %d", <API key>.Name, <API key>.Priority, -scaleDownBy) freedCapacity = freedCapacity + scaleDownBy } } } } // We might still not have enough capacity and we haven't waited for scale down to complete, so just scale up what's available now delta = available log.Debugf(" [scale] Can only scale %s by %d", t.Name, delta) } if delta > 0 { demandChanged = true available -= delta if t.Demand >= t.MaxContainers { log.Errorf(" [scale ] Limiting %s to its configured max %d", t.Name, t.MaxContainers) t.Demand = t.MaxContainers } else { log.Debugf(" [scale] Service %s scaling up %d", t.Name, delta) t.Demand = t.Running + delta } } } return demandChanged }
<?php /* TwigBundle:Exception:error.rdf.twig */ class <API key> extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 $this->env->loadTemplate("TwigBundle:Exception:error.xml.twig")->display(array_merge($context, array("exception" => $this->getContext($context, "exception")))); } public function getTemplateName() { return "TwigBundle:Exception:error.rdf.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 25 => 5, 19 => 1, 79 => 21, 72 => 13, 69 => 12, 47 => 18, 40 => 11, 37 => 10, 22 => 2, 246 => 32, 157 => 56, 145 => 46, 139 => 45, 131 => 42, 123 => 41, 120 => 40, 115 => 39, 111 => 38, 108 => 37, 101 => 33, 98 => 32, 96 => 31, 83 => 25, 74 => 14, 66 => 11, 55 => 16, 52 => 21, 50 => 14, 43 => 9, 41 => 8, 35 => 9, 32 => 9, 29 => 6, 209 => 82, 203 => 78, 199 => 76, 193 => 73, 189 => 71, 187 => 70, 182 => 68, 176 => 64, 173 => 63, 168 => 62, 164 => 58, 162 => 57, 154 => 54, 149 => 51, 147 => 50, 144 => 49, 141 => 48, 133 => 42, 130 => 41, 125 => 38, 122 => 37, 116 => 36, 112 => 35, 109 => 34, 106 => 36, 103 => 32, 99 => 30, 95 => 28, 92 => 29, 86 => 24, 82 => 22, 80 => 24, 73 => 19, 64 => 19, 60 => 6, 57 => 12, 54 => 22, 51 => 10, 48 => 9, 45 => 17, 42 => 16, 39 => 6, 36 => 5, 33 => 4, 30 => 3,); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RemotyMPC81.Classes { static class Commands { public static Dictionary<string, string> ButtonActions = new Dictionary<string, string>{ {"PlayButton", "887"}, {"btnPrevious", "901"}, {"btnNext", "902"}, {"btnPreviousChapter", "921"}, {"btnNextChapter", "922"}, {"btnVolumeUp", "907"}, {"btnVolumeDown", "908"}, {"btn_volumeMute", "909"}, {"btnFullscreen", "830"}, {"btnSubtitleRew", "24001"}, {"btnSubtitleFwd", "24000"}, {"PauseButton", "888"}, {"shutdown", "915"}, {"seek", "-1"} }; public static string GetCommand(string action) { // Try to get the result in the static Dictionary string result; if (ButtonActions.TryGetValue(action, out result)) { return result; } else { return null; } } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_65) on Tue Nov 24 14:22:17 CST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>com.olemob.paysdk.interfaces (OlePaySDK-iAppPay)</title> <meta name="date" content="2015-11-24"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../com/olemob/paysdk/interfaces/package-summary.html" target="classFrame">com.olemob.paysdk.interfaces</a></h1> <div class="indexContainer"> <h2 title=""></h2> <ul title=""> <li><a href="InitCallback.html" title="com.olemob.paysdk.interfaces" target="classFrame"><span class="interfaceName">InitCallback</span></a></li> <li><a href="IOrderManager.html" title="com.olemob.paysdk.interfaces" target="classFrame"><span class="interfaceName">IOrderManager</span></a></li> <li><a href="OrderCallback.html" title="com.olemob.paysdk.interfaces" target="classFrame"><span class="interfaceName">OrderCallback</span></a></li> <li><a href="OrderStateCallback.html" title="com.olemob.paysdk.interfaces" target="classFrame"><span class="interfaceName">OrderStateCallback</span></a></li> <li><a href="PayResultCallback.html" title="com.olemob.paysdk.interfaces" target="classFrame"><span class="interfaceName">PayResultCallback</span></a></li> </ul> </div> </body> </html>
package fr.atelechev.chess.fen2cb.service; import javax.ws.rs.ext.Provider; import fr.atelechev.chess.fen2cb.exception.<API key>; import fr.atelechev.util.web.<API key>; @Provider public class <API key> extends <API key> { @Override protected void traceException(Exception exception) { if (!(exception instanceof <API key>)) { LOGGER.error(EXCEPTION_TRACE, exception); } else { LOGGER.debug(EXCEPTION_TRACE, exception); } } @Override protected int <API key>(Exception ex) { if (ex instanceof <API key>) { return 400; } return -1; } }
package model.order; import model.Entity; import java.sql.Timestamp; public class SetupProvider extends Entity { private String providerId; private String providerName; public SetupProvider() { super(); } public SetupProvider(String providerName) { this(); this.providerName = providerName; } public String getProviderId() { return providerId; } public void setProviderId(String providerId) { this.providerId = providerId; } public String getProviderName() { return providerName; } public void setProviderName(String providerName) { this.providerName = providerName; } public boolean isBlockFlag() { return blockFlag; } public Timestamp getCreateAt() { return createAt; } }
.magazineDashboard { border-collapse: collapse; width: 100%; & td { border: 1px solid black; padding: 20px; } &_title, &_series { font-size: 1.2rem; } &_status { font-size: 2rem; text-align: center; width: 1rem; } &_action { & form { display: inline-block; margin-right: 10px; } & input { @apply --clickable; padding: 2px; background-color: rgba(0, 0, 0, 0); font-size: 2rem; } } }
class RequestOptions(object): class Operator: Equals = 'eq' GreaterThan = 'gt' GreaterThanOrEqual = 'gte' LessThan = 'lt' LessThanOrEqual = 'lte' In = 'in' class Field: CreatedAt = 'createdAt' LastLogin = 'lastLogin' Name = 'name' OwnerName = 'ownerName' SiteRole = 'siteRole' Tags = 'tags' UpdatedAt = 'updatedAt' class Direction: Desc = 'desc' Asc = 'asc' def __init__(self, pagenumber=1, pagesize=100): self.pagenumber = pagenumber self.pagesize = pagesize self.sort = set() self.filter = set() def page_size(self, page_size): self.pagesize = page_size return self def page_number(self, page_number): self.pagenumber = page_number return self def apply_query_params(self, url): params = [] if self.page_number: params.append('pageNumber={0}'.format(self.pagenumber)) if self.page_size: params.append('pageSize={0}'.format(self.pagesize)) if len(self.sort) > 0: params.append('sort={}'.format(','.join(str(sort_item) for sort_item in self.sort))) if len(self.filter) > 0: params.append('filter={}'.format(','.join(str(filter_item) for filter_item in self.filter))) return "{0}?{1}".format(url, '&'.join(params))
class ArticlesController < <API key> include ArticlesHelper before_filter :require_login, only: [:new, :create, :edit, :update, :destroy] def index @articles = Article.all end def show @article = Article.find(params[:id]) @comment = Comment.new @comment.article_id = @article.id end def new @article = Article.new end def create @article = Article.new(article_params) @article.save flash.notice = "Article '#{@article.title}' Created!" redirect_to article_path(@article) end def destroy @article = Article.find(params[:id]) @article.destroy flash.notice = "Article '#{@article.title}' Deleted!" redirect_to action: "index" end def edit @article = Article.find(params[:id]) end def update @article = Article.find(params[:id]) @article.update(article_params) flash.notice = "Article '#{@article.title}' Updated!" redirect_to article_path(@article) end end
<?php /* Safe sample input : reads the field UserData from the variable $_GET sanitize : cast via + = 0 construction : interpretation with simple quote */ $tainted = $_GET['UserData']; $tainted += 0 ; $var = header("Location: pages/'$tainted'.php"); ?>
<?php /* Safe sample input : use shell_exec to cat /tmp/tainted.txt sanitize : cast in float construction : concatenation with simple quote */ $tainted = shell_exec('cat /tmp/tainted.txt'); $tainted = (float) $tainted ; $query = "SELECT * FROM student where id='". $tainted . "'"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
#ifndef ACE_BUTTON_H #define ACE_BUTTON_H #include <string> #include <map> #include <OpenGL\ShadersUtility.h> #include <Geometry\DrawingUtils.h> #include <BaseGUIObject.h> namespace AceGUI{ class Button :public BaseGUIElement{ vao_state m_box_filled; DrawingUtils::<API key> *m_box_filled_data; vao_state m_box_wire_frame; DrawingUtils::<API key> *<API key>; float m_size_x; float m_size_y; float m_center_x; float m_center_y; float m_r_current; float m_g_current; float m_b_current; float m_r_default; float m_g_default; float m_b_default; float m_r_original; float m_g_original; float m_b_original; float m_min_size_x; unsigned int m_text_id; void update_button_box(const float & _text_size); void <API key>(); std::pair<float, float>get_text_location(const float &_text_size); float get_text_size(); void add_default_events(); void init_button(const std::string &_str, const float &_x, const float &_y); Button(const Button &) = delete; Button(Button &&) = delete; Button &operator=(const Button &) = delete; Button &operator=(Button &&) = delete; public: Button(); Button(const std::string &_str, const float &_x, const float &_y); Button(const std::string &_str); ~Button(); enum BUTTON_EVENT{ HOVER,MOUSE_DOWN,MOUSE_CLICK}; void create(const std::string &_text); void set_default_color(const float &_r, const float &_g, const float &_b); void get_default_color(float &_r, float &_g, float &_b); void set_current_color(const float &_r, const float &_g, const float &_b); void get_current_color(float &_r, float &_g, float &_b); void set_original_color(const float &_r, const float &_g, const float &_b); void get_original_color(float &_r, float &_g, float &_b); void set_text(const std::string &_str); void set_text_size(const float &_size); void set_text_color(const float &_r, const float &_g, const float &_b); void set_size(const float &_size_x, const float &_size_y); float get_size_x(); void reset_min_size(); float get_size_y(); void set_center(const float &_center_x, const float &_center_y); void render(); bool <API key>(const double &_x, const double &_y); void set_min_size_x(const float &_x); float get_min_size_x(); void animate() {}; private: std::map<BUTTON_EVENT, void*> m_callbacks; }; } #endif
'use strict' export default () => { if (ON_TEST) { require('./test/auctions.component.test') } const auctions = { bindings: { props: '=' }, controller: 'AuctionsController as Auctions', template: require('./views/auctions-main.html') } angular.module('app.auctions') .component('auctions', auctions) }
<!DOCTYPE html> <html> <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>state « Pei LiPing's Blog</title> <meta name="description" content="fevernovastateflinkstate"> <link rel="stylesheet" href="/blog/css/main.css"> <link rel="canonical" href="http://peiliping.github.io/blog/archivers/2020-05-11-state"> <link rel="alternate" type="application/rss+xml" title="Pei LiPing's Blog" href="http://peiliping.github.io/blog/feed.xml" /> </head> <body> <header class="header"> <div class="wrapper"> <a class="site-title" href="/blog/">Pei LiPing's Blog</a> <nav class="site-nav"> <a class="page-link" href="/blog/about/">About</a> <a class="page-link" href="/blog/category/">Category</a> </nav> </div> </header> <div class="page-content"> <div class="wrapper"> <div class="col-main"> <div class="post"> <header class="post-header"> <h1 class="post-title">state</h1> <p class="post-meta">May 11, 2020</p> </header> <article class="post-content"> <p>fevernovastateflinkstate</p> <p>flinkstatestate</p> <h2 id="fevernovastate">fevernovastate</h2> <p>fevernovastate</p> <p>statekafkaoffsetbinlogfilenameposition</p> <p>kafka To HDFScommitstate</p> <p>flinkrollingfilesink</p> <h2 id="state">state</h2> <p>metastate</p> <p>Nas</p> <h2 id="section"></h2> <p><a href="https://github.com/OpenHFT">OpenHFT</a></p> <p>state</p> <p>WriteBytesMarshallableReadBytesMarshallable</p> <p>state</p> <p>fevernovaexchange</p> <h2 id="section-1"></h2> <p>Chandy-Lamport</p> <p>kafkacpu</p> <p>fevernovaexchangeRoaringbitmap</p> <p>state</p> </article> </div> </div> <div class="col-second"> <div class="col-box col-box-author"> <img class="avatar" src=" <div class="col-box-title name">Pei LiPing</div> <p>The Cabin Of Pei LiPing.</p> <p class="contact"> <a href="mailto:peilipingplp@gmail.com">Email</a> </p> </div> <div class="col-box"> <div class="col-box-title">Newest Posts</div> <ul class="post-list"> <li><a class="post-link" href="/blog/archivers/2021-12-29-Linear">Linear</a></li> <li><a class="post-link" href="/blog/archivers/2021-11-20-Pine">Pine</a></li> <li><a class="post-link" href="/blog/archivers/2021-10-10-baby">Baby</a></li> <li><a class="post-link" href="/blog/archivers/2021-09-11-wyckoff2">Wyckoff2</a></li> <li><a class="post-link" href="/blog/archivers/2021-08-19-wyckoff">Wyckoff</a></li> </ul> </div> <div class="col-box post-toc hide"> <div class="col-box-title">TOC</div> </div> </div> </div> </div> <footer class="footer"> <div class="wrapper"> &copy; 2016 Pei LiPing </div> </footer> <script src="//upcdn.b0.upaiyun.com/libs/jquery/jquery-1.9.0.min.js"></script> <script src="/blog/js/easybook.js"></script> </body> </html>
<!DOCTYPE html PUBLIC "- <html xmlns="http: <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.9.1"/> <title>V8 API Reference Guide for node.js v5.1.1: Member List</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> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v5.1.1 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </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="<API key>"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="<API key>.html">ScriptCompiler</a></li><li class="navelem"><a class="el" href="<API key>.html"><API key></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::ScriptCompiler::<API key> Member List</div> </div> </div><!--header <div class="contents"> <p>This is the complete list of members for <a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">GetMoreData</a>(const uint8_t **src)=0</td><td class="entry"><a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="<API key>.html#<API key>">ResetToBookmark</a>()</td><td class="entry"><a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">SetBookmark</a>()</td><td class="entry"><a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~<API key></b>() (defined in <a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a>)</td><td class="entry"><a class="el" href="<API key>.html">v8::ScriptCompiler::<API key></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
int variable; void protoOnly(void); void defOnly(void) { } void protoAndDef(void); void protoAndDef(void) { } template<typename T> void tmplProtoOnly(T t); template<typename T> void tmplDefOnly(T t) {} template<typename T> void tmplProtoAndDef(T t); template<typename T> void tmplProtoAndDef(T t) {} class Cl { int clVar; void clProtoOnly(void); void clDefOnly(void) { } void clProtoAndDef(void); template<typename T> void clTmplProtoOnly(T t); template<typename T> void clTmplDefOnly(T t) {} template<typename T> void clTmplProtoAndDef(T t); }; void Cl::clProtoAndDef(void) { } template<typename T> void Cl::clTmplProtoAndDef(T t) {} class classProtoOnly; class classProtoAndDef; class classProtoAndDef { }; template<typename T> class tmplClassProtoOnly; template<typename T> class <API key>; template<typename T> class <API key> { }; template<typename T> void <API key>(T t); template<typename T> void <API key>(T t) {} template<typename T> class <API key>; template<typename T> class <API key> { T t; }; void f(void) { <API key><int> tici; <API key><double> ticd; int i; double d; <API key>(i); <API key>(d); }
#include <limits> #include "hungarian.hpp" using namespace std; <API key>::<API key>() { } <API key>::~<API key>() { } double <API key>::Solve(vector<vector<double>>& DistMatrix,vector<int>& Assignment,TMethod Method) { int N=DistMatrix.size(); // number of columns (tracks) int M=DistMatrix[0].size(); // number of rows (measurements) int *assignment =new int[N]; double *distIn =new double[N*M]; double cost; // Fill matrix with random numbers for(int i=0; i<N; i++) { for(int j=0; j<M; j++) { distIn[i+N*j] = DistMatrix[i][j]; } } switch(Method) { case optimal: assignmentoptimal(assignment, &cost, distIn, N, M); break; case <API key>: assignmentoptimal(assignment, &cost, distIn, N, M); break; case <API key>: assignmentoptimal(assignment, &cost, distIn, N, M); break; } // form result Assignment.clear(); for(int x=0; x<N; x++) { Assignment.push_back(assignment[x]); } delete[] assignment; delete[] distIn; return cost; } // Computes the optimal assignment (minimum overall costs) using Munkres algorithm. void <API key>::assignmentoptimal(int *assignment, double *cost, double *distMatrixIn, int nOfRows, int nOfColumns) { double *distMatrix; double *distMatrixTemp; double *distMatrixEnd; double value; double minValue; bool *coveredColumns; bool *coveredRows; bool *starMatrix; bool *newStarMatrix; bool *primeMatrix; int nOfElements; int minDim; int row; // Init *cost = 0; for(row=0; row<nOfRows; row++) { assignment[row] = -1.0; } // Generate distance matrix // and check matrix elements positiveness :) // Total elements number nOfElements = nOfRows * nOfColumns; // Memory allocation distMatrix = (double *)malloc(nOfElements * sizeof(double)); // Pointer to last element distMatrixEnd = distMatrix + nOfElements; for(row=0; row<nOfElements; row++) { value = distMatrixIn[row]; if(value < 0) { cout << "All matrix elements have to be non-negative." << endl; } distMatrix[row] = value; } // Memory allocation coveredColumns = (bool *)calloc(nOfColumns, sizeof(bool)); coveredRows = (bool *)calloc(nOfRows, sizeof(bool)); starMatrix = (bool *)calloc(nOfElements, sizeof(bool)); primeMatrix = (bool *)calloc(nOfElements, sizeof(bool)); newStarMatrix = (bool *)calloc(nOfElements, sizeof(bool)); /* used in step4 */ /* preliminary steps */ if(nOfRows <= nOfColumns) { minDim = nOfRows; for(row=0; row<nOfRows; row++) { /* find the smallest element in the row */ distMatrixTemp = distMatrix + row; minValue = *distMatrixTemp; distMatrixTemp += nOfRows; while(distMatrixTemp < distMatrixEnd) { value = *distMatrixTemp; if(value < minValue) { minValue = value; } distMatrixTemp += nOfRows; } /* subtract the smallest element from each element of the row */ distMatrixTemp = distMatrix + row; while(distMatrixTemp < distMatrixEnd) { *distMatrixTemp -= minValue; distMatrixTemp += nOfRows; } } /* Steps 1 and 2a */ for(row=0; row<nOfRows; row++) { for(int col=0; col<nOfColumns; col++) { if ((distMatrix[row + nOfRows*col] == 0) && !coveredColumns[col]) { starMatrix[row + nOfRows*col] = true; coveredColumns[col] = true; break; } } } } else /* if(nOfRows > nOfColumns) */ { minDim = nOfColumns; for(int col=0; col<nOfColumns; col++) { /* find the smallest element in the column */ distMatrixTemp = distMatrix + nOfRows*col; double *columnEnd = distMatrixTemp + nOfRows; minValue = *distMatrixTemp++; while(distMatrixTemp < columnEnd) { value = *distMatrixTemp++; if(value < minValue) { minValue = value; } } /* subtract the smallest element from each element of the column */ distMatrixTemp = distMatrix + nOfRows*col; while(distMatrixTemp < columnEnd) { *distMatrixTemp++ -= minValue; } } /* Steps 1 and 2a */ for(int col=0; col<nOfColumns; col++) { for(row=0; row<nOfRows; row++) { if((distMatrix[row + nOfRows*col] == 0) && !coveredRows[row]) { starMatrix[row + nOfRows*col] = true; coveredColumns[col] = true; coveredRows[row] = true; break; } } } for(row=0; row<nOfRows; row++) { coveredRows[row] = false; } } /* move to step 2b */ step2b(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); /* compute cost and remove invalid assignments */ <API key>(assignment, cost, distMatrixIn, nOfRows); /* free allocated memory */ free(distMatrix); free(coveredColumns); free(coveredRows); free(starMatrix); free(primeMatrix); free(newStarMatrix); return; } void <API key>::<API key>(int *assignment, bool *starMatrix, int nOfRows, int nOfColumns) { int row, col; for(row=0; row<nOfRows; row++) { for(col=0; col<nOfColumns; col++) { if(starMatrix[row + nOfRows*col]) { assignment[row] = col; break; } } } } void <API key>::<API key>(int *assignment, double *cost, double *distMatrix, int nOfRows) { for(int row=0; row<nOfRows; row++) { int col = assignment[row]; if(col >= 0) { *cost += distMatrix[row + nOfRows*col]; } } } void <API key>::step2a(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim) { /* cover every column containing a starred zero */ for(int col=0; col<nOfColumns; col++) { bool *starMatrixTemp = starMatrix + nOfRows*col; bool *columnEnd = starMatrixTemp + nOfRows; while(starMatrixTemp < columnEnd) { if(*starMatrixTemp++) { coveredColumns[col] = true; break; } } } /* move to step 3 */ step2b(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void <API key>::step2b(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim) { int col, nOfCoveredColumns; /* count covered columns */ nOfCoveredColumns = 0; for(col=0; col<nOfColumns; col++) { if(coveredColumns[col]) { nOfCoveredColumns++; } } if(nOfCoveredColumns == minDim) { /* algorithm finished */ <API key>(assignment, starMatrix, nOfRows, nOfColumns); } else { /* move to step 3 */ step3(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } } void <API key>::step3(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim) { bool zerosFound; int row, col, starCol; zerosFound = true; while(zerosFound) { zerosFound = false; for(col=0; col<nOfColumns; col++) { if(!coveredColumns[col]) { for(row=0; row<nOfRows; row++) { if((!coveredRows[row]) && (distMatrix[row + nOfRows*col] == 0)) { /* prime zero */ primeMatrix[row + nOfRows*col] = true; /* find starred zero in current row */ for(starCol=0; starCol<nOfColumns; starCol++) if(starMatrix[row + nOfRows*starCol]) { break; } if(starCol == nOfColumns) /* no starred zero found */ { /* move to step 4 */ step4(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim, row, col); return; } coveredRows[row] = true; coveredColumns[starCol] = false; zerosFound = true; break; } } } } } /* move to step 5 */ step5(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void <API key>::step4(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim, int row, int col) { int n, starRow, starCol, primeCol; int nOfElements = nOfRows*nOfColumns; /* generate temporary copy of starMatrix */ for(n=0; n<nOfElements; n++) { newStarMatrix[n] = starMatrix[n]; } /* star current zero */ newStarMatrix[row + nOfRows*col] = true; /* find starred zero in current column */ starCol = col; for(starRow=0; starRow<nOfRows; starRow++) { if(starMatrix[starRow + nOfRows*starCol]) { break; } } while(starRow<nOfRows) { /* unstar the starred zero */ newStarMatrix[starRow + nOfRows*starCol] = false; /* find primed zero in current row */ int primeRow = starRow; for(primeCol=0; primeCol<nOfColumns; primeCol++) { if(primeMatrix[primeRow + nOfRows*primeCol]) { break; } } /* star the primed zero */ newStarMatrix[primeRow + nOfRows*primeCol] = true; /* find starred zero in current column */ starCol = primeCol; for(starRow=0; starRow<nOfRows; starRow++) { if(starMatrix[starRow + nOfRows*starCol]) { break; } } } /* use temporary copy as new starMatrix */ /* delete all primes, uncover all rows */ for(n=0; n<nOfElements; n++) { primeMatrix[n] = false; starMatrix[n] = newStarMatrix[n]; } for(n=0; n<nOfRows; n++) { coveredRows[n] = false; } /* move to step 2a */ step2a(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } void <API key>::step5(int *assignment, double *distMatrix, bool *starMatrix, bool *newStarMatrix, bool *primeMatrix, bool *coveredColumns, bool *coveredRows, int nOfRows, int nOfColumns, int minDim) { double h, value; int row, col; /* find smallest uncovered element h */ h = numeric_limits<double>::max(); for(row=0; row<nOfRows; row++) { if(!coveredRows[row]) { for(col=0; col<nOfColumns; col++) { if(!coveredColumns[col]) { value = distMatrix[row + nOfRows*col]; if(value < h) { h = value; } } } } } /* add h to each covered row */ for(row=0; row<nOfRows; row++) { if(coveredRows[row]) { for(col=0; col<nOfColumns; col++) { distMatrix[row + nOfRows*col] += h; } } } /* subtract h from each uncovered column */ for(col=0; col<nOfColumns; col++) { if(!coveredColumns[col]) { for(row=0; row<nOfRows; row++) { distMatrix[row + nOfRows*col] -= h; } } } /* move to step 3 */ step3(assignment, distMatrix, starMatrix, newStarMatrix, primeMatrix, coveredColumns, coveredRows, nOfRows, nOfColumns, minDim); } // Computes a suboptimal solution. Good for cases without forbidden assignments. void <API key>::<API key>(int *assignment, double *cost, double *distMatrixIn, int nOfRows, int nOfColumns) { int n, row, col, tmpRow, tmpCol, nOfElements; double value, *distMatrix; /* make working copy of distance Matrix */ nOfElements = nOfRows * nOfColumns; distMatrix = (double *)malloc(nOfElements * sizeof(double)); for(n=0; n<nOfElements; n++) { distMatrix[n] = distMatrixIn[n]; } /* initialization */ *cost = 0; for(row=0; row<nOfRows; row++) { assignment[row] = -1.0; } /* recursively search for the minimum element and do the assignment */ while(true) { /* find minimum distance <API key> pair */ double minValue = numeric_limits<double>::max(); for(row=0; row<nOfRows; row++) for(col=0; col<nOfColumns; col++) { value = distMatrix[row + nOfRows*col]; if(value!=numeric_limits<double>::max() && (value < minValue)) { minValue = value; tmpRow = row; tmpCol = col; } } if(minValue!=numeric_limits<double>::max()) { assignment[tmpRow] = tmpCol; *cost += minValue; for(n=0; n<nOfRows; n++) { distMatrix[n + nOfRows*tmpCol] = numeric_limits<double>::max(); } for(n=0; n<nOfColumns; n++) { distMatrix[tmpRow + nOfRows*n] = numeric_limits<double>::max(); } } else break; } /* while(true) */ free(distMatrix); } // Computes a suboptimal solution. Good for cases with many forbidden assignments. void <API key>::<API key>(int *assignment, double *cost, double *distMatrixIn, int nOfRows, int nOfColumns) { bool infiniteValueFound, finiteValueFound; int n, row, col, tmpRow, tmpCol, nOfElements; int *<API key>, *nOfValidTracks; double value, minValue, *distMatrix; /* make working copy of distance Matrix */ nOfElements = nOfRows * nOfColumns; distMatrix = (double *)malloc(nOfElements * sizeof(double)); for(n=0; n<nOfElements; n++) { distMatrix[n] = distMatrixIn[n]; } /* initialization */ *cost = 0; for(row=0; row<nOfRows; row++) { assignment[row] = -1.0; } /* allocate memory */ <API key> = (int *)calloc(nOfRows, sizeof(int)); nOfValidTracks = (int *)calloc(nOfColumns, sizeof(int)); /* compute number of validations */ infiniteValueFound = false; finiteValueFound = false; for(row=0; row<nOfRows; row++) { for(col=0; col<nOfColumns; col++) { if(distMatrix[row + nOfRows*col]!=numeric_limits<double>::max()) { nOfValidTracks[col] += 1; <API key>[row] += 1; finiteValueFound = true; } else infiniteValueFound = true; } } if(infiniteValueFound) { if(!finiteValueFound) { /* free allocated memory */ free(<API key>); free(nOfValidTracks); free(distMatrix); return; } bool repeatSteps = true; while(repeatSteps) { repeatSteps = false; /* step 1: reject assignments of multiply validated tracks to singly validated observations */ for(col=0; col<nOfColumns; col++) { bool <API key> = false; for(row=0; row<nOfRows; row++) if(distMatrix[row + nOfRows*col]!=numeric_limits<double>::max() && (<API key>[row] == 1)) { <API key> = true; break; } if(<API key>) { for(row=0; row<nOfRows; row++) if((<API key>[row] > 1) && distMatrix[row + nOfRows*col]!=numeric_limits<double>::max()) { distMatrix[row + nOfRows*col] = numeric_limits<double>::max(); <API key>[row] -= 1; nOfValidTracks[col] -= 1; repeatSteps = true; } } } /* step 2: reject assignments of multiply validated observations to singly validated tracks */ if(nOfColumns > 1) { for(row=0; row<nOfRows; row++) { bool <API key> = false; for(col=0; col<nOfColumns; col++) { if(distMatrix[row + nOfRows*col]!=numeric_limits<double>::max() && (nOfValidTracks[col] == 1)) { <API key> = true; break; } } if(<API key>) { for(col=0; col<nOfColumns; col++) { if((nOfValidTracks[col] > 1) && distMatrix[row + nOfRows*col]!=numeric_limits<double>::max()) { distMatrix[row + nOfRows*col] = numeric_limits<double>::max(); <API key>[row] -= 1; nOfValidTracks[col] -= 1; repeatSteps = true; } } } } } } /* while(repeatSteps) */ /* for each multiply validated track that validates only with singly validated */ /* observations, choose the observation with minimum distance */ for(row=0; row<nOfRows; row++) { if(<API key>[row] > 1) { bool allSinglyValidated = true; minValue = numeric_limits<double>::max(); for(col=0; col<nOfColumns; col++) { value = distMatrix[row + nOfRows*col]; if(value!=numeric_limits<double>::max()) { if(nOfValidTracks[col] > 1) { allSinglyValidated = false; break; } else if((nOfValidTracks[col] == 1) && (value < minValue)) { tmpCol = col; minValue = value; } } } if(allSinglyValidated) { assignment[row] = tmpCol; *cost += minValue; for(n=0; n<nOfRows; n++) { distMatrix[n + nOfRows*tmpCol] = numeric_limits<double>::max(); } for(n=0; n<nOfColumns; n++) { distMatrix[row + nOfRows*n] = numeric_limits<double>::max(); } } } } /* for each multiply validated observation that validates only with singly validated */ /* track, choose the track with minimum distance */ for(col=0; col<nOfColumns; col++) { if(nOfValidTracks[col] > 1) { bool allSinglyValidated = true; minValue = numeric_limits<double>::max(); for(row=0; row<nOfRows; row++) { value = distMatrix[row + nOfRows*col]; if(value!=numeric_limits<double>::max()) { if(<API key>[row] > 1) { allSinglyValidated = false; break; } else if((<API key>[row] == 1) && (value < minValue)) { tmpRow = row; minValue = value; } } } if(allSinglyValidated) { assignment[tmpRow] = col; *cost += minValue; for(n=0; n<nOfRows; n++) distMatrix[n + nOfRows*col] = numeric_limits<double>::max(); for(n=0; n<nOfColumns; n++) distMatrix[tmpRow + nOfRows*n] = numeric_limits<double>::max(); } } } } /* if(infiniteValueFound) */ /* now, recursively search for the minimum element and do the assignment */ while(true) { /* find minimum distance <API key> pair */ minValue = numeric_limits<double>::max(); for(row=0; row<nOfRows; row++) for(col=0; col<nOfColumns; col++) { value = distMatrix[row + nOfRows*col]; if(value!=numeric_limits<double>::max() && (value < minValue)) { minValue = value; tmpRow = row; tmpCol = col; } } if(minValue!=numeric_limits<double>::max()) { assignment[tmpRow] = tmpCol; *cost += minValue; for(n=0; n<nOfRows; n++) distMatrix[n + nOfRows*tmpCol] = numeric_limits<double>::max(); for(n=0; n<nOfColumns; n++) distMatrix[tmpRow + nOfRows*n] = numeric_limits<double>::max(); } else break; } /* while(true) */ /* free allocated memory */ free(<API key>); free(nOfValidTracks); free(distMatrix); }
#!/bin/env bash # WARNING - Read First Before Running This Script! # Running this script maybe HARMFUL to your system. Therefor, the user shall # carefully read all of this script and bear the relevant risks by # himself/herself. Running this script means the user accepting agreement above. # Centos Tweak script for server # Licenced under GPLv3 # Writen by: leo <leo.ss.pku@gmail.com> # Inspired by: yzhkpli@gmail.com # History: # 2010-10-28: # Fixed: # Disable CentALT yum repo by default. # Change running ntpdate from daily to weekly. # Change default VIM coloscheme from elflord to delek. # Fixed auto yes(-y) while install fail2ban by yum. # Add: # Add expandta & autoindent in /etc/vimrc. # Add auto start fail2ban after install fail2ban. # 2010-09-26: # Fixed: # A bug while generating /etc/yum.repo.d/dag-sohu.repo. # Change this file to UTF8-NOBOM. # Add: # CentALT yum repository(/etc/yum.repo.d/centalt.repo) while the OS is RHEL/CentOS 5. # 2010-09-11: # Add: # Install fail2ban to prevent password exhaustion attacking and set ban time as 12 hours.(default not effect. recommend uncomment if your server had public IP.) # Fixed: # Command not found bug when running by sudo. # 2010-08-25: # Add: # Disable Ctrl+Alt+Del rebooting(thanks 181789871).(default not effect. uncommnet to take effect.) # Add README file. # 2010-08-18: # Fixed: # A bug while exporting path into /etc/bashrc caused by "\"(thanks 181789871). # 2010-08-16: # Add: # Close the tty between second and sixth(thanks selboo). # Increase default open file limits from 1024 to 65525. # 2010-08-14: # Fixed: # Optimize code of disabling selinux(thanks huichrist) # 2010-08-10: # Fixed: # Disable ius yum repository by default. # 2010-08-09: # Add: # Tweak enviroment like PATH, LDFLAGS and LD_LIBRARY_PATH for easy using sudo. # 2010-08-08: # Add: # Firstly check running this script as root. # Disable gpgcheck and plugins for running fastly. # Increase yum cache expire time from 1h to 24h. # Turn off auto running fsck while days duration. # Turn off writing file reading time (add noatime in /etc/fstab). # Fixed: # Change file name to centostweak.sh # Change /etc/cron.daily/ntpdate with run mode(+x). # 2010-08-04: # Add: # Install sudo. Enable wheel group to use nopasswrd sudo. # 2010-08-02: # Add: # Install & config snmpd. # Default iptables rules. # Fixed: # ntp package name from ntpdate. # 2010-08-01: # To avoid backup file overried, Change backup file name ended from ".origin" to ".%Y-%m-%d_%H-%M-%S". # 2010-07-31: # Modified to be used with CentOS 5.x Server and sohu mirrors. # Removed some unuseful functions. # Add functions for turnning unuseful service off while system start. # Add functions for kernel & TCP parameters optimizing. # 2010-06-06: export PATH=$PATH:/bin:/sbin:/usr/sbin # Require root to run this script. if [[ "$(whoami)" != "root" ]]; then echo "Please run this script as root." >&2 exit 1 fi SERVICE=`which service` CHKCONFIG=`which chkconfig` cd /etc/yum.repos.d/ cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.`date +"%Y-%m-%d_%H-%M-%S"` sed -i -e 's/mirrorlist/#mirrorlist/' CentOS-Base.repo sed -i -e 's/#baseurl/baseurl/' CentOS-Base.repo sed -i -e 's/mirror.centos.org/mirrors.sohu.com/' CentOS-Base.repo cp /etc/yum.conf /etc/yum.conf.`date +"%Y-%m-%d_%H-%M-%S"` sed -i 's/gpgcheck=1/gpgcheck=0/' /etc/yum.conf sed -i 's/plugins=1/plugins=0/' /etc/yum.conf sed -i 's/metadata_expire=1h/metadata_expire=24h/' /etc/yum.conf # dag@sohu # relver=`uname -r | awk -F. '{print $NF}'` echo -e " " "[dag-sohu]\n"\ "name = Red Hat Enterprise \$releasever – sohu.com – dag\n"\ "baseurl = http://mirrors.sohu.com/dag/redhat/`uname -r | awk -F. '{print substr($NF,1,3)}'`/en/\$basearch/dag\n"\ "enabled = 1\n"\ "gpgcheck = 0" > /etc/yum.repos.d/dag-sohu.repo # epel@sohu echo -e " " "[epel-sohu]\n"\ "name = Fedora EPEL \$releasever - sohu.com\n"\ "baseurl = http://mirrors.sohu.com/fedora-epel/\$releasever/\$basearch\n"\ "enabled = 1\n"\ "gpgcheck = 0" > /etc/yum.repos.d/epel-sohu.repo # CentALT # --enablerepo=centalt if [[ `uname -r | awk -F. '{print substr($NF,1,3)}'` == "el5" ]]; then echo -e "[CentALT]\n"\ "name=CentALT Packages for Enterprise Linux 5 - \$basearch\n"\ "baseurl=http://centos.alt.ru/repository/centos/5/\$basearch/\n"\ "enabled=0\n"\ "gpgcheck=0" > /etc/yum.repos.d/centalt.repo fi # ius # --enablerepo=iusyum install python26 --enablerepo=ius echo -e "# Name: IUS RPM Repository for Red Hat Enterprise 5\n"\ " "[ius]\n"\ "name = Red Hat Enterprise \$releasever – ius\n"\ "baseurl = http://dl.iuscommunity.org/pub/ius/stable/Redhat/\$releasever/\$basearch/\n"\ "enabled = 0\n"\ "gpgcheck = 0" > /etc/yum.repos.d/ius.repo # sysstat, ntp, snmpd, sudo yum install sysstat ntp net-snmp sudo screen -y # sudo cp /etc/sudoers /etc/sudoers.`date +"%Y-%m-%d_%H-%M-%S"` # wheelsudoroot sed -i -e '/NOPASSWD/s/^# //' /etc/sudoers sed -i -e 's/env_reset/!env_reset/' /etc/sudoers # sudo echo 'export PATH=$PATH:/sbin:/usr/sbin' >> /etc/bashrc echo 'export LDFLAGS="-L/usr/local/lib -Wl,-rpath,/usr/local/lib"' >> /etc/bashrc echo 'export LD_LIBRARY_PATH="/usr/local/lib"' >> /etc/bashrc # echo -ne $(echo export PRMPT_COMMAND='{ cmd=$(history 1 | { read x y; echo $y; }); echo -ne [ $(date "+%c") ]$LOGNAME :: $SUDO_USER :: $SSH_CLIENT :: $SSH_TTY :: $cmd "\n"; } >> $HOME/.bash_history.log') >> /etc/bashrc cp /etc/fstab /etc/fstab.`date +"%Y-%m-%d_%H-%M-%S"` sed -i 's/ext3 defaults/ext3 defaults,noatime/' /etc/fstab # fsck grep ext3 /etc/fstab | grep -v boot | awk '{print $1}' | xargs -i tune2fs -i0 {} # mountfsck # grep ext3 /etc/fstab | grep -v boot | awk '{print $1}' | xargs -i tune2fs -c-1 {} echo "/usr/sbin/ntpdate cn.pool.ntp.org" >> /etc/cron.weekly/ntpdate chmod +x /etc/cron.weekly/ntpdate # snmpd cp /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf.`date +"%Y-%m-%d_%H-%M-%S"` sed -i 's/#view all/view all/' /etc/snmp/snmpd.conf sed -i 's/#access MyROGroup/access MyROGroup/' /etc/snmp/snmpd.conf ${CHKCONFIG} snmpd on ${SERVICE} snmpd start # vim mv /etc/vimrc /etc/vimrc.`date +"%Y-%m-%d_%H-%M-%S"` cp /usr/share/vim/vim70/vimrc_example.vim /etc/vimrc sed -i -e 's/set mouse=a/" set mouse=a/' /etc/vimrc # tabelflord echo "set history=1000" >> /etc/vimrc echo "set expandtab" >> /etc/vimrc echo "set ai" >> /etc/vimrc echo "set tabstop=4" >> /etc/vimrc echo "set shiftwidth=4" >> /etc/vimrc echo "set paste" >> /etc/vimrc #echo "colo elflord" >> /etc/vimrc echo "colo delek" >> /etc/vimrc # SELINUX cp /etc/sysconfig/selinux /etc/sysconfig/selinux.`date +"%Y-%m-%d_%H-%M-%S"` sed -i '/SELINUX/s/\(enforcing\|permissive\)/disabled/' /etc/sysconfig/selinux # ,/etc/sysconfig /network/etc/hosts #sed -i -e "/HOSTNAME/s/^/#/" /etc/sysconfig/network #sed -i -e "$ a HOSTNAME=$HOSTNAME" /etc/sysconfig/network #sed -i -e "/127.0.0.1/c 127.0.0.1 $HOSTNAME localhost.localdomain localhost" /etc/hosts # disable IPV6 cp /etc/modprobe.conf /etc/modprobe.conf.`date +"%Y-%m-%d_%H-%M-%S"` echo "alias net-pf-10 off" >> /etc/modprobe.conf echo "alias ipv6 off" >> /etc/modprobe.conf # ssh cp /etc/ssh/sshd_config /etc/ssh/sshd_config.`date +"%Y-%m-%d_%H-%M-%S"` # root # sed -i '/#PermitRootLogin/s/#PermitRootLogin/PermitRootLogin/' /etc/ssh/sshd_config # GSSAPIAuthentication yesGSSAPICleanupCredentials yes sed -i -e '74 s/^/#/' -i -e '76 s/^/#/' /etc/ssh/sshd_config # DNS sed -i "s/#UseDNS yes/UseDNS no/" /etc/ssh/sshd_config # 44#<API key> yes48#<API key> no # sed -i -e '44 s/^/#/' -i -e '48 s/^/#/' /etc/ssh/sshd_config /etc/init.d/sshd restart # cp /etc/inputrc /etc/inputrc.origin # sed -i '/#set bell-style none/s/#set bell-style none/set bell-style none/' /etc/inputrc SERVICES="acpid atd auditd avahi-daemon bluetooth cpuspeed cups firstboot hidd ip6tables isdn mcstrans messagebus pcscd rawdevices sendmail yum-updatesd" for service in $SERVICES do ${CHKCONFIG} $service off ${SERVICE} $service stop done mv /etc/sysctl.conf /etc/sysctl.conf.`date +"%Y-%m-%d_%H-%M-%S"` echo -e "kernel.core_uses_pid = 1\n"\ "kernel.msgmnb = 65536\n"\ "kernel.msgmax = 65536\n"\ "kernel.shmmax = 68719476736\n"\ "kernel.shmall = 4294967296\n"\ "kernel.sysrq = 0\n"\ "net.core.netdev_max_backlog = 262144\n"\ "net.core.rmem_default = 8388608\n"\ "net.core.rmem_max = 16777216\n"\ "net.core.somaxconn = 262144\n"\ "net.core.wmem_default = 8388608\n"\ "net.core.wmem_max = 16777216\n"\ "net.ipv4.conf.default.rp_filter = 1\n"\ "net.ipv4.conf.default.accept_source_route = 0\n"\ "net.ipv4.ip_forward = 0\n"\ "net.ipv4.ip_local_port_range = 5000 65000\n"\ "net.ipv4.tcp_fin_timeout = 1\n"\ "net.ipv4.tcp_keepalive_time = 30\n"\ "net.ipv4.tcp_max_orphans = 3276800\n"\ "net.ipv4.tcp_max_syn_backlog = 262144\n"\ "net.ipv4.tcp_max_tw_buckets = 6000\n"\ "net.ipv4.tcp_mem = 94500000 915000000 927000000\n"\ "# net.ipv4.tcp_no_metrics_save=1\n"\ "net.ipv4.tcp_rmem = 4096 87380 16777216\n"\ "net.ipv4.tcp_sack = 1\n"\ "net.ipv4.tcp_syn_retries = 1\n"\ "net.ipv4.tcp_synack_retries = 1\n"\ "net.ipv4.tcp_syncookies = 1\n"\ "net.ipv4.tcp_timestamps = 0\n"\ "net.ipv4.tcp_tw_recycle = 1\n"\ "net.ipv4.tcp_tw_reuse = 1\n"\ "net.ipv4.tcp_window_scaling = 1\n"\ "net.ipv4.tcp_wmem = 4096 16384 16777216\n" > /etc/sysctl.conf sysctl -p # iptables if [ -f /etc/sysconfig/iptables ]; then cp /etc/sysconfig/iptables /etc/sysconfig/iptables.`date +"%Y-%m-%d_%H-%M-%S"` fi echo -e "*filter\n"\ ":INPUT DROP [0:0]\n"\ "#:INPUT ACCEPT [0:0]\n"\ ":FORWARD ACCEPT [0:0]\n"\ ":OUTPUT ACCEPT [0:0]\n"\ "-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT\n"\ "-A INPUT -p icmp -m icmp --icmp-type any -j ACCEPT\n"\ "# setting trust ethernet.\n"\ "-A INPUT -i eth0 -j ACCEPT\n"\ "-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT\n"\ "-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT\n"\ "-A INPUT -d 127.0.0.1 -j ACCEPT\n"\ "-A INPUT -j DROP\n"\ "-A FORWARD -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -m limit --limit 1/sec -j ACCEPT \n"\ "-A FORWARD -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK RST -m limit --limit 1/sec -j ACCEPT \n"\ "#-A FORWARD -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT \n"\ "COMMIT\n" > /etc/sysconfig/iptables ${SERVICE} iptables restart # Linux pts tty cp /etc/inittab /etc/inittab.`date +"%Y-%m-%d_%H-%M-%S"` sed -i '/tty[2-6]/s/^/#/' /etc/inittab cp /etc/security/limits.conf /etc/security/limits.conf.`date +"%Y-%m-%d_%H-%M-%S"` sed -i '/# End of file/i\*\t\t-\tnofile\t\t65535' /etc/security/limits.conf # ctrl+alt+del # cp /etc/inittab /etc/inittab.`date +"%Y-%m-%d_%H-%M-%S"` # sed -i "s/ca::ctrlaltdel:\/sbin\/shutdown -t3 -r now/#ca::ctrlaltdel:\/sbin\/shutdown -t3 -r now/" /etc/inittab # /sbin/init q # fail2banIP # yum install -y fail2ban # cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.conf.`date +"%Y-%m-%d_%H-%M-%S"` # sed -i 's/bantime = 600/bantime = 43200/' /etc/fail2ban/jail.conf # ${SERVICE} fail2ban start
namespace System.Web.Mvc { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Mvc.Resources; public class DefaultModelBinder : IModelBinder { private <API key> _binders; private static string _resourceClassKey; [SuppressMessage("Microsoft.Usage", "CA2227:<API key>", Justification = "Property is settable so that the dictionary can be provided for unit testing purposes.")] protected internal <API key> Binders { get { if (_binders == null) { _binders = ModelBinders.Binders; } return _binders; } set { _binders = value; } } public static string ResourceClassKey { get { return _resourceClassKey ?? String.Empty; } set { _resourceClassKey = value; } } internal void <API key>(ControllerContext controllerContext, ModelBindingContext bindingContext, object model) { // need to replace the property filter + model object and create an inner binding context BindAttribute bindAttr = (BindAttribute)TypeDescriptor.GetAttributes(bindingContext.ModelType)[typeof(BindAttribute)]; Predicate<string> newPropertyFilter = (bindAttr != null) ? propertyName => bindAttr.IsPropertyAllowed(propertyName) && bindingContext.PropertyFilter(propertyName) : bindingContext.PropertyFilter; ModelBindingContext newBindingContext = new ModelBindingContext() { Model = model, ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, ModelType = bindingContext.ModelType, PropertyFilter = newPropertyFilter, ValueProvider = bindingContext.ValueProvider }; // validation if (OnModelUpdating(controllerContext, newBindingContext)) { BindProperties(controllerContext, newBindingContext); OnModelUpdated(controllerContext, newBindingContext); } } internal object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { object model = bindingContext.Model; Type modelType = bindingContext.ModelType; // if we're being asked to create an array, create a list instead, then coerce to an array after the list is created if (model == null && modelType.IsArray) { Type elementType = modelType.GetElementType(); Type listType = typeof(List<>).MakeGenericType(elementType); object collection = CreateModel(controllerContext, bindingContext, listType); ModelBindingContext arrayBindingContext = new ModelBindingContext() { Model = collection, ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, ModelType = listType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; IList list = (IList)UpdateCollection(controllerContext, arrayBindingContext, elementType); if (list == null) { return null; } Array array = Array.CreateInstance(elementType, list.Count); list.CopyTo(array, 0); return array; } if (model == null) { model = CreateModel(controllerContext,bindingContext,modelType); } // special-case IDictionary<,> and ICollection<> Type dictionaryType = <API key>(modelType, typeof(IDictionary<,>)); if (dictionaryType != null) { Type[] genericArguments = dictionaryType.GetGenericArguments(); Type keyType = genericArguments[0]; Type valueType = genericArguments[1]; ModelBindingContext <API key> = new ModelBindingContext() { Model = model, ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, ModelType = modelType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object dictionary = UpdateDictionary(controllerContext, <API key>, keyType, valueType); return dictionary; } Type enumerableType = <API key>(modelType, typeof(IEnumerable<>)); if (enumerableType != null) { Type elementType = enumerableType.GetGenericArguments()[0]; Type collectionType = typeof(ICollection<>).MakeGenericType(elementType); if (collectionType.IsInstanceOfType(model)) { ModelBindingContext <API key> = new ModelBindingContext() { Model = model, ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, ModelType = modelType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object collection = UpdateCollection(controllerContext, <API key>, elementType); return collection; } } // otherwise, just update the properties on the complex type <API key>(controllerContext, bindingContext, model); return model; } public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext == null) { throw new <API key>("bindingContext"); } bool performedFallback = false; if (!String.IsNullOrEmpty(bindingContext.ModelName) && !DictionaryHelpers.<API key>(bindingContext.ValueProvider, bindingContext.ModelName)) { // We couldn't find any entry that began with the prefix. If this is the top-level element, fall back // to the empty prefix. if (bindingContext.<API key>) { bindingContext = new ModelBindingContext() { Model = bindingContext.Model, ModelState = bindingContext.ModelState, ModelType = bindingContext.ModelType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; performedFallback = true; } else { return null; } } // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string)) // or by seeing if a value in the request exactly matches the name of the model we're binding. // Complex type = everything else. if (!performedFallback) { ValueProviderResult vpResult; bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out vpResult); if (vpResult != null) { return BindSimpleModel(controllerContext, bindingContext, vpResult); } } if (TypeDescriptor.GetConverter(bindingContext.ModelType).CanConvertFrom(typeof(string))) { return null; } return BindComplexModel(controllerContext, bindingContext); } private void BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) { <API key> properties = GetModelProperties(controllerContext, bindingContext); foreach (PropertyDescriptor property in properties) { BindProperty(controllerContext, bindingContext, property); } } protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) { // need to skip properties that aren't part of the request, else we might hit a <API key> string fullPropertyKey = <API key>(bindingContext.ModelName, propertyDescriptor.Name); if (!DictionaryHelpers.<API key>(bindingContext.ValueProvider, fullPropertyKey)) { return; } // call into the property's model binder IModelBinder propertyBinder = Binders.GetBinder(propertyDescriptor.PropertyType); object <API key> = propertyDescriptor.GetValue(bindingContext.Model); ModelBindingContext innerBindingContext = new ModelBindingContext() { Model = <API key>, ModelName = fullPropertyKey, ModelState = bindingContext.ModelState, ModelType = propertyDescriptor.PropertyType, ValueProvider = bindingContext.ValueProvider }; object newPropertyValue = propertyBinder.BindModel(controllerContext, innerBindingContext); // validation if (<API key>(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) { SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue); } } internal object BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) { bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); // if the value provider returns an instance of the requested data type, we can just short-circuit // the evaluation and return that instance if (bindingContext.ModelType.IsInstanceOfType(valueProviderResult.RawValue)) { return valueProviderResult.RawValue; } // since a string is an IEnumerable<char>, we want it to skip the two checks immediately following if (bindingContext.ModelType != typeof(string)) { // conversion results in 3 cases, as below if (bindingContext.ModelType.IsArray) { // case 1: user asked for an array // ValueProviderResult.ConvertTo() understands array types, so pass in the array type directly object modelArray = <API key>(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType); return modelArray; } Type enumerableType = <API key>(bindingContext.ModelType, typeof(IEnumerable<>)); if (enumerableType != null) { // case 2: user asked for a collection rather than an array // need to call ConvertTo() on the array type, then copy the array to the collection object modelCollection = CreateModel(controllerContext, bindingContext, bindingContext.ModelType); Type elementType = enumerableType.GetGenericArguments()[0]; Type arrayType = elementType.MakeArrayType(); object modelArray = <API key>(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, arrayType); Type collectionType = typeof(ICollection<>).MakeGenericType(elementType); if (collectionType.IsInstanceOfType(modelCollection)) { CollectionHelpers.ReplaceCollection(elementType, modelCollection, modelArray); } return modelCollection; } } // case 3: user asked for an individual element object model = <API key>(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType); return model; } private static bool <API key>(Type type) { // value types aren't strictly immutable, but because they have copy-by-value semantics // we can't update a value type that is marked readonly if (type.IsValueType) { return false; } // arrays are mutable, but because we can't change their length we shouldn't try // to update an array that is referenced readonly if (type.IsArray) { return false; } // special-case known common immutable types if (type == typeof(string)) { return false; } return true; } [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)", Justification = "The target object should make the correct culture determination, not this method.")] [SuppressMessage("Microsoft.Design", "CA1031:<API key>", Justification = "We're recording this exception so that we can act on it later.")] private static object <API key>(<API key> modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType) { try { object convertedValue = valueProviderResult.ConvertTo(destinationType); return convertedValue; } catch (Exception ex) { modelState.AddModelError(modelStateKey, ex); return null; } } protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { Type typeToCreate = modelType; // we can understand some collection interfaces, e.g. IList<>, IDictionary<,> if (modelType.IsGenericType) { Type <API key> = modelType.<API key>(); if (<API key> == typeof(IDictionary<,>)) { typeToCreate = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments()); } else if (<API key> == typeof(IEnumerable<>) || <API key> == typeof(ICollection<>) || <API key> == typeof(IList<>)) { typeToCreate = typeof(List<>).MakeGenericType(modelType.GetGenericArguments()); } } // fallback to the type's default constructor return Activator.CreateInstance(typeToCreate); } protected static string CreateSubIndexName(string prefix, int index) { return String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", prefix, index); } protected static string <API key>(string prefix, string propertyName) { return (!String.IsNullOrEmpty(prefix)) ? prefix + "." + propertyName : propertyName; } private static Type <API key>(Type queryType, Type interfaceType) { Func<Type, bool> matchesInterface = t => t.IsGenericType && t.<API key>() == interfaceType; return (matchesInterface(queryType)) ? queryType : queryType.GetInterfaces().FirstOrDefault(matchesInterface); } protected virtual <API key> GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) { <API key> allProperties = TypeDescriptor.GetProperties(bindingContext.ModelType); Predicate<string> propertyFilter = bindingContext.PropertyFilter; var filteredProperties = from PropertyDescriptor property in allProperties where <API key>(property, propertyFilter) select property; return new <API key>(filteredProperties.ToArray()); } private static string <API key>(ControllerContext controllerContext) { string resourceValue = null; if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null)) { // If the user specified a ResourceClassKey try to load the resource they specified. // If the class key is invalid, an exception will be thrown. // If the class key is valid but the resource is not found, it returns null, in which // case it will fall back to the MVC default error message. resourceValue = controllerContext.HttpContext.<API key>(ResourceClassKey, "<API key>", CultureInfo.CurrentUICulture) as string; } return resourceValue ?? MvcResources.<API key>; } protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo; if (errorProvider != null) { string errorText = errorProvider.Error; if (!String.IsNullOrEmpty(errorText)) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorText); } } } protected virtual bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext) { // default implementation does nothing return true; } protected virtual void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo; if (errorProvider != null) { string errorText = errorProvider[propertyDescriptor.Name]; if (!String.IsNullOrEmpty(errorText)) { string modelStateKey = <API key>(bindingContext.ModelName, propertyDescriptor.Name); bindingContext.ModelState.AddModelError(modelStateKey, errorText); } } } protected virtual bool <API key>(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { // default implementation just checks to make sure that required text entry fields aren't left blank string modelStateKey = <API key>(bindingContext.ModelName, propertyDescriptor.Name); return <API key>(controllerContext, bindingContext.ModelState, modelStateKey, propertyDescriptor.PropertyType, value); } [SuppressMessage("Microsoft.Design", "CA1031:<API key>", Justification = "We're recording this exception so that we can act on it later.")] protected virtual void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { if (propertyDescriptor.IsReadOnly) { return; } try { propertyDescriptor.SetValue(bindingContext.Model, value); } catch (Exception ex) { string modelStateKey = <API key>(bindingContext.ModelName, propertyDescriptor.Name); bindingContext.ModelState.AddModelError(modelStateKey, ex); } } private static bool <API key>(PropertyDescriptor property, Predicate<string> propertyFilter) { if (property.IsReadOnly && !<API key>(property.PropertyType)) { return false; } // if this property is rejected by the filter, move on if (!propertyFilter(property.Name)) { return false; } // otherwise, allow return true; } internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) { IModelBinder elementBinder = Binders.GetBinder(elementType); // build up a list of items from the request List<object> modelList = new List<object>(); for (int currentIndex = 0; ; currentIndex++) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex); if (!DictionaryHelpers.<API key>(bindingContext.ValueProvider, subIndexKey)) { // we ran out of elements to pull break; } ModelBindingContext innerContext = new ModelBindingContext() { ModelName = subIndexKey, ModelState = bindingContext.ModelState, ModelType = elementType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object thisElement = elementBinder.BindModel(controllerContext, innerContext); // we need to merge model errors up <API key>(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement); modelList.Add(thisElement); } // if there weren't any elements at all in the request, just return if (modelList.Count == 0) { return null; } // replace the original collection object collection = bindingContext.Model; CollectionHelpers.ReplaceCollection(elementType, collection, modelList); return collection; } internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) { IModelBinder keyBinder = Binders.GetBinder(keyType); IModelBinder valueBinder = Binders.GetBinder(valueType); // build up a list of items from the request List<KeyValuePair<object, object>> modelList = new List<KeyValuePair<object, object>>(); for (int currentIndex = 0; ; currentIndex++) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex); string keyFieldKey = <API key>(subIndexKey, "key"); string valueFieldKey = <API key>(subIndexKey, "value"); if (!(DictionaryHelpers.<API key>(bindingContext.ValueProvider, keyFieldKey) && DictionaryHelpers.<API key>(bindingContext.ValueProvider, valueFieldKey))) { // we ran out of elements to pull break; } // bind the key ModelBindingContext keyBindingContext = new ModelBindingContext() { ModelName = keyFieldKey, ModelState = bindingContext.ModelState, ModelType = keyType, ValueProvider = bindingContext.ValueProvider }; object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext); // we need to merge model errors up <API key>(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey); if (!keyType.IsInstanceOfType(thisKey)) { // we can't add an invalid key, so just move on continue; } // bind the value ModelBindingContext valueBindingContext = new ModelBindingContext() { ModelName = valueFieldKey, ModelState = bindingContext.ModelState, ModelType = valueType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object thisValue = valueBinder.BindModel(controllerContext, valueBindingContext); // we need to merge model errors up <API key>(controllerContext, bindingContext.ModelState, valueFieldKey, valueType, thisValue); KeyValuePair<object, object> kvp = new KeyValuePair<object, object>(thisKey, thisValue); modelList.Add(kvp); } // if there weren't any elements at all in the request, just return if (modelList.Count == 0) { return null; } // replace the original collection object dictionary = bindingContext.Model; CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList); return dictionary; } private static bool <API key>(ControllerContext controllerContext, <API key> modelState, string modelStateKey, Type elementType, object value) { if (value == null && !TypeHelpers.TypeAllowsNullValue(elementType)) { if (modelState.IsValidField(modelStateKey)) { // a required entry field was left blank string message = <API key>(controllerContext); modelState.AddModelError(modelStateKey, message); } // we don't care about "you must enter a value" messages if there was an error return false; } return true; } // This helper type is used because we're working with strongly-typed collections, but we don't know the Ts // ahead of time. By using the generic methods below, we can consolidate the collection-specific code in a // single helper type rather than having reflection-based calls spread throughout the DefaultModelBinder type. // There is a single point of entry to each of the methods below, so they're fairly simple to maintain. private static class CollectionHelpers { private static readonly MethodInfo <API key> = typeof(CollectionHelpers).GetMethod("<API key>", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo <API key> = typeof(CollectionHelpers).GetMethod("<API key>", BindingFlags.Static | BindingFlags.NonPublic); public static void ReplaceCollection(Type collectionType, object collection, object newContents) { MethodInfo targetMethod = <API key>.MakeGenericMethod(collectionType); targetMethod.Invoke(null, new object[] { collection, newContents }); } private static void <API key><T>(ICollection<T> collection, IEnumerable newContents) { collection.Clear(); if (newContents != null) { foreach (object item in newContents) { // if the item was not a T, some conversion failed. the error message will be propagated, // but in the meanwhile we need to make a placeholder element in the array. T castItem = (item is T) ? (T)item : default(T); collection.Add(castItem); } } } public static void ReplaceDictionary(Type keyType, Type valueType, object dictionary, object newContents) { MethodInfo targetMethod = <API key>.MakeGenericMethod(keyType, valueType); targetMethod.Invoke(null, new object[] { dictionary, newContents }); } private static void <API key><TKey, TValue>(IDictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<object, object>> newContents) { dictionary.Clear(); foreach (var item in newContents) { // if the item was not a T, some conversion failed. the error message will be propagated, // but in the meanwhile we need to make a placeholder element in the dictionary. TKey castKey = (TKey)item.Key; // this cast shouldn't fail TValue castValue = (item.Value is TValue) ? (TValue)item.Value : default(TValue); dictionary[castKey] = castValue; } } } } }
import Ember from 'ember'; export default function backup(isOffline, backupFn, args) { return function(error) { if(isOffline(error)) { return backupFn.apply(null, args); } else { return Ember.RSVP.reject(error); } }; }
import java.io.*; import java.util.*; public class DavisStaircase { static int[] res; static int mod = 1000000007; //Complete the stepPerms function below. public static int stepPerms(int n) { if(n == 0) return 1; if(n < 0) return 0; if(res[n] == -1) { int sum = stepPerms(n-3) + stepPerms(n-2) + stepPerms(n-1); res[n] = sum; } return res[n]; } // public static void stepPerms() { // res[1] = 1; // res[2] = 2; // res[3] = 4; // for(int i=4;i<=36;i++){ // res[i] = res[i-1] + res[i-2] + res[i-3]; public static void main(String[] args) { res = new int[37]; for(int i=0;i<37;i++) res[i] = -1; stepPerms(36); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int num; for (int i = 0; i < n; i++) { num = sc.nextInt(); System.out.println(res[num]); } sc.close(); } }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class CI_Input { /** * IP address of the current user * * @var string */ protected $ip_address = FALSE; /** * Allow GET array flag * * If set to FALSE, then $_GET will be set to an empty array. * * @var bool */ protected $_allow_get_array = TRUE; /** * Standardize new lines flag * * If set to TRUE, then newlines are standardized. * * @var bool */ protected $<API key>; /** * Enable XSS flag * * Determines whether the XSS filter is always active when * GET, POST or COOKIE data is encountered. * Set automatically based on config setting. * * @var bool */ protected $_enable_xss = FALSE; /** * Enable CSRF flag * * Enables a CSRF cookie token to be set. * Set automatically based on config setting. * * @var bool */ protected $_enable_csrf = FALSE; /** * List of all HTTP request headers * * @var array */ protected $headers = array(); /** * Raw input stream data * * Holds a cache of php://input contents * * @var string */ protected $_raw_input_stream; /** * Parsed input stream data * * Parsed from php://input at runtime * * @see CI_Input::input_stream() * @var array */ protected $_input_stream; protected $security; protected $uni; /** * Class constructor * * Determines whether to globally enable the XSS processing * and whether to allow the $_GET array. * * @return void */ public function __construct() { $this->_allow_get_array = (config_item('allow_get_array') === TRUE); $this->_enable_xss = (config_item('<API key>') === TRUE); $this->_enable_csrf = (config_item('csrf_protection') === TRUE); $this-><API key> = (bool) config_item('<API key>'); $this->security =& load_class('Security', 'core'); // Do we need the UTF-8 class? if (UTF8_ENABLED === TRUE) { $this->uni =& load_class('Utf8', 'core'); } // Sanitize global arrays $this->_sanitize_globals(); // CSRF Protection check if ($this->_enable_csrf === TRUE && ! is_cli()) { $this->security->csrf_verify(); } log_message('info', 'Input Class Initialized'); } /** * Fetch from array * * Internal method used to retrieve values from global arrays. * * @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc. * @param mixed $index Index for item to be fetched from $array * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL) { is_bool($xss_clean) OR $xss_clean = $this->_enable_xss; // If $index is NULL, it means that the whole $array is requested isset($index) OR $index = array_keys($array); // allow fetching multiple keys at once if (is_array($index)) { $output = array(); foreach ($index as $key) { $output[$key] = $this->_fetch_from_array($array, $key, $xss_clean); } return $output; } if (isset($array[$index])) { $value = $array[$index]; } elseif (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) // Does the index contain array notation { $value = $array; for ($i = 0; $i < $count; $i++) { $key = trim($matches[0][$i], '[]'); if ($key === '') // Empty notation will return the value as array { break; } if (isset($value[$key])) { $value = $value[$key]; } else { return NULL; } } } else { return NULL; } return ($xss_clean === TRUE) ? $this->security->xss_clean($value) : $value; } /** * Fetch an item from the GET array * * @param mixed $index Index for item to be fetched from $_GET * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function get($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_GET, $index, $xss_clean); } /** * Fetch an item from the POST array * * @param mixed $index Index for item to be fetched from $_POST * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function post($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_POST, $index, $xss_clean); } /** * Fetch an item from POST data with fallback to GET * * @param string $index Index for item to be fetched from $_POST or $_GET * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function post_get($index, $xss_clean = NULL) { return isset($_POST[$index]) ? $this->post($index, $xss_clean) : $this->get($index, $xss_clean); } /** * Fetch an item from GET data with fallback to POST * * @param string $index Index for item to be fetched from $_GET or $_POST * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function get_post($index, $xss_clean = NULL) { return isset($_GET[$index]) ? $this->get($index, $xss_clean) : $this->post($index, $xss_clean); } /** * Fetch an item from the COOKIE array * * @param mixed $index Index for item to be fetched from $_COOKIE * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function cookie($index = NULL, $xss_clean = NULL) { return $this->_fetch_from_array($_COOKIE, $index, $xss_clean); } /** * Fetch an item from the SERVER array * * @param mixed $index Index for item to be fetched from $_SERVER * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function server($index, $xss_clean = NULL) { return $this->_fetch_from_array($_SERVER, $index, $xss_clean); } /** * Fetch an item from the php://input stream * * Useful when you need to access PUT, DELETE or PATCH request data. * * @param string $index Index for item to be fetched * @param bool $xss_clean Whether to apply XSS filtering * @return mixed */ public function input_stream($index = NULL, $xss_clean = NULL) { // Prior to PHP 5.6, the input stream can only be read once, // so we'll need to check if we have already done that first. if ( ! is_array($this->_input_stream)) { // $this->raw_input_stream will trigger __get(). parse_str($this->raw_input_stream, $this->_input_stream); is_array($this->_input_stream) OR $this->_input_stream = array(); } return $this->_fetch_from_array($this->_input_stream, $index, $xss_clean); } /** * Set cookie * * Accepts an arbitrary number of parameters (up to 7) or an associative * array in the first parameter containing all the values. * * @param string|mixed[] $name Cookie name or an array containing parameters * @param string $value Cookie value * @param int $expire Cookie expiration time in seconds * @param string $domain Cookie domain (e.g.: '.yourdomain.com') * @param string $path Cookie path (default: '/') * @param string $prefix Cookie name prefix * @param bool $secure Whether to only transfer cookies via SSL * @param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript) * @return void */ public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL) { if (is_array($name)) { // always leave 'name' in last place, as the loop will break otherwise, due to $$item foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item) { if (isset($name[$item])) { $$item = $name[$item]; } } } if ($prefix === '' && config_item('cookie_prefix') !== '') { $prefix = config_item('cookie_prefix'); } if ($domain == '' && config_item('cookie_domain') != '') { $domain = config_item('cookie_domain'); } if ($path === '/' && config_item('cookie_path') !== '/') { $path = config_item('cookie_path'); } $secure = ($secure === NULL && config_item('cookie_secure') !== NULL) ? (bool) config_item('cookie_secure') : (bool) $secure; $httponly = ($httponly === NULL && config_item('cookie_httponly') !== NULL) ? (bool) config_item('cookie_httponly') : (bool) $httponly; if ( ! is_numeric($expire)) { $expire = time() - 86500; } else { $expire = ($expire > 0) ? time() + $expire : 0; } setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); } /** * Fetch the IP Address * * Determines and validates the visitor's IP address. * * @return string IP address */ public function ip_address() { if ($this->ip_address !== FALSE) { return $this->ip_address; } $proxy_ips = config_item('proxy_ips'); if ( ! empty($proxy_ips) && ! is_array($proxy_ips)) { $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips)); } $this->ip_address = $this->server('REMOTE_ADDR'); if ($proxy_ips) { foreach (array('<API key>', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', '<API key>') as $header) { if (($spoof = $this->server($header)) !== NULL) { // Some proxies typically list the whole chain of IP // addresses through which the client has reached us. // e.g. client_ip, proxy_ip1, proxy_ip2, etc. sscanf($spoof, '%[^,]', $spoof); if ( ! $this->valid_ip($spoof)) { $spoof = NULL; } else { break; } } } if ($spoof) { for ($i = 0, $c = count($proxy_ips); $i < $c; $i++) { // Check if we have an IP address or a subnet if (strpos($proxy_ips[$i], '/') === FALSE) { // An IP address (and not a subnet) is specified. // We can compare right away. if ($proxy_ips[$i] === $this->ip_address) { $this->ip_address = $spoof; break; } continue; } // We have a subnet ... now the heavy lifting begins isset($separator) OR $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.'; // If the proxy entry doesn't match the IP protocol - skip it if (strpos($proxy_ips[$i], $separator) === FALSE) { continue; } // Convert the REMOTE_ADDR IP address to binary, if needed if ( ! isset($ip, $sprintf)) { if ($separator === ':') { // Make sure we're have the "full" IPv6 format $ip = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($this->ip_address, ':')), $this->ip_address ) ); for ($j = 0; $j < 8; $j++) { $ip[$j] = intval($ip[$j], 16); } $sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b'; } else { $ip = explode('.', $this->ip_address); $sprintf = '%08b%08b%08b%08b'; } $ip = vsprintf($sprintf, $ip); } // Split the netmask length off the network address sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen); // Again, an IPv6 address is most likely in a compressed form if ($separator === ':') { $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr)); for ($j = 0; $j < 8; $j++) { $netaddr[$j] = intval($netaddr[$j], 16); } } else { $netaddr = explode('.', $netaddr); } // Convert to binary and finally compare if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0) { $this->ip_address = $spoof; break; } } } } if ( ! $this->valid_ip($this->ip_address)) { return $this->ip_address = '0.0.0.0'; } return $this->ip_address; } /** * Validate IP Address * * @param string $ip IP address * @param string $which IP protocol: 'ipv4' or 'ipv6' * @return bool */ public function valid_ip($ip, $which = '') { switch (strtolower($which)) { case 'ipv4': $which = FILTER_FLAG_IPV4; break; case 'ipv6': $which = FILTER_FLAG_IPV6; break; default: $which = NULL; break; } return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which); } /** * Fetch user Agent string * * @return string|null user Agent string or NULL if it doesn't exist */ public function user_agent($xss_clean = NULL) { return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean); } /** * Sanitize Globals * * Internal method serving for the following purposes: * * - Unsets $_GET data, if query strings are not enabled * - Cleans POST, COOKIE and SERVER data * - Standardizes newline characters to PHP_EOL * * @return void */ protected function _sanitize_globals() { // Is $_GET data allowed? If not we'll set the $_GET to an empty array if ($this->_allow_get_array === FALSE) { $_GET = array(); } elseif (is_array($_GET)) { foreach ($_GET as $key => $val) { $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_POST Data if (is_array($_POST)) { foreach ($_POST as $key => $val) { $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); } } // Clean $_COOKIE Data if (is_array($_COOKIE)) { // Also get rid of specially treated cookies that might be set by a server // or silly application, that are of no use to a CI application anyway // but that when present will trip our 'Disallowed Key Characters' alarm // note that the key names below are single quoted strings, and are not PHP variables unset( $_COOKIE['$Version'], $_COOKIE['$Path'], $_COOKIE['$Domain'] ); foreach ($_COOKIE as $key => $val) { if (($cookie_key = $this->_clean_input_keys($key)) !== FALSE) { $_COOKIE[$cookie_key] = $this->_clean_input_data($val); } else { unset($_COOKIE[$key]); } } } // Sanitize PHP_SELF $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']); log_message('debug', 'Global POST, GET and COOKIE data sanitized'); } /** * Clean Input Data * * Internal method that aids in escaping data and * standardizing newline characters to PHP_EOL. * * @param string|string[] $str Input string(s) * @return string */ protected function _clean_input_data($str) { if (is_array($str)) { $new_array = array(); foreach (array_keys($str) as $key) { $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]); } return $new_array; } /* We strip slashes if magic quotes is on to keep things consistent NOTE: In PHP 5.4 <API key>() will always return 0 and it will probably not exist in future versions at all. */ if ( ! is_php('5.4') && <API key>()) { $str = stripslashes($str); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } // Remove control characters $str = <API key>($str, FALSE); // Standardize newlines if needed if ($this-><API key> === TRUE) { return preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $str); } return $str; } /** * Clean Keys * * Internal method that helps to prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * * @param string $str Input string * @param bool $fatal Whether to terminate script exection * or to return FALSE if an invalid * key is encountered * @return string|bool */ protected function _clean_input_keys($str, $fatal = TRUE) { if ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str)) { if ($fatal === TRUE) { return FALSE; } else { set_status_header(503); echo 'Disallowed Key Characters.'; exit(7); // EXIT_USER_INPUT } } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { return $this->uni->clean_string($str); } return $str; } /** * Request Headers * * @param bool $xss_clean Whether to apply XSS filtering * @return array */ public function request_headers($xss_clean = FALSE) { // If header is already defined, return it immediately if ( ! empty($this->headers)) { return $this->_fetch_from_array($this->headers, NULL, $xss_clean); } // In Apache, you can simply call <API key>() if (function_exists('<API key>')) { $this->headers = <API key>(); } else { isset($_SERVER['CONTENT_TYPE']) && $this->headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; foreach ($_SERVER as $key => $val) { if (sscanf($key, 'HTTP_%s', $header) === 1) { // take SOME_HEADER and turn it into Some-Header $header = str_replace('_', ' ', strtolower($header)); $header = str_replace(' ', '-', ucwords($header)); $this->headers[$header] = $_SERVER[$key]; } } } return $this->_fetch_from_array($this->headers, NULL, $xss_clean); } /** * Get Request Header * * Returns the value of a single member of the headers class member * * @param string $index Header name * @param bool $xss_clean Whether to apply XSS filtering * @return string|null The requested header on success or NULL on failure */ public function get_request_header($index, $xss_clean = FALSE) { static $headers; if ( ! isset($headers)) { empty($this->headers) && $this->request_headers(); foreach ($this->headers as $key => $value) { $headers[strtolower($key)] = $value; } } $index = strtolower($index); if ( ! isset($headers[$index])) { return NULL; } return ($xss_clean === TRUE) ? $this->security->xss_clean($headers[$index]) : $headers[$index]; } /** * Is AJAX request? * * Test to see if a request contains the <API key> header. * * @return bool */ public function is_ajax_request() { return ( ! empty($_SERVER['<API key>']) && strtolower($_SERVER['<API key>']) === 'xmlhttprequest'); } /** * Is CLI request? * * Test to see if a request was made from the command line. * * @deprecated 3.0.0 Use is_cli() instead * @return bool */ public function is_cli_request() { return is_cli(); } /** * Get Request Method * * Return the request method * * @param bool $upper Whether to return in upper or lower case * (default: FALSE) * @return string */ public function method($upper = FALSE) { return ($upper) ? strtoupper($this->server('REQUEST_METHOD')) : strtolower($this->server('REQUEST_METHOD')); } /** * Magic __get() * * Allows read access to protected properties * * @param string $name * @return mixed */ public function __get($name) { if ($name === 'raw_input_stream') { isset($this->_raw_input_stream) OR $this->_raw_input_stream = file_get_contents('php://input'); return $this->_raw_input_stream; } elseif ($name === 'ip_address') { return $this->ip_address; } } }
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif] <!-- Add your site or application content here --> <form action="" method="post" id="register-form" novalidate="novalidate"> <h2>User Registration</h2> <div id="form-content"> <fieldset> <div class="fieldgroup"> <label for="firstname">First Name</label> <input type="text" name="firstname"/> </div> <div class="fieldgroup"> <label for="lastname">Last Name</label> <input type="text" name="lastname"/> </div> <div class="fieldgroup"> <label for="email">Email</label> <input type="text" name="email"/> </div> <div class="fieldgroup"> <label for="password">Password</label> <input type="password" name="password"/> </div> <div class="fieldgroup"> <p class="right">By clicking register you agree to our <a target="_blank" href="/policy">policy</a>.</p> <input type="submit" value="Register" class="submit"/> </div> </fieldset> </div> <div class="fieldgroup"> <p>Already registered? <a href="/login">Sign in</a>.</p> </div> </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(b,o,i,l,e,r){b.<API key>=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.<API key>(i)[0]; e.src=' r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','UA-XXXXX-X');ga('send','pageview'); </script> </body> </html>
(function() { var winston = require('winston'); var logger = null; var init = function(config) { var logToConsole = !!config.logToConsole, logLevel = config.logLevel || 'error', filePath = typeof config.filePath !== 'undefined' ? config.filePath : '/tmp/nm-logger.log', maxsize = config.maxsize || 1024*1024*50, maxFiles = config.maxFiles || 10, transports = []; if (logToConsole) transports.push(new (winston.transports.Console)({level:logLevel})); transports.push(new winston.transports.File({ filename:filePath, level:logLevel, maxsize:maxsize, maxFiles:maxFiles })); logger = new (winston.Logger)({ transports: transports }); logger.write = function(message) { logger.info(message); }; <API key>(); }; var formatTime = function(dateTime) { var month = dateTime.getMonth()+1; if ((''+month).length === 1) month = '0'+month; var date = [dateTime.getFullYear(), month, dateTime.getDate()]; var time = [dateTime.getHours(), dateTime.getMinutes(), dateTime.getSeconds(), dateTime.getMilliseconds()]; return date.join('/') + ' ' + time.join(':'); }; var <API key> = function() { var overrideMethod = function(method) { var originalMethod = logger[method]; logger[method] = function(msg) { var fileAndLine = traceCaller(1); return originalMethod.call(this, formatTime(new Date()) + ' : ' + fileAndLine + ' : ' + msg); }; }; overrideMethod('debug'); overrideMethod('info'); overrideMethod('error'); overrideMethod('warn'); }; var traceCaller = function(n) { if (isNaN(n) || n < 0) n = 1; n += 1; var s = (new Error()).stack, a = s.indexOf('\n', 5); while (n a = s.indexOf('\n', a+1); if (a < 0) { a = s.lastIndexOf('\n', s.length); break; } } var b = s.indexOf('\n', a+1); if (b < 0) b = s.length; a = Math.max(s.lastIndexOf(' ', b), s.lastIndexOf('/', b)); b = s.lastIndexOf(':', b); s = s.substring(a+1, b); return s; }; var getLogger = function() { return logger; }; exports.init = init; exports.getLogger = getLogger; })();
package java.awt.image; import java.awt.Transparency; import java.awt.color.ColorSpace; /** * The <code>PackedColorModel</code> class is an abstract * {@link ColorModel} class that works with pixel values which represent * color and alpha information as separate samples and which pack all * samples for a single pixel into a single int, short, or byte quantity. * This class can be used with an arbitrary {@link ColorSpace}. The number of * color samples in the pixel values must be the same as the number of color * components in the <code>ColorSpace</code>. There can be a single alpha * sample. The array length is always 1 for those methods that use a * primitive array pixel representation of type <code>transferType</code>. * The transfer types supported are DataBuffer.TYPE_BYTE, * DataBuffer.TYPE_USHORT, and DataBuffer.TYPE_INT. * Color and alpha samples are stored in the single element of the array * in bits indicated by bit masks. Each bit mask must be contiguous and * masks must not overlap. The same masks apply to the single int * pixel representation used by other methods. The correspondence of * masks and color/alpha samples is as follows: * <ul> * <li> Masks are identified by indices running from 0 through * {@link ColorModel#getNumComponents() getNumComponents}&nbsp;-&nbsp;1. * <li> The first * {@link ColorModel#<API key>() <API key>} * indices refer to color samples. * <li> If an alpha sample is present, it corresponds the last index. * <li> The order of the color indices is specified * by the <code>ColorSpace</code>. Typically, this reflects the name of * the color space type (for example, TYPE_RGB), index 0 * corresponds to red, index 1 to green, and index 2 to blue. * </ul> * <p> * The translation from pixel values to color/alpha components for * display or processing purposes is a one-to-one correspondence of * samples to components. * A <code>PackedColorModel</code> is typically used with image data * that uses masks to define packed samples. For example, a * <code>PackedColorModel</code> can be used in conjunction with a * {@link <API key>} to construct a * {@link BufferedImage}. Normally the masks used by the * {@link SampleModel} and the <code>ColorModel</code> would be the same. * However, if they are different, the color interpretation of pixel data is * done according to the masks of the <code>ColorModel</code>. * <p> * A single <code>int</code> pixel representation is valid for all objects * of this class since it is always possible to represent pixel values * used with this class in a single <code>int</code>. Therefore, methods * that use this representation do not throw an * <code><API key></code> due to an invalid pixel value. * <p> * A subclass of <code>PackedColorModel</code> is {@link DirectColorModel}, * which is similar to an X11 TrueColor visual. * * @see DirectColorModel * @see <API key> * @see BufferedImage */ public abstract class PackedColorModel extends ColorModel { int[] maskArray; int[] maskOffsets; float[] scaleFactors; /** * Constructs a <code>PackedColorModel</code> from a color mask array, * which specifies which bits in an <code>int</code> pixel representation * contain each of the color samples, and an alpha mask. Color * components are in the specified <code>ColorSpace</code>. The length of * <code>colorMaskArray</code> should be the number of components in * the <code>ColorSpace</code>. All of the bits in each mask * must be contiguous and fit in the specified number of least significant * bits of an <code>int</code> pixel representation. If the * <code>alphaMask</code> is 0, there is no alpha. If there is alpha, * the <code>boolean</code> <code><API key></code> specifies * how to interpret color and alpha samples in pixel values. If the * <code>boolean</code> is <code>true</code>, color samples are assumed * to have been multiplied by the alpha sample. The transparency, * <code>trans</code>, specifies what alpha values can be represented * by this color model. The transfer type is the type of primitive * array used to represent pixel values. * @param space the specified <code>ColorSpace</code> * @param bits the number of bits in the pixel values * @param colorMaskArray array that specifies the masks representing * the bits of the pixel values that represent the color * components * @param alphaMask specifies the mask representing * the bits of the pixel values that represent the alpha * component * @param <API key> <code>true</code> if color samples are * premultiplied by the alpha sample; <code>false</code> otherwise * @param trans specifies the alpha value that can be represented by * this color model * @param transferType the type of array used to represent pixel values * @throws <API key> if <code>bits</code> is less than * 1 or greater than 32 */ public PackedColorModel (ColorSpace space, int bits, int[] colorMaskArray, int alphaMask, boolean <API key>, int trans, int transferType) { super(bits, PackedColorModel.createBitsArray(colorMaskArray, alphaMask), space, (alphaMask == 0 ? false : true), <API key>, trans, transferType); if (bits < 1 || bits > 32) { throw new <API key>("Number of bits must be between" +" 1 and 32."); } maskArray = new int[numComponents]; maskOffsets = new int[numComponents]; scaleFactors = new float[numComponents]; for (int i=0; i < numColorComponents; i++) { // Get the mask offset and #bits DecomposeMask(colorMaskArray[i], i, space.getName(i)); } if (alphaMask != 0) { DecomposeMask(alphaMask, numColorComponents, "alpha"); if (nBits[numComponents-1] == 1) { transparency = Transparency.BITMASK; } } } /** * Constructs a <code>PackedColorModel</code> from the specified * masks which indicate which bits in an <code>int</code> pixel * representation contain the alpha, red, green and blue color samples. * Color components are in the specified <code>ColorSpace</code>, which * must be of type ColorSpace.TYPE_RGB. All of the bits in each * mask must be contiguous and fit in the specified number of * least significant bits of an <code>int</code> pixel representation. If * <code>amask</code> is 0, there is no alpha. If there is alpha, * the <code>boolean</code> <code><API key></code> * specifies how to interpret color and alpha samples * in pixel values. If the <code>boolean</code> is <code>true</code>, * color samples are assumed to have been multiplied by the alpha sample. * The transparency, <code>trans</code>, specifies what alpha values * can be represented by this color model. * The transfer type is the type of primitive array used to represent * pixel values. * @param space the specified <code>ColorSpace</code> * @param bits the number of bits in the pixel values * @param rmask specifies the mask representing * the bits of the pixel values that represent the red * color component * @param gmask specifies the mask representing * the bits of the pixel values that represent the green * color component * @param bmask specifies the mask representing * the bits of the pixel values that represent * the blue color component * @param amask specifies the mask representing * the bits of the pixel values that represent * the alpha component * @param <API key> <code>true</code> if color samples are * premultiplied by the alpha sample; <code>false</code> otherwise * @param trans specifies the alpha value that can be represented by * this color model * @param transferType the type of array used to represent pixel values * @throws <API key> if <code>space</code> is not a * TYPE_RGB space * @see ColorSpace */ public PackedColorModel(ColorSpace space, int bits, int rmask, int gmask, int bmask, int amask, boolean <API key>, int trans, int transferType) { super (bits, PackedColorModel.createBitsArray(rmask, gmask, bmask, amask), space, (amask == 0 ? false : true), <API key>, trans, transferType); if (space.getType() != ColorSpace.TYPE_RGB) { throw new <API key>("ColorSpace must be TYPE_RGB."); } maskArray = new int[numComponents]; maskOffsets = new int[numComponents]; scaleFactors = new float[numComponents]; DecomposeMask(rmask, 0, "red"); DecomposeMask(gmask, 1, "green"); DecomposeMask(bmask, 2, "blue"); if (amask != 0) { DecomposeMask(amask, 3, "alpha"); if (nBits[3] == 1) { transparency = Transparency.BITMASK; } } } /** * Returns the mask indicating which bits in a pixel * contain the specified color/alpha sample. For color * samples, <code>index</code> corresponds to the placement of color * sample names in the color space. Thus, an <code>index</code> * equal to 0 for a CMYK ColorSpace would correspond to * Cyan and an <code>index</code> equal to 1 would correspond to * Magenta. If there is alpha, the alpha <code>index</code> would be: * <pre> * alphaIndex = numComponents() - 1; * </pre> * @param index the specified color or alpha sample * @return the mask, which indicates which bits of the <code>int</code> * pixel representation contain the color or alpha sample specified * by <code>index</code>. * @throws <API key> if <code>index</code> is * greater than the number of components minus 1 in this * <code>PackedColorModel</code> or if <code>index</code> is * less than zero */ final public int getMask(int index) { return maskArray[index]; } /** * Returns a mask array indicating which bits in a pixel * contain the color and alpha samples. * @return the mask array , which indicates which bits of the * <code>int</code> pixel * representation contain the color or alpha samples. */ final public int[] getMasks() { return (int[]) maskArray.clone(); } /* * A utility function to compute the mask offset and scalefactor, * store these and the mask in instance arrays, and verify that * the mask fits in the specified pixel size. */ private void DecomposeMask(int mask, int idx, String componentName) { int off = 0; int count = nBits[idx]; // Store the mask maskArray[idx] = mask; // Now find the shift if (mask != 0) { while ((mask & 1) == 0) { mask >>>= 1; off++; } } if (off + count > pixel_bits) { throw new <API key>(componentName + " mask "+ Integer.toHexString(maskArray[idx])+ " overflows pixel (expecting "+ pixel_bits+" bits"); } maskOffsets[idx] = off; if (count == 0) { // High enough to scale any 0-ff value down to 0.0, but not // high enough to get Infinity when scaling back to pixel bits scaleFactors[idx] = 256.0f; } else { scaleFactors[idx] = 255.0f / ((1 << count) - 1); } } /** * Creates a <code>SampleModel</code> with the specified width and * height that has a data layout compatible with this * <code>ColorModel</code>. * @param w the width (in pixels) of the region of the image data * described * @param h the height (in pixels) of the region of the image data * described * @return the newly created <code>SampleModel</code>. * @throws <API key> if <code>w</code> or * <code>h</code> is not greater than 0 * @see SampleModel */ public SampleModel <API key>(int w, int h) { return new <API key>(transferType, w, h, maskArray); } /** * Checks if the specified <code>SampleModel</code> is compatible * with this <code>ColorModel</code>. If <code>sm</code> is * <code>null</code>, this method returns <code>false</code>. * @param sm the specified <code>SampleModel</code>, * or <code>null</code> * @return <code>true</code> if the specified <code>SampleModel</code> * is compatible with this <code>ColorModel</code>; * <code>false</code> otherwise. * @see SampleModel */ public boolean <API key>(SampleModel sm) { if (! (sm instanceof <API key>)) { return false; } // Must have the same number of components if (numComponents != sm.getNumBands()) { return false; } // Transfer type must be the same if (sm.getTransferType() != transferType) { return false; } <API key> sppsm = (<API key>) sm; // Now compare the specific masks int[] bitMasks = sppsm.getBitMasks(); if (bitMasks.length != maskArray.length) { return false; } /* compare 'effective' masks only, i.e. only part of the mask * which fits the capacity of the transfer type. */ int maxMask = (int)((1L << DataBuffer.getDataTypeSize(transferType)) - 1); for (int i=0; i < bitMasks.length; i++) { if ((maxMask & bitMasks[i]) != (maxMask & maskArray[i])) { return false; } } return true; } /** * Returns a {@link WritableRaster} representing the alpha channel of * an image, extracted from the input <code>WritableRaster</code>. * This method assumes that <code>WritableRaster</code> objects * associated with this <code>ColorModel</code> store the alpha band, * if present, as the last band of image data. Returns <code>null</code> * if there is no separate spatial alpha channel associated with this * <code>ColorModel</code>. This method creates a new * <code>WritableRaster</code>, but shares the data array. * @param raster a <code>WritableRaster</code> containing an image * @return a <code>WritableRaster</code> that represents the alpha * channel of the image contained in <code>raster</code>. */ public WritableRaster getAlphaRaster(WritableRaster raster) { if (hasAlpha() == false) { return null; } int x = raster.getMinX(); int y = raster.getMinY(); int[] band = new int[1]; band[0] = raster.getNumBands() - 1; return raster.createWritableChild(x, y, raster.getWidth(), raster.getHeight(), x, y, band); } /** * Tests if the specified <code>Object</code> is an instance * of <code>PackedColorModel</code> and equals this * <code>PackedColorModel</code>. * @param obj the <code>Object</code> to test for equality * @return <code>true</code> if the specified <code>Object</code> * is an instance of <code>PackedColorModel</code> and equals this * <code>PackedColorModel</code>; <code>false</code> otherwise. */ public boolean equals(Object obj) { if (!(obj instanceof PackedColorModel)) { return false; } if (!super.equals(obj)) { return false; } PackedColorModel cm = (PackedColorModel) obj; int numC = cm.getNumComponents(); if (numC != numComponents) { return false; } for(int i=0; i < numC; i++) { if (maskArray[i] != cm.getMask(i)) { return false; } } return true; } private final static int[] createBitsArray(int[]colorMaskArray, int alphaMask) { int numColors = colorMaskArray.length; int numAlpha = (alphaMask == 0 ? 0 : 1); int[] arr = new int[numColors+numAlpha]; for (int i=0; i < numColors; i++) { arr[i] = countBits(colorMaskArray[i]); if (arr[i] < 0) { throw new <API key>("Noncontiguous color mask (" + Integer.toHexString(colorMaskArray[i])+ "at index "+i); } } if (alphaMask != 0) { arr[numColors] = countBits(alphaMask); if (arr[numColors] < 0) { throw new <API key>("Noncontiguous alpha mask (" + Integer.toHexString(alphaMask)); } } return arr; } private final static int[] createBitsArray(int rmask, int gmask, int bmask, int amask) { int[] arr = new int[3 + (amask == 0 ? 0 : 1)]; arr[0] = countBits(rmask); arr[1] = countBits(gmask); arr[2] = countBits(bmask); if (arr[0] < 0) { throw new <API key>("Noncontiguous red mask (" + Integer.toHexString(rmask)); } else if (arr[1] < 0) { throw new <API key>("Noncontiguous green mask (" + Integer.toHexString(gmask)); } else if (arr[2] < 0) { throw new <API key>("Noncontiguous blue mask (" + Integer.toHexString(bmask)); } if (amask != 0) { arr[3] = countBits(amask); if (arr[3] < 0) { throw new <API key>("Noncontiguous alpha mask (" + Integer.toHexString(amask)); } } return arr; } private final static int countBits(int mask) { int count = 0; if (mask != 0) { while ((mask & 1) == 0) { mask >>>= 1; } while ((mask & 1) == 1) { mask >>>= 1; count++; } } if (mask != 0) { return -1; } return count; } }
# 18s_rDNA Phil Gough's PhD Installation ## What's new in this version This version is the 3rd iteration of the concept for the PhD I'm working on. It will integrate the data into an interactive installation, and remove some of the more confusing or unreliable interactions ## Requirements This is built with openFrameworks (moving away from Processing) and relies on several openFrameworks addons. The installation now uses the Kinect and OpenNI for user-interaction.
<nav class="main-nav"> {% if page.url != "/index.html" %} <a href='{{ site.baseurl }}{{ page.about }}'> <span class="arrow">←</span> Home </a> {% endif %} {% if page.url != "/about/" %} {% if site.aboutPage %} <a href='{{ site.baseurl }}about'>About </a> {% endif %} {% endif %} <a class="cta" href="http://eepurl.com/bwabaX">Subscribe</a> </nav>
* { margin: 0; padding: 0; } body { background: #eeeeee; } #container, #table-container { position: absolute; width: 800px; top: 50px; left: 50%; margin-left: -400px; } #table-container { text-align: center; } table { display: inline-block; border-collapse: separate; border-spacing: 5px; vertical-align: top; margin: 10px auto; padding: 0 10px; } td { text-align: center; } h1 { font-size: 32px; } h2 { font-size: 18px; text-align: left; } a { color: #5252ad; text-decoration: none; } a:hover { color: #ef2900; } p { font-size: 18px; margin: 10px 0; } ul { list-style-type: none; } li { margin: 5px 0; } #spacer { height: 100px; } #footer { text-align: center; margin-bottom: 50px; }
(function(angular){ 'use strict'; angular.module('auth', ['ngRoute', 'ngCookies']) .service('AuthUserService', require('./user-service')) .controller('AuthController', require('./controller')) .directive('authAccountBox', require('./account-box/directive')) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/auth/:mode', { templateUrl: 'auth/index.tmpl', controller: 'AuthController' }); }]); })(angular);
#pragma once #include <geneial/namespaces.h> <API key>(geneial) { <API key>(utility) { <API key> { /** * @brief This class can be used widget style like. * Will allow to call make shared on protected ctors. */ template<typename CLIENT> class EnableMakeShared { protected: /** * @brief creates a shared pointer using make shared improved version * @param ctors arguments list for CLIENT * @return a shared pointer to the initialized object's ctor */ template<typename ...ARG> std::shared_ptr<CLIENT> static makeShared(ARG&&...arg) { struct <API key>: public CLIENT { <API key>(ARG&&...arg) : CLIENT(std::forward<ARG>(arg)...) { } }; return std::make_shared<<API key>>(std::forward<ARG>(arg)...); } }; } /* export namespace */ } /* namespace utility */ } /* namespace geneial */
import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'components/bottom-navigation'; const requireDemo = require.context( 'docs/src/pages/components/bottom-navigation', false, /\.(js|tsx)$/, ); const requireRaw = require.context( '!raw-loader!../../src/pages/components/bottom-navigation', false, /\.(js|md|tsx)$/, ); export default function Page({ demos, docs }) { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
module Heroics # Generate a static client that uses Heroics under the hood. This is a good # option if you want to ship a gem or generate API documentation using Yard. # @param module_name [String] The name of the module, as rendered in a Ruby # source file, to use for the generated client. # @param schema [Schema] The schema instance to generate the client from. # @param url [String] The URL for the API service. # @param options [Hash] Configuration for links. Possible keys include: # - default_headers: Optionally, a set of headers to include in every # request made by the client. Default is no custom headers. # - cache: Optionally, a Moneta-compatible cache to store ETags. Default # is no caching. def self.generate_client(module_name, schema, url, options) filename = File.dirname(__FILE__) + '/views/client.erb' eruby = Erubis::Eruby.new(File.read(filename)) context = build_context(module_name, schema, url, options) eruby.evaluate(context) end private # Process the schema to build up the context needed to render the source # template. def self.build_context(module_name, schema, url, options) resources = [] schema.resources.each do |resource_schema| links = [] resource_schema.links.each do |link_schema| links << GeneratorLink.new(link_schema.name.gsub('-', '_'), link_schema.description, link_schema.parameter_details, link_schema.needs_request_body?) end resources << GeneratorResource.new(resource_schema.name.gsub('-', '_'), resource_schema.description, links) end context = {module_name: module_name, url: url, default_headers: options.fetch(:default_headers, {}), cache: options.fetch(:cache, {}), description: schema.description, schema: MultiJson.dump(schema.schema), resources: resources} end # A representation of a resource for use when generating source code in the # template. class GeneratorResource attr_reader :name, :description, :links def initialize(name, description, links) @name = name @description = description @links = links end # The name of the resource class in generated code. def class_name Heroics.camel_case(name) end end # A representation of a link for use when generating source code in the # template. class GeneratorLink attr_reader :name, :description, :parameters, :takes_body def initialize(name, description, parameters, takes_body) @name = name @description = description @parameters = parameters if takes_body parameters << BodyParameter.new end end # The list of parameters to render in generated source code for the method # signature for the link. def parameter_names @parameters.map { |info| info.name }.join(', ') end end # Convert a lower_case_name to CamelCase. def self.camel_case(text) return text if text !~ /_/ && text =~ /[A-Z]+.*/ text = text.split('_').map{ |element| element.capitalize }.join [/^Ssl/, /^Http/, /^Xml/].each do |replace| text.sub!(replace) { |match| match.upcase } end text end # A representation of a body parameter. class BodyParameter attr_reader :name, :description def initialize @name = 'body' @description = 'the object to pass as the request payload' end end end
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>midic14</title> <link rel="stylesheet" type="text/css" href="csound.css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" /> <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" /> <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" /> <link rel="prev" href="midglobal.html" title="midglobal" /> <link rel="next" href="midic21.html" title="midic21" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">midic14</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="midglobal.html">Précédent</a> </td> <th width="60%" align="center">Opcodes et opérateurs de l'orchestre</th> <td width="20%" align="right"> <a accesskey="n" href="midic21.html">Suivant</a></td> </tr> </table> <hr /> </div> <div class="refentry"> <a id="midic14"></a> <div class="titlepage"></div> <a id="IndexMidic14" class="indexterm"></a> <div class="refnamediv"> <h2> <span class="refentrytitle">midic14</span> </h2> <p>midic14 — Permet un signal MIDI sur 14 bit en nombres décimaux selon une échelle entre des limites minimale et maximale. </p> </div> <div class="refsect1"> <a id="idm47887660016624"></a> <h2>Description</h2> <p> Permet un signal MIDI sur 14 bit en nombres décimaux selon une échelle entre des limites minimale et maximale. </p> </div> <div class="refsect1"> <a id="idm47887660015200"></a> <h2>Syntaxe</h2> <pre class="synopsis">idest <span class="command"><strong>midic14</strong></span> ictlno1, ictlno2, imin, imax [, ifn]</pre> <pre class="synopsis">kdest <span class="command"><strong>midic14</strong></span> ictlno1, ictlno2, kmin, kmax [, ifn]</pre> </div> <div class="refsect1"> <a id="idm47887660011712"></a> <h2>Initialisation</h2> <p> <span class="emphasis"><em>idest</em></span> -- signal de sortie </p> <p> <span class="emphasis"><em>ictln1o</em></span> </p> <p> <span class="emphasis"><em>ictlno2</em></span> </p> <p> <span class="emphasis"><em>imin</em></span> </p> <p> <span class="emphasis"><em>imax</em></span> </p> <p> <span class="emphasis"><em>ifn</em></span> (facultatif) La table doit être normalisée. La sortie est mise à l'échelle entre les valeurs <span class="emphasis"><em>imax</em></span> et <span class="emphasis"><em>imin</em></span>. </p> </div> <div class="refsect1"> <a id="idm47887660004224"></a> <h2>Exécution</h2> <p> <span class="emphasis"><em>kdest</em></span> -- signal de sortie </p> <p> <span class="emphasis"><em>kmin</em></span> </p> <p> <span class="emphasis"><em>kmax</em></span> </p> <p> <span class="emphasis"><em>midic14</em></span> (contrôle MIDI sur 14 bit au taux-i et au taux-k) permet un signal MIDI sur 14 bit en nombres décimaux mis à l'échelle entre des limites minimale et maximale. Les valeurs minimale et maximale peuvent être variées au taux-k. Il peut utiliser en option une indexation de table interpolée. Il nécessite deux contrôleurs MIDI en entrée. </p> <div class="note" style="margin-left: 0.5in; margin-right: 0.5in;"> <table border="0" summary="Note"> <tr> <td rowspan="2" align="center" valign="top" width="25"> <img alt="[Note]" src="images/note.png" /> </td> <th align="left">Note</th> </tr> <tr> <td align="left" valign="top"> <p>Veuillez noter que la famille des opcodes <span class="emphasis"><em>midic</em></span> est prévue pour des évènements MIDI déclenchés, et ne nécessite pas de numéro de canal car ils vont répondre au même canal que celui qui a déclenché l'instrument (voir <a class="link" href="massign.html" title="massign"><em class="citetitle">massign</em></a>). Cependant ils vont planter s'ils sont appelés depuis un évènement de partition.</p> </td> </tr> </table> </div> </div> <div class="refsect1"> <a id="idm47887659996512"></a> <h2>Voir aussi</h2> <p> <a class="link" href="ctrl7.html" title="ctrl7"><em class="citetitle">ctrl7</em></a>, <a class="link" href="ctrl14.html" title="ctrl14"><em class="citetitle">ctrl14</em></a>, <a class="link" href="ctrl21.html" title="ctrl21"><em class="citetitle">ctrl21</em></a>, <a class="link" href="initc7.html" title="initc7"><em class="citetitle">initc7</em></a>, <a class="link" href="initc14.html" title="initc14"><em class="citetitle">initc14</em></a>, <a class="link" href="initc21.html" title="initc21"><em class="citetitle">initc21</em></a>, <a class="link" href="midic7.html" title="midic7"><em class="citetitle">midic7</em></a>, <a class="link" href="midic21.html" title="midic21"><em class="citetitle">midic21</em></a> </p> </div> <div class="refsect1"> <a id="idm47887659987680"></a> <h2>Crédits</h2> <p> </p> <table border="0" summary="Simple list" class="simplelist"> <tr> <td>Auteur : Gabriel Maldonado</td> </tr> <tr> <td>Italie</td> </tr> </table> <p> </p> <p>Nouveau dans la version 3.47 de Csound</p> <p>Merci à Rasmus Ekman pour avoir indiqué le bon intervalle pour le numéro de contrôleur.</p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="midglobal.html">Précédent</a> </td> <td width="20%" align="center"> <a accesskey="u" href="OpcodesTop.html">Niveau supérieur</a> </td> <td width="40%" align="right"> <a accesskey="n" href="midic21.html">Suivant</a></td> </tr> <tr> <td width="40%" align="left" valign="top">midglobal </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Sommaire</a> </td> <td width="40%" align="right" valign="top"> midic21</td> </tr> </table> </div> </body> </html>
require 'nokogiri' require 'date' require 'open-uri' module Wordpress module Comments class Client attr_reader :url def initialize url @url = url end def parse xml doc = Nokogiri::XML(xml) { |config| config.strict } doc.search('item').map do |doc_item| item = {} item[:link] = doc_item.at('link').text item[:title] = doc_item.at('title').text item[:commenter] = doc_item.xpath('dc:creator').text item[:date] = DateTime.parse doc_item.at('pubDate').text item end end def fetch xml = get @url parse xml end private def get url open url end end end end
(function ( $ ) { $.fn.skillBars = function( options ) { var settings = $.extend({ from: 0, // number start to: false, // number end speed: 1000, // how long it should take to count between the target numbers interval: 100, // how often the element should be updated decimals: 0, // the number of decimal places to show onUpdate: null, // callback method for every time the element is updated, onComplete: null, // callback method for when the element finishes updating /*onComplete: function(from) { console.debug(this); }*/ classes:{ skillBarBar : '.skillbar-bar', skillBarPercent : '.skill-bar-percent', } }, options ); return this.each(function(){ var obj = $(this), to = (settings.to != false) ? settings.to : parseInt(obj.attr('data-percent')); if(to > 100){ to = 100; }; var from = settings.from, loops = Math.ceil(settings.speed / settings.interval), increment = (to - from) / loops, loopCount = 0, interval = setInterval(updateValue, settings.interval); obj.find(settings.classes.skillBarBar).animate({ width: parseInt(obj.attr('data-percent'))+'%' }, settings.speed); function updateValue(){ from += increment; loopCount++; $(obj).find(settings.classes.skillBarPercent).text(from.toFixed(settings.decimals)+'%'); if (typeof(settings.onUpdate) == 'function') { settings.onUpdate.call(obj, from); } if (loopCount >= loops) { clearInterval(interval); from = to; if (typeof(settings.onComplete) == 'function') { settings.onComplete.call(obj, from); } } } }); }; }( jQuery ));
require 'kickscraper' Kickscraper.configure do |config| config.email = '' config.password = '' end client = Kickscraper.client puts " A | C |" puts " client.user.backed_projects.each {|x| print (x.active? ? ' X |' : ' |') print (x.successful? ? ' X | ' : ' | ') puts x.name }
<?php namespace controllers; class validController extends <API key> { public function __construct(&$c) { parent::__construct($c); } public function indexAction() { return 'CookController indexAction'; } public function setAction($name='') { $v = new \Valitron\Validator(array('name' => $name)); \Valitron\Validator::addRule('md5', function($field, $value) { return (!preg_match('/^([a-zA-Z0-9]{32})$/', $value)) ? false : true; }, 'is not a MD5 value'); $v->rule('required','name'); $v->rule('md5','name'); $v->rule('length','name','32'); if ($v->validate()) { return "Yay! We're all good!"; } else { return print_r($v->errors(),true); } } public function testAction($num='') { $foo = $this->c->Request->get('num',0,<API key>); return '<h3>Foo is: '.(($foo) ? 'true' : 'false').'</h3>'; } } /* end controller */
let currentPosition, currentOffset, currentSpeed, tripletMeasure; function reset () { currentPosition = 1; currentSpeed = 1; tripletMeasure = false; } function size () { let increment = 1 * currentSpeed; if (tripletMeasure) { increment = (increment / 3) * 2; } return increment; } function step () { currentPosition += size(); currentOffset = 0; } function offset(offset) { if (typeof offset !== 'undefined') { currentOffset = offset; } else { return currentOffset || 0; } } function position (position) { if (position) { currentPosition = position; } else { return currentPosition; } } function speed (speed) { if (speed) { currentSpeed = speed; } else { return currentSpeed; } } function triplets (triplets) { if (typeof triplets === 'boolean') { tripletMeasure = triplets; } else { return tripletMeasure; } } export default { reset, step, position, speed, triplets, size, offset };
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Colores_model extends CI_Model { //Obtiene todos los colores function getColores($codigo_idioma) { $this->db->select('id, nombre'); $this->db->from('listar_colores'); $this->db->where('codigo', $codigo_idioma); $this->db->order_by('nombre', 'ASC'); $query = $this->db->get(); $colores = array(); foreach ($query->result() as $color) { $color->nombre = stripslashes($color->nombre); $colores[] = $color; } return $colores; } //Obtiene un color por id function getColor($id, $codigo_idioma) { $this->db->select('id, nombre'); $this->db->from('listar_colores'); $this->db->where('id', $id); $this->db->where('codigo', $codigo_idioma); $query = $this->db->get(); $color = NULL; if ($query->num_rows() > 0) { $color = $query->first_row(); } return $color; } //Obtiene todos los colores por producto function getColorProductos($id, $codigo_idioma) { $this->db->select('id_colores, color'); $this->db->from('<API key>'); $this->db->where('id', $id); $this->db->where('codigo', $codigo_idioma); $this->db->order_by('color', 'ASC'); $query = $this->db->get(); $colores = array(); foreach ($query->result() as $color) { $colores[] = $color; } return $colores; } //Actualiza los textos de un color function updateColor($id, $nombre, $codigo_idioma) { $datos = array( 'nombre' => $nombre ); $this->db->where('id', $id); $this->db->where('codigo', $codigo_idioma); $query = $this->db->update('listar_colores', $datos); return $query; } //Inserta un color function insertColor() { $this->db->set('id', NULL); $query = $this->db->insert('colores'); return $query; } function getUltimoId() { $this->db->select_max('id'); $query = $this->db->get('colores'); return $query->first_row(); } //Inserta los textos de un color function insertColorIdioma($fk_colores, $fk_idiomas, $nombre) { $datos = array( 'fk_colores' => $fk_colores, 'fk_idiomas' => $fk_idiomas, 'nombre' => $nombre ); $query = $this->db->insert('colores_idiomas', $datos); return $query; } //Elimina un color function deleteColor($id) { $datos = array( 'id' => $id ); $query = $this->db->delete('colores', $datos); return $query; } }
# Generated by Django 3.2.4 on 2021-06-11 13:24 import calaccess_processed.proxies from django.db import migrations class Migration(migrations.Migration): initial = True dependencies = [ ('elections', '<API key>'), ] operations = [ migrations.CreateModel( name='<API key>', fields=[ ], options={ 'verbose_name_plural': 'ballot measures', 'proxy': True, 'indexes': [], 'constraints': [], }, bases=('elections.<API key>', calaccess_processed.proxies.OCDProxyModelMixin), ), migrations.CreateModel( name='<API key>', fields=[ ], options={ 'verbose_name_plural': 'candidates', 'proxy': True, 'indexes': [], 'constraints': [], }, bases=('elections.candidacy', calaccess_processed.proxies.OCDProxyModelMixin), ), migrations.CreateModel( name='<API key>', fields=[ ], options={ 'verbose_name_plural': 'recall measures', 'proxy': True, 'indexes': [], 'constraints': [], }, bases=('elections.retentioncontest', calaccess_processed.proxies.OCDProxyModelMixin), ), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom managers for the Division model. """ from __future__ import unicode_literals from calaccess_processed.managers import BulkLoadSQLManager class <API key>(BulkLoadSQLManager): """ Custom manager for state assembly OCD Divisions. """ def get_queryset(self): """ Filters down to state assembly divisions. """ qs = super(<API key>, self).get_queryset() return qs.filter(subid1='ca', subtype2='sldl') class <API key>(BulkLoadSQLManager): """ Custom manager for state senate OCD Divisions. """ def get_queryset(self): """ Filters down to state senate divisions. """ qs = super(<API key>, self).get_queryset() return qs.filter(subid1='ca', subtype2='sldu') class <API key>(BulkLoadSQLManager): """ Custom manager for OCD Divisions in California. """ def get_queryset(self): """ Filters down to divisions in California. """ qs = super(<API key>, self).get_queryset() return qs.filter(subid1='ca') def california(self): """ Returns state of California division. """ qs = super(<API key>, self).get_queryset() return qs.get(id='ocd-division/country:us/state:ca')
package org.snf4j.websocket.frame; public class ContinuationFrame extends DataFrame { /** * Constructs a Web Socket continuation frame containing binary data. * * @param finalFragment determines if the created frame is the final fragment in * a message * @param rsvBits reserved bits for extensions or future versions * @param payload payload data */ public ContinuationFrame(boolean finalFragment, int rsvBits, byte[] payload) { super(Opcode.CONTINUATION, finalFragment, rsvBits, payload); } /** * Constructs a Web Socket continuation frame containing binary data. The frame * is created as the final fragment in a message and with all reserved bits * cleared. * * @param payload payload data */ public ContinuationFrame(byte[] payload) { super(Opcode.CONTINUATION, payload); } /** * Constructs an empty Web Socket continuation frame. The frame is created as * the final fragment in a message and with all reserved bits cleared. */ public ContinuationFrame() { this(EMPTY_PAYLOAD); } /** * Constructs a Web Socket continuation frame containing text data. * * @param finalFragment determines if the created frame is the final fragment in * a message * @param rsvBits reserved bits for extensions or future versions * @param text text data */ public ContinuationFrame(boolean finalFragment, int rsvBits, String text) { this(finalFragment, rsvBits, TextFrame.toBytes(text)); } /** * Constructs a Web Socket continuation frame containing text data. The frame is * created as the final fragment in a message and with all reserved bits * cleared. * * @param text text data */ public ContinuationFrame(String text) { this(TextFrame.toBytes(text)); } /** * Returns the text data in this frame. * * @return the text data */ public String getText() { return TextFrame.fromBytes(payload); } }
<?php namespace Sidex\Framework\Database\PDO; use PDO; class Connector { /** * PDO Object * * @access protected */ protected $pdo; protected function connect() { $config = $this->dbconfig('config/database.php'); extract(require $config); $this->pdo = new PDO($dsn, $username, $password, $options); foreach($queryes as $q) { $this->pdo->prepare($q)->execute(); } return $this->pdo; } protected function dbconfig($path) { return application_path($path); } // end class... } /* End of file Connector.php */ /* Location: ./(<application folder>/libraries/<namespace>)/Connector.php */
a { text-decoration: none; } #admacademica p { font-size: 1.9em; margin: 28% 0 0 3%; } #admacademica img { margin: 25% 14% 0 6%; } #admPersonas p { font-size: 1.5em; margin-top: 21%; } #admPersonas img { margin: 10% 19% 0% 10%; } #aulaVirtual p { font-size: 2.5em; margin-top: 17%; } #CinferiorDer { height: 38%; overflow: hidden; width: 53%; } #CinferiorDer .boxMPA:nth-child(1) { margin-right: 0.25em; } #CinferiorIzq { height: 38%; overflow: hidden; width: 45%; } #CinferiorIzq .boxMPA:nth-child(1) { margin-right: 0.25em; } #CsuperiorDer { height: 61%; margin: 0 0 0.25em 0; overflow: hidden; vertical-align: top; width: 53%; } #CsuperiorDer .boxMPA:nth-child(1) { margin-right: 0.25em; } #CsuperiorDer .boxMPA:nth-child(2) { margin-bottom: 0.25em; } #CsuperiorIzq { height: 61%; margin: 0 0 0.25em 0; overflow: hidden; vertical-align: top; width: 45%; } #CsuperiorIzq .boxMPA:nth-child(1) { margin-right: 0.25em; } #CsuperiorIzq .boxMPA:nth-child(2) { margin-bottom: 0.25em; } #CsuperiorIzq, #CsuperiorDer, #CinferiorIzq, #CinferiorDer { display: inline-block; vertical-align: top; } #confSitema p { font-size: 2em; margin-top: 70%; } #confSitema img { margin: 30% 10% 0 2%; } #Estaditicas p { font-size: 1.5em; margin-top: 25%; } #Estaditicas img { margin: 5% 15% 0 2%; } #organizador p { font-size: 1.3em; margin-top: 21%; } #obsevaciones p { font-size: 1.3em; margin-top: 21%; } #planEstudios p { font-size: 1.5em; margin-top: 20%; } #planEstudios img { margin: 3% 8% 0 0%; } #perfil p { font-size: 3.5em; margin-top: 21%; } #tutoriales p { font-size: 1.8em; margin-top: 35%; } .boxMPA { cursor: pointer; box-shadow: inset 0px 0px 1px #ffc; float: left; overflow: hidden; padding: 0.5em; position: relative; transition: all 0.5s ease; vertical-align: top; -webkit-transition: all 0.1s linear; } .boxMPA:hover { -webkit-box-shadow: inset 0px 0px 0px 3px rgba(58,58,58,0.8); box-shadow: inset 0px 0px 0px 3px rgba(58,58,58,0.8); } .caja1MPA { height: 203px; width: 164px; } .caja2MPA { height: 91.5px; width: 133px; } .caja3MPA { height: 203px; width: 56%; } .caja4MPA { height: 120px; width: 164px; } .caja5MPA { height: 120px; width: 133px; } .caja6MPA { height: 120px; width: 56%; } .textoMPA { color: #fff; font-family: "Segoe UI light"; line-height: 1.1; position: relative; word-wrap: break-word; } .TexLeft { text-align: left; } .TexCentro { text-align: center; }
.SUFFIXES: ifeq ($(strip $(PSL1GHT)),) $(error "PSL1GHT must be set in the environment.") endif include $(PSL1GHT)/host/ppu.mk TARGET := $(notdir $(CURDIR)) BUILD := build SOURCE := source INCLUDE := include DATA := data LIBS := -lnet -lsysmodule TITLE := ECHOServer - PSL1GHT APPID := TEST0SRV1 CONTENTID := UP0001-$(APPID)<API key> PKGFILES := release CFLAGS += -O2 -Wall -std=gnu99 CXXFLAGS += -O2 -Wall ifneq ($(BUILD),$(notdir $(CURDIR))) export OUTPUT := $(CURDIR)/$(TARGET) export VPATH := $(foreach dir,$(SOURCE),$(CURDIR)/$(dir)) \ $(foreach dir,$(DATA),$(CURDIR)/$(dir)) export BUILDDIR := $(CURDIR)/$(BUILD) export DEPSDIR := $(BUILDDIR)
var gulp = require('gulp'); var browserSync = require('browser-sync'); var mainBowerFiles = require('main-bower-files'); var filter = require('gulp-filter'); var flatten = require('gulp-flatten'); var jade = require('gulp-jade'); var htmlPrettify = require('gulp-html-prettify'); var inject = require('gulp-inject'); var less = require('gulp-less'); var gulpSync = require('gulp-sync')(gulp); var changed = require('gulp-changed'); var pathModule = require('path'); var path = { getDebugPath:function(){ return './build/debug/'; }, getSrcPath:function(){ return './src'; } } var InjectOption = function(injectName,type){ } var browserSyncInstance = browserSync.create(); gulp.task('default',['debug']); gulp.task('debug',['debug:watch'],function(){ browserSyncInstance.init({ files:[ path.getDebugPath() + 'app*.html', path.getDebugPath() + 'index.html', path.getDebugPath() + 'common*.js', return gulp.src(path.getSrcPath() + '/assets/img*') return gulp.src(path.getSrcPath() + '*.js') .pipe(filter('**/*.js')) return gulp.src([path.getSrcPath() + '*.jade']) return gulp.src([path.getSrcPath() + '/app/*.less',path.getSrcPath() + '/app/**/*.less']) return gulp.src(path.getSrcPath() + '/common*.less') var lessFilter = filter('**/*.less'); .pipe(inject(gulp.src([path.getDebugPath() + 'app*.js','!'+ path.getDebugPath() + 'app/init.js','!'+ path.getDebugPath() + 'app/route.js']),{name:'components',ignorePath:'/build/debug'})) .pipe(inject(gulp.src([path.getDebugPath() + 'common*.js']),{name:'common',ignorePath:'/build/debug'})) .pipe(inject(gulp.src([path.getDebugPath() + 'app*.js','!'+ path.getDebugPath() + 'app/init.js','!'+ path.getDebugPath() + 'app/route.js']),{name:'components',ignorePath:'/build/debug'})) .pipe(inject(gulp.src([path.getDebugPath() + 'common*.js']),{name:'common',ignorePath:'/build/debug'})) gulp.watch(['src*.jade','!src/index.jade'],['debug:compile:html']); gulp.watch('src*.js',['debug:compile:scripts']); gulp.watch('src*.less',['debug:compile:stylesheet']);
# -*- coding: utf-8 -*- $TESTING=true require 'rubygems' require 'rspec' require 'wpconv' Dir[File.join(File.dirname(__FILE__), "..", "lib", "**/*.rb")].each do |f| require f end RSpec.configure do |config| config.color_enabled = true config.<API key> :skip => true end
/** * Instantiated and export Models. * * Throughout the app these instantiated models will be the canonical instance. */ import { LadderItem, LadderModel, MatchItem, MatchModel, TeamItem, TeamModel, VenueItem, VenueModel, } from './index'; const ladder = new LadderModel<LadderItem>(LadderItem); const match = new MatchModel<MatchItem>(MatchItem); const team = new TeamModel<TeamItem>(TeamItem); const venue = new VenueModel<VenueItem>(VenueItem); export { ladder as Ladder, match as Match, team as Team, venue as Venue, };
<?php namespace RedKiteLabs\RedKiteCms\<API key>\Tests\Unit\Core\Block\Menu; use RedKiteLabs\RedKiteCms\<API key>\Core\Block\Menu\<API key>; /** * <API key> * * @author RedKite Labs <info@redkite-labs.com> */ class <API key> extends <API key> { protected function setUp() { parent::setUp(); $this->blocksTemplate = '<API key>:Content:Menu/menu_vertical.html.twig'; } protected function getBlockManager() { return new <API key>($this->container, $this->validator); } }
# confreaks [![Build Status](https: confreaks on the command line ## Installation Grab binary from [release page](https://github.com/subosito/confreaks/releases/latest) Or if you have go installed, you can simply: go get github.com/subosito/confreaks
<ol id="posts"> {block:Posts}{block:Text} <li class="post text"> {block:Title} <h3><a href="{Permalink}">{Title}</a></h3> {/block:Title}{Body} </li> {/block:Text}{block:Photo} <li class="post photo"> <img src="{PhotoURL-500}" alt="{PhotoAlt}"/> {block:Caption} <div class="caption">{Caption}</div> {/block:Caption} </li> {/block:Photo}{block:Panorama} <li class="post panorama"> {LinkOpenTag} <img src="{PhotoURL-Panorama}" alt="{PhotoAlt}"/> {LinkCloseTag}{block:Caption} <div class="caption">{Caption}</div> {/block:Caption} </li> {/block:Panorama}{block:Photoset} <li class="post photoset"> {Photoset-500}{block:Caption} <div class="caption">{Caption}</div> {/block:Caption} </li> {/block:Photoset}{block:Quote} <li class="post quote"> "{Quote}" {block:Source} <div class="source">{Source}</div> {/block:Source} </li> {/block:Quote}{block:Link} <li class="post link"> <a href="{URL}" class="link" {Target}>{Name}</a> {block:Description} <div class="description">{Description}</div> {/block:Description} </li> {/block:Link}{block:Chat} <li class="post chat"> {block:Title} <h3><a href="{Permalink}">{Title}</a></h3> {/block:Title} <ul class="chat"> {block:Lines} <li class="{Alt} user_{UserNumber}"> {block:Label} <span class="label">{Label}</span> {/block:Label}{Line} </li> {/block:Lines} </ul> </li> {/block:Chat}{block:Video} <li class="post video"> {Video-500}{block:Caption} <div class="caption">{Caption}</div> {/block:Caption} </li> {/block:Video}{block:Audio} <li class="post audio"> {AudioEmbed}{block:Caption} <div class="caption">{Caption}</div> {/block:Caption} </li> {/block:Audio}{/block:Posts} </ol> <p id="footer"> {block:PreviousPage} <a href="{PreviousPage}">&#171; Previous</a> {/block:PreviousPage}{block:NextPage} <a href="{NextPage}">Next &#187;</a> {/block:NextPage} <a href="/archive">Archive</a> </p> </body> </html>
// This file is part of RTIMULib-Teensy // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // copies or substantial portions of the Software. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // The MPU-9250 driver code is based on code generously supplied by // UU: This file was changed to // include temperature from pressure, humidity and IMU in data structure #ifndef _RTIMULIBDEFS_H #define _RTIMULIBDEFS_H #include "RTMath.h" #include "utility/RTIMUDefs.h" // these defines describe the various fusion filter options #define RTFUSION_TYPE_NULL 0 // just a dummy to keep things happy if not needed #define <API key> 1 // kalman state is the quaternion pose #define RTFUSION_TYPE_RTQF 2 // RT quaternion fusion #define RTFUSION_TYPE_AHRS 3 // AHRS quaternion fusion #define RTFUSION_TYPE_COUNT 4 // number of fusion algorithm types #define MAGFIELDNORM 47.118f // Earths Magnetic Field Strength in Tucson #define DECLINATION 9.98f * 3.1415926535f / 180.0f // Declination in Tucson // This is a convenience structure that can be used to pass IMU data around typedef struct { uint64_t timestamp; bool fusionPoseValid; RTVector3 fusionPose; bool fusionQPoseValid; RTQuaternion fusionQPose; bool gyroValid; RTVector3 gyro; bool accelValid; RTVector3 accel; bool compassValid; RTVector3 compass; bool motion; bool temperatureValid; RTFLOAT temperature; } RTIMU_DATA; typedef struct { uint64_t timestamp; bool humidityValid; RTFLOAT humidity; bool temperatureValid; RTFLOAT temperature; } HUMIDITY_DATA; typedef struct { uint64_t timestamp; bool pressureValid; RTFLOAT pressure; bool temperatureValid; RTFLOAT temperature; } PRESSURE_DATA; typedef struct { RTVector3 worldAcceleration; RTVector3 worldVelocity; RTVector3 worldPosition; RTVector3 worldVelocityDrift; RTVector3 residuals; bool motion; } MOTION_DATA; #endif // _RTIMULIBDEFS_H
const Language = require('./Language'); module.exports = Language;
#!/usr/bin python3 # -*- coding:utf-8 -*- # File Name: fact.py # Mail: niuleipeng@gmail.com # Created Time: 2016-05-11 17:27:38 # def fact(n): # if n == 1: # return 1 # return fact(n-1) * n def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product) num = int(input('input a number plz:')) print(fact(num));
import java.util.LinkedList; public interface FileEncoderFN { public void encode(String sourceFile, String destinationFile, LinkedList<Character> key); /** * Encodes a file with the specified key and saves the result to a given file. * @param sourceFile - path to the initial file * @param destinationFile - path to the result file * @param key - list of replacement bytes */ public void decode(String encodedFile, String destinationFile, LinkedList<Character> key); /** * Decodes a file that was encoded with the above algorithm. * @param encodedFile - path to encoded file * @param destinationFile - path to the result file * @param key - list of replacement bytes that were used to encode the file */ }