repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
michaeltandy/contraction-hierarchies
src/main/java/uk/me/mjt/ch/UnionList.java
1027
package uk.me.mjt.ch; import java.util.AbstractList; import java.util.Collections; import java.util.List; public class UnionList<N> extends AbstractList<N> implements List<N> { private final List<N> first; private final List<N> second; private final int size; public UnionList(List<N> first, N second) { this(first,Collections.singletonList(second)); } public UnionList(List<N> first, List<N> second) { Preconditions.checkNoneNull(first,second); this.first = first; this.second = second; this.size = first.size() + second.size(); } @Override public N get(int index) { if (index < first.size()) { return first.get(index); } else { return second.get(index-first.size()); } } @Override public int size() { return size; } public List<N> getFirstSublist() { return first; } public List<N> getSecondSublist() { return second; } }
mit
danielabar/framegen
FramegenCore/src/main/java/com/framegen/core/framehandler/option/NegativeFrameHandler.java
4070
package com.framegen.core.framehandler.option; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.framegen.api.response.FrameHandlerVO; import com.framegen.api.response.TaskResultVO; import com.framegen.api.service.IFrameHandler; import com.framegen.api.settings.SettingsVO; import com.framegen.api.settings.option.NegativeSettingsVO; import com.framegen.core.framehandler.FrameHandlerBase; import com.framegen.core.task.OffsetFilterTask; import com.framegen.core.taskvo.OffsetFilterTaskVO; public class NegativeFrameHandler extends FrameHandlerBase implements IFrameHandler { private static final Float MULTIPLIER_START = Float.valueOf("1.0"); private static final Float MULTIPLIER_END = Float.valueOf("-1.0"); private static final Float OFFSET_START = Float.valueOf("0"); private static final Float OFFSET_END = Float.valueOf("255"); private final ExecutorService taskExecutor; private final CompletionService<TaskResultVO> taskCompletionService; public NegativeFrameHandler() { super(); this.taskExecutor = Executors.newFixedThreadPool(getNumberOfThreads()); this.taskCompletionService = new ExecutorCompletionService<TaskResultVO>(taskExecutor); } @Override public Integer getNumberOfFrames(SettingsVO settings) throws IOException { NegativeSettingsVO negativeSettings = settings.getNegativeSettings(); return negativeSettings.getSteps() + 1; } @Override public FrameHandlerVO generateFrames(SettingsVO settings) throws IOException, InterruptedException { BufferedImage baseImage = getBaseImage(settings); NegativeSettingsVO negativeSettings = settings.getNegativeSettings(); Integer steps = negativeSettings.getSteps(); Float multiplierIncrement = (MULTIPLIER_START - MULTIPLIER_END) / steps; Float offsetIncrement = (OFFSET_END - OFFSET_START) / steps; for (int i=0; i<steps; i++) { OffsetFilterTaskVO offsetFilterTaskVO = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), getMultiplier(i, multiplierIncrement), getOffset(i, offsetIncrement), settings.getProgramSettings().getGeneratedImageNamePrefix(), i, NUMBER_OF_PAD_CHARS, steps); OffsetFilterTask<TaskResultVO> task = new OffsetFilterTask<TaskResultVO>(offsetFilterTaskVO); taskCompletionService.submit(task); } OffsetFilterTaskVO vo = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), MULTIPLIER_END, OFFSET_END, settings.getProgramSettings().getGeneratedImageNamePrefix(), steps, NUMBER_OF_PAD_CHARS, steps); OffsetFilterTask<String> task = new OffsetFilterTask<String>(vo); taskCompletionService.submit(task); return buildFrameHandlerResponse(taskCompletionService, steps+1); } private Float getMultiplier(int i, Float multiplierIncrement) { return MULTIPLIER_START - (i * multiplierIncrement); } private Float getOffset(int i, Float offsetIncrement) { return OFFSET_START + (i * offsetIncrement); } @Override public Double getAllFrameSize(SettingsVO settings) throws Exception { BufferedImage baseImage = getBaseImage(settings); NegativeSettingsVO negativeSettings = settings.getNegativeSettings(); Integer steps = negativeSettings.getSteps(); Float multiplierIncrement = (MULTIPLIER_START - MULTIPLIER_END) / steps; Float offsetIncrement = (OFFSET_END - OFFSET_START) / steps; OffsetFilterTaskVO offsetFilterTaskVO = new OffsetFilterTaskVO(baseImage, settings.getProgramSettings().getOutputDir(), getMultiplier(1, multiplierIncrement), getOffset(1, offsetIncrement), settings.getProgramSettings().getGeneratedImageNamePrefix(), 1, NUMBER_OF_PAD_CHARS, steps); OffsetFilterTask<TaskResultVO> task = new OffsetFilterTask<TaskResultVO>(offsetFilterTaskVO); TaskResultVO overlayResultVO = task.overlay(); return overlayResultVO.getFrameSize() * getNumberOfFrames(settings); } }
mit
akaiz/swapeazyfinal
app/modules/uploader/language/english/uploader_lang.php
543
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Name: Module Language File (Outlet) - English * * Author: Kolawole Gabriel * [email protected] * @gabkolawole * * * * Created: 26.07.2015 * * Description: English language file for outlet views * */ // Errors $lang['image_upload_fail'] = 'Ad Image upload failed, see error'; $lang['image_upload_required'] = 'Atleast one image is required for an Ad'; // Success $lang['image_upload_success'] = 'Ad Image was successfully uploaded!';
mit
opsway/doctrine-dbal-postgresql
src/Doctrine/ORM/Query/AST/Functions/ArrayAggregate.php
701
<?php namespace Opsway\Doctrine\ORM\Query\AST\Functions; use Doctrine\ORM\Query\AST\Functions\FunctionNode; use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\SqlWalker; class ArrayAggregate extends FunctionNode { private $expr1; public function parse(Parser $parser) { $parser->match(Lexer::T_IDENTIFIER); $parser->match(Lexer::T_OPEN_PARENTHESIS); $this->expr1 = $parser->ArithmeticPrimary(); $parser->match(Lexer::T_CLOSE_PARENTHESIS); } public function getSql(SqlWalker $sqlWalker) { return sprintf( 'array_agg(%s)', $this->expr1->dispatch($sqlWalker) ); } }
mit
LyricTian/oauth2
errors/response.go
3116
package errors import ( "errors" "net/http" ) // Response error response type Response struct { Error error ErrorCode int Description string URI string StatusCode int Header http.Header } // NewResponse create the response pointer func NewResponse(err error, statusCode int) *Response { return &Response{ Error: err, StatusCode: statusCode, } } // SetHeader sets the header entries associated with key to // the single element value. func (r *Response) SetHeader(key, value string) { if r.Header == nil { r.Header = make(http.Header) } r.Header.Set(key, value) } // https://tools.ietf.org/html/rfc6749#section-5.2 var ( ErrInvalidRequest = errors.New("invalid_request") ErrUnauthorizedClient = errors.New("unauthorized_client") ErrAccessDenied = errors.New("access_denied") ErrUnsupportedResponseType = errors.New("unsupported_response_type") ErrInvalidScope = errors.New("invalid_scope") ErrServerError = errors.New("server_error") ErrTemporarilyUnavailable = errors.New("temporarily_unavailable") ErrInvalidClient = errors.New("invalid_client") ErrInvalidGrant = errors.New("invalid_grant") ErrUnsupportedGrantType = errors.New("unsupported_grant_type") ) // Descriptions error description var Descriptions = map[error]string{ ErrInvalidRequest: "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed", ErrUnauthorizedClient: "The client is not authorized to request an authorization code using this method", ErrAccessDenied: "The resource owner or authorization server denied the request", ErrUnsupportedResponseType: "The authorization server does not support obtaining an authorization code using this method", ErrInvalidScope: "The requested scope is invalid, unknown, or malformed", ErrServerError: "The authorization server encountered an unexpected condition that prevented it from fulfilling the request", ErrTemporarilyUnavailable: "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server", ErrInvalidClient: "Client authentication failed", ErrInvalidGrant: "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client", ErrUnsupportedGrantType: "The authorization grant type is not supported by the authorization server", } // StatusCodes response error HTTP status code var StatusCodes = map[error]int{ ErrInvalidRequest: 400, ErrUnauthorizedClient: 401, ErrAccessDenied: 403, ErrUnsupportedResponseType: 401, ErrInvalidScope: 400, ErrServerError: 500, ErrTemporarilyUnavailable: 503, ErrInvalidClient: 401, ErrInvalidGrant: 401, ErrUnsupportedGrantType: 401, }
mit
instructure/CanvasAPI
src/main/java/com/instructure/canvasapi/model/Submission.java
12933
package com.instructure.canvasapi.model; import android.os.Parcel; import com.instructure.canvasapi.utilities.APIHelpers; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Brady Larson * * Copyright (c) 2014 Instructure. All rights reserved. */ public class Submission extends CanvasModel<Submission>{ private long id; private String grade; private double score; private long attempt; private String submitted_at; private ArrayList<SubmissionComment> submission_comments = new ArrayList<SubmissionComment>(); private Date commentCreated; private String mediaContentType; private String mediaCommentUrl; private String mediaCommentDisplay; private ArrayList<Submission> submission_history = new ArrayList<Submission>(); private ArrayList<Attachment> attachments = new ArrayList<Attachment>(); private String body; private HashMap<String,RubricCriterionRating> rubric_assessment = new HashMap<>(); private boolean grade_matches_current_submission; private String workflow_state; private String submission_type; private String preview_url; private String url; private boolean late; private boolean excused; private MediaComment media_comment; //Conversation Stuff private long assignment_id; private Assignment assignment; private long user_id; private long grader_id; private User user; //this value could be null. Currently will only be returned when getting the submission for //a user when the submission_type is discussion_topic private ArrayList<DiscussionEntry> discussion_entries = new ArrayList<DiscussionEntry>(); // Group Info only available when including groups in the Submissions#index endpoint private Group group; /////////////////////////////////////////////////////////////////////////// // Helpers /////////////////////////////////////////////////////////////////////////// public boolean isWithoutGradedSubmission() { return !isGraded() && getSubmissionType() == null; } public boolean isGraded() { return getGrade() != null; } /////////////////////////////////////////////////////////////////////////// // Getters and Setters /////////////////////////////////////////////////////////////////////////// @Override public long getId() { return id; } public void setId(long id) { this.id = id; } public long getUser_id(){return user_id;} public void setUser_id(long user_id){this.user_id = user_id;} public ArrayList<SubmissionComment> getComments() { return submission_comments; } public void setComments(ArrayList<SubmissionComment> comments) { this.submission_comments = comments; } public Date getCommentCreated() { return commentCreated; } public void setCommentCreated(Date commentCreated) { this.commentCreated = commentCreated; } public String getMediaContentType() { return mediaContentType; } public void setMediaContentType(String mediaContentType) { this.mediaContentType = mediaContentType; } public String getMediaCommentUrl() { return mediaCommentUrl; } public void setMediaCommentUrl(String mediaCommentUrl) { this.mediaCommentUrl = mediaCommentUrl; } public String getMediaCommentDisplay() { return mediaCommentDisplay; } public void setMediaCommentDisplay(String mediaCommentDisplay) { this.mediaCommentDisplay = mediaCommentDisplay; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public long getAssignment_id() {return assignment_id;} public void setAssignment_id(long assignment_id) {this.assignment_id = assignment_id;} public Assignment getAssignment(){ return assignment; } public void setAssignment(Assignment assignment){this.assignment = assignment;} public long getGraderID(){ return grader_id; } public boolean isExcused(){ return excused; } public void setExcused(boolean excused){ this.excused = excused; } public Date getSubmitDate() { if(submitted_at == null) { return null; } return APIHelpers.stringToDate(submitted_at); } public void setSubmitDate(String submitDate) { if(submitDate == null) { this.submitted_at = null; } else { this.submitted_at = submitDate; } } public void setSubmissionHistory(ArrayList<Submission> history) { this.submission_history = history; } public ArrayList<Submission> getSubmissionHistory() { return submission_history; } public ArrayList<Attachment> getAttachments() { return attachments; } public void setAttachments(ArrayList<Attachment> attachments) { this.attachments = attachments; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public boolean isGradeMatchesCurrentSubmission() { return grade_matches_current_submission; } public void setGradeMatchesCurrentSubmission( boolean gradeMatchesCurrentSubmission) { this.grade_matches_current_submission = gradeMatchesCurrentSubmission; } public String getWorkflowState() { return workflow_state; } public void setWorkflowState(String workflowState) { this.workflow_state = workflowState; } public String getSubmissionType() { return submission_type; } public void setSubmissionType(String submissionType) { this.submission_type = submissionType; } public String getPreviewUrl() { return preview_url; } public void setPreviewUrl(String previewUrl) { this.preview_url = previewUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public RubricAssessment getRubricAssessment() { RubricAssessment assessment = new RubricAssessment(); ArrayList<RubricCriterionRating> ratings = new ArrayList<RubricCriterionRating>(); if (rubric_assessment != null) { for (Map.Entry<String, RubricCriterionRating> entry : rubric_assessment.entrySet()) { RubricCriterionRating rating = entry.getValue(); rating.setCriterionId(entry.getKey()); ratings.add(rating); } } assessment.setRatings(ratings); return assessment; } public HashMap<String,RubricCriterionRating> getRubricAssessmentHash(){ return this.rubric_assessment; } public void setRubricAssessment(HashMap<String,RubricCriterionRating> ratings){ this.rubric_assessment = ratings; } public ArrayList<DiscussionEntry> getDiscussion_entries() { return discussion_entries; } public void setDiscussion_entries(ArrayList<DiscussionEntry> discussion_entries) { this.discussion_entries = discussion_entries; } public MediaComment getMediaComment() { return media_comment; } public void setMediaComment(MediaComment media_comment) { this.media_comment = media_comment; } public long getAttempt() { return attempt; } public void setAttempt(long attempt) { this.attempt = attempt; } public boolean isLate() { return late; } public void setIslate(boolean late){ this.late = late; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } /////////////////////////////////////////////////////////////////////////// // Required Overrides /////////////////////////////////////////////////////////////////////////// @Override public Date getComparisonDate() { return getSubmitDate(); } @Override public String getComparisonString() { return getSubmissionType(); } /////////////////////////////////////////////////////////////////////////// // Constructors /////////////////////////////////////////////////////////////////////////// public Submission() {} /////////////////////////////////////////////////////////////////////////// // Helpers /////////////////////////////////////////////////////////////////////////// public ArrayList<Long> getUserIds() { ArrayList<Long> ids = new ArrayList<Long>(); for(int i = 0; i < submission_comments.size(); i++) { ids.add(submission_comments.get(i).getAuthorID()); } return ids; } /* * Submissions will have dummy submissions if they grade an assignment with no actual submissions. * We want to see if any are not dummy submissions */ public boolean hasRealSubmission(){ if(submission_history != null) { for (Submission submission : submission_history) { if (submission != null && submission.getSubmissionType() != null) { return true; } } } return false; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(this.id); dest.writeString(this.grade); dest.writeDouble(this.score); dest.writeString(this.submitted_at); dest.writeList(this.submission_comments); dest.writeLong(commentCreated != null ? commentCreated.getTime() : -1); dest.writeString(this.mediaContentType); dest.writeString(this.mediaCommentUrl); dest.writeString(this.mediaCommentDisplay); dest.writeList(this.submission_history); dest.writeList(this.attachments); dest.writeString(this.body); dest.writeSerializable(this.rubric_assessment); dest.writeByte(grade_matches_current_submission ? (byte) 1 : (byte) 0); dest.writeString(this.workflow_state); dest.writeString(this.submission_type); dest.writeString(this.preview_url); dest.writeString(this.url); dest.writeParcelable(this.assignment, flags); dest.writeLong(this.user_id); dest.writeLong(this.grader_id); dest.writeLong(this.assignment_id); dest.writeParcelable(this.user, flags); dest.writeParcelable(this.media_comment, flags); dest.writeList(this.discussion_entries); dest.writeLong(this.attempt); dest.writeByte(this.excused ? (byte) 1 : (byte) 0); dest.writeByte(this.late ? (byte) 1 : (byte) 0); dest.writeParcelable(this.group, flags); } private Submission(Parcel in) { this.assignment = new Assignment(); this.id = in.readLong(); this.grade = in.readString(); this.score = in.readDouble(); this.submitted_at = in.readString(); in.readList(this.submission_comments, SubmissionComment.class.getClassLoader()); long tmpCommentCreated = in.readLong(); this.commentCreated = tmpCommentCreated == -1 ? null : new Date(tmpCommentCreated); this.mediaContentType = in.readString(); this.mediaCommentUrl = in.readString(); this.mediaCommentDisplay = in.readString(); in.readList(this.submission_history, Submission.class.getClassLoader()); in.readList(this.attachments, Attachment.class.getClassLoader()); this.body = in.readString(); this.rubric_assessment =(HashMap<String,RubricCriterionRating>) in.readSerializable(); this.grade_matches_current_submission = in.readByte() != 0; this.workflow_state = in.readString(); this.submission_type = in.readString(); this.preview_url = in.readString(); this.url = in.readString(); this.assignment = in.readParcelable(Assignment.class.getClassLoader()); this.user_id = in.readLong(); this.grader_id = in.readLong(); this.assignment_id = in.readLong(); this.user = in.readParcelable(User.class.getClassLoader()); this.media_comment = in.readParcelable(MediaComment.class.getClassLoader()); in.readList(this.discussion_entries, DiscussionEntry.class.getClassLoader()); this.attempt = in.readLong(); this.excused = in.readByte() != 0; this.late = in.readByte() != 0; this.group = in.readParcelable(Group.class.getClassLoader()); } public static Creator<Submission> CREATOR = new Creator<Submission>() { public Submission createFromParcel(Parcel source) { return new Submission(source); } public Submission[] newArray(int size) { return new Submission[size]; } }; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
mit
mvtenorio/mico
app/Mico/Repositories/BackendServiceProvider.php
586
<?php namespace Mico\Repositories; use Illuminate\Support\ServiceProvider; class BackendServiceProvider extends ServiceProvider { public function register() { $this->app->bind( 'Mico\Repositories\Interfaces\UserRepositoryInterface', 'Mico\Repositories\Eloquent\EloquentUserRepository' ); $this->app->bind( 'Mico\Repositories\Interfaces\ItemRepositoryInterface', 'Mico\Repositories\Eloquent\EloquentItemRepository' ); $this->app->bind( 'Mico\Repositories\Interfaces\TagRepositoryInterface', 'Mico\Repositories\Eloquent\EloquentTagRepository' ); } }
mit
suprojs/suprolftpd
view/LFTPD.js
12246
/* * lftp channels controlling and status */ Ext.define('App.model.LFTPD',{ extend: App.model.Base, fields:[ // `chancfg.sts`: status 3-chars for 3 status info: // [0]- upload status:'r'un/'q'uit // [1]-download status:'r'un/'q'uit // [2]-transport queue:'g'o /'s'top { name:'sts', persist: false }, { name:'txt', persist: false }, { name:'id', persist: false } ] }) Ext.ns ('App.suprolftpd.view.LFTPD') // define ns for class loader App.cfg['App.suprolftpd.view.LFTPD'] = {// fast init __noctl: true,// view-only stuff uses fast init extend: App.view.Window, title: l10n.lftpd.title, wmTooltip: l10n.lftpd.modname, wmImg: App.backendURL + '/css/suprolftpd/crossroads.png', wmId: 'suprolftpd.view.LFTPD', id: 'suprolftpd-view-LFTPD', requires:['App.suprolftpd.view.ControlTools'], width: 777, height: 477,// initial layout: 'hbox', autoScroll: true, maximized: true, initComponent: function initLFTPD(){ var me = this, tabs // common tools on bottom for both channels in grid rows and log tabs me.dockedItems = [ new App.suprolftpd.view.ControlTools ] me.callParent() setTimeout(function(){ me.setLoading(true) },0) me.on('destroy', function(){ App.backend.req('/suprolftpd/lib/dev') }) // further setup using backend data return App.backend.req('/suprolftpd/lib/cnl/get', function(err, lftpds){ var Model, store, i, m, records // connection or app logic errors if(err || !lftpds.success) return Ext.Msg.alert({ buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR, title: 'lftpd load fail', msg: Ext.encode(lftpds).replace(/\\n/g, '<br>'), fn: function(btn){ //if('yes' == btn)... } }) store = Ext.create(App.store.WES,{// setup data storeId: 'lftpd', view: me, informStore: false,// optimize status update / only 'img src' change model: Model = App.model.LFTPD }) records = [ ] for(i in lftpds.data){// open code loadData(); default status for NULL m = new Model(lftpds.data[i] || { id: i, sts: 'bbb|' }) m.on('datachanged', changedModel) records.push(m) } store.loadRecords(records) // setup UI me.add(getItems(store)) m = me.down('#tools')// if allowed bind toolbar to grid m && m.bindGrid(me.down('grid')) tabs = me.down('tabpanel') return setTimeout(function(){ me.setLoading(false) },0) }) function getItems(store){ return [ { xtype:'component', html: '<a href="/css/suprolftpd/supronet.png" target="_blank">'+ '<img class="rotate" src="' + me.wmImg + '"></img></a>', padding:7, width: 77, itemId:'log' }, { xtype: 'tabpanel', height: '100%', border: 0, flex: 1, items:[ { closable: false, reorderable: false, xtype: 'grid', iconCls: 'ld-icon-chs', title: l10n.lftpd.channels, store:store, listeners:{ itemdblclick: itemdblclick }, columns:[ { dataIndex: 'sts', text:'<img src="' + App.backendURL + '/css/suprolftpd/upload.png" width="21" height="21"></img>', tooltip: l10n.lftpd.sts.upload, width: 34, draggable: false, menuDisabled: true, defaultRenderer: render0 }, { dataIndex: 'sts', text:'<img src="' + App.backendURL + '/css/suprolftpd/download.png" width="21" height="21"></img>', tooltip: l10n.lftpd.sts.download, width: 34, draggable: false, menuDisabled: true, defaultRenderer: render1 }, { dataIndex: 'sts', text:'<img src="' + App.backendURL + '/css/suprolftpd/transmit.png"></img>', tooltip: l10n.lftpd.sts.transport, width: 29, draggable: false, menuDisabled: true, defaultRenderer: render2 }, { dataIndex: 'id', text: '<img src="' + App.backendURL + '/css/suprolftpd/page_link.png"></img>', tooltip: l10n.lftpd.chaname, width: 77 }, { text: 'txt', dataIndex: 'txt', flex: 1 }, { text: 'Phone', dataIndex: 'phone' } ] }] }] } function render0(value, meta){ meta.tdAttr = 'data-qtip="' + l10n.lftpd.sts[value[0]] + '"' return '<img sts src="' + App.backendURL + '/css/suprolftpd/' + value[0] + ('r' == value[0] ? 'u' : '') + '.png">' } function render1(value, meta){ meta.tdAttr = 'data-qtip="' + l10n.lftpd.sts[value[1]] + '"' return '<img sts src="' + App.backendURL + '/css/suprolftpd/' + value[1] + ('r' == value[1] ? 'd' : '') + '.png">' } function render2(value, meta, model){ meta.tdAttr = 'data-qtip="' + l10n.lftpd.sts[value[2]] + '"' return '<img sts src="' + App.backendURL + '/css/suprolftpd/' + value[2] + '.png">' } function changedModel(m, updated, node){// `node` may be undefined var panel, el, n, i, mdata = m.data, out = true if(~updated.indexOf('sts')){ mdata.prests || (mdata.prests = 'bbb')// define pre status if(mdata.prests === (n = mdata.sts.slice(0, 3))){ out = false// no real change -- don't do default highlight // even with this filter highlighting is being done long // after all changes are gone; this is because animation // repetition is checked on element basis, but here row // is updated by `renderer` thus all anim elements are new // here for optimized new cell value update via attrs in nodes // `App.store.WES.informStore` is used to skip normal ExtJS's // cell + whole row re-rendering } else if(node && (el = node.dom.querySelectorAll('img[sts]')) && el.length) for(i = 0; i < 4; ++i) if(mdata.prests[i] != n[i]){ el[i].setAttribute('src', App.backendURL + '/css/suprolftpd/' + n[i] + ('r' == n[i] ? 0 == i ? 'u' : 'd' : '') + '.png' )// asm:EXTJS4 (architecture specific model of coding) el[i].parentNode.parentNode.setAttribute('data-qtip', l10n.lftpd.sts[n[i]] ) } mdata.prests = n if((panel = tabs.items.getByKey(mdata.id))){ n = mdata.sts.slice(4)// no status chars if('zzzz' == n){ n = l10n.lftpd.zzzz } el = document.createElement('div') el.innerHTML = n panel.down('#log').getEl().dom.appendChild(el) panel.body.scroll('b', 1 << 22)// 'autoScroll' is here el = void 0 } } return out } function itemdblclick(view){ var model = view.selModel.getSelection()[0] ,ch = model && model.data.id ,panel if(!ch) return if(!tabs.items.getByKey(ch)){ panel = tabs.add( { xtype: 'panel', iconCls: 'ld-icon-chan', title: ch + ': ' + model.data.txt, itemId: ch, closable: true, bodyStyle: 'font-family: "Lucida Console" monospace; font-size: 10pt;' + 'background-color: black; color: #00FF00;', autoScroll: true, listeners:{ activate: selectModel }, dockedItems:[ { xtype: 'toolbar', dock: 'top', items:['-', { text: l10n.lftpd.testBegin + ' <b>api.lftp.send()</b>' ,itemId: 'api.lftp.send' ,iconCls:'ld-icon-test' ,handler: testAPI ,tooltip: l10n.lftpd.testSend },'-', { text: '<b>api.lftp.on()</b> ' + l10n.lftpd.testEnd ,itemId: 'api.lftp.on' ,iconCls:'ld-icon-test' ,handler: testAPI ,tooltip: l10n.lftpd.testOn },'-','->','-', { text: l10n.lftpd.refreshLog ,iconCls: 'sm-rl' ,handler: refreshLog }, { text: l10n.stsClean ,iconCls: 'sm-cl' ,handler: cleanLog } ] }], items:[ { xtype: 'component', style: 'white-space: pre-wrap', html: l10n.lftpd.noload + '\n', itemId:'log' } ] }) } tabs.setActiveTab(ch) return function selectModel(){ view.selModel.select(model) panel.body.scroll('b', 1 << 22)// 'autoScroll' is here } function refreshLog(){ return App.backend.req('/suprolftpd/lib/cnl/log',{ id: ch }, function(err, json){ if(!err && 'string' == typeof json){// expecting text panel.down('#log').update(json) panel.body.scroll('b', 1 << 22)// 'autoScroll' is here return } // json = { success: false, err: "foo" } Ext.Msg.show({ title: l10n.errun_title, buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR, msg: l10n.errapi + '<br><b>' + l10n.lftpd[json.err] + '</b>' }) }) } function cleanLog(){ view.selModel.getSelection()[0].data.sts = ''// show new info panel.down('#log').update('') } function testAPI(btn){ var model = view.selModel.getSelection()[0] App.backend.req('/suprolftpd/lib/cnl/do',{ cmd:btn.itemId, id: model.data.id }) } } } }
mit
jonnybee/RawDataAccessBencher
EFCore/Model/EntityClasses/SalesTaxRate.cs
1675
//------------------------------------------------------------------------------ // <auto-generated>This code was generated by LLBLGen Pro v5.6.</auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace EFCore.Bencher.EntityClasses { /// <summary>Class which represents the entity 'SalesTaxRate'.</summary> public partial class SalesTaxRate : CommonEntityBase { /// <summary>Method called from the constructor</summary> partial void OnCreated(); /// <summary>Initializes a new instance of the <see cref="SalesTaxRate"/> class.</summary> public SalesTaxRate() : base() { OnCreated(); } /// <summary>Gets or sets the ModifiedDate field. </summary> public System.DateTime ModifiedDate { get; set; } /// <summary>Gets or sets the Name field. </summary> public System.String Name { get; set; } /// <summary>Gets or sets the Rowguid field. </summary> public System.Guid Rowguid { get; set; } /// <summary>Gets or sets the SalesTaxRateId field. </summary> public System.Int32 SalesTaxRateId { get; set; } /// <summary>Gets or sets the StateProvinceId field. </summary> public System.Int32 StateProvinceId { get; set; } /// <summary>Gets or sets the TaxRate field. </summary> public System.Decimal TaxRate { get; set; } /// <summary>Gets or sets the TaxType field. </summary> public System.Byte TaxType { get; set; } /// <summary>Represents the navigator which is mapped onto the association 'SalesTaxRate.StateProvince - StateProvince.SalesTaxRates (m:1)'</summary> public virtual StateProvince StateProvince { get; set; } } }
mit
maxharp3r/zotero-to-html
bib2html.py
3527
#!/usr/bin/env python # -*- coding: utf-8 -*- # global imports import argparse from HTMLParser import HTMLParser import json import os from pyquery import PyQuery import pystache import re import sys # local imports import env logger = env.logger() parser = HTMLParser() renderer = pystache.Renderer(file_encoding="utf-8") HYPERLINK_REGEX = re.compile(r"(https?://[^ ]+)") def get_clean_bib(bib): """extract the html citation, remove the html boilerplate that zotero returns""" d = PyQuery(bib) div = d("div.csl-right-inline").html() # zotero keeps the html escaped in the return value div = parser.unescape(div) return hyperlink_string(div) def get_clean_zotero_link(links): """the default zotero link doesn't show an edit button. fix that.""" link = "https://www.zotero.org/%s/items" % os.getenv("ZTH_SEARCH_PREFIX_URI") if "alternate" in links: link = links["alternate"]["href"].replace("items", "items/itemKey") return link def hyperlink_string(s): """take a string, insert <a> tags where http://... is found""" # from http://stackoverflow.com/a/720137/293087 return HYPERLINK_REGEX.sub(r'<a href="\1">\1</a>', s) def split_text_to_list(s): """turn a string into a list of strings, using line-breaks as the splitter""" return [line for line in s.split("\n") if line] def emit_html(zotero_json): current_year = 0 for item in zotero_json: # emit a year template when we encounter a new one year = int(item["meta"]["parsedDate"][:4]) if "parsedDate" in item["meta"] else "Unknown Publication Date" if year and year != current_year: current_year = year yield renderer.render_path("%s/year.mustache.html" % os.getenv("ZTH_TMPL_DIR"), {"year": year}) # emit entry template yield renderer.render_path("%s/entry.mustache.html" % os.getenv("ZTH_TMPL_DIR"), item) def main(): parser = argparse.ArgumentParser(description="zotero json => html") parser.add_argument("-o", "--out", dest="outfile", help="output file name") args = parser.parse_args() # validate args if not args.outfile: raise ValueError("Requires -o to run.") logger.info("starting") zotero_json_str = sys.stdin.read() zotero_json = json.loads(zotero_json_str) for item in zotero_json: item["bibclean"] = get_clean_bib(item["bib"]) # links note = item["csljson"]["note"] if "note" in item["csljson"] else "" item["more"] = split_text_to_list(note) if "URL" in item["csljson"] \ and os.getenv("ZTH_INCLUDE_URL_IN_MORE") == "True": item["more"].append(item["csljson"]["URL"]) if os.getenv("ZTH_INCLUDE_ZOTERO_LINK_IN_MORE") == "True": item["more"].append("zotero: " + get_clean_zotero_link(item["links"])) # add hyperlinks item["more"] = [hyperlink_string(s) for s in item["more"]] with open(args.outfile, "w") as out: css = renderer.render_path("%s/bib.mustache.css" % os.getenv("ZTH_TMPL_DIR")) js = renderer.render_path("%s/bib.mustache.js" % os.getenv("ZTH_TMPL_DIR")) out.write(renderer.render_path("%s/header.mustache.html" % os.getenv("ZTH_TMPL_DIR"), {"css": css})) for html_fragment in emit_html(zotero_json): out.write(html_fragment.encode("utf-8")) out.write(renderer.render_path("%s/footer.mustache.html" % os.getenv("ZTH_TMPL_DIR"), {"js": js})) if __name__ == "__main__": main()
mit
commoncrawl/cc-mrjob
server_count_warc.py
928
import re from mrcc import CCJob server_regex = re.compile('^server:\s*(.+)$', re.I) class ServerCount(CCJob): """ Count server names in HTTP headers contained in WARC files. Note: If WAT files are available the class ServerAnalysis should be used. WAT files are smaller and faster to process. """ def process_record(self, record): if record['WARC-Type'] != 'response': # we're only interested in the HTTP responses return for line in record.payload: match = server_regex.match(line) if match: server = match.group(1).strip() yield server, 1 return elif line.strip() == '': # empty line indicates end of HTTP response header yield '(no server in HTTP header)', 1 return if __name__ == '__main__': ServerCount.run()
mit
ciena-blueplanet/ember-dagre
tests/unit/rank/util-test.js
1951
import {expect} from 'chai' import {longestPath} from 'ciena-dagre/rank/util' import {normalizeRanks} from 'ciena-dagre/util' import {Graph} from 'ciena-graphlib' import {beforeEach, describe, it} from 'mocha' describe('rank/util', function () { describe('longestPath', function () { let g beforeEach(function () { g = new Graph() .setDefaultNodeLabel(function () { return {} }) .setDefaultEdgeLabel(function () { return {minlen: 1} }) }) it('should assign a rank to a single node graph', function () { g.setNode('a') longestPath(g) normalizeRanks(g) expect(g.node('a').rank).to.equal(0) }) it('should assign ranks to unconnected nodes', function () { g.setNode('a') g.setNode('b') longestPath(g) normalizeRanks(g) expect(g.node('a').rank).to.equal(0) expect(g.node('b').rank).to.equal(0) }) it('should assign ranks to connected nodes', function () { g.setEdge('a', 'b') longestPath(g) normalizeRanks(g) expect(g.node('a').rank).to.equal(0) expect(g.node('b').rank).to.equal(1) }) it('should assign ranks for a diamond', function () { g.setPath(['a', 'b', 'd']) g.setPath(['a', 'c', 'd']) longestPath(g) normalizeRanks(g) expect(g.node('a').rank).to.equal(0) expect(g.node('b').rank).to.equal(1) expect(g.node('c').rank).to.equal(1) expect(g.node('d').rank).to.equal(2) }) it('should use the minlen attribute on the edge', function () { g.setPath(['a', 'b', 'd']) g.setEdge('a', 'c') g.setEdge('c', 'd', {minlen: 2}) longestPath(g) normalizeRanks(g) expect(g.node('a').rank).to.equal(0) // longest path biases towards the lowest rank it can assign expect(g.node('b').rank).to.equal(2) expect(g.node('c').rank).to.equal(1) expect(g.node('d').rank).to.equal(3) }) }) })
mit
juliomiguel1/redsocialBUENA
src/main/java/net/daw/service/implementation/PublicacionesService.java
14674
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/openAUSIAS * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT 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. */ package net.daw.service.implementation; import com.google.gson.Gson; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import net.daw.bean.implementation.AmistadBean; import net.daw.bean.implementation.PublicacionesBean; import net.daw.bean.implementation.UsuarioBean; import net.daw.connection.publicinterface.ConnectionInterface; import net.daw.dao.implementation.PublicacionesDao; import net.daw.helper.statics.AppConfigurationHelper; import static net.daw.helper.statics.AppConfigurationHelper.getSourceConnection; import net.daw.helper.statics.ExceptionBooster; import net.daw.helper.statics.FilterBeanHelper; import net.daw.helper.statics.JsonMessage; import net.daw.helper.statics.ParameterCook; import net.daw.service.publicinterface.TableServiceInterface; import net.daw.service.publicinterface.ViewServiceInterface; public class PublicacionesService implements TableServiceInterface, ViewServiceInterface { protected HttpServletRequest oRequest = null; public PublicacionesService(HttpServletRequest request) { oRequest = request; } private Boolean checkpermission(String strMethodName) throws Exception { UsuarioBean oUserBean = (UsuarioBean) oRequest.getSession().getAttribute("userBean"); if (oUserBean != null) { return true; } else { return false; } } @Override public String getcount() throws Exception { if (this.checkpermission("getcount")) { String data = null; ArrayList<FilterBeanHelper> alFilter = ParameterCook.prepareFilter(oRequest); Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); data = JsonMessage.getJson("200", Integer.toString(oPublicacionesDao.getCount(alFilter))); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getCount ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String get() throws Exception { if (this.checkpermission("get")) { int id = ParameterCook.prepareId(oRequest); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); PublicacionesBean oPublicacionesBean = new PublicacionesBean(); oPublicacionesBean.setId(id); oPublicacionesBean = oPublicacionesDao.get(oPublicacionesBean, AppConfigurationHelper.getJsonDepth()); Gson gson = AppConfigurationHelper.getGson(); data = JsonMessage.getJson("200", AppConfigurationHelper.getGson().toJson(oPublicacionesBean)); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":get ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String getall() throws Exception { if (this.checkpermission("getall")) { ArrayList<FilterBeanHelper> alFilter = ParameterCook.prepareFilter(oRequest); HashMap<String, String> hmOrder = ParameterCook.prepareOrder(oRequest); UsuarioBean oUserBean = (UsuarioBean) oRequest.getSession().getAttribute("userBean"); int id_usuario = oUserBean.getId(); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); ArrayList<PublicacionesBean> arrBeans = oPublicacionesDao.getAll(alFilter, hmOrder, 1, id_usuario); data = JsonMessage.getJson("200", AppConfigurationHelper.getGson().toJson(arrBeans)); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getAll ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override @SuppressWarnings("empty-statement") public String getpage() throws Exception { if (this.checkpermission("getpage")) { int intRegsPerPag = ParameterCook.prepareRpp(oRequest);; int intPage = ParameterCook.preparePage(oRequest); ArrayList<FilterBeanHelper> alFilter = ParameterCook.prepareFilter(oRequest); HashMap<String, String> hmOrder = ParameterCook.prepareOrder(oRequest); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); List<PublicacionesBean> arrBeans = oPublicacionesDao.getPage(intRegsPerPag, intPage, alFilter, hmOrder, AppConfigurationHelper.getJsonDepth()); data = JsonMessage.getJson("200", AppConfigurationHelper.getGson().toJson(arrBeans)); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPage ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String getpages() throws Exception { if (this.checkpermission("getpages")) { int intRegsPerPag = ParameterCook.prepareRpp(oRequest); ArrayList<FilterBeanHelper> alFilter = ParameterCook.prepareFilter(oRequest); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); data = JsonMessage.getJson("200", Integer.toString(oPublicacionesDao.getPages(intRegsPerPag, alFilter))); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPages ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String getaggregateviewsome() throws Exception { if (this.checkpermission("getaggregateviewsome")) { String data = null; try { String page = this.getpage(); String pages = this.getpages(); String registers = this.getcount(); data = "{" + "\"page\":" + page + ",\"pages\":" + pages + ",\"registers\":" + registers + "}"; data = JsonMessage.getJson("200", data); } catch (Exception ex) { ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getAggregateViewSome ERROR: " + ex.getMessage())); } return data; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String remove() throws Exception { if (this.checkpermission("remove")) { Integer id = ParameterCook.prepareId(oRequest); String resultado = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); oConnection.setAutoCommit(false); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); resultado = JsonMessage.getJson("200", (String) oPublicacionesDao.remove(id).toString()); oConnection.commit(); } catch (Exception ex) { oConnection.rollback(); ExceptionBooster.boost(new Exception(this.getClass().getName() + ":remove ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return resultado; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } @Override public String set() throws Exception { if (this.checkpermission("set")) { String jason = ParameterCook.prepareJson(oRequest); String resultado = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; UsuarioBean oUserBean = (UsuarioBean) oRequest.getSession().getAttribute("userBean"); int id_usuario = oUserBean.getId(); try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); oConnection.setAutoCommit(false); PublicacionesDao oPublicacionesDao = new PublicacionesDao(oConnection); PublicacionesBean oPublicacionesBean = new PublicacionesBean(); oPublicacionesBean = AppConfigurationHelper.getGson().fromJson(jason, oPublicacionesBean.getClass()); oPublicacionesBean.setId_usuario(id_usuario); if (oPublicacionesBean != null) { Integer iResult = oPublicacionesDao.set(oPublicacionesBean); if (iResult >= 1) { resultado = JsonMessage.getJson("200", iResult.toString()); } else { resultado = JsonMessage.getJson("500", "Error during registry set"); } } else { resultado = JsonMessage.getJson("500", "Error during registry set"); } oConnection.commit(); } catch (Exception ex) { oConnection.rollback(); ExceptionBooster.boost(new Exception(this.getClass().getName() + ":set ERROR: " + ex.getMessage())); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return resultado; } else { return JsonMessage.getJsonMsg("401", "Unauthorized"); } } }
mit
Neopallium/lua-llnet
src/lsocket.nobj.lua
7595
-- Copyright (c) 2011 by Robert G. Jakabosky <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT 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. export_definitions { -- address families "AF_UNSPEC", "AF_UNIX", "AF_INET", "AF_INET6", "AF_IPX", "AF_NETLINK", "AF_PACKET", -- socket types "SOCK_STREAM", "SOCK_DGRAM", "SOCK_SEQPACKET", "SOCK_RAW", "SOCK_RDM", -- flags "SOCK_NONBLOCK", "SOCK_CLOEXEC", -- IP_MTU_DISCOVER arguments. "IP_PMTUDISC_DONT", -- Never send DF frames. "IP_PMTUDISC_WANT", -- Use per route hints. "IP_PMTUDISC_DO", -- Always DF. "IP_PMTUDISC_PROBE", -- Ignore dst pmtu. -- IPV6_MTU_DISCOVER arguments. "IPV6_PMTUDISC_DONT", -- Never send DF frames. "IPV6_PMTUDISC_WANT", -- Use per route hints. "IPV6_PMTUDISC_DO", -- Always DF. "IPV6_PMTUDISC_PROBE", -- Ignore dst pmtu. -- Routing header options for IPv6. "IPV6_RTHDR_LOOSE", -- Hop doesn't need to be neighbour. "IPV6_RTHDR_STRICT", -- Hop must be a neighbour. "IPV6_RTHDR_TYPE_0", -- IPv6 Routing header type 0. } object "LSocket" { userdata_type = 'embed', include "lsocket.h", ffi_typedef[[ typedef int LSocketFD; struct LSocket { LSocketFD fd; }; ]], implements "FD" { implement_method "get_fd" { get_field = 'fd' }, implement_method "get_type" { constant = "1", -- 1 == socket }, }, constructor { c_method_call "errno_rc" "l_socket_open" { "int", "domain", "int", "type", "int", "protocol?", "int", "flags?" }, }, constructor "fd" { var_in{"int", "fd"}, c_source" ${this}->fd = ${fd};", ffi_source" ${this}.fd = ${fd}", }, destructor "close" { c_method_call "void" "l_socket_close" {}, }, method "__tostring" { var_out{ "const char *", "str", }, c_source "pre" [[ char tmp[64]; ]], c_source[[ ${str} = tmp; snprintf(tmp, 64, "LSocket: fd=%d", ${this}->fd); ]], ffi_source[[ ${str} = string.format("LSocket: fd=%i", ${this}.fd) ]], }, method "shutdown" { c_method_call "errno_rc" "l_socket_shutdown" { "bool", "read", "bool", "write" }, }, method "fileno" { var_out{"int", "fd"}, c_source" ${fd} = ${this}->fd;", ffi_source" ${fd} = ${this}.fd", }, method "set_nonblock" { c_method_call "errno_rc" "l_socket_set_nonblock" { "bool", "nonblock" }, }, method "connect" { c_method_call "errno_rc" "l_socket_connect" { "LSockAddr *", "addr" }, }, method "bind" { c_method_call "errno_rc" "l_socket_bind" { "LSockAddr *", "addr" }, }, method "listen" { c_method_call "errno_rc" "l_socket_listen" { "int", "backlog" }, }, method "get_sockname" { c_method_call "errno_rc" "l_socket_get_sockname" { "LSockAddr *", "addr" }, }, method "get_peername" { c_method_call "errno_rc" "l_socket_get_peername" { "LSockAddr *", "addr" }, }, method "accept" { c_method_call { "errno_rc", "rc"} "l_socket_accept" { "LSocket *", "client>1", "LSockAddr *", "peer?", "int", "flags?" }, }, method "send" { c_method_call { "errno_rc", "rc"} "l_socket_send" { "const char *", "data", "size_t", "#data", "int", "flags?" }, c_source[[ /* ${rc} >= 0, then return number of bytes sent. */ if(${rc} >= 0) { lua_pushinteger(L, ${rc}); return 1; } ]], ffi_source[[ -- ${rc} >= 0, then return number of bytes sent. if ${rc} >= 0 then return ${rc} end ]], }, method "recv" { var_out{"char *", "data", need_buffer = 8192, length = 'len' }, c_method_call { "errno_rc", "rc"} "l_socket_recv" { "char *", "data", "size_t", "len", "int", "flags?" }, c_source[[ /* ${rc} == 0, then socket is closed. */ if(${rc} == 0) { lua_pushnil(L); lua_pushliteral(L, "CLOSED"); return 2; } ${len} = ${rc}; ]], ffi_source[[ -- ${rc} == 0, then socket is closed. if ${rc} == 0 then return nil, "CLOSED" end ${len} = ${rc}; ]], }, method "send_buffer" { var_in{"Buffer", "buf"}, var_in{"size_t", "off?", default = 0 }, var_in{"size_t", "len?", default = 0 }, c_source[[ ${data_len} = ${buf}_if->get_size(${buf}); ${data} = ${buf}_if->const_data(${buf}); /* apply offset. */ if(${off} > 0) { if(${off} >= ${data_len}) { luaL_argerror(L, ${off::idx}, "Offset out-of-bounds."); } ${data} += ${off}; ${data_len} -= ${off}; } /* apply length. */ if(${len} > 0) { if(${len} > ${data_len}) { luaL_argerror(L, ${len::idx}, "Length out-of-bounds."); } ${data_len} = ${len}; } ]], ffi_source[[ ${data_len} = ${buf}_if.get_size(${buf}) ${data} = ${buf}_if.const_data(${buf}) -- apply offset. if(${off} > 0) then if(${off} >= ${data_len}) then error("Offset out-of-bounds."); end ${data} = ${data} + ${off}; ${data_len} = ${data_len} - ${off}; end -- apply length. if(${len} > 0) then if(${len} > ${data_len}) then error("Length out-of-bounds."); end ${data_len} = ${len}; end ]], c_method_call { "errno_rc", "rc"} "l_socket_send" { "const char *", "(data)", "size_t", "(data_len)", "int", "flags?" }, c_source[[ /* ${rc} >= 0, then return number of bytes sent. */ if(${rc} >= 0) { lua_pushinteger(L, ${rc}); return 1; } ]], ffi_source[[ -- ${rc} >= 0, then return number of bytes sent. if ${rc} >= 0 then return ${rc} end ]], }, method "recv_buffer" { var_in{"MutableBuffer", "buf"}, var_in{"size_t", "off?", default = 0 }, var_in{"size_t", "len?", default = 4 * 1024 }, var_in{"int", "flags?"}, var_out{"int", "data_len"}, c_source[[ ${data_len} = ${buf}_if->get_size(${buf}); ${data} = ${buf}_if->data(${buf}); /* apply offset. */ if(${off} > 0) { if(${off} >= ${data_len}) { luaL_argerror(L, ${off::idx}, "Offset out-of-bounds."); } ${data} += ${off}; ${data_len} -= ${off}; } /* calculate read length. */ if(${len} < ${data_len}) { ${data_len} = ${len}; } if(0 == ${data_len}) { lua_pushnil(L); lua_pushliteral(L, "ENOBUFS"); return 2; } ]], ffi_source[[ ${data_len} = ${buf}_if.get_size(${buf}) ${data} = ${buf}_if.data(${buf}) -- apply offset. if(${off} > 0) then if(${off} >= ${data_len}) then error("Offset out-of-bounds."); end ${data} = ${data} + ${off}; ${data_len} = ${data_len} - ${off}; end -- calculate read length. if(${len} < ${data_len}) then ${data_len} = ${len}; end if(0 == ${data_len}) then return nil, "ENOBUFS" end ]], c_method_call { "errno_rc", "rc"} "l_socket_recv" { "char *", "(data)", "size_t", "(data_len)", "int", "flags?" }, c_source[[ /* ${rc} == 0, then socket is closed. */ if(${rc} == 0) { lua_pushnil(L); lua_pushliteral(L, "CLOSED"); return 2; } ${data_len} = ${rc}; ]], ffi_source[[ -- ${rc} == 0, then socket is closed. if ${rc} == 0 then return nil, "CLOSED" end ${data_len} = ${rc} ]], }, }
mit
NathanielInman/socket.io-game-boilerplate
src/app/app.js
754
import {easel} from './vendor/easel'; import {eventListeners} from './eventListeners'; import {eventDispatch} from './eventDispatch'; /** * Launch application if easel was able to create a canvas, * if it wasn't then we know canvas isn't supported */ { let noscript = document.getElementById('noscript'); if(!easel.activated){ noscript.innerHTML = ` <p class="browsehappy"> You are using an outdated browser. Please <a href="http://browsehappy.com/"> upgrade your browser</a> to improve your experience. <span style="color:red;"><br/>Canvas isn't supported in your browser.</span> </p>`; }else{ noscript.style.visibility='hidden'; eventListeners.attach(); eventDispatch.start(); } //end if }
mit
msdark/msdark.github.io
src/pages/blog.js
650
import React from 'react' import styled from 'react-emotion' import Container from '../components/Container' const Content = styled.div` max-width: 90%; position: relative; text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; flex: 1 0 0%; ` const Row = styled.div` position: relative; text-align: center; display: flex; flex-direction: row; align-items: center; justify-content: center; flex: 1; ` const SecondPage = () => ( <Container> <Content> <Row> <h1>Articulos</h1> </Row> </Content> </Container> ) export default SecondPage
mit
sirius2013/BuildCore
app/models/invoice/hits/review.rb
1363
# Hit class to review and pay workers after a hit is finished. class Hits::Review < Hit def self.complete!(id, already_aproved = false) builder = find(id) return false unless builder.mt_hit builder.set_as_reviewing! builder.aprove_mt_assignments! unless already_aproved builder.dispose_mt_hit! builder.update_attributes(submited: true) true end def self.pay_for(id) builder = find(id) return false unless builder.mt_hit builder.aprove_mt_assignments! true end def self.extend_hit!(id) builder = find(id) return false unless builder.mt_hit builder.extend_hit true end def extend_hit if mt_hit.status == "Disposed" return false else mt_hit.extend!({assignments: 1, seconds: 10.days}) end end def mt_hit begin @mt_hit ||= RTurk::Hit.find(mt_hit_id) rescue RTurk::InvalidRequest false end end def set_as_reviewing! begin mt_hit.set_as_reviewing! rescue end end def aprove_mt_assignments! mt_hit.assignments.each do |mt_assignment| begin mt_assignment.approve! rescue RTurk::InvalidRequest end end end def dispose_mt_hit! begin if mt_hit.status != 'Reviewable' mt_hit.disable! else mt_hit.dispose! end rescue end end end
mit
bittiez/AwesomeCommands
src/US/bittiez/Config/Configurator.java
707
package US.bittiez.Config; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.Plugin; public class Configurator { public FileConfiguration config; public Configurator(FileConfiguration config) { setConfig(config); } public Configurator() {} public void setConfig(FileConfiguration config) { this.config = config; } public void setConfig(Plugin plugin) { config = plugin.getConfig(); } public void saveDefaultConfig(Plugin plugin) { plugin.saveDefaultConfig(); } public void reloadPluginDefaultConfig(Plugin plugin) { plugin.reloadConfig(); config = plugin.getConfig(); } }
mit
jakubfijalkowski/pluggablebot
DefaultProtocols/DefaultProtocolsPlugin.cpp
1753
#include "DefaultProtocolsPlugin.h" #include "GGProtocol.h" namespace PluggableBot { namespace DefaultProtocols { DefaultProtocolsPlugin::DefaultProtocolsPlugin(ApplicationContext* context) : name("DefaultProtocols"), Logger(Logging::LogFactory::GetLogger("DefaultProtocols")), context(context) { } DefaultProtocolsPlugin::~DefaultProtocolsPlugin() { for (auto p : this->suppotedProtocols) { delete p; } this->suppotedProtocols.clear(); } const std::string& DefaultProtocolsPlugin::GetName() const { return this->name; } void DefaultProtocolsPlugin::Configure(const jsonxx::Object& configuration) { if (configuration.has<jsonxx::Object>("gg")) { auto config = configuration.get<jsonxx::Object>("gg"); auto status = GGProtocol::CheckConfiguration(config); if (status == ConfigurationStatus::Valid) { auto gg = new GGProtocol(this->context, config); this->suppotedProtocols.push_back(gg); } else if (status == ConfigurationStatus::Disabled) { Logger->Information("Gadu-Gadu support is disabled."); } else { Logger->Warning("Gadu-Gadu configuration is invalid."); } } else { Logger->Warning("There is no configuration entry for Gadu-Gadu."); } } const IPlugin::CommandList* DefaultProtocolsPlugin::GetSupportedCommands() const { return nullptr; } const IPlugin::ProtocolList* DefaultProtocolsPlugin::GetSupportedProtocols() const { return &this->suppotedProtocols; } extern "C" { IPlugin* CreatePlugin(ApplicationContext* context) { return new DefaultProtocolsPlugin(context); } void DeletePlugin(IPlugin* plugin) { delete (DefaultProtocolsPlugin*)plugin; } } } }
mit
wesleywh/GameDevRepo
Scripts/GameManager/TransitionManager.cs
3764
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace CyberBullet.GameManager { [RequireComponent(typeof(GUIManager))] public class TransitionManager : MonoBehaviour { public bool gameManager = true; [Header("Debugging")] public bool disable = false; public string travelToNamedObject = ""; private GUIManager guiManager = null; private AsyncOperation ao; // Use this for initialization void Start () { guiManager = dontDestroy.currentGameManager.GetComponent<GUIManager>(); if (gameManager == false && disable == false) { string targetName = dontDestroy.currentGameManager.GetComponent<TransitionManager>().travelToNamedObject; if (string.IsNullOrEmpty(targetName) == false) { GameObject target = GameObject.Find(targetName); if (target == null) return; this.transform.position = target.transform.position; this.transform.rotation = target.transform.rotation; } } GameObject.FindGameObjectWithTag("GameManager").GetComponent<PlayerManager>().SetPlayerObject(gameObject); } public void LoadTargetLevel(string name, string travelPoint, AudioClip clip = null, float volume = 0.5f, string title = "", string description = "", Texture2D background = null) { StartCoroutine(LoadLevel(name, travelPoint,clip,volume,title,description,background)); } IEnumerator LoadLevel(string name, string travelPoint, AudioClip clip, float volume, string title, string description, Texture2D background) { //Create a temp music player and player it. GameObject musicPlayer = GameObject.CreatePrimitive (PrimitiveType.Cube); musicPlayer.transform.position = GameObject.FindGameObjectWithTag ("Player").transform.position; Destroy (GameObject.FindGameObjectWithTag ("Player")); musicPlayer.tag = "Player"; AudioSource audioSrc = musicPlayer.AddComponent<AudioSource> (); musicPlayer.AddComponent<AudioListener> (); audioSrc.clip = clip; audioSrc.volume = volume; audioSrc.loop = true; audioSrc.spatialBlend = 0.0f; audioSrc.Play (); //Set Transition Manager Var travelToNamedObject = travelPoint; //Set the Transition Manager travel to point for next area (Makes the player jump to this object on area load) guiManager.EnableLoadingScreen(true,title,description,background); //Turn on GUI and set loading bar to zero yield return new WaitForSeconds (0.1f); //Give some refresh time (To visually load objects) ao = SceneManager.LoadSceneAsync (name); //Start loading the other area asyncronously float progress = 0.0f; //Track the loading progress while (!ao.isDone) { //Keep updating the load bar until area is fully loaded progress = Mathf.Clamp01(ao.progress / 0.9f); //Calculate to make sure bar fills when it hits 0.9f (100% loaded) guiManager.SetLoadingBarValue(progress); //Visually set the loading bar progress yield return null; //this allows the while loop to keep going } //Note: The loading screen should be turned off by the next area } } }
mit
bigeasy/dotfiles
libexec/dots/node/codecov.js
889
#!/usr/bin/env node /* ___ usage ___ en_US ___ usage: dots git issue create [options] [subject] desciption: Create a GitHub issue from the command line using the given subject. If the creation is successful, the new issue number is printed to standard out. ___ . ___ */ // TODO Really should be `dots node package --travis` or something. require('arguable')(module, require('cadence')(function (async, program) { var fs = require('fs') var ok = require('assert').ok var url = require('url') async(function () { fs.readFile('package.json', 'utf8', async()) }, function (body) { var json = JSON.parse(body) var repository = json.repository ok(repository, 'repository defined') ok(repository.type == 'git', 'repository is git') console.log('https://codecov.io/gh/' + repository.url) }) }))
mit
JanBe/woo-map
config/application.rb
535
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module WooMap class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. config.autoload_paths << Rails.root.join('lib') end end
mit
ChilliCreative/solidtimberbenchtops.com.au
web/app/plugins/all-in-one-seo-pack-pro/aioseop_class.php
185387
<?php /** * @package All-in-One-SEO-Pack-Pro */ /** * Include the module base class. */ require_once( 'aioseop_module_class.php' ); /** * The main class. */ class All_in_One_SEO_Pack extends All_in_One_SEO_Pack_Module { /** The current version of the plugin. **/ var $version = AIOSEOP_VERSION; /** Max numbers of chars in auto-generated description */ var $maximum_description_length = 160; /** Minimum number of chars an excerpt should be so that it can be used * as description. Touch only if you know what you're doing */ var $minimum_description_length = 1; /** Whether output buffering is already being used during forced title rewrites. **/ var $ob_start_detected = false; /** The start of the title text in the head section for forced title rewrites. **/ var $title_start = -1; /** The end of the title text in the head section for forced title rewrites. **/ var $title_end = -1; /** The title before rewriting */ var $orig_title = ''; /** Filename of log file. */ var $log_file; /** Flag whether there should be logging. */ var $do_log; var $token; var $secret; var $access_token; var $ga_token; var $account_cache; var $profile_id; var $meta_opts = false; var $is_front_page = null; function __construct() { global $aioseop_options; $this->log_file = dirname( __FILE__ ) . '/all_in_one_seo_pack.log'; if ( !empty( $aioseop_options ) && isset( $aioseop_options['aiosp_do_log'] ) && $aioseop_options['aiosp_do_log'] ) $this->do_log = true; else $this->do_log = false; $this->init(); $this->name = sprintf( __( '%s Plugin Options', 'all_in_one_seo_pack' ), AIOSEOP_PLUGIN_NAME ); $this->menu_name = __( 'General Settings', 'all_in_one_seo_pack' ); $this->prefix = 'aiosp_'; // option prefix $this->option_name = 'aioseop_options'; $this->store_option = true; $this->file = __FILE__; // the current file $blog_name = esc_attr( get_bloginfo( 'name' ) ); parent::__construct(); $this->help_text = Array( "license_key" => __( "This will be the license key received when the product was purchased. This is used for automatic upgrades.", 'all_in_one_seo_pack'), "can" => __( "This option will automatically generate Canonical URLs for your entire WordPress installation. This will help to prevent duplicate content penalties by <a href=\'http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html\' target=\'_blank\'>Google</a>.", 'all_in_one_seo_pack'), "no_paged_canonical_links"=> __( "Checking this option will set the Canonical URL for all paginated content to the first page.", 'all_in_one_seo_pack'), "customize_canonical_links"=> __( "Checking this option will allow you to customize Canonical URLs for specific posts.", 'all_in_one_seo_pack'), "can_set_protocol" => __( "Set protocol for canonical URLs.", 'all_in_one_seo_pack' ), "use_original_title" => __( "Use wp_title to get the title used by the theme; this is disabled by default. If you use this option, set your title formats appropriately, as your theme might try to do its own title SEO as well.", 'all_in_one_seo_pack' ), "do_log" => __( "Check this and All in One SEO Pack will create a log of important events (all_in_one_seo_pack.log) in its plugin directory which might help debugging. Make sure this directory is writable.", 'all_in_one_seo_pack' ), "home_title" => __( "As the name implies, this will be the Meta Title of your homepage. This is independent of any other option. If not set, the default Site Title (found in WordPress under Settings, General, Site Title) will be used.", 'all_in_one_seo_pack' ), "home_description" => __( "This will be the Meta Description for your homepage. This is independent of any other option. The default is no Meta Description at all if this is not set.", 'all_in_one_seo_pack' ), "home_keywords" => __( "Enter a comma separated list of your most important keywords for your site that will be written as Meta Keywords on your homepage. Don\'t stuff everything in here.", 'all_in_one_seo_pack' ), "use_static_home_info" => __( "Checking this option uses the title, description, and keywords set on your static Front Page.", 'all_in_one_seo_pack' ), "togglekeywords" => __( "This option allows you to toggle the use of Meta Keywords throughout the whole of the site.", 'all_in_one_seo_pack' ), "use_categories" => __( "Check this if you want your categories for a given post used as the Meta Keywords for this post (in addition to any keywords you specify on the Edit Post screen).", 'all_in_one_seo_pack' ), "use_tags_as_keywords" => __( "Check this if you want your tags for a given post used as the Meta Keywords for this post (in addition to any keywords you specify on the Edit Post screen).", 'all_in_one_seo_pack' ), "dynamic_postspage_keywords"=> __( "Check this if you want your keywords on your Posts page (set in WordPress under Settings, Reading, Front Page Displays) and your archive pages to be dynamically generated from the keywords of the posts showing on that page. If unchecked, it will use the keywords set in the edit page screen for the posts page.", 'all_in_one_seo_pack'), "rewrite_titles" => __( "Note that this is all about the title tag. This is what you see in your browser's window title bar. This is NOT visible on a page, only in the title bar and in the source code. If enabled, all page, post, category, search and archive page titles get rewritten. You can specify the format for most of them. For example: Using the default post title format below, Rewrite Titles will write all post titles as 'Post Title | Blog Name'. If you have manually defined a title using All in One SEO Pack, this will become the title of your post in the format string.", 'all_in_one_seo_pack' ), "cap_titles" => __( "Check this and Search Page Titles and Tag Page Titles will have the first letter of each word capitalized.", 'all_in_one_seo_pack' ), "cap_cats" => __( "Check this and Category Titles will have the first letter of each word capitalized.", 'all_in_one_seo_pack'), "home_page_title_format" => __( "This controls the format of the title tag for your Home Page.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%page_title% - The original title of the page', 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_login% - This page's author' login", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_nicename% - This page's author' nicename", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_firstname% - This page's author' first name (capitalized)", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_lastname% - This page's author' last name (capitalized)", 'all_in_one_seo_pack' ) . '</li>' . '</ul>', "page_title_format" => __( "This controls the format of the title tag for Pages.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%page_title% - The original title of the page', 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_login% - This page's author' login", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_nicename% - This page's author' nicename", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_firstname% - This page's author' first name (capitalized)", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%page_author_lastname% - This page's author' last name (capitalized)", 'all_in_one_seo_pack' ) . '</li>' . '</ul>', "post_title_format" => __( "This controls the format of the title tag for Posts.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%post_title% - The original title of the post', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%category_title% - The (main) category of the post', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%category% - Alias for %category_title%', 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_login% - This post's author' login", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_nicename% - This post's author' nicename", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_firstname% - This post's author' first name (capitalized)", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_lastname% - This post's author' last name (capitalized)", 'all_in_one_seo_pack' ) . '</li>' . '</ul>', "category_title_format" => __( "This controls the format of the title tag for Category Archives.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%category_title% - The original title of the category', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%category_description% - The description of the category', 'all_in_one_seo_pack' ) . '</li></ul>', "archive_title_format" => __( "This controls the format of the title tag for Custom Post Archives.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%archive_title - The original archive title given by wordpress', 'all_in_one_seo_pack' ) . '</li></ul>', "date_title_format" => __( "This controls the format of the title tag for Date Archives.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%date% - The original archive title given by wordpress, e.g. "2007" or "2007 August"', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%day% - The original archive day given by wordpress, e.g. "17"', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%month% - The original archive month given by wordpress, e.g. "August"', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%year% - The original archive year given by wordpress, e.g. "2007"', 'all_in_one_seo_pack' ) . '</li></ul>', "author_title_format" => __( "This controls the format of the title tag for Author Archives.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%author% - The original archive title given by wordpress, e.g. "Steve" or "John Smith"', 'all_in_one_seo_pack' ) . '</li></ul>', "tag_title_format" => __( "This controls the format of the title tag for Tag Archives.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%tag% - The name of the tag', 'all_in_one_seo_pack' ) . '</li></ul>', "search_title_format" => __( "This controls the format of the title tag for the Search page.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%search% - What was searched for', 'all_in_one_seo_pack' ) . '</li></ul>', "description_format" => __( "This controls the format of Meta Descriptions.The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%description% - The original description as determined by the plugin, e.g. the excerpt if one is set or an auto-generated one if that option is set', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%post_title% - The original title of the post', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%wp_title% - The original wordpress title, e.g. post_title for posts', 'all_in_one_seo_pack' ) . '</li></ul>', "404_title_format" => __( "This controls the format of the title tag for the 404 page.<br />The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%request_url% - The original URL path, like "/url-that-does-not-exist/"', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%request_words% - The URL path in human readable form, like "Url That Does Not Exist"', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%404_title% - Additional 404 title input"', 'all_in_one_seo_pack' ) . '</li></ul>', "paged_format" => __( "This string gets appended/prepended to titles of paged index pages (like home or archive pages).", 'all_in_one_seo_pack' ) . __( 'The following macros are supported:', 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%page% - The page number', 'all_in_one_seo_pack' ) . '</li></ul>', "enablecpost" => __( "Check this if you want to use All in One SEO Pack with any Custom Post Types on this site.", 'all_in_one_seo_pack' ), "cpostadvanced" => __( "This will show or hide the advanced options for SEO for Custom Post Types.", 'all_in_one_seo_pack' ), "cpostactive" => __( "Use these checkboxes to select which Post Types you want to use All in One SEO Pack with.", 'all_in_one_seo_pack' ), "taxactive" => __( "Use these checkboxes to select which Taxonomies you want to use All in One SEO Pack with.", 'all_in_one_seo_pack' ), "cposttitles" => __( "This allows you to set the title tags for each Custom Post Type.", 'all_in_one_seo_pack' ), "posttypecolumns" => __( "This lets you select which screens display the SEO Title, SEO Keywords and SEO Description columns.", 'all_in_one_seo_pack' ), "admin_bar" => __( "Check this to add All in One SEO Pack to the Admin Bar for easy access to your SEO settings.", 'all_in_one_seo_pack' ), "custom_menu_order" => __( "Check this to move the All in One SEO Pack menu item to the top of your WordPress Dashboard menu.", 'all_in_one_seo_pack' ), "google_verify" => __( "Enter your verification code here to verify your site with Google Webmaster Tools.<br /><a href='http://semperplugins.com/documentation/google-webmaster-tools-verification/' target='_blank'>Click here for documentation on this setting</a>", 'all_in_one_seo_pack' ), "bing_verify" => __( "Enter your verification code here to verify your site with Bing Webmaster Tools.<br /><a href='http://semperplugins.com/documentation/bing-webmaster-verification/' target='_blank'>Click here for documentation on this setting</a>", 'all_in_one_seo_pack' ), "pinterest_verify" => __( "Enter your verification code here to verify your site with Pinterest.<br /><a href='http://semperplugins.com/documentation/pinterest-site-verification/' target='_blank'>Click here for documentation on this setting</a>", 'all_in_one_seo_pack' ), "google_publisher" => __( "Enter your Google+ Profile URL here to add the rel=“author” tag to your site for Google authorship. It is recommended that the URL you enter here should be your personal Google+ profile. Use the Advanced Authorship Options below if you want greater control over the use of authorship.", 'all_in_one_seo_pack' ), "google_disable_profile"=> __( "Check this to remove the Google Plus field from the user profile screen.", 'all_in_one_seo_pack' ), "google_author_advanced"=> __( "Enable this to display advanced options for controlling Google Plus authorship information on your website.", 'all_in_one_seo_pack' ), "google_author_location"=> __( "This option allows you to control which types of pages you want to display rel=\"author\" on for Google authorship. The options include the Front Page (the homepage of your site), Posts, Pages, and any Custom Post Types. The Everywhere Else option includes 404, search, categories, tags, custom taxonomies, date archives, author archives and any other page template.", 'all_in_one_seo_pack' ), "google_enable_publisher"=> __( "This option allows you to control whether rel=\"publisher\" is displayed on the homepage of your site. Google recommends using this if the site is a business website.", 'all_in_one_seo_pack' ), "google_specify_publisher"=> __( "The Google+ profile you enter here will appear on your homepage only as the rel=\"publisher\" tag. It is recommended that the URL you enter here should be the Google+ profile for your business.", 'all_in_one_seo_pack' ), "google_sitelinks_search"=> __( "Add markup to display the Google Sitelinks Search Box next to your search results in Google.", 'all_in_one_seo_pack' ), "google_set_site_name" => __( "Add markup to tell Google the preferred name for your website.", 'all_in_one_seo_pack' ), "google_connect" => __( "Press the connect button to connect with Google Analytics; or if already connected, press the disconnect button to disable and remove any stored analytics credentials.", 'all_in_one_seo_pack' ), "google_analytics_id" => __( "Enter your Google Analytics ID here to track visitor behavior on your site using Google Analytics.", 'all_in_one_seo_pack' ), "ga_use_universal_analytics" => __( "Use the new Universal Analytics tracking code for Google Analytics.", 'all_in_one_seo_pack' ), "ga_advanced_options" => __( "Check to use advanced Google Analytics options.", 'all_in_one_seo_pack' ), "ga_domain" => __( "Enter your domain name without the http:// to set your cookie domain.", 'all_in_one_seo_pack' ), "ga_multi_domain" => __( "Use this option to enable tracking of multiple or additional domains.", 'all_in_one_seo_pack' ), "ga_addl_domains" => __( "Add a list of additional domains to track here. Enter one domain name per line without the http://.", 'all_in_one_seo_pack' ), "ga_anonymize_ip" => __( "This enables support for IP Anonymization in Google Analytics.", 'all_in_one_seo_pack' ), "ga_display_advertising"=> __( "This enables support for the Display Advertiser Features in Google Analytics.", 'all_in_one_seo_pack' ), "ga_exclude_users" => __( "Exclude logged-in users from Google Analytics tracking by role.", 'all_in_one_seo_pack' ), "ga_track_outbound_links"=> __( "Check this if you want to track outbound links with Google Analytics.", 'all_in_one_seo_pack' ), "ga_link_attribution"=> __( "This enables support for the Enhanced Link Attribution in Google Analytics.", 'all_in_one_seo_pack' ), "ga_enhanced_ecommerce" => __( "This enables support for the Enhanced Ecommerce in Google Analytics.", 'all_in_one_seo_pack' ), "cpostnoindex" => __( "Set the default NOINDEX setting for each Post Type.", 'all_in_one_seo_pack' ), "cpostnofollow" => __( "Set the default NOFOLLOW setting for each Post Type.", 'all_in_one_seo_pack' ), "category_noindex" => __( "Check this to ask search engines not to index Category Archives. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "archive_date_noindex" => __( "Check this to ask search engines not to index Date Archives. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "archive_author_noindex"=> __( "Check this to ask search engines not to index Author Archives. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "tags_noindex" => __( "Check this to ask search engines not to index Tag Archives. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "search_noindex" => __( "Check this to ask search engines not to index the Search page. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "404_noindex" => __( "Check this to ask search engines not to index the 404 page.", 'all_in_one_seo_pack' ), "tax_noindex" => __( "Check this to ask search engines not to index custom Taxonomy archive pages. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "paginated_noindex" => __( "Check this to ask search engines not to index paginated pages/posts. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), "paginated_nofollow" => __( "Check this to ask search engines not to follow links from paginated pages/posts. Useful for avoiding duplicate content.", 'all_in_one_seo_pack' ), 'noodp' => __( 'Check this box to ask search engines not to use descriptions from the Open Directory Project for your entire site.', 'all_in_one_seo_pack' ), 'cpostnoodp' => __( "Set the default noodp setting for each Post Type.", 'all_in_one_seo_pack' ), 'noydir' => __( 'Check this box to ask Yahoo! not to use descriptions from the Yahoo! directory for your entire site.', 'all_in_one_seo_pack' ), 'cpostnoydir' => __( "Set the default noydir setting for each Post Type.", 'all_in_one_seo_pack' ), "skip_excerpt" => __( "Check this and your Meta Descriptions won't be generated from the excerpt.", 'all_in_one_seo_pack' ), "generate_descriptions" => __( "Check this and your Meta Descriptions will be auto-generated from your excerpt or content.", 'all_in_one_seo_pack' ), "run_shortcodes" => __( "Check this and shortcodes will get executed for descriptions auto-generated from content.", 'all_in_one_seo_pack' ), "hide_paginated_descriptions"=> __( "Check this and your Meta Descriptions will be removed from page 2 or later of paginated content.", 'all_in_one_seo_pack' ), "dont_truncate_descriptions"=> __( "Check this to prevent your Description from being truncated regardless of its length.", 'all_in_one_seo_pack' ), "schema_markup"=> __( "Check this to support Schema.org markup, i.e., itemprop on supported metadata.", 'all_in_one_seo_pack' ), "unprotect_meta" => __( "Check this to unprotect internal postmeta fields for use with XMLRPC. If you don't know what that is, leave it unchecked.", 'all_in_one_seo_pack' ), "ex_pages" => __( "Enter a comma separated list of pages here to be excluded by All in One SEO Pack. This is helpful when using plugins which generate their own non-WordPress dynamic pages. Ex: <em>/forum/, /contact/</em> For instance, if you want to exclude the virtual pages generated by a forum plugin, all you have to do is add forum or /forum or /forum/ or and any URL with the word \"forum\" in it, such as http://mysite.com/forum or http://mysite.com/forum/someforumpage here and it will be excluded from All in One SEO Pack.", 'all_in_one_seo_pack' ), "post_meta_tags" => __( "What you enter here will be copied verbatim to the header of all Posts. You can enter whatever additional headers you want here, even references to stylesheets.", 'all_in_one_seo_pack' ), "page_meta_tags" => __( "What you enter here will be copied verbatim to the header of all Pages. You can enter whatever additional headers you want here, even references to stylesheets.", 'all_in_one_seo_pack' ), "front_meta_tags" => __( "What you enter here will be copied verbatim to the header of the front page if you have set a static page in Settings, Reading, Front Page Displays. You can enter whatever additional headers you want here, even references to stylesheets. This will fall back to using Additional Page Headers if you have them set and nothing is entered here.", 'all_in_one_seo_pack' ), "home_meta_tags" => __( "What you enter here will be copied verbatim to the header of the home page if you have Front page displays your latest posts selected in Settings, Reading.  It will also be copied verbatim to the header on the Posts page if you have one set in Settings, Reading. You can enter whatever additional headers you want here, even references to stylesheets.", 'all_in_one_seo_pack' ), ); $this->help_anchors = Array( 'license_key' => '#license-key', 'can' => '#canonical-urls', 'no_paged_canonical_links' => '#no-pagination-for-canonical-urls', 'customize_canonical_links' => '#enable-custom-canonical-urls', 'use_original_title' => '#use-original-title', 'schema_markup' => '#use-schema-markup', 'do_log' => '#log-important-events', 'home_title' => '#home-title', 'home_description' => '#home-description', 'home_keywords' => '#home-keywords', 'togglekeywords' => '#use-keywords', 'use_categories' => '#use-categories-for-meta-keywords', 'use_tags_as_keywords' => '#use-tags-for-meta-keywords', 'dynamic_postspage_keywords' => '#dynamically-generate-keywords-for-posts-page', 'rewrite_titles' => '#rewrite-titles', 'cap_titles' => '#capitalize-titles', 'home_page_title_format' => '#title-format-fields', 'page_title_format' => '#title-format-fields', 'post_title_format' => '#title-format-fields', 'category_title_format' => '#title-format-fields', 'archive_title_format' => '#title-format-fields', 'date_title_format' => '#title-format-fields', 'author_title_format' => '#title-format-fields', 'tag_title_format' => '#title-format-fields', 'search_title_format' => '#title-format-fields', '404_title_format' => '#title-format-fields', 'enablecpost' => '#seo-for-custom-post-types', 'cpostadvanced' => '#enable-advanced-options', 'cpostactive' => '#seo-on-only-these-post-types', 'taxactive' => '#seo-on-only-these-taxonomies', 'cposttitles' => '#custom-titles', 'posttypecolumns' => '#show-column-labels-for-custom-post-types', 'admin_bar' => '#display-menu-in-admin-bar', 'custom_menu_order' => '#display-menu-at-the-top', 'google_verify' => '', 'bing_verify' => '', 'pinterest_verify' => '', 'google_publisher' => '#google-plus-default-profile', 'google_disable_profile' => '#disable-google-plus-profile', 'google_author_advanced' => '#advanced-authorship-options', 'google_author_location' => '#display-google-authorship', 'google_enable_publisher' => '#display-publisher-meta-on-front-page', 'google_specify_publisher' => '#specify-publisher-url', 'google_analytics_id' => 'http://semperplugins.com/documentation/setting-up-google-analytics/', 'ga_use_universal_analytics' => '#use-universal-analytics', 'ga_domain' => '#tracking-domain', 'ga_multi_domain' => '#track-multiple-domains-additional-domains', 'ga_addl_domains' => '#track-multiple-domains-additional-domains', 'ga_anonymize_ip' => '#anonymize-ip-addresses', 'ga_display_advertising' => '#display-advertiser-tracking', 'ga_exclude_users' => '#exclude-users-from-tracking', 'ga_track_outbound_links' => '#track-outbound-links', 'ga_link_attribution' => '#enhanced-link-attribution', 'ga_enhanced_ecommerce' => '#enhanced-ecommerce', 'cpostnoindex' => '#use-noindex-for-paginated-pages-posts', 'cpostnofollow' => '#use-nofollow-for-paginated-pages-posts', 'noodp' => '#exclude-site-from-the-open-directory-project', 'noydir' => '#exclude-site-from-yahoo-directory', 'generate_descriptions' => '#autogenerate-descriptions', 'run_shortcodes' => '#run-shortcodes-in-autogenerated-descriptions', 'hide_paginated_descriptions' => '#remove-descriptions-for-paginated-pages', 'dont_truncate_descriptions' => '#never-shorten-long-descriptions', 'unprotect_meta' => '#unprotect-post-meta-fields', 'ex_pages' => '#exclude-pages', 'post_meta_tags' => '#additional-post-headers', 'page_meta_tags' => '#additional-page-headers', 'front_meta_tags' => '#additional-front-page-headers', 'home_meta_tags' => '#additional-blog-page-headers' ); $meta_help_text = Array( 'snippet' => __( 'A preview of what this page might look like in search engine results.', 'all_in_one_seo_pack' ), 'title' => __( 'A custom title that shows up in the title tag for this page.', 'all_in_one_seo_pack' ), 'description' => __( 'The META description for this page. This will override any autogenerated descriptions.', 'all_in_one_seo_pack' ), 'keywords' => __( 'A comma separated list of your most important keywords for this page that will be written as META keywords.', 'all_in_one_seo_pack' ), 'custom_link' => __( "Override the canonical URLs for this post.", 'all_in_one_seo_pack'), 'noindex' => __( 'Check this box to ask search engines not to index this page.', 'all_in_one_seo_pack' ), 'nofollow' => __( 'Check this box to ask search engines not to follow links from this page.', 'all_in_one_seo_pack' ), 'noodp' => __( 'Check this box to ask search engines not to use descriptions from the Open Directory Project for this page.', 'all_in_one_seo_pack' ), 'noydir' => __( 'Check this box to ask Yahoo! not to use descriptions from the Yahoo! directory for this page.', 'all_in_one_seo_pack' ), 'titleatr' => __( 'Set the title attribute for menu links.', 'all_in_one_seo_pack' ), 'menulabel' => __( 'Set the label for this page menu item.', 'all_in_one_seo_pack' ), 'sitemap_exclude' => __( "Don't display this page in the sitemap.", 'all_in_one_seo_pack' ), 'disable' => __( 'Disable SEO on this page.', 'all_in_one_seo_pack' ), 'disable_analytics' => __( 'Disable Google Analytics on this page.', 'all_in_one_seo_pack' ) ); $this->default_options = array( "license_key" => Array( 'name' => __( 'License Key:', 'all_in_one_seo_pack' ), 'type' => 'text' ), "home_title"=> Array( 'name' => __( 'Home Title:', 'all_in_one_seo_pack' ), 'default' => null, 'type' => 'textarea', 'sanitize' => 'text', 'count' => true, 'rows' => 1, 'cols' => 60, 'condshow' => Array( "aiosp_use_static_home_info" => 0 ) ), "home_description"=> Array( 'name' => __( 'Home Description:', 'all_in_one_seo_pack' ), 'default' => '', 'type' => 'textarea', 'sanitize' => 'text', 'count' => true, 'cols' => 80, 'rows' => 2, 'condshow' => Array( "aiosp_use_static_home_info" => 0 ) ), "togglekeywords" => Array( 'name' => __( 'Use Keywords:', 'all_in_one_seo_pack' ), 'default' => 0, 'type' => 'radio', 'initial_options' => Array( 0 => __( 'Enabled', 'all_in_one_seo_pack' ), 1 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "home_keywords"=> Array( 'name' => __( 'Home Keywords (comma separated):', 'all_in_one_seo_pack' ), 'default' => null, 'type' => 'textarea', 'sanitize' => 'text', 'condshow' => Array( "aiosp_togglekeywords" => 0, "aiosp_use_static_home_info" => 0 ) ), "use_static_home_info" => Array( 'name' => __( "Use Static Front Page Instead", 'all_in_one_seo_pack' ), 'default' => 0, 'type' => 'radio', 'initial_options' => Array( 1 => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "can"=> Array( 'name' => __( 'Canonical URLs:', 'all_in_one_seo_pack' ), 'default' => 1), "no_paged_canonical_links"=> Array( 'name' => __( 'No Pagination for Canonical URLs:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( "aiosp_can" => 'on' ) ), "customize_canonical_links" => Array( 'name' => __( 'Enable Custom Canonical URLs:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( "aiosp_can" => 'on' ) ), "can_set_protocol" => Array( 'name' => __( 'Set Protocol For Canonical URLs:', 'all_in_one_seo_pack' ), 'type' => 'radio', 'default' => 'auto', 'initial_options' => Array( 'auto' => __( 'Auto', 'all_in_one_seo_pack' ), 'http' => __( 'HTTP', 'all_in_one_seo_pack' ), 'https' => __( 'HTTPS', 'all_in_one_seo_pack' ) ), 'condshow' => Array( "aiosp_can" => 'on' ) ), "rewrite_titles"=> Array( 'name' => __( 'Rewrite Titles:', 'all_in_one_seo_pack' ), 'default' => 1, 'type' => 'radio', 'initial_options' => Array( 1 => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "force_rewrites"=> Array( 'name' => __( 'Force Rewrites:', 'all_in_one_seo_pack' ), 'default' => 1, 'type' => 'hidden', 'prefix' => $this->prefix, 'initial_options' => Array( 1 => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "use_original_title"=> Array( 'name' => __( 'Use Original Title:', 'all_in_one_seo_pack' ), 'type' => 'radio', 'default' => 0, 'initial_options' => Array( 1 => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "cap_titles"=> Array( 'name' => __( 'Capitalize Titles:', 'all_in_one_seo_pack' ), 'default' => 1), "cap_cats"=> Array( 'name' => __( 'Capitalize Category Titles:', 'all_in_one_seo_pack' ), 'default' => 1), "home_page_title_format"=> Array( 'name' => __( 'Home Page Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%page_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "page_title_format"=> Array( 'name' => __( 'Page Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%page_title% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "post_title_format"=> Array( 'name' => __( 'Post Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%post_title% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "category_title_format"=> Array( 'name' => __( 'Category Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%category_title% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "archive_title_format"=> Array( 'name' => __( 'Archive Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%archive_title% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "date_title_format"=> Array( 'name' => __( 'Date Archive Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%date% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "author_title_format"=> Array( 'name' => __( 'Author Archive Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%author% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "tag_title_format"=> Array( 'name' => __( 'Tag Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%tag% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "search_title_format"=> Array( 'name' => __( 'Search Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%search% | %blog_title%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "description_format"=> Array( 'name' => __( 'Description Format', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%description%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "404_title_format"=> Array( 'name' => __( '404 Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => 'Nothing found for %request_words%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "paged_format"=> Array( 'name' => __( 'Paged Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => ' - Part %page%', 'condshow' => Array( "aiosp_rewrite_titles" => 1 ) ), "enablecpost"=> Array( 'name' => __( 'SEO for Custom Post Types:', 'all_in_one_seo_pack' ), 'default' => 'on', 'type' => 'radio', 'initial_options' => Array( 'on' => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ) ), "cpostactive" => Array( 'name' => __( 'SEO on only these post types:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array('post', 'page'), 'condshow' => Array( 'aiosp_enablecpost' => 'on' ) ), "taxactive" => Array( 'name' => __( 'SEO on only these taxonomies:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array('category', 'post_tag'), 'condshow' => Array( 'aiosp_enablecpost' => 'on' ) ), "cpostadvanced" => Array( 'name' => __( 'Enable Advanced Options:', 'all_in_one_seo_pack' ), 'default' => 0, 'type' => 'radio', 'initial_options' => Array( 'on' => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ), 'label' => null, 'condshow' => Array( "aiosp_enablecpost" => 'on' ) ), "cpostnoindex" => Array( 'name' => __( 'Default to NOINDEX:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array(), 'condshow' => Array( 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "cpostnofollow" => Array( 'name' => __( 'Default to NOFOLLOW:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array(), 'condshow' => Array( 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "cpostnoodp"=> Array( 'name' => __( 'Default to NOODP:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array(), 'condshow' => Array( 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "cpostnoydir"=> Array( 'name' => __( 'Default to NOYDIR:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array(), 'condshow' => Array( 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "cposttitles" => Array( 'name' => __( 'Custom titles:', 'all_in_one_seo_pack' ), 'type' => 'checkbox', 'default' => 0, 'condshow' => Array( "aiosp_rewrite_titles" => 1, 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "posttypecolumns" => Array( 'name' => __( 'Show Column Labels for Custom Post Types:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array('post', 'page') ), "admin_bar" => Array( 'name' => __( 'Display Menu In Admin Bar:', 'all_in_one_seo_pack' ), 'default' => 'on', ), "custom_menu_order" => Array( 'name' => __( 'Display Menu At The Top:', 'all_in_one_seo_pack' ), 'default' => 'on', ), "google_verify" => Array( 'name' => __( 'Google Webmaster Tools:', 'all_in_one_seo_pack' ), 'default' => '', 'type' => 'text' ), "bing_verify" => Array( 'name' => __( 'Bing Webmaster Center:', 'all_in_one_seo_pack' ), 'default' => '', 'type' => 'text' ), "pinterest_verify" => Array( 'name' => __( 'Pinterest Site Verification:', 'all_in_one_seo_pack' ), 'default' => '', 'type' => 'text' ), "google_publisher"=> Array( 'name' => __( 'Google Plus Default Profile:', 'all_in_one_seo_pack' ), 'default' => '', 'type' => 'text' ), "google_disable_profile"=> Array( 'name' => __( 'Disable Google Plus Profile:', 'all_in_one_seo_pack' ), 'default' => 0, 'type' => 'checkbox' ), "google_sitelinks_search" => Array( 'name' => __( 'Display Sitelinks Search Box:', 'all_in_one_seo_pack' ) ), "google_set_site_name" => Array( 'name' => __( 'Set Preferred Site Name:', 'all_in_one_seo_pack' ) ), "google_specify_site_name" => Array( 'name' => __( 'Specify A Preferred Name:', 'all_in_one_seo_pack' ), 'type' => 'text', 'placeholder' => $blog_name, 'condshow' => Array( 'aiosp_google_set_site_name' => 'on' ) ), "google_author_advanced" => Array( 'name' => __( 'Advanced Authorship Options:', 'all_in_one_seo_pack' ), 'default' => 0, 'type' => 'radio', 'initial_options' => Array( 'on' => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ), 'label' => null ), "google_author_location"=> Array( 'name' => __( 'Display Google Authorship:', 'all_in_one_seo_pack' ), 'default' => array( 'all' ), 'type' => 'multicheckbox', 'condshow' => Array( 'aiosp_google_author_advanced' => 'on' ) ), "google_enable_publisher" => Array( 'name' => __( 'Display Publisher Meta on Front Page:', 'all_in_one_seo_pack' ), 'default' => 'on', 'type' => 'radio', 'initial_options' => Array( 'on' => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ), 'condshow' => Array( 'aiosp_google_author_advanced' => 'on' ) ), "google_specify_publisher" => Array( 'name' => __( 'Specify Publisher URL:', 'all_in_one_seo_pack' ), 'type' => 'text', 'condshow' => Array( 'aiosp_google_author_advanced' => 'on', 'aiosp_google_enable_publisher' => 'on' ) ), // "google_connect"=>Array( 'name' => __( 'Connect With Google Analytics', 'all_in_one_seo_pack' ), ), "google_analytics_id"=> Array( 'name' => __( 'Google Analytics ID:', 'all_in_one_seo_pack' ), 'default' => null, 'type' => 'text', 'placeholder' => 'UA-########-#' ), "ga_use_universal_analytics" => Array( 'name' => __( 'Use Universal Analytics:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ) ) ), "ga_advanced_options"=> Array( 'name' => __( 'Advanced Analytics Options:', 'all_in_one_seo_pack' ), 'default' => 'on', 'type' => 'radio', 'initial_options' => Array( 'on' => __( 'Enabled', 'all_in_one_seo_pack' ), 0 => __( 'Disabled', 'all_in_one_seo_pack' ) ), 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ) ) ), "ga_domain"=> Array( 'name' => __( 'Tracking Domain:', 'all_in_one_seo_pack' ), 'type' => 'text', 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on') ), "ga_multi_domain"=> Array( 'name' => __( 'Track Multiple Domains:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_addl_domains" => Array( 'name' => __( 'Additional Domains:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on', 'aiosp_ga_multi_domain' => 'on' ) ), "ga_anonymize_ip"=> Array( 'name' => __( 'Anonymize IP Addresses:', 'all_in_one_seo_pack' ), 'type' => 'checkbox', 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_display_advertising"=> Array( 'name' => __( 'Display Advertiser Tracking:', 'all_in_one_seo_pack' ), 'type' => 'checkbox', 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_exclude_users"=> Array( 'name' => __( 'Exclude Users From Tracking:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_track_outbound_links"=> Array( 'name' => __( 'Track Outbound Links:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_link_attribution"=> Array( 'name' => __( 'Enhanced Link Attribution:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_advanced_options' => 'on' ) ), "ga_enhanced_ecommerce"=> Array( 'name' => __( 'Enhanced Ecommerce:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_google_analytics_id' => Array( 'lhs' => 'aiosp_google_analytics_id', 'op' => '!=', 'rhs' => '' ), 'aiosp_ga_use_universal_analytics' => 'on', 'aiosp_ga_advanced_options' => 'on' ) ), "use_categories"=> Array( 'name' => __( 'Use Categories for META keywords:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( "aiosp_togglekeywords" => 0 ) ), "use_tags_as_keywords" => Array( 'name' => __( 'Use Tags for META keywords:', 'all_in_one_seo_pack' ), 'default' => 1, 'condshow' => Array( "aiosp_togglekeywords" => 0 ) ), "dynamic_postspage_keywords"=> Array( 'name' => __( 'Dynamically Generate Keywords for Posts Page/Archives:', 'all_in_one_seo_pack' ), 'default' => 1, 'condshow' => Array( "aiosp_togglekeywords" => 0 ) ), "category_noindex"=> Array( 'name' => __( 'Use noindex for Categories:', 'all_in_one_seo_pack' ), 'default' => 1), "archive_date_noindex"=> Array( 'name' => __( 'Use noindex for Date Archives:', 'all_in_one_seo_pack' ), 'default' => 1), "archive_author_noindex"=> Array( 'name' => __( 'Use noindex for Author Archives:', 'all_in_one_seo_pack' ), 'default' => 1), "tags_noindex"=> Array( 'name' => __( 'Use noindex for Tag Archives:', 'all_in_one_seo_pack' ), 'default' => 0), "search_noindex"=> Array( 'name' => __( 'Use noindex for the Search page:', 'all_in_one_seo_pack' ), 'default' => 0), "404_noindex"=> Array( 'name' => __( 'Use noindex for the 404 page:', 'all_in_one_seo_pack' ), 'default' => 0), "tax_noindex"=> Array( 'name' => __( 'Use noindex for Taxonomy Archives:', 'all_in_one_seo_pack' ), 'type' => 'multicheckbox', 'default' => array(), 'condshow' => Array( 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on' ) ), "paginated_noindex" => Array( 'name' => __( 'Use noindex for paginated pages/posts:', 'all_in_one_seo_pack' ), 'default' => 0), "paginated_nofollow"=> Array( 'name' => __( 'Use nofollow for paginated pages/posts:', 'all_in_one_seo_pack' ), 'default' => 0), "noodp"=> Array( 'name' => __( 'Exclude site from the Open Directory Project:', 'all_in_one_seo_pack' ), 'default' => 0), "noydir"=> Array( 'name' => __( 'Exclude site from Yahoo! Directory:', 'all_in_one_seo_pack' ), 'default' => 0), "skip_excerpt"=> Array( 'name' => __( 'Avoid Using The Excerpt In Descriptions:', 'all_in_one_seo_pack' ), 'default' => 0 ), "generate_descriptions"=> Array( 'name' => __( 'Autogenerate Descriptions:', 'all_in_one_seo_pack' ), 'default' => 1), "run_shortcodes"=> Array( 'name' => __( 'Run Shortcodes In Autogenerated Descriptions:', 'all_in_one_seo_pack' ), 'default' => 0, 'condshow' => Array( 'aiosp_generate_descriptions' => 'on' ) ), "hide_paginated_descriptions"=> Array( 'name' => __( 'Remove Descriptions For Paginated Pages:', 'all_in_one_seo_pack' ), 'default' => 0), "dont_truncate_descriptions"=> Array( 'name' => __( 'Never Shorten Long Descriptions:', 'all_in_one_seo_pack' ), 'default' => 0), "schema_markup"=> Array( 'name' => __( 'Use Schema.org Markup', 'all_in_one_seo_pack' ), 'default' => 1), "unprotect_meta"=> Array( 'name' => __( 'Unprotect Post Meta Fields:', 'all_in_one_seo_pack' ), 'default' => 0), "ex_pages" => Array( 'name' => __( 'Exclude Pages:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'default' => '' ), "post_meta_tags"=> Array( 'name' => __( 'Additional Post Headers:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'default' => '', 'sanitize' => 'default' ), "page_meta_tags"=> Array( 'name' => __( 'Additional Page Headers:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'default' => '', 'sanitize' => 'default' ), "front_meta_tags"=> Array( 'name' => __( 'Additional Front Page Headers:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'default' => '', 'sanitize' => 'default' ), "home_meta_tags"=> Array( 'name' => __( 'Additional Blog Page Headers:', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'default' => '', 'sanitize' => 'default' ), "do_log"=> Array( 'name' => __( 'Log important events:', 'all_in_one_seo_pack' ), 'default' => null ), ); $this->locations = Array( 'default' => Array( 'name' => $this->name, 'prefix' => 'aiosp_', 'type' => 'settings', 'options' => null ), 'aiosp' => Array( 'name' => $this->plugin_name, 'type' => 'metabox', 'prefix' => '', 'help_link' => 'http://semperplugins.com/sections/postpage-settings/', 'options' => Array( 'edit', 'nonce-aioseop-edit', 'upgrade', 'snippet', 'title', 'description', 'keywords', 'custom_link', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel', 'sitemap_exclude', 'disable', 'disable_analytics' ), 'default_options' => Array( 'edit' => Array( 'type' => 'hidden', 'default' => 'aiosp_edit', 'prefix' => true, 'nowrap' => 1 ), 'nonce-aioseop-edit' => Array( 'type' => 'hidden', 'default' => null, 'prefix' => false, 'nowrap' => 1 ), 'upgrade' => Array( 'type' => 'html', 'label' => 'none', 'default' => '<a target="_blank" href="http://semperplugins.com/support/">' . __( 'Support Forum', 'all_in_one_seo_pack' ) . '</a>' ), 'snippet' => Array( 'name' => __( 'Preview Snippet', 'all_in_one_seo_pack' ), 'type' => 'custom', 'label' => 'top', 'default' => ' <script> jQuery(document).ready(function() { jQuery("#aiosp_title_wrapper").bind("input", function() { jQuery("#aiosp_snippet_title").text(jQuery("#aiosp_title_wrapper input").val().replace(/<(?:.|\n)*?>/gm, "")); }); jQuery("#aiosp_description_wrapper").bind("input", function() { jQuery("#aioseop_snippet_description").text(jQuery("#aiosp_description_wrapper textarea").val().replace(/<(?:.|\n)*?>/gm, "")); }); }); </script> <div class="preview_snippet"><div id="aioseop_snippet"><h3><a>%s</a></h3><div><div><cite id="aioseop_snippet_link">%s</cite></div><span id="aioseop_snippet_description">%s</span></div></div></div>' ), 'title' => Array( 'name' => __( 'Title', 'all_in_one_seo_pack' ), 'type' => 'text', 'count' => true, 'size' => 60 ), 'description' => Array( 'name' => __( 'Description', 'all_in_one_seo_pack' ), 'type' => 'textarea', 'count' => true, 'cols' => 80, 'rows' => 2 ), 'keywords' => Array( 'name' => __( 'Keywords (comma separated)', 'all_in_one_seo_pack' ), 'type' => 'text' ), 'custom_link' => Array( 'name' => __( 'Custom Canonical URL', 'all_in_one_seo_pack' ), 'type' => 'text', 'size' => 60 ), 'noindex' => Array( 'name' => __( "Robots Meta NOINDEX", 'all_in_one_seo_pack' ), 'default' => '' ), 'nofollow' => Array( 'name' => __( "Robots Meta NOFOLLOW", 'all_in_one_seo_pack' ), 'default' => '' ), 'noodp' => Array( 'name' => __( "Robots Meta NOODP", 'all_in_one_seo_pack' ) ), 'noydir' => Array( 'name' => __( "Robots Meta NOYDIR", 'all_in_one_seo_pack' ) ), 'titleatr' => Array( 'name' => __( 'Title Attribute', 'all_in_one_seo_pack' ), 'type' => 'text', 'size' => 60 ), 'menulabel' => Array( 'name' => __( 'Menu Label', 'all_in_one_seo_pack' ), 'type' => 'text', 'size' => 60 ), 'sitemap_exclude' => Array( 'name' => __( 'Exclude From Sitemap', 'all_in_one_seo_pack' ) ), 'disable' => Array( 'name' => __( 'Disable on this page/post', 'all_in_one_seo_pack' ) ), 'disable_analytics' => Array( 'name' => __( 'Disable Google Analytics', 'all_in_one_seo_pack' ), 'condshow' => Array( 'aiosp_disable' => 'on' ) ) ), 'display' => null ) ); if ( !empty( $meta_help_text ) ) foreach( $meta_help_text as $k => $v ) $this->locations['aiosp']['default_options'][$k]['help_text'] = $v; $this->layout = Array( 'default' => Array( 'name' => __( 'General Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/general-settings/', 'options' => Array() // this is set below, to the remaining options -- pdb ), 'home' => Array( 'name' => __( 'Home Page Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/home-page-settings/', 'options' => Array( 'home_title', 'home_description', 'home_keywords', 'use_static_home_info' ) ), 'keywords' => Array( 'name' => __( 'Keyword Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/keyword-settings/', 'options' => Array( "togglekeywords", "use_categories", "use_tags_as_keywords", "dynamic_postspage_keywords" ) ), 'title' => Array( 'name' => __( 'Title Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/title-settings/', 'options' => Array( "rewrite_titles", "force_rewrites", "cap_titles", "cap_cats", "home_page_title_format", "page_title_format", "post_title_format", "category_title_format", "archive_title_format", "date_title_format", "author_title_format", "tag_title_format", "search_title_format", "description_format", "404_title_format", "paged_format" ) ), 'cpt' => Array( 'name' => __( 'Custom Post Type Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/custom-post-type-settings/', 'options' => Array( "enablecpost", "cpostactive", "taxactive", "cpostadvanced", "cposttitles" ) ), 'display' => Array( 'name' => __( 'Display Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/display-settings/', 'options' => Array( "posttypecolumns", "admin_bar", "custom_menu_order" ) ), 'webmaster' => Array( 'name' => __( 'Webmaster Verification', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/sections/webmaster-verification/', 'options' => Array( "google_verify", "bing_verify", "pinterest_verify" ) ), 'google' => Array( 'name' => __( 'Google Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/google-settings/', 'options' => Array( "google_publisher", "google_disable_profile", "google_sitelinks_search", "google_set_site_name", "google_specify_site_name", "google_author_advanced", "google_author_location", "google_enable_publisher" , "google_specify_publisher", // "google_connect", "google_analytics_id", "ga_use_universal_analytics", "ga_advanced_options", "ga_domain", "ga_multi_domain", "ga_addl_domains", "ga_anonymize_ip", "ga_display_advertising", "ga_exclude_users", "ga_track_outbound_links", "ga_link_attribution", "ga_enhanced_ecommerce" ) ), 'noindex' => Array( 'name' => __( 'Noindex Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/noindex-settings/', 'options' => Array( 'cpostnoindex', 'cpostnofollow', 'cpostnoodp', 'cpostnoydir', 'category_noindex', 'archive_date_noindex', 'archive_author_noindex', 'tags_noindex', 'search_noindex', '404_noindex', 'tax_noindex', 'paginated_noindex', 'paginated_nofollow', 'noodp', 'noydir' ) ), 'advanced' => Array( 'name' => __( 'Advanced Settings', 'all_in_one_seo_pack' ), 'help_link' => 'http://semperplugins.com/documentation/advanced-settings/', 'options' => Array( 'generate_descriptions', 'skip_excerpt', 'run_shortcodes', 'hide_paginated_descriptions', 'dont_truncate_descriptions', 'unprotect_meta', 'ex_pages', 'post_meta_tags', 'page_meta_tags', 'front_meta_tags', 'home_meta_tags' ) ) ); $other_options = Array(); foreach( $this->layout as $k => $v ) $other_options = array_merge( $other_options, $v['options'] ); $this->layout['default']['options'] = array_diff( array_keys( $this->default_options ), $other_options ); if ( is_admin() ) { $this->add_help_text_links(); add_action( "aioseop_global_settings_header", Array( $this, 'display_right_sidebar' ) ); add_action( "aioseop_global_settings_footer", Array( $this, 'display_settings_footer' ) ); add_action( "output_option", Array( $this, 'custom_output_option' ), 10, 2 ); } add_action( 'split_shared_term', Array( $this, 'split_shared_term' ), 10, 4 ); } function get_all_term_data( $term_id ) { $terms = Array(); $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'sitemap_exclude', 'disable', 'disable_analytics', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); foreach( $optlist as $f ) { $meta = get_term_meta( $term_id, '_aioseop_' . $f, true ); if ( !empty( $meta ) ) { $terms['_aioseop_' . $f] = $meta; } } return $terms; } function split_shared_term( $term_id, $new_term_id, $term_taxonomy_id = '', $taxonomy = '' ) { $terms = $this->get_all_term_data( $term_id ); if ( !empty( $terms ) ) { $new_terms = $this->get_all_term_data( $new_term_id ); if ( empty( $new_terms ) ) { foreach( $terms as $k => $v ) { add_term_meta( $new_term_id, $k, $v, true ); } add_term_meta( $term_id, '_aioseop_term_was_split', true, true ); } } } function get_page_snippet_info() { static $info = Array(); if ( !empty( $info ) ) return $info; global $post, $aioseop_options, $wp_query; $title = $url = $description = $term = $category = ''; $p = $post; $w = $wp_query; if ( !is_object( $post ) ) $post = $this->get_queried_object(); if ( empty( $this->meta_opts ) ) $this->meta_opts = $this->get_current_options( Array(), 'aiosp' ); if ( !is_object( $post ) && is_admin() && !empty( $_GET ) && !empty( $_GET['post_type'] ) && !empty( $_GET['taxonomy'] ) && !empty( $_GET['tag_ID'] ) ) { $term = get_term_by( 'id', $_GET['tag_ID'], $_GET['taxonomy'] ); } if ( is_object( $post ) ) { $opts = $this->meta_opts; $post_id = $p->ID; if ( empty( $post->post_modified_gmt ) ) $wp_query = new WP_Query( array( 'p' => $post_id, 'post_type' => $post->post_type ) ); if ( $post->post_type == 'page' ) $wp_query->is_page = true; elseif ( $post->post_type == 'attachment' ) $wp_query->is_attachment = true; else $wp_query->is_single = true; if ( empty( $this->is_front_page ) ) $this->is_front_page = false; if ( get_option( 'show_on_front' ) == 'page' ) { if ( is_page() && $post->ID == get_option( 'page_on_front' ) ) $this->is_front_page = true; elseif ( $post->ID == get_option( 'page_for_posts' ) ) $wp_query->is_home = true; } $wp_query->queried_object = $post; if ( !empty( $post ) && !$wp_query->is_home && !$this->is_front_page ) { $title = $this->internationalize( get_post_meta( $post->ID, "_aioseop_title", true ) ); if ( empty( $title ) ) $title = $post->post_title; } $title_format = ''; if ( empty( $title ) ) { $title = $this->wp_title(); } $description = $this->get_main_description( $post ); if ( empty( $title_format ) ) { if ( is_page() ) $title_format = $aioseop_options['aiosp_page_title_format']; elseif ( is_single() || is_attachment() ) $title_format = $this->get_post_title_format( 'post', $post ); } if ( empty( $title_format ) ) { $title_format = '%post_title%'; } $categories = $this->get_all_categories( $post_id ); $category = ''; if ( count( $categories ) > 0 ) $category = $categories[0]; } else if ( is_object( $term ) ) { if ( $_GET['taxonomy'] == 'category' ) { query_posts( Array( 'cat' => $_GET['tag_ID'] ) ); } else if ( $_GET['taxonomy'] == 'post_tag' ) { query_posts( Array( 'tag' => $term->slug ) ); } else { query_posts( Array( 'page' => '', $_GET['taxonomy'] => $term->slug, 'post_type' => $_GET['post_type'] ) ); } if ( empty( $this->meta_opts ) ) $this->meta_opts = $this->get_current_options( Array(), 'aiosp' ); $title = $this->get_tax_name( $_GET['taxonomy'] ); $title_format = $this->get_tax_title_format(); $opts = $this->meta_opts; if ( !empty( $opts ) ) $description = $opts['aiosp_description']; if ( empty( $description ) ) $description = term_description(); $description = $this->internationalize( $description ); } $show_page = true; if ( !empty( $aioseop_options["aiosp_no_paged_canonical_links"] ) ) $show_page = false; if ( $aioseop_options['aiosp_can'] ) { if ( !empty( $aioseop_options['aiosp_customize_canonical_links'] ) && !empty( $opts['aiosp_custom_link'] ) ) $url = $opts['aiosp_custom_link']; if ( empty( $url ) ) $url = $this->aiosp_mrt_get_url( $wp_query, $show_page ); $url = apply_filters( 'aioseop_canonical_url', $url ); } if ( !$url ) $url = get_permalink(); $title = $this->apply_cf_fields( $title ); $description = $this->apply_cf_fields( $description ); $description = apply_filters( 'aioseop_description', $description ); $keywords = $this->get_main_keywords(); $keywords = $this->apply_cf_fields( $keywords ); $keywords = apply_filters( 'aioseop_keywords', $keywords ); $info = Array( 'title' => $title, 'description' => $description, 'keywords' => $keywords, 'url' => $url, 'title_format' => $title_format, 'category' => $category, 'w' => $wp_query, 'p' => $post ); wp_reset_postdata(); $wp_query = $w; $post = $p; return $info; } /*** Use custom callback for outputting snippet ***/ function custom_output_option( $buf, $args ) { if ( $args['name'] == 'aiosp_snippet' ) { $args['options']['type'] = 'html'; $args['options']['nowrap'] = false; $args['options']['save'] = false; $info = $this->get_page_snippet_info(); extract( $info ); } else return ''; if ( $this->strlen( $title ) > 70 ) $title = $this->trim_excerpt_without_filters( $title, 70 ) . '...'; if ( $this->strlen( $description ) > 156 ) $description = $this->trim_excerpt_without_filters( $description, 156 ) . '...'; $extra_title_len = 0; if ( empty( $title_format ) ) { $title = '<span id="' . $args['name'] . '_title">' . esc_attr( wp_strip_all_tags( html_entity_decode( $title ) ) ) . '</span>'; } else { if ( strpos( $title_format, '%blog_title%' ) !== false ) $title_format = str_replace( '%blog_title%', get_bloginfo( 'name' ), $title_format ); $title_format = $this->apply_cf_fields( $title_format ); $replace_title = '<span id="' . $args['name'] . '_title">' . esc_attr( wp_strip_all_tags( html_entity_decode( $title ) ) ) . '</span>'; if ( strpos( $title_format, '%post_title%' ) !== false ) $title_format = str_replace( '%post_title%', $replace_title, $title_format ); if ( strpos( $title_format, '%page_title%' ) !== false ) $title_format = str_replace( '%page_title%', $replace_title, $title_format ); if ( $w->is_category || $w->is_tag || $w->is_tax ) { if ( !empty( $_GET ) && !empty( $_GET['taxonomy'] ) && function_exists( 'wp_get_split_terms' ) ) { $was_split = get_term_meta( $term_id, '_aioseop_term_was_split', true ); if ( !$was_split ) { $split_terms = wp_get_split_terms( $featured_tag_id, $_GET['taxonomy'] ); if ( !empty( $split_terms ) ) { foreach ( $split_terms as $new_tax => $new_term ) { $this->split_shared_term( $term_id, $new_term ); } } } } if ( strpos( $title_format, '%category_title%' ) !== false ) $title_format = str_replace( '%category_title%', $replace_title, $title_format ); if ( strpos( $title_format, '%taxonomy_title%' ) !== false ) $title_format = str_replace( '%taxonomy_title%', $replace_title, $title_format ); } else { if ( strpos( $title_format, '%category%' ) !== false ) $title_format = str_replace( '%category%', $category, $title_format ); if ( strpos( $title_format, '%category_title%' ) !== false ) $title_format = str_replace( '%category_title%', $category, $title_format ); if ( strpos( $title_format, '%taxonomy_title%' ) !== false ) $title_format = str_replace( '%taxonomy_title%', $category, $title_format ); if ( strpos( $title_format, "%tax_" ) && !empty( $p ) ) { $taxes = get_object_taxonomies( $p, 'objects' ); if ( !empty( $taxes ) ) foreach( $taxes as $t ) if ( strpos( $title_format, "%tax_{$t->name}%" ) ) { $terms = $this->get_all_terms( $p->ID, $t->name ); $term = ''; if ( count( $terms ) > 0 ) $term = $terms[0]; $title_format = str_replace( "%tax_{$t->name}%", $term, $title_format ); } } } if ( strpos( $title_format, '%taxonomy_description%' ) !== false ) $title_format = str_replace( '%taxonomy_description%', $description, $title_format ); $title_format = preg_replace( '/%([^%]*?)%/', '', $title_format ); $title = $title_format; $extra_title_len = strlen( str_replace( $replace_title, '', $title_format ) ); } $args['value'] = sprintf( $args['value'], $title, esc_url( $url ), esc_attr( wp_strip_all_tags( $description ) ) ); $extra_title_len = (int)$extra_title_len; $args['value'] .= "<script>var aiosp_title_extra = {$extra_title_len};</script>"; $buf = $this->get_option_row( $args['name'], $args['options'], $args ); return $buf; } function add_page_icon() { wp_enqueue_script( 'wp-pointer', false, array( 'jquery' ) ); wp_enqueue_style( 'wp-pointer' ); $this->add_admin_pointers(); ?> <style> #toplevel_page_all-in-one-seo-pack-pro-aioseop_class .wp-menu-image { background: url(<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>shield-sprite-16.png) no-repeat 8px 6px !important; } #toplevel_page_all-in-one-seo-pack-pro-aioseop_class .wp-menu-image img { display: none; } #adminmenu #toplevel_page_all-in-one-seo-pack-pro-aioseop_class .wp-menu-image:before { content: ''; } #toplevel_page_all-in-one-seo-pack-pro-aioseop_class:hover .wp-menu-image, #toplevel_page_all-in-one-seo-pack-pro-aioseop_class.wp-has-current-submenu .wp-menu-image { background-position: 8px -26px !important; } #icon-aioseop.icon32 { background: url(<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>shield32.png) no-repeat left top !important; } #aioseop_settings_header #message { padding: 5px 0px 5px 50px; background-image: url(<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>update32.png); background-repeat: no-repeat; background-position: 10px; font-size: 14px; min-height: 32px; clear: none; } @media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and ( min--moz-device-pixel-ratio: 1.5), only screen and ( -o-min-device-pixel-ratio: 3/2), only screen and ( min-device-pixel-ratio: 1.5), only screen and ( min-resolution: 1.5dppx) { #toplevel_page_all-in-one-seo-pack-pro-aioseop_class .wp-menu-image { background-image: url('<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>shield-sprite-32.png') !important; -webkit-background-size: 16px 48px !important; -moz-background-size: 16px 48px !important; background-size: 16px 48px !important; } #icon-aioseop.icon32 { background-image: url('<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>shield64.png') !important; -webkit-background-size: 32px 32px !important; -moz-background-size: 32px 32px !important; background-size: 32px 32px !important; } #aioseop_settings_header #message { background-image: url(<?php echo AIOSEOP_PLUGIN_IMAGES_URL; ?>update64.png) !important; -webkit-background-size: 32px 32px !important; -moz-background-size: 32px 32px !important; background-size: 32px 32px !important; } } </style> <script> function aioseop_show_pointer( handle, value ) { if ( typeof( jQuery ) != 'undefined' ) { var p_edge = 'bottom'; var p_align = 'center'; if ( typeof( jQuery( value.pointer_target ).pointer) != 'undefined' ) { if ( typeof( value.pointer_edge ) != 'undefined' ) p_edge = value.pointer_edge; if ( typeof( value.pointer_align ) != 'undefined' ) p_align = value.pointer_align; jQuery(value.pointer_target).pointer({ content : value.pointer_text, position: { edge: p_edge, align: p_align }, close : function() { jQuery.post( ajaxurl, { pointer: handle, action: 'dismiss-wp-pointer' }); } }).pointer('open'); } } } <?php if ( !empty( $this->pointers ) ) { ?> if ( typeof( jQuery ) != 'undefined' ) { jQuery(document).ready(function() { var admin_pointer; var admin_index; <?php foreach( $this->pointers as $k => $p ) if ( !empty( $p["pointer_scope"] ) && ( $p["pointer_scope"] == 'global' ) ) { ?>admin_index = "<?php echo esc_attr($k); ?>"; admin_pointer = <?php echo json_encode( $p ); ?>; aioseop_show_pointer( admin_index, admin_pointer ); <?php } ?> }); } <?php } ?> </script> <?php } function add_page_hooks() { // $this->oauth_init(); $post_objs = get_post_types( '', 'objects' ); $pt = array_keys( $post_objs ); $rempost = array( 'revision', 'nav_menu_item' ); $pt = array_diff( $pt, $rempost ); $post_types = Array(); foreach ( $pt as $p ) { if ( !empty( $post_objs[$p]->label ) ) $post_types[$p] = $post_objs[$p]->label; else $post_types[$p] = $p; } $taxes = get_taxonomies( '', 'objects' ); $tx = array_keys( $taxes ); $remtax = array( 'nav_menu', 'link_category', 'post_format' ); $tx = array_diff( $tx, $remtax ); $tax_types = Array(); foreach( $tx as $t ) if ( !empty( $taxes[$t]->label ) ) $tax_types[$t] = $taxes[$t]->label; else $taxes[$t] = $t; $this->default_options["posttypecolumns"]['initial_options'] = $post_types; $this->default_options["cpostactive"]['initial_options'] = $post_types; $this->default_options["cpostnoindex"]['initial_options'] = $post_types; $this->default_options["cpostnofollow"]['initial_options'] = $post_types; $this->default_options["cpostnoodp"]['initial_options'] = $post_types; $this->default_options["cpostnoydir"]['initial_options'] = $post_types; $this->default_options["taxactive"]['initial_options'] = $tax_types; $this->default_options["google_author_location"]['initial_options'] = $post_types; $this->default_options['google_author_location' ]['initial_options'] = array_merge( Array( 'front' => __( 'Front Page', 'all_in_one_seo_pack' ) ), $post_types, Array( 'all' => __( 'Everywhere Else', 'all_in_one_seo_pack' ) ) ); $this->default_options["google_author_location"]['default'] = array_keys( $this->default_options["google_author_location"]['initial_options'] ); foreach ( $post_types as $p => $pt ) { $field = $p . "_title_format"; $name = $post_objs[$p]->labels->singular_name; if ( !isset( $this->default_options[$field] ) ) { $this->default_options[$field] = Array ( 'name' => "$name " . __( 'Title Format:', 'all_in_one_seo_pack' ) . "<br />($p)", 'type' => 'text', 'default' => '%post_title% | %blog_title%', 'condshow' => Array( 'aiosp_rewrite_titles' => 1, 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on', 'aiosp_cposttitles' => 'on', 'aiosp_cpostactive\[\]' => $p ) ); $this->help_text[$field] = __( 'The following macros are supported:', 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%post_title% - The original title of the post.', 'all_in_one_seo_pack' ) . '</li><li>'; $taxes = get_object_taxonomies( $p, 'objects' ); if ( !empty( $taxes ) ) foreach( $taxes as $n => $t ) $this->help_text[$field] .= sprintf( __( "%%tax_%s%% - This post's associated %s taxnomy title", 'all_in_one_seo_pack' ), $n, $t->label ) . '</li><li>'; $this->help_text[$field] .= __( "%post_author_login% - This post's author' login", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_nicename% - This post's author' nicename", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_firstname% - This post's author' first name (capitalized)", 'all_in_one_seo_pack' ) . '</li><li>' . __( "%post_author_lastname% - This post's author' last name (capitalized)", 'all_in_one_seo_pack' ) . '</li>' . '</ul>'; $this->help_anchors[$field] = '#custom-titles'; $this->layout['cpt']['options'][] = $field; } } global $wp_roles; if ( ! isset( $wp_roles ) ) { $wp_roles = new WP_Roles(); } $role_names = $wp_roles->get_names(); ksort( $role_names ); $this->default_options["ga_exclude_users"]['initial_options'] = $role_names; unset( $tax_types['category'] ); unset( $tax_types['post_tag'] ); $this->default_options["tax_noindex"]['initial_options'] = $tax_types; if ( empty( $tax_types ) ) unset( $this->default_options["tax_noindex"] ); foreach ( $tax_types as $p => $pt ) { $field = $p . "_tax_title_format"; $name = $pt; if ( !isset( $this->default_options[$field] ) ) { $this->default_options[$field] = Array ( 'name' => "$name " . __( 'Taxonomy Title Format:', 'all_in_one_seo_pack' ), 'type' => 'text', 'default' => '%taxonomy_title% | %blog_title%', 'condshow' => Array( 'aiosp_rewrite_titles' => 1, 'aiosp_enablecpost' => 'on', 'aiosp_cpostadvanced' => 'on', 'aiosp_cposttitles' => 'on', 'aiosp_taxactive\[\]' => $p ) ); $this->help_text[$field] = __( "The following macros are supported:", 'all_in_one_seo_pack' ) . '<ul><li>' . __( '%blog_title% - Your blog title', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%blog_description% - Your blog description', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%taxonomy_title% - The original title of the taxonomy', 'all_in_one_seo_pack' ) . '</li><li>' . __( '%taxonomy_description% - The description of the taxonomy', 'all_in_one_seo_pack' ) . '</li></ul>'; $this->help_anchors[$field] = '#custom-titles'; $this->layout['cpt']['options'][] = $field; } } $this->setting_options(); $this->add_help_text_links(); global $aioseop_update_checker; add_action( "{$this->prefix}update_options", Array( $aioseop_update_checker, 'license_change_check' ), 10, 2 ); add_action( "{$this->prefix}settings_update", Array( $aioseop_update_checker, 'update_check' ), 10, 2 ); add_filter( "{$this->prefix}display_options", Array( $this, 'filter_options' ), 10, 2 ); parent::add_page_hooks(); } function add_admin_pointers() { $this->pointers['aioseop_menu_236'] = Array( 'pointer_target' => '#toplevel_page_all-in-one-seo-pack-pro-aioseop_class', 'pointer_text' => '<h3>' . sprintf( __( 'Welcome to Version %s!', 'all_in_one_seo_pack' ), AIOSEOP_VERSION ) . '</h3><p>' . __( 'Thank you for running the latest and greatest All in One SEO Pack Pro ever! Please review your settings, as we\'re always adding new features for you!', 'all_in_one_seo_pack' ) . '</p>', 'pointer_edge' => 'top', 'pointer_align' => 'left', 'pointer_scope' => 'global' ); $this->pointers['aioseop_welcome_230'] = Array( 'pointer_target' => '#aioseop_top_button', 'pointer_text' => '<h3>' . sprintf( __( 'Review Your Settings', 'all_in_one_seo_pack' ), AIOSEOP_VERSION ) . '</h3><p>' . __( 'New in 2.3: improved support for taxonomies and a Video Sitemap module; enable modules from our feature manager! And please review your settings, we have added some new ones!', 'all_in_one_seo_pack' ) . '</p>', 'pointer_edge' => 'bottom', 'pointer_align' => 'left', 'pointer_scope' => 'local' ); $this->filter_pointers(); } function settings_page_init() { add_filter( "{$this->prefix}submit_options", Array( $this, 'filter_submit' ) ); } function enqueue_scripts() { add_filter( "{$this->prefix}display_settings", Array( $this, 'filter_settings' ), 10, 3 ); add_filter( "{$this->prefix}display_options", Array( $this, 'filter_options' ), 10, 2 ); parent::enqueue_scripts(); } function filter_submit( $submit ) { $submit['Submit_Default']['value'] = __( 'Reset General Settings to Defaults', 'all_in_one_seo_pack' ) . ' &raquo;'; $submit['Submit_All_Default'] = Array( 'type' => 'submit', 'class' => 'button-primary', 'value' => __( 'Reset ALL Settings to Defaults', 'all_in_one_seo_pack' ) . ' &raquo;' ); return $submit; } /** * Handle resetting options to defaults, but preserve the license key. */ function reset_options( $location = null, $delete = false ) { global $aioseop_update_checker; if ( $delete === true ) { $license_key = ''; if ( isset( $this->options ) && isset( $this->options['aiosp_license_key'] ) ) $license_key = $this->options['aiosp_license_key']; $this->delete_class_option( $delete ); $this->options = Array( 'aiosp_license_key' => $license_key ); } $default_options = $this->default_options( $location ); foreach ( $default_options as $k => $v ) if ( $k != 'aiosp_license_key' ) $this->options[$k] = $v; $aioseop_update_checker->license_key = $this->options['aiosp_license_key']; $this->update_class_option( $this->options ); } function get_current_options( $opts = Array(), $location = null, $defaults = null, $post = null ) { if ( ( $location === 'aiosp' ) && ( $this->locations[$location]['type'] == 'metabox' ) ) { if ( $post == null ) { global $post; } $post_id = $post; if ( is_object( $post_id ) ) $post_id = $post_id->ID; $get_opts = $this->default_options( $location ); $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'sitemap_exclude', 'disable', 'disable_analytics', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); if ( !( !empty( $this->options['aiosp_can'] ) ) && ( !empty( $this->options['aiosp_customize_canonical_links'] ) ) ) { unset( $optlist["custom_link"] ); } foreach ( $optlist as $f ) { $meta = ''; $field = "aiosp_$f"; if ( ( isset( $_GET['taxonomy'] ) && isset( $_GET['tag_ID'] ) ) || is_category() || is_tag() || is_tax() ) { if ( is_admin() && isset( $_GET['tag_ID'] ) ) { $meta = get_term_meta( $_GET['tag_ID'], '_aioseop_' . $f, true ); } else { $queried_object = get_queried_object(); if ( !empty( $queried_object ) && !empty( $queried_object->term_id ) ) { $meta = get_term_meta( $queried_object->term_id, '_aioseop_' . $f, true ); } } } else $meta = get_post_meta( $post_id, '_aioseop_' . $f, true ); $get_opts[$field] = htmlspecialchars( stripslashes( $meta ) ); } $opts = wp_parse_args( $opts, $get_opts ); return $opts; } else { $options = parent::get_current_options( $opts, $location, $defaults ); return $options; } } function filter_settings( $settings, $location, $current ) { if ( $location == null ) { $prefix = $this->prefix; foreach ( Array( 'seopostcol', 'seocustptcol', 'debug_info', 'max_words_excerpt' ) as $opt ) unset( $settings["{$prefix}$opt"] ); if ( !class_exists( 'DOMDocument' ) ) { unset( $settings["{prefix}google_connect"] ); } if ( !empty( $this->options['aiosp_license_key'] ) ) { $settings['aiosp_license_key']['type'] = 'password'; $settings['aiosp_license_key']['size'] = 38; } } elseif ( $location == 'aiosp' ) { global $post, $aioseop_sitemap; $prefix = $this->get_prefix( $location ) . $location . '_'; if ( !empty( $post ) ) { $post_type = get_post_type( $post ); if ( !empty( $this->options['aiosp_cpostnoindex'] ) && ( in_array( $post_type, $this->options['aiosp_cpostnoindex'] ) ) ) { $settings["{$prefix}noindex"]['type'] = 'select'; $settings["{$prefix}noindex"]['initial_options'] = Array( '' => __( 'Default - noindex', 'all_in_one_seo_pack' ), 'off' => __( 'index', 'all_in_one_seo_pack' ), 'on' => __( 'noindex', 'all_in_one_seo_pack' ) ); } if ( !empty( $this->options['aiosp_cpostnofollow'] ) && ( in_array( $post_type, $this->options['aiosp_cpostnofollow'] ) ) ) { $settings["{$prefix}nofollow"]['type'] = 'select'; $settings["{$prefix}nofollow"]['initial_options'] = Array( '' => __( 'Default - nofollow', 'all_in_one_seo_pack' ), 'off' => __( 'follow', 'all_in_one_seo_pack' ), 'on' => __( 'nofollow', 'all_in_one_seo_pack' ) ); } if ( !empty( $this->options['aiosp_cpostnoodp'] ) && ( in_array( $post_type, $this->options['aiosp_cpostnoodp'] ) ) ) { $settings["{$prefix}noodp"]['type'] = 'select'; $settings["{$prefix}noodp"]['initial_options'] = Array( '' => __( 'Default - noodp', 'all_in_one_seo_pack' ), 'off' => __( 'odp', 'all_in_one_seo_pack' ), 'on' => __( 'noodp', 'all_in_one_seo_pack' ) ); } if ( !empty( $this->options['aiosp_cpostnoydir'] ) && ( in_array( $post_type, $this->options['aiosp_cpostnoydir'] ) ) ) { $settings["{$prefix}noydir"]['type'] = 'select'; $settings["{$prefix}noydir"]['initial_options'] = Array( '' => __( 'Default - noydir', 'all_in_one_seo_pack' ), 'off' => __( 'ydir', 'all_in_one_seo_pack' ), 'on' => __( 'noydir', 'all_in_one_seo_pack' ) ); } global $post; $info = $this->get_page_snippet_info(); extract( $info ); $settings["{$prefix}title"]['placeholder'] = $title; $settings["{$prefix}description"]['placeholder'] = $description; $settings["{$prefix}keywords"]['placeholder'] = $keywords; } if ( !is_object( $aioseop_sitemap ) ) unset( $settings['aiosp_sitemap_exclude'] ); if ( is_object( $post ) ) { if ( $post->post_type != 'page' ) { unset( $settings["{$prefix}titleatr"] ); unset( $settings["{$prefix}menulabel"] ); } } if ( !empty( $this->options[$this->prefix . 'togglekeywords'] ) ) { unset( $settings["{$prefix}keywords"] ); unset( $settings["{$prefix}togglekeywords"] ); } elseif ( !empty( $current["{$prefix}togglekeywords"] ) ) { unset( $settings["{$prefix}keywords"] ); } if ( !( !empty( $this->options['aiosp_can'] ) ) && ( !empty( $this->options['aiosp_customize_canonical_links'] ) ) ) { unset( $settings["{$prefix}custom_link"] ); } } return $settings; } function filter_options( $options, $location ) { if ( $location == 'aiosp' ) { global $post; if ( !empty( $post ) ) { $prefix = $this->prefix; $post_type = get_post_type( $post ); foreach( Array( 'noindex', 'nofollow', 'noodp', 'noydir' ) as $no ) { if ( empty( $this->options['aiosp_cpost' . $no] ) || ( !in_array( $post_type, $this->options['aiosp_cpost' . $no] ) ) ) if ( isset( $options["{$prefix}{$no}"] ) && ( $options["{$prefix}{$no}"] != 'on' ) ) unset( $options["{$prefix}{$no}"] ); } } } if ( $location == null ) { $prefix = $this->prefix; if ( isset( $options["{$prefix}rewrite_titles"] ) && ( !empty( $options["{$prefix}rewrite_titles"] ) ) ) $options["{$prefix}rewrite_titles"] = 1; if ( ( isset( $options["{$prefix}enablecpost"] ) ) && ( $options["{$prefix}enablecpost"] === '' ) ) $options["{$prefix}enablecpost"] = 0; if ( ( isset( $options["{$prefix}use_original_title"] ) ) && ( $options["{$prefix}use_original_title"] === '' ) ) $options["{$prefix}use_original_title"] = 0; } return $options; } function display_extra_metaboxes( $add, $meta ) { echo "<div class='aioseop_metabox_wrapper' >"; switch ( $meta['id'] ) { case "aioseop-about": ?><div class="aioseop_metabox_text"> <p><h2 style="display:inline;"><?php echo AIOSEOP_PLUGIN_NAME; ?></h2><?php sprintf( __( "by %s of %s.", 'all_in_one_seo_pack' ), 'Michael Torbert', '<a target="_blank" title="Semper Fi Web Design" href="http://semperfiwebdesign.com/">Semper Fi Web Design</a>' ); ?>.</p> <?php global $current_user; $user_id = $current_user->ID; $ignore = get_user_meta( $user_id, 'aioseop_ignore_notice' ); if ( !empty( $ignore ) ) { $qa = Array(); wp_parse_str( $_SERVER["QUERY_STRING"], $qa ); $qa['aioseop_reset_notices'] = 1; $url = '?' . build_query( $qa ); echo '<p><a href="' . $url . '">' . __( "Reset Dismissed Notices", 'all_in_one_seo_pack' ) . '</a></p>'; } ?> </div> <?php case "aioseop-donate": ?> <div> <div class="aioseop_metabox_feature"> <a target="_blank" title="<?php _e( 'Follow us on Facebook', 'all_in_one_seo_pack' ); ?>" href="http://www.facebook.com/pages/Semper-Fi-Web-Design/121878784498475"><span class="aioseop_follow_button aioseop_facebook_follow"></span></a> <a target="_blank" title="<?php _e( 'Follow us on Twitter', 'all_in_one_seo_pack' ); ?>" href="http://twitter.com/semperfidev/"><span class="aioseop_follow_button aioseop_twitter_follow"></span></a> </div> </div> <?php break; case "aioseop-list": ?><div class="aioseop_metabox_text"> <form action="http://semperfiwebdesign.us1.list-manage.com/subscribe/post?u=794674d3d54fdd912f961ef14&amp;id=af0a96d3d9" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"> <h2><?php _e( 'Join our mailing list for tips, tricks, and WordPress secrets.', 'all_in_one_seo_pack' ); ?></h2> <p><i><?php _e( 'Sign up today and receive a free copy of the e-book 5 SEO Tips for WordPress ($39 value).', 'all_in_one_seo_pack' ); ?></i></p> <p><input type="text" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Address"> <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn"></p> </form> </div> <?php break; case "aioseop-support": ?><div class="aioseop_metabox_text"> <p><div class="aioseop_icon aioseop_file_icon"></div><a target="_blank" href="http://semperplugins.com/documentation/"><?php _e( 'Read the All in One SEO Pack user guide', 'all_in_one_seo_pack' ); ?></a></p> <p><div class="aioseop_icon aioseop_support_icon"></div><a target="_blank" title="<?php _e( 'All in One SEO Pro Plugin Support Forum', 'all_in_one_seo_pack' ); ?>" href="http://semperplugins.com/support/"><?php _e( 'Access our Premium Support Forums', 'all_in_one_seo_pack' ); ?></a></p> <p><div class="aioseop_icon aioseop_cog_icon"></div><a target="_blank" title="<?php _e( 'All in One SEO Pro Plugin Changelog', 'all_in_one_seo_pack' ); ?>" href="http://semperplugins.com/documentation/all-in-one-seo-pack-pro-changelog/"><?php _e( 'View the Changelog', 'all_in_one_seo_pack' ); ?></a></p> <p><div class="aioseop_icon aioseop_youtube_icon"></div><a target="_blank" href="http://semperplugins.com/doc-type/video/"><?php _e( 'Watch video tutorials', 'all_in_one_seo_pack' ); ?></a></p> <p><div class="aioseop_icon aioseop_book_icon"></div><a target="_blank" href="http://semperplugins.com/documentation/quick-start-guide/"><?php _e( 'Getting started? Read the Beginners Guide', 'all_in_one_seo_pack' ); ?></a></p> </div> <?php break; } echo "</div>"; } function get_queried_object() { static $p = null; global $wp_query, $post; if ( $p !== null ) return $p; if ( is_object( $post ) ) $p = $post; else { if ( !$wp_query ) return null; $p = $wp_query->get_queried_object(); } return $p; } function is_page_included() { global $aioseop_options; if ( is_feed() ) return false; if ( aioseop_mrt_exclude_this_page() ) return false; $post = $this->get_queried_object(); $post_type = ''; if ( !empty( $post ) && !empty( $post->post_type ) ) $post_type = $post->post_type; if ( empty( $aioseop_options['aiosp_enablecpost'] ) ) { $wp_post_types = get_post_types( Array( '_builtin' => true ) ); // don't display meta if SEO isn't enabled on custom post types -- pdb if( is_singular() && !in_array( $post_type, $wp_post_types ) && !is_front_page() ) return false; } else { $wp_post_types = $aioseop_options['aiosp_cpostactive']; if ( empty( $wp_post_types ) ) $wp_post_types = Array(); if ( is_tax() ) { if ( empty( $aioseop_options['aiosp_taxactive'] ) || !is_tax( $aioseop_options['aiosp_taxactive'] ) ) return false; } elseif ( is_category() ) { if ( empty( $aioseop_options['aiosp_taxactive'] ) || !in_array( 'category', $aioseop_options['aiosp_taxactive'] ) ) return false; } elseif ( is_tag() ) { if ( empty( $aioseop_options['aiosp_taxactive'] ) || !in_array( 'post_tag', $aioseop_options['aiosp_taxactive'] ) ) return false; } else if ( !in_array( $post_type, $wp_post_types ) && !is_front_page() && !is_post_type_archive( $wp_post_types ) ) return false; } $this->meta_opts = $this->get_current_options( Array(), 'aiosp' ); $aiosp_disable = $aiosp_disable_analytics = false; if ( !empty( $this->meta_opts ) ) { if ( isset( $this->meta_opts['aiosp_disable'] ) ) $aiosp_disable = $this->meta_opts['aiosp_disable']; if ( isset( $this->meta_opts['aiosp_disable_analytics'] ) ) $aiosp_disable_analytics = $this->meta_opts['aiosp_disable_analytics']; } if ( $aiosp_disable ) { if ( !$aiosp_disable_analytics ) { if ( aioseop_option_isset( 'aiosp_google_analytics_id' ) ) { remove_action( 'aioseop_modules_wp_head', array( $this, 'aiosp_google_analytics' ) ); add_action( 'wp_head', array( $this, 'aiosp_google_analytics' ) ); } } return false; } if ( !empty( $this->meta_opts ) && $this->meta_opts['aiosp_disable'] == true ) return false; return true; } function template_redirect() { global $aioseop_options; $post = $this->get_queried_object(); if ( !$this->is_page_included() ) return; if ( !empty( $aioseop_options['aiosp_rewrite_titles'] ) ) { $force_rewrites = 1; if ( isset( $aioseop_options['aiosp_force_rewrites'] ) ) $force_rewrites = $aioseop_options['aiosp_force_rewrites']; if ( $force_rewrites ) ob_start( array( $this, 'output_callback_for_title' ) ); else add_filter( 'wp_title', array( $this, 'wp_title' ), 20 ); } } function output_callback_for_title( $content ) { return $this->rewrite_title( $content ); } function init() { if ( !defined( 'WP_PLUGIN_DIR' ) ) { load_plugin_textdomain( 'all_in_one_seo_pack', str_replace( ABSPATH, '', dirname( __FILE__ ) ) ); } else { load_plugin_textdomain( 'all_in_one_seo_pack', false, AIOSEOP_PLUGIN_DIRNAME ); } } function add_hooks() { global $aioseop_options, $aioseop_update_checker; aioseop_update_settings_check(); add_filter( 'user_contactmethods', 'aioseop_add_contactmethods' ); if ( is_user_logged_in() && function_exists( 'is_admin_bar_showing' ) && is_admin_bar_showing() && current_user_can( 'manage_options' ) ) add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ), 1000 ); if ( is_admin() ) { add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_head', array( $this, 'add_page_icon' ) ); add_action( 'admin_init', 'aioseop_addmycolumns', 1 ); add_action( 'admin_init', 'aioseop_handle_ignore_notice' ); if ( current_user_can( 'update_plugins' ) ) add_action( 'admin_notices', Array( $aioseop_update_checker, 'key_warning' ) ); add_action( 'after_plugin_row_' . AIOSEOP_PLUGIN_BASENAME, Array( $aioseop_update_checker, 'add_plugin_row' ) ); } else { if ( $aioseop_options['aiosp_can'] == '1' || $aioseop_options['aiosp_can'] == 'on' ) remove_action( 'wp_head', 'rel_canonical' ); ////analytics if ( aioseop_option_isset( 'aiosp_google_analytics_id' ) ) add_action( 'aioseop_modules_wp_head', array( $this, 'aiosp_google_analytics' ) ); add_filter( 'wp_list_pages', 'aioseop_list_pages' ); add_action( 'wp_head', array( $this, 'wp_head'), apply_filters( 'aioseop_wp_head_priority', 1 ) ); add_action( 'template_redirect', array( $this, 'template_redirect' ), 0 ); add_filter( 'wp_list_pages_excludes', 'aioseop_get_pages_start' ); add_filter( 'get_pages', 'aioseop_get_pages' ); } } function is_static_front_page() { if ( isset( $this->is_front_page ) && $this->is_front_page !== null ) return $this->is_front_page; $post = $this->get_queried_object(); $this->is_front_page = ( get_option( 'show_on_front' ) == 'page' && is_page() && !empty( $post ) && $post->ID == get_option( 'page_on_front' ) ); return $this->is_front_page; } function is_static_posts_page() { static $is_posts_page = null; if ( $is_posts_page !== null ) return $is_posts_page; $post = $this->get_queried_object(); $is_posts_page = ( get_option( 'show_on_front' ) == 'page' && is_home() && !empty( $post ) && $post->ID == get_option( 'page_for_posts' ) ); return $is_posts_page; } function check_rewrite_handler() { global $aioseop_options; $force_rewrites = 1; if ( isset( $aioseop_options['aiosp_force_rewrites'] ) ) $force_rewrites = $aioseop_options['aiosp_force_rewrites']; if ( !empty( $aioseop_options['aiosp_rewrite_titles'] ) && $force_rewrites ) { // make the title rewrite as short as possible if (function_exists( 'ob_list_handlers' ) ) { $active_handlers = ob_list_handlers(); } else { $active_handlers = array(); } if (sizeof($active_handlers) > 0 && $this->strtolower( $active_handlers[sizeof( $active_handlers ) - 1] ) == $this->strtolower( 'All_in_One_SEO_Pack::output_callback_for_title' ) ) { ob_end_flush(); } else { $this->log( "another plugin interfering?" ); // if we get here there *could* be trouble with another plugin :( $this->ob_start_detected = true; if ( $this->option_isset( "rewrite_titles" ) ) { // try alternate method -- pdb $aioseop_options['aiosp_rewrite_titles'] = 0; $force_rewrites = 0; add_filter( 'wp_title', array( $this, 'wp_title' ), 20 ); } if ( function_exists( 'ob_list_handlers' ) ) { foreach ( ob_list_handlers() as $handler ) { $this->log( "detected output handler $handler" ); } } } } } // handle prev / next links function get_prev_next_links( $post = null ) { $prev = $next = ''; $page = $this->get_page_number(); if ( is_home() || is_archive() || is_paged() ) { global $wp_query; $max_page = $wp_query->max_num_pages; if ( $page > 1 ) $prev = get_previous_posts_page_link(); if ( $page < $max_page ) { $paged = $GLOBALS['paged']; if ( !is_single() ) { if ( !$paged ) $paged = 1; $nextpage = intval($paged) + 1; if ( !$max_page || $max_page >= $nextpage ) $next = get_pagenum_link($nextpage); } } } else if ( is_page() || is_single() ) { $numpages = 1; $multipage = 0; $page = get_query_var('page'); if ( ! $page ) $page = 1; if ( is_single() || is_page() || is_feed() ) $more = 1; $content = $post->post_content; if ( false !== strpos( $content, '<!--nextpage-->' ) ) { if ( $page > 1 ) $more = 1; $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content ); $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content ); $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content ); // Ignore nextpage at the beginning of the content. if ( 0 === strpos( $content, '<!--nextpage-->' ) ) $content = substr( $content, 15 ); $pages = explode('<!--nextpage-->', $content); $numpages = count($pages); if ( $numpages > 1 ) $multipage = 1; } if ( !empty( $page ) ) { if ( $page > 1 ) $prev = _wp_link_page( $page - 1 ); if ( $page + 1 <= $numpages ) $next = _wp_link_page( $page + 1 ); } if ( !empty( $prev ) ) { $prev = $this->substr( $prev, 9, -2 ); } if ( !empty( $next ) ) { $next = $this->substr( $next, 9, -2 ); } } return Array( 'prev' => $prev, 'next' => $next ); } function get_google_authorship( $post ) { global $aioseop_options; $page = $this->get_page_number(); // handle authorship $googleplus = $publisher = $author = ''; if ( !empty( $post ) && isset( $post->post_author ) && empty( $aioseop_options['aiosp_google_disable_profile'] ) ) $googleplus = get_the_author_meta( 'googleplus', $post->post_author ); if ( empty( $googleplus ) && !empty( $aioseop_options['aiosp_google_publisher'] ) ) $googleplus = $aioseop_options['aiosp_google_publisher']; if ( ( is_front_page() ) && ( $page < 2 ) ) { if ( !empty( $aioseop_options['aiosp_google_publisher'] ) ) $publisher = $aioseop_options['aiosp_google_publisher']; if ( !empty( $aioseop_options["aiosp_google_author_advanced"] ) ) { if ( empty( $aioseop_options["aiosp_google_enable_publisher"] ) ) { $publisher = ''; } elseif ( !empty( $aioseop_options["aiosp_google_specify_publisher"] ) ) { $publisher = $aioseop_options["aiosp_google_specify_publisher"]; } } } if ( is_singular() && ( !empty( $googleplus ) ) ) $author = $googleplus; else if ( !empty( $aioseop_options['aiosp_google_publisher'] ) ) $author = $aioseop_options['aiosp_google_publisher']; if ( !empty( $aioseop_options['aiosp_google_author_advanced'] ) && isset( $aioseop_options['aiosp_google_author_location'] ) ) { if ( empty( $aioseop_options['aiosp_google_author_location'] ) ) $aioseop_options['aiosp_google_author_location'] = Array(); if ( is_front_page() && !in_array( 'front', $aioseop_options['aiosp_google_author_location'] ) ) { $author = ''; } else { if ( in_array( 'all', $aioseop_options['aiosp_google_author_location'] ) ) { if ( is_singular() && !is_singular( $aioseop_options['aiosp_google_author_location'] ) ) $author = ''; } else { if ( !is_singular( $aioseop_options['aiosp_google_author_location'] ) ) $author = ''; } } } return Array( 'publisher' => $publisher, 'author' => $author ); } function get_robots_meta() { global $aioseop_options; $opts = $this->meta_opts; $page = $this->get_page_number(); $robots_meta = $tax_noindex = ''; if ( isset( $aioseop_options['aiosp_tax_noindex'] ) ) $tax_noindex = $aioseop_options['aiosp_tax_noindex']; if ( empty( $tax_noindex ) || !is_array( $tax_noindex) ) $tax_noindex = Array(); $aiosp_noindex = $aiosp_nofollow = $aiosp_noodp = $aiosp_noydir = ''; $noindex = "index"; $nofollow = "follow"; if ( ( is_category() && !empty( $aioseop_options['aiosp_category_noindex'] ) ) || ( !is_category() && is_archive() && !is_tag() && !is_tax() && ( ( is_date() && !empty( $aioseop_options['aiosp_archive_date_noindex'] ) ) || ( is_author() && !empty( $aioseop_options['aiosp_archive_author_noindex'] ) ) ) ) || ( is_tag() && !empty( $aioseop_options['aiosp_tags_noindex'] ) ) || ( is_search() && !empty( $aioseop_options['aiosp_search_noindex'] ) ) || ( is_404() && !empty( $aioseop_options['aiosp_404_noindex'] ) ) || ( is_tax() && in_array( get_query_var( 'taxonomy' ), $tax_noindex ) ) ) { $noindex = 'noindex'; } elseif ( ( is_single() || is_page() || $this->is_static_posts_page() || is_attachment() || is_category() || is_tag() || is_tax() || ( $page > 1 ) ) ) { $post_type = get_post_type(); if ( !empty( $opts ) ) { $aiosp_noindex = htmlspecialchars( stripslashes( $opts['aiosp_noindex'] ) ); $aiosp_nofollow = htmlspecialchars( stripslashes( $opts['aiosp_nofollow'] ) ); $aiosp_noodp = htmlspecialchars( stripslashes( $opts['aiosp_noodp'] ) ); $aiosp_noydir = htmlspecialchars( stripslashes( $opts['aiosp_noydir'] ) ); } if ( $aiosp_noindex || $aiosp_nofollow || $aiosp_noodp || $aiosp_noydir || !empty( $aioseop_options['aiosp_cpostnoindex'] ) || !empty( $aioseop_options['aiosp_cpostnofollow'] ) || !empty( $aioseop_options['aiosp_cpostnoodp'] ) || !empty( $aioseop_options['aiosp_cpostnoydir'] ) || !empty( $aioseop_options['aiosp_paginated_noindex'] ) || !empty( $aioseop_options['aiosp_paginated_nofollow'] ) ) { if ( ( $aiosp_noindex == 'on' ) || ( ( !empty( $aioseop_options['aiosp_paginated_noindex'] ) ) && ( ( $page > 1 ) ) ) || ( ( $aiosp_noindex == '' ) && ( !empty( $aioseop_options['aiosp_cpostnoindex'] ) ) && ( in_array( $post_type, $aioseop_options['aiosp_cpostnoindex'] ) ) ) ) $noindex = "no" . $noindex; if ( ( $aiosp_nofollow == 'on' ) || ( ( !empty( $aioseop_options['aiosp_paginated_nofollow'] ) ) && ( ( $page > 1 ) ) ) || ( ( $aiosp_nofollow == '' ) && ( !empty( $aioseop_options['aiosp_cpostnofollow'] ) ) && ( in_array( $post_type, $aioseop_options['aiosp_cpostnofollow'] ) ) ) ) $nofollow = "no" . $nofollow; if ( ( !empty( $aioseop_options['aiosp_cpostnoodp'] ) && ( in_array( $post_type, $aioseop_options['aiosp_cpostnoodp'] ) ) ) ) $aiosp_noodp = true; if ( ( !empty( $aioseop_options['aiosp_cpostnoydir'] ) && ( in_array( $post_type, $aioseop_options['aiosp_cpostnoydir'] ) ) ) ) $aiosp_noydir = true; } } if ( !empty( $aioseop_options['aiosp_noodp'] ) && $aioseop_options['aiosp_noodp'] ) $aiosp_noodp = true; if ( !empty( $aioseop_options['aiosp_noydir'] ) && $aioseop_options['aiosp_noydir'] ) $aiosp_noydir = true; if ( $aiosp_noodp ) $nofollow .= ',noodp'; if ( $aiosp_noydir ) $nofollow .= ',noydir'; $robots_meta = $noindex . ',' . $nofollow; if ( $robots_meta == 'index,follow' ) $robots_meta = ''; return $robots_meta; } function get_main_description( $post = null ) { global $aioseop_options; $opts = $this->meta_opts; $description = ''; if ( ( is_category() || is_tag() || is_tax() ) && $this->show_page_description() ) { if ( !empty( $opts ) ) $description = $opts['aiosp_description']; if ( empty( $description ) ) $description = term_description(); $description = $this->internationalize( $description ); } elseif ( is_author() && $this->show_page_description() ) { $description = $this->internationalize( get_the_author_meta( 'description' ) ); } else if ( is_front_page() ) { $description = $this->get_aioseop_description( $post ); } else if ( function_exists( 'woocommerce_get_page_id' ) && is_post_type_archive( 'product' ) && ( $post_id = woocommerce_get_page_id( 'shop' ) ) && ( $post = get_post( $post_id ) ) ) { $description = $this->get_post_description( $post ); $description = $this->apply_cf_fields( $description ); } else if ( is_single() || is_page() || is_attachment() || is_home() || $this->is_static_posts_page() ) { $description = $this->get_aioseop_description( $post ); } if ( empty( $aioseop_options['aiosp_dont_truncate_descriptions'] ) ) { $description = $this->trim_excerpt_without_filters( $description ); } return $description; } function trim_description( $description ) { $description = trim( wp_strip_all_tags( $description ) ); $description = str_replace( '"', '&quot;', $description ); $description = str_replace( "\r\n", ' ', $description ); $description = str_replace( "\n", ' ', $description ); return $description; } function apply_description_format( $description, $post = null ) { global $aioseop_options, $wp_query; $description_format = $aioseop_options['aiosp_description_format']; if ( !isset( $description_format ) || empty( $description_format ) ) { $description_format = "%description%"; } $description = str_replace( '%description%', apply_filters( 'aioseop_description_override', $description ), $description_format ); if ( strpos( $description, '%blog_title%' ) !== false ) $description = str_replace( '%blog_title%', get_bloginfo( 'name' ), $description ); if ( strpos( $description, '%blog_description%' ) !== false ) $description = str_replace( '%blog_description%', get_bloginfo( 'description' ), $description ); if ( strpos( $description, '%wp_title%' ) !== false ) $description = str_replace( '%wp_title%', $this->get_original_title(), $description ); if ( strpos( $description, '%post_title%' ) !== false ) $description = str_replace( '%post_title%', $this->get_aioseop_title( $post ), $description ); if( $aioseop_options['aiosp_can'] && is_attachment() ) { $url = $this->aiosp_mrt_get_url( $wp_query ); if ( $url ) { $matches = Array(); preg_match_all( '/(\d+)/', $url, $matches ); if ( is_array( $matches ) ){ $uniqueDesc = join( '', $matches[0] ); } } $description .= ' ' . $uniqueDesc; } return $description; } function get_main_keywords() { global $aioseop_options; global $aioseop_keywords; global $post; $opts = $this->meta_opts; if ( ( ( is_front_page() && $aioseop_options['aiosp_home_keywords'] && !$this->is_static_posts_page() ) || $this->is_static_front_page() ) ) { if ( !empty( $aioseop_options['aiosp_use_static_home_info'] ) ) { $keywords = $this->get_all_keywords(); } else { $keywords = trim( $this->internationalize( $aioseop_options['aiosp_home_keywords'] ) ); } } elseif ( empty( $aioseop_options['aiosp_dynamic_postspage_keywords'] ) && $this->is_static_posts_page() ) { $keywords = stripslashes( $this->internationalize( $opts["aiosp_keywords"] ) ); // and if option = use page set keywords instead of keywords from recent posts } elseif ( ( $blog_page = $this->get_blog_page( $post ) ) && empty( $aioseop_options['aiosp_dynamic_postspage_keywords'] ) ) { $keywords = stripslashes( $this->internationalize( get_post_meta( $blog_page->ID, "_aioseop_keywords", true ) ) ); } elseif ( empty( $aioseop_options['aiosp_dynamic_postspage_keywords'] ) && ( is_archive() || is_post_type_archive() ) ) { $keywords = ""; } else { $keywords = $this->get_all_keywords(); } return $keywords; } function wp_head() { if ( !$this->is_page_included() ) return; $opts = $this->meta_opts; global $aioseop_update_checker, $wp_query, $aioseop_options, $posts; static $aioseop_dup_counter = 0; $aioseop_dup_counter++; if ( $aioseop_dup_counter > 1 ) { echo "\n<!-- " . sprintf( __( "Debug Warning: All in One SEO Pack Pro meta data was included again from %s filter. Called %s times!", 'all_in_one_seo_pack' ), current_filter(), $aioseop_dup_counter ) . " -->\n"; return; } if ( is_home() && !is_front_page() ) { $post = $this->get_blog_page(); } else { $post = $this->get_queried_object(); } $meta_string = null; $description = ''; // logging - rewrite handler check for output buffering $this->check_rewrite_handler(); echo "\n<!-- All in One SEO Pack Pro $this->version by Michael Torbert of Semper Fi Web Design"; if ( $this->ob_start_detected ) echo "ob_start_detected "; echo "[$this->title_start,$this->title_end] "; echo "-->\n"; echo "<!-- " . __( "Debug String", 'all_in_one_seo_pack' ) . ": " . $aioseop_update_checker->get_verification_code() . " -->\n"; $blog_page = $this->get_blog_page( $post ); $save_posts = $posts; if ( function_exists( 'woocommerce_get_page_id' ) && is_post_type_archive( 'product' ) && ( $post_id = woocommerce_get_page_id( 'shop' ) ) && ( $post = get_post( $post_id ) ) ) { global $posts; $opts = $this->meta_opts = $this->get_current_options( Array(), 'aiosp', null, $post ); $posts = Array(); $posts[] = $post; } $posts = $save_posts; $description = apply_filters( 'aioseop_description', $this->get_main_description( $post ) ); // get the description // handle the description format if ( isset($description) && ( $this->strlen($description) > $this->minimum_description_length ) && !( is_front_page() && is_paged() ) ) { $description = $this->trim_description( $description ); if ( !isset( $meta_string) ) $meta_string = ''; // description format $description = apply_filters( 'aioseop_description_full', $this->apply_description_format( $description, $post ) ); $desc_attr = ''; if ( !empty( $aioseop_options['aiosp_schema_markup'] ) ) $desc_attr = 'itemprop="description"'; $desc_attr = apply_filters( 'aioseop_description_attributes', $desc_attr ); $meta_string .= sprintf( "<meta name=\"description\" %s content=\"%s\" />\n", $desc_attr, $description ); } // get the keywords $togglekeywords = 0; if ( isset( $aioseop_options['aiosp_togglekeywords'] ) ) $togglekeywords = $aioseop_options['aiosp_togglekeywords']; if ( $togglekeywords == 0 && !( is_front_page() && is_paged() ) ) { $keywords = $this->get_main_keywords(); $keywords = $this->apply_cf_fields( $keywords ); $keywords = apply_filters( 'aioseop_keywords', $keywords ); if ( isset( $keywords ) && !empty( $keywords ) ) { if ( isset( $meta_string ) ) $meta_string .= "\n"; $keywords = wp_filter_nohtml_kses( str_replace( '"', '', $keywords ) ); $key_attr = ''; if ( !empty( $aioseop_options['aiosp_schema_markup'] ) ) $key_attr = 'itemprop="keywords"'; $key_attr = apply_filters( 'aioseop_keywords_attributes', $key_attr ); $meta_string .= sprintf( "<meta name=\"keywords\" %s content=\"%s\" />\n", $key_attr, $keywords ); } } // handle noindex, nofollow - robots meta $robots_meta = apply_filters( 'aioseop_robots_meta', $this->get_robots_meta() ); if ( !empty( $robots_meta ) ) $meta_string .= '<meta name="robots" content="' . esc_attr( $robots_meta ) . '" />' . "\n"; // handle site verification if ( is_front_page() ) { foreach( Array( 'google' => 'google-site-verification', 'bing' => 'msvalidate.01', 'pinterest' => 'p:domain_verify' ) as $k => $v ) if ( !empty( $aioseop_options["aiosp_{$k}_verify"] ) ) $meta_string .= '<meta name="' . $v . '" content="' . trim( strip_tags( $aioseop_options["aiosp_{$k}_verify"] ) ) . '" />' . "\n"; // sitelinks search if ( !empty( $aioseop_options["aiosp_google_sitelinks_search"] ) || !empty( $aioseop_options["aiosp_google_set_site_name"] ) ) $meta_string .= $this->sitelinks_search_box() . "\n"; } // handle extra meta fields foreach( Array( 'page_meta', 'post_meta', 'home_meta', 'front_meta' ) as $meta ) { if ( !empty( $aioseop_options["aiosp_{$meta}_tags" ] ) ) $$meta = html_entity_decode( stripslashes( $aioseop_options["aiosp_{$meta}_tags" ] ), ENT_QUOTES ); else $$meta = ''; } if ( is_page() && isset( $page_meta ) && !empty( $page_meta ) && ( !is_front_page() || empty( $front_meta ) ) ) { if ( isset( $meta_string ) ) $meta_string .= "\n"; $meta_string .= $page_meta; } if ( is_single() && isset( $post_meta ) && !empty( $post_meta ) ) { if ( isset( $meta_string ) ) $meta_string .= "\n"; $meta_string .= $post_meta; } // handle authorship $authorship = $this->get_google_authorship( $post ); $publisher = apply_filters( 'aioseop_google_publisher', $authorship["publisher"] ); if ( !empty( $publisher ) ) $meta_string = '<link rel="publisher" href="' . esc_url( $publisher ) . '" />' . "\n" . $meta_string; $author = apply_filters( 'aioseop_google_author', $authorship["author"] ); if ( !empty( $author ) ) $meta_string = '<link rel="author" href="' . esc_url( $author ) . '" />' . "\n" . $meta_string; if ( is_front_page() && !empty( $front_meta ) ) { if ( isset( $meta_string ) ) $meta_string .= "\n"; $meta_string .= $front_meta; } else { if ( is_home() && !empty( $home_meta ) ) { if ( isset( $meta_string ) ) $meta_string .= "\n"; $meta_string .= $home_meta; } } $prev_next = $this->get_prev_next_links( $post ); $prev = apply_filters( 'aioseop_prev_link', $prev_next['prev'] ); $next = apply_filters( 'aioseop_next_link', $prev_next['next'] ); if ( !empty( $prev ) ) $meta_string .= "<link rel='prev' href='" . esc_url( $prev ) . "' />\n"; if ( !empty( $next ) ) $meta_string .= "<link rel='next' href='" . esc_url( $next ) . "' />\n"; if ( $meta_string != null ) echo "$meta_string\n"; // handle canonical links $show_page = true; if ( !empty( $aioseop_options["aiosp_no_paged_canonical_links"] ) ) $show_page = false; if ( $aioseop_options['aiosp_can'] ) { $url = ''; if ( !empty( $aioseop_options['aiosp_customize_canonical_links'] ) && !empty( $opts['aiosp_custom_link'] ) ) $url = $opts['aiosp_custom_link']; if ( empty( $url ) ) $url = $this->aiosp_mrt_get_url( $wp_query, $show_page ); $url = apply_filters( 'aioseop_canonical_url', $url ); if ( !empty( $url ) ) echo '<link rel="canonical" href="'. esc_url( $url ) . '" />'."\n"; } do_action( 'aioseop_modules_wp_head' ); echo "<!-- /all in one seo pack pro -->\n"; } function override_options( $options, $location, $settings ) { if ( class_exists( 'DOMDocument' ) ) { $options['aiosp_google_connect'] = $settings['aiosp_google_connect']['default']; } return $options; } function oauth_init() { if ( !is_user_logged_in() || !current_user_can( 'manage_options' ) ) return false; $this->token = "anonymous"; $this->secret = "anonymous"; $preload = $this->get_class_option(); $manual_ua = ''; if ( !empty( $_POST ) ) { if ( !empty( $_POST["{$this->prefix}google_connect"] ) ) { $manual_ua = 1; } } elseif ( !empty( $preload["{$this->prefix}google_connect"] ) ) { $manual_ua = 1; } if ( !empty( $manual_ua ) ) { foreach ( Array( "token", "secret", "access_token", "ga_token", "account_cache" ) as $v ) { if ( !empty( $preload["{$this->prefix}{$v}"]) ) { unset( $preload["{$this->prefix}{$v}"] ); unset( $this->$v ); } } $this->update_class_option( $preload ); $this->update_options( ); // return; } foreach ( Array( "token", "secret", "access_token", "ga_token", "account_cache" ) as $v ) { if ( !empty( $preload["{$this->prefix}{$v}"]) ) { $this->$v = $preload["{$this->prefix}{$v}"]; } } $callback_url = NULL; if ( !empty( $_REQUEST['oauth_verifier'] ) ) { $this->verifier = $_REQUEST['oauth_verifier']; if ( !empty( $_REQUEST['oauth_token'] ) ) { if ( isset( $this->token ) && $this->token == $_REQUEST['oauth_token'] ) { $this->access_token = $this->oauth_get_token( $this->verifier ); if ( is_array( $this->access_token ) && !empty( $this->access_token['oauth_token'] ) ) { unset( $this->token ); unset( $this->secret ); $this->ga_token = $this->access_token['oauth_token']; foreach ( Array( "token", "secret", "access_token", "ga_token" ) as $v ) { if ( !empty( $this->$v) ) $preload["{$this->prefix}{$v}"] = $this->$v; } $this->update_class_option( $preload ); } } wp_redirect( menu_page_url( plugin_basename( $this->file ), false ) ); exit; } } if ( !empty( $this->ga_token ) ) { if ( !empty( $this->account_cache ) ) { $ua = $this->account_cache['ua']; $profiles = $this->account_cache['profiles']; } else { $this->token = $this->access_token['oauth_token']; $this->secret = $this->access_token['oauth_token_secret']; $data = $this->oauth_get_data('https://www.googleapis.com/analytics/v2.4/management/accounts/~all/webproperties/~all/profiles' ); $http_code = wp_remote_retrieve_response_code( $data ); if( $http_code == 200 ) { $response = wp_remote_retrieve_body( $data ); $xml = $this->xml_string_to_array( $response ); $ua = Array(); $profiles = Array(); if ( !empty( $xml["entry"] ) ) { $rec = Array(); $results = Array(); if ( !empty( $xml["entry"][0] ) ) $results = $xml["entry"]; else $results[] = $xml["entry"]; foreach( $results as $r ) { foreach( $r as $k => $v ) switch( $k ) { case 'id': $rec['id'] = $v; break; case 'title': $rec['title'] = $v['@content']; break; case 'dxp:property': $attr = Array(); foreach ( $v as $a => $f ) if ( is_array($f) && !empty($f['@attributes'] ) ) $rec[$f['@attributes']['name']] = $f['@attributes']['value']; break; } $ua[$rec['title']] = Array( $rec['ga:webPropertyId'] => $rec['ga:webPropertyId'] ); $profiles[ $rec['ga:webPropertyId'] ] = $rec['ga:profileId']; } } $this->account_cache = Array(); $this->account_cache['ua'] = $ua; $this->account_cache['profiles'] = $profiles; $preload["{$this->prefix}account_cache"] = $this->account_cache; } else { unset( $this->token ); unset( $this->secret ); unset( $this->ga_token ); unset( $preload["{$this->prefix}ga_token"] ); // error condition here -- pdb $response = wp_remote_retrieve_body( $data ); $xml = $this->xml_string_to_array( $response ); if ( !empty( $xml ) && !empty( $xml["error"] ) ) { $error = 'Error: '; if ( !empty( $xml["error"]["internalReason"] ) ) { $error .= $xml["error"]["internalReason"]; } else { foreach( $xml["error"] as $k => $v ) $error .= "$k: $v\n"; } $this->output_error( $error ); } } } } if ( !empty( $this->ga_token ) ) { $this->default_options["google_analytics_id"]['type'] = 'select'; $this->default_options["google_analytics_id"]['initial_options'] = $ua; $this->default_options["google_connect"]["type"] = 'html'; $this->default_options["google_connect"]["nolabel"] = 1; $this->default_options["google_connect"]["save"] = true; $this->default_options["google_connect"]["name"] = __( 'Disconnect From Google Analytics', 'all_in_one_seo_pack' ); $this->default_options["google_connect"]["default"] = "<input name='aiosp_google_connect' type=submit class='button-primary' value='" . __( 'Remove Stored Credentials', 'all_in_one_seo_pack' ) . "'>"; add_filter( $this->prefix . 'override_options', Array( $this, 'override_options' ), 10, 3 ); } else { $this->default_options["google_connect"]["type"] = 'html'; $this->default_options["google_connect"]["nolabel"] = 1; $this->default_options["google_connect"]["save"] = false; $url = $this->oauth_connect(); $this->default_options["google_connect"]["default"] = "<a href='{$url}' class='button-primary'>" . __( 'Connect With Google Analytics', 'all_in_one_seo_pack' ) . "</a>"; foreach ( Array( "token", "secret", "access_token", "ga_token", "account_cache" ) as $v ) { if ( !empty( $this->$v) ) $preload["{$this->prefix}{$v}"] = $this->$v; } } $this->update_class_option( $preload ); $this->update_options( ); // $url = $this->report_query(); if ( !empty( $this->account_cache ) && !empty( $this->options["{$this->prefix}google_analytics_id"] ) && !empty( $this->account_cache["profiles"][ $this->options["{$this->prefix}google_analytics_id"] ] ) ) { $this->profile_id = $this->account_cache["profiles"][ $this->options["{$this->prefix}google_analytics_id"] ]; } } function oauth_get_data( $oauth_url, $args = null ) { if ( !class_exists( 'OAuthConsumer' ) ) require_once( 'OAuth.php' ); if ( $args === null ) $args = Array( 'scope' => 'https://www.googleapis.com/auth/analytics.readonly', 'xoauth_displayname' => AIOSEOP_PLUGIN_NAME . ' ' . __('Google Analytics', 'all_in_one_seo_pack' ) ); $req_token = new OAuthConsumer( $this->token, $this->secret ); $req = $this->oauth_get_creds( $oauth_url, $req_token, $args ); return wp_remote_get( $req->to_url() ); } function oauth_get_creds( $oauth_url, $req_token = NULL, $args = Array(), $callback = null ) { if ( !class_exists( 'OAuthConsumer' ) ) require_once( 'OAuth.php' ); if ( !empty( $callback ) ) $args['oauth_callback'] = $callback; if ( empty( $this->sig_method ) ) $this->sig_method = new OAuthSignatureMethod_HMAC_SHA1(); if ( empty( $this->consumer ) ) $this->consumer = new OAuthCOnsumer( 'anonymous', 'anonymous' ); $req_req = OAuthRequest::from_consumer_and_token( $this->consumer, $req_token, "GET", $oauth_url, $args ); $req_req->sign_request( $this->sig_method, $this->consumer, $req_token ); return $req_req; } function oauth_get_token( $oauth_verifier ) { if ( !class_exists( 'OAuthConsumer' ) ) require_once( 'OAuth.php' ); $args = Array( 'scope' => 'https://www.google.com/analytics/feeds/', 'xoauth_displayname' => AIOSEOP_PLUGIN_NAME . ' ' . __('Google Analytics', 'all_in_one_seo_pack' ) ); $args['oauth_verifier'] = $oauth_verifier; $oauth_access_token = "https://www.google.com/accounts/OAuthGetAccessToken"; $reqData = $this->oauth_get_data( $oauth_access_token, $args ); $reqOAuthData = OAuthUtil::parse_parameters( wp_remote_retrieve_body( $reqData ) ); return $reqOAuthData; } function oauth_connect( $count = 0 ) { global $aiosp_activation; if ( !class_exists( 'OAuthConsumer' ) ) require_once( 'OAuth.php' ); $url = ''; $callback_url = NULL; $consumer_key = "anonymous"; $consumer_secret = "anonymous"; $oauth_request_token = "https://www.google.com/accounts/OAuthGetRequestToken"; $oauth_authorize = "https://www.google.com/accounts/OAuthAuthorizeToken"; $oauth_access_token = "https://www.google.com/accounts/OAuthGetAccessToken"; if ( $aiosp_activation ) { $oauth_current = false; } else { $oauth_current = get_transient( "aioseop_oauth_current" ); } if ( !empty( $this->token ) && ( $this->token != 'anonymous' ) && $oauth_current ) { return $oauth_authorize . '?oauth_token=' . $this->token; } else { set_transient( "aioseop_oauth_current", 1, 3600 ); unset( $this->token ); unset( $this->secret ); } $args = array( 'scope' => 'https://www.google.com/analytics/feeds/', 'xoauth_displayname' => AIOSEOP_PLUGIN_NAME . ' ' . __('Google Analytics', 'all_in_one_seo_pack') ); $req_req = $this->oauth_get_creds( $oauth_request_token, NULL, $args, admin_url( "admin.php?page=all-in-one-seo-pack-pro/aioseop_class.php" ) ); $reqData = wp_remote_get( $req_req->to_url() ); $reqOAuthData = OAuthUtil::parse_parameters( wp_remote_retrieve_body( $reqData ) ); if ( !empty( $reqOAuthData['oauth_token'] ) ) $this->token = $reqOAuthData['oauth_token']; if ( !empty( $reqOAuthData['oauth_token_secret'] ) ) $this->secret = $reqOAuthData['oauth_token_secret']; if ( !empty( $this->token ) && ( $this->token != 'anonymous' ) && ( $oauth_current ) ) { $url = $oauth_authorize . "?oauth_token={$this->token}"; } else { if ( !$count ) { return $this->oauth_connect( 1 ); } } return $url; } function get_analytics_domain() { global $aioseop_options; if ( !empty( $aioseop_options['aiosp_ga_domain'] ) ) return $this->sanitize_domain( $aioseop_options['aiosp_ga_domain'] ); return ''; } function universal_analytics() { global $aioseop_options; $analytics = ''; if ( !empty( $aioseop_options['aiosp_ga_use_universal_analytics'] ) ) { $allow_linker = $cookie_domain = $domain = $addl_domains = $domain_list = ''; if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) ) $cookie_domain = $this->get_analytics_domain(); if ( !empty( $cookie_domain ) ) { $cookie_domain = esc_js( $cookie_domain ); $cookie_domain = "'cookieDomain': '{$cookie_domain}'"; } if ( empty( $cookie_domain ) ) { $domain = ", 'auto'"; } if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_multi_domain'] ) ) { $allow_linker = "'allowLinker': true"; if ( !empty( $aioseop_options['aiosp_ga_addl_domains'] ) ) { $addl_domains = trim( $aioseop_options['aiosp_ga_addl_domains'] ); $addl_domains = preg_split('/[\s,]+/', $addl_domains); if ( !empty( $addl_domains ) ) { foreach( $addl_domains as $d ) { $d = $this->sanitize_domain( $d ); if ( !empty( $d ) ) { if ( !empty( $domain_list ) ) $domain_list .= ", "; $domain_list .= "'" . $d . "'"; } } } } } $extra_options = ''; if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_display_advertising'] ) ) { $extra_options .= "ga('require', 'displayfeatures');"; } if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_enhanced_ecommerce'] ) ) { if ( !empty( $extra_options ) ) $extra_options .= "\n\t\t\t"; $extra_options .= "ga('require', 'ec');"; } if ( !empty( $domain_list ) ) { if ( !empty( $extra_options ) ) $extra_options .= "\n\t\t\t"; $extra_options .= "ga('require', 'linker');\n\t\t\tga('linker:autoLink', [{$domain_list}] );"; } if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_link_attribution'] ) ) { if ( !empty( $extra_options ) ) $extra_options .= "\n\t\t\t"; $extra_options .= "ga('require', 'linkid', 'linkid.js');"; } if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_anonymize_ip'] ) ) { if ( !empty( $extra_options ) ) $extra_options .= "\n\t\t\t"; $extra_options .= "ga('set', 'anonymizeIp', true);"; } $js_options = Array(); foreach( Array( 'cookie_domain', 'allow_linker' ) as $opts ) { if ( !empty( $$opts ) ) $js_options[] = $$opts; } if ( !empty( $js_options ) ) { $js_options = join( ',', $js_options ); $js_options = ', { ' . $js_options . ' } '; } else $js_options = ''; $analytics_id = esc_js( $aioseop_options["aiosp_google_analytics_id"] ); $analytics =<<<EOF <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '{$analytics_id}'{$domain}{$js_options}); {$extra_options} ga('send', 'pageview'); </script> EOF; } return $analytics; } function aiosp_google_analytics() { global $aioseop_options; $analytics = ''; if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_exclude_users'] ) ) { if ( is_user_logged_in() ) { global $current_user; if ( empty( $current_user ) ) get_currentuserinfo(); if ( !empty( $current_user ) ) { $intersect = array_intersect( $aioseop_options['aiosp_ga_exclude_users'], $current_user->roles ); if ( !empty( $intersect ) ) return; } } } if ( !empty( $aioseop_options['aiosp_google_analytics_id'] ) ) { ob_start(); $analytics = $this->universal_analytics(); echo $analytics; if ( empty( $analytics ) ) { ?> <script type="text/javascript"> var _gaq = _gaq || []; <?php if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_link_attribution'] ) ) { ?> var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; _gaq.push(['_require', 'inpage_linkid', pluginUrl]); <?php } ?> _gaq.push(['_setAccount', '<?php echo $aioseop_options['aiosp_google_analytics_id']; ?>']); <?php if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_anonymize_ip'] ) ) { ?> _gaq.push(['_gat._anonymizeIp']); <?php } ?> <?php if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_multi_domain'] ) ) { ?> _gaq.push(['_setAllowLinker', true]); <?php } ?> <?php if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_domain'] ) ) { $domain = $this->get_analytics_domain(); ?> _gaq.push(['_setDomainName', '<?php echo $domain; ?>']); <?php } ?> _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; <?php if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && !empty( $aioseop_options['aiosp_ga_display_advertising'] ) ) { ?> ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; <?php } else { ?> ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; <?php } ?> var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <?php } if ( !empty( $aioseop_options['aiosp_ga_advanced_options'] ) && $aioseop_options['aiosp_ga_track_outbound_links'] ) { ?> <script type="text/javascript"> function recordOutboundLink(link, category, action) { <?php if ( !empty( $aioseop_options['aiosp_ga_use_universal_analytics'] ) ) { ?> ga('send', 'event', category, action); <?php } if ( empty( $aioseop_options['aiosp_ga_use_universal_analytics'] ) ) { ?> _gat._getTrackerByName()._trackEvent(category, action); <?php } ?> if ( link.target == '_blank' ) return true; setTimeout('document.location = "' + link.href + '"', 100); return false; } /* use regular Javascript for this */ function getAttr(ele, attr) { var result = (ele.getAttribute && ele.getAttribute(attr)) || null; if( !result ) { var attrs = ele.attributes; var length = attrs.length; for(var i = 0; i < length; i++) if(attr[i].nodeName === attr) result = attr[i].nodeValue; } return result; } function aiosp_addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } function aiosp_addEvent(element, evnt, funct){ if (element.attachEvent) return element.attachEvent('on'+evnt, funct); else return element.addEventListener(evnt, funct, false); } aiosp_addLoadEvent(function () { var links = document.getElementsByTagName('a'); for (var x=0; x < links.length; x++) { if (typeof links[x] == 'undefined') continue; aiosp_addEvent( links[x], 'onclick', function () { var mydomain = new RegExp(document.domain, 'i'); href = getAttr(this, 'href'); if (href && href.toLowerCase().indexOf('http') === 0 && !mydomain.test(href)) { recordOutboundLink(this, 'Outbound Links', href); } }); } }); </script> <?php } $analytics = ob_get_clean(); } echo apply_filters( 'aiosp_google_analytics', $analytics ); } function sitelinks_search_box() { global $aioseop_options; $home_url = esc_url( get_home_url() ); $name_block = $search_block = ''; if ( !empty( $aioseop_options["aiosp_google_set_site_name"] ) ) { if ( !empty( $aioseop_options["aiosp_google_specify_site_name"] ) ) { $blog_name = $aioseop_options["aiosp_google_specify_site_name"]; } else { $blog_name = get_bloginfo( 'name' ); } $blog_name = esc_attr( $blog_name ); $name_block=<<<EOF "name": "{$blog_name}", EOF; } if ( !empty( $aioseop_options["aiosp_google_sitelinks_search"] ) ) { $search_block=<<<EOF "potentialAction": { "@type": "SearchAction", "target": "{$home_url}/?s={search_term}", "query-input": "required name=search_term" } EOF; } $search_box=<<<EOF <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "{$home_url}/", EOF; if ( !empty( $name_block ) ) $search_box .= $name_block; if ( !empty( $search_block ) ) $search_box .= $search_block; $search_box.=<<<EOF } </script> EOF; return apply_filters( 'aiosp_sitelinks_search_box', $search_box ); } // Thank you, Yoast de Valk, for much of this code. function aiosp_mrt_get_url( $query, $show_page = true ) { if ( $query->is_404 || $query->is_search ) return false; $link = ''; $haspost = count( $query->posts ) > 0; if ( get_query_var( 'm' ) ) { $m = preg_replace( '/[^0-9]/', '', get_query_var( 'm' ) ); switch ( $this->strlen( $m ) ) { case 4: $link = get_year_link( $m ); break; case 6: $link = get_month_link( $this->substr( $m, 0, 4), $this->substr($m, 4, 2 ) ); break; case 8: $link = get_day_link( $this->substr( $m, 0, 4 ), $this->substr( $m, 4, 2 ), $this->substr( $m, 6, 2 ) ); break; default: return false; } } elseif ( ( $query->is_home && (get_option( 'show_on_front' ) == 'page' ) && ( $pageid = get_option( 'page_for_posts' ) ) ) ) { $link = get_permalink( $pageid ); } elseif ( is_front_page() || ( $query->is_home && ( get_option( 'show_on_front' ) != 'page' || !get_option( 'page_for_posts' ) ) ) ) { if ( function_exists( 'icl_get_home_url' ) ) { $link = icl_get_home_url(); } else { $link = trailingslashit( home_url() ); } } elseif ( ( $query->is_single || $query->is_page ) && $haspost ) { $post = $query->posts[0]; $link = get_permalink( $post->ID ); } elseif ( $query->is_author && $haspost ) { $author = get_userdata( get_query_var( 'author' ) ); if ($author === false) return false; $link = get_author_posts_url( $author->ID, $author->user_nicename ); } elseif ( $query->is_category && $haspost ) { $link = get_category_link( get_query_var( 'cat' ) ); } elseif ( $query->is_tag && $haspost ) { $tag = get_term_by( 'slug', get_query_var( 'tag' ), 'post_tag' ); if ( !empty( $tag->term_id ) ) $link = get_tag_link( $tag->term_id ); } elseif ( $query->is_day && $haspost ) { $link = get_day_link( get_query_var( 'year' ), get_query_var( 'monthnum' ), get_query_var( 'day' ) ); } elseif ( $query->is_month && $haspost ) { $link = get_month_link( get_query_var( 'year' ), get_query_var( 'monthnum' ) ); } elseif ( $query->is_year && $haspost ) { $link = get_year_link( get_query_var( 'year' ) ); } elseif ( $query->is_tax && $haspost ) { $taxonomy = get_query_var( 'taxonomy' ); $term = get_query_var( 'term' ); if ( !empty( $term ) ) $link = get_term_link( $term, $taxonomy ); } elseif ( $query->is_archive && function_exists( 'get_post_type_archive_link' ) && ( $post_type = get_query_var( 'post_type' ) ) ) { if ( is_array( $post_type ) ) $post_type = reset( $post_type ); $link = get_post_type_archive_link( $post_type ); } else { return false; } if ( empty( $link ) || !is_string( $link ) ) return false; if ( apply_filters( 'aioseop_canonical_url_pagination', $show_page ) ) $link = $this->get_paged( $link ); if ( !empty( $link ) ) { global $aioseop_options; if ( !empty( $aioseop_options['aiosp_can_set_protocol'] ) && ( $aioseop_options['aiosp_can_set_protocol'] != 'auto' ) ) { if ( $aioseop_options['aiosp_can_set_protocol'] == 'http' ) { $link = preg_replace("/^https:/i", "http:", $link ); } elseif ( $aioseop_options['aiosp_can_set_protocol'] == 'https' ) { $link = preg_replace("/^http:/i", "https:", $link ); } } } return $link; } function get_page_number() { $page = get_query_var( 'page' ); if ( empty( $page ) ) $page = get_query_var( 'paged' ); return $page; } function get_paged( $link ) { global $wp_rewrite; $page = $this->get_page_number(); $page_name = 'page'; if ( !empty( $wp_rewrite ) && !empty( $wp_rewrite->pagination_base ) ) $page_name = $wp_rewrite->pagination_base; if ( !empty( $page ) && $page > 1 ) { if ( get_query_var( 'page' ) == $page ) $link = trailingslashit( $link ) . "$page"; else $link = trailingslashit( $link ) . trailingslashit( $page_name ) . $page; $link = user_trailingslashit( $link, 'paged' ); } return $link; } function is_singular( $post_types = Array(), $post = null ) { if ( !empty( $post_types ) && is_object( $post ) ) return in_array( $post->post_type, (array)$post_types ); else return is_singular( $post_types ); } function show_page_description() { global $aioseop_options; if ( !empty( $aioseop_options['aiosp_hide_paginated_descriptions'] ) ) { $page = $this->get_page_number(); if ( !empty( $page ) && ( $page > 1 ) ) return false; } return true; } function get_post_description( $post ) { global $aioseop_options; $description = ''; if ( !$this->show_page_description() ) { return ''; } $description = trim( stripslashes( $this->internationalize( get_post_meta( $post->ID, "_aioseop_description", true ) ) ) ); if ( !empty( $post ) && post_password_required( $post ) ) { return $description; } if ( !$description ) { if ( empty( $aioseop_options["aiosp_skip_excerpt"] ) ) $description = $this->trim_excerpt_without_filters_full_length( $this->internationalize( $post->post_excerpt ) ); if ( !$description && $aioseop_options["aiosp_generate_descriptions"] ) { $content = $post->post_content; if ( !empty( $aioseop_options["aiosp_run_shortcodes"] ) ) $content = do_shortcode( $content ); $content = wp_strip_all_tags( $content ); $description = $this->trim_excerpt_without_filters( $this->internationalize( $content ) ); } } // "internal whitespace trim" $description = preg_replace( "/\s\s+/u", " ", $description ); return $description; } function get_blog_page( $p = null ) { static $blog_page = ''; static $page_for_posts = ''; if ( $p === null ) { global $post; } else { $post = $p; } if ( $blog_page === '' ) { if ( $page_for_posts === '' ) $page_for_posts = get_option( 'page_for_posts' ); if ( $page_for_posts && is_home() && ( !is_object( $post ) || ( $page_for_posts != $post->ID ) ) ) $blog_page = get_post( $page_for_posts ); } return $blog_page; } function get_aioseop_description( $post = null ) { global $aioseop_options; if ( $post === null ) $post = $GLOBALS["post"]; $blog_page = $this->get_blog_page(); $description = ''; if ( is_front_page() && empty( $aioseop_options['aiosp_use_static_home_info'] ) ) $description = trim( stripslashes( $this->internationalize( $aioseop_options['aiosp_home_description'] ) ) ); elseif ( !empty( $blog_page ) ) $description = $this->get_post_description( $blog_page ); if ( empty( $description ) && is_object( $post ) && !is_archive() && empty( $blog_page ) ) $description = $this->get_post_description( $post ); $description = $this->apply_cf_fields( $description ); return $description; } function replace_title( $content, $title ) { $title = trim( strip_tags( $title ) ); $title_tag_start = "<title"; $title_tag_end = "</title"; $title = stripslashes( trim( $title ) ); $start = $this->strpos( $content, $title_tag_start ); $end = $this->strpos( $content, $title_tag_end ); $this->title_start = $start; $this->title_end = $end; $this->orig_title = $title; return preg_replace( '/<title([^>]*?)\s*>([^<]*?)<\/title\s*>/is', '<title\\1>' . preg_replace('/(\$|\\\\)(?=\d)/', '\\\\\1', strip_tags( $title ) ) . '</title>', $content, 1 ); } function internationalize( $in ) { if ( function_exists( 'langswitch_filter_langs_with_message' ) ) $in = langswitch_filter_langs_with_message( $in ); if ( function_exists( 'polyglot_filter' ) ) $in = polyglot_filter( $in ); if ( function_exists( 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage' ) ) { $in = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage( $in ); } elseif ( function_exists( 'ppqtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage' ) ) { $in = ppqtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage( $in ); } elseif ( function_exists( 'qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage' ) ) { $in = qtranxf_useCurrentLanguageIfNotFoundUseDefaultLanguage( $in ); } return apply_filters( 'localization', $in ); } /** @return The original title as delivered by WP (well, in most cases) */ function get_original_title( $sep = '|', $echo = false, $seplocation = '' ) { global $aioseop_options; if ( !empty( $aioseop_options['aiosp_use_original_title'] ) ) { $has_filter = has_filter( 'wp_title', Array( $this, 'wp_title' ) ); if ( $has_filter !== false ) remove_filter( 'wp_title', Array( $this, 'wp_title' ), $has_filter ); if ( current_theme_supports( 'title-tag' ) ) { $sep = '|'; $echo = false; $seplocation = 'right'; } $title = wp_title( $sep, $echo, $seplocation ); if ( $has_filter !== false ) add_filter( 'wp_title', Array( $this, 'wp_title' ), $has_filter ); if ( $title && ( $title = trim( $title ) ) ) return trim( $title ); } // the_search_query() is not suitable, it cannot just return global $s; $title = null; if ( is_home() ) { $title = get_option( 'blogname' ); } else if ( is_single() ) { $title = $this->internationalize( single_post_title( '', false ) ); } else if ( is_search() && isset($s) && !empty($s) ) { $search = esc_attr( stripslashes($s) ); if ( !empty( $aioseop_options['aiosp_cap_titles'] ) ) $search = $this->capitalize( $search ); $title = $search; } else if ( ( is_tax() || is_category() ) && !is_feed() ) { $category_name = $this->ucwords($this->internationalize( single_cat_title( '', false ) ) ); $title = $category_name; } else if ( is_page() ) { $title = $this->internationalize( single_post_title( '', false ) ); } else if ( is_tag() ) { global $utw; if ( $utw ) { $tags = $utw->GetCurrentTagSet(); $tag = $tags[0]->tag; $tag = str_replace('-', ' ', $tag); } else { // wordpress > 2.3 $tag = $this->internationalize( single_term_title( '', false ) ); } if ( $tag ) $title = $tag; } else if ( is_author() ) { $author = get_userdata( get_query_var( 'author' ) ); if ( $author === false ) { global $wp_query; $author = $wp_query->get_queried_object(); } if ($author !== false) $title = $author->display_name; } else if ( is_day() ) { $title = get_the_date(); } else if ( is_month() ) { $title = get_the_date( 'F, Y' ); } else if ( is_year() ) { $title = get_the_date( 'Y' ); } else if ( is_archive() ) { $title = $this->internationalize( post_type_archive_title( '', false) ); } else if ( is_404() ) { $title_format = $aioseop_options['aiosp_404_title_format']; $new_title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name' ) ), $title_format ); if ( strpos( $new_title, '%blog_description%' ) !== false ) $new_title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description' ) ), $new_title ); if ( strpos( $new_title, '%request_url%' ) !== false ) $new_title = str_replace( '%request_url%', $_SERVER['REQUEST_URI'], $new_title); if ( strpos( $new_title, '%request_words%' ) !== false ) $new_title = str_replace( '%request_words%', $this->request_as_words( $_SERVER['REQUEST_URI'] ), $new_title ); $title = $new_title; } return trim( $title ); } function paged_title( $title ) { // the page number if paged global $paged; global $aioseop_options; // simple tagging support global $STagging; $page = get_query_var( 'page' ); if ( $paged > $page ) $page = $paged; if ( is_paged() || ( isset($STagging) && $STagging->is_tag_view() && $paged ) || ( $page > 1 ) ) { $part = $this->internationalize( $aioseop_options['aiosp_paged_format'] ); if ( isset( $part ) || !empty( $part ) ) { $part = " " . trim( $part ); $part = str_replace( '%page%', $page, $part ); $this->log( "paged_title() [$title] [$part]" ); $title .= $part; } } return $title; } function get_tax_title_format( $tax = '' ) { global $aioseop_options; $title_format = '%taxonomy_title% | %blog_title%'; if ( is_category() ) { $title_format = $aioseop_options['aiosp_category_title_format']; } else { $taxes = $aioseop_options['aiosp_taxactive']; if ( empty( $tax ) ) $tax = get_query_var( 'taxonomy' ); if ( !empty( $aioseop_options["aiosp_{$tax}_tax_title_format"] ) ) $title_format = $aioseop_options["aiosp_{$tax}_tax_title_format"]; } if ( empty( $title_format ) ) $title_format = '%category_title% | %blog_title%'; return $title_format; } function apply_tax_title_format( $category_name, $category_description, $tax = '' ) { if ( empty( $tax ) ) $tax = get_query_var( 'taxonomy' ); $title_format = $this->get_tax_title_format( $tax ); $title = str_replace( '%taxonomy_title%', $category_name, $title_format ); if ( strpos( $title, '%taxonomy_description%' ) !== false ) $title = str_replace( '%taxonomy_description%', $category_description, $title ); if ( strpos( $title, '%category_title%' ) !== false ) $title = str_replace( '%category_title%', $category_name, $title ); if ( strpos( $title, '%category_description%' ) !== false ) $title = str_replace( '%category_description%', $category_description, $title ); if ( strpos( $title, '%blog_title%' ) !== false ) $title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name' ) ), $title ); if ( strpos( $title, '%blog_description%' ) !== false ) $title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description' ) ), $title ); $title = wp_strip_all_tags( $title ); return $this->paged_title( $title ); } function get_tax_name( $tax ) { $opts = $this->meta_opts; if ( !empty( $opts ) ) $name = $opts['aiosp_title']; if ( empty( $name ) ) $name = single_term_title( '', false ); if ( ( $tax == 'category' ) && ( !empty( $aioseop_options['aiosp_cap_cats'] ) ) ) $name = $this->ucwords( $name ); return $this->internationalize( $name ); } function get_tax_desc( $tax ) { $opts = $this->meta_opts; if ( !empty( $opts ) ) $desc = $opts['aiosp_description']; if ( empty( $desc ) ) $desc = term_description( '', $tax ); return $this->internationalize( $desc ); } function get_tax_title( $tax = '' ) { if ( empty( $this->meta_opts ) ) $this->meta_opts = $this->get_current_options( Array(), 'aiosp' ); if ( empty( $tax ) ) if ( is_category() ) $tax = 'category'; else $tax = get_query_var( 'taxonomy' ); $name = $this->get_tax_name( $tax ); $desc = $this->get_tax_desc( $tax ); return $this->apply_tax_title_format( $name, $desc, $tax ); } function get_post_title_format( $title_type = 'post', $p = null ) { global $aioseop_options; if ( ( $title_type != 'post' ) && ( $title_type != 'archive' ) ) return false; $title_format = "%{$title_type}_title% | %blog_title%"; if ( isset( $aioseop_options["aiosp_{$title_type}_title_format"] ) ) $title_format = $aioseop_options["aiosp_{$title_type}_title_format"]; if( !empty( $aioseop_options['aiosp_enablecpost'] ) && !empty( $aioseop_options['aiosp_cpostactive'] ) ) { $wp_post_types = $aioseop_options['aiosp_cpostactive']; if ( !empty( $aioseop_options["aiosp_cposttitles"] ) ) { if ( ( ( $title_type == 'archive' ) && is_post_type_archive( $wp_post_types ) && $prefix = "aiosp_{$title_type}_" ) || ( ( $title_type == 'post' ) && $this->is_singular( $wp_post_types, $p ) && $prefix = "aiosp_" ) ) { $post_type = get_post_type( $p ); if ( !empty( $aioseop_options["{$prefix}{$post_type}_title_format"] ) ) { $title_format = $aioseop_options["{$prefix}{$post_type}_title_format"]; } } } } return $title_format; } function get_archive_title_format() { return $this->get_post_title_format( "archive" ); } function apply_archive_title_format( $title, $category = '' ) { $title_format = $this->get_archive_title_format(); $r_title = array( '%blog_title%', '%blog_description%', '%archive_title%' ); $d_title = array( $this->internationalize( get_bloginfo('name') ), $this->internationalize( get_bloginfo( 'description' ) ), post_type_archive_title( '', false ) ); $title = trim( str_replace( $r_title, $d_title, $title_format ) ); return $title; } function title_placeholder_helper( $title, $post, $type = 'post', $title_format = '', $category = '' ) { if ( !empty( $post ) ) $authordata = get_userdata( $post->post_author ); else $authordata = new WP_User(); $new_title = str_replace( "%blog_title%", $this->internationalize( get_bloginfo( 'name' ) ), $title_format ); if ( strpos( $new_title, "%blog_description%" ) !== false ) $new_title = str_replace( "%blog_description%", $this->internationalize( get_bloginfo( 'description' ) ), $new_title ); if ( strpos( $new_title, "%{$type}_title%" ) !== false ) $new_title = str_replace( "%{$type}_title%", $title, $new_title ); if ( $type == 'post' ) { if ( strpos( $new_title, "%category%" ) !== false ) $new_title = str_replace( "%category%", $category, $new_title ); if ( strpos( $new_title, "%category_title%" ) !== false ) $new_title = str_replace( "%category_title%", $category, $new_title ); if ( strpos( $new_title, "%tax_" ) && !empty( $post ) ) { $taxes = get_object_taxonomies( $post, 'objects' ); if ( !empty( $taxes ) ) foreach( $taxes as $t ) if ( strpos( $new_title, "%tax_{$t->name}%" ) ) { $terms = $this->get_all_terms( $post->ID, $t->name ); $term = ''; if ( count( $terms ) > 0 ) $term = $terms[0]; $new_title = str_replace( "%tax_{$t->name}%", $term, $new_title ); } } } if ( strpos( $new_title, "%{$type}_author_login%" ) !== false ) $new_title = str_replace( "%{$type}_author_login%", $authordata->user_login, $new_title ); if ( strpos( $new_title, "%{$type}_author_nicename%" ) !== false ) $new_title = str_replace( "%{$type}_author_nicename%", $authordata->user_nicename, $new_title ); if ( strpos( $new_title, "%{$type}_author_firstname%" ) !== false ) $new_title = str_replace( "%{$type}_author_firstname%", $this->ucwords($authordata->first_name ), $new_title ); if ( strpos( $new_title, "%{$type}_author_lastname%" ) !== false ) $new_title = str_replace( "%{$type}_author_lastname%", $this->ucwords($authordata->last_name ), $new_title ); $title = trim( $new_title ); return $title; } function apply_post_title_format( $title, $category = '', $p = null ) { if ( $p === null ) { global $post; } else { $post = $p; } $title_format = $this->get_post_title_format( 'post', $post ); return $this->title_placeholder_helper( $title, $post, 'post', $title_format, $category ); } function apply_page_title_format( $title, $p = null, $title_format = '' ) { global $aioseop_options; if ( $p === null ) { global $post; } else { $post = $p; } if ( empty( $title_format ) ) $title_format = $aioseop_options['aiosp_page_title_format']; return $this->title_placeholder_helper( $title, $post, 'page', $title_format ); } /*** Gets the title that will be used by AIOSEOP for title rewrites or returns false. ***/ function get_aioseop_title( $post ) { global $aioseop_options; // the_search_query() is not suitable, it cannot just return global $s, $STagging; $opts = $this->meta_opts; if ( is_front_page() ) { if ( !empty( $aioseop_options['aiosp_use_static_home_info'] ) ) { global $post; if ( get_option( 'show_on_front' ) == 'page' && is_page() && $post->ID == get_option( 'page_on_front' ) ) { $title = $this->internationalize( get_post_meta( $post->ID, "_aioseop_title", true ) ); if ( !$title ) $title = $this->internationalize( $post->post_title ); if ( !$title ) $title = $this->internationalize( $this->get_original_title( '', false ) ); if ( !empty( $aioseop_options['aiosp_home_page_title_format'] ) ) $title = $this->apply_page_title_format( $title, $post, $aioseop_options['aiosp_home_page_title_format'] ); $title = $this->paged_title( $title ); $title = apply_filters( 'aioseop_home_page_title', $title ); } } else { $title = $this->internationalize( $aioseop_options['aiosp_home_title'] ); if ( !empty( $aioseop_options['aiosp_home_page_title_format'] ) ) $title = $this->apply_page_title_format( $title, null, $aioseop_options['aiosp_home_page_title_format'] ); } if (empty( $title ) ) $title = $this->internationalize( get_option( 'blogname' ) ) . ' | ' . $this->internationalize( get_bloginfo( 'description' ) ); return $this->paged_title( $title ); } else if ( is_attachment() ) { if ( $post === null ) return false; $title = get_post_meta( $post->ID, "_aioseop_title", true ); if ( empty( $title ) ) $title = $post->post_title; if ( empty( $title ) ) $title = $this->get_original_title( '', false ); if ( empty( $title ) ) $title = get_the_title( $post->post_parent ); $title = apply_filters( 'aioseop_attachment_title', $this->internationalize( $this->apply_post_title_format( $title, '', $post ) ) ); return $title; } else if ( is_page() || $this->is_static_posts_page() || ( is_home() && !$this->is_static_posts_page() ) ) { if ( $post === null ) return false; if ( ( $this->is_static_front_page() ) && ( $home_title = $this->internationalize( $aioseop_options['aiosp_home_title'] ) ) ) { if ( !empty( $aioseop_options['aiosp_home_page_title_format'] ) ) $home_title = $this->apply_page_title_format( $home_title, $post, $aioseop_options['aiosp_home_page_title_format'] ); //home title filter return apply_filters( 'aioseop_home_page_title', $home_title ); } else { $page_for_posts = ''; if ( is_home() ) $page_for_posts = get_option( 'page_for_posts' ); if ( $page_for_posts ) { $title = $this->internationalize( get_post_meta( $page_for_posts, "_aioseop_title", true ) ); if ( !$title ) { $post_page = get_post( $page_for_posts ); $title = $this->internationalize( $post_page->post_title ); } } else { $title = $this->internationalize( get_post_meta( $post->ID, "_aioseop_title", true ) ); if ( !$title ) $title = $this->internationalize( $post->post_title ); } if ( !$title ) $title = $this->internationalize( $this->get_original_title( '', false ) ); $title = $this->apply_page_title_format( $title, $post ); $title = $this->paged_title( $title ); $title = apply_filters( 'aioseop_title_page', $title ); if ( $this->is_static_posts_page() ) $title = apply_filters( 'single_post_title', $title ); return $title; } } else if ( function_exists( 'woocommerce_get_page_id' ) && is_post_type_archive( 'product' ) && ( $post_id = woocommerce_get_page_id( 'shop' ) ) && ( $post = get_post( $post_id ) ) ) { $title = $this->internationalize( get_post_meta( $post->ID, "_aioseop_title", true ) ); if ( !$title ) $title = $this->internationalize( $post->post_title ); if ( !$title ) $title = $this->internationalize( $this->get_original_title( '', false ) ); $title = $this->apply_page_title_format( $title, $post ); $title = $this->paged_title( $title ); $title = apply_filters( 'aioseop_title_page', $title ); return $title; } else if ( is_single() ) { // we're not in the loop :( if ( $post === null ) return false; $categories = $this->get_all_categories(); $category = ''; if ( count( $categories ) > 0 ) $category = $categories[0]; $title = $this->internationalize( get_post_meta( $post->ID, "_aioseop_title", true ) ); if ( !$title ) { $title = $this->internationalize( get_post_meta( $post->ID, "title_tag", true ) ); if ( !$title ) $title = $this->internationalize($this->get_original_title( '', false ) ); } if ( empty( $title ) ) $title = $post->post_title; if ( !empty( $title ) ) $title = $this->apply_post_title_format( $title, $category, $post ); $title = $this->paged_title( $title ); return apply_filters( 'aioseop_title_single', $title ); } else if ( is_search() && isset( $s ) && !empty( $s ) ) { $search = esc_attr( stripslashes( $s ) ); if ( !empty( $aioseop_options['aiosp_cap_titles'] ) ) $search = $this->capitalize( $search ); $title_format = $aioseop_options['aiosp_search_title_format']; $title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name' ) ), $title_format ); if ( strpos( $title, '%blog_description%' ) !== false ) $title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description' ) ), $title ); if ( strpos( $title, '%search%' ) !== false ) $title = str_replace( '%search%', $search, $title ); $title = $this->paged_title( $title ); return $title; } else if ( is_tag() ) { global $utw; $tag = $tag_description = ''; if ( $utw ) { $tags = $utw->GetCurrentTagSet(); $tag = $tags[0]->tag; $tag = str_replace('-', ' ', $tag); } else { if ( !empty( $opts ) && !empty( $opts['aiosp_title'] ) ) $tag = $opts['aiosp_title']; if ( !empty( $opts ) ) { if ( !empty( $opts['aiosp_title'] ) ) $tag = $opts['aiosp_title']; if ( !empty( $opts['aiosp_description'] ) ) $tag_description = $opts['aiosp_description']; } if ( empty( $tag ) ) $tag = $this->get_original_title( '', false ); if ( empty( $tag_description ) ) $tag_description = tag_description(); $tag = $this->internationalize( $tag ); $tag_description = $this->internationalize( $tag_description ); } if ( $tag ) { if ( !empty( $aioseop_options['aiosp_cap_titles'] ) ) $tag = $this->capitalize( $tag ); $title_format = $aioseop_options['aiosp_tag_title_format']; $title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo('name') ), $title_format ); if ( strpos( $title, '%blog_description%' ) !== false ) $title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description') ), $title ); if ( strpos( $title, '%tag%' ) !== false ) $title = str_replace( '%tag%', $tag, $title ); if ( strpos( $title, '%tag_description%' ) !== false ) $title = str_replace( '%tag_description%', $tag_description, $title ); if ( strpos( $title, '%taxonomy_description%' ) !== false ) $title = str_replace( '%taxonomy_description%', $tag_description, $title ); $title = trim( wp_strip_all_tags( $title ) ); $title = str_replace( Array( '"', "\r\n", "\n" ), Array( '&quot;', ' ', ' ' ), $title ); $title = $this->paged_title( $title ); return $title; } } else if ( ( is_tax() || is_category() ) && !is_feed() ) { return $this->get_tax_title(); } else if ( isset( $STagging ) && $STagging->is_tag_view() ) { // simple tagging support $tag = $STagging->search_tag; if ( $tag ) { if ( !empty( $aioseop_options['aiosp_cap_titles'] ) ) $tag = $this->capitalize($tag); $title_format = $aioseop_options['aiosp_tag_title_format']; $title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name') ), $title_format); if ( strpos( $title, '%blog_description%' ) !== false ) $title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description') ), $title); if ( strpos( $title, '%tag%' ) !== false ) $title = str_replace( '%tag%', $tag, $title ); $title = $this->paged_title( $title ); return $title; } } else if ( is_archive() || is_post_type_archive() ) { if ( is_author() ) { $author = $this->internationalize( $this->get_original_title( '', false ) ); $title_format = $aioseop_options['aiosp_author_title_format']; $new_title = str_replace( '%author%', $author, $title_format ); } else if ( is_date() ) { global $wp_query; $date = $this->internationalize( $this->get_original_title( '', false ) ); $title_format = $aioseop_options['aiosp_date_title_format']; $new_title = str_replace( '%date%', $date, $title_format ); $day = get_query_var( 'day' ); if ( empty( $day ) ) $day = ''; $new_title = str_replace( '%day%', $day, $new_title ); $monthnum = get_query_var( 'monthnum' ); $year = get_query_var( 'year' ); if ( empty( $monthnum ) || is_year() ) { $month = ''; $monthnum = 0; } $month = date( "F", mktime( 0,0,0,(int)$monthnum,1,(int)$year ) ); $new_title = str_replace( '%monthnum%', $monthnum, $new_title ); if ( strpos( $new_title, '%month%' ) !== false ) $new_title = str_replace( '%month%', $month, $new_title ); if ( strpos( $new_title, '%year%' ) !== false ) $new_title = str_replace( '%year%', get_query_var( 'year' ), $new_title ); } else if ( is_post_type_archive() ) { if ( empty( $title ) ) $title = $this->get_original_title( '', false ); $new_title = apply_filters( 'aioseop_archive_title', $this->apply_archive_title_format( $title ) ); } else return false; $new_title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name' ) ), $new_title ); if ( strpos( $new_title, '%blog_description%' ) !== false ) $new_title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description' ) ), $new_title ); $title = trim( $new_title ); $title = $this->paged_title( $title ); return $title; } else if ( is_404() ) { $title_format = $aioseop_options['aiosp_404_title_format']; $new_title = str_replace( '%blog_title%', $this->internationalize( get_bloginfo( 'name') ), $title_format ); if ( strpos( $new_title, '%blog_description%' ) !== false ) $new_title = str_replace( '%blog_description%', $this->internationalize( get_bloginfo( 'description' ) ), $new_title ); if ( strpos( $new_title, '%request_url%' ) !== false ) $new_title = str_replace( '%request_url%', $_SERVER['REQUEST_URI'], $new_title ); if ( strpos( $new_title, '%request_words%' ) !== false ) $new_title = str_replace( '%request_words%', $this->request_as_words( $_SERVER['REQUEST_URI'] ), $new_title ); if ( strpos( $new_title, '%404_title%' ) !== false ) $new_title = str_replace( '%404_title%', $this->internationalize( $this->get_original_title( '', false ) ), $new_title ); return $new_title; } return false; } /*** Used to filter wp_title(), get our title. ***/ function wp_title() { global $aioseop_options; $title = false; $post = $this->get_queried_object(); if ( !empty( $aioseop_options['aiosp_rewrite_titles'] ) ) { $title = $this->get_aioseop_title( $post ); $title = $this->apply_cf_fields( $title ); } if ( $title === false ) $title = $this->get_original_title(); return apply_filters( 'aioseop_title', $title ); } /*** Used for forcing title rewrites. ***/ function rewrite_title($header) { global $wp_query; if (!$wp_query) { $header .= "<!-- no wp_query found! -->\n"; return $header; } $title = $this->wp_title(); if ( !empty( $title ) ) $header = $this->replace_title( $header, $title ); return $header; } /** * @return User-readable nice words for a given request. */ function request_as_words( $request ) { $request = htmlspecialchars( $request ); $request = str_replace( '.html', ' ', $request ); $request = str_replace( '.htm', ' ', $request ); $request = str_replace( '.', ' ', $request ); $request = str_replace( '/', ' ', $request ); $request = str_replace( '-', ' ', $request ); $request_a = explode( ' ', $request ); $request_new = array(); foreach ( $request_a as $token ) { $request_new[] = $this->ucwords( trim( $token ) ); } $request = implode( ' ', $request_new ); return $request; } function capitalize( $s ) { $s = trim( $s ); $tokens = explode( ' ', $s ); while ( list( $key, $val ) = each( $tokens ) ) { $tokens[ $key ] = trim( $tokens[ $key ] ); $tokens[ $key ] = $this->strtoupper( $this->substr( $tokens[$key], 0, 1 ) ) . $this->substr( $tokens[$key], 1 ); } $s = implode( ' ', $tokens ); return $s; } function trim_excerpt_without_filters( $text, $max = 0 ) { $text = str_replace( ']]>', ']]&gt;', $text ); $text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text ); $text = wp_strip_all_tags( $text ); if ( !$max ) $max = $this->maximum_description_length; $len = $this->strlen( $text ); if ( $max < $len ) { if ( function_exists( 'mb_strrpos' ) ) { $pos = mb_strrpos( $text, ' ', -($len - $max) ); if ( $pos === false ) $pos = $max; if ( $pos > $this->minimum_description_length ) { $max = $pos; } else { $max = $this->minimum_description_length; } } else { while( $text[$max] != ' ' && $max > $this->minimum_description_length ) { $max--; } } } $text = $this->substr( $text, 0, $max ); return trim( stripslashes( $text ) ); } function trim_excerpt_without_filters_full_length( $text ) { $text = str_replace( ']]>', ']]&gt;', $text ); $text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text ); $text = wp_strip_all_tags( $text ); return trim( stripslashes( $text ) ); } function keyword_string_to_list( $keywords ) { $traverse = Array(); $keywords_i = str_replace( '"', '', $keywords ); if (isset( $keywords_i ) && !empty( $keywords_i ) ) { $traverse = explode( ',', $keywords_i ); } return $traverse; } function get_all_categories( $id = 0 ) { $keywords = Array(); $categories = get_the_category( $id ); if ( !empty( $categories ) ) foreach ( $categories as $category ) $keywords[] = $this->internationalize( $category->cat_name ); return $keywords; } function get_all_tags( $id = 0 ) { $keywords = Array(); $tags = get_the_tags( $id ); if ( !empty( $tags ) && is_array( $tags) ) foreach ( $tags as $tag ) $keywords[] = $this->internationalize( $tag->name ); // Ultimate Tag Warrior integration global $utw; if ( $utw ) { $tags = $utw->GetTagsForPost( $p ); if ( is_array( $tags ) ) foreach ( $tags as $tag ) { $tag = $tag->tag; $tag = str_replace( '_', ' ', $tag ); $tag = str_replace( '-', ' ', $tag ); $tag = stripslashes( $tag ); $keywords[] = $tag; } } return $keywords; } function get_all_terms( $id, $taxnomy ) { $keywords = Array(); $terms = get_the_terms( $id, $taxnomy ); if ( !empty( $terms ) ) foreach ( $terms as $term ) $keywords[] = $this->internationalize( $term->name ); return $keywords; } /** * @return comma-separated list of unique keywords */ function get_all_keywords() { global $posts; global $aioseop_options; if ( is_404() ) return null; // if we are on synthetic pages if ( !is_home() && !is_page() && !is_single() && !$this->is_static_front_page() && !$this->is_static_posts_page() && !is_archive() && !is_post_type_archive() &&!is_category() && !is_tag() && !is_tax() ) return null; $keywords = array(); $opts = $this->meta_opts; if ( !empty( $opts["aiosp_keywords"] ) ) { $traverse = $this->keyword_string_to_list( $this->internationalize( $opts["aiosp_keywords"] ) ); if ( !empty( $traverse ) ) foreach ( $traverse as $keyword ) $keywords[] = $keyword; } if ( empty( $posts ) ) { global $post; $post_arr = Array( $post ); } else { $post_arr = $posts; } if ( is_array( $post_arr ) ) { $postcount = count( $post_arr ); foreach ( $post_arr as $p ) { if ( $p ) { $id = $p->ID; if ( $postcount == 1 || !empty( $aioseop_options['aiosp_dynamic_postspage_keywords'] ) ) { // custom field keywords $keywords_i = null; $keywords_i = stripslashes( $this->internationalize( get_post_meta( $id, "_aioseop_keywords", true ) ) ); if ( is_attachment() ) { $id = $p->post_parent; if ( empty( $keywords_i ) ) $keywords_i = stripslashes( $this->internationalize( get_post_meta( $id, "_aioseop_keywords", true ) ) ); } $traverse = $this->keyword_string_to_list( $keywords_i ); if ( !empty( $traverse ) ) foreach ( $traverse as $keyword ) $keywords[] = $keyword; } if ( !empty( $aioseop_options['aiosp_use_tags_as_keywords'] ) ) { $keywords = array_merge( $keywords, $this->get_all_tags( $id ) ); } // autometa $autometa = stripslashes( get_post_meta( $id, 'autometa', true ) ); if ( isset( $autometa ) && !empty( $autometa ) ) { $autometa_array = explode( ' ', $autometa ); foreach ( $autometa_array as $e ) $keywords[] = $e; } if ( $aioseop_options['aiosp_use_categories'] && !is_page() ) { $keywords = array_merge( $keywords, $this->get_all_categories( $id ) ); } } } } return $this->get_unique_keywords( $keywords ); } function clean_keyword_list( $keywords ) { $small_keywords = array(); if ( !is_array( $keywords ) ) $keywords = $this->keyword_string_to_list( $keywords ); if ( !empty( $keywords ) ) foreach ( $keywords as $word ) { $small_keywords[] = trim( $this->strtolower( $word ) ); } return array_unique( $small_keywords ); } function get_unique_keywords($keywords) { return implode( ',', $this->clean_keyword_list( $keywords ) ); } function log( $message ) { if ( $this->do_log ) { @error_log( date( 'Y-m-d H:i:s' ) . " " . $message . "\n", 3, $this->log_file ); } } function save_post_data( $id ) { $awmp_edit = $nonce = null; if ( empty( $_POST ) ) return false; if ( isset( $_POST[ 'aiosp_edit' ] ) ) $awmp_edit = $_POST['aiosp_edit']; if ( isset( $_POST[ 'nonce-aioseop-edit' ] ) ) $nonce = $_POST['nonce-aioseop-edit']; if ( isset($awmp_edit) && !empty($awmp_edit) && wp_verify_nonce($nonce, 'edit-aioseop-nonce') ) { $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'sitemap_exclude', 'disable', 'disable_analytics', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); if ( !( !empty( $this->options['aiosp_can'] ) ) && ( !empty( $this->options['aiosp_customize_canonical_links'] ) ) ) { unset( $optlist["custom_link"] ); } foreach ( $optlist as $f ) { $field = "aiosp_$f"; if ( isset( $_POST[$field] ) ) $$field = $_POST[$field]; } $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); if ( !( !empty( $this->options['aiosp_can'] ) ) && ( !empty( $this->options['aiosp_customize_canonical_links'] ) ) ) { unset( $optlist["custom_link"] ); } foreach ( $optlist as $f ) delete_post_meta( $id, "_aioseop_{$f}" ); if ( $this->is_admin() ) { delete_post_meta($id, '_aioseop_sitemap_exclude' ); delete_post_meta($id, '_aioseop_disable' ); delete_post_meta($id, '_aioseop_disable_analytics' ); } foreach ( $optlist as $f ) { $var = "aiosp_$f"; $field = "_aioseop_$f"; if ( isset( $$var ) && !empty( $$var ) ) add_post_meta( $id, $field, $$var ); } if (isset( $aiosp_sitemap_exclude ) && !empty( $aiosp_sitemap_exclude ) && $this->is_admin() ) add_post_meta( $id, '_aioseop_sitemap_exclude', $aiosp_sitemap_exclude ); if (isset( $aiosp_disable ) && !empty( $aiosp_disable ) && $this->is_admin() ) { add_post_meta( $id, '_aioseop_disable', $aiosp_disable ); if (isset( $aiosp_disable_analytics ) && !empty( $aiosp_disable_analytics ) ) add_post_meta( $id, '_aioseop_disable_analytics', $aiosp_disable_analytics ); } } } function display_tabbed_metabox( $post, $metabox ) { $tabs = $metabox['args']; echo '<div class="aioseop_tabs">'; $header = $this->get_metabox_header( $tabs ); echo $header; $active = ""; foreach( $tabs as $m ) { echo '<div id="'.$m['id'].'" class="aioseop_tab"' . $active . '>'; if ( !$active ) $active = ' style="display:none;"'; $m['args'] = $m['callback_args']; $m['callback'][0]->{$m['callback'][1]}( $post, $m ); echo '</div>'; } echo '</div>'; } function admin_bar_menu() { global $wp_admin_bar, $aioseop_admin_menu, $aioseop_options, $post; if ( !empty( $aioseop_options['aiosp_admin_bar'] ) ) { $menu_slug = plugin_basename( __FILE__ ); $url = ''; if ( function_exists( 'menu_page_url' ) ) $url = menu_page_url( $menu_slug, 0 ); if ( empty( $url ) ) $url = esc_url( admin_url( 'admin.php?page=' . $menu_slug ) ); $wp_admin_bar->add_menu( array( 'id' => AIOSEOP_PLUGIN_DIRNAME, 'title' => __( 'SEO', 'all_in_one_seo_pack' ), 'href' => $url ) ); $aioseop_admin_menu = 1; if ( !is_admin() && !empty( $post ) ) { $blog_page = $this->get_blog_page( $post ); if ( !empty( $blog_page ) ) $post = $blog_page; $wp_admin_bar->add_menu( array( 'id' => 'aiosp_edit_' . $post->ID, 'parent' => AIOSEOP_PLUGIN_DIRNAME, 'title' => __( 'Edit SEO', 'all_in_one_seo_pack' ), 'href' => get_edit_post_link( $post->ID ) . '#aiosp' ) ); } } } function menu_order() { return 5; } function display_category_metaboxes( $tax ) { $screen = 'edit-' . $tax->taxonomy; ?><div id="poststuff"> <?php do_meta_boxes( '', 'advanced', $tax ); ?> </div> <?php } function save_category_metaboxes( $id ) { $awmp_edit = $nonce = null; if ( isset( $_POST[ 'aiosp_edit' ] ) ) $awmp_edit = $_POST['aiosp_edit']; if ( isset( $_POST[ 'nonce-aioseop-edit' ] ) ) $nonce = $_POST['nonce-aioseop-edit']; if ( isset($awmp_edit) && !empty($awmp_edit) && wp_verify_nonce($nonce, 'edit-aioseop-nonce') ) { $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'sitemap_exclude', 'disable', 'disable_analytics', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); foreach ( $optlist as $f ) { $field = "aiosp_$f"; if ( isset( $_POST[$field] ) ) $$field = $_POST[$field]; } $optlist = Array( 'keywords', 'description', 'title', 'custom_link', 'noindex', 'nofollow', 'noodp', 'noydir', 'titleatr', 'menulabel' ); if ( !( !empty( $this->options['aiosp_can'] ) ) && ( !empty( $this->options['aiosp_customize_canonical_links'] ) ) ) { unset( $optlist["custom_link"] ); } foreach ( $optlist as $f ) delete_term_meta( $id, "_aioseop_{$f}" ); if ( $this->is_admin() ) { delete_term_meta($id, '_aioseop_sitemap_exclude' ); delete_term_meta($id, '_aioseop_disable' ); delete_term_meta($id, '_aioseop_disable_analytics' ); } foreach ( $optlist as $f ) { $var = "aiosp_$f"; $field = "_aioseop_$f"; if ( isset( $$var ) && !empty( $$var ) ) add_term_meta( $id, $field, $$var ); } if (isset( $aiosp_sitemap_exclude ) && !empty( $aiosp_sitemap_exclude ) && $this->is_admin() ) add_term_meta( $id, '_aioseop_sitemap_exclude', $aiosp_sitemap_exclude ); if (isset( $aiosp_disable ) && !empty( $aiosp_disable ) && $this->is_admin() ) { add_term_meta( $id, '_aioseop_disable', $aiosp_disable ); if (isset( $aiosp_disable_analytics ) && !empty( $aiosp_disable_analytics ) ) add_term_meta( $id, '_aioseop_disable_analytics', $aiosp_disable_analytics ); } } } function admin_menu() { $file = plugin_basename( __FILE__ ); $menu_name = __( 'All in One SEO', 'all_in_one_seo_pack' ); $this->locations['aiosp']['default_options']['nonce-aioseop-edit']['default'] = wp_create_nonce('edit-aioseop-nonce'); $custom_menu_order = false; global $aioseop_options; if ( !isset( $aioseop_options['custom_menu_order'] ) ) $custom_menu_order = true; $this->update_options( ); $this->add_admin_pointers(); if ( !empty( $this->pointers ) ) foreach( $this->pointers as $k => $p ) if ( !empty( $p["pointer_scope"] ) && ( $p["pointer_scope"] == 'global' ) ) unset( $this->pointers[$k] ); if ( ( isset( $_POST ) ) && ( isset( $_POST['module'] ) ) && ( isset( $_POST['nonce-aioseop'] ) ) && ( $_POST['module'] == 'All_in_One_SEO_Pack' ) && ( wp_verify_nonce( $_POST['nonce-aioseop'], 'aioseop-nonce' ) ) ) { if ( isset($_POST["Submit"] ) ) { if ( isset( $_POST["aiosp_custom_menu_order"] ) ) $custom_menu_order = $_POST["aiosp_custom_menu_order"]; else $custom_menu_order = false; } else if ( ( isset($_POST["Submit_Default"] ) ) || ( ( isset($_POST["Submit_All_Default"] ) ) ) ) { $custom_menu_order = true; } } else { if ( isset( $this->options["aiosp_custom_menu_order"] ) ) $custom_menu_order = $this->options["aiosp_custom_menu_order"]; } if ( $custom_menu_order ) { add_filter( 'custom_menu_order', '__return_true' ); add_filter( 'menu_order', array( $this, 'set_menu_order' ) ); } if ( !empty( $this->options['aiosp_enablecpost'] ) && $this->options['aiosp_enablecpost'] ) { $this->locations['aiosp']['display'] = $this->options['aiosp_cpostactive']; if ( !empty( $this->options['aiosp_taxactive'] ) ) { foreach( $this->options['aiosp_taxactive'] as $tax ) { $this->locations['aiosp']['display'][] = 'edit-' . $tax; add_action( "{$tax}_edit_form", Array( $this, 'display_category_metaboxes' ) ); add_action( "edited_{$tax}", Array( $this, 'save_category_metaboxes' ) ); } } } else { $this->locations['aiosp']['display'] = Array( 'post', 'page' ); } if ( $custom_menu_order ) add_menu_page( $menu_name, $menu_name, 'manage_options', $file, Array( $this, 'display_settings_page' ) ); else add_utility_page( $menu_name, $menu_name, 'manage_options', $file, Array( $this, 'display_settings_page' ) ); add_meta_box('aioseop-list', __( "Join Our Mailing List", 'all_in_one_seo_pack' ), array( $this, 'display_extra_metaboxes'), 'aioseop_metaboxes', 'normal', 'core'); add_meta_box('aioseop-about', __( "About", 'all_in_one_seo_pack' ), array( $this, 'display_extra_metaboxes'), 'aioseop_metaboxes', 'side', 'core'); add_meta_box('aioseop-support', __( "Support", 'all_in_one_seo_pack' ) . " <span style='float:right;'>" . __( "Version", 'all_in_one_seo_pack' ) . " <b>" . AIOSEOP_VERSION . "</b></span>", array( $this, 'display_extra_metaboxes'), 'aioseop_metaboxes', 'side', 'core'); add_action( 'aioseop_modules_add_menus', Array( $this, 'add_menu' ), 5 ); do_action( 'aioseop_modules_add_menus', $file ); $metaboxes = apply_filters( 'aioseop_add_post_metabox', Array() ); if ( !empty( $metaboxes ) ) { if ( $this->tabbed_metaboxes ) { $tabs = Array(); $tab_num = 0; foreach ( $metaboxes as $m ) { if ( !isset( $tabs[ $m['post_type'] ] ) ) $tabs[ $m['post_type'] ] = Array(); $tabs[ $m['post_type'] ][] = $m; } if ( !empty( $tabs ) ) { foreach( $tabs as $p => $m ) { $tab_num = count( $m ); $title = $m[0]['title']; if ( $title != $this->plugin_name ) $title = $this->plugin_name . ' - ' . $title; if ( $tab_num <= 1 ) { if ( !empty( $m[0]['callback_args']['help_link'] ) ) $title .= "<a class='aioseop_help_text_link aioseop_meta_box_help' target='_blank' href='" . $m[0]['callback_args']['help_link'] . "'><span>" . __( 'Help', 'all_in_one_seo_pack' ) . "</span></a>"; add_meta_box( $m[0]['id'], $title, $m[0]['callback'], $m[0]['post_type'], $m[0]['context'], $m[0]['priority'], $m[0]['callback_args'] ); } elseif ( $tab_num > 1 ) { add_meta_box( $m[0]['id'] . '_tabbed', $title, Array( $this, 'display_tabbed_metabox' ), $m[0]['post_type'], $m[0]['context'], $m[0]['priority'], $m ); } } } } else { foreach ( $metaboxes as $m ) { $title = $m['title']; if ( $title != $this->plugin_name ) $title = $this->plugin_name . ' - ' . $title; if ( !empty( $m['help_link'] ) ) $title .= "<a class='aioseop_help_text_link aioseop_meta_box_help' target='_blank' href='" . $m['help_link'] . "'><span>" . __( 'Help', 'all_in_one_seo_pack' ) . "</span></a>"; add_meta_box( $m['id'], $title, $m['callback'], $m['post_type'], $m['context'], $m['priority'], $m['callback_args'] ); } } } } function get_metabox_header( $tabs ) { $header = '<ul class="aioseop_header_tabs hide">'; $active = ' active'; foreach( $tabs as $t ) { if ( $active ) $title = __( 'Main Settings', 'all_in_one_seo_pack' ); else $title = $t['title']; $header .= '<li><label class="aioseop_header_nav"><a class="aioseop_header_tab' . $active . '" href="#'. $t['id'] .'">'.$title.'</a></label></li>'; $active = ''; } $header .= '</ul>'; return $header; } function set_menu_order( $menu_order ) { $order = array(); $file = plugin_basename( __FILE__ ); foreach ( $menu_order as $index => $item ) { if ( $item != $file ) $order[] = $item; if ( $index == 0 ) $order[] = $file; } return $order; } function display_settings_header() { } function display_settings_footer( ) { } function display_right_sidebar( ) { global $wpdb; if( !get_option( 'aioseop_options' ) ) { $msg = "<div style='text-align:center;'><p><strong>Your database options need to be updated.</strong><em>(Back up your database before updating.)</em> <FORM action='' method='post' name='aioseop-migrate-options'> <input type='hidden' name='nonce-aioseop-migrate-options' value='" . wp_create_nonce( 'aioseop-migrate-nonce-options' ) . "' /> <input type='submit' name='aioseop_migrate_options' class='button-primary' value='Update Database Options'> </FORM> </p></div>"; aioseop_output_dismissable_notice( $msg, "", "error" ); } ?> <div class="aioseop_top"> <div class="aioseop_top_sidebar aioseop_options_wrapper"> <?php do_meta_boxes( 'aioseop_metaboxes', 'normal', Array( 'test' ) ); ?> </div> </div> <style> #wpbody-content { min-width: 900px; } </style> <div class="aioseop_right_sidebar aioseop_options_wrapper"> <div class="aioseop_sidebar"> <?php do_meta_boxes( 'aioseop_metaboxes', 'side', Array( 'test' ) ); ?> <script type="text/javascript"> //<![CDATA[ jQuery(document).ready( function($) { // close postboxes that should be closed $('.if-js-closed').removeClass('if-js-closed').addClass('closed'); // postboxes setup if ( typeof postboxes !== 'undefined' ) postboxes.add_postbox_toggles('<?php echo $this->pagehook; ?>'); //$('.meta-box-sortables').removeClass('meta-box-sortables'); }); //]]> </script> </div> </div> <?php } }
mit
Screeder/SAssemblies
SStandalones/SMiscs/SAntiJumpMisc/Program.cs
5532
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using LeagueSharp.Common; using LeagueSharp; using SAssemblies; using SAssemblies.Miscs; using Menu = SAssemblies.Menu; using System.Drawing; namespace SAssemblies { class MainMenu : Menu { private readonly Dictionary<MenuItemSettings, Func<dynamic>> MenuEntries; public static MenuItemSettings Misc = new MenuItemSettings(); public static MenuItemSettings AntiJumpMisc = new MenuItemSettings(); public MainMenu() { MenuEntries = new Dictionary<MenuItemSettings, Func<dynamic>> { { AntiJumpMisc, () => new AntiJump() }, }; } public Tuple<MenuItemSettings, Func<dynamic>> GetDirEntry(MenuItemSettings menuItem) { return new Tuple<MenuItemSettings, Func<dynamic>>(menuItem, MenuEntries[menuItem]); } public Dictionary<MenuItemSettings, Func<dynamic>> GetDirEntries() { return MenuEntries; } public void UpdateDirEntry(ref MenuItemSettings oldMenuItem, MenuItemSettings newMenuItem) { Func<dynamic> save = MenuEntries[oldMenuItem]; MenuEntries.Remove(oldMenuItem); MenuEntries.Add(newMenuItem, save); oldMenuItem = newMenuItem; } } class MainMenu2 : Menu2 { public static MenuItemSettings Misc = new MenuItemSettings(); public static MenuItemSettings AntiJumpMisc = new MenuItemSettings(); public MainMenu2() { MenuEntries = new Dictionary<MenuItemSettings, Func<dynamic>> { { AntiJumpMisc, () => new AntiJump() }, }; } } class Program { private static bool threadActive = true; private static float lastDebugTime = 0; private MainMenu mainMenu; private static readonly Program instance = new Program(); public static void Main(string[] args) { AssemblyResolver.Init(); AppDomain.CurrentDomain.DomainUnload += delegate { threadActive = false; }; AppDomain.CurrentDomain.ProcessExit += delegate { threadActive = false; }; Instance().Load(); } public void Load() { mainMenu = new MainMenu(); LeagueSharp.SDK.Core.Events.Load.OnLoad += Game_OnGameLoad; } public static Program Instance() { return instance; } private async void Game_OnGameLoad(Object obj, EventArgs args) { CreateMenu(); Common.ShowNotification("SAntiJumpMisc loaded!", Color.LawnGreen, 5000); new Thread(GameOnOnGameUpdate).Start(); } private void CreateMenu() { //http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes try { var menu = Menu2.CreateMainMenu(); Menu2.CreateGlobalMenuItems(menu); //MainMenu.Misc = Misc.SetupMenu(menu); //mainMenu.UpdateDirEntry(ref MainMenu.AntiJump, AntiJump.SetupMenu(MainMenu.Misc.Menu)); Menu2.MenuItemSettings AntiJumpMisc = new Menu2.MenuItemSettings(typeof(AntiJump)); AntiJumpMisc.Menu = Menu2.AddMenu(ref menu, new LeagueSharp.SDK.Core.UI.IMenu.Menu("SAssembliesMiscsAntiJump", Language.GetString("MISCS_ANTIJUMP_MAIN"))); AntiJumpMisc.CreateActiveMenuItem("SAssembliesMiscsAntiJumpActive"); MainMenu2.AntiJumpMisc = AntiJumpMisc; } catch (Exception) { throw; } } private void GameOnOnGameUpdate(/*EventArgs args*/) { try { while (threadActive) { Thread.Sleep(1000); if (mainMenu == null) continue; foreach (var entry in mainMenu.GetDirEntries()) { var item = entry.Key; if (item == null) { continue; } try { if (item.GetActive() == false && item.Item != null) { item.Item = null; } else if (item.GetActive() && item.Item == null && !item.ForceDisable && item.Type != null) { try { item.Item = entry.Value(); } catch (Exception e) { Console.WriteLine(e); } } } catch (Exception e) { } } } } catch (Exception e) { Console.WriteLine("SAwareness: " + e); threadActive = false; } } } }
mit
max-gram/viewport-size
app/scripts/devtools.js
221
var backgroundPageConnection = chrome.runtime.connect({ name: "devtools-vs-connect"}); backgroundPageConnection.postMessage({ name: 'devtools-vs-init', tabId: chrome.devtools.inspectedWindow.tabId });
mit
roryaronson/OpenFarm
test/factories/token.rb
61
FactoryGirl.define do factory :token do user end end
mit
MarinesBG/Programming-Fundamentals
Programming-Fundamentals-Exercise/03 - Data Types and Variables - Exercise/P13-Vowel or Digit/Properties/AssemblyInfo.cs
1407
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("P13-Vowel or Digit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("P13-Vowel or Digit")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bc06f953-0ac8-4f36-af93-7b22a55dc71e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
ThaDafinser/Piwik-LdapConnection
API.php
2084
<?php /** * @author https://github.com/ThaDafinser */ namespace Piwik\Plugins\LdapConnection; use Exception; use Piwik\Piwik; use Zend\Ldap\Ldap; class API extends \Piwik\Plugin\API { /** * * @var Ldap */ protected $ldap; /** * For IDE and codecompletion * * @return API */ public static function getInstance() { return parent::getInstance(); } /** * * @return Ldap */ public function getConnection() { if ($this->ldap === null) { require __DIR__ . '/vendor/autoload.php'; $settings = new SystemSettings(); $settingValues = [ 'host' => $settings->host->getValue(), 'port' => $settings->port->getValue(), 'baseDn' => $settings->baseDn->getValue(), 'username' => $settings->username->getValue(), 'password' => $settings->password->getValue(), 'bindRequiresDn' => $settings->bindRequiresDn->getValue(), 'useSsl' => $settings->useSsl->getValue(), 'useStartTls' => $settings->useStartTls->getValue(), 'accountCanonicalForm' => $settings->accountCanonicalForm->getValue(), 'accountDomainName' => $settings->accountDomainName->getValue(), 'accountDomainNameShort' => $settings->accountDomainNameShort->getValue(), 'accountFilterFormat' => $settings->accountFilterFormat->getValue(), 'allowEmptyPassword' => $settings->allowEmptyPassword->getValue(), 'optReferrals' => $settings->optReferrals->getValue(), 'tryUsernameSplit' => $settings->tryUsernameSplit->getValue(), 'networkTimeout' => $settings->networkTimeout->getValue(), ]; $ldap = new Ldap($settingValues); $this->ldap = $ldap; } return $this->ldap; } }
mit
ipfs/node-ipfs
src/cli/commands/get.js
1874
'use strict' var fs = require('fs') const path = require('path') const mkdirp = require('mkdirp') const pull = require('pull-stream') const toPull = require('stream-to-pull-stream') function checkArgs (hash, outPath) { // format the output directory if (!outPath.endsWith(path.sep)) { outPath += path.sep } return outPath } function ensureDirFor (dir, file, callback) { const lastSlash = file.path.lastIndexOf('/') const filePath = file.path.substring(0, lastSlash + 1) const dirPath = path.join(dir, filePath) mkdirp(dirPath, callback) } function fileHandler (dir) { return function onFile (file, callback) { ensureDirFor(dir, file, (err) => { if (err) { callback(err) } else { const fullFilePath = path.join(dir, file.path) if (file.content) { file.content .pipe(fs.createWriteStream(fullFilePath)) .once('error', callback) .once('finish', callback) } else { // this is a dir mkdirp(fullFilePath, callback) } } }) } } module.exports = { command: 'get <ipfsPath>', describe: 'Fetch a file or directory with files references from an IPFS Path', builder: { output: { alias: 'o', type: 'string', default: process.cwd() } }, handler ({ getIpfs, print, ipfsPath, output, resolve }) { resolve((async () => { const ipfs = await getIpfs() return new Promise((resolve, reject) => { const dir = checkArgs(ipfsPath, output) const stream = ipfs.getReadableStream(ipfsPath) print(`Saving file(s) ${ipfsPath}`) pull( toPull.source(stream), pull.asyncMap(fileHandler(dir)), pull.onEnd((err) => { if (err) return reject(err) resolve() }) ) }) })()) } }
mit
yizhang7210/Acre
server/algos/euler/transformer.py
4204
""" This is algos.euler.transformer module. This module is responsible for transforming raw candle data into training samples usable to the Euler algorithm. """ import datetime import decimal from algos.euler.models import training_samples as ts from core.models import instruments from datasource.models import candles TWO_PLACES = decimal.Decimal('0.01') def extract_features(day_candle): """ Extract the features for the learning algorithm from a daily candle. The Features are: high_bid, low_bid, close_bid, open_ask, high_ask, low_ask, and close_ask (all relative to open_bid) in pips. Args: day_candle: candles.Candle object representing a daily candle. Returns: features: List of Decimals. The features described above, all in two decimal places. """ multiplier = day_candle.instrument.multiplier features = [ day_candle.high_bid, day_candle.low_bid, day_candle.close_bid, day_candle.open_ask, day_candle.high_ask, day_candle.low_ask, day_candle.close_ask, ] features = [multiplier * (x - day_candle.open_bid) for x in features] features = [decimal.Decimal(x).quantize(TWO_PLACES) for x in features] return features def get_profitable_change(day_candle): """ Get the potential daily profitable price change in pips. If prices rise enough, we have: close_bid - open_ask (> 0), buy. If prices fall enough, we have: close_ask - open_bid (< 0), sell. if prices stay relatively still, we don't buy or sell. It's 0. Args: day_candle: candles.Candle object representing a daily candle. Returns: profitable_change: Decimal. The profitable rate change described above, in two decimal places. """ multiplier = day_candle.instrument.multiplier change = 0 if day_candle.close_bid > day_candle.open_ask: change = multiplier * (day_candle.close_bid - day_candle.open_ask) elif day_candle.close_ask < day_candle.open_bid: change = multiplier * (day_candle.close_ask - day_candle.open_bid) return decimal.Decimal(change).quantize(TWO_PLACES) def build_sample_row(candle_previous, candle_next): """ Build one training sample from two consecutive days of candles. Args: candle_previous: candles.Candle object. Candle of first day. candle_next: candles.Candle object. Candle of second day. Returns: sample: TrainingSample object. One training sample for learning. """ return ts.create_one( instrument=candle_next.instrument, date=candle_next.start_time.date() + datetime.timedelta(1), features=extract_features(candle_previous), target=get_profitable_change(candle_next)) def get_start_time(instrument): """ Get the start time for retrieving candles of the given instrument. This is determined by the last training sample in the database. Args: instrument: Instrument object. The given instrument. Returns: start_time: Datetime object. The datetime from which to query candles from to fill the rest of the training samples. """ last_sample = ts.get_last(instrument) if last_sample is not None: start_date = last_sample.date - datetime.timedelta(1) return datetime.datetime.combine(start_date, datetime.time()) return datetime.datetime(2005, 1, 1) def run(): """ Update the training samples in the database from the latest candles. This should be run daily to ensure the training set is up-to-date. Args: None. """ all_new_samples = [] for instrument in instruments.get_all(): start_time = get_start_time(instrument) new_candles = candles.get_candles( instrument=instrument, start=start_time, order_by='start_time') for i in range(len(new_candles) - 1): all_new_samples.append( build_sample_row(new_candles[i], new_candles[i + 1])) ts.insert_many(all_new_samples)
mit
DrFriendless/TradeMaximizerOz
src/Cycle.java
596
import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: john * Date: 11/12/2010 * Time: 11:37:11 AM * To change this template use File | Settings | File Templates. */ public class Cycle { private List<Vertex> vertices; private long cost; Cycle(List<Vertex> vertices, long cost) { this.vertices = vertices; this.cost = cost; } int size() { return vertices.size(); } List<Vertex> getVertices() { return new ArrayList<Vertex>(vertices); } long getCost() { return cost; } }
mit
aki-russia/node
lib/translator.js
601
var lingo = require('lingo'), fs = require('fs'), join = require('path').join, _ = require("underscore"), conf_path = null, translations = null; exports.create = function(siteDir, lang_code){ conf_path = join(siteDir, 'config/locales/' + lang_code + '.json'); translations = JSON.parse(fs.readFileSync(conf_path)); // ru.translations = {}; return function(path){ var path = path.split("."); var words = translations; while(path.length && words){ words = words[path.shift()]; } return _.isString(words) ? words : "translation missing for " + path; }; };
mit
ActiveState/code
recipes/Python/576526_compare_making_filter_fun_again/recipe-576526.py
1104
class compare(object): def __init__(self, function): self.function = function def __eq__(self, other): def c(l, r): return l == r return comparator(self.function, c, other) def __ne__(self, other): def c(l, r): return l != r return comparator(self.function, c, other) def __lt__(self, other): def c(l, r): return l < r return comparator(self.function, c, other) def __le__(self, other): def c(l, r): return l <= r return comparator(self.function, c, other) def __gt__(self, other): def c(l, r): return l > r return comparator(self.function, c, other) def __ge__(self, other): def c(l, r): return l >= r return comparator(self.function, c, other) class comparator(object): def __init__(self, function, comparison, value): self.function = function self.comparison = comparison self.value = value def __call__(self, *arguments, **keywords): return self.comparison(self.function(*arguments, **keywords), self.value)
mit
Burtt/IllumicatsVision
RaspberryPi/ScanForSingleTarget.py
1995
#! /usr/bin/env python import numpy as np import cv2 import visiontable display = False cap = cv2.VideoCapture(0) table = visiontable.VisionTable() lower_lim = np.array([60,60,60]) upper_lim = np.array([100,255,255]) minContourArea = 400 while(True): # Capture frame-by-frame ret, frame = cap.read() # find contours hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower_lim, upper_lim) contours, heirarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # draw contours if(display): imW = np.size(frame, 0) imH = np.size(frame, 1) img = np.zeros((imW,imH,3), np.uint8) img = cv2.drawContours(img, contours, -1, (255,255,0), 3) if(len(contours) > 0): # find biggest contour biggestContourIndex = 0 for i in range(len(contours)): if(cv2.contourArea(contours[i]) > cv2.contourArea(contours[biggestContourIndex])): biggestContourIndex = i # Check if biggest contour is big enough if(cv2.contourArea(contours[biggestContourIndex]) > minContourArea): # find center rect = cv2.minAreaRect(contours[biggestContourIndex]) bx = int((rect[0][0] + rect[1][0])/2) by = int((rect[0][1] + rect[1][1])/2) # draw center if(display): box = np.int0(box) img = cv2.drawContours(img,[box],0,(0,0,255),1) img = cv2.circle(img,(bx,by),4,(0,255,255),-1) # publish results to dashboard table.update(True, bx, by) print str(bx) + " " + str(by) # Otherwise, assume it is noise else: table.update(False) else: table.update(False) # Display the resulting frame if(display): cv2.imshow('frame',img) # When everything's done, release the capture cap.release() cv2.destroyAllWindows()
mit
Kofel/Gutenberg
src/Gutenberg/Printable/ZPLPrintable.php
1898
<?php /** * Created by IntelliJ IDEA. * User: kofel * Date: 03.02.15 * Time: 10:43 */ namespace Gutenberg\Printable; use Gutenberg\Printable\ZPL\PreprocessorInterface; use Gutenberg\Printable\ZPL\Replacer\GRFQrCodeReplacer; use Gutenberg\Printable\ZPL\Replacer\VariableReplacer; class ZPLPrintable implements PrintableInterface { /** * @var string */ private $zpl; /** * @var PreprocessorInterface[] */ private $preprocessors = []; /** * @var array */ private $params = []; /** * ZPLPrintable constructor. * @param string $zpl * @param ZPL\PreprocessorInterface[] $preprocessors */ public function __construct($zpl, array $preprocessors) { $this->zpl = $zpl; $this->preprocessors = $preprocessors; } /** * Add preprocessor * * @param PreprocessorInterface $preprocessor * @return $this */ public function addPreprocessor(PreprocessorInterface $preprocessor) { $this->preprocessors[] = $preprocessor; return $this; } /** * Bind printable parameters * * @param $params */ public function setParams(array $params) { $this->params = $params; } /** * Get original ZPL source * * @return string */ public function getOriginalContent() { return $this->zpl; } /** * Get preprocessed content * * @return string */ public function getContent() { return $this->processContent($this->zpl, $this->params); } /** * @param $zpl * @param $params * @return string */ private function processContent($zpl, $params) { foreach ($this->preprocessors as $preprocessor) { $zpl = $preprocessor->replace($zpl, $params); } return $zpl; } }
mit
magpiemac/Your-Wardrobe-Tracker
db/migrate/20171003085925_create_wardrobe_items.rb
196
class CreateWardrobeItems < ActiveRecord::Migration[5.0] def change create_table :wardrobe_items do |t| t.string :item t.string :description t.timestamps end end end
mit
hartmannr76/EasyIoC
EasyIoC/Finders/AssemblyFinder.cs
1080
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyModel; namespace EasyIoC.Finders { public class AssemblyFinder { private readonly HashSet<string> _defaultIgnoredAssemblies = new HashSet<string>() { "Microsoft.", "System." }; public ImmutableList<Assembly> FindAssemblies(HashSet<string> ignoredAssemblies) { var ctx = DependencyContext.Default; ignoredAssemblies = ignoredAssemblies ?? _defaultIgnoredAssemblies; var assemblyNames = from lib in ctx.RuntimeLibraries from assemblyName in lib.GetDefaultAssemblyNames(ctx) where ignoredAssemblies.Any(x => !assemblyName.Name.StartsWith(x)) select assemblyName; var lookup = assemblyNames.ToLookup(x => x.Name).Select(x => x.First()); var asList = lookup.Select(Assembly.Load).ToImmutableList(); return asList; } } }
mit
suzdalnitski/Zenject
UnityProject/Assets/Plugins/Zenject/OptionalExtras/UnitTests/Editor/Factories/Bindings/TestFactoryFromResolve0.cs
1841
using System; using System.Collections.Generic; using System.Linq; using Zenject; using NUnit.Framework; using ModestTree; using Assert=ModestTree.Assert; namespace Zenject.Tests.Bindings { [TestFixture] public class TestFactoryFromResolve0 : ZenjectUnitTestFixture { [Test] public void TestSelf() { var foo = new Foo(); Container.BindInstance(foo).NonLazy(); Container.BindFactory<Foo, Foo.Factory>().FromResolve().NonLazy(); Assert.IsEqual(Container.Resolve<Foo.Factory>().Create(), foo); } [Test] public void TestConcrete() { var foo = new Foo(); Container.BindInstance(foo).NonLazy(); Container.BindFactory<IFoo, IFooFactory>().To<Foo>().FromResolve().NonLazy(); Assert.IsEqual(Container.Resolve<IFooFactory>().Create(), foo); } [Test] public void TestSelfIdentifier() { var foo = new Foo(); Container.BindInstance(foo).WithId("foo").NonLazy(); Container.BindFactory<Foo, Foo.Factory>().FromResolve("foo").NonLazy(); Assert.IsEqual(Container.Resolve<Foo.Factory>().Create(), foo); } [Test] public void TestConcreteIdentifier() { var foo = new Foo(); Container.BindInstance(foo).WithId("foo").NonLazy(); Container.BindFactory<IFoo, IFooFactory>().To<Foo>().FromResolve("foo").NonLazy(); Assert.IsEqual(Container.Resolve<IFooFactory>().Create(), foo); } interface IFoo { } class IFooFactory : Factory<IFoo> { } class Foo : IFoo { public class Factory : Factory<Foo> { } } } }
mit
MysteryCoin/MysteryCoinHasSecrets
src/qt/locale/bitcoin_zh_TW.ts
113338
<?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Bitcoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Bitcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;位元幣&lt;/b&gt;版本</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> 這是一套實驗性的軟體. 此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php. 此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>版權</translation> </message> <message> <location line="+0"/> <source>The Bitcoin developers</source> <translation>位元幣開發人員</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>位址簿</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>點兩下來修改位址或標記</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>產生新位址</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>複製目前選取的位址到系統剪貼簿</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>新增位址</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>複製位址</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>顯示 &amp;QR 條碼</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Bitcoin address</source> <translation>簽署訊息是用來證明位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>從列表中刪除目前選取的位址</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Bitcoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>刪除</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>編輯</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>付錢</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>匯出位址簿資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號區隔資料檔 (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入檔案 %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(沒有標記)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>密碼對話視窗</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>輸入密碼</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>新的密碼</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>重複新密碼</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>輸入錢包的新密碼.&lt;br/&gt;請用&lt;b&gt;10個以上的字元&lt;/b&gt;, 或是&lt;b&gt;8個以上的單字&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>錢包加密</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>這個動作需要用你的錢包密碼來解鎖</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>錢包解鎖</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>這個動作需要用你的錢包密碼來解密</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>錢包解密</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>變更密碼</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>輸入錢包的新舊密碼.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>錢包加密確認</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>警告: 如果將錢包加密後忘記密碼, 你會&lt;b&gt;失去其中所有的位元幣&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>你確定要將錢包加密嗎?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>警告: 大寫字母鎖定作用中!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>錢包已加密</translation> </message> <message> <location line="-56"/> <source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source> <translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>錢包加密失敗</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>提供的密碼不符.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>錢包解鎖失敗</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>用來解密錢包的密碼輸入錯誤.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>錢包解密失敗</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>錢包密碼變更成功.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>訊息簽署...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>網路同步中...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>總覽</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>顯示錢包一般總覽</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>交易</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>瀏覽交易紀錄</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>編輯位址與標記的儲存列表</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>顯示收款位址的列表</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>結束</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>結束應用程式</translation> </message> <message> <location line="+4"/> <source>Show information about Bitcoin</source> <translation>顯示位元幣相關資訊</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>關於 &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>顯示有關於 Qt 的資訊</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>選項...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>錢包加密...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>錢包備份...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>密碼變更...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>從磁碟匯入區塊中...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>重建磁碟區塊索引中...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Bitcoin address</source> <translation>付錢到位元幣位址</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Bitcoin</source> <translation>修改位元幣的設定選項</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>將錢包備份到其它地方</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>變更錢包加密用的密碼</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>除錯視窗</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>開啓除錯與診斷主控台</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>驗證訊息...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Bitcoin</source> <translation>位元幣</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>付出</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>收受</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>位址</translation> </message> <message> <location line="+22"/> <source>&amp;About Bitcoin</source> <translation>關於位元幣</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>顯示或隱藏</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>顯示或隱藏主視窗</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>將屬於你的錢包的密鑰加密</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Bitcoin addresses to prove you own them</source> <translation>用位元幣位址簽署訊息來證明那是你的</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Bitcoin addresses</source> <translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>檔案</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>設定</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>求助</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>分頁工具列</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Bitcoin client</source> <translation>位元幣客戶端軟體</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Bitcoin network</source> <translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>目前沒有區塊來源...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>已處理了 %1 個區塊的交易紀錄.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n 個小時</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n 天</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n 個星期</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>落後 %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>最近收到的區塊是在 %1 之前生產出來.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>會看不見在這之後的交易.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>最新狀態</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>進度追趕中...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>確認交易手續費</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>付款交易</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>收款交易</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>日期: %1 金額: %2 類別: %3 位址: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI 處理</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source> <translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;解鎖中&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>錢包&lt;b&gt;已加密&lt;/b&gt;並且正&lt;b&gt;上鎖中&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source> <translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>網路警報</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>編輯位址</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>標記</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>與這個位址簿項目關聯的標記</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>位址</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>新收款位址</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>新增付款位址</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>編輯收款位址</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>編輯付款位址</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>輸入的位址&quot;%1&quot;已存在於位址簿中.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Bitcoin address.</source> <translation>輸入的位址 &quot;%1&quot; 並不是有效的位元幣位址.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>無法將錢包解鎖.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>新密鑰產生失敗.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Bitcoin-Qt</source> <translation>位元幣-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>版本</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>使用界面選項</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>設定語言, 比如說 &quot;de_DE&quot; (預設: 系統語系)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>啓動時最小化 </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>顯示啓動畫面 (預設: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>選項</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>主要</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>付交易手續費</translation> </message> <message> <location line="+31"/> <source>Automatically start Bitcoin after logging in to the system.</source> <translation>在登入系統後自動啓動位元幣.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Bitcoin on system login</source> <translation>系統登入時啟動位元幣</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>回復所有客戶端軟體選項成預設值.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>選項回復</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>網路</translation> </message> <message> <location line="+6"/> <source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>自動在路由器上開啟 MysteryCoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>用 &amp;UPnP 設定通訊埠對應</translation> </message> <message> <location line="+7"/> <source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>透過 SOCKS 代理伺服器連線:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>代理伺服器位址:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>通訊埠:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>代理伺服器的通訊埠 (比如說 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS 協定版本:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>視窗</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>最小化視窗後只在通知區域顯示圖示</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>最小化至通知區域而非工作列</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>關閉時最小化</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>顯示</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>使用界面語言</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source> <translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>金額顯示單位:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>選擇操作界面與付錢時預設顯示的細分單位.</translation> </message> <message> <location line="+9"/> <source>Whether to show Bitcoin addresses in the transaction list or not.</source> <translation>是否要在交易列表中顯示位元幣位址.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>在交易列表顯示位址</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>好</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>取消</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>套用</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>預設</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>確認回復選項</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>你想要就做下去嗎?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Bitcoin.</source> <translation>這個設定會在位元幣程式重啓後生效.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>提供的代理伺服器位址無效</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source> <translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>未確認額:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>錢包</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>未熟成</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>尚未熟成的開採金額</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;最近交易&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>目前餘額</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>尚未確認之交易的總額, 不包含在目前餘額中</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>沒同步</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start bitcoin: click-to-pay handler</source> <translation>無法啟動 mysterycoin 隨按隨付處理器</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR 條碼對話視窗</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>付款單</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>金額:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>標記:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>訊息:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>儲存為...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>將 URI 編碼成 QR 條碼失敗</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>輸入的金額無效, 請檢查看看.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>儲存 QR 條碼</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG 圖檔 (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>客戶端軟體名稱</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>無</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>客戶端軟體版本</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>資訊</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>使用 OpenSSL 版本</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>啓動時間</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>網路</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>連線數</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>位於測試網路</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>區塊鎖鏈</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>目前區塊數</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>估計總區塊數</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>最近區塊時間</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>開啓</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>命令列選項</translation> </message> <message> <location line="+7"/> <source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source> <translation>顯示位元幣-Qt的求助訊息, 來取得可用的命令列選項列表.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>顯示</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>主控台</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>建置日期</translation> </message> <message> <location line="-104"/> <source>Bitcoin - Debug window</source> <translation>位元幣 - 除錯視窗</translation> </message> <message> <location line="+25"/> <source>Bitcoin Core</source> <translation>位元幣核心</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>除錯紀錄檔</translation> </message> <message> <location line="+7"/> <source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>清主控台</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Bitcoin RPC console.</source> <translation>歡迎使用位元幣 RPC 主控台.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>請用上下游標鍵來瀏覽歷史指令, 且可用 &lt;b&gt;Ctrl-L&lt;/b&gt; 來清理畫面.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>請打 &lt;b&gt;help&lt;/b&gt; 來看可用指令的簡介.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>付錢</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>一次付給多個人</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>加收款人</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>移除所有交易欄位</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>餘額:</translation> </message> <message> <location line="+10"/> <source>123.456 MYST</source> <translation>123.456 MYST</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>確認付款動作</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>付出</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; 給 %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>確認要付錢</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>確定要付出 %1 嗎?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>和</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>無效的收款位址, 請再檢查看看.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>付款金額必須大於 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>金額超過餘額了.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>錯誤: 交易產生失敗!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>表單</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>金額:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>付給:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>輸入一個標記給這個位址, 並加到位址簿中</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>標記:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>從位址簿中選一個位址</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>去掉這個收款人</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>簽章 - 簽署或驗證訊息</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>從位址簿選一個位址</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>從剪貼簿貼上位址</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>在這裡輸入你想簽署的訊息</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>簽章</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>複製目前的簽章到系統剪貼簿</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Bitcoin address</source> <translation>簽署訊息是用來證明這個位元幣位址是你的</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>訊息簽署</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>重置所有訊息簽署欄位</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>全部清掉</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用&quot;中間人攻擊法&quot;詐騙.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Bitcoin address</source> <translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>訊息驗證</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>重置所有訊息驗證欄位</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>按&quot;訊息簽署&quot;來產生簽章</translation> </message> <message> <location line="+3"/> <source>Enter Bitcoin signature</source> <translation>輸入位元幣簽章</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>輸入的位址無效.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>請檢查位址是否正確後再試一次.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>輸入的位址沒有指到任何密鑰.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>錢包解鎖已取消.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>沒有所輸入位址的密鑰.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>訊息簽署失敗.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>訊息已簽署.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>無法將這個簽章解碼.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>請檢查簽章是否正確後再試一次.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>這個簽章與訊息的數位摘要不符.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>訊息驗證失敗.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>訊息已驗證.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Bitcoin developers</source> <translation>位元幣開發人員</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/離線中</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/未確認</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>經確認 %1 次</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>狀態</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, 已公告至 %n 個節點</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>來源</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>生產出</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>來處</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>目的</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>自己的位址</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>標籤</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>入帳</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>不被接受</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>出帳</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>交易手續費</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>淨額</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>訊息</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>附註</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>交易識別碼</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>生產出來的錢要再等 120 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成&quot;不被接受&quot;, 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>除錯資訊</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>交易</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>輸入</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>是</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>否</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, 尚未成功公告出去</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>未知</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>交易明細</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>此版面顯示交易的詳細說明</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>金額</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>在 %1 前未定</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>離線中 (經確認 %1 次)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>已確認 (經確認 %1 次)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>生產出但不被接受</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>收受自</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>付給自己</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(不適用)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>收到交易的日期與時間.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>交易的種類.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>交易的目標位址.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>減去或加入至餘額的金額</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>全部</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>今天</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>這週</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>這個月</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>上個月</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>今年</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>指定範圍...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>收受於</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>付出至</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>給自己</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>開採所得</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>其他</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>輸入位址或標記來搜尋</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>最小金額</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>複製位址</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>複製標記</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>複製金額</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>複製交易識別碼</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>編輯標記</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>顯示交易明細</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>匯出交易資料</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>逗號分隔資料檔 (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>已確認</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>日期</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>種類</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>標記</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>位址</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>金額</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>識別碼</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>匯出失敗</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>無法寫入至 %1 檔案.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>範圍:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>至</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>付錢</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>匯出</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>將目前分頁的資料匯出存成檔案</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>錢包備份</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>錢包資料檔 (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>備份失敗</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>儲存錢包資料到新的地方失敗</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>備份成功</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>錢包的資料已經成功儲存到新的地方了.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Bitcoin version</source> <translation>位元幣版本</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>用法:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or bitcoind</source> <translation>送指令給 -server 或 bitcoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>列出指令 </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>取得指令說明 </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>選項: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation>指定設定檔 (預設: bitcoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation>指定行程識別碼檔案 (預設: bitcoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>指定資料目錄 </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 11030 or testnet: 5744)</source> <translation>在通訊埠 &lt;port&gt; 聽候連線 (預設: 11030, 或若為測試網路: 5744)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>維持與節點連線數的上限為 &lt;n&gt; 個 (預設: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>指定自己公開的位址</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 21030 or testnet: 5745)</source> <translation>在通訊埠 &lt;port&gt; 聽候 JSON-RPC 連線 (預設: 21030, 或若為測試網路: 5745)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>接受命令列與 JSON-RPC 指令 </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>以背景程式執行並接受指令</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>使用測試網路 </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Bitcoin Alert&quot; [email protected] </source> <translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword): %s 建議你使用以下隨機產生的密碼: rpcuser=bitcoinrpc rpcpassword=%s (你不用記住這個密碼) 使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同! 如果設定檔還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;. 也建議你設定警示通知, 發生問題時你才會被通知到; 比如說設定為: alertnotify=echo %%s | mail -s &quot;Bitcoin Alert&quot; [email protected] </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 &quot;[主機]:通訊埠&quot; 這種格式</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source> <translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Bitcoin will not work properly.</source> <translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>區塊產生選項:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>只連線至指定節點(可多個)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>發現區塊資料庫壞掉了</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>你要現在重建區塊資料庫嗎?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>初始化區塊資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>錢包資料庫環境 %s 初始化錯誤!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>載入區塊資料庫失敗</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>打開區塊資料庫檔案失敗</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>錯誤: 磁碟空間很少!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>錯誤: 系統錯誤:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>讀取區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>讀取區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>同步區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>寫入區塊索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>寫入區塊資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>寫入區塊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>寫入檔案資訊失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>寫入位元幣資料庫失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>寫入交易索引失敗</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>寫入回復資料失敗</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>生產位元幣 (預設值: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>檔案描述器不足.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>驗證區塊資料中...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>驗證錢包資料中...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>從其它來源的 blk000??.dat 檔匯入區塊</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>資訊</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>無效的 -tor 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -minrelaytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -mintxfee=&lt;amount&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>維護全部交易的索引 (預設為 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>每個連線的接收緩衝區大小上限為 &lt;n&gt;*1000 個位元組 (預設: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>每個連線的傳送緩衝區大小上限為 &lt;n&gt;*1000 位元組 (預設: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>只和 &lt;net&gt; 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>輸出額外的網路除錯資訊</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>在除錯輸出內容前附加時間</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL 選項: (SSL 設定程序請見 MysteryCoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>輸出追蹤或除錯資訊給除錯器</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>設定區塊大小下限為多少位元組 (預設: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>簽署交易失敗</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>系統錯誤:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>交易金額太小</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>交易金額必須是正的</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>交易位元量太大</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC 連線使用者名稱</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>警告</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC 連線密碼</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>只允許從指定網路位址來的 JSON-RPC 連線</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>送指令給在 &lt;ip&gt; 的節點 (預設: 127.0.0.1) </translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>將錢包升級成最新的格式</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>設定密鑰池大小為 &lt;n&gt; (預設: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>於 JSON-RPC 連線使用 OpenSSL (https) </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>伺服器憑證檔 (預設: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>伺服器密鑰檔 (預設: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>此協助訊息 </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>透過 SOCKS 代理伺服器連線</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>載入位址中...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source> <translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 MysteryCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Bitcoin to complete</source> <translation>錢包需要重寫: 請重啟位元幣來完成</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>載入檔案 wallet.dat 失敗</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>無效的 -proxy 位址: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>在 -onlynet 指定了不明的網路別: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>在 -socks 指定了不明的代理協定版本: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>無法解析 -bind 位址: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>無法解析 -externalip 位址: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>設定 -paytxfee=&lt;金額&gt; 的金額無效: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>無效的金額</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>累積金額不足</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>載入區塊索引中...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source> <translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>交易付款時每 KB 的交易手續費</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>載入錢包中...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>無法將錢包格式降級</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>無法寫入預設位址</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>重新掃描中...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>載入完成</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>為了要使用 %s 選項</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>錯誤</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=&lt;password&gt;): %s 如果這個檔案還不存在, 請在新增時, 設定檔案權限為&quot;只有主人才能讀取&quot;.</translation> </message> </context> </TS>
mit
onzag/NotionScript
ast/statments/OPERATION/COMPARISON.js
511
let Statment = require('../base').Statment; let util = require('../../util'); const EQUALITY_OPERATORS = require('../../../basics/basics').CONTENT.EQUALITY_OPERATORS; let equalityOperatorsInverse = {}; Object.keys(EQUALITY_OPERATORS).forEach((key)=>{ if (key[0] === "."){ return; } let value = EQUALITY_OPERATORS[key]; equalityOperatorsInverse[value] = key; }) let COMPARISON = Statment.extend('OPERATION', 'COMPARISON', { 'values': Array, 'comparisonType': 'string' }); module.exports = COMPARISON;
mit
welovekpop/uwave-web-welovekpop.club
es/mobile/components/RoomHistory/Row.js
1089
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import React from 'react'; import PropTypes from 'prop-types'; import Avatar from "@material-ui/core/es/Avatar"; import ListItem from "@material-ui/core/es/ListItem"; import ListItemAvatar from "@material-ui/core/es/ListItemAvatar"; import ListItemText from "@material-ui/core/es/ListItemText"; import Votes from './Votes'; var wrapTitle = function wrapTitle(title) { return _jsx("span", { className: "MobileMediaRow-title" }, void 0, title); }; var HistoryRow = function HistoryRow(_ref) { var media = _ref.media; return _jsx(ListItem, { className: "MobileMediaRow" }, void 0, _jsx(ListItemAvatar, {}, void 0, _jsx(Avatar, { src: media.media.thumbnail, style: { borderRadius: 0 } })), _jsx(ListItemText, { primary: wrapTitle(media.media.title), secondary: media.media.artist }), React.createElement(Votes, media.stats)); }; HistoryRow.propTypes = process.env.NODE_ENV !== "production" ? { media: PropTypes.object } : {}; export default HistoryRow; //# sourceMappingURL=Row.js.map
mit
isuttell/ceres-framework
spec/controllers/warpRoute_spec.js
2751
const Promise = require('bluebird'); const wrapRoute = require('../../src/controllers/wrapRoute'); describe('wrapRoute', () => { let ceres; beforeEach(() => { ceres = { log: { internal: { debug() {}, }, }, }; }); it('should return a function', () => { function handler() {} const ctx = {}; let result; expect(() => { result = wrapRoute(handler, ctx, ceres); }).not.toThrow(); expect(typeof result).toBe('function'); }); it('should extend "this" with any custom properties', () => { let result; function handler() { result = this; } const ctx = { extend: true, }; expect(() => { const wrappedFunction = wrapRoute(handler, ctx, ceres); wrappedFunction().finally(() => { expect(result.extend).toBe(ctx.extend); }); }).not.toThrow(); }); it('should assign "req", "res", "next" to "this" of the handler', () => { let result; function handler() { result = this; } const ctx = {}; const req = {}; const res = {}; const next = () => {}; expect(() => { const wrappedFunction = wrapRoute(handler, ctx, ceres); wrappedFunction(req, res, next).finally(() => { expect(result.req).toBe(req); expect(result.res).toBe(res); expect(result.next).toBe(next); }); }).not.toThrow(); }); it('should call the "next" handler if theres an error', () => { const err = new Error('ERROR'); const handler = () => { throw err; }; const ctx = {}; const next = jest.fn(); const wrappedFunction = wrapRoute(handler, ctx, ceres); wrappedFunction({}, {}, next).then(() => { expect(next).toHaveBeenCalledWith(err); }); }); it('should automatically "send" the result of a promise', done => { const expected = { results: [], }; const handler = () => expected; const ctx = { send: jest.fn(), }; const res = { writable: true, headerSent: false, }; const fn = wrapRoute(handler, ctx, ceres); fn({}, res, () => {}) .then(() => { expect(ctx.send).toHaveBeenCalledWith(expected); }) .finally(() => { done(); }); }); it('should not write the response if is not writable', () => { const expected = { results: [], }; function handler() { return new Promise(resolve => { resolve(expected); }); } const ctx = { send: jest.fn(), }; const res = { writable: false, }; const fn = wrapRoute(handler, ctx, ceres); return fn({}, res, () => {}).then(() => { expect(ctx.send).not.toHaveBeenCalled(); }); }); });
mit
3zcurdia/badger
assets/badger.min.js
52
//= require_directory ./javascripts //= require_self
mit
DrLSimon/CGILabs
utils/vboindexer.cpp
7397
#include <vector> #include <map> #include <unordered_map> #include <glm/glm.hpp> #include "utils/vboindexer.h" #include <string.h> // for memcmp // Returns true iif v1 can be considered equal to v2 bool is_near(float v1, float v2){ return fabs( v1-v2 ) < 0.01f; } // Searches through all already-exported vertices // for a similar one. // Similar = same position + same UVs + same normal bool getSimilarVertexIndex( glm::vec3 & in_vertex, glm::vec2 & in_uv, glm::vec3 & in_normal, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, unsigned int & result ){ // Lame linear search for ( unsigned int i=0; i<out_vertices.size(); i++ ){ if ( is_near( in_vertex.x , out_vertices[i].x ) && is_near( in_vertex.y , out_vertices[i].y ) && is_near( in_vertex.z , out_vertices[i].z ) && is_near( in_uv.x , out_uvs [i].x ) && is_near( in_uv.y , out_uvs [i].y ) && is_near( in_normal.x , out_normals [i].x ) && is_near( in_normal.y , out_normals [i].y ) && is_near( in_normal.z , out_normals [i].z ) ){ result = i; return true; } } // No other vertex could be used instead. // Looks like we'll have to add it to the VBO. return false; } void indexVBO_slow( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<unsigned int> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ){ // For each input vertex for ( unsigned int i=0; i<in_vertices.size(); i++ ){ // Try to find a similar vertex in out_XXXX unsigned int index; bool found = getSimilarVertexIndex(in_vertices[i], in_uvs[i], in_normals[i], out_vertices, out_uvs, out_normals, index); if ( found ){ // A similar vertex is already in the VBO, use it instead ! out_indices.push_back( index ); }else{ // If not, it needs to be added in the output data. out_vertices.push_back( in_vertices[i]); out_uvs .push_back( in_uvs[i]); out_normals .push_back( in_normals[i]); out_indices .push_back( (unsigned int)out_vertices.size() - 1 ); } } } struct PackedVertex{ glm::vec3 position; glm::vec2 uv; glm::vec3 normal; bool operator<(const PackedVertex that) const{ return memcmp((void*)this, (void*)&that, sizeof(PackedVertex))>0; }; }; bool getSimilarVertexIndex_fast( PackedVertex & packed, std::map<PackedVertex,unsigned int> & VertexToOutIndex, unsigned int & result ){ std::map<PackedVertex,unsigned int>::iterator it = VertexToOutIndex.find(packed); if ( it == VertexToOutIndex.end() ){ return false; }else{ result = it->second; return true; } } void indexVBO( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<unsigned int> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ){ std::map<PackedVertex,unsigned int> VertexToOutIndex; // For each input vertex for ( unsigned int i=0; i<in_vertices.size(); i++ ){ PackedVertex packed = {in_vertices[i], in_uvs[i], in_normals[i]}; // Try to find a similar vertex in out_XXXX unsigned int index; bool found = getSimilarVertexIndex_fast( packed, VertexToOutIndex, index); if ( found ){ // A similar vertex is already in the VBO, use it instead ! out_indices.push_back( index ); }else{ // If not, it needs to be added in the output data. out_vertices.push_back( in_vertices[i]); out_uvs .push_back( in_uvs[i]); out_normals .push_back( in_normals[i]); unsigned int newindex = (unsigned int)out_vertices.size() - 1; out_indices .push_back( newindex ); VertexToOutIndex[ packed ] = newindex; } } } //!loic: changing the way to lookup vertices to make it faster // comparison operators for glm::vec/*{{{*/ bool is_near(const glm::vec3 &vecA, const glm::vec3 &vecB) { return is_near(vecA[0], vecB[0]) and is_near(vecA[1], vecB[1]) and is_near(vecA[2], vecB[2]); } bool is_near(const glm::vec2 &vecA, const glm::vec2 &vecB) { return is_near(vecA[0], vecB[0]) and is_near(vecA[1], vecB[1]); } /*}}}*/ struct PackedVertexPTNUV/*{{{*/ { glm::vec3 position; glm::vec3 normal; glm::vec3 tangent; glm::vec2 uv; PackedVertexPTNUV(glm::vec3 position=glm::vec3(), glm::vec3 normal=glm::vec3(), glm::vec3 tangent=glm::vec3(), glm::vec2 uv=glm::vec2()):position(position), normal(normal), tangent(tangent), uv(uv){} bool operator==(const PackedVertexPTNUV& other) const { return is_near(position, other.position) and is_near(normal, other.normal) and is_near(tangent, other.tangent) and is_near(uv, other.uv); } };/*}}}*/ // Template specialization of std::hash {{{ namespace std{ template<> struct hash<PackedVertexPTNUV> { public: std::size_t operator()(const PackedVertexPTNUV& v) const { std::size_t hashes[]={ std::hash<float>()(v.position.x), std::hash<float>()(v.position.y), std::hash<float>()(v.position.z), std::hash<float>()(v.normal.x), std::hash<float>()(v.normal.y), std::hash<float>()(v.normal.z), std::hash<float>()(v.tangent.x), std::hash<float>()(v.tangent.y), std::hash<float>()(v.tangent.z), std::hash<float>()(v.uv.x), std::hash<float>()(v.uv.y)}; std::size_t seed=0; for(std::size_t h : hashes) { // from boost::hash_combine seed ^= h + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; }/*}}}*/ void indexVBO_TBN( std::vector<glm::vec3> & in_vertices, std::vector<glm::vec2> & in_uvs, std::vector<glm::vec3> & in_normals, std::vector<glm::vec3> & in_tangents, std::vector<glm::vec3> & in_bitangents, std::vector<unsigned int> & out_indices, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals, std::vector<glm::vec3> & out_tangents, std::vector<glm::vec3> & out_bitangents ){ std::unordered_map<PackedVertexPTNUV, unsigned int> vert_indices; // For each input vertex for ( unsigned int i=0; i<in_vertices.size(); i++ ){ // Try to find a similar vertex in out_XXXX unsigned int index; PackedVertexPTNUV v(in_vertices[i], in_normals[i], in_tangents[i], in_uvs[i]); bool found = vert_indices.find(v)!=vert_indices.end(); if ( found ){ // A similar vertex is already in the VBO, use it instead ! index=vert_indices[v]; out_indices.push_back( index ); }else{ // If not, it needs to be added in the output data. out_vertices.push_back( in_vertices[i]); out_uvs .push_back( in_uvs[i]); out_normals .push_back( in_normals[i]); out_tangents .push_back( in_tangents[i]); out_bitangents .push_back( in_bitangents[i]); index=(unsigned int)out_vertices.size() - 1; out_indices.push_back(index); vert_indices[v]=index; } } } // vim: set foldmethod=marker :
mit
brian831/Cashoo
Brian831/src/CashooBundle/Resources/Interfaces/HandlerInterface.php
330
<?php namespace Brian831\CashooBundle\Resources\Interfaces; interface HandlerInterface { public function exists($index); public function getCreatedAt($index); public function getContent($index); public function setContent($index,$content); public function delete($index); }
mit
rossipedia/toml-net
toml-net/Parser/KeyValue.cs
603
namespace Toml.Parser { internal class KeyValue { private readonly string key; private readonly object value; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public KeyValue(string key, object value) { this.key = key; this.value = value; } public string Key { get { return this.key; } } public object Value { get { return this.value; } } } }
mit
dotnet/roslyn-analyzers
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotPassLiteralsAsLocalizedParameters.cs
19552
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.NetAnalyzers; namespace Microsoft.NetCore.Analyzers.Runtime { using static MicrosoftNetCoreAnalyzersResources; /// <summary> /// CA1303: Do not pass literals as localized parameters /// A method passes a string literal as a parameter to a constructor or method in the .NET Framework class library and that string should be localizable. /// This warning is raised when a literal string is passed as a value to a parameter or property and one or more of the following cases is true: /// 1. The LocalizableAttribute attribute of the parameter or property is set to true. /// 2. The parameter or property name contains "Text", "Message", or "Caption". /// 3. The name of the string parameter that is passed to a Console.Write or Console.WriteLine method is either "value" or "format". /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotPassLiteralsAsLocalizedParameters : AbstractGlobalizationDiagnosticAnalyzer { internal const string RuleId = "CA1303"; internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( RuleId, CreateLocalizableResourceString(nameof(DoNotPassLiteralsAsLocalizedParametersTitle)), CreateLocalizableResourceString(nameof(DoNotPassLiteralsAsLocalizedParametersMessage)), DiagnosticCategory.Globalization, RuleLevel.Disabled, description: CreateLocalizableResourceString(nameof(DoNotPassLiteralsAsLocalizedParametersDescription)), isPortedFxCopRule: true, isDataflowRule: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); protected override void InitializeWorker(CompilationStartAnalysisContext context) { INamedTypeSymbol? localizableStateAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelLocalizableAttribute); INamedTypeSymbol? conditionalAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute); INamedTypeSymbol? systemConsoleSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole); ImmutableHashSet<INamedTypeSymbol> typesToIgnore = GetTypesToIgnore(context.Compilation); context.RegisterOperationBlockStartAction(operationBlockStartContext => { if (operationBlockStartContext.OwningSymbol is not IMethodSymbol containingMethod || operationBlockStartContext.Options.IsConfiguredToSkipAnalysis(Rule, containingMethod, operationBlockStartContext.Compilation)) { return; } Lazy<DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>?> lazyValueContentResult = new Lazy<DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>?>( valueFactory: ComputeValueContentAnalysisResult, isThreadSafe: false); operationBlockStartContext.RegisterOperationAction(operationContext => { var argument = (IArgumentOperation)operationContext.Operation; IMethodSymbol? targetMethod = null; switch (argument.Parent) { case IInvocationOperation invocation: targetMethod = invocation.TargetMethod; break; case IObjectCreationOperation objectCreation: targetMethod = objectCreation.Constructor; break; } if (ShouldAnalyze(targetMethod)) { AnalyzeArgument(argument.Parameter, containingPropertySymbol: null, operation: argument, reportDiagnostic: operationContext.ReportDiagnostic, GetUseNamingHeuristicOption(operationContext)); } }, OperationKind.Argument); operationBlockStartContext.RegisterOperationAction(operationContext => { var propertyReference = (IPropertyReferenceOperation)operationContext.Operation; if (propertyReference.Parent is IAssignmentOperation assignment && assignment.Target == propertyReference && !propertyReference.Property.IsIndexer && propertyReference.Property.SetMethod?.Parameters.Length == 1 && ShouldAnalyze(propertyReference.Property)) { IParameterSymbol valueSetterParam = propertyReference.Property.SetMethod.Parameters[0]; AnalyzeArgument(valueSetterParam, propertyReference.Property, assignment, operationContext.ReportDiagnostic, GetUseNamingHeuristicOption(operationContext)); } }, OperationKind.PropertyReference); return; // Local functions bool ShouldAnalyze(ISymbol? symbol) => symbol != null && !operationBlockStartContext.Options.IsConfiguredToSkipAnalysis(Rule, symbol, operationBlockStartContext.OwningSymbol, operationBlockStartContext.Compilation); static bool GetUseNamingHeuristicOption(OperationAnalysisContext operationContext) => operationContext.Options.GetBoolOptionValue(EditorConfigOptionNames.UseNamingHeuristic, Rule, operationContext.Operation.Syntax.SyntaxTree, operationContext.Compilation, defaultValue: false); void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol? containingPropertySymbol, IOperation operation, Action<Diagnostic> reportDiagnostic, bool useNamingHeuristic) { if (ShouldBeLocalized(parameter.OriginalDefinition, containingPropertySymbol?.OriginalDefinition, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore, useNamingHeuristic) && lazyValueContentResult.Value != null) { ValueContentAbstractValue stringContentValue = lazyValueContentResult.Value[operation.Kind, operation.Syntax]; if (stringContentValue.IsLiteralState) { Debug.Assert(!stringContentValue.LiteralValues.IsEmpty); if (stringContentValue.LiteralValues.Any(l => l is not string)) { return; } var stringLiteralValues = stringContentValue.LiteralValues.Cast<string?>(); // FxCop compat: Do not fire if the literal value came from a default parameter value if (stringContentValue.LiteralValues.Count == 1 && parameter.IsOptional && parameter.ExplicitDefaultValue is string defaultValue && defaultValue == stringLiteralValues.Single()) { return; } // FxCop compat: Do not fire if none of the string literals have any non-control character. if (!LiteralValuesHaveNonControlCharacters(stringLiteralValues)) { return; } // FxCop compat: Filter out xml string literals. IEnumerable<string> filteredStrings = stringLiteralValues.Where(literal => literal != null && !LooksLikeXmlTag(literal))!; if (filteredStrings.Any()) { // Method '{0}' passes a literal string as parameter '{1}' of a call to '{2}'. Retrieve the following string(s) from a resource table instead: "{3}". var arg1 = containingMethod.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); var arg2 = parameter.Name; var arg3 = parameter.ContainingSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); var arg4 = FormatLiteralValues(filteredStrings); var diagnostic = operation.CreateDiagnostic(Rule, arg1, arg2, arg3, arg4); reportDiagnostic(diagnostic); } } } } DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>? ComputeValueContentAnalysisResult() { var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph(); if (cfg != null) { var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationBlockStartContext.Compilation); return ValueContentAnalysis.TryGetOrComputeResult(cfg, containingMethod, wellKnownTypeProvider, operationBlockStartContext.Options, Rule, PointsToAnalysisKind.PartialWithoutTrackingFieldsAndProperties); } return null; } }); } private static ImmutableHashSet<INamedTypeSymbol> GetTypesToIgnore(Compilation compilation) { var builder = PooledHashSet<INamedTypeSymbol>.GetInstance(); var xmlWriter = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlWriter); if (xmlWriter != null) { builder.Add(xmlWriter); } var webUILiteralControl = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUILiteralControl); if (webUILiteralControl != null) { builder.Add(webUILiteralControl); } var unitTestingAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert); if (unitTestingAssert != null) { builder.Add(unitTestingAssert); } var unitTestingCollectionAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert); if (unitTestingCollectionAssert != null) { builder.Add(unitTestingCollectionAssert); } var unitTestingCollectionStringAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert); if (unitTestingCollectionStringAssert != null) { builder.Add(unitTestingCollectionStringAssert); } return builder.ToImmutableAndFree(); } private static bool ShouldBeLocalized( IParameterSymbol parameterSymbol, IPropertySymbol? containingPropertySymbol, INamedTypeSymbol? localizableStateAttributeSymbol, INamedTypeSymbol? conditionalAttributeSymbol, INamedTypeSymbol? systemConsoleSymbol, ImmutableHashSet<INamedTypeSymbol> typesToIgnore, bool useNamingHeuristic) { Debug.Assert(parameterSymbol.ContainingSymbol.Kind == SymbolKind.Method); if (parameterSymbol.Type.SpecialType != SpecialType.System_String) { return false; } // Verify LocalizableAttributeState if (localizableStateAttributeSymbol != null) { LocalizableAttributeState localizableAttributeState = GetLocalizableAttributeState(parameterSymbol, localizableStateAttributeSymbol); switch (localizableAttributeState) { case LocalizableAttributeState.False: return false; case LocalizableAttributeState.True: return true; default: break; } } // FxCop compat checks. if (typesToIgnore.Contains(parameterSymbol.ContainingType) || parameterSymbol.ContainingSymbol.HasAttribute(conditionalAttributeSymbol)) { return false; } // FxCop compat: For overrides, check for localizability of the corresponding parameter in the overridden method. var method = (IMethodSymbol)parameterSymbol.ContainingSymbol; if (method.IsOverride && method.OverriddenMethod?.Parameters.Length == method.Parameters.Length) { int parameterIndex = method.GetParameterIndex(parameterSymbol); IParameterSymbol overridenParameter = method.OverriddenMethod.Parameters[parameterIndex]; if (Equals(overridenParameter.Type, parameterSymbol.Type)) { return ShouldBeLocalized(overridenParameter, containingPropertySymbol, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore, useNamingHeuristic); } } if (useNamingHeuristic) { if (IsLocalizableByNameHeuristic(parameterSymbol) || containingPropertySymbol != null && IsLocalizableByNameHeuristic(containingPropertySymbol)) { return true; } } if (method.ContainingType.Equals(systemConsoleSymbol) && (method.Name.Equals("Write", StringComparison.Ordinal) || method.Name.Equals("WriteLine", StringComparison.Ordinal)) && (parameterSymbol.Name.Equals("format", StringComparison.OrdinalIgnoreCase) || parameterSymbol.Name.Equals("value", StringComparison.OrdinalIgnoreCase))) { return true; } return false; // FxCop compat: If a localizable attribute isn't defined then fall back to name heuristics. static bool IsLocalizableByNameHeuristic(ISymbol symbol) => symbol.Name.Equals("message", StringComparison.OrdinalIgnoreCase) || symbol.Name.Equals("text", StringComparison.OrdinalIgnoreCase) || symbol.Name.Equals("caption", StringComparison.OrdinalIgnoreCase); } private static LocalizableAttributeState GetLocalizableAttributeState(ISymbol symbol, INamedTypeSymbol localizableAttributeTypeSymbol) { if (symbol == null) { return LocalizableAttributeState.Undefined; } LocalizableAttributeState localizedState = GetLocalizableAttributeStateCore(symbol.GetAttributes(), localizableAttributeTypeSymbol); if (localizedState != LocalizableAttributeState.Undefined) { return localizedState; } ISymbol containingSymbol = (symbol as IMethodSymbol)?.AssociatedSymbol is IPropertySymbol propertySymbol ? propertySymbol : symbol.ContainingSymbol; return GetLocalizableAttributeState(containingSymbol, localizableAttributeTypeSymbol); } private static LocalizableAttributeState GetLocalizableAttributeStateCore(ImmutableArray<AttributeData> attributeList, INamedTypeSymbol localizableAttributeTypeSymbol) { var localizableAttribute = attributeList.FirstOrDefault(attr => localizableAttributeTypeSymbol.Equals(attr.AttributeClass)); if (localizableAttribute != null && localizableAttribute.AttributeConstructor.Parameters.Length == 1 && localizableAttribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Boolean && localizableAttribute.ConstructorArguments.Length == 1 && localizableAttribute.ConstructorArguments[0].Kind == TypedConstantKind.Primitive && localizableAttribute.ConstructorArguments[0].Value is bool isLocalizable) { return isLocalizable ? LocalizableAttributeState.True : LocalizableAttributeState.False; } return LocalizableAttributeState.Undefined; } private static string FormatLiteralValues(IEnumerable<string> literalValues) { var literals = new StringBuilder(); foreach (string literal in literalValues.Order()) { // sanitize the literal to ensure it's not multi-line // replace any newline characters with a space var sanitizedLiteral = literal.Replace((char)13, ' '); sanitizedLiteral = sanitizedLiteral.Replace((char)10, ' '); if (literals.Length > 0) { literals.Append(", "); } literals.Append(sanitizedLiteral); } return literals.ToString(); } /// <summary> /// Returns true if the given string looks like an XML/HTML tag /// </summary> private static bool LooksLikeXmlTag(string literal) { // Call the trim function to remove any spaces around the beginning and end of the string so we can more accurately detect // XML strings string trimmedLiteral = literal.Trim(); return trimmedLiteral.Length > 2 && trimmedLiteral[0] == '<' && trimmedLiteral[^1] == '>'; } /// <summary> /// Returns true if any character in literalValues is not a control character /// </summary> private static bool LiteralValuesHaveNonControlCharacters(IEnumerable<string?> literalValues) { foreach (string? literal in literalValues) { if (literal == null) { continue; } foreach (char ch in literal) { if (!char.IsControl(ch)) { return true; } } } return false; } } }
mit
sitepoint/the86-client
lib/the86-client/user.rb
280
module The86 module Client class User < Resource attribute :id, Integer attribute :name, String attribute :created_at, DateTime attribute :updated_at, DateTime has_many :access_tokens, ->{ AccessToken } path "users" end end end
mit
sergiojaviermoyano/cuyomateriales
application/views/login.php
2629
<body class="login-page"> <div class="login-box"> <div class="login-logo"> <a href="../../index2.html"><?php echo Globals::getTitle();?><b><?php echo Globals::getTitle2();?></b></a> </div><!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">Ingreso</p> <div> <div class="row"> <div class="col-xs-12"> <div class="alert alert-danger alert-dismissable" id="errorLgn" style="display: none"> <h4><i class="icon fa fa-ban"></i> Error!</h4> Revise los datos de acceso ingresados </div> </div> </div> <div class="form-group has-feedback"> <input type="email" class="form-control" placeholder="Usuario" id="usrName"> <span class="glyphicon glyphicon-user form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Contraseña" id="usrPassword"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-8"> </div><!-- /.col --> <div class="col-xs-4"> <button class="btn btn-primary btn-block btn-flat" id="login">Ingresar</button> </div><!-- /.col --> </div> </div> </div><!-- /.login-box-body --> </div><!-- /.login-box --> </body> <script> //A este script despùes llevarlo a un archivo js $('#login').click(function(){ var hayError = false; if($('#usrName').val() == '') { hayError = true; } if($('#usrPassword').val() == ''){ hayError = true; } if(hayError == true){ $('#errorLgn').fadeIn('slow'); return; } $('#errorLgn').fadeOut('hide'); WaitingOpen('Validando datos'); $.ajax({ type: 'POST', data: { usr: $('#usrName').val(), pas: $('#usrPassword').val() }, url: 'index.php/login/sessionStart_', success: function(result){ WaitingClose(); if(result == 0){ $('#errorLgn').fadeIn('slow'); }else{ window.location.href = 'dash'; } }, error: function(result){ WaitingClose(); $('#errorLgn').fadeIn('slow'); }, dataType: 'json' }); }); </script>
mit
RonenNess/GeonBit.UI
GeonBit.UI/Source/Entities/VerticalScrollbar.cs
9246
#region File Description //----------------------------------------------------------------------------- // Vertical scrollbar is used internally to scroll through lists etc. // // Author: Ronen Ness. // Since: 2016. //----------------------------------------------------------------------------- #endregion using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GeonBit.UI.Entities { /// <summary> /// Used internally as a scrollbar for lists, text boxes, etc.. /// </summary> public class VerticalScrollbar : Slider { /// <summary> /// Static ctor. /// </summary> static VerticalScrollbar() { Entity.MakeSerializable(typeof(VerticalScrollbar)); } // frame and mark actual height float _frameActualHeight = 0f; int _markHeight = 20; /// <summary> /// If true, will adjust max value automatically based on entities in parent. /// </summary> public bool AdjustMaxAutomatically = false; /// <summary>Default styling for vertical scrollbars. Note: loaded from UI theme xml file.</summary> new public static StyleSheet DefaultStyle = new StyleSheet(); /// <summary> /// Create the scrollbar. /// </summary> /// <param name="min">Min scrollbar value.</param> /// <param name="max">Max scrollbar value.</param> /// <param name="anchor">Position anchor.</param> /// <param name="offset">Offset from anchor position.</param> /// <param name="adjustMaxAutomatically">If true, the scrollbar will set its max value automatically based on entities in its parent.</param> public VerticalScrollbar(uint min, uint max, Anchor anchor = Anchor.Auto, Vector2? offset = null, bool adjustMaxAutomatically = false) : base(0, 0, USE_DEFAULT_SIZE, SliderSkin.Default, anchor, offset) { // set this scrollbar to respond even when direct parent is locked DoEventsIfDirectParentIsLocked = true; // set if need to adjust max automatically AdjustMaxAutomatically = adjustMaxAutomatically; // update default style UpdateStyle(DefaultStyle); } /// <summary> /// Create vertical scroll with default params. /// </summary> public VerticalScrollbar() : this(0, 10) { } /// <summary> /// Handle mouse down event. /// The Scrollbar entity override this function to handle sliding mark up and down, instead of left-right. /// </summary> override protected void DoOnMouseReleased() { // get mouse position and apply scroll value var mousePos = GetMousePos(_lastScrollVal.ToVector2()); // if mouse is on the min side, decrease by 1 if (mousePos.Y <= _destRect.Y + _frameActualHeight) { Value = _value - GetStepSize(); } // else if mouse is on the max side, increase by 1 else if (mousePos.Y >= _destRect.Bottom - _frameActualHeight) { Value = _value + GetStepSize(); } // call base function base.DoOnMouseReleased(); } /// <summary> /// Handle while mouse is down event. /// The Scrollbar entity override this function to handle sliding mark up and down, instead of left-right. /// </summary> override protected void DoWhileMouseDown() { // get mouse position and apply scroll value var mousePos = GetMousePos(_lastScrollVal.ToVector2()); // if in the middle calculate value based on mouse position if ((mousePos.Y >= _destRect.Y + _frameActualHeight * 0.5) && (mousePos.Y <= _destRect.Bottom - _frameActualHeight * 0.5)) { float relativePos = (mousePos.Y - _destRect.Y - _frameActualHeight * 0.5f - _markHeight * 0.5f); float internalHeight = (_destRect.Height - _frameActualHeight) - _markHeight * 0.5f; float relativeVal = (relativePos / internalHeight); Value = (int)System.Math.Round(Min + relativeVal * (Max - Min)); } // call event handler WhileMouseDown?.Invoke(this); } /// <summary> /// Draw the entity. /// </summary> /// <param name="spriteBatch">Sprite batch to draw on.</param> /// <param name="phase">The phase we are currently drawing.</param> override protected void DrawEntity(SpriteBatch spriteBatch, DrawPhase phase) { // if needed, recalc max (but not if currently interacting with this object). if (UserInterface.Active.ActiveEntity != this) { CalcAutoMaxValue(); } // get textures based on type Texture2D texture = Resources.VerticalScrollbarTexture; Texture2D markTexture = Resources.VerticalScrollbarMarkTexture; float FrameHeight = Resources.VerticalScrollbarData.FrameHeight; // draw scrollbar body UserInterface.Active.DrawUtils.DrawSurface(spriteBatch, texture, _destRect, new Vector2(0f, FrameHeight), 1, FillColor); // calc frame actual height and scaling factor (this is needed to calc frame width in pixels) Vector2 frameSizeTexture = new Vector2(texture.Width, texture.Height * FrameHeight); Vector2 frameSizeRender = frameSizeTexture; float ScaleYfac = _destRect.Width / frameSizeRender.X; // calc the size of the mark piece int markWidth = _destRect.Width; _markHeight = (int)(((float)markTexture.Height / (float)markTexture.Width) * (float)markWidth); // calc frame width in pixels _frameActualHeight = FrameHeight * texture.Height * ScaleYfac; // now draw mark float markY = _destRect.Y + _frameActualHeight + _markHeight * 0.5f + (_destRect.Height - _frameActualHeight * 2 - _markHeight) * (GetValueAsPercent()); Rectangle markDest = new Rectangle(_destRect.X, (int)System.Math.Round(markY) - _markHeight / 2, markWidth, _markHeight); UserInterface.Active.DrawUtils.DrawImage(spriteBatch, markTexture, markDest, FillColor); } /// <summary> /// Called every frame after update. /// Scrollbar override this function to handle wheel scroll while pointing on parent entity - we still want to capture that. /// </summary> override protected void DoAfterUpdate() { // if the active entity is self or parent, listen to mousewheel if (_isInteractable && (UserInterface.Active.ActiveEntity == this || UserInterface.Active.ActiveEntity == _parent || (UserInterface.Active.ActiveEntity != null && UserInterface.Active.ActiveEntity.IsDeepChildOf(_parent)))) { if (MouseInput.MouseWheelChange != 0) { Value = _value - MouseInput.MouseWheelChange * GetStepSize(); } } } /// <summary> /// Calculate max value based on siblings (note: only if AdjustMaxAutomatically is true) /// </summary> private void CalcAutoMaxValue() { // if need to adjust max automatically if (AdjustMaxAutomatically) { // get parent top int newMax = 0; int parentTop = Parent.InternalDestRect.Y; // iterate parent children to get the most bottom child foreach (var child in Parent._children) { // skip self if (child == this) continue; // skip internals if (child._hiddenInternalEntity) continue; // get current child bottom int bottom = child.GetActualDestRect().Bottom; // calc new max value int currNewMax = bottom - parentTop; newMax = System.Math.Max(newMax, currNewMax); } // remove parent size from result (the -4 is to give extra pixels down) newMax -= Parent.InternalDestRect.Height - 4; newMax = System.Math.Max(newMax, 0); // set new max value if (newMax != Max) { Max = (uint)newMax; } // set steps count StepsCount = (Max - Min) / 80; } } /// <summary> /// Handle when mouse wheel scroll and this entity is the active entity. /// Note: Scrollbar entity override this function to change scrollbar value based on wheel scroll, which is inverted. /// </summary> override protected void DoOnMouseWheelScroll() { Value = _value - MouseInput.MouseWheelChange * GetStepSize(); } } }
mit
solo123/travel_admin
app/models/pay_credit_card.rb
309
class PayCreditCard < ActiveRecord::Base belongs_to :payment belongs_to :account belongs_to :user_info belongs_to :order has_one :telephone, :as => :tel_number, :dependent => :destroy has_one :address, :as => :address_data, :dependent => :destroy default_scope {order(id: :desc)} end
mit
mpuncel/tty_helper
lib/tty_helper/version.rb
41
module TtyHelper VERSION = "0.0.1" end
mit
lorandszakacs/UPT-Projects
PRC/Java RMI - Peer to Peer Chat/CRAT/src/crat/client/Network.java
11156
package crat.client; import java.net.UnknownHostException; import java.rmi.AccessException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicBoolean; import crat.common.*; /** * This class handles all the connections: to the server and to other users */ public class Network { private final String myName; private final MainGUI mainWindow; private ServerInterface server; private final CopyOnWriteArraySet<User> users; private final ConnectionManager connectionManager; public Network( String myName, ServerInterface server, ReceiveConnectionRequestsI connections ){ this.myName = myName; this.server = server; this.users = new CopyOnWriteArraySet<User>(); this.mainWindow = WindowMain.createControlGUI( this.myName, this ); this.connectionManager = new ConnectionManager( myName,this.mainWindow, connections ); } public void start() { try { this.mainWindow.start(); this.connectionManager.start(); this.server.registerListener( this.myName, this.mainWindow.getServerListener() ); } catch (RemoteException e) { UserDialog .showError( "Cannot register ServerEventListener, the Available Users List will not be updated", "Register Listener" ); } catch (Exception e) { UserDialog.showError( "Unable to start application", "Network.start()" ); } } /** * @param userName */ public void showUserGUI( String userName ) { for (User user : this.users ) try { if ( user.getRemoteName().equals( userName ) ) { user.showGUI(); } } catch (Exception whatTheHell) { UserDialog.userTooStupidDialog( whatTheHell.getMessage() ); } } private final AtomicBoolean hasBeenClosed = new AtomicBoolean( false ); public void close() { if ( hasBeenClosed.compareAndSet( false, true ) ) { this.connectionManager.close(); try { server.disconnect( this.myName ); } catch (Exception ignore) {} } } /** * This class handles all user connection related issues */ private class ConnectionManager { /** * thread in which all connections requests from other users are handled */ private Thread requestHandler; /** * The thread in which all connections demanded by the user are established */ private Thread connectionSendThread; /** * This thread handles the disconnect requests from the user AND removes all * users that have disconnected on their own(e.g. by closing the application * and calling the method "disconnect" on the {@link SendMessagesI} ) */ private Thread disconnectHandler; private String myName; private MainGUI mainGUI; /** * The object through which we expect to receive connections, this is also * the object that we register at the server */ private ReceiveConnectionRequestsI connections; public ConnectionManager( String myName, MainGUI control, ReceiveConnectionRequestsI connRecv ){ this.myName = myName; this.mainGUI = control; this.connections = connRecv; Network.this.server = server; this.requestHandler = new Thread( new Runnable() { @Override public void run() { ConnectionManager.this.runInboundConnectionsThread(); } } ); this.disconnectHandler = new Thread( new Runnable() { @Override public void run() { ConnectionManager.this.runDisconnectThread(); } } ); this.connectionSendThread = new Thread( new Runnable() { @Override public void run() { ConnectionManager.this.runOutboundConnectionsThread(); } } ); } public void start() { this.requestHandler.setDaemon( true ); this.connectionSendThread.setDaemon( true ); this.disconnectHandler.setDaemon( true ); this.connectionSendThread.start(); this.requestHandler.start(); this.disconnectHandler.start(); } public void close() { this.requestHandler.interrupt(); this.connectionSendThread.interrupt(); this.disconnectHandler.interrupt(); for (User user : Network.this.users ) { try { user.close(); } catch (Exception ignore) {} } } private void runDisconnectThread() { while (true) { if ( Thread.currentThread().isInterrupted() ) return; String toDisconnect = null; try { // we get the user we want to disconnect from, or wait until there is // one toDisconnect = Network.this.mainWindow.getDisconnectRequest(); } catch (InterruptedException ignore) { // we put this here so we interrupt this thread as soon as possible. if ( Thread.currentThread().isInterrupted() ) return; } if ( toDisconnect != null ) { try { for (User user : Network.this.users ) { if ( user.getRemoteName().equals( toDisconnect ) ) { user.close(); Network.this.users.remove( toDisconnect ); break; } } } catch (Exception whatTheHell) { UserDialog.userTooStupidDialog( "Disconnect handler" ); } } // now we check if any user has disconnected; try { for (User user : Network.this.users ) { if ( user.isDisconnected() ) { // DO NOT use user.close() it is not necessary! Network.this.mainWindow.removeUser( user.getRemoteName() ); Network.this.users.remove( user ); break; } } } catch (Exception whatTheHell) { UserDialog.userTooStupidDialog( "Disconnect handler" ); } } } private void runOutboundConnectionsThread() { while (true) { if ( Thread.currentThread().isInterrupted() ) return; String remoteName = null; try { remoteName = Network.this.mainWindow.getConnectionRequest(); } catch (InterruptedException ignore) { if ( Thread.currentThread().isInterrupted() ) return; } if ( remoteName != null ) try { // we check to see if we got a request to connect to someone we're // already connected to if ( Network.this.users.contains( remoteName ) ) { UserDialog.showError( String.format( "Already connected to '%s'.", remoteName ), "Already Connected: Network" ); continue; } SendConnectionRequestsI connect = Network.this.server .getUserConnectionI( remoteName ); if ( connect == null ) throw new UnknownHostException( remoteName ); Messenger bridge = new Messenger(); SendMessagesI sendingEnd = connect.connect( this.myName, bridge ); if ( sendingEnd == null ) { UserDialog .showMessage( String.format( "%s has declined your connection", remoteName ), "Connection Decline" ); continue; } User newUser = new User( bridge,sendingEnd,remoteName,this.myName ); // true if the user wasn't present if ( Network.this.users.add( newUser ) ) { Network.this.mainWindow.addUser( remoteName ); newUser.start(); } else { UserDialog.showError( String.format( "User '%s' already connected" ), "Outbound Connections: Network" ); } } catch (AccessException e) { UserDialog.showError( e.getMessage(), "Stupid security clearence" ); } catch (RemoteException e) { UserDialog.showError( e.getMessage(), "Remote Exception @ Connecting" ); } catch (UnknownHostException e) { UserDialog.showError( String.format( "Unkown user: '%s'", e.getMessage() ), "Unkown User Name" ); } catch (NullPointerException nullPointer) { UserDialog.nullPointerDialog( "@Connecting" ); } catch (Exception e) { UserDialog.userTooStupidDialog( "@Connecting" ); } } } private void runInboundConnectionsThread() { while (true) { if ( Thread.currentThread().isInterrupted() ) return; ReceiveConnectionRequestsI.PackagedData userData; try { userData = this.connections.getConnectionRequest(); if ( userData != null ) { User newUser = new User( userData.receivingEndI, userData.sendingEnd,userData.name,this.myName ); if ( Network.this.users.add( newUser ) ) { this.mainGUI.addUser( userData.name ); newUser.start(); } } } catch (InterruptedException itr) { if ( Thread.currentThread().isInterrupted() ) return; } catch (Exception e) { UserDialog.showError( e.getMessage(), "Couldn't Process Connection Request" ); } } } } public void disconnectFromServer() throws RemoteException { this.server.disconnect( this.myName ); this.server = null; UserDialog.showMessage( "You are no longer connected to the server.", "Disconnect from Server" ); } /** * @param serverAddress * the server of the server we wish to connect to * @return true if the connection was successful * false otherwise */ public boolean reconnectToServer( String serverAddress ) { try { if ( serverAddress == null || serverAddress.equals( "" ) ) return false; Registry registry = LocateRegistry.getRegistry( serverAddress, ServerInterface.PORT ); // we get the Server object through which we will be communicating this.server = (ServerInterface) registry .lookup( ServerInterface.REGISTRY_NAME ); this.server.register( this.myName, (ConnectionBridge) this.connectionManager.connections ); this.server.registerListener( this.myName, this.mainWindow.getServerListener() ); return true; } catch (Exception e) { return false; } } }
mit
Azure/azure-mobile-apps
sdk/dotnet/test/Microsoft.Datasync.Client.Test/Http/Precondition.Test.cs
4884
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using Datasync.Common.Test; using System; using System.Diagnostics.CodeAnalysis; using Xunit; namespace Microsoft.Datasync.Client.Test.Http { [ExcludeFromCodeCoverage] public class Precondition_Test : BaseTest { [Fact] [Trait("Method", "IfMatch.Any")] public void IfExists_GeneratesObject() { IfMatch condition = IfMatch.Any(); Assert.NotNull(condition); Assert.Contains("(If-Match=*)", condition.ToString()); } [Fact] [Trait("Method", "IfNoneMatch.Any")] public void IfNotExists_GeneratesObject() { IfNoneMatch condition = IfNoneMatch.Any(); Assert.NotNull(condition); Assert.Contains("(If-None-Match=*)", condition.ToString()); } [Fact] [Trait("Method", "IfMatch.Version")] public void IfMatch_NullByteArray_Throws() { byte[] version = null; Assert.Throws<ArgumentNullException>(() => IfMatch.Version(version)); } [Fact] [Trait("Method", "IfMatch.Version")] public void IfMatch_EmptyByteArray_Throws() { byte[] version = Array.Empty<byte>(); Assert.Throws<ArgumentException>(() => IfMatch.Version(version)); } [Fact] [Trait("Method", "IfMatch.Version")] public void IfMatch_FilledByteArray_GeneratedObject() { byte[] version = Guid.Parse("063d5aea-03f5-431c-b0ec-261ee2490651").ToByteArray(); var condition = IfMatch.Version(version); Assert.NotNull(condition); Assert.Contains("(If-Match=\"6lo9BvUDHEOw7CYe4kkGUQ==\")", condition.ToString()); } [Fact] [Trait("Method", "IfMatch.Version")] public void IfMatch_NullString_Throws() { const string version = null; Assert.Throws<ArgumentNullException>(() => IfMatch.Version(version)); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData(" ")] [Trait("Method", "IfMatch.Version")] public void IfMatch_EmptyString_Throws(string version) { Assert.Throws<ArgumentException>(() => IfMatch.Version(version)); } [Theory] [InlineData("\"etag\"", "\"etag\"")] [InlineData("etag", "\"etag\"")] [InlineData("*", "*")] [Trait("Method", "IfMatch.Version")] public void IfMatch_FilledString_GeneratesObject(string version, string expected) { var condition = IfMatch.Version(version); Assert.NotNull(condition); Assert.Contains($"(If-Match={expected})", condition.ToString()); } [Fact] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_NullByteArray_Throws() { byte[] version = null; Assert.Throws<ArgumentNullException>(() => IfNoneMatch.Version(version)); } [Fact] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_EmptyByteArray_Throws() { byte[] version = Array.Empty<byte>(); Assert.Throws<ArgumentException>(() => IfNoneMatch.Version(version)); } [Fact] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_FilledByteArray_GeneratedObject() { byte[] version = Guid.Parse("063d5aea-03f5-431c-b0ec-261ee2490651").ToByteArray(); var condition = IfNoneMatch.Version(version); Assert.NotNull(condition); Assert.Contains("(If-None-Match=\"6lo9BvUDHEOw7CYe4kkGUQ==\")", condition.ToString()); } [Fact] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_NullString_Throws() { const string version = null; Assert.Throws<ArgumentNullException>(() => IfNoneMatch.Version(version)); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData(" ")] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_EmptyString_Throws(string version) { Assert.Throws<ArgumentException>(() => IfNoneMatch.Version(version)); } [Theory] [InlineData("\"etag\"", "\"etag\"")] [InlineData("etag", "\"etag\"")] [InlineData("*", "*")] [Trait("Method", "IfNoneMatch.Version")] public void IfNotMatch_FilledString_GeneratesObject(string version, string expected) { var condition = IfNoneMatch.Version(version); Assert.NotNull(condition); Assert.Contains($"(If-None-Match={expected})", condition.ToString()); } } }
mit
tojibon/simplipro
db/migrate/20140706053122_add_is_client_to_admin_user.rb
128
class AddIsClientToAdminUser < ActiveRecord::Migration def change add_column :admin_users, :is_client, :boolean end end
mit
vitto/dustman
lib/message.js
3612
var message = (function(){ var colour = require('colour'); // var sleep = require('sleep').sleep; colour.setTheme({ error: 'red bold', event: 'magenta', intro: 'rainbow', notice: 'yellow', speak: 'white', success: 'green', task: 'white', verbose: 'blue', warning: 'yellow bold' }); var verbose = 3; var phrases = { add: [ 'What the hell is %file%?? I, DUSTMAN will do something to solve this situation...', 'I\'ve found a sensational discovery, %file% is alive!', 'Hey %file%, welcome to da build', 'File %file% detected. Updating the build.' ], change: [ 'Hey, something\'s happened to %file%, this is a work for DUSTMAN...', 'Dear %file%, do you really though I wouldn\'t noticed you? Hahaha!', 'Aha! %file%! You are under build!', 'We change every day, just as you, %file%' ], unlink: [ 'We have lost %file%, this is a work for DUSTMAN...', 'Oh my god... %file%... Nooooo!', 'Another good %file% gone... I will avange you...', 'Good bye %file%. I will clean your past without pain.' ], wait: [ 'Waiting silently if something changes, is unlinked or added', 'Dustman is watching them', 'The dust is never clear totally, waiting for changes', 'I will seek and clean. Again, and again' ] }; var isVerboseEnough = function(verbosity) { return verbose >= verbosity; }; var log = function(level, message, delay) { if (isVerboseEnough(level)) { console.log(message); if (typeof delay !== 'undefined') { var waitTill = new Date(new Date().getTime() + delay * 1000); while(waitTill > new Date()) { } // sleep(delay); } } }; var event = function(eventType, file) { var min, max, phrase, splitPhrase, finalPhrase, index; min = 1; max = phrases[eventType].length; index = (Math.floor(Math.random() * (max - min + 1)) + min) - 1; phrase = phrases[eventType][index]; if (typeof file !== 'undefined') { splitPhrase = phrase.split('%file%'); finalPhrase = colour.event(splitPhrase[0]) + file + colour.event(splitPhrase[1]); } else { finalPhrase = colour.event(phrase + '...'); } log(1, finalPhrase); }; return { intro: function() { console.log(''); console.log(colour.intro(' D U S T M A N ')); console.log(''); }, error: function(message) { log(0, colour.error('Error: ') + message.toString().trim()); }, event: function(eventType, file) { event(eventType, file); }, wait: function() { log(3, ''); event('wait'); }, notice: function(message, delay) { log(2, colour.notice('Notice: ') + message.toString().trim(), delay); }, setVerbosity: function(verbosity) { verbose = verbosity; }, speak: function(message, delay) { log(2, colour.speak(message), delay); }, success: function(message, delay) { log(1, colour.success(message.toString().trim()), delay); }, task: function(message, delay) { log(3, ''); log(2, colour.task(message), delay); }, verbose: function(title, message, delay) { if (typeof message !== 'undefined') { log(3, colour.verbose(title.toString().trim() + ': ') + message.toString().trim(), delay); } else { log(3, colour.verbose(title.toString().trim()), delay); } }, warning: function(message, delay){ log(2, colour.warning('Warning: ') + message.toString().trim(), delay); }, }; })();
mit
kbussell/django-auditlog
src/auditlog/migrations/0002_auto_support_long_primary_keys.py
411
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auditlog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='logentry', name='object_id', field=models.BigIntegerField(db_index=True, null=True, verbose_name='object id', blank=True), ), ]
mit
agrc/AmdButler
amdbutler.py
7087
import sublime import sublime_plugin import os from . import buffer_parser from . import crawler from . import zipper PATH_SETTING_NAME = 'amd_butler_packages_base_path' PARAMS_ONE_LINE_SETTING_NAME = 'amd_butler_params_one_line' SETTINGS_FILE_NAME = 'AmdButler.sublime-settings' def _all_text(view): return view.substr(sublime.Region(0, view.size())) def _get_sorted_pairs(view): try: imports_span = buffer_parser.get_imports_span(_all_text(view)) params_span = buffer_parser.get_params_span(_all_text(view)) return zipper.zip(view.substr(sublime.Region(*imports_span)), view.substr(sublime.Region(*params_span))) except buffer_parser.ParseError as er: sublime.error_message(er.message) def _update_with_pairs(view, edit, pairs): imports_span = buffer_parser.get_imports_span(_all_text(view)) params_span = buffer_parser.get_params_span(_all_text(view)) project = _get_project_data() if (project is not None and not project.get('settings', False) is False and not project['settings'].get(PARAMS_ONE_LINE_SETTING_NAME, False) is False): oneLine = project['settings'][PARAMS_ONE_LINE_SETTING_NAME] else: settings = sublime.load_settings(SETTINGS_FILE_NAME) oneLine = settings.get(PARAMS_ONE_LINE_SETTING_NAME) # replace params - do these first since they won't affect the # imports region params_txt = zipper.generate_params_txt(pairs, '\t', oneLine) view.replace(edit, sublime.Region(*params_span), params_txt) # replace imports import_txt = zipper.generate_imports_txt(pairs, '\t') view.replace(edit, sublime.Region(*imports_span), import_txt) def _set_mods(view): settings = sublime.load_settings(SETTINGS_FILE_NAME) def on_folder_defined(txt): project = _get_project_data() if project is None: # no project open use default setting settings.set(PATH_SETTING_NAME, txt) sublime.save_settings(SETTINGS_FILE_NAME) else: project['settings'].update({PATH_SETTING_NAME: txt}) _save_project_data(project) get_imports() def get_folder(): sublime.active_window().show_input_panel( 'name of folder containing AMD packages (e.g. "src")', '', on_folder_defined, lambda: None, lambda: None) def get_imports(): _get_available_imports(view) view.run_command('amd_butler_add') project = _get_project_data() if project is not None: # create settings project prop if needed if (project.get('settings', False) is False or project['settings'].get(PATH_SETTING_NAME, False) is False): project.update({'settings': {PATH_SETTING_NAME: False}}) _save_project_data(project) get_folder() else: get_imports() else: # no project if settings.get(PATH_SETTING_NAME, False) is False: get_folder() else: get_imports() def _get_available_imports(view): project = _get_project_data() if project is None: settings = sublime.load_settings(SETTINGS_FILE_NAME) folder_name = settings.get( PATH_SETTING_NAME) path = _validate_folder(view, folder_name) if path is None: return else: settings = project['settings'] folder_name = settings[PATH_SETTING_NAME] path = _validate_folder(view, folder_name) if path is None: return sublime.status_message( 'AMD Butler: Processing modules in {} ...'.format(path)) view.mods = crawler.crawl(path, _get_sorted_pairs(view)) sublime.status_message( 'AMD Butler: Processing complete. {} total modules processed.'.format( len(view.mods))) def _validate_folder(view, folder_name): if view.file_name() is None: sublime.error_message('File must be saved in order to ' 'search for available modules!') path = os.path.join(view.file_name().split(folder_name)[0], folder_name) if os.path.exists(path): return path else: sublime.error_message('{} not found in the path of the current file!' .format(folder_name)) return None def _get_project_data(): return sublime.active_window().project_data() def _save_project_data(data): return sublime.active_window().set_project_data(data) class _Enabled(object): def is_enabled(self): return self.view.settings().get('syntax').find('JavaScript') != -1 class AmdButlerSort(_Enabled, sublime_plugin.TextCommand): def run(self, edit): _update_with_pairs(self.view, edit, _get_sorted_pairs(self.view)) class AmdButlerAdd(_Enabled, sublime_plugin.TextCommand): def run(self, edit): if not hasattr(self.view, 'mods'): _set_mods(self.view) else: self.view.window().show_quick_panel( self.view.mods, self.on_mod_selected) def on_mod_selected(self, i): if i != -1: pair = self.view.mods.pop(i) self.view.run_command('amd_butler_internal_add', {'pair': pair}) class AmdButlerRemove(_Enabled, sublime_plugin.TextCommand): def run(self, edit): self.pairs = _get_sorted_pairs(self.view) self.view.window().show_quick_panel( zipper.scrub_nones(self.pairs), self.on_mod_selected) def on_mod_selected(self, i): if i != -1: pair = self.pairs.pop(i) try: self.view.mods.append(pair) except AttributeError: pass self.view.run_command('amd_butler_internal_update', {'pairs': self.pairs}) class AmdButlerInternalUpdate(_Enabled, sublime_plugin.TextCommand): def run(self, edit, pairs): _update_with_pairs(self.view, edit, pairs) class AmdButlerInternalAdd(_Enabled, sublime_plugin.TextCommand): def run(self, edit, pair=''): # add param first try: params_point = buffer_parser.get_params_span( _all_text(self.view))[0] self.view.insert(edit, params_point, pair[1] + ',') imports_point = buffer_parser.get_imports_span( _all_text(self.view))[0] self.view.insert(edit, imports_point, '\'{}\','.format(pair[0])) except buffer_parser.ParseError as er: sublime.error_message(er.message) self.view.run_command('amd_butler_sort') class AmdButlerRefresh(_Enabled, sublime_plugin.TextCommand): def run(self, edit): _set_mods(self.view) class AmdButlerPrune(_Enabled, sublime_plugin.TextCommand): def run(self, edit): pairs = _get_sorted_pairs(self.view) new_pairs = buffer_parser.prune(pairs, _all_text(self.view)) _update_with_pairs(self.view, edit, new_pairs)
mit
ignaciocases/hermeneumatics
node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/runtime/DoubleRef.js
2533
/** @constructor */ ScalaJS.c.scala_runtime_DoubleRef = (function() { ScalaJS.c.java_lang_Object.call(this); this.elem$1 = 0.0 }); ScalaJS.c.scala_runtime_DoubleRef.prototype = new ScalaJS.inheritable.java_lang_Object(); ScalaJS.c.scala_runtime_DoubleRef.prototype.constructor = ScalaJS.c.scala_runtime_DoubleRef; ScalaJS.c.scala_runtime_DoubleRef.prototype.elem__D = (function() { return this.elem$1 }); ScalaJS.c.scala_runtime_DoubleRef.prototype.elem$und$eq__D__V = (function(x$1) { this.elem$1 = x$1 }); ScalaJS.c.scala_runtime_DoubleRef.prototype.toString__T = (function() { return ScalaJS.modules.scala_scalajs_runtime_RuntimeString().valueOf__D__T(this.elem__D()) }); ScalaJS.c.scala_runtime_DoubleRef.prototype.init___D = (function(elem) { this.elem$1 = elem; ScalaJS.c.java_lang_Object.prototype.init___.call(this); return this }); ScalaJS.c.scala_runtime_DoubleRef.prototype.elem$und$eq__D__ = (function(x$1) { return ScalaJS.bV(this.elem$und$eq__D__V(x$1)) }); ScalaJS.c.scala_runtime_DoubleRef.prototype.elem__ = (function() { return ScalaJS.bD(this.elem__D()) }); /** @constructor */ ScalaJS.inheritable.scala_runtime_DoubleRef = (function() { /*<skip>*/ }); ScalaJS.inheritable.scala_runtime_DoubleRef.prototype = ScalaJS.c.scala_runtime_DoubleRef.prototype; ScalaJS.is.scala_runtime_DoubleRef = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_runtime_DoubleRef))) }); ScalaJS.as.scala_runtime_DoubleRef = (function(obj) { if ((ScalaJS.is.scala_runtime_DoubleRef(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.runtime.DoubleRef") } }); ScalaJS.isArrayOf.scala_runtime_DoubleRef = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_runtime_DoubleRef))) }); ScalaJS.asArrayOf.scala_runtime_DoubleRef = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_runtime_DoubleRef(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.runtime.DoubleRef;", depth) } }); ScalaJS.data.scala_runtime_DoubleRef = new ScalaJS.ClassTypeData({ scala_runtime_DoubleRef: 0 }, false, "scala.runtime.DoubleRef", ScalaJS.data.java_lang_Object, { scala_runtime_DoubleRef: 1, java_io_Serializable: 1, java_lang_Object: 1 }); ScalaJS.c.scala_runtime_DoubleRef.prototype.$classData = ScalaJS.data.scala_runtime_DoubleRef; //@ sourceMappingURL=DoubleRef.js.map
mit
chloereimer/smartcards
spec/models/card_spec.rb
419
describe Card do let( :card ) { create :card } it "has a valid factory" do expect( card ).to be_valid end it "is invalid without a deck" do card.deck = nil expect( card ).to_not be_valid end it "is invalid without a front" do card.front = nil expect( card ).to_not be_valid end it "is invalid without a back" do card.back = nil expect( card ).to_not be_valid end end
mit
restify-ts/core
packages/core/src/utils/throw-providers-collision-error.ts
960
import { Scope } from '../types/mix'; export function throwProvidersCollisionError( moduleName: string, duplicates: any[], modulesNames: string[] = [], scope?: Scope ) { const namesArr = duplicates.map((p) => p.name || p); const namesStr = namesArr.join(', '); let fromModules = 'from several modules '; let example = ''; if (modulesNames.length) { fromModules = `from ${modulesNames.join(', ')} `; example = ` For example: resolvedCollisionsPer${scope || 'App'}: [ [${namesArr[0]}, ${modulesNames[0]}] ].`; } const resolvedCollisionsPer = scope ? `resolvedCollisionsPer${scope}` : 'resolvedCollisionsPer*'; const provider = duplicates.length > 1 ? 'these providers' : 'this provider'; const msg = `Importing providers to ${moduleName} failed: exports ${fromModules}causes collision with ${namesStr}. ` + `You should add ${provider} to ${resolvedCollisionsPer} in ${moduleName}.${example}`; throw new Error(msg); }
mit
CS2103JAN2017-T11-B4/main
src/main/java/seedu/task/model/task/DueDate.java
1115
//@@author A0164103W package seedu.task.model.task; import java.util.Calendar; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.model.util.DateParser; public class DueDate { /** * Represents a Task's due date in the task list. * Guarantees: immutable; is valid as declared in {@link #isValidDueDate(String)} */ public final Calendar dueDate; /** * Validates given description. * * @throws IllegalValueException if given description string is invalid. */ public DueDate(String inputDueDate) throws IllegalValueException { this.dueDate = DateParser.parse(inputDueDate); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DueDate // instanceof handles nulls && this.dueDate.equals(((DueDate) other).dueDate)); // state check } @Override public String toString() { return DateParser.toString(dueDate); } @Override public int hashCode() { return dueDate.hashCode(); } }
mit
portchris/NaturalRemedyCompany
src/dev/tests/functional/tests/app/Mage/CatalogRule/Test/Constraint/AssertCatalogPriceRuleAppliedInCatalogPage.php
3788
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Tests * @package Tests_Functional * @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ namespace Mage\CatalogRule\Test\Constraint; use Mage\Catalog\Test\Page\Category\CatalogCategoryView; use Mage\Cms\Test\Page\CmsIndex; use Magento\Mtf\Constraint\AbstractAssertForm; use Magento\Mtf\Fixture\InjectableFixture; /** * Check that Catalog Price Rule is applied for product(s) in Catalog * according to Priority(Priority/Stop Further Rules Processing). */ class AssertCatalogPriceRuleAppliedInCatalogPage extends AbstractAssertForm { /* tags */ const SEVERITY = 'high'; /* end tags */ /** * Verify fields. * * @var array */ protected $verifyFields = [ 'regular', 'special', 'discount_amount' ]; /** * Assert that Catalog Price Rule is applied for product(s) in Catalog * according to Priority(Priority/Stop Further Rules Processing). * * @param InjectableFixture $product * @param CmsIndex $cmsIndex * @param CatalogCategoryView $catalogCategoryView * @param array $prices * @return void */ public function processAssert( InjectableFixture $product, CmsIndex $cmsIndex, CatalogCategoryView $catalogCategoryView, array $prices ) { $cmsIndex->open(); $cmsIndex->getTopmenu()->selectCategory($product->getCategoryIds()[0]); $formPrices = $this->getFormPrices($product, $catalogCategoryView); $fixturePrices = $this->prepareFixturePrices($prices); $diff = $this->verifyData($fixturePrices, $formPrices); \PHPUnit_Framework_Assert::assertEmpty($diff, $diff . "\n On: " . date('l jS \of F Y h:i:s A')); } /** * Prepare fixture prices. * * @param array $prices * @return array */ protected function prepareFixturePrices(array $prices) { return array_intersect_key($prices, array_flip($this->verifyFields)); } /** * Get form prices. * * @param InjectableFixture $product * @param CatalogCategoryView $catalogCategoryView * @return array */ protected function getFormPrices(InjectableFixture $product, CatalogCategoryView $catalogCategoryView) { $productPriceBlock = $catalogCategoryView->getListProductBlock()->getProductPriceBlock($product->getName()); $actualPrices = [ 'regular' => $productPriceBlock->getRegularPrice(), 'special' => $productPriceBlock->getSpecialPrice() ]; $actualPrices['discount_amount'] = number_format($actualPrices['regular'] - $actualPrices['special'], 2); return $actualPrices; } /** * Returns a string representation of successful assertion. * * @return string */ public function toString() { return 'Catalog Price Rule is applied for product(s) in Catalog according to Priority.'; } }
mit
IvanJobs/play
unix-programming/getenv.cpp
154
#include <cstdio> #include <cstdlib> int main() { char *p = NULL; if ((p = getenv("OK"))) { printf("OK=%s\n", p); } return 0; }
mit
prebm/edinost-skofice
openlayers/lib/OpenLayers/Renderer/VML.js
46380
/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Renderer/Elements.js */ /** * Class: OpenLayers.Renderer.VML * Render vector features in browsers with VML capability. Construct a new * VML renderer with the <OpenLayers.Renderer.VML> constructor. * * Note that for all calculations in this class, we use (num | 0) to truncate a * float value to an integer. This is done because it seems that VML doesn't * support float values. * * Inherits from: * - <OpenLayers.Renderer.Elements> */ OpenLayers.Renderer.VML = OpenLayers.Class(OpenLayers.Renderer.Elements, { /** * Property: xmlns * {String} XML Namespace URN */ xmlns: "urn:schemas-microsoft-com:vml", /** * Property: symbolCache * {DOMElement} node holding symbols. This hash is keyed by symbol name, * and each value is a hash with a "path" and an "extent" property. */ symbolCache: {}, /** * Property: offset * {Object} Hash with "x" and "y" properties */ offset: null, /** * Constructor: OpenLayers.Renderer.VML * Create a new VML renderer. * * Parameters: * containerID - {String} The id for the element that contains the renderer */ initialize: function(containerID) { if (!this.supported()) { return; } if (!document.namespaces.olv) { document.namespaces.add("olv", this.xmlns); var style = document.createStyleSheet(); var shapes = ['shape','rect', 'oval', 'fill', 'stroke', 'imagedata', 'group','textbox','textpath','path']; for (var i = 0, len = shapes.length; i < len; i++) { style.addRule('olv\\:' + shapes[i], "behavior: url(#default#VML); " + "position: absolute; display: inline-block;"); } } OpenLayers.Renderer.Elements.prototype.initialize.apply(this, arguments); }, /** * APIMethod: supported * Determine whether a browser supports this renderer. * * Returns: * {Boolean} The browser supports the VML renderer */ supported: function() { return !!(document.namespaces); }, /** * Method: setExtent * Set the renderer's extent * * Parameters: * extent - {<OpenLayers.Bounds>} * resolutionChanged - {Boolean} * * Returns: * {Boolean} true to notify the layer that the new extent does not exceed * the coordinate range, and the features will not need to be redrawn. */ setExtent: function(extent, resolutionChanged) { OpenLayers.Renderer.Elements.prototype.setExtent.apply(this, arguments); var resolution = this.getResolution(); var left = (extent.left/resolution) | 0; var top = (extent.top/resolution - this.size.h) | 0; if (resolutionChanged || !this.offset) { this.offset = {x: left, y: top}; left = 0; top = 0; } else { left = left - this.offset.x; top = top - this.offset.y; } var org = left + " " + top; this.root.coordorigin = org; var roots = [this.root, this.vectorRoot, this.textRoot]; var root; for(var i=0, len=roots.length; i<len; ++i) { root = roots[i]; var size = this.size.w + " " + this.size.h; root.coordsize = size; } // flip the VML display Y axis upside down so it // matches the display Y axis of the map this.root.style.flip = "y"; return true; }, /** * Method: setSize * Set the size of the drawing surface * * Parameters: * size - {<OpenLayers.Size>} the size of the drawing surface */ setSize: function(size) { OpenLayers.Renderer.prototype.setSize.apply(this, arguments); // setting width and height on all roots to avoid flicker which we // would get with 100% width and height on child roots var roots = [ this.rendererRoot, this.root, this.vectorRoot, this.textRoot ]; var w = this.size.w + "px"; var h = this.size.h + "px"; var root; for(var i=0, len=roots.length; i<len; ++i) { root = roots[i]; root.style.width = w; root.style.height = h; } }, /** * Method: getNodeType * Get the node type for a geometry and style * * Parameters: * geometry - {<OpenLayers.Geometry>} * style - {Object} * * Returns: * {String} The corresponding node type for the specified geometry */ getNodeType: function(geometry, style) { var nodeType = null; switch (geometry.CLASS_NAME) { case "OpenLayers.Geometry.Point": if (style.externalGraphic) { nodeType = "olv:rect"; } else if (this.isComplexSymbol(style.graphicName)) { nodeType = "olv:shape"; } else { nodeType = "olv:oval"; } break; case "OpenLayers.Geometry.Rectangle": nodeType = "olv:rect"; break; case "OpenLayers.Geometry.LineString": case "OpenLayers.Geometry.LinearRing": case "OpenLayers.Geometry.Polygon": case "OpenLayers.Geometry.Curve": case "OpenLayers.Geometry.Surface": nodeType = "olv:shape"; break; default: break; } return nodeType; }, /** * Method: setStyle * Use to set all the style attributes to a VML node. * * Parameters: * node - {DOMElement} An VML element to decorate * style - {Object} * options - {Object} Currently supported options include * 'isFilled' {Boolean} and * 'isStroked' {Boolean} * geometry - {<OpenLayers.Geometry>} */ setStyle: function(node, style, options, geometry) { style = style || node._style; options = options || node._options; var fillColor = style.fillColor; if (node._geometryClass === "OpenLayers.Geometry.Point") { if (style.externalGraphic) { options.isFilled = true; if (style.graphicTitle) { node.title=style.graphicTitle; } var width = style.graphicWidth || style.graphicHeight; var height = style.graphicHeight || style.graphicWidth; width = width ? width : style.pointRadius*2; height = height ? height : style.pointRadius*2; var resolution = this.getResolution(); var xOffset = (style.graphicXOffset != undefined) ? style.graphicXOffset : -(0.5 * width); var yOffset = (style.graphicYOffset != undefined) ? style.graphicYOffset : -(0.5 * height); node.style.left = (((geometry.x/resolution - this.offset.x)+xOffset) | 0) + "px"; node.style.top = (((geometry.y/resolution - this.offset.y)-(yOffset+height)) | 0) + "px"; node.style.width = width + "px"; node.style.height = height + "px"; node.style.flip = "y"; // modify fillColor and options for stroke styling below fillColor = "none"; options.isStroked = false; } else if (this.isComplexSymbol(style.graphicName)) { var cache = this.importSymbol(style.graphicName); node.path = cache.path; node.coordorigin = cache.left + "," + cache.bottom; var size = cache.size; node.coordsize = size + "," + size; this.drawCircle(node, geometry, style.pointRadius); node.style.flip = "y"; } else { this.drawCircle(node, geometry, style.pointRadius); } } // fill if (options.isFilled) { node.fillcolor = fillColor; } else { node.filled = "false"; } var fills = node.getElementsByTagName("fill"); var fill = (fills.length == 0) ? null : fills[0]; if (!options.isFilled) { if (fill) { node.removeChild(fill); } } else { if (!fill) { fill = this.createNode('olv:fill', node.id + "_fill"); } fill.opacity = style.fillOpacity; if (node._geometryClass === "OpenLayers.Geometry.Point" && style.externalGraphic) { // override fillOpacity if (style.graphicOpacity) { fill.opacity = style.graphicOpacity; } fill.src = style.externalGraphic; fill.type = "frame"; if (!(style.graphicWidth && style.graphicHeight)) { fill.aspect = "atmost"; } } if (fill.parentNode != node) { node.appendChild(fill); } } // additional rendering for rotated graphics or symbols var rotation = style.rotation; if ((rotation !== undefined || node._rotation !== undefined)) { node._rotation = rotation; if (style.externalGraphic) { this.graphicRotate(node, xOffset, yOffset, style); // make the fill fully transparent, because we now have // the graphic as imagedata element. We cannot just remove // the fill, because this is part of the hack described // in graphicRotate fill.opacity = 0; } else if(node._geometryClass === "OpenLayers.Geometry.Point") { node.style.rotation = rotation || 0; } } // stroke var strokes = node.getElementsByTagName("stroke"); var stroke = (strokes.length == 0) ? null : strokes[0]; if (!options.isStroked) { node.stroked = false; if (stroke) { stroke.on = false; } } else { if (!stroke) { stroke = this.createNode('olv:stroke', node.id + "_stroke"); node.appendChild(stroke); } stroke.on = true; stroke.color = style.strokeColor; stroke.weight = style.strokeWidth + "px"; stroke.opacity = style.strokeOpacity; stroke.endcap = style.strokeLinecap == 'butt' ? 'flat' : (style.strokeLinecap || 'round'); if (style.strokeDashstyle) { stroke.dashstyle = this.dashStyle(style); } } if (style.cursor != "inherit" && style.cursor != null) { node.style.cursor = style.cursor; } return node; }, /** * Method: graphicRotate * If a point is to be styled with externalGraphic and rotation, VML fills * cannot be used to display the graphic, because rotation of graphic * fills is not supported by the VML implementation of Internet Explorer. * This method creates a olv:imagedata element inside the VML node, * DXImageTransform.Matrix and BasicImage filters for rotation and * opacity, and a 3-step hack to remove rendering artefacts from the * graphic and preserve the ability of graphics to trigger events. * Finally, OpenLayers methods are used to determine the correct * insertion point of the rotated image, because DXImageTransform.Matrix * does the rotation without the ability to specify a rotation center * point. * * Parameters: * node - {DOMElement} * xOffset - {Number} rotation center relative to image, x coordinate * yOffset - {Number} rotation center relative to image, y coordinate * style - {Object} */ graphicRotate: function(node, xOffset, yOffset, style) { var style = style || node._style; var rotation = style.rotation || 0; var aspectRatio, size; if (!(style.graphicWidth && style.graphicHeight)) { // load the image to determine its size var img = new Image(); img.onreadystatechange = OpenLayers.Function.bind(function() { if(img.readyState == "complete" || img.readyState == "interactive") { aspectRatio = img.width / img.height; size = Math.max(style.pointRadius * 2, style.graphicWidth || 0, style.graphicHeight || 0); xOffset = xOffset * aspectRatio; style.graphicWidth = size * aspectRatio; style.graphicHeight = size; this.graphicRotate(node, xOffset, yOffset, style); } }, this); img.src = style.externalGraphic; // will be called again by the onreadystate handler return; } else { size = Math.max(style.graphicWidth, style.graphicHeight); aspectRatio = style.graphicWidth / style.graphicHeight; } var width = Math.round(style.graphicWidth || size * aspectRatio); var height = Math.round(style.graphicHeight || size); node.style.width = width + "px"; node.style.height = height + "px"; // Three steps are required to remove artefacts for images with // transparent backgrounds (resulting from using DXImageTransform // filters on svg objects), while preserving awareness for browser // events on images: // - Use the fill as usual (like for unrotated images) to handle // events // - specify an imagedata element with the same src as the fill // - style the imagedata element with an AlphaImageLoader filter // with empty src var image = document.getElementById(node.id + "_image"); if (!image) { image = this.createNode("olv:imagedata", node.id + "_image"); node.appendChild(image); } image.style.width = width + "px"; image.style.height = height + "px"; image.src = style.externalGraphic; image.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(" + "src='', sizingMethod='scale')"; var rot = rotation * Math.PI / 180; var sintheta = Math.sin(rot); var costheta = Math.cos(rot); // do the rotation on the image var filter = "progid:DXImageTransform.Microsoft.Matrix(M11=" + costheta + ",M12=" + (-sintheta) + ",M21=" + sintheta + ",M22=" + costheta + ",SizingMethod='auto expand')\n"; // set the opacity (needed for the imagedata) var opacity = style.graphicOpacity || style.fillOpacity; if (opacity && opacity != 1) { filter += "progid:DXImageTransform.Microsoft.BasicImage(opacity=" + opacity+")\n"; } node.style.filter = filter; // do the rotation again on a box, so we know the insertion point var centerPoint = new OpenLayers.Geometry.Point(-xOffset, -yOffset); var imgBox = new OpenLayers.Bounds(0, 0, width, height).toGeometry(); imgBox.rotate(style.rotation, centerPoint); var imgBounds = imgBox.getBounds(); node.style.left = Math.round( parseInt(node.style.left) + imgBounds.left) + "px"; node.style.top = Math.round( parseInt(node.style.top) - imgBounds.bottom) + "px"; }, /** * Method: postDraw * Does some node postprocessing to work around browser issues: * - Some versions of Internet Explorer seem to be unable to set fillcolor * and strokecolor to "none" correctly before the fill node is appended * to a visible vml node. This method takes care of that and sets * fillcolor and strokecolor again if needed. * - In some cases, a node won't become visible after being drawn. Setting * style.visibility to "visible" works around that. * * Parameters: * node - {DOMElement} */ postDraw: function(node) { node.style.visibility = "visible"; var fillColor = node._style.fillColor; var strokeColor = node._style.strokeColor; if (fillColor == "none" && node.fillcolor != fillColor) { node.fillcolor = fillColor; } if (strokeColor == "none" && node.strokecolor != strokeColor) { node.strokecolor = strokeColor; } }, /** * Method: setNodeDimension * Get the geometry's bounds, convert it to our vml coordinate system, * then set the node's position, size, and local coordinate system. * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} */ setNodeDimension: function(node, geometry) { var bbox = geometry.getBounds(); if(bbox) { var resolution = this.getResolution(); var scaledBox = new OpenLayers.Bounds((bbox.left/resolution - this.offset.x) | 0, (bbox.bottom/resolution - this.offset.y) | 0, (bbox.right/resolution - this.offset.x) | 0, (bbox.top/resolution - this.offset.y) | 0); // Set the internal coordinate system to draw the path node.style.left = scaledBox.left + "px"; node.style.top = scaledBox.top + "px"; node.style.width = scaledBox.getWidth() + "px"; node.style.height = scaledBox.getHeight() + "px"; node.coordorigin = scaledBox.left + " " + scaledBox.top; node.coordsize = scaledBox.getWidth()+ " " + scaledBox.getHeight(); } }, /** * Method: dashStyle * * Parameters: * style - {Object} * * Returns: * {String} A VML compliant 'stroke-dasharray' value */ dashStyle: function(style) { var dash = style.strokeDashstyle; switch (dash) { case 'solid': case 'dot': case 'dash': case 'dashdot': case 'longdash': case 'longdashdot': return dash; default: // very basic guessing of dash style patterns var parts = dash.split(/[ ,]/); if (parts.length == 2) { if (1*parts[0] >= 2*parts[1]) { return "longdash"; } return (parts[0] == 1 || parts[1] == 1) ? "dot" : "dash"; } else if (parts.length == 4) { return (1*parts[0] >= 2*parts[1]) ? "longdashdot" : "dashdot"; } return "solid"; } }, /** * Method: createNode * Create a new node * * Parameters: * type - {String} Kind of node to draw * id - {String} Id for node * * Returns: * {DOMElement} A new node of the given type and id */ createNode: function(type, id) { var node = document.createElement(type); if (id) { node.id = id; } // IE hack to make elements unselectable, to prevent 'blue flash' // while dragging vectors; #1410 node.unselectable = 'on'; node.onselectstart = OpenLayers.Function.False; return node; }, /** * Method: nodeTypeCompare * Determine whether a node is of a given type * * Parameters: * node - {DOMElement} An VML element * type - {String} Kind of node * * Returns: * {Boolean} Whether or not the specified node is of the specified type */ nodeTypeCompare: function(node, type) { //split type var subType = type; var splitIndex = subType.indexOf(":"); if (splitIndex != -1) { subType = subType.substr(splitIndex+1); } //split nodeName var nodeName = node.nodeName; splitIndex = nodeName.indexOf(":"); if (splitIndex != -1) { nodeName = nodeName.substr(splitIndex+1); } return (subType == nodeName); }, /** * Method: createRenderRoot * Create the renderer root * * Returns: * {DOMElement} The specific render engine's root element */ createRenderRoot: function() { return this.nodeFactory(this.container.id + "_vmlRoot", "div"); }, /** * Method: createRoot * Create the main root element * * Parameters: * suffix - {String} suffix to append to the id * * Returns: * {DOMElement} */ createRoot: function(suffix) { return this.nodeFactory(this.container.id + suffix, "olv:group"); }, /************************************** * * * GEOMETRY DRAWING FUNCTIONS * * * **************************************/ /** * Method: drawPoint * Render a point * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} or false if the point could not be drawn */ drawPoint: function(node, geometry) { return this.drawCircle(node, geometry, 1); }, /** * Method: drawCircle * Render a circle. * Size and Center a circle given geometry (x,y center) and radius * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * radius - {float} * * Returns: * {DOMElement} or false if the circle could not ne drawn */ drawCircle: function(node, geometry, radius) { if(!isNaN(geometry.x)&& !isNaN(geometry.y)) { var resolution = this.getResolution(); node.style.left = (((geometry.x /resolution - this.offset.x) | 0) - radius) + "px"; node.style.top = (((geometry.y /resolution - this.offset.y) | 0) - radius) + "px"; var diameter = radius * 2; node.style.width = diameter + "px"; node.style.height = diameter + "px"; return node; } return false; }, /** * Method: drawLineString * Render a linestring. * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} */ drawLineString: function(node, geometry) { return this.drawLine(node, geometry, false); }, /** * Method: drawLinearRing * Render a linearring * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} */ drawLinearRing: function(node, geometry) { return this.drawLine(node, geometry, true); }, /** * Method: DrawLine * Render a line. * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * closeLine - {Boolean} Close the line? (make it a ring?) * * Returns: * {DOMElement} */ drawLine: function(node, geometry, closeLine) { this.setNodeDimension(node, geometry); var resolution = this.getResolution(); var numComponents = geometry.components.length; var parts = new Array(numComponents); var comp, x, y; for (var i = 0; i < numComponents; i++) { comp = geometry.components[i]; x = (comp.x/resolution - this.offset.x) | 0; y = (comp.y/resolution - this.offset.y) | 0; parts[i] = " " + x + "," + y + " l "; } var end = (closeLine) ? " x e" : " e"; node.path = "m" + parts.join("") + end; return node; }, /** * Method: drawPolygon * Render a polygon * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} */ drawPolygon: function(node, geometry) { this.setNodeDimension(node, geometry); var resolution = this.getResolution(); var path = []; var j, jj, points, area, first, second, i, ii, comp, pathComp, x, y; for (j=0, jj=geometry.components.length; j<jj; j++) { path.push("m"); points = geometry.components[j].components; // we only close paths of interior rings with area area = (j === 0); first = null; second = null; for (i=0, ii=points.length; i<ii; i++) { comp = points[i]; x = (comp.x / resolution - this.offset.x) | 0; y = (comp.y / resolution - this.offset.y) | 0; pathComp = " " + x + "," + y; path.push(pathComp); if (i==0) { path.push(" l"); } if (!area) { // IE improperly renders sub-paths that have no area. // Instead of checking the area of every ring, we confirm // the ring has at least three distinct points. This does // not catch all non-zero area cases, but it greatly improves // interior ring digitizing and is a minor performance hit // when rendering rings with many points. if (!first) { first = pathComp; } else if (first != pathComp) { if (!second) { second = pathComp; } else if (second != pathComp) { // stop looking area = true; } } } } path.push(area ? " x " : " "); } path.push("e"); node.path = path.join(""); return node; }, /** * Method: drawRectangle * Render a rectangle * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} */ drawRectangle: function(node, geometry) { var resolution = this.getResolution(); node.style.left = ((geometry.x/resolution - this.offset.x) | 0) + "px"; node.style.top = ((geometry.y/resolution - this.offset.y) | 0) + "px"; node.style.width = ((geometry.width/resolution) | 0) + "px"; node.style.height = ((geometry.height/resolution) | 0) + "px"; return node; }, /** * Method: drawText * This method is only called by the renderer itself. * * Parameters: * featureId - {String} * style - * location - {<OpenLayers.Geometry.Point>} * useHalo - {Boolean} */ drawText: function (featureId, style, location, useHalo) { // If the user wants a halo, first draw the text with a // thick stroke (using the halo color) and then draw the // text normally over that // Idea from: // http://www.mail-archive.com/[email protected]/msg01002.html if (style.labelHaloColor) { var haloStyle = OpenLayers.Util.extend({}, style); haloStyle.fontStrokeColor = haloStyle.labelHaloColor; haloStyle.fontStrokeWidth = haloStyle.labelHaloWidth || 2; delete haloStyle.labelHaloColor; this.drawText(featureId, haloStyle, location, true); } var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + (useHalo ? this.HALO_ID_SUFFIX : ""), "olv:shape"); // Add it to the DOM hierarchy if(!label.parentNode) { this.textRoot.appendChild(label); } // Set its dimension and position attributes var resolution = this.getResolution(); label.style.left = ((location.x/resolution - this.offset.x) | 0) + "px"; label.style.top = ((location.y/resolution - this.offset.y) | 0) + "px"; label.style.flip = "y"; label.style.position = "absolute"; label.style.width = 1 + "px"; // some dummy value label.style.height = 1 + "px"; // some dummy value label.style.antialias = "true"; /* var nodeStyle = { fillColor: style.fontColor, fillOpacity: style.fontOpacity, strokeColor: style.fontStrokeColor, strokeWidth: style.fontHaloSize || 2, strokeOpacity: style.fontOpacity } var nodeOptions = { isFilled: style.fontColor, isStroked: style.fontStrokeColor } this.setStyle(label, nodeStyle, nodeOptions, null); */ // Create the fill object var myFill = document.createElement("olv:fill"); myFill.on = "true"; myFill.color = style.fontColor; // Add it to the DOM hierarchy label.appendChild(myFill); // Create the stroke object. We need to define the // stroke explicitly, otherwise we get a default // black outline var myStroke = document.createElement("olv:stroke"); if (style.fontStrokeColor) { myStroke.on = "true"; myStroke.color = style.fontStrokeColor; } else { myStroke.on = "false"; } if (style.fontStrokeWidth) { myStroke.weight = style.fontStrokeWidth; } // Add it to the DOM hierarchy label.appendChild(myStroke); // Create the path object var path = document.createElement("olv:path"); path.textpathok = "True"; path.v = "m 0,0 l 200,0"; // Add it to the DOM hierarchy label.appendChild(path); // Create the textpath object var textpath = document.createElement("olv:textpath"); textpath.on = "true"; textpath.fitpath = "false"; textpath.string = style.label; label.appendChild(textpath); if (style.cursor != "inherit" && style.cursor != null) { label.style.cursor = style.cursor; } if (style.fontColor) { textpath.style.color = style.fontColor; } if (style.fontOpacity) { myFill.opacity = style.fontOpacity; myStroke.opacity = style.fontOpacity; } // Setting the font family does not seem to work // TODO: make this work! if (style.fontFamily) { textpath.style.fontfamily = style.fontFamily; //textpath.style['font-family'] = style.fontFamily; label.style.fontFamily = style.fontFamily; } // We need to set the fontSize to prevent JS errors textpath.style.fontSize = style.fontSize || 10; if (style.fontWeight) { textpath.style.fontWeight = style.fontWeight; } if (style.fontStyle) { textpath.style.fontStyle = style.fontStyle; } var align = style.labelAlign || "cm"; if (align.length == 1) { align += "m"; } // Set the horizontal align var hAlign; switch (align.substr(0,1)) { case 'l': hAlign = "left"; break; case 'c': hAlign = "center"; break; case 'r': hAlign = "right"; break; } textpath.style['v-text-align'] = hAlign; if(style.labelSelect === true) { label._featureId = featureId; textpath._featureId = featureId; textpath._geometry = location; textpath._geometryClass = location.CLASS_NAME; //label._geometry = location; //label._geometryClass = location.CLASS_NAME; } // Somehow our label is 1 pixel off horizontally // TODO: find out what causes it and then fix it var xshift = 1; // hack label.style.left = parseInt(label.style.left)+xshift+"px"; // Set the vertical align by using the fontSize as the height // We default to 0.5 in case style.labelAlign comes from a // variable like "${labelAlign}" as happens when an OL.Graticule // ends up in a GeoExt LegenPanel var yshift = parseInt(textpath.style.fontSize) * (OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)] || 0.5); // somehow our label is about 10 pixels off vertically // TODO: find out what causes it and then fix it yshift -= 7; label.style.top = parseInt(label.style.top)+yshift+"px"; }, /** * This method is only called by the renderer itself. * * Parameters: * featureId - {String} * style - * location - {<OpenLayers.Geometry.Point>} */ drawTextOLD: function(featureId, style, location) { var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX, "olv:rect"); var textbox = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_textbox", "olv:textbox"); // var layer = this.map.getLayer(this.container.id); // var feature = layer.getFeatureById(featureId); // location = (feature.attributes.centroid ? feature.attributes.centroid : location); var resolution = this.getResolution(); label.style.left = ((location.x/resolution - this.offset.x) | 0) + "px"; label.style.top = ((location.y/resolution - this.offset.y) | 0) + "px"; label.style.flip = "y"; textbox.innerText = style.label; // if (style.angle || style.angle == 0) { // //var rotate = 'rotate(' + style.angle + ',' + x + "," + -y + ')'; // textbox.style.angle = 'rotate:' + style.angle; // } if (style.cursor != "inherit" && style.cursor != null) { textbox.style.cursor = style.cursor; } if (style.fontColor) { textbox.style.color = style.fontColor; } if (style.fontOpacity) { textbox.style.filter = 'alpha(opacity=' + (style.fontOpacity * 100) + ')'; } if (style.fontFamily) { textbox.style.fontFamily = style.fontFamily; } if (style.fontSize) { textbox.style.fontSize = style.fontSize; } if (style.fontWeight) { textbox.style.fontWeight = style.fontWeight; } if (style.fontStyle) { textbox.style.fontStyle = style.fontStyle; } if(style.labelSelect === true) { label._featureId = featureId; textbox._featureId = featureId; textbox._geometry = location; textbox._geometryClass = location.CLASS_NAME; } textbox.style.whiteSpace = "nowrap"; // fun with IE: IE7 in standards compliant mode does not display any // text with a left inset of 0. So we set this to 1px and subtract one // pixel later when we set label.style.left textbox.inset = "1px,0px,0px,0px"; if(!label.parentNode) { label.appendChild(textbox); this.textRoot.appendChild(label); } var align = style.labelAlign || "cm"; if (align.length == 1) { align += "m"; } var xshift = textbox.clientWidth * (OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]); var yshift = textbox.clientHeight * (OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]); label.style.left = parseInt(label.style.left)-xshift-1+"px"; label.style.top = parseInt(label.style.top)+yshift+"px"; //################################## OL 2.8 // alert("a"); // var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX, "olv:rect"); // var textbox = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_textbox", "olv:textbox"); // // var resolution = this.getResolution(); // label.style.left = (location.x/resolution - this.offset.x).toFixed() + "px"; // label.style.top = (location.y/resolution - this.offset.y).toFixed() + "px"; // label.style.flip = "y"; // // textbox.innerText = style.label; // // if (style.fillColor) { // textbox.style.color = style.fontColor; // } // if (style.fontFamily) { // textbox.style.fontFamily = style.fontFamily; // } // if (style.fontSize) { // textbox.style.fontSize = style.fontSize; // } // if (style.fontWeight) { // textbox.style.fontWeight = style.fontWeight; // } // textbox.style.whiteSpace = "nowrap"; // // fun with IE: IE7 in standards compliant mode does not display any // // text with a left inset of 0. So we set this to 1px and subtract one // // pixel later when we set label.style.left // textbox.inset = "1px,0px,0px,0px"; // // if(!label.parentNode) { // label.appendChild(textbox); // this.textRoot.appendChild(label); // } // // var align = style.labelAlign || "cm"; // var xshift = textbox.clientWidth * // (OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]); // var yshift = textbox.clientHeight * // (OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]); // label.style.left = parseInt(label.style.left)-xshift-1+"px"; // label.style.top = parseInt(label.style.top)+yshift+"px"; //############################### Rotate // alert("a"); // var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX, "olv:shape"); // alert(label); // this.textRoot.appendChild(label); // alert(style.label); // // Get the style of the shape, then copy it to the label. // var layer = this.map.getLayer(this.container.id); // var feature = layer.getFeatureById(featureId); // location = (feature.attributes.centroid ? feature.attributes.centroid : location); // alert("location " + location); // var geometry = feature.geometry; //das ist ein Punkt und daher ist die geometry nur ein punkt, daher funktioniert die for unten nicht. Was tun? // alert(feature.geometry ); // // this.setNodeDimension(label, geometry); // label.style.flip = "y"; // // // Get the path of shape to calulate the line needed for the shape here. // var resolution = this.getResolution(); // // var vertices = []; // var linearRing, i, j, len, ilen, comp, x, y; // for (j = 0, len=geometry.components.length; j<len; j++) { // linearRing = geometry.components[j]; // // for (i=0, ilen=linearRing.components.length; i<ilen; i++) { // comp = linearRing.components[i]; // x = comp.x / resolution - this.offset.x; // y = comp.y / resolution - this.offset.y; // vertices.push([parseInt(x.toFixed()), parseInt(y.toFixed())]); // } // } // // var point1 = new Object(); // point1.x = (vertices[0][0] + vertices[1][0])/2; // point1.y = (vertices[0][1] + vertices[1][1])/2; // // var point2 = new Object(); // point2.x = (vertices[2][0] + vertices[3][0])/2; // point2.y = (vertices[2][1] + vertices[3][1])/2; // // // // Flip y // var y = label.coordorigin.y; // // var point1FlipY = new Object(); // point1FlipY.y = y - (point1.y - y) + label.coordsize.y; // // var point2FlipY = new Object(); // point2FlipY.y = y - (point2.y - y) + label.coordsize.y; // label.path = " m" + point1.x.toFixed() + "," + point1FlipY.y.toFixed() + " l" + point2.x.toFixed() + "," + point2FlipY.y.toFixed() + " e"; // // // var path = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_path", "olv:path"); // path.textpathok = true; // label.appendChild(path); // // var textbox = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_textpath", "olv:textpath"); // textbox.string = style.label; // textbox.on = true; // // label.stroke.on = false; // if (style.fontColor) { // label.fillcolor = style.fontColor; // } // if (style.fontFamily) { // textbox.style.fontFamily = style.fontFamily; // } // if (style.fontSize) { // textbox.style.fontSize = style.fontSize; // } // if (style.fontWeight) { // textbox.style.fontWeight = style.fontWeight; // } // // label.appendChild(textbox); //############################### Rotate END }, /** * Method: drawSurface * * Parameters: * node - {DOMElement} * geometry - {<OpenLayers.Geometry>} * * Returns: * {DOMElement} */ drawSurface: function(node, geometry) { this.setNodeDimension(node, geometry); var resolution = this.getResolution(); var path = []; var comp, x, y; for (var i=0, len=geometry.components.length; i<len; i++) { comp = geometry.components[i]; x = (comp.x / resolution - this.offset.x) | 0; y = (comp.y / resolution - this.offset.y) | 0; if ((i%3)==0 && (i/3)==0) { path.push("m"); } else if ((i%3)==1) { path.push(" c"); } path.push(" " + x + "," + y); } path.push(" x e"); node.path = path.join(""); return node; }, /** * Method: moveRoot * moves this renderer's root to a different renderer. * * Parameters: * renderer - {<OpenLayers.Renderer>} target renderer for the moved root * root - {DOMElement} optional root node. To be used when this renderer * holds roots from multiple layers to tell this method which one to * detach * * Returns: * {Boolean} true if successful, false otherwise */ moveRoot: function(renderer) { var layer = this.map.getLayer(renderer.container.id); if(layer instanceof OpenLayers.Layer.Vector.RootContainer) { layer = this.map.getLayer(this.container.id); } layer && layer.renderer.clear(); OpenLayers.Renderer.Elements.prototype.moveRoot.apply(this, arguments); layer && layer.redraw(); }, /** * Method: importSymbol * add a new symbol definition from the rendererer's symbol hash * * Parameters: * graphicName - {String} name of the symbol to import * * Returns: * {Object} - hash of {DOMElement} "symbol" and {Number} "size" */ importSymbol: function (graphicName) { var id = this.container.id + "-" + graphicName; // check if symbol already exists in the cache var cache = this.symbolCache[id]; if (cache) { return cache; } var symbol = OpenLayers.Renderer.symbol[graphicName]; if (!symbol) { throw new Error(graphicName + ' is not a valid symbol name'); } var symbolExtent = new OpenLayers.Bounds( Number.MAX_VALUE, Number.MAX_VALUE, 0, 0); var pathitems = ["m"]; for (var i=0; i<symbol.length; i=i+2) { var x = symbol[i]; var y = symbol[i+1]; symbolExtent.left = Math.min(symbolExtent.left, x); symbolExtent.bottom = Math.min(symbolExtent.bottom, y); symbolExtent.right = Math.max(symbolExtent.right, x); symbolExtent.top = Math.max(symbolExtent.top, y); pathitems.push(x); pathitems.push(y); if (i == 0) { pathitems.push("l"); } } pathitems.push("x e"); var path = pathitems.join(" "); var diff = (symbolExtent.getWidth() - symbolExtent.getHeight()) / 2; if(diff > 0) { symbolExtent.bottom = symbolExtent.bottom - diff; symbolExtent.top = symbolExtent.top + diff; } else { symbolExtent.left = symbolExtent.left + diff; symbolExtent.right = symbolExtent.right - diff; } cache = { path: path, size: symbolExtent.getWidth(), // equals getHeight() now left: symbolExtent.left, bottom: symbolExtent.bottom }; this.symbolCache[id] = cache; return cache; }, CLASS_NAME: "OpenLayers.Renderer.VML" }); /** * Constant: OpenLayers.Renderer.VML.LABEL_SHIFT * {Object} */ OpenLayers.Renderer.VML.LABEL_SHIFT = { "l": 0, "c": .5, "r": 1, "t": 0, "m": .5, "b": 1 };
mit
xto3na/chat
Chat/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19486
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Chat.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
mit
ihidalgo/uip-prog3
Parciales/practicas/kivy-designer-master/designer/uix/contextual.py
22345
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem,\ TabbedPanelHeader, TabbedPanelContent from kivy.properties import ObjectProperty, StringProperty,\ BooleanProperty, NumericProperty from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.widget import Widget from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.uix.bubble import Bubble, BubbleButton from kivy.lang import Builder from kivy.metrics import dp from kivy.uix.scrollview import ScrollView from kivy.clock import Clock from kivy.uix.actionbar import ActionItem, ActionView class DesignerActionView(ActionView): '''Custom ActionView to support custom action group ''' def _layout_random(self): '''Handle custom action group ''' self.overflow_group.show_group = self.show_group super(DesignerActionView, self)._layout_random() def show_group(self, *l): '''Show custom groups ''' over = self.overflow_group over.clear_widgets() for item in over._list_overflow_items + over.list_action_item: item.inside_group = True if item.parent is not None: item.parent.remove_widget(item) group = self.get_group(item) if group is not None and group.disabled: continue if not isinstance(item, ContextSubMenu): over._dropdown.add_widget(item) def get_group(self, item): '''Get the ActionGroup of an item ''' for group in self._list_action_group: if item in group.list_action_item: return group return None class MenuBubble(Bubble): ''' ''' pass class MenuHeader(TabbedPanelHeader): '''MenuHeader class. To be used as default TabbedHeader. ''' show_arrow = BooleanProperty(False) '''Specifies whether to show arrow or not. :data:`show_arrow` is a :class:`~kivy.properties.BooleanProperty`, default to True ''' class ContextMenuException(Exception): '''ContextMenuException class ''' pass class MenuButton(Button): '''MenuButton class. Used as a default menu button. It auto provides look and feel for a menu button. ''' cont_menu = ObjectProperty(None) '''Reference to :class:`~designer.uix.contextual.ContextMenu`. ''' def on_release(self, *args): '''Default Event Handler for 'on_release' ''' self.cont_menu.dismiss() super(MenuButton, self).on_release(*args) class ContextMenu(TabbedPanel): '''ContextMenu class. See module documentation for more information. :Events: `on_select`: data Fired when a selection is done, with the data of the selection as first argument. Data is what you pass in the :meth:`select` method as first argument. `on_dismiss`: .. versionadded:: 1.8.0 Fired when the ContextMenu is dismissed either on selection or on touching outside the widget. ''' container = ObjectProperty(None) '''(internal) The container which will be used to contain Widgets of main menu. :data:`container` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`~kivy.uix.boxlayout.BoxLayout`. ''' main_tab = ObjectProperty(None) '''Main Menu Tab of ContextMenu. :data:`main_tab` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' bubble_cls = ObjectProperty(MenuBubble) '''Bubble Class, whose instance will be used to create container of ContextMenu. :data:`bubble_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuBubble`. ''' header_cls = ObjectProperty(MenuHeader) '''Header Class used to create Tab Header. :data:`header_cls` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`MenuHeader`. ''' attach_to = ObjectProperty(allownone=True) '''(internal) Property that will be set to the widget on which the drop down list is attached to. The method :meth:`open` will automatically set that property, while :meth:`dismiss` will set back to None. ''' auto_width = BooleanProperty(True) '''By default, the width of the ContextMenu will be the same as the width of the attached widget. Set to False if you want to provide your own width. ''' dismiss_on_select = BooleanProperty(True) '''By default, the ContextMenu will be automatically dismissed when a selection have been done. Set to False to prevent the dismiss. :data:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`, default to True. ''' max_height = NumericProperty(None, allownone=True) '''Indicate the maximum height that the dropdown can take. If None, it will take the maximum height available, until the top or bottom of the screen will be reached. :data:`max_height` is a :class:`~kivy.properties.NumericProperty`, default to None. ''' __events__ = ('on_select', 'on_dismiss') def __init__(self, **kwargs): self._win = None self.add_tab = super(ContextMenu, self).add_widget self.bubble = self.bubble_cls(size_hint=(None, None)) self.container = None self.main_tab = self.header_cls(text='Main') self.main_tab.content = ScrollView(size_hint=(1, 1)) self.main_tab.content.bind(height=self.on_scroll_height) super(ContextMenu, self).__init__(**kwargs) self.bubble.add_widget(self) self.bind(size=self._reposition) self.bubble.bind(on_height=self._bubble_height) def _bubble_height(self, *args): '''Handler for bubble's 'on_height' event. ''' self.height = self.bubble.height def open(self, widget): '''Open the dropdown list, and attach to a specific widget. Depending the position of the widget on the window and the height of the dropdown, the placement might be lower or higher off that widget. ''' # if trying to open a non-visible widget if widget.parent is None: return # ensure we are not already attached if self.attach_to is not None: self.dismiss() # we will attach ourself to the main window, so ensure the widget we are # looking for have a window self._win = widget.get_parent_window() if self._win is None: raise ContextMenuException( 'Cannot open a dropdown list on a hidden widget') self.attach_to = widget widget.bind(pos=self._reposition, size=self._reposition) self.add_tab(self.main_tab) self.switch_to(self.main_tab) self.main_tab.show_arrow = False self._reposition() # attach ourself to the main window self._win.add_widget(self.bubble) self.main_tab.color = (0, 0, 0, 0) def on_select(self, data): '''Default handler for 'on_select' event. ''' pass def dismiss(self, *largs): '''Remove the dropdown widget from the window, and detach itself from the attached widget. ''' if self.bubble.parent: self.bubble.parent.remove_widget(self.bubble) if self.attach_to: self.attach_to.unbind(pos=self._reposition, size=self._reposition) self.attach_to = None self.switch_to(self.main_tab) for child in self.tab_list[:]: self.remove_widget(child) self.dispatch('on_dismiss') def select(self, data): '''Call this method to trigger the `on_select` event, with the `data` selection. The `data` can be anything you want. ''' self.dispatch('on_select', data) if self.dismiss_on_select: self.dismiss() def on_dismiss(self): '''Default event handler for 'on_dismiss' event. ''' pass def _set_width_to_bubble(self, *args): '''To set self.width and bubble's width equal. ''' self.width = self.bubble.width def _reposition(self, *largs): # calculate the coordinate of the attached widget in the window # coordinate sysem win = self._win widget = self.attach_to if not widget or not win: return wx, wy = widget.to_window(*widget.pos) wright, wtop = widget.to_window(widget.right, widget.top) # set width and x if self.auto_width: # Calculate minimum required width if len(self.container.children) == 1: self.bubble.width = max(self.main_tab.parent.parent.width, self.container.children[0].width) else: self.bubble.width = max(self.main_tab.parent.parent.width, self.bubble.width, *([i.width for i in self.container.children])) Clock.schedule_once(self._set_width_to_bubble, 0.01) # ensure the dropdown list doesn't get out on the X axis, with a # preference to 0 in case the list is too wide. # try to center bubble with parent position x = wx - self.bubble.width / 4 if x + self.bubble.width > win.width: x = win.width - self.bubble.width if x < 0: x = 0 self.bubble.x = x # bubble position relative with the parent center x_relative = x - (wx - self.bubble.width / 4) x_range = self.bubble.width / 4 # consider 25% as the range # determine if we display the dropdown upper or lower to the widget h_bottom = wy - self.bubble.height h_top = win.height - (wtop + self.bubble.height) def _get_hpos(): '''Compare the position of the widget with the parent to display the arrow in the correct position ''' _pos = 'mid' if x_relative == 0: _pos = 'mid' elif x_relative < -x_range: _pos = 'right' elif x_relative > x_range: _pos = 'left' return _pos if h_bottom > 0: self.bubble.top = wy self.bubble.arrow_pos = 'top_' + _get_hpos() elif h_top > 0: self.bubble.y = wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() else: # none of both top/bottom have enough place to display the widget at # the current size. Take the best side, and fit to it. height = max(h_bottom, h_top) if height == h_bottom: self.bubble.top = wy self.bubble.height = wy self.bubble.arrow_pos = 'top_' + _get_hpos() else: self.bubble.y = wtop self.bubble.height = win.height - wtop self.bubble.arrow_pos = 'bottom_' + _get_hpos() def on_touch_down(self, touch): '''Default Handler for 'on_touch_down' ''' if super(ContextMenu, self).on_touch_down(touch): return True if self.collide_point(*touch.pos): return True self.dismiss() def on_touch_up(self, touch): '''Default Handler for 'on_touch_up' ''' if super(ContextMenu, self).on_touch_up(touch): return True self.dismiss() def add_widget(self, widget, index=0): '''Add a widget. ''' if self.content is None: return if widget.parent is not None: widget.parent.remove_widget(widget) if self.tab_list and widget == self.tab_list[0].content or\ widget == self._current_tab.content or \ self.content == widget or\ self._tab_layout == widget or\ isinstance(widget, TabbedPanelContent) or\ isinstance(widget, TabbedPanelHeader): super(ContextMenu, self).add_widget(widget, index) return if not self.container: self.container = GridLayout(orientation='vertical', size_hint_y=None, cols=1) self.main_tab.content.add_widget(self.container) self.container.bind(height=self.on_main_box_height) self.container.add_widget(widget, index) if hasattr(widget, 'cont_menu'): widget.cont_menu = self widget.bind(height=self.on_child_height) widget.size_hint_y = None def remove_widget(self, widget): '''Remove a widget ''' if self.container and widget in self.container.children: self.container.remove_widget(widget) else: super(ContextMenu, self).remove_widget(widget) def on_scroll_height(self, *args): '''Event Handler for scollview's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) def on_main_box_height(self, *args): '''Event Handler for main_box's height. ''' if not self.container: return self.container.height = max(self.container.height, self.main_tab.content.height) if self.max_height: self.bubble.height = min(self.container.height + self.tab_height + dp(16), self.max_height) else: self.bubble.height = self.container.height + \ self.tab_height + dp(16) def on_child_height(self, *args): '''Event Handler for children's height. ''' height = 0 for i in self.container.children: height += i.height self.main_tab.content.height = height self.container.height = height def add_tab(self, widget, index=0): '''To add a Widget as a new Tab. ''' super(ContextMenu, self).add_widget(widget, index) class ContextSubMenu(MenuButton): '''ContextSubMenu class. To be used to add a sub menu. ''' attached_menu = ObjectProperty(None) '''(internal) Menu attached to this sub menu. :data:`attached_menu` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' cont_menu = ObjectProperty(None) '''(internal) Reference to the main ContextMenu. :data:`cont_menu` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' container = ObjectProperty(None) '''(internal) The container which will be used to contain Widgets of main menu. :data:`container` is a :class:`~kivy.properties.ObjectProperty`, default to :class:`~kivy.uix.boxlayout.BoxLayout`. ''' show_arrow = BooleanProperty(False) '''(internal) To specify whether ">" arrow image should be shown in the header or not. If there exists a child menu then arrow image will be shown otherwise not. :data:`show_arrow` is a :class:`~kivy.properties.BooleanProperty`, default to False ''' def __init__(self, **kwargs): super(ContextSubMenu, self).__init__(**kwargs) self._list_children = [] def on_text(self, *args): '''Default handler for text. ''' if self.attached_menu: self.attached_menu.text = self.text def on_attached_menu(self, *args): '''Default handler for attached_menu. ''' self.attached_menu.text = self.text def add_widget(self, widget, index=0): '''Add a widget. ''' if isinstance(widget, Image): Button.add_widget(self, widget, index) return self._list_children.append((widget, index)) if hasattr(widget, 'cont_menu'): widget.cont_menu = self.cont_menu def remove_children(self): '''Clear _list_children[] ''' for child, index in self._list_children: self.container.remove_widget(child) self._list_children = [] def on_cont_menu(self, *args): '''Default handler for cont_menu. ''' self._add_widget() def _add_widget(self, *args): if not self.cont_menu: return if not self.attached_menu: self.attached_menu = self.cont_menu.header_cls(text=self.text) self.attached_menu.content = ScrollView(size_hint=(1, 1)) self.attached_menu.content.bind(height=self.on_scroll_height) self.container = GridLayout(orientation='vertical', size_hint_y=None, cols=1) self.attached_menu.content.add_widget(self.container) self.container.bind(height=self.on_container_height) for widget, index in self._list_children: self.container.add_widget(widget, index) widget.cont_menu = self.cont_menu widget.bind(height=self.on_child_height) def on_scroll_height(self, *args): '''Handler for scrollview's height. ''' self.container.height = max(self.container.minimum_height, self.attached_menu.content.height) def on_container_height(self, *args): '''Handler for container's height. ''' self.container.height = max(self.container.minimum_height, self.attached_menu.content.height) def on_child_height(self, *args): '''Handler for children's height. ''' height = 0 for i in self.container.children: height += i.height self.container.height = height def on_release(self, *args): '''Default handler for 'on_release' event. ''' if not self.attached_menu or not self._list_children: return try: index = self.cont_menu.tab_list.index(self.attached_menu) self.cont_menu.switch_to(self.cont_menu.tab_list[index]) tab = self.cont_menu.tab_list[index] if hasattr(tab, 'show_arrow') and index != 0: tab.show_arrow = True else: tab.show_arrow = False except: if not self.cont_menu.current_tab in self.cont_menu.tab_list: return curr_index = self.cont_menu.tab_list.index( self.cont_menu.current_tab) for i in range(curr_index - 1, -1, -1): self.cont_menu.remove_widget(self.cont_menu.tab_list[i]) self.cont_menu.add_tab(self.attached_menu) self.cont_menu.switch_to(self.cont_menu.tab_list[0]) if hasattr(self.cont_menu.tab_list[1], 'show_arrow'): self.cont_menu.tab_list[1].show_arrow = True else: self.cont_menu.tab_list[1].show_arrow = False from kivy.clock import Clock Clock.schedule_once(self._scroll, 0.1) def _scroll(self, dt): '''To scroll ContextMenu's strip to appropriate place. ''' from kivy.animation import Animation self.cont_menu._reposition() total_tabs = len(self.cont_menu.tab_list) tab_list = self.cont_menu.tab_list curr_index = total_tabs - tab_list.index(self.cont_menu.current_tab) to_scroll = len(tab_list) / curr_index anim = Animation(scroll_x=to_scroll, d=0.75) anim.cancel_all(self.cont_menu.current_tab.parent.parent) anim.start(self.cont_menu.current_tab.parent.parent) if __name__ == '__main__': from kivy.app import App class ActionContext(ContextSubMenu, ActionItem): pass Builder.load_string(''' #:import ContextMenu contextual.ContextMenu <ContextMenu>: <DesignerActionView>: <Test>: ActionBar: pos_hint: {'top':1} DesignerActionView: use_separator: True ActionPrevious: title: 'Action Bar' with_previous: False ActionOverflow: ActionButton: text: 'Btn0' icon: 'atlas://data/images/defaulttheme/audio-volume-high' ActionButton: text: 'Btn1' ActionButton: text: 'Btn2' ActionButton: text: 'Btn3' ActionButton: text: 'Btn4' ActionGroup: mode: 'spinner' text: 'Group1' dropdown_cls: ContextMenu ActionButton: text: 'Btn5' height: 30 size_hint_y: None ActionButton: text: 'Btnddddddd6' height: 30 size_hint_y: None ActionButton: text: 'Btn7' height: 30 size_hint_y: None ActionContext: text: 'Item2' size_hint_y: None height: 30 ActionButton: text: '2->1' size_hint_y: None height: 30 ActionButton: text: '2->2' size_hint_y: None height: 30 ActionButton: text: '2->2' size_hint_y: None height: 30 ''') class CMenu(ContextMenu): pass class Test(FloatLayout): def __init__(self, **kwargs): super(Test, self).__init__(**kwargs) self.context_menu = CMenu() def add_menu(self, obj, *l): self.context_menu = CMenu() self.context_menu.open(self.children[0]) class MyApp(App): def build(self): return Test() MyApp().run()
mit
iMartinezMateu/gamecraft
gamecraft-slack-notification-manager/src/main/java/com/gamecraft/service/dto/SlackMessage.java
995
package com.gamecraft.service.dto; import java.util.Arrays; public class SlackMessage { private String[] channels; private String[] users; private String message; public SlackMessage() { } public String[] getChannels() { return channels; } public void setChannels(String[] channels) { this.channels = channels; } public String[] getUsers() { return users; } public void setUsers(String[] users) { this.users = users; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "SlackMessage{" + (channels != null ? "channels=" + Arrays.toString(channels) + ", " : "") + (users != null ? "users=" + Arrays.toString(users) + ", " : "") + (message != null ? "message=" + message + ", " : "") + "}"; } }
mit
cujo/content
src/Cache/Cache.php
1453
<?php namespace Cujo\Content\Cache; use Cujo\Content\Content; use Cujo\Content\Proxy; abstract class Cache extends Proxy { protected $prefix; protected $ttl; public function __construct($content, $prefix = null, $ttl = null) { parent::__construct($content); $this->prefix = $prefix; $this->ttl = $ttl; } abstract protected function getFromCache($key); abstract protected function addToCache($key, $value, $ttl); abstract protected function deleteFromCache($key); protected function getCacheKey($key) { return $this->prefix . $key; } protected function createCache(Content $content, $prefix, $ttl) { $class = new get_class(); return new $class($value, $prefix, $ttl); } public function get($key) { $cacheKey = $this->getCacheKey($key); $value = $this->getFromCache($cacheKey); if (false === $value) { $value = parent::get($key); $this->addToCache($cacheKey, $value, $this->ttl); } if ($value instanceof Content) { $value = $this->createCache($value, $cacheKey . '#', $this->ttl); } return $value; } public function set($key, $value) { $this->deleteFromCache($key); parent::set($key, $value); } public function remove($key) { $this->deleteFromCache($key); parent::remove($key); } }
mit
open-city/school-admissions
api/__init__.py
265
from flask import Flask from api.endpoints import endpoints from api.views import views def create_app(): app = Flask(__name__) app.config.from_object('api.app_config') app.register_blueprint(endpoints) app.register_blueprint(views) return app
mit
php-api-clients/github
src/Resource/Repository/Milestone.php
2011
<?php declare(strict_types=1); namespace ApiClients\Client\Github\Resource\Repository; use ApiClients\Foundation\Hydrator\Annotation\EmptyResource; use ApiClients\Foundation\Hydrator\Annotation\Nested; use ApiClients\Foundation\Resource\AbstractResource; /** * @Nested( * creator="User" * ) * @EmptyResource("Repository\EmptyMilestone") */ abstract class Milestone extends AbstractResource implements MilestoneInterface { /** * @var int */ protected $id; /** * @var int */ protected $number; /** * @var string */ protected $state; /** * @var string */ protected $title; /** * @var string */ protected $description; /** * @var User */ protected $creator; /** * @var int */ protected $open_issues; /** * @var int */ protected $closed_issues; /** * @var string */ protected $url; /** * @return int */ public function id(): int { return $this->id; } /** * @return int */ public function number(): int { return $this->number; } /** * @return string */ public function state(): string { return $this->state; } /** * @return string */ public function title(): string { return $this->title; } /** * @return string */ public function description(): string { return $this->description; } /** * @return User */ public function creator(): User { return $this->creator; } /** * @return int */ public function openIssues(): int { return $this->open_issues; } /** * @return int */ public function closedIssues(): int { return $this->closed_issues; } /** * @return string */ public function url(): string { return $this->url; } }
mit
szhnet/kcp-netty
kcp-example/src/main/java/io/jpower/kcp/example/echo/EchoServerHandler.java
989
package io.jpower.kcp.example.echo; import io.jpower.kcp.netty.UkcpChannel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * Handler implementation for the echo server. * * @author <a href="mailto:[email protected]">szh</a> */ public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { UkcpChannel kcpCh = (UkcpChannel) ctx.channel(); kcpCh.conv(EchoServer.CONV); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. cause.printStackTrace(); ctx.close(); } }
mit
prack/php-rb
test/unit/io_file_test.php
2011
<?php class Prb_IO_FileTest extends PHPUnit_Framework_TestCase { /** * It should indicate writability correctly * @author Joshua Morris * @test */ public function It_should_indicate_writability_correctly() { $filepath = Prb_IO_Tempfile::generatePath(); $file = Prb_IO::withFile( $filepath, Prb_IO_File::APPEND_AS_WRITE ); $this->assertTrue( $file->isWritable() ); $this->assertFalse( $file->isReadable() ); $file->close(); $file = Prb_IO::withFile( $filepath, Prb_IO_File::NO_CREATE_READ ); $this->assertFalse( $file->isWritable() ); $this->assertTrue( $file->isReadable() ); $file->close(); $file->unlink(); } // It should indicate writability correctly /** * It should throw an exception when file at specified path is inaccessible * @author Joshua Morris * @test */ public function It_should_throw_an_exception_when_file_at_specified_path_is_inaccessible() { $filepath = Prb_IO_Tempfile::generatePath().Prb::Time()->getSeconds(); try { $file = Prb_IO::withFile( $filepath, Prb_IO_File::NO_CREATE_READ ); } catch ( Prb_Exception_System_ErrnoENOENT $e1 ) {}; if ( isset( $e1 ) ) $this->assertRegExp( '/file not found for no-create open/', $e1->getMessage() ); else $this->fail( "Excpected exception on no-create IO instantiation when file doesn't exist." ); } // It should throw an exception when file at specified path is inaccessible /** * It should know if it was opened in binary mode * @author Joshua Morris * @test */ public function It_should_know_if_it_was_opened_in_binary_mode() { $filepath = Prb_IO_Tempfile::generatePath(); $file = Prb_IO::withFile( $filepath, Prb_IO_File::APPEND_AS_WRITE | Prb_IO_File::FORCE_TEXT ); $this->assertFalse( $file->isBinMode() ); $file->close(); $file = Prb_IO::withFile( $filepath, Prb_IO_File::NO_CREATE_READ ); $this->assertTrue( $file->isBinMode() ); $file->close(); $file->delete(); } // It should know if it was opened in binary mode }
mit
dmpayton/django-flanker
tests/models.py
272
from django.db import models from django_flanker.models import EmailField class Person(models.Model): name = models.CharField(max_length=100) email = EmailField(max_length=254) def __unicode__(self): return '{0} <{1}>'.format(self.name, self.email)
mit
Olyvko/oxrom
application/models/oxfilecollector.php
4094
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OXID eShop Community Edition is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @copyright (C) OXID eSales AG 2003-2016 * @version OXID eShop CE */ /** * Directory reader. * Performs reading of file list of one shop directory * */ class oxFileCollector { /** * base directory * * @var string */ protected $_sBaseDirectory; /** * array of collected files * * @var array */ protected $_aFiles; /** * Setter for working directory * * @param string $sDir Directory */ public function setBaseDirectory($sDir) { if (!empty($sDir)) { $this->_sBaseDirectory = $sDir; } } /** * get collection files * * @return mixed */ public function getFiles() { return $this->_aFiles; } /** * Add one file to collection if it exists * * @param string $sFile file name to add to collection * * @throws Exception * @return null */ public function addFile($sFile) { if (empty($sFile)) { throw new Exception('Parameter $sFile is empty!'); } if (empty($this->_sBaseDirectory)) { throw new Exception('Base directory is not set, please use setter setBaseDirectory!'); } if (is_file($this->_sBaseDirectory . $sFile)) { $this->_aFiles[] = $sFile; return true; } return false; } /** * browse all folders and sub-folders after files which have given extensions * * @param string $sFolder which is explored * @param array $aExtensions list of extensions to scan - if empty all files are taken * @param boolean $blRecursive should directories be checked in recursive manner * * @throws exception * @return null */ public function addDirectoryFiles($sFolder, $aExtensions = array(), $blRecursive = false) { if (empty($sFolder)) { throw new Exception('Parameter $sFolder is empty!'); } if (empty($this->_sBaseDirectory)) { throw new Exception('Base directory is not set, please use setter setBaseDirectory!'); } $aCurrentList = array(); if (!is_dir($this->_sBaseDirectory . $sFolder)) { return; } $handle = opendir($this->_sBaseDirectory . $sFolder); while ($sFile = readdir($handle)) { if ($sFile != "." && $sFile != "..") { if (is_dir($this->_sBaseDirectory . $sFolder . $sFile)) { if ($blRecursive) { $aResultList = $this->addDirectoryFiles($sFolder . $sFile . '/', $aExtensions, $blRecursive); if (is_array($aResultList)) { $aCurrentList = array_merge($aCurrentList, $aResultList); } } } else { $sExt = substr(strrchr($sFile, '.'), 1); if ((!empty($aExtensions) && is_array($aExtensions) && in_array($sExt, $aExtensions)) || (empty($aExtensions)) ) { $this->addFile($sFolder . $sFile); } } } } closedir($handle); } }
mit
dmincu/IOC
new_php/closure-library/closure/goog/testing/fs/file.js
1639
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Mock file object. * */ goog.provide('goog.testing.fs.File'); goog.require('goog.testing.fs.Blob'); /** * A mock file object. * * @param {string} name The name of the file. * @param {Date=} opt_lastModified The last modified date for this file. May be * null if file modification dates are not supported. * @param {string=} opt_data The string data encapsulated by the blob. * @param {string=} opt_type The mime type of the blob. * @constructor * @extends {goog.testing.fs.Blob} * @final */ goog.testing.fs.File = function(name, opt_lastModified, opt_data, opt_type) { goog.base(this, opt_data, opt_type); /** * @see http://www.w3.org/TR/FileAPI/#dfn-name * @type {string} */ this.name = name; /** * @see http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate * @type {Date} */ this.lastModifiedDate = opt_lastModified || null; }; goog.inherits(goog.testing.fs.File, goog.testing.fs.Blob);
mit
BookingBug/bookingbug_yellowfin
db/migrate/20141110144754_create_bookingbug_yellowfin_booking_details.rb
1039
class CreateBookingbugYellowfinBookingDetails < ActiveRecord::Migration def change create_table :bookingbug_yellowfin_booking_details do |t| t.integer :booking_id t.integer :slot_id t.string :company_id t.string :booking_created_at t.string :yf_format_booking_created_at t.integer :member_id t.string :service t.string :resource t.string :person t.string :session t.string :just_date t.string :yf_format_just_date t.string :day_of_week t.string :month t.string :just_time t.string :duration t.string :price t.integer :paid t.string :s_status t.string :coupon_code t.integer :repeat_booking_id t.integer :purchase_item_id t.string :cancellation_date t.string :late_cancel t.string :attended t.string :name t.string :channel t.string :readable_current_multi_stat t.text :notes t.string :feedback t.string :pretty_print_multi_status end end end
mit
smiffytech/raspidev-public
software/i2cinit.py
246
#!/usr/bin/python import smbus bus = smbus.SMBus(1) # Setup I2C bus multiplexer (address: 0x70) # 0xx - no channel selected # 100 - channel 0 selected # 101 - channel 1 selected # 11x - no channel selected bus.write_byte_data(0x70, 0, 0x04)
mit
DonJayamanne/pythonVSCode
src/client/interpreter/configuration/interpreterSelector/commands/resetInterpreter.ts
1594
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. 'use strict'; import { inject, injectable } from 'inversify'; import { IApplicationShell, ICommandManager, IWorkspaceService } from '../../../../common/application/types'; import { Commands } from '../../../../common/constants'; import { IPythonPathUpdaterServiceManager } from '../../types'; import { BaseInterpreterSelectorCommand } from './base'; @injectable() export class ResetInterpreterCommand extends BaseInterpreterSelectorCommand { constructor( @inject(IPythonPathUpdaterServiceManager) pythonPathUpdaterService: IPythonPathUpdaterServiceManager, @inject(ICommandManager) commandManager: ICommandManager, @inject(IApplicationShell) applicationShell: IApplicationShell, @inject(IWorkspaceService) workspaceService: IWorkspaceService, ) { super(pythonPathUpdaterService, commandManager, applicationShell, workspaceService); } public async activate() { this.disposables.push( this.commandManager.registerCommand(Commands.ClearWorkspaceInterpreter, this.resetInterpreter.bind(this)), ); } public async resetInterpreter() { const targetConfig = await this.getConfigTarget(); if (!targetConfig) { return; } const configTarget = targetConfig.configTarget; const wkspace = targetConfig.folderUri; await this.pythonPathUpdaterService.updatePythonPath(undefined, configTarget, 'ui', wkspace); } }
mit
aneeshdash/library-app
app/views/user/contacts.blade.php
4002
@extends('user.master') @section('title') Library | Contacts @endsection @section('main_content') <div class=row"> <div class="col-lg-9"> <div class="showback"> <h3><i class="fa fa-angle-right"></i> Contact Librarian</h3><br><br> <h4><i class="fa fa-user"></i> Sanket Dayma</h4> <h4><i class="fa fa-phone"></i> 9085295067</h4> <h4><i class="fa fa-envelope-o"></i> [email protected]</h4> </div><!-- /showback --> </div> <div class="col-lg-3 ds"> <!--COMPLETED ACTIONS DONUTS CHART--> <h3>Quick links</h3> <!-- First Action --> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://jatinga.iitg.ernet.in/cseintranet/">CSE</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://www.iitg.ernet.in/acad/acadCal/academic_calander.htm">ACADEMIC CALENDER</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://bidya.iitg.ernet.in:8680/opac/">CENTRAL LIBRARY</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="repo.cse.iitg.ernet.in">SOFTWARE REPOSITORY</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="https://intranet.iitg.ernet.in/moodle/login/index.php">MOODLE</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="https://webmail.iitg.ernet.in/src/login.php">WEBMAIL</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://shilloi.iitg.ernet.in/~acad/intranet/courses_syllabee.php">COURSES AND SYLLABUS</a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://shilloi.iitg.ernet.in/~acad/intranet/index.php">ACADMIC SECTION </a> </div> </div> <div class="desc"> <div class="thumb"> <span class="badge bg-theme"><i class="fa fa-tag"></i></span> </div> <div class="details"> <a href="http://shilloi.iitg.ernet.in/~acad/intranet/tt/ctt.htm">CLASS TIME TABLE</a> </div> </div> </div><!-- /col-lg-3 --> @endsection @section('user-contacts') active @endsection @section('scripts') @endsection
mit
harrystech/hyppo-worker
worker/src/main/scala/com/harrys/hyppo/HyppoWorker.scala
3342
package com.harrys.hyppo import javax.inject.{Inject, Singleton} import akka.actor._ import akka.pattern.gracefulStop import com.codahale.metrics.MetricRegistry import com.google.inject.{Guice, Injector, Provider} import com.harrys.hyppo.config.{HyppoWorkerModule, WorkerConfig} import com.harrys.hyppo.util.ConfigUtils import com.harrys.hyppo.worker.actor.WorkerFSM import com.harrys.hyppo.worker.actor.amqp.QueueHelpers import com.harrys.hyppo.worker.actor.queue.WorkDelegation import com.sandinh.akuice.ActorInject import com.thenewmotion.akka.rabbitmq._ import com.typesafe.config.Config import scala.concurrent.duration._ import scala.concurrent.{Await, Future} /** * Created by jpetty on 8/28/15. */ @Singleton final class HyppoWorker @Inject() ( injectorProvider: Provider[Injector], system: ActorSystem, config: WorkerConfig, workerFactory: WorkerFSM.Factory ) extends ActorInject { override def injector: Injector = injectorProvider.get() val connection = system.actorOf(ConnectionActor.props(config.rabbitMQConnectionFactory, reconnectionDelay = config.rabbitMQTimeout, initializeConnection), name = "rabbitmq") val delegation = injectTopActor[WorkDelegation]("delegation") val workerFSMs = (1 to config.workerCount).inclusive.map(i => createWorker(i)) system.registerOnTermination({ delegation ! Lifecycle.ImpendingShutdown val workerWait = FiniteDuration(config.shutdownTimeout.mul(0.8).toMillis, MILLISECONDS) val futures = workerFSMs.map(ref => gracefulStop(ref, workerWait, Lifecycle.ImpendingShutdown)) implicit val ec = system.dispatcher Await.result(Future.sequence(futures), config.shutdownTimeout) }) def suspendUntilSystemTermination(): Unit = { Await.result(system.whenTerminated, Duration.Inf) } def shutdownActorSystem(timeout: Duration): Unit = { Await.result(system.terminate(), timeout) } private def createWorker(number: Int): ActorRef = { implicit val topLevel = system injectActor(workerFactory(delegation, connection), "worker-%02d".format(number)) } private def initializeConnection(connection: Connection, actor: ActorRef): Unit = { val helpers = new QueueHelpers(config) helpers.initializeRequiredQueues(connection) } } object HyppoWorker { def apply(system: ActorSystem): HyppoWorker = { apply(system, createConfig(system.settings.config)) } def apply[M <: HyppoWorkerModule](system: ActorSystem, config: WorkerConfig): HyppoWorker = { val module = new HyppoWorkerModule { override protected def configureSpecializedBindings(): Unit = { bind(classOf[ActorSystem]).toInstance(system) bind(classOf[WorkerConfig]).toInstance(config) bind(classOf[MetricRegistry]).asEagerSingleton() } } val injector = Guice.createInjector(module) injector.getInstance(classOf[HyppoWorker]) } def createConfig(appConfig: Config): WorkerConfig = { val config = appConfig.withFallback(referenceConfig()) val merged = requiredConfig() .withFallback(config) .resolve() new WorkerConfig(merged) } def requiredConfig(): Config = ConfigUtils.resourceFileConfig("/com/harrys/hyppo/config/required.conf") def referenceConfig(): Config = ConfigUtils.resourceFileConfig("/com/harrys/hyppo/config/reference.conf") }
mit
ollyau/MDLXChecker
MDLXChecker/Program.cs
6235
using iniLib; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace MDLXChecker { class Program { static void Main(string[] args) { Console.WriteLine(string.Format("MDLX Checker by Orion Lyau\r\nVersion: {0}\r\n", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)); try { Init(); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine("\r\nPress any key to close."); Console.ReadKey(); } static void Init() { var parser = new ArgumentParser(); List<Simulator> sims = new List<Simulator>(); if (!parser.Check("sim", (arg) => { if (arg.Equals("fsx", StringComparison.InvariantCultureIgnoreCase)) { sims.Add(new FlightSimulatorX()); } if (arg.Equals("esp", StringComparison.InvariantCultureIgnoreCase)) { sims.Add(new EnterpriseSimulationPlatform()); } else if (arg.Equals("p3d", StringComparison.InvariantCultureIgnoreCase)) { sims.Add(new Prepar3D()); } else if (arg.Equals("p3d2", StringComparison.InvariantCultureIgnoreCase)) { sims.Add(new Prepar3D2()); } else if (arg.Equals("fsxse", StringComparison.InvariantCultureIgnoreCase)) { sims.Add(new FlightSimulatorXSteamEdition()); } })) { List<Simulator> allSims = new List<Simulator>(); allSims.Add(new FlightSimulatorX()); allSims.Add(new EnterpriseSimulationPlatform()); allSims.Add(new Prepar3D()); allSims.Add(new Prepar3D2()); allSims.Add(new FlightSimulatorXSteamEdition()); sims = new List<Simulator>(allSims.Where(x => x.Directory != Simulator.NOT_FOUND)); } if (sims.Count == 0) { Console.WriteLine("No simulators found."); return; } foreach (var sim in sims) { Console.WriteLine("Simulator: {0}\r\n", sim.Name); var modelTypes = ModelTypes(new SimConfig(sim).SimObjectDirectories()); var notNative = modelTypes.Where(x => !x.Value.Equals("MDLX")); foreach (var mdl in notNative) { Console.WriteLine("{0}, {1}", mdl.Key, mdl.Value); } } } private static Dictionary<string, string> ModelTypes(List<string> directories) { string[] filenames = { "aircraft.cfg", "sim.cfg" }; string[] models = { "normal", "interior" }; Dictionary<string, string> modelTypes = new Dictionary<string, string>(); foreach (var objectsDir in directories) { if (!Directory.Exists(objectsDir)) { continue; } foreach (var objectDir in Directory.GetDirectories(objectsDir)) { foreach (var name in filenames) { var cfgPath = Path.Combine(objectDir, name); if (!File.Exists(cfgPath)) { continue; } Ini simCfg = new Ini(cfgPath); foreach (string s in simCfg.GetCategoryNames().Where(x => x.StartsWith("fltsim."))) { if (simCfg.KeyValueExists(s, "visual_model_guid")) { Console.WriteLine("{0} {1} not checked (model referenced using visual_model_guid)", cfgPath, s); continue; } var modelFolderName = simCfg.GetKeyValue(s, "model"); var modelFolderPath = string.IsNullOrWhiteSpace(modelFolderName) ? Path.Combine(objectDir, "model") : Path.Combine(objectDir, "model." + modelFolderName); var modelCfgPath = Path.Combine(modelFolderPath, "model.cfg"); if (!File.Exists(modelCfgPath)) { Console.WriteLine("{0} {1} not checked (missing model.cfg)", cfgPath, s); continue; } Ini modelCfg = new Ini(modelCfgPath); foreach (string m in models) { if (modelCfg.KeyValueExists("models", m)) { var modelName = modelCfg.GetKeyValue("models", m); if (modelName.EndsWith(".mdl", StringComparison.InvariantCultureIgnoreCase)) { modelName = modelName.Substring(0, modelName.Length - 4); } var modelPath = Path.Combine(modelFolderPath, modelName + ".mdl"); if (modelTypes.Keys.Contains(modelPath)) { continue; } if (File.Exists(modelPath)) { byte[] data = new byte[4]; using (var fstream = new FileStream(modelPath, FileMode.Open, FileAccess.Read)) { fstream.Seek(8, SeekOrigin.Begin); fstream.Read(data, 0, 4); } modelTypes.Add(modelPath, Encoding.UTF8.GetString(data)); } else { Console.WriteLine("Missing model: {0}", modelPath); } } } } } } } return modelTypes; } } }
mit
xhhjin/heroku-ghost
node_modules/sqlite3/src/database.cc
20171
#include <string.h> #include <node.h> #include "macros.h" #include "database.h" #include "statement.h" using namespace node_sqlite3; Persistent<FunctionTemplate> Database::constructor_template; void Database::Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Database")); NODE_SET_PROTOTYPE_METHOD(constructor_template, "close", Close); NODE_SET_PROTOTYPE_METHOD(constructor_template, "exec", Exec); NODE_SET_PROTOTYPE_METHOD(constructor_template, "wait", Wait); NODE_SET_PROTOTYPE_METHOD(constructor_template, "loadExtension", LoadExtension); NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", Serialize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "parallelize", Parallelize); NODE_SET_PROTOTYPE_METHOD(constructor_template, "configure", Configure); NODE_SET_GETTER(constructor_template, "open", OpenGetter); target->Set(String::NewSymbol("Database"), constructor_template->GetFunction()); } void Database::Process() { if (!open && locked && !queue.empty()) { EXCEPTION(String::New("Database handle is closed"), SQLITE_MISUSE, exception); Local<Value> argv[] = { exception }; bool called = false; // Call all callbacks with the error object. while (!queue.empty()) { Call* call = queue.front(); if (!call->baton->callback.IsEmpty() && call->baton->callback->IsFunction()) { TRY_CATCH_CALL(handle_, call->baton->callback, 1, argv); called = true; } queue.pop(); // We don't call the actual callback, so we have to make sure that // the baton gets destroyed. delete call->baton; delete call; } // When we couldn't call a callback function, emit an error on the // Database object. if (!called) { Local<Value> args[] = { String::NewSymbol("error"), exception }; EMIT_EVENT(handle_, 2, args); } return; } while (open && (!locked || pending == 0) && !queue.empty()) { Call* call = queue.front(); if (call->exclusive && pending > 0) { break; } queue.pop(); locked = call->exclusive; call->callback(call->baton); delete call; if (locked) break; } } void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) { if (!open && locked) { EXCEPTION(String::New("Database is closed"), SQLITE_MISUSE, exception); if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { exception }; TRY_CATCH_CALL(handle_, baton->callback, 1, argv); } else { Local<Value> argv[] = { String::NewSymbol("error"), exception }; EMIT_EVENT(handle_, 2, argv); } return; } if (!open || ((locked || exclusive || serialize) && pending > 0)) { queue.push(new Call(callback, baton, exclusive || serialize)); } else { locked = exclusive; callback(baton); } } Handle<Value> Database::New(const Arguments& args) { HandleScope scope; if (!args.IsConstructCall()) { return ThrowException(Exception::TypeError( String::New("Use the new operator to create new Database objects")) ); } REQUIRE_ARGUMENT_STRING(0, filename); int pos = 1; int mode; if (args.Length() >= pos && args[pos]->IsInt32()) { mode = args[pos++]->Int32Value(); } else { mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; } Local<Function> callback; if (args.Length() >= pos && args[pos]->IsFunction()) { callback = Local<Function>::Cast(args[pos++]); } Database* db = new Database(); db->Wrap(args.This()); args.This()->Set(String::NewSymbol("filename"), args[0]->ToString(), ReadOnly); args.This()->Set(String::NewSymbol("mode"), Integer::New(mode), ReadOnly); // Start opening the database. OpenBaton* baton = new OpenBaton(db, callback, *filename, mode); Work_BeginOpen(baton); return args.This(); } void Database::Work_BeginOpen(Baton* baton) { int status = uv_queue_work(uv_default_loop(), &baton->request, Work_Open, (uv_after_work_cb)Work_AfterOpen); assert(status == 0); } void Database::Work_Open(uv_work_t* req) { OpenBaton* baton = static_cast<OpenBaton*>(req->data); Database* db = baton->db; baton->status = sqlite3_open_v2( baton->filename.c_str(), &db->handle, baton->mode, NULL ); if (baton->status != SQLITE_OK) { baton->message = std::string(sqlite3_errmsg(db->handle)); sqlite3_close(db->handle); db->handle = NULL; } else { // Set default database handle values. sqlite3_busy_timeout(db->handle, 1000); } } void Database::Work_AfterOpen(uv_work_t* req) { HandleScope scope; OpenBaton* baton = static_cast<OpenBaton*>(req->data); Database* db = baton->db; Local<Value> argv[1]; if (baton->status != SQLITE_OK) { EXCEPTION(String::New(baton->message.c_str()), baton->status, exception); argv[0] = exception; } else { db->open = true; argv[0] = Local<Value>::New(Null()); } if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } else if (!db->open) { Local<Value> args[] = { String::NewSymbol("error"), argv[0] }; EMIT_EVENT(db->handle_, 2, args); } if (db->open) { Local<Value> args[] = { String::NewSymbol("open") }; EMIT_EVENT(db->handle_, 1, args); db->Process(); } delete baton; } Handle<Value> Database::OpenGetter(Local<String> str, const AccessorInfo& accessor) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(accessor.This()); return Boolean::New(db->open); } Handle<Value> Database::Close(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); OPTIONAL_ARGUMENT_FUNCTION(0, callback); Baton* baton = new Baton(db, callback); db->Schedule(Work_BeginClose, baton, true); return args.This(); } void Database::Work_BeginClose(Baton* baton) { assert(baton->db->locked); assert(baton->db->open); assert(baton->db->handle); assert(baton->db->pending == 0); baton->db->RemoveCallbacks(); int status = uv_queue_work(uv_default_loop(), &baton->request, Work_Close, (uv_after_work_cb)Work_AfterClose); assert(status == 0); } void Database::Work_Close(uv_work_t* req) { Baton* baton = static_cast<Baton*>(req->data); Database* db = baton->db; baton->status = sqlite3_close(db->handle); if (baton->status != SQLITE_OK) { baton->message = std::string(sqlite3_errmsg(db->handle)); } else { db->handle = NULL; } } void Database::Work_AfterClose(uv_work_t* req) { HandleScope scope; Baton* baton = static_cast<Baton*>(req->data); Database* db = baton->db; Local<Value> argv[1]; if (baton->status != SQLITE_OK) { EXCEPTION(String::New(baton->message.c_str()), baton->status, exception); argv[0] = exception; } else { db->open = false; // Leave db->locked to indicate that this db object has reached // the end of its life. argv[0] = Local<Value>::New(Null()); } // Fire callbacks. if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } else if (db->open) { Local<Value> args[] = { String::NewSymbol("error"), argv[0] }; EMIT_EVENT(db->handle_, 2, args); } if (!db->open) { Local<Value> args[] = { String::NewSymbol("close"), argv[0] }; EMIT_EVENT(db->handle_, 1, args); db->Process(); } delete baton; } Handle<Value> Database::Serialize(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); OPTIONAL_ARGUMENT_FUNCTION(0, callback); bool before = db->serialize; db->serialize = true; if (!callback.IsEmpty() && callback->IsFunction()) { TRY_CATCH_CALL(args.This(), callback, 0, NULL); db->serialize = before; } db->Process(); return args.This(); } Handle<Value> Database::Parallelize(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); OPTIONAL_ARGUMENT_FUNCTION(0, callback); bool before = db->serialize; db->serialize = false; if (!callback.IsEmpty() && callback->IsFunction()) { TRY_CATCH_CALL(args.This(), callback, 0, NULL); db->serialize = before; } db->Process(); return args.This(); } Handle<Value> Database::Configure(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); REQUIRE_ARGUMENTS(2); if (args[0]->Equals(String::NewSymbol("trace"))) { Local<Function> handle; Baton* baton = new Baton(db, handle); db->Schedule(RegisterTraceCallback, baton); } else if (args[0]->Equals(String::NewSymbol("profile"))) { Local<Function> handle; Baton* baton = new Baton(db, handle); db->Schedule(RegisterProfileCallback, baton); } else if (args[0]->Equals(String::NewSymbol("busyTimeout"))) { if (!args[1]->IsInt32()) { return ThrowException(Exception::TypeError( String::New("Value must be an integer")) ); } Local<Function> handle; Baton* baton = new Baton(db, handle); baton->status = args[1]->Int32Value(); db->Schedule(SetBusyTimeout, baton); } else { return ThrowException(Exception::Error(String::Concat( args[0]->ToString(), String::NewSymbol(" is not a valid configuration option") ))); } db->Process(); return args.This(); } void Database::SetBusyTimeout(Baton* baton) { assert(baton->db->open); assert(baton->db->handle); // Abuse the status field for passing the timeout. sqlite3_busy_timeout(baton->db->handle, baton->status); delete baton; } void Database::RegisterTraceCallback(Baton* baton) { assert(baton->db->open); assert(baton->db->handle); Database* db = baton->db; if (db->debug_trace == NULL) { // Add it. db->debug_trace = new AsyncTrace(db, TraceCallback); sqlite3_trace(db->handle, TraceCallback, db); } else { // Remove it. sqlite3_trace(db->handle, NULL, NULL); db->debug_trace->finish(); db->debug_trace = NULL; } delete baton; } void Database::TraceCallback(void* db, const char* sql) { // Note: This function is called in the thread pool. // Note: Some queries, such as "EXPLAIN" queries, are not sent through this. static_cast<Database*>(db)->debug_trace->send(new std::string(sql)); } void Database::TraceCallback(Database* db, std::string* sql) { // Note: This function is called in the main V8 thread. HandleScope scope; Local<Value> argv[] = { String::NewSymbol("trace"), String::New(sql->c_str()) }; EMIT_EVENT(db->handle_, 2, argv); delete sql; } void Database::RegisterProfileCallback(Baton* baton) { assert(baton->db->open); assert(baton->db->handle); Database* db = baton->db; if (db->debug_profile == NULL) { // Add it. db->debug_profile = new AsyncProfile(db, ProfileCallback); sqlite3_profile(db->handle, ProfileCallback, db); } else { // Remove it. sqlite3_profile(db->handle, NULL, NULL); db->debug_profile->finish(); db->debug_profile = NULL; } delete baton; } void Database::ProfileCallback(void* db, const char* sql, sqlite3_uint64 nsecs) { // Note: This function is called in the thread pool. // Note: Some queries, such as "EXPLAIN" queries, are not sent through this. ProfileInfo* info = new ProfileInfo(); info->sql = std::string(sql); info->nsecs = nsecs; static_cast<Database*>(db)->debug_profile->send(info); } void Database::ProfileCallback(Database *db, ProfileInfo* info) { HandleScope scope; Local<Value> argv[] = { String::NewSymbol("profile"), String::New(info->sql.c_str()), Integer::New((double)info->nsecs / 1000000.0) }; EMIT_EVENT(db->handle_, 3, argv); delete info; } void Database::RegisterUpdateCallback(Baton* baton) { assert(baton->db->open); assert(baton->db->handle); Database* db = baton->db; if (db->update_event == NULL) { // Add it. db->update_event = new AsyncUpdate(db, UpdateCallback); sqlite3_update_hook(db->handle, UpdateCallback, db); } else { // Remove it. sqlite3_update_hook(db->handle, NULL, NULL); db->update_event->finish(); db->update_event = NULL; } delete baton; } void Database::UpdateCallback(void* db, int type, const char* database, const char* table, sqlite3_int64 rowid) { // Note: This function is called in the thread pool. // Note: Some queries, such as "EXPLAIN" queries, are not sent through this. UpdateInfo* info = new UpdateInfo(); info->type = type; info->database = std::string(database); info->table = std::string(table); info->rowid = rowid; static_cast<Database*>(db)->update_event->send(info); } void Database::UpdateCallback(Database *db, UpdateInfo* info) { HandleScope scope; Local<Value> argv[] = { String::NewSymbol(sqlite_authorizer_string(info->type)), String::New(info->database.c_str()), String::New(info->table.c_str()), Integer::New(info->rowid), }; EMIT_EVENT(db->handle_, 4, argv); delete info; } Handle<Value> Database::Exec(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); REQUIRE_ARGUMENT_STRING(0, sql); OPTIONAL_ARGUMENT_FUNCTION(1, callback); Baton* baton = new ExecBaton(db, callback, *sql); db->Schedule(Work_BeginExec, baton, true); return args.This(); } void Database::Work_BeginExec(Baton* baton) { assert(baton->db->locked); assert(baton->db->open); assert(baton->db->handle); assert(baton->db->pending == 0); int status = uv_queue_work(uv_default_loop(), &baton->request, Work_Exec, (uv_after_work_cb)Work_AfterExec); assert(status == 0); } void Database::Work_Exec(uv_work_t* req) { ExecBaton* baton = static_cast<ExecBaton*>(req->data); char* message = NULL; baton->status = sqlite3_exec( baton->db->handle, baton->sql.c_str(), NULL, NULL, &message ); if (baton->status != SQLITE_OK && message != NULL) { baton->message = std::string(message); sqlite3_free(message); } } void Database::Work_AfterExec(uv_work_t* req) { HandleScope scope; ExecBaton* baton = static_cast<ExecBaton*>(req->data); Database* db = baton->db; if (baton->status != SQLITE_OK) { EXCEPTION(String::New(baton->message.c_str()), baton->status, exception); if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { exception }; TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } else { Local<Value> args[] = { String::NewSymbol("error"), exception }; EMIT_EVENT(db->handle_, 2, args); } } else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { Local<Value>::New(Null()) }; TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } db->Process(); delete baton; } Handle<Value> Database::Wait(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); OPTIONAL_ARGUMENT_FUNCTION(0, callback); Baton* baton = new Baton(db, callback); db->Schedule(Work_Wait, baton, true); return args.This(); } void Database::Work_Wait(Baton* baton) { HandleScope scope; assert(baton->db->locked); assert(baton->db->open); assert(baton->db->handle); assert(baton->db->pending == 0); if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { Local<Value>::New(Null()) }; TRY_CATCH_CALL(baton->db->handle_, baton->callback, 1, argv); } baton->db->Process(); delete baton; } Handle<Value> Database::LoadExtension(const Arguments& args) { HandleScope scope; Database* db = ObjectWrap::Unwrap<Database>(args.This()); REQUIRE_ARGUMENT_STRING(0, filename); OPTIONAL_ARGUMENT_FUNCTION(1, callback); Baton* baton = new LoadExtensionBaton(db, callback, *filename); db->Schedule(Work_BeginLoadExtension, baton, true); return args.This(); } void Database::Work_BeginLoadExtension(Baton* baton) { assert(baton->db->locked); assert(baton->db->open); assert(baton->db->handle); assert(baton->db->pending == 0); int status = uv_queue_work(uv_default_loop(), &baton->request, Work_LoadExtension, (uv_after_work_cb)Work_AfterLoadExtension); assert(status == 0); } void Database::Work_LoadExtension(uv_work_t* req) { LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data); sqlite3_enable_load_extension(baton->db->handle, 1); char* message = NULL; baton->status = sqlite3_load_extension( baton->db->handle, baton->filename.c_str(), 0, &message ); sqlite3_enable_load_extension(baton->db->handle, 0); if (baton->status != SQLITE_OK && message != NULL) { baton->message = std::string(message); sqlite3_free(message); } } void Database::Work_AfterLoadExtension(uv_work_t* req) { HandleScope scope; LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data); Database* db = baton->db; if (baton->status != SQLITE_OK) { EXCEPTION(String::New(baton->message.c_str()), baton->status, exception); if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { exception }; TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } else { Local<Value> args[] = { String::NewSymbol("error"), exception }; EMIT_EVENT(db->handle_, 2, args); } } else if (!baton->callback.IsEmpty() && baton->callback->IsFunction()) { Local<Value> argv[] = { Local<Value>::New(Null()) }; TRY_CATCH_CALL(db->handle_, baton->callback, 1, argv); } db->Process(); delete baton; } void Database::RemoveCallbacks() { if (debug_trace) { debug_trace->finish(); debug_trace = NULL; } if (debug_profile) { debug_profile->finish(); debug_profile = NULL; } }
mit
XcoreCMS/InlineEditing
client-side/gulpfile.js
669
var gulp = require('gulp'); var browserify = require('browserify'); var tsify = require('tsify'); var source = require('vinyl-source-stream') var sass = require('gulp-sass'); gulp.task('ts', function () { var bundleStream = browserify('src/ts/inline.ts') .plugin(tsify) .bundle() .on('error', function (error) { console.error(error.toString()); }) return bundleStream .pipe(source('inline.js')) .pipe(gulp.dest('dist')) }); gulp.task('sass', function () { return gulp.src('src/sass/inline.scss') .pipe(sass()) .pipe(gulp.dest('dist')); }); gulp.task('default', ['ts', 'sass']);
mit
arkhitech/redmine_sencha_app
touch/src/draw/gradient/Radial.js
3481
/** * Radial gradient. * * @example preview miniphone * var component = new Ext.draw.Component({ * items: [{ * type: 'circle', * cx: 50, * cy: 50, * r: 100, * fillStyle: { * type: 'radial', * start: { * x: 0, * y: 0, * r: 0 * }, * end: { * x: 0, * y: 0, * r: 1 * }, * stops: [ * { * offset: 0, * color: 'white' * }, * { * offset: 1, * color: 'blue' * } * ] * } * }] * }); * Ext.Viewport.setLayout('fit'); * Ext.Viewport.add(component); */ Ext.define("Ext.draw.gradient.Radial", { extend: 'Ext.draw.gradient.Gradient', type: 'radial', config: { /** * @cfg {Object} start The starting circle of the gradient. */ start: { x: 0, y: 0, r: 0 }, /** * @cfg {Object} end The ending circle of the gradient. */ end: { x: 0, y: 0, r: 1 } }, applyStart: function(newStart, oldStart) { if (!oldStart) { return newStart; } var circle = { x: oldStart.x, y: oldStart.y, r: oldStart.r }; if ('x' in newStart) { circle.x = newStart.x; } else if ('centerX' in newStart) { circle.x = newStart.centerX; } if ('y' in newStart) { circle.y = newStart.y; } else if ('centerY' in newStart) { circle.y = newStart.centerY; } if ('r' in newStart) { circle.r = newStart.r; } else if ('radius' in newStart) { circle.r = newStart.radius; } return circle; }, applyEnd: function(newEnd, oldEnd) { if (!oldEnd) { return newEnd; } var circle = { x: oldEnd.x, y: oldEnd.y, r: oldEnd.r }; if ('x' in newEnd) { circle.x = newEnd.x; } else if ('centerX' in newEnd) { circle.x = newEnd.centerX; } if ('y' in newEnd) { circle.y = newEnd.y; } else if ('centerY' in newEnd) { circle.y = newEnd.centerY; } if ('r' in newEnd) { circle.r = newEnd.r; } else if ('radius' in newEnd) { circle.r = newEnd.radius; } return circle; }, /** * @inheritdoc */ generateGradient: function(ctx, bbox) { var start = this.getStart(), end = this.getEnd(), w = bbox.width * 0.5, h = bbox.height * 0.5, x = bbox.x + w, y = bbox.y + h, gradient = ctx.createRadialGradient( x + start.x * w, y + start.y * h, start.r * Math.max(w, h), x + end.x * w, y + end.y * h, end.r * Math.max(w, h) ), stops = this.getStops(), ln = stops.length, i; for (i = 0; i < ln; i++) { gradient.addColorStop(stops[i].offset, stops[i].color); } return gradient; } });
mit
fsek/web
spec/services/calendar_service_spec.rb
3198
require 'rails_helper' RSpec.describe CalendarService do describe 'set all_day' do it 'sets date if all_day' do events = [] events << build_stubbed(:event, :timestamps, all_day: true, title: 'Hela dagen', starts_at: 1.day.from_now, ends_at: 3.days.from_now) events << build_stubbed(:event, :timestamps, all_day: false, title: 'Inte hela dagen') result = CalendarService.export(events) result.to_ical.should include("DTSTART;VALUE=DATE:#{1.day.from_now.strftime('%Y%m%d')}") # Need to add one day to the end time result.to_ical.should include("DTEND;VALUE=DATE:#{(3 + 1).day.from_now.strftime('%Y%m%d')}") end end describe 'set_timezone' do it 'sets the right timezone' do events = [] events << build_stubbed(:event, :timestamps) events << build_stubbed(:event, :timestamps) result = CalendarService.export(events) result.to_ical.should include("TZID:#{Event::TZID}") end it 'sets UTC for created and modified' do event = build_stubbed(:event, :timestamps) ical = CalendarService.export([event]).to_ical ical.should include("CREATED:#{event.created_at.utc.strftime('%Y%m%dT%H%M%SZ')}") ical.should include("LAST-MODIFIED:#{event.created_at.utc.strftime('%Y%m%dT%H%M%SZ')}") end end describe '#set_timezone' do it 'sets TZInfo' do calendar = Icalendar::Calendar.new calendar.has_timezone?.should be_falsey calendar = CalendarService.set_timezone(calendar) calendar.has_timezone?.should be_truthy calendar.timezones.first.tzid.should eq(Event::TZID) end end describe '#event' do it 'sets title from locale' do event = build_stubbed(:event, :timestamps, title_sv: 'Svensk titel', title_en: 'English title', description_sv: 'Svensk beskrivning', description_en: 'English description') result = CalendarService.event(event) en_result = CalendarService.event(event, locale: 'en') result.summary.should eq('Svensk titel') en_result.summary.should eq('English title') result.description.should include('Svensk beskrivning') en_result.description.should include('English description') end it 'applies timezone to starts_at and ends_at' do starts_at = 1.hour.from_now ends_at = starts_at + 4.hours event = build_stubbed(:event, :timestamps, starts_at: starts_at, ends_at: ends_at) result = CalendarService.event(event) # We have to use "be_within(1.second).of" instead of "eq" # because the precision in the DB is too low result.dtstart.should be_within(1.second).of(starts_at) result.dtstart.time_zone.tzinfo.name.should eq(Event::TZID) result.dtend.should be_within(1.second).of(ends_at) result.dtend.time_zone.tzinfo.name.should eq(Event::TZID) end end end
mit
relik/Nuff.js
nuff/intro.js
297
/** * @desc Nuff.js is a simple Model Presenter framework to structure your JS code * @version 0.1.0 * @author Jérémie Dubuis [email protected] * @license The MIT License (MIT) */ var Nuff = function() { var Nuff = { models: [], presenterInstances: [] };
mit
ada/ws
server/client/script/graph.js
2113
app.controller("graph", ['$scope','Restangular', '$location', function($scope, Restangular, $location){ angular.element(document).ready(function () { }); $scope.$on('$routeUpdate', function(){ $scope.newSearch(); }); $scope.searchOptions = $location.search(); $scope.newSearch = function(){ $scope.error = null; $location.path('/graph').search($.param($scope.searchOptions)); $scope.loading = true; $scope.weatherData = []; Restangular.all('weather').getList($location.search()).then( function(r) { var TRows = []; var HRows = []; var UVRows = []; var CO2Rows = []; for (var i = 0; i < r.length; i++) { var d = new Date(Date.parse(r[i].created)); var date = d.getDate() + '/' + d.getMonth(); TRows.push(createRow(date, r[i].temperature, " C")); HRows.push(createRow(date, r[i].humidity, "%")); UVRows.push(createRow(date, r[i].uv, " P")); CO2Rows.push(createRow(date, r[i].co2, "PPM")); } $scope.CDTemperature = createChartData("Temperature", TRows); $scope.CDHumidity = createChartData("Humidity", HRows); $scope.CDUV = createChartData("UV", UVRows); $scope.CDCO2 = createChartData("CO2", CO2Rows); $scope.weatherData = r; $scope.loading = false; }, function(err){ $scope.loading = false; $scope.error = err; }); }; $scope.newSearch(); function createRow(date, v, label){ return { "c": [ {"v": date}, {"v": v, "f": v + label} ] } } function createChartData(title, rows){ return { "type": "LineChart", "displayed": false, "data": { "cols": [ { "id": "month", "label": "Month", "type": "string", "p": {} }, { "id": title, "label": title, "type": "number", "p": {} } ], "rows": rows }, "options": { "title": title, "isStacked": "false", "fill": 20, "displayExactValues": true, "vAxis": { "title": "Temperature", "gridlines": { "count": 10 } }, "hAxis": { "title": "Date" } }, "formatters": {} } } }]);
mit
GeekAb/Crawlers
csvcreators/las.php
9830
<?php // Include config and initiate include_once __DIR__ . '/../scripts/config/default_config.php'; include_once __DIR__ . '/../scripts/config/database.php'; include_once __DIR__ . '/../scripts/config/log.php'; include_once __DIR__ . '/common.php'; include_once __DIR__ . '/getCategoryStr.php'; // Get Database $db = new Db(); $data = $db->query("SELECT * from products_data WHERE source='lashowroom'"); $tempData = array(); $csvData = array(); $count = 0; $colorSet = array(); $sizeArray = array(); $packArray = array(); // Remove file if exist if (file_exists('las.csv')) unlink('las.csv'); $fp = fopen("las.csv", "a+"); foreach ($data as $value) { $imgStr = ''; $sizeArray = array(); $packArray = array(); $tempData = json_decode($value['data'],TRUE); // print_r($tempData); $packQtySizeArray = array(); $packQtyArray = array(); $packSizeArray = array(); $comments = (isset($tempData['comments'])?$tempData['comments']:''); preg_match_all("/[1-9][0-9]*[a-zA-Z]/", $comments, $packQtySizeArray); preg_match_all("/[1-9][0-9]*/", implode(",", $packQtySizeArray[0]), $packQtyArray); preg_match_all("/[a-zA-Z]/", implode(",", $packQtySizeArray[0]), $packSizeArray); $totalQty = 0; foreach ($packQtyArray[0] as $q) { $totalQty += $q; } if($totalQty == 0) { preg_match_all("/[1-9][0-9]*/", $comments, $packQtySizeArray); $packSizeArray[0] = array(0 => 'onesize'); $packQtyArray[0] = $packQtySizeArray[0]; } $categoryStr = getCategoryString($tempData['category'],$tempData['subCategory'],$value['category']); $temp = explode('/',$categoryStr); $category = $temp[0]; $subcategory = (isset($temp[1])?$temp[1]:''); /*Get dimension*/ $dimension = getDimensions($category,$subcategory); foreach ($tempData['images'] as $img) { $imgMain = str_replace(array(",", '\'', '"' ), "", $img); $imgStr .= $value['id'].'_wl_'.basename($imgMain).";"; download_remote_file_with_curl(trim($imgMain), $value['id']); } if(strtolower($tempData['made_in']) == 'usa') $made = 'USA'; else $made = 'Imported'; if($categoryStr == '' || $value['status'] == 0) { $value['status'] = 0; } if($tempData['style_no'][0] == '') $value['status'] = 0; foreach ($tempData['color'] as $color) { $csvData[$count]['sku'] = 'WL#'.$value['id'].'#'.$color; $csvData[$count]['bin_location'] = ''; $csvData[$count]['type'] = 'simple'; $csvData[$count]['store'] = 'default'; $csvData[$count]['name'] = $color.' '.$value['category']; // $csvData[$count]['description'] = $tempData['description']; // $csvData[$count]['short_description'] = $tempData['description']; $csvData[$count]['price'] = $configPrice = str_replace('$', '', $tempData['price']); // $csvData[$count]['qty'] = 100; $csvData[$count]['weight'] = $dimension['weight']; $csvData[$count]['is_in_stock'] = $value['status']; $csvData[$count]['manage_stock'] = 1; $csvData[$count]['use_config_manage_stock'] = 1; $csvData[$count]['model_size_desc'] = $tempData['model_text']; $csvData[$count]['status'] = 1; $csvData[$count]['visibility'] = '"Not Visible Individually"'; $csvData[$count]['brand'] = ''; $csvData[$count]['categories'] = $categoryStr; $csvData[$count]['pack'] = (isset($tempData['min_order'])?$tempData['min_order']:'Not Available'); $csvData[$count]['fabric'] = $tempData['fabric']; $csvData[$count]['made'] = $made; $csvData[$count]['source'] = 'lashowroom'; $csvData[$count]['source_sku'] = $tempData['style_no'][0]; $csvData[$count]['tax_class_id'] = 'None'; $csvData[$count]['image'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['small_image'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['thumbnail'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['image_label'] = $tempData['description']; $csvData[$count]['small_image_label'] = $tempData['description']; $csvData[$count]['thumbnail_label'] = $tempData['description']; $csvData[$count]['media_gallery'] = $imgStr; $csvData[$count]['auctioninc_product_length'] = $dimension['length']; $csvData[$count]['auctioninc_product_width'] = $dimension['width']; $csvData[$count]['auctioninc_product_height'] = $dimension['height']; $csvData[$count]['auctioninc_calc_method'] = 'C'; $csvData[$count]['attribute_set'] = 'Default'; $csvData[$count]['configurable_attributes'] = 'leggingscolor'; /*Setting size*/ $csvData[$count]['leggingspacksize'] = $tempData['pack_size'];//implode(",", $packSizeArray[0]); $csvData[$count]['leggingspackqty'] = $tempData['pack_qty'];//implode(",", $packQtyArray[0]); $csvData[$count]['prod_url'] = $value['url']; $csvData[$count++]['leggingscolor'] = $color; } // Config Price $configPrice = str_replace('$', '', $tempData['pack_price']); $configLength = $dimension['length']; $configWidth = $dimension['width']; $configHeight = $dimension['height']; $configWeight = $dimension['weight']; /*Create configurable Product*/ $csvData[$count]['sku'] = 'WL#'.$value['id']; $csvData[$count]['bin_location'] = ''; $csvData[$count]['type'] = 'configurable'; $csvData[$count]['store'] = 'default'; $csvData[$count]['name'] = $tempData['category'] .' '. $tempData['subCategory']; // $csvData[$count]['description'] = $tempData['description']; // $csvData[$count]['short_description'] = $tempData['description']; $csvData[$count]['price'] = $configPrice; // $csvData[$count]['qty'] = 100; $csvData[$count]['weight'] = $configWeight; $csvData[$count]['is_in_stock'] = $value['status']; $csvData[$count]['manage_stock'] = 1; $csvData[$count]['use_config_manage_stock'] = 1; $csvData[$count]['model_size_desc'] = $tempData['model_text']; $csvData[$count]['status'] = 1; $csvData[$count]['visibility'] = '"Catalog, Search"'; $csvData[$count]['brand'] = ''; $csvData[$count]['categories'] = $categoryStr; $csvData[$count]['pack'] = (isset($tempData['min_order'])?$tempData['min_order']:'Not Available'); $csvData[$count]['fabric'] = $tempData['fabric']; $csvData[$count]['made'] = $made; $csvData[$count]['source'] = 'lashowroom'; $csvData[$count]['source_sku'] = $tempData['style_no'][0]; $csvData[$count]['tax_class_id'] = 'None'; $csvData[$count]['image'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['small_image'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['thumbnail'] = $value['id'].'_wl_'.basename(str_replace(array(",", '\'', '"' ), "", $tempData['images'][0])); $csvData[$count]['image_label'] = $tempData['description']; $csvData[$count]['small_image_label'] = $tempData['description']; $csvData[$count]['thumbnail_label'] = $tempData['description']; $csvData[$count]['media_gallery'] = $imgStr; $csvData[$count]['auctioninc_product_length'] = $configLength; $csvData[$count]['auctioninc_product_width'] = $configWidth; $csvData[$count]['auctioninc_product_height'] = $configHeight; $csvData[$count]['auctioninc_calc_method'] = 'C'; $csvData[$count]['attribute_set'] = 'Default'; $csvData[$count]['configurable_attributes'] = 'leggingscolor'; $csvData[$count]['leggingspacksize'] = $tempData['pack_size'];//implode(",", $packSizeArray[0]); $csvData[$count]['leggingspackqty'] = $tempData['pack_qty'];//implode(",", $packQtyArray[0]); $csvData[$count]['prod_url'] = $value['url']; $csvData[$count++]['leggingscolor'] = ''; } } fputcsv($fp, array_keys($csvData[0])); foreach ($csvData as $data) { fputcsv($fp, $data); } fclose($fp);
mit
marcovisona/multiStepForm
page3.php
145
<?php require_once 'multiStepForm.php'; setCurrentStepIndex(2); if (!checkCorrectStep()) { redirect(firstFormStep()); } ?> <h3>Fine!!</h3>
mit
kore52/FutureSight
FutureSight/lib/MTGSource.cs
495
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace FutureSight.lib { public class MTGSource : MTGObject { public MTGPlayer Controller { get; set; } public MTGSource() {} public MTGSource(MTGPlayer controller) { Controller = controller; } public bool IsController(MTGPlayer player) => Controller.Equals(player); } }
mit
saimasarifa/votingsystem1
app/Voter.php
132
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Voter extends Model { protected $guarded = []; // }
mit
finalist736/seabotserver
service/router/router.go
1708
package router import ( "fmt" "runtime" "github.com/finalist736/seabotserver" "github.com/finalist736/seabotserver/gameplay/battle" "github.com/finalist736/seabotserver/gameplay/queue" "github.com/finalist736/seabotserver/storage/database/dbsql" "github.com/finalist736/seabotserver/tcpserver/bots/aibot" ) func Dispatch(bot seabotserver.BotService, fbot *seabotserver.FromBot) { if bot.DBBot().ID == 0 { if fbot.Auth == "" { return } else { dbBotService := dbsql.NewDBBotService() dbbot, err := dbBotService.Auth(fbot.Auth) //fmt.Printf("after auth: %+v\n", dbbot) if err != nil { bot.SendError("auth error, register on http://finalistx.com/ for new key") bot.Disconnect() return } bot.SetDBBot(dbbot) tb := &seabotserver.ToBot{} tb.Auth = &seabotserver.TBAuth{} tb.Auth.OK = true tb.Auth.ID = bot.DBBot().ID tb.Auth.User = bot.DBBot().User bot.Send(tb) } } else if bot.Battle() == nil { if fbot.Bvb != nil { // stay to queue fmt.Printf("setting to queue: %+v\n", fbot) queue.Handle(bot, fbot.Bvb) } else if fbot.Bvr != nil { f := &seabotserver.QueueData{bot, fbot.Bvr, false} s := &seabotserver.QueueData{aibot.NewBot(), &seabotserver.FBBvb{0, nil}, false} battle.Create(f, s) } else if fbot.Exit { bot.Disconnect() return } else if fbot.Profile != nil { prof := &seabotserver.TBProfile{} prof.Gnum = runtime.NumGoroutine() bot.Send(&seabotserver.ToBot{Profile: prof}) } } else { if fbot.Turn == nil { return } if bot.Battle() == nil { return } btl := bot.Battle().(*battle.Battle) if btl == nil { return } btl.Handle(bot, fbot.Turn) // need to handle exit? } }
mit
CjHare/systematic-trading
systematic-trading-backtest-output-elastic/src/test/java/com/systematic/trading/backtest/output/elastic/model/index/ElasticNetworthIndexTest.java
2771
/** * Copyright (c) 2015-2018, CJ Hare All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * * Neither the name of [project] nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.systematic.trading.backtest.output.elastic.model.index; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import com.systematic.trading.backtest.output.elastic.model.ElasticIndexName; /** * Purpose being to Verify the JSON messages to Elastic Search. * * @author CJ Hare */ @RunWith(MockitoJUnitRunner.class) public class ElasticNetworthIndexTest extends ElasticIndexTestBase { private static final String JSON_PUT_INDEX = "{\"settings\":{\"number_of_shards\":5,\"number_of_replicas\":1}}"; private static final String JSON_PUT_INDEX_MAPPING = "{\"properties\":{\"equity_balance_value\":{\"type\":\"float\"},\"event_date\":{\"type\":\"date\"},\"networth\":{\"type\":\"float\"},\"event\":{\"type\":\"keyword\"},\"cash_balance\":{\"type\":\"float\"},\"equity_balance\":{\"type\":\"float\"}}"; @Override protected String jsonPutIndex() { return JSON_PUT_INDEX; } @Override protected String jsonPutIndexMapping() { return JSON_PUT_INDEX_MAPPING; } @Override protected ElasticIndexName indexName() { return ElasticIndexName.NETWORTH; } @Override protected ElasticCommonIndex index() { return new ElasticNetworthIndex(dao(), pool(), elasticConfig()); } }
mit
goodwinxp/Yorozuya
library/ATF/$C4660CC06E52BF36695D340908ABB2B1.hpp
274
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE enum $C4660CC06E52BF36695D340908ABB2B1 { exchange_zone = 0x18, }; END_ATF_NAMESPACE
mit
crmis/weddings
app/controllers/extras_controller.rb
1213
# @author Stacey Rees <https://github.com/staceysmells> class ExtrasController < ApplicationController # @see def resource_not_found around_filter :resource_not_found before_action :set_extra, only: [:show, :edit, :update, :destroy] def index @extras = Extra.all end def show end def new @extra = Extra.new end def edit end def create @extra = Extra.new(extra_params) if @extra.save redirect_to @extra, notice: 'Extra was successfully created.' else render :new end end def update if @extra.update(extra_params) redirect_to @extra, notice: 'Extra was successfully updated.' else render :edit end end def destroy @extra.destroy redirect_to extras_url, notice: 'Extra was successfully destroyed.' end private def set_extra @extra = Extra.find(params[:id]) end # If resource not found redirect to root and flash error. def resource_not_found yield rescue ActiveRecord::RecordNotFound redirect_to root_url, :notice => "Room Category not found." end def extra_params params.require(:extra).permit(:extraimg, :name, :description, :quantity, :price, :extracat_id) end end
mit
matmello/smartedu
index.php
34654
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Agency - Start Bootstrap Theme</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/agency.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:600' rel='stylesheet' type='text/css'> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="#page-top">SmartEdu</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#services">Services</a> </li> <li> <a class="page-scroll" href="#portfolio">Portfolio</a> </li> <li> <a class="page-scroll" href="#about">About</a> </li> <li> <a class="page-scroll" href="#team">Team</a> </li> <li> <a class="page-scroll" href="#contact">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- Header --> <header> <div class="container"> <div class="intro-text"> <div class="intro-lead-in">Education as we know it was designed for people who lived</div> <div class="intro-heading">200 years ago</div> <a href="#services" class="page-scroll btn btn-xl">It is time to change it.</a> </div> </div> </header> <!-- Services Section --> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Services</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row text-center"> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-shopping-cart fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">E-Commerce</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-laptop fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Responsive Design</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-lock fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Web Security</h4> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima maxime quam architecto quo inventore harum ex magni, dicta impedit.</p> </div> </div> </div> </section> <!-- Portfolio Grid Section --> <section id="portfolio" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Portfolio</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/roundicons.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Round Icons</h4> <p class="text-muted">Graphic Design</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal2" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/startup-framework.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Startup Framework</h4> <p class="text-muted">Website Design</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal3" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/treehouse.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Treehouse</h4> <p class="text-muted">Website Design</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal4" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/golden.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Golden</h4> <p class="text-muted">Website Design</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal5" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/escape.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Escape</h4> <p class="text-muted">Website Design</p> </div> </div> <div class="col-md-4 col-sm-6 portfolio-item"> <a href="#portfolioModal6" class="portfolio-link" data-toggle="modal"> <div class="portfolio-hover"> <div class="portfolio-hover-content"> <i class="fa fa-plus fa-3x"></i> </div> </div> <img src="img/portfolio/dreams.png" class="img-responsive" alt=""> </a> <div class="portfolio-caption"> <h4>Dreams</h4> <p class="text-muted">Website Design</p> </div> </div> </div> </div> </section> <!-- About Section --> <section id="about"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">About</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <ul class="timeline"> <li> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/1.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>2009-2011</h4> <h4 class="subheading">Our Humble Beginnings</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/2.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>March 2011</h4> <h4 class="subheading">An Agency is Born</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/4.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>July 2014</h4> <h4 class="subheading">Phase Two Expansion</h4> </div> <div class="timeline-body"> <p class="text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <h4>Be Part <br>Of Our <br>Story!</h4> </div> </li> </ul> </div> </div> </div> </section> <!-- Team Section --> <section id="team" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Our Amazing Team</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/1.jpg" class="img-responsive img-circle" alt=""> <h4>Kay Garland</h4> <p class="text-muted">Lead Designer</p> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/2.jpg" class="img-responsive img-circle" alt=""> <h4>Larry Parker</h4> <p class="text-muted">Lead Marketer</p> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-sm-4"> <div class="team-member"> <img src="img/team/3.jpg" class="img-responsive img-circle" alt=""> <h4>Diana Pertersen</h4> <p class="text-muted">Lead Developer</p> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <p class="large text-muted">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.</p> </div> </div> </div> </section> <!-- Clients Aside --> <aside class="clients"> <div class="container"> <div class="row"> <div class="col-md-3 col-sm-6"> <a href="#"> <img src="img/logos/envato.jpg" class="img-responsive img-centered" alt=""> </a> </div> <div class="col-md-3 col-sm-6"> <a href="#"> <img src="img/logos/designmodo.jpg" class="img-responsive img-centered" alt=""> </a> </div> <div class="col-md-3 col-sm-6"> <a href="#"> <img src="img/logos/themeforest.jpg" class="img-responsive img-centered" alt=""> </a> </div> <div class="col-md-3 col-sm-6"> <a href="#"> <img src="img/logos/creative-market.jpg" class="img-responsive img-centered" alt=""> </a> </div> </div> </div> </aside> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Contact Us</h2> <h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <form name="sentMessage" id="contactForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number."> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group"> <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <button type="submit" class="btn btn-xl">Send Message</button> </div> </div> </form> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-md-4"> <span class="copyright">Copyright &copy; Your Website 2014</span> </div> <div class="col-md-4"> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-inline quicklinks"> <li><a href="#">Privacy Policy</a> </li> <li><a href="#">Terms of Use</a> </li> </ul> </div> </div> </div> </footer> <!-- Portfolio Modals --> <!-- Use the modals below to showcase details about your portfolio projects! --> <!-- Portfolio Modal 1 --> <div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive" src="img/portfolio/roundicons-free.png" alt=""> <p>Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!</p> <p> <strong>Want these icons in this portfolio item sample?</strong>You can download 60 of them for free, courtesy of <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">RoundIcons.com</a>, or you can purchase the 1500 icon set <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">here</a>.</p> <ul class="list-inline"> <li>Date: July 2014</li> <li>Client: Round Icons</li> <li>Category: Graphic Design</li> </ul> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 2 --> <div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Project Heading</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/startup-framework-preview.png" alt=""> <p><a href="http://designmodo.com/startup/?u=787">Startup Framework</a> is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.</p> <p>You can preview Startup Framework <a href="http://designmodo.com/startup/?u=787">here</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 3 --> <div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/treehouse-preview.png" alt=""> <p>Treehouse is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/treehouse-free-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 4 --> <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/golden-preview.png" alt=""> <p>Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/golden-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 5 --> <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/escape-preview.png" alt=""> <p>Escape is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/escape-one-page-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 6 --> <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/dreams-preview.png" alt=""> <p>Dreams is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Dreams is a modern one page web template designed for almost any purpose. It’s a beautiful template that’s designed with the Bootstrap framework in mind.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/dreams-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> <!-- jQuery Version 1.11.0 --> <script src="js/jquery-1.11.0.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="js/classie.js"></script> <script src="js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="js/agency.js"></script> </body> </html>
mit
lordmilko/PrtgAPI
src/PrtgAPI/Objects/EventObjects/SensorHistoryReportItem.cs
2537
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace PrtgAPI { /// <summary> /// Represents a historical occurrence of a <see cref="Sensor"/> being in a particular <see cref="PrtgAPI.Status"/>. /// </summary> [DebuggerDisplay("SensorId = {SensorId}, Status = {Status}, Duration = {Duration}, StartDate = {StartDate}")] public class SensorHistoryReportItem : IEventObject { [ExcludeFromCodeCoverage] string IObject.Name => StartDate.ToString(CultureInfo.InvariantCulture) + " - " + EndDate.ToString(CultureInfo.InvariantCulture); [ExcludeFromCodeCoverage] int IEventObject.ObjectId => SensorId; /// <summary> /// Gets the ID of the sensor to which this historical event pertains. /// </summary> public int SensorId { get; } /// <summary> /// Gets the status the sensor was within within the <see cref="StartDate"/> and <see cref="EndDate"/>. /// </summary> public Status Status { get; } /// <summary> /// Gets the start time when the sensor entered the given <see cref="PrtgAPI.Status"/>.<para/> /// Note: if the sensor was already in the specified status prior to the start date of the the sensor history /// report that this item was included in,<para/>this value will simply be the beginning of the entire requested reporting period. /// </summary> public DateTime StartDate { get; } /// <summary> /// Gets the start time when the sensor exited the given <see cref="PrtgAPI.Status"/>.<para/> /// Note: if the sensor continued to be in the specified status after the end date of the the sensor history /// report that this item was included in,<para/>this value will simply be the end of the entire request reporting period. /// </summary> public DateTime EndDate { get; } /// <summary> /// Gets the duration the sensor was in the specified <see cref="Status"/> based on the <see cref="StartDate"/> and <see cref="EndDate"/> properties of this report item. /// </summary> public TimeSpan Duration { get; } internal SensorHistoryReportItem(int sensorId, Status status, DateTime startDate, DateTime endDate) { SensorId = sensorId; Status = status; StartDate = startDate; EndDate = endDate; Duration = EndDate - StartDate; } } }
mit
polysquare/jobstamps
test/test_jobstamps.py
17647
# /test/test_jobstamps.py # # Unit tests for the jobstamps module. # # See /LICENCE.md for Copyright information """Unit tests for the jobstamps module.""" import os import shutil import time from test import testutil from jobstamps import jobstamp from mock import Mock, call from nose_parameterized import param, parameterized from testtools import ExpectedException from testtools.matchers import DirExists class MockJob(Mock): """Wraps Mock to provide __name__ attribute.""" def __init__(self, *args, **kwargs): """Pass __name__ attribute to __init__.""" super(MockJob, self).__init__(*args, __name__="job", **kwargs) self.return_value = None def _update_method_doc(func, num, params): """Format docstring for tests with different update methods.""" del num if params[0][0] is jobstamp.MTimeMethod: return func.__doc__[:-1] + """ using Modification Time Method.""" elif params[0][0] is jobstamp.HashMethod: return func.__doc__[:-1] + """ using Hash Method.""" raise RuntimeError("""Unknown method {}""".format(params[0][0])) class TestJobstamps(testutil.InTemporaryDirectoryTestBase): """TestCase for jobstamps module.""" _METHODS = (param(jobstamp.MTimeMethod), param(jobstamp.HashMethod)) def setUp(self): # suppress(invalid-name) """Clear the JOBSTAMPS_ALWAYS_USE_HASHES variable before each test.""" super(TestJobstamps, self).setUp() always_use_hashes_var = "JOBSTAMPS_ALWAYS_USE_HASHES" testutil.temporarily_clear_variable_on_testsuite(self, always_use_hashes_var) testutil.temporarily_clear_variable_on_testsuite(self, "JOBSTAMPS_DISABLED") def test_raise_if_cachedir_exists_as_file(self): # suppress(no-self-use) """Raise IOError if specified cache dir exists and is a file.""" cache_entry = os.path.join(os.getcwd(), "cache") with open(cache_entry, "w") as cache_entry_file: cache_entry_file.write("Regular file") with ExpectedException(IOError): jobstamp.run(lambda: None, jobstamps_cache_output_directory=cache_entry) def test_running_job_creates_cache_directory(self): """Running job creates stamp file directory.""" os.chdir("..") cache_directory = self._temporary_directory shutil.rmtree(cache_directory) job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=cache_directory) self.assertThat(cache_directory, DirExists()) def test_can_create_cache_directory_in_nested_directories(self): """Running job creates stamp file directory, even if nested.""" os.chdir("..") cache_directory = os.path.join(self._temporary_directory, "nested") shutil.rmtree(self._temporary_directory) job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=cache_directory) self.assertThat(cache_directory, DirExists()) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_stampfile_out_of_date_when_stampfile_doesnt_exist(self, method): """Stamp file marked out of date when stamp file doesn't exist.""" cwd = os.getcwd() ret = jobstamp.out_of_date(MockJob(), 1, jobstamps_cache_output_directory=cwd, jobstamps_method=method) self.assertNotEqual(None, ret) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_nothing_out_of_date_when_stampfile_does_exist(self, method): """Nothing marked out of date when stamp file doesn't exist.""" job = MockJob() cwd = os.getcwd() jobstamp.run(job, 1, jobstamps_cache_output_directory=cwd, jobstamps_method=method) ret = jobstamp.out_of_date(job, 1, jobstamps_cache_output_directory=cwd, jobstamps_method=method) self.assertEqual(None, ret) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_running_job_returns_expected_value(self, method): """Job is run initially when there is no stamp and returns value.""" job = MockJob() job.return_value = "expected" value = jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) self.assertEqual(value, job.return_value) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_running_job_twice_returns_expected_value(self, method): """Job is run again when there is no stamp.""" job = MockJob() job.return_value = "expected" jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) value = jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd()) self.assertEqual(value, job.return_value) def test_running_job_once_runs_job(self): # suppress(no-self-use) """Job is run initially when there is no stamp.""" job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd()) job.assert_called_with(1) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_running_job_twice_only_runs_underlying_job_once(self, method): """Job is not run twice when there are no deps and already stamped.""" job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) job.assert_called_once_with(1) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_running_twice_with_jobstamps_disabled_runs_twice(self, method): """Job is run twice when JOBSTAMPS_DISABLED is set.""" os.environ["JOBSTAMPS_DISABLED"] = "1" self.addCleanup(lambda: os.environ.pop("JOBSTAMPS_DISABLED", None)) job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) job.assert_has_calls([call(1), call(1)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_running_job_with_different_args_runs_it_again(self, method): """Job can be run twice with different args.""" job = MockJob() jobstamp.run(job, 1, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) jobstamp.run(job, 2, jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) job.assert_has_calls([call(1), call(2)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_job_runs_again_when_dependency_doesnt_exist(self, method): """Job can be run twice with different args when dep doesn't exist.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) job.assert_has_calls([call(1), call(1)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_dependency_out_of_date_when_dependency_doesnt_exist(self, method): """Dependency is marked out of date when it does not exist.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") cwd = os.getcwd() jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) ret = jobstamp.out_of_date(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) self.assertEqual(dependency, ret) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_job_runs_once_only_once_when_dependency_up_to_date(self, method): """Job runs only once when stamp is more recent than dependency.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) job.assert_called_once_with(1) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_job_runs_again_when_dependency_not_up_to_date(self, method): """Job runs again when dependency is more recent than stamp.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) time.sleep(1) with open(dependency, "w") as dependency_file: dependency_file.write("Updated") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd()) job.assert_has_calls([call(1), call(1)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_dependency_out_of_date_when_dependency_updated(self, method): """Dependency is marked out of date when it is updated.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") cwd = os.getcwd() with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) time.sleep(1) with open(dependency, "w") as dependency_file: dependency_file.write("Updated") ret = jobstamp.out_of_date(MockJob(), 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) self.assertEqual(dependency, ret) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_job_runs_again_when_dependency_added(self, method): """Job runs again when a new dependency is added.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) time.sleep(1) dependency_new = os.path.join(os.getcwd(), "dependency_new") with open(dependency_new, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency, dependency_new], jobstamps_cache_output_directory=os.getcwd()) job.assert_has_calls([call(1), call(1)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) # suppress(no-self-use) def test_job_runs_again_when_dependency_deleted(self, method): """Job runs again when dependency is later deleted.""" job = MockJob() dependency = os.path.join(os.getcwd(), "dependency") with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd(), jobstamps_method=method) os.remove(dependency) jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=os.getcwd()) job.assert_has_calls([call(1), call(1)]) @parameterized.expand(_METHODS, testcase_func_doc=_update_method_doc) def test_dependency_out_of_date_when_dependency_deleted(self, method): """Dependency is marked out of date when it is deleted.""" job = MockJob() cwd = os.getcwd() dependency = os.path.join(os.getcwd(), "dependency") with open(dependency, "w") as dependency_file: dependency_file.write("Contents") jobstamp.run(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) os.remove(dependency) cwd = os.getcwd() ret = jobstamp.out_of_date(job, 1, jobstamps_dependencies=[dependency], jobstamps_cache_output_directory=cwd, jobstamps_method=method) self.assertEqual(dependency, ret) # suppress(no-self-use) def test_job_runs_again_when_output_file_doesnt_exist(self): """Job can be run twice when output file doesn't exist.""" job = MockJob() expected_outputs = os.path.join(os.getcwd(), "expected_output") jobstamp.run(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=os.getcwd()) jobstamp.run(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=os.getcwd()) job.assert_has_calls([call(1), call(1)]) def test_output_file_out_of_date_when_output_file_doesnt_exist(self): """Output file is out of date when output file doesn't exist.""" expected_outputs = os.path.join(os.getcwd(), "expected_output") cwd = os.getcwd() job = MockJob() jobstamp.run(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=cwd) ret = jobstamp.out_of_date(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=cwd) self.assertEqual(expected_outputs, ret) # suppress(no-self-use) def test_job_runs_once_when_output_file_exists(self): """Job runs only once when output file exists.""" job = MockJob() expected_outputs = os.path.join(os.getcwd(), "expected_output") jobstamp.run(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=os.getcwd()) with open(expected_outputs, "w") as expected_outputs_file: expected_outputs_file.write("Expected output") jobstamp.run(job, 1, jobstamps_output_files=[expected_outputs], jobstamps_cache_output_directory=os.getcwd()) job.assert_called_once_with(1)
mit
boomcms/boom-robotstxt
src/BoomCMS/ServiceProviders/RobotsServiceProvider.php
880
<?php namespace BoomCMS\ServiceProviders; use Illuminate\Support\ServiceProvider as BaseServiceProvider; class RobotsServiceProvider extends BaseServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $this->loadViewsFrom(__DIR__.'/../../views/boomcms', 'boomcms'); $this->loadTranslationsFrom(__DIR__.'/../../lang', 'boomcms'); $this->publishes([ __DIR__.'/../../../public' => public_path('vendor/boomcms/boom-robotstxt'), __DIR__.'/../../database/migrations' => base_path('/migrations/boomcms'), ], 'boomcms'); include __DIR__.'/../../routes.php'; } /** * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../../config/menu.php', 'boomcms.menu'); } }
mit