text
stringlengths
2
1.04M
meta
dict
using System.Collections; using System.Linq; using SanicballCore.MatchMessages; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Sanicball.UI { public class ChatMessageArgs : System.EventArgs { public string Text { get; private set; } public ChatMessageArgs(string text) { Text = text; } } [RequireComponent(typeof(CanvasGroup))] public class Chat : MonoBehaviour { private const float MAX_VISIBLE_TIME = 4f; private const float FADE_TIME = 0.2f; [SerializeField] private Text chatMessagePrefab = null; [SerializeField] private RectTransform chatMessageContainer = null; [SerializeField] private InputField messageInputField = null; [SerializeField] private RectTransform hoverArea = null; private GameObject prevSelectedObject; private bool shouldEnableInput = false; private CanvasGroup canvasGroup; private float visibleTime = 0; public event System.EventHandler<ChatMessageArgs> MessageSent; private void Start() { DontDestroyOnLoad(gameObject); canvasGroup = GetComponent<CanvasGroup>(); canvasGroup.alpha = 0; } public void Update() { EventSystem es = EventSystem.current; if (GameInput.IsOpeningChat()) { if (es.currentSelectedGameObject != messageInputField.gameObject) { prevSelectedObject = es.currentSelectedGameObject; es.SetSelectedGameObject(messageInputField.gameObject); } } if (es.currentSelectedGameObject == messageInputField.gameObject) { visibleTime = MAX_VISIBLE_TIME; if (Input.GetKeyDown(KeyCode.Return)) SendMessage(); } if (Input.mousePosition.x < hoverArea.sizeDelta.x && Input.mousePosition.y < hoverArea.sizeDelta.y) { visibleTime = MAX_VISIBLE_TIME; } if (visibleTime > 0) { visibleTime -= Time.deltaTime; canvasGroup.alpha = 1; } else if (canvasGroup.alpha > 0) { canvasGroup.alpha = Mathf.Max(canvasGroup.alpha - Time.deltaTime / FADE_TIME, 0); } } public void LateUpdate() { if (shouldEnableInput) { GameInput.KeyboardDisabled = false; shouldEnableInput = false; } } public void ShowMessage(ChatMessageType type, string from, string text) { Text messageObj = Instantiate(chatMessagePrefab); messageObj.transform.SetParent(chatMessageContainer, false); switch (type) { case ChatMessageType.User: messageObj.text = string.Format("<color=#6688ff><b>{0}</b></color>: {1}", from, text); break; case ChatMessageType.System: messageObj.text = string.Format("<color=#ffff77><b>{0}</b></color>", text); break; } visibleTime = MAX_VISIBLE_TIME; } public void DisableInput() { GameInput.KeyboardDisabled = true; } public void EnableInput() { shouldEnableInput = true; } public void SendMessage() { string text = messageInputField.text; if (text.Trim() != string.Empty) { if (MessageSent != null) MessageSent(this, new ChatMessageArgs(text)); } EventSystem.current.SetSelectedGameObject(prevSelectedObject); messageInputField.text = string.Empty; } } }
{ "content_hash": "15a11cf995bb3b3de83ca89d08d326d6", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 111, "avg_line_length": 28.834532374100718, "alnum_prop": 0.5469061876247505, "repo_name": "BK-TN/Sanicball", "id": "7db6f291bfb53ec3d1590fcfe6e82d1965a07f26", "size": "4010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/UI/Chat.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "866826" }, { "name": "HLSL", "bytes": "1639" }, { "name": "ShaderLab", "bytes": "294699" } ], "symlink_target": "" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "runtime.h" #include "defs_GOOS_GOARCH.h" #include "signals_GOOS.h" #include "os_GOOS.h" void runtime·dumpregs(Sigcontext *r) { runtime·printf("rax %X\n", r->rax); runtime·printf("rbx %X\n", r->rbx); runtime·printf("rcx %X\n", r->rcx); runtime·printf("rdx %X\n", r->rdx); runtime·printf("rdi %X\n", r->rdi); runtime·printf("rsi %X\n", r->rsi); runtime·printf("rbp %X\n", r->rbp); runtime·printf("rsp %X\n", r->rsp); runtime·printf("r8 %X\n", r->r8 ); runtime·printf("r9 %X\n", r->r9 ); runtime·printf("r10 %X\n", r->r10); runtime·printf("r11 %X\n", r->r11); runtime·printf("r12 %X\n", r->r12); runtime·printf("r13 %X\n", r->r13); runtime·printf("r14 %X\n", r->r14); runtime·printf("r15 %X\n", r->r15); runtime·printf("rip %X\n", r->rip); runtime·printf("rflags %X\n", r->eflags); runtime·printf("cs %X\n", (uint64)r->cs); runtime·printf("fs %X\n", (uint64)r->fs); runtime·printf("gs %X\n", (uint64)r->gs); } /* * This assembler routine takes the args from registers, puts them on the stack, * and calls sighandler(). */ extern void runtime·sigtramp(void); extern void runtime·sigreturn(void); // calls runtime·sigreturn void runtime·sighandler(int32 sig, Siginfo *info, void *context, G *gp) { Ucontext *uc; Mcontext *mc; Sigcontext *r; uintptr *sp; SigTab *t; uc = context; mc = &uc->uc_mcontext; r = (Sigcontext*)mc; // same layout, more conveient names if(sig == SIGPROF) { runtime·sigprof((uint8*)r->rip, (uint8*)r->rsp, nil, gp); return; } t = &runtime·sigtab[sig]; if(info->si_code != SI_USER && (t->flags & SigPanic)) { if(gp == nil) goto Throw; // Make it look like a call to the signal func. // Have to pass arguments out of band since // augmenting the stack frame would break // the unwinding code. gp->sig = sig; gp->sigcode0 = info->si_code; gp->sigcode1 = ((uintptr*)info)[2]; gp->sigpc = r->rip; // Only push runtime·sigpanic if r->rip != 0. // If r->rip == 0, probably panicked because of a // call to a nil func. Not pushing that onto sp will // make the trace look like a call to runtime·sigpanic instead. // (Otherwise the trace will end at runtime·sigpanic and we // won't get to see who faulted.) if(r->rip != 0) { sp = (uintptr*)r->rsp; *--sp = r->rip; r->rsp = (uintptr)sp; } r->rip = (uintptr)runtime·sigpanic; return; } if(info->si_code == SI_USER || (t->flags & SigNotify)) if(runtime·sigsend(sig)) return; if(t->flags & SigKill) runtime·exit(2); if(!(t->flags & SigThrow)) return; Throw: runtime·startpanic(); if(sig < 0 || sig >= NSIG) runtime·printf("Signal %d\n", sig); else runtime·printf("%s\n", runtime·sigtab[sig].name); runtime·printf("PC=%X\n", r->rip); runtime·printf("\n"); if(runtime·gotraceback()){ runtime·traceback((void*)r->rip, (void*)r->rsp, 0, gp); runtime·tracebackothers(gp); runtime·dumpregs(r); } runtime·exit(2); } void runtime·signalstack(byte *p, int32 n) { Sigaltstack st; st.ss_sp = p; st.ss_size = n; st.ss_flags = 0; runtime·sigaltstack(&st, nil); } void runtime·setsig(int32 i, void (*fn)(int32, Siginfo*, void*, G*), bool restart) { Sigaction sa; runtime·memclr((byte*)&sa, sizeof sa); sa.sa_flags = SA_ONSTACK | SA_SIGINFO | SA_RESTORER; if(restart) sa.sa_flags |= SA_RESTART; sa.sa_mask = ~0ULL; sa.sa_restorer = (void*)runtime·sigreturn; if(fn == runtime·sighandler) fn = (void*)runtime·sigtramp; sa.sa_handler = fn; if(runtime·rt_sigaction(i, &sa, nil, sizeof(sa.sa_mask)) != 0) runtime·throw("rt_sigaction failure"); }
{ "content_hash": "360e58031015a01f5769fa3b4bee77a8", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 80, "avg_line_length": 26.368055555555557, "alnum_prop": 0.6262839083486963, "repo_name": "Triskite/willstone-goclone", "id": "8ff5be7859160980d1d90153113bf8e822a578f8", "size": "3851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pkg/runtime/signal_linux_amd64.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "280892" }, { "name": "Awk", "bytes": "3780" }, { "name": "Bison", "bytes": "92689" }, { "name": "C", "bytes": "4559937" }, { "name": "C++", "bytes": "75538" }, { "name": "CSS", "bytes": "1897" }, { "name": "Emacs Lisp", "bytes": "34387" }, { "name": "Go", "bytes": "14854262" }, { "name": "HTML", "bytes": "103824" }, { "name": "JavaScript", "bytes": "1033" }, { "name": "Logos", "bytes": "1248" }, { "name": "Makefile", "bytes": "10175" }, { "name": "OpenEdge ABL", "bytes": "9784" }, { "name": "Perl", "bytes": "189741" }, { "name": "Python", "bytes": "123397" }, { "name": "Shell", "bytes": "73639" }, { "name": "VimL", "bytes": "22363" } ], "symlink_target": "" }
``` s3 = boto3.client('s3') url= s3.generate_presigned_url(ClientMethod='put_object', Params={ 'Bucket': DEFAULT_BUCKET, 'Key': file_key, }, ExpiresIn=3600) ``` by using curl we can put a file into aws s3 `curl -v --request PUT --upload-file test.txt "presigned url"` ### post ``` resp = s3.generate_presigned_post( Bucket= DEFAULT_BUCKET, Key= file_key, ExpiresIn=3600) ``` resp is like `{'url': u'https://bucket.s3.amazonaws.com/', 'fields': {'policy': u'xxxx', 'AWSAccessKeyId': u'xxx', 'key': 'filekey', 'signature': u'xxx'}}` we can also use curl to post file ``` curl -v -F AWSAccessKeyId=xx \ -F key=test/mytest.txt \ -F signature=xxxx \ -F policy=xxxx \ -F file=@/tmp/test.txt \ https://bucket.s3.amazonaws.com/ ``` ### post presigned url and set content type ``` resp = s3.generate_presigned_post( Bucket= DEFAULT_BUCKET, Fields={ 'Content-Type': 'text/plain' }, Key= file_key, Conditions=[ ['starts-with', '$content-type', 'text/plain'] ], ExpiresIn=3600) ``` it works after both set fields and Conditions
{ "content_hash": "cbb493df7a9e75d7c1656cea6f9983e1", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 155, "avg_line_length": 21.471698113207548, "alnum_prop": 0.6080843585237259, "repo_name": "kkito/lettuce", "id": "a8e26269c0f01ccf9d4cfbc0c048a10094521632", "size": "1197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/content/posts/2019-03-29/aws_s3_boto3_presigned_url_and_curl.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12517" }, { "name": "Pug", "bytes": "1852" }, { "name": "SCSS", "bytes": "1770" }, { "name": "Shell", "bytes": "129" } ], "symlink_target": "" }
#import <UIKit/UIKit.h> #import <IGListKit/IGListSectionController.h> #import <IGListKit/IGListMacros.h> NS_ASSUME_NONNULL_BEGIN /** A block used to configure cells. @param item The model with which to configure the cell. @param cell The cell to configure. */ NS_SWIFT_NAME(ListSingleSectionCellConfigureBlock) typedef void (^IGListSingleSectionCellConfigureBlock)(id item, __kindof UICollectionViewCell *cell); /** A block that returns the size for the cell given the collection context. @param item The model for the section. @param collectionContext The collection context for the section. @return The size for the cell. */ NS_SWIFT_NAME(ListSingleSectionCellSizeBlock) typedef CGSize (^IGListSingleSectionCellSizeBlock)(id item, id<IGListCollectionContext> _Nullable collectionContext); @class IGListSingleSectionController; /** A delegate that can receive selection events on an `IGListSingleSectionController`. */ NS_SWIFT_NAME(ListSingleSectionControllerDelegate) @protocol IGListSingleSectionControllerDelegate <NSObject> /** Tells the delegate that the section controller was selected. @param sectionController The section controller that was selected. @param object The model for the given section. */ - (void)didSelectSectionController:(IGListSingleSectionController *)sectionController withObject:(id)object; @optional /** Tells the delegate that the section controller was deselected. @param sectionController The section controller that was deselected. @param object The model for the given section. @note Method is `@optional` until the 4.0.0 release where it will become required. */ - (void)didDeselectSectionController:(IGListSingleSectionController *)sectionController withObject:(id)object; @end /** This section controller is meant to make building simple, single-cell lists easier. By providing the type of cell, a block to configure the cell, and a block to return the size of a cell, you can use an `IGListAdapter`-powered list with a simpler architecture. */ IGLK_SUBCLASSING_RESTRICTED NS_SWIFT_NAME(ListSingleSectionController) @interface IGListSingleSectionController : IGListSectionController /** Creates a new section controller for a given cell type that will always have only one cell when present in a list. @param cellClass The `UICollectionViewCell` subclass for the single cell. @param configureBlock A block that configures the cell with the item given to the section controller. @param sizeBlock A block that returns the size for the cell given the collection context. @return A new section controller. @warning Be VERY CAREFUL not to create retain cycles by holding strong references to: the object that owns the adapter (usually `self`) or the `IGListAdapter`. Pass in locally scoped objects or use `weak` references! */ - (instancetype)initWithCellClass:(Class)cellClass configureBlock:(IGListSingleSectionCellConfigureBlock)configureBlock sizeBlock:(IGListSingleSectionCellSizeBlock)sizeBlock; /** Creates a new section controller for a given nib name and bundle that will always have only one cell when present in a list. @param nibName The name of the nib file for the single cell. @param bundle The bundle in which to search for the nib file. If `nil`, this method looks for the file in the main bundle. @param configureBlock A block that configures the cell with the item given to the section controller. @param sizeBlock A block that returns the size for the cell given the collection context. @return A new section controller. @warning Be VERY CAREFUL not to create retain cycles by holding strong references to: the object that owns the adapter (usually `self`) or the `IGListAdapter`. Pass in locally scoped objects or use `weak` references! */ - (instancetype)initWithNibName:(NSString *)nibName bundle:(nullable NSBundle *)bundle configureBlock:(IGListSingleSectionCellConfigureBlock)configureBlock sizeBlock:(IGListSingleSectionCellSizeBlock)sizeBlock; /** Creates a new section controller for a given storyboard cell identifier that will always have only one cell when present in a list. @param identifier The identifier of the cell prototype in storyboard. @param configureBlock A block that configures the cell with the item given to the section controller. @param sizeBlock A block that returns the size for the cell given the collection context. @return A new section controller. @warning Be VERY CAREFUL not to create retain cycles by holding strong references to: the object that owns the adapter (usually `self`) or the `IGListAdapter`. Pass in locally scoped objects or use `weak` references! */ - (instancetype)initWithStoryboardCellIdentifier:(NSString *)identifier configureBlock:(IGListSingleSectionCellConfigureBlock)configureBlock sizeBlock:(IGListSingleSectionCellSizeBlock)sizeBlock; /** An optional delegate that handles selection and deselection. */ @property (nonatomic, weak, nullable) id<IGListSingleSectionControllerDelegate> selectionDelegate; /** :nodoc: */ - (instancetype)init NS_UNAVAILABLE; /** :nodoc: */ + (instancetype)new NS_UNAVAILABLE; @end NS_ASSUME_NONNULL_END
{ "content_hash": "b6f6875c33a2269d943ea67a6353f6de", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 132, "avg_line_length": 38.43571428571428, "alnum_prop": 0.7623118379483368, "repo_name": "PJayRushton/stats", "id": "745d45062b31053f7a5059059e1495ce226ea444", "size": "5689", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Pods/IGListKit/Source/IGListSingleSectionController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1918" }, { "name": "Swift", "bytes": "516587" } ], "symlink_target": "" }
Ext.define('icc.view.idatabase.Structure.FilterCombobox', { extend : 'icc.common.Combobox', alias : 'widget.idatabaseStructureFilterCombobox', fieldLabel : '选择过滤器', name : 'filter', store : 'idatabase.Structure.FilterType', valueField : 'val', displayField : 'name', queryMode : 'remote', editable : false, typeAhead : false });
{ "content_hash": "cf4c5b5afbc371c47218c8bea0a2362f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 59, "avg_line_length": 29.25, "alnum_prop": 0.6923076923076923, "repo_name": "handsomegyr/ent", "id": "17592a71ee5a61c449218c05c66dbb0b7ff6a1a2", "size": "361", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/js/.sencha_backup/icc/4.2.2.1144/app/view/idatabase/Structure/FilterCombobox.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "8148133" }, { "name": "JavaScript", "bytes": "95187624" }, { "name": "PHP", "bytes": "777992" }, { "name": "Ruby", "bytes": "7898" } ], "symlink_target": "" }
A First Level Header ==================== A Second Level Header --------------------- Now is the time for all good men to come to the aid of their country. This is just a regular paragraph. The quick brown fox jumped over the lazy dog's back. ### Header 3 > This is a blockquote. > > This is the second paragraph in the blockquote. > > ## This is an H2 in blockquote a
{ "content_hash": "21232b3104bdaef5d3b9255c3c43822f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 49, "avg_line_length": 18.75, "alnum_prop": 0.6453333333333333, "repo_name": "ocpsoft/rewrite", "id": "dcb4f08cd5168cf109a41242aaeae02e7df8d509", "size": "375", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "showcase/transform/src/main/webapp/markdown/index.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6794" }, { "name": "HTML", "bytes": "59894" }, { "name": "Java", "bytes": "2721796" }, { "name": "JavaScript", "bytes": "697545" }, { "name": "Less", "bytes": "383" }, { "name": "Ruby", "bytes": "1234887" }, { "name": "SCSS", "bytes": "193" }, { "name": "Shell", "bytes": "815" } ], "symlink_target": "" }
using System.Reflection; using System.Web.Mvc; using Composite.Core.Routing; using Composite.Core.WebClient.Renderings.Page; namespace CompositeC1Contrib.Rendering.Mvc.Routing { public class C1RenderingReasonAttribute : ActionMethodSelectorAttribute { private readonly RenderingReason _renderingReason; public C1RenderingReasonAttribute(RenderingReason renderingReason) { _renderingReason = renderingReason; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { if (PageRenderer.RenderingReason == RenderingReason.Undefined) { PageRenderer.RenderingReason = new UrlSpace(controllerContext.HttpContext).ForceRelativeUrls ? RenderingReason.C1ConsoleBrowserPageView : RenderingReason.PageView; } return _renderingReason == RenderingReason.Undefined || _renderingReason == PageRenderer.RenderingReason; } } }
{ "content_hash": "f7b8253d1131d2d5f84912caf429ec19", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 179, "avg_line_length": 36.857142857142854, "alnum_prop": 0.7044573643410853, "repo_name": "burningice2866/CompositeC1Contrib", "id": "8ec11e22a7cd01c2ac6319db8fad5df9ea331128", "size": "1034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Rendering.Mvc/Routing/C1RenderingReasonAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "12894" }, { "name": "C#", "bytes": "680107" }, { "name": "CSS", "bytes": "2766" }, { "name": "HTML", "bytes": "2927" }, { "name": "JavaScript", "bytes": "2427" }, { "name": "XSLT", "bytes": "6068" } ], "symlink_target": "" }
package org.wso2.das.analytics.rest.beans; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * The bean class for column types */ @XmlType(name = "columnType") @XmlEnum public enum ColumnTypeBean { @XmlEnumValue("STRING") STRING, @XmlEnumValue("INTEGER") INTEGER, @XmlEnumValue("LONG") LONG, @XmlEnumValue("FLOAT") FLOAT, @XmlEnumValue("DOUBLE") DOUBLE, @XmlEnumValue("BOOLEAN") BOOLEAN, @XmlEnumValue("BINARY") BINARY, @XmlEnumValue("FACET") FACET }
{ "content_hash": "36fcbdae57512bb3142c7effe1b63936", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 46, "avg_line_length": 15.375, "alnum_prop": 0.6682926829268293, "repo_name": "Amutheezan/product-das", "id": "d2fafaa462d655a05e7e69743f2736dad9d14174", "size": "1285", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/das/analytics/rest/beans/ColumnTypeBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15145" }, { "name": "CSS", "bytes": "152643" }, { "name": "HTML", "bytes": "13285" }, { "name": "Java", "bytes": "531667" }, { "name": "JavaScript", "bytes": "6729217" }, { "name": "Shell", "bytes": "156931" } ], "symlink_target": "" }
package ws.web.dto; public class ChannelDTO { private String name; private Integer platformID; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPlatformID() { return platformID; } public void setPlatformID(Integer platformID) { this.platformID = platformID; } }
{ "content_hash": "613c9b2712b1c56bf74bbe982e56213d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 51, "avg_line_length": 17.608695652173914, "alnum_prop": 0.6197530864197531, "repo_name": "Gyoo/Discord-Streambot", "id": "5aa9b4ce7d9c7743ab95a440f51a4c969caa8f9e", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ws/web/dto/ChannelDTO.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "80292" } ], "symlink_target": "" }
<?php class Crunchbutton_Order_Logistics_Parking extends Cana_Table { const DEFAULT_TIME = 5; // minutes public function __construct($id = null) { parent::__construct(); $this ->table('order_logistics_parking') ->idVar('id_order_logistics_parking') ->load($id); } }
{ "content_hash": "c7a051d52e43e37e637ded0d9c66b60a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 61, "avg_line_length": 21, "alnum_prop": 0.5625, "repo_name": "crunchbutton/crunchbutton", "id": "a50a45819172e94a96a26c624ce23a32620fa53b", "size": "336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/library/Crunchbutton/Order/Logistics/Parking.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "926622" }, { "name": "Dockerfile", "bytes": "1222" }, { "name": "HTML", "bytes": "1802625" }, { "name": "JavaScript", "bytes": "3783935" }, { "name": "PHP", "bytes": "4055953" }, { "name": "Shell", "bytes": "6131" }, { "name": "TSQL", "bytes": "65011" } ], "symlink_target": "" }
import numpy as np from .Player import Player from ..ai import GameTree, heuristic from ..ai.search import * class RobotTS(Player): is_ai = True def __init__(self, name='R0bot', stone=0, search_method=Minimax( hfunc=heuristic.Simple().evaluate, use_symmetry=True), depth=4, silent=True): super().__init__(name=name, stone=stone) self._search_method = search_method self._depth = depth self._silent = silent def decide(self, game): tree = GameTree('current', game_core=game.core) self._search_method.search(node=tree, depth=self._depth) coords_reward = [(child.name, child.reward) for child in tree.children] best_reward = max(r for _, r in coords_reward) best_coords = [m for m, r in coords_reward if r == best_reward] if self._search_method.use_symmetry: coord_choices = list() for x in best_coords: coord_choices.extend(game.gameboard.equivalent_coords_dict.get(x, [x])) coord_choices = list(set(coord_choices)) else: coord_choices = best_coords coord = coord_choices[np.random.choice(range(len(coord_choices)))] if not self._silent: print(game.turn) print('root:', tree.root_player) print(game.gameboard.array) tree.show(1) print(coord_choices) return coord def decide_ui(self, game_ui): coord = self.decide(game=game_ui.game) game_ui.gameboard_buttons.get(coord).click()
{ "content_hash": "82c02d584269c16578ea728e749cf9c8", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 87, "avg_line_length": 37.40909090909091, "alnum_prop": 0.5741190765492102, "repo_name": "kitman0804/BoardGame", "id": "01c3eca3c2b4e5689f3021723a5fec0e5560b294", "size": "1646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BoardGame/prototype/mnkgame/players/RobotTS.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "44138" } ], "symlink_target": "" }
<?php namespace AppBundle\Form\Type; use AppBundle\Entity\Author; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class AuthorType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', TextType::class, [ 'required' => true, ]); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Author::class ]); } }
{ "content_hash": "55c7e624661ef794fdf5ab3fd90cac6d", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 76, "avg_line_length": 23.03125, "alnum_prop": 0.6445047489823609, "repo_name": "burnhamrobertp/AdventureLookup", "id": "d5ce847cf9a6290120d4007d589d637e9a007fbe", "size": "737", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AppBundle/Form/Type/AuthorType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3605" }, { "name": "CSS", "bytes": "1745" }, { "name": "HTML", "bytes": "67771" }, { "name": "JavaScript", "bytes": "13354" }, { "name": "PHP", "bytes": "388574" }, { "name": "Shell", "bytes": "1313" } ], "symlink_target": "" }
function Enable-IisSecurityAuthentication { <# .SYNOPSIS Enables anonymous or basic authentication for an entire site or a sub-directory of that site. .DESCRIPTION By default, enables an authentication type on an entire website. You can enable an authentication type at a specific path under a website by passing the virtual path (*not* the physical path) to that directory as the value of the `Path` parameter. .LINK Disable-IisSecurityAuthentication .LINK Get-IisSecurityAuthentication .LINK Test-IisSecurityAuthentication .EXAMPLE Enable-IisSecurityAuthentication -SiteName Peanuts -Anonymous Turns on anonymous authentication for the `Peanuts` website. .EXAMPLE Enable-IisSecurityAuthentication -SiteName Peanuts Snoopy/DogHouse -Basic Turns on anonymous authentication for the `Snoopy/DogHouse` directory under the `Peanuts` website. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # The site where anonymous authentication should be set. $SiteName, [string] # The optional path where anonymous authentication should be set. $Path = '', [Parameter(Mandatory=$true,ParameterSetName='Anonymous')] [Switch] # Enable anonymouse authentication. $Anonymous, [Parameter(Mandatory=$true,ParameterSetName='Basic')] [Switch] # Enable basic authentication. $Basic, [Parameter(Mandatory=$true,ParameterSetName='Windows')] [Switch] # Enable Windows authentication. $Windows ) $authType = $pscmdlet.ParameterSetName $getArgs = @{ $authType = $true; } $authSettings = Get-IisSecurityAuthentication -SiteName $SiteName -Path $Path @getArgs $authSettings.SetAttributeValue('enabled', 'true') if( $pscmdlet.ShouldProcess( "$SiteName/$Path", ("enable {0}" -f $authType) ) ) { Write-Host ('IIS:{0}/{1}: enabling {2} authentication' -f $SiteName,$Path,$authType) $authSettings.CommitChanges() } }
{ "content_hash": "c5b410fe104e8d183f23d15f0def36c5", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 252, "avg_line_length": 31.985294117647058, "alnum_prop": 0.6616091954022989, "repo_name": "cloudoman/carbon", "id": "6b93ad297daacb8248ab2f8bbb1d176236dee7a2", "size": "2755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Carbon/IIS/Enable-IisSecurityAuthentication.ps1", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "61104" }, { "name": "CSS", "bytes": "1499" }, { "name": "PowerShell", "bytes": "862541" } ], "symlink_target": "" }
require 'spec_helper' describe Spree::PageLayout do let (:page_layout) { Spree::PageLayout.first } it "build html css js" do html, css = page_layout.build_content html.present?.should be_true css.present?.should be_true end it "create new page_layout tree" do # objects = Spree::Section.roots # section_hash= objects.inject({}){|h,sp| h[sp.slug] = sp; h} # center area # center_area = Spree::PageLayout.create_layout(section_hash['center_area'], "center_area") # center_area.add_section(section_hash['center_part'],:title=>"center_part") # center_area.add_section(section_hash['left_part'],:title=>"left_part") # center_area.add_section(section_hash['right_part'],:title=>"right_part") # center_area.children.count.should eq(3) # center_area.param_values.count.should eq(0) end it "valid section context" do product_detail = Spree::PageLayout.find_by_section_context( Spree::PageLayout::ContextEnum.detail) product_detail.context_detail?.should be_true product_list = Spree::PageLayout.find_by_section_context( Spree::PageLayout::ContextEnum.list) product_list.context_list?.should be_true end it "could update context" do list_section = Spree::PageLayout.find_by_section_context('list') detail_section = Spree::PageLayout.find_by_section_context('detail') #contexts = [Spree::PageLayout::ContextEnum.account, Spree::PageLayout::ContextEnum.thanks,Spree::PageLayout::ContextEnum.cart, Spree::PageLayout::ContextEnum.checkout] contexts = [Spree::PageLayout::ContextEnum.list, Spree::PageLayout::ContextEnum.detail] page_layout.update_section_context contexts for node in page_layout.self_and_descendants if node.is_or_is_descendant_of? list_section node.current_contexts.should eq(list_section.current_contexts) elsif node.is_or_is_descendant_of? detail_section node.current_contexts.should eq(detail_section.current_contexts) else node.current_contexts.should eq(contexts) end end end it "could verify contexts" do Spree::PageLayout.verify_contexts( Spree::PageLayout::ContextEnum.cart, [:cart, :checkout, :thankyou ] ).should be_true Spree::PageLayout.verify_contexts( [Spree::PageLayout::ContextEnum.cart], [:cart, :checkout, :thankyou ] ).should be_true Spree::PageLayout.verify_contexts( Spree::PageLayout::ContextEnum.either, [:cart, :checkout, :thankyou ] ).should be_false end it "could replace section" do original_page_layout = page_layout.dup root2 = Spree::Section.find('root2') page_layout.replace_with(root2) original_page_layout.param_values.empty?.should be_true page_layout.section.should eq root2 page_layout.param_values.present?.should be_true end end
{ "content_hash": "32591e64cce624099a25291ddb631452", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 172, "avg_line_length": 40.5, "alnum_prop": 0.7022927689594356, "repo_name": "RuanShan/spree_theme", "id": "47d223ba92f0a8a3dc995906f69b08f79160f327", "size": "2858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/page_layout_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9761" }, { "name": "JavaScript", "bytes": "253599" }, { "name": "Ruby", "bytes": "284748" } ], "symlink_target": "" }
pv - WebGL protein viewer ========================================= pv is a WebGL-based protein viewer whose goal is to once-for-all end the reign of Java applets on websites that require visualisation of protein structures. It's not you Java, it's all the annoying security popups and slow loading times. pv implements all major render modes that you would expect, and supports custom color schemes. Because there is nothing worse than a unresponsive website, pv has been implemented with maximum performane in mind. Even very large macromolecules can be visualised at interactive framerates. Trying it out ----------------------------------------- You can try the [online demo](http://biasmv.github.io/pv/demo.html) or run it locally on your computer. Clone this repository ```bash git clone https://github.com/biasmv/pv.git ``` Change to the pv directory and serve the files using the serve script in the source directory. This will start a simple static-file server using Python's SimpleHTTPServer module. ```bash cd pv ./serve ``` Open a WebGL-enabled web browser and visit http://localhost:8000 Want to use PV on your website? ---------------------------------------- I would love you to! Most features you would expect from a protein viewer are already present and working. One considerations is important though: * WebGL is only supported in a subset of browsers. If you can afford to lose users of IE and older versions of browsers, `pv` is a good solution for protein visualisation. Citing PV? ---------------------------------------- I'm planning on writing a small application note, but in the mean time, use the following DOI for citing PV in your work. [![DOI](https://zenodo.org/badge/7050/biasmv/pv.png)](http://dx.doi.org/10.5281/zenodo.12620) Contributing ----------------------------------------- Contributions of any kind (bugfixes, documentation, new features etc) are more than welcome. Just file bugs or file bug requests. Before submitting pull requests, please make sure to follow these [guide-lines](https://github.com/biasmv/pv/blob/master/CONTRIBUTE.md). Acknowledgements ---------------------------------------- PV uses the amazing [gl-matrix](https://github.com/toji/gl-matrix) JavaScript library for matrix and vector operations. Thanks to @Traksewt, @kozmad, @greenify for their contributions Documentation --------------------------------------- Documentation for pv is available [here](http://pv.readthedocs.org). Changelog ---------------------------------------- # New since latest release - Added special selection highlighting render mode. - Improve handling of click event by only firing click events when the mouse button is pressed/released within a short timespan. - Improve rendering of outline by properly scaling the extrusion factor based on the size of the GL canvas. # New in Version 1.7.2 - Made a few changes to the samples contained in the docs that don't work for some people. There is no functionality change on the code-level, that's why there is no 1.7.2 release. # New in Version 1.7.1 - Added bower.json to release package so people can install PV using bower. This only works for release packages, but not the git repository itself. ### New in Version 1.7.0 - PDB import: Improved code to guess element from atom name. This fixes issues in correctly detecting hydrogen atoms for some cases. - Add support for click events on custom meshes - Deprecated atomDoubleClick/atomClick events in favor of click/doubleClicked to make it clearer that the target of the click event might be objects other than atoms. - Simplified the picking results object. The picking results now provides the position of the clicked object as the ```pos()``` property. It is no longer required to transform the atom position by the symmetry transformation matrix when displaying biological units. - Support for loading multi-model pdb files. - Added functionality to superpose two structures using least-square fitting ### New in Version 1.6.0 - Added option to set field of view (FOV) - Added "points" rendering mode in which every atom is rendered as a point. This is useful for rendering point clouds. - Get BioJS snippets working again (@greenify) ### New in Version 1.5.0 - Added Viewer.spin command to spin the camera around an axis - Relax some limits on number of elements that could be rendered at full connectivity level. Now it would theoretically be possible to render 2^24 atoms, even though the amount of geometry is likely to take down the browser. - Fix rendering for very long RNA molecules that broke some assumptions in the cartoon rendering code (1J5E, for example see issue [#82](https://github.com/biasmv/pv/issues/82)). - Improve heuristics to determine whether two residues belong to the same trace by not introducing trace breaks in case the residues are connected by a bond. This allows users to manually set bonds in case they have other means of knowing that two residues are to part of the same trace ([#83](https://github.com/biasmv/pv/issues/83)). ### New in Version 1.4.0 - Basic support RNA/DNA rendering for all render modes - Multi-touch support for iOS and Android (with contributions by @kozmad, @lordvlad) - improved visual clarity of text labels - use correct line width when manual anti-aliasing is enabled. - text labels can now be styled (color, font-family, font-weight, size) - reduced file size of minified JavaScript file by a little more than 10% - ability to add geometric shapes to the 3D scene through customMesh - ability to specify custom color palettes (@andreasprlic) - viewerReady event (@andreasprlic) - PV can optionally be used as an AMD module without polluting the global namespace - added more unit and functional tests. The tests reach a coverage of 80% of the total number of exectuable lines of code. - support for loading small molecules from SDF files ### New in Version 1.3.1 - fix bug in strand smoothing which would cause residues at the beginning of the trace to get collapsed. - rendering: check for null slab object to allow drawing to work when no objects are visible. ### New in Version 1.3 - publish it as an npm module - PDB IO: parse insertion codes - add method to retrieve current color of atom. This is useful for highlighting purposes, where the color of certain atoms is temporarily changed and then reverted back to the original. - smoothing of strands when rendering as helix, strand, coil cartoon - implement proper strand "arrows" - improved auto-slabbing when the rendered objects are off-center ### New in Version 1.2 - add transparancy support to mesh and line geoms (@kozmad) - substantial speed improvements through implementation of buffer pool for typed arrays. - method to assign secondary structure based on carbon-alpha positions - improved documentation - improve dictionary selection - support for adding text labels to the 3D scene - autoZoom to fit structure into viewport - work around uint16 buffer limit of WebGL by automatically splitting the geometry of large molecules into multiple buffers - support for different color notations, e.g. hex, color names. - support for displaying molecular assemblies, including support for picking of symmetry-related copies - implement different slab-modes - rudimentary support for rendering MSMS surfaces in the browser. Requires conversion to binary format first. - adding customisable animation time (@Traksewt) - add customizable atom picking events (double and single click) (@Traksewt) - improved animation support (@Traksewt) - customizable background color (@Traksewt)
{ "content_hash": "2ad73bc793769f574e58df86eeedd9ff", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 335, "avg_line_length": 50.71333333333333, "alnum_prop": 0.7504929670040752, "repo_name": "Traksewt/pv", "id": "35eec278ddbf8cd0e68fcd3172899ee8cc65f045", "size": "7607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4992" }, { "name": "HTML", "bytes": "6394" }, { "name": "JavaScript", "bytes": "602098" }, { "name": "Python", "bytes": "7028" }, { "name": "Shell", "bytes": "880" } ], "symlink_target": "" }
<?php /* |-------------------------------------------------------------------------- | Auth Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application authencation. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ if (config('auth.routes.login')) { Route::get('login', 'Auth\LoginController@showLoginForm')->name('login'); Route::post('login', 'Auth\LoginController@login'); Route::post('logout', 'Auth\LoginController@logout')->name('logout'); Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request'); Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email'); Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset'); Route::post('password/reset', 'Auth\ResetPasswordController@reset'); } if (config('auth.routes.register')) { Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); Route::post('register', 'Auth\RegisterController@register'); } if (config('auth.routes.social') === true) { Route::get('auth/{provider}', 'Auth\SocialAuthencation@redirectToProvider')->name('social'); Route::get('auth/{provider}/callback', 'Auth\SocialAuthencation@handleProviderCallback')->name('social.callback'); }
{ "content_hash": "9ae2a2d056f456a2e5a85d18019b5ae8", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 118, "avg_line_length": 46.18181818181818, "alnum_prop": 0.6535433070866141, "repo_name": "CPSB/Skeleton-project", "id": "b9d2ca9db7ceedda9f16c1e28c501b27368daad8", "size": "1524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "routes/auth.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "81989" }, { "name": "PHP", "bytes": "229476" }, { "name": "Shell", "bytes": "177" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
require_relative 'live_query' require 'volt/utils/generic_pool' # LiveQueryPool runs on the server and keeps track of all outstanding # queries. class LiveQueryPool < Volt::GenericPool def initialize(data_store) @data_store = data_store super() end def lookup(collection, query) # collection = collection.to_sym query = normalize_query(query) super(collection, query) end def updated_collection(collection, skip_channel) # collection = collection.to_sym lookup_all(collection).each do |live_query| live_query.run(skip_channel) end end private # Creates the live query if it doesn't exist, and stores it so it # can be found later. def create(collection, query = {}) # collection = collection.to_sym # If not already setup, create a new one for this collection/query LiveQuery.new(self, @data_store, collection, query) end def normalize_query(query) # TODO: add something to sort query properties so the queries are # always compared the same. query end end
{ "content_hash": "912d48274299ffce15d9f6b78d716924", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 70, "avg_line_length": 25.071428571428573, "alnum_prop": 0.704653371320038, "repo_name": "bglusman/volt", "id": "ec6c11cea1737a6952865ea649dc2b384f362147", "size": "1053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/volt/tasks/live_query/live_query_pool.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "508" }, { "name": "HTML", "bytes": "51226" }, { "name": "JavaScript", "bytes": "6607" }, { "name": "Ruby", "bytes": "476472" } ], "symlink_target": "" }
/* * rt_defines.h * * Code generation for model "CSE1_HIL_tau". * * Model version : 1.153 * Simulink Coder version : 8.6 (R2014a) 27-Dec-2013 * C source code generated on : Tue Apr 14 18:13:38 2015 * * Target selection: NIVeriStand_VxWorks.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: 32-bit Generic * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_rt_defines_h_ #define RTW_HEADER_rt_defines_h_ /*===========* * Constants * *===========*/ #define RT_PI 3.14159265358979323846 #define RT_PIF 3.1415927F #define RT_LN_10 2.30258509299404568402 #define RT_LN_10F 2.3025851F #define RT_LOG10E 0.43429448190325182765 #define RT_LOG10EF 0.43429449F #define RT_E 2.7182818284590452354 #define RT_EF 2.7182817F /* * UNUSED_PARAMETER(x) * Used to specify that a function parameter (argument) is required but not * accessed by the function body. */ #ifndef UNUSED_PARAMETER # if defined(__LCC__) # define UNUSED_PARAMETER(x) /* do nothing */ # else /* * This is the semi-ANSI standard way of indicating that an * unused function parameter is required. */ # define UNUSED_PARAMETER(x) (void) (x) # endif #endif #endif /* RTW_HEADER_rt_defines_h_ */
{ "content_hash": "914e40ccf9a72767e2f619c781bd27ee", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 81, "avg_line_length": 31.775510204081634, "alnum_prop": 0.5857418111753372, "repo_name": "NTNU-MCS/CS_EnterpriseI", "id": "161fb8a9dd510fd67de80f4dc27eb87fc3ed1905", "size": "1557", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "02 simulink code/CSE1_HIL_tau_niVeriStand_VxWorks_rtw/rt_defines.h", "mode": "33188", "license": "mit", "language": [ { "name": "AGS Script", "bytes": "116448" }, { "name": "Batchfile", "bytes": "28199" }, { "name": "C", "bytes": "42454968" }, { "name": "C++", "bytes": "179753" }, { "name": "HTML", "bytes": "90461" }, { "name": "LabVIEW", "bytes": "726855" }, { "name": "Makefile", "bytes": "789944" }, { "name": "Matlab", "bytes": "134137" }, { "name": "Objective-C", "bytes": "1128875" }, { "name": "XSLT", "bytes": "23994" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Schools extends CI_Controller { public function view($school_name) { $school_header_info_q = $this->db->query("select sc_full_name, tagline from schools where sc_name = '$school_name'"); $school_header_info = $school_header_info_q->row(); $data ['title'] = strtoupper($school_name) . '&nbsp;|&nbsp; GBU Online'; $data ['heading'] = $school_header_info->sc_full_name; $data['message'] = $school_header_info->tagline; $data['school_name'] = $school_name; $this->load->view('pages/common/link',$data); $this->load->view('pages/common/header'); $this->load->view('pages/common/page-heading',$data); $this->load->view('pages/schools/school_info',$school_name); $this->load->view('pages/common/extras'); $this->load->view('pages/common/footer'); } }
{ "content_hash": "049930c90fe97dc314c60b7f5047ce5e", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 129, "avg_line_length": 43.95454545454545, "alnum_prop": 0.5894519131334023, "repo_name": "opengbu/gbuonline", "id": "3c7267019c8386534107d63192882650bf1ac168", "size": "967", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Schools.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1153" }, { "name": "CSS", "bytes": "109308" }, { "name": "HTML", "bytes": "214902" }, { "name": "JavaScript", "bytes": "27053" }, { "name": "PHP", "bytes": "2571880" } ], "symlink_target": "" }
import { TooltipProps } from 'src/components/Tooltip'; export const TOOLTIP_COMMON_PROPS: Partial<TooltipProps> = { moveBy: { x: 0, y: 2 }, appendTo: 'scrollParent', placement: 'top', };
{ "content_hash": "92709a08286959338606e0d6a8579a42", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 27.714285714285715, "alnum_prop": 0.6804123711340206, "repo_name": "wix/wix-style-react", "id": "e58251c72a6d85b8c92fd677e35c21af7dae88fd", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/wix-ui-tpa/src/components/ColorPicker/ColorPickerItem/tooltipCommonProps.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "325595" }, { "name": "HTML", "bytes": "20584" }, { "name": "JavaScript", "bytes": "4465095" }, { "name": "Shell", "bytes": "4264" }, { "name": "TypeScript", "bytes": "219813" } ], "symlink_target": "" }
package com.tinapaproject.tinapa; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.FrameLayout; import android.widget.ImageView; import com.squareup.otto.Bus; import com.squareup.otto.Subscribe; import com.tinapaproject.tinapa.database.key.DexKeyValues; import com.tinapaproject.tinapa.database.key.OwnedKeyValues; import com.tinapaproject.tinapa.database.key.PlannedKeyValues; import com.tinapaproject.tinapa.database.key.TeamKeyValues; import com.tinapaproject.tinapa.database.provider.TinapaContentProvider; import com.tinapaproject.tinapa.events.CreatePlannedPokemonEvent; import com.tinapaproject.tinapa.events.DeleteOwnedPokemonEvent; import com.tinapaproject.tinapa.events.DeletePlannedPokemonEvent; import com.tinapaproject.tinapa.events.SaveTeamEvent; import com.tinapaproject.tinapa.events.StartNewTeamEvent; import com.tinapaproject.tinapa.events.TeamListSelectedEvent; import com.tinapaproject.tinapa.fragments.DexDetailFragment; import com.tinapaproject.tinapa.fragments.DexDetailFragment.DexDetailListener; import com.tinapaproject.tinapa.fragments.DexListFragment; import com.tinapaproject.tinapa.fragments.DexListFragment.DexListListener; import com.tinapaproject.tinapa.fragments.OwnedAddDialogFragment; import com.tinapaproject.tinapa.fragments.OwnedAddDialogFragment.OwnedAddFragmentListener; import com.tinapaproject.tinapa.fragments.OwnedListFragment; import com.tinapaproject.tinapa.fragments.OwnedListFragment.OwnedListListener; import com.tinapaproject.tinapa.fragments.PlannedAddDialogFragment; import com.tinapaproject.tinapa.fragments.PlannedListFragment; import com.tinapaproject.tinapa.fragments.PlannedListFragment.PlannedListListener; import com.tinapaproject.tinapa.fragments.TeamAddDialogFragment; import com.tinapaproject.tinapa.fragments.TeamListFragment; public class MainActivity extends Activity implements DexListListener, DexDetailListener, OwnedListListener, OwnedAddFragmentListener, PlannedListListener { private String temp_id; private ImageView temp_imageView; private boolean temp_isDefault; private boolean temp_isShiny; private boolean temp_isIcon; private Bus bus; public static int RESULT_LOAD_DEX_LIST_ICON = 100; public static final String SAVE_STATE_SELECTED_TAB_INDEX = "SAVE_STATE_SELECTED_TAB_INDEX"; public static final String DEX_DETAILS_FRAGMENT = "DEX_DETAILS_FRAGMENT"; public static final String OWNED_DETAILS_FRAGMENT = "OWNED_DETAILS_FRAGMENT"; public static final String PLANNED_DETAILS_FRAGMENT = "PLANNED_DETAILS_FRAGMENT"; public static final String TEAM_DETAILS_FRAGMENT = "TEAM_DETAILS_FRAGMENT"; public static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bus = TinapaApplication.bus; bus.register(this); ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); Tab dexTab = actionBar.newTab() .setText(R.string.tab_pokedex) .setTabListener(new TabListener<DexListFragment>("Pokedex" /*TODO: Needs to be a field. */, new DexListFragment())); actionBar.addTab(dexTab, true); Tab ownedTab = actionBar.newTab() .setText(R.string.tab_owned_pokemon) .setTabListener(new TabListener<OwnedListFragment>("Owned" /*TODO: Needs to be a field. */, new OwnedListFragment())); actionBar.addTab(ownedTab); Tab plannedTab = actionBar.newTab() .setText(R.string.tab_planned_pokemon) .setTabListener(new TabListener<PlannedListFragment>("Planned" /*TODO: Needs to be a field. */, new PlannedListFragment())); actionBar.addTab(plannedTab); Tab teamTab = actionBar.newTab() .setText(R.string.tab_teams) .setTabListener(new TabListener<TeamListFragment>("Team" /*TODO: Needs to be a field. */, new TeamListFragment())); actionBar.addTab(teamTab); Log.i(TAG, "All tabs have been added."); if (savedInstanceState != null) { actionBar.setSelectedNavigationItem(savedInstanceState.getInt(SAVE_STATE_SELECTED_TAB_INDEX, 0)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); bus.register(this); } @Override protected void onPause() { super.onPause(); bus.unregister(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_DEX_LIST_ICON && resultCode == RESULT_OK && data != null) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.outHeight = temp_imageView.getHeight(); imageOptions.outWidth = temp_imageView.getWidth(); temp_imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath, imageOptions)); // Now store the path Cursor imageQuery = null; if (!TextUtils.isEmpty(temp_id)) { imageQuery = getContentResolver().query(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, null, "pokemon_id = " + temp_id + " AND is_default = " + (temp_isDefault ? 1 : 0) + " AND is_shinny = " + (temp_isShiny ? 1 : 0) + " AND is_icon = " + (temp_isIcon ? 1 : 0), null, null); ContentValues values = new ContentValues(); values.put(DexKeyValues.imageUri, picturePath); values.put(DexKeyValues.isDefault, temp_isDefault ? 1 : 0); values.put(DexKeyValues.isShiny, temp_isShiny ? 1 : 0); values.put(DexKeyValues.isIcon, temp_isIcon ? 1 : 0); if (imageQuery.getCount() > 0) { getContentResolver().update(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, values, DexKeyValues.insertIntoImageColumnWhereCreation(temp_id), null); } else { values.put("pokemon_id", temp_id); getContentResolver().insert(TinapaContentProvider.POKEDEX_POKEMON_IMAGE_URI, values); } } temp_id = null; temp_imageView = null; temp_isDefault = false; temp_isShiny = false; temp_isIcon = false; } } // From DexCursorAdapter @Override public void onDexItemClicked(String id) { // TODO: Pull information using the ID based off of the topic. // Cursor pokemonCursor = getContentResolver().query(TinapaContentProvider.POKEDEX_URI, null, "pokemon.id = " + id, null, null); // Cursor movesCursor = getContentResolver().query(TinapaContentProvider.POKEDEX_POKEMON_MOVES_URI, null, "pokemon_moves.pokemon_id = " + id, null, null); FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), DexDetailFragment.newInstance(id), DEX_DETAILS_FRAGMENT); ft.addToBackStack("DexDetail"); ft.commit(); } // From DexCursorAdapter @Override public void onDexImageLongClicked(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { loadImage(id, imageView, isDefault, isShiny, isIcon); } // From DexDetailFragment @Override public void onDexDetailImageLongClicked(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { loadImage(id, imageView, isDefault, isShiny, isIcon); } // From OwnedListFragment @Override public void onOwnedItemClicked(String id) { FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), OwnedAddDialogFragment.newInstance(id), OWNED_DETAILS_FRAGMENT); ft.addToBackStack("OwnedDetail"); ft.commit(); } // From OwnedListFragment @Override public void onAddOwnedClicked() { OwnedAddDialogFragment dialogFragment = OwnedAddDialogFragment.newInstance(); dialogFragment.show(getFragmentManager(), OwnedAddDialogFragment.TAG); } // From OwnedAddDialog @Override public void onPositiveClicked(int level, String nickname, boolean shinny, String speciesId, String abilityId, String natureId, String genderId, String move1Id, String move2Id, String move3Id, String move4Id, int ivHP, int ivAtt, int ivDef, int ivSAtt, int ivSDef, int ivSpd, int evHP, int evAtt, int evDef, int evSAtt, int evSDef, int evSpd, String notes, String planId) { // TODO ContentValues contentValues = new ContentValues(); contentValues.put(OwnedKeyValues.LEVEL, level); contentValues.put(OwnedKeyValues.NICKNAME, nickname); contentValues.put(OwnedKeyValues.SHINNY, shinny); contentValues.put(OwnedKeyValues.POKEMON_ID, speciesId); contentValues.put(OwnedKeyValues.ABILITY_ID, abilityId); contentValues.put(OwnedKeyValues.NATURE_ID, natureId); contentValues.put(OwnedKeyValues.GENDER_ID, genderId); contentValues.put(OwnedKeyValues.MOVE1_ID, move1Id); contentValues.put(OwnedKeyValues.MOVE2_ID, move2Id); contentValues.put(OwnedKeyValues.MOVE3_ID, move3Id); contentValues.put(OwnedKeyValues.MOVE4_ID, move4Id); contentValues.put(OwnedKeyValues.IV_HP, ivHP); contentValues.put(OwnedKeyValues.IV_ATT, ivAtt); contentValues.put(OwnedKeyValues.IV_DEF, ivDef); contentValues.put(OwnedKeyValues.IV_SATT, ivSAtt); contentValues.put(OwnedKeyValues.IV_SDEF, ivSDef); contentValues.put(OwnedKeyValues.IV_SPD, ivSpd); contentValues.put(OwnedKeyValues.EV_HP, evHP); contentValues.put(OwnedKeyValues.EV_ATT, evAtt); contentValues.put(OwnedKeyValues.EV_DEF, evDef); contentValues.put(OwnedKeyValues.EV_SATT, evSAtt); contentValues.put(OwnedKeyValues.EV_SDEF, evSDef); contentValues.put(OwnedKeyValues.EV_SPD, evSpd); contentValues.put(OwnedKeyValues.NOTE, notes); contentValues.put(OwnedKeyValues.PLAN_ID, planId); Uri uri = getContentResolver().insert(TinapaContentProvider.OWNED_POKEMON_URI, contentValues); Log.d(TAG, "Added an owned Pokemon with ID of " + uri.getLastPathSegment()); } // From OwnedAddDialog @Override public void onUpdateClicked(String ownedId, int level, String nickname, boolean shinny, String speciesId, String abilityId, String natureId, String genderId, String move1Id, String move2Id, String move3Id, String move4Id, int ivHP, int ivAtt, int ivDef, int ivSAtt, int ivSDef, int ivSpd, int evHP, int evAtt, int evDef, int evSAtt, int evSDef, int evSpd, String notes, String planId) { // TODO ContentValues contentValues = new ContentValues(); contentValues.put(OwnedKeyValues.LEVEL, level); contentValues.put(OwnedKeyValues.NICKNAME, nickname); contentValues.put(OwnedKeyValues.SHINNY, shinny); contentValues.put(OwnedKeyValues.POKEMON_ID, speciesId); contentValues.put(OwnedKeyValues.ABILITY_ID, abilityId); contentValues.put(OwnedKeyValues.NATURE_ID, natureId); contentValues.put(OwnedKeyValues.GENDER_ID, genderId); contentValues.put(OwnedKeyValues.MOVE1_ID, move1Id); contentValues.put(OwnedKeyValues.MOVE2_ID, move2Id); contentValues.put(OwnedKeyValues.MOVE3_ID, move3Id); contentValues.put(OwnedKeyValues.MOVE4_ID, move4Id); contentValues.put(OwnedKeyValues.IV_HP, ivHP); contentValues.put(OwnedKeyValues.IV_ATT, ivAtt); contentValues.put(OwnedKeyValues.IV_DEF, ivDef); contentValues.put(OwnedKeyValues.IV_SATT, ivSAtt); contentValues.put(OwnedKeyValues.IV_SDEF, ivSDef); contentValues.put(OwnedKeyValues.IV_SPD, ivSpd); contentValues.put(OwnedKeyValues.EV_HP, evHP); contentValues.put(OwnedKeyValues.EV_ATT, evAtt); contentValues.put(OwnedKeyValues.EV_DEF, evDef); contentValues.put(OwnedKeyValues.EV_SATT, evSAtt); contentValues.put(OwnedKeyValues.EV_SDEF, evSDef); contentValues.put(OwnedKeyValues.EV_SPD, evSpd); contentValues.put(OwnedKeyValues.NOTE, notes); contentValues.put(OwnedKeyValues.PLAN_ID, planId); getContentResolver().update(TinapaContentProvider.OWNED_POKEMON_URI, contentValues, "owned_pokemons.id == " + ownedId, null); Log.d(TAG, "Update an owned Pokemon with ID of " + ownedId); onBackPressed(); } @Subscribe public void deleteOwnedPokemon(DeleteOwnedPokemonEvent event) { getContentResolver().delete(TinapaContentProvider.OWNED_POKEMON_URI, event.getOwnedId(), null); Log.d(TAG, "The column for " + event.getOwnedId() + " was deleted."); onBackPressed(); } private void loadImage(String id, ImageView imageView, boolean isDefault, boolean isShiny, boolean isIcon) { temp_id = id; temp_imageView = imageView; temp_isDefault = isDefault; temp_isShiny = isShiny; temp_isIcon = isIcon; Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // intent.setType("image/*"); startActivityForResult(intent, RESULT_LOAD_DEX_LIST_ICON); } @Override public void plannedItemAddClicked() { PlannedAddDialogFragment dialogFragment = PlannedAddDialogFragment.newInstance(); dialogFragment.show(getFragmentManager(), PlannedAddDialogFragment.TAG); } @Override public void plannedItemClicked(String id) { FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), PlannedAddDialogFragment.newInstance(id), PLANNED_DETAILS_FRAGMENT); ft.addToBackStack("PlannedDetail"); ft.commit(); } @Override public void plannedItemLongClicked(String id) { // TODO } @Subscribe public void onPlannedPokemonAdded(CreatePlannedPokemonEvent event) { ContentValues contentValues = new ContentValues(); contentValues.put(PlannedKeyValues.POKEMON_ID, event.getSpeciesId()); contentValues.put(PlannedKeyValues.ABILITY_ID, event.getAbilityId()); contentValues.put(PlannedKeyValues.ITEM_ID, event.getItemId()); contentValues.put(PlannedKeyValues.NATURE_ID, event.getNatureId()); contentValues.put(PlannedKeyValues.MOVE1_ID, event.getMove1Id()); contentValues.put(PlannedKeyValues.MOVE2_ID, event.getMove2Id()); contentValues.put(PlannedKeyValues.MOVE3_ID, event.getMove3Id()); contentValues.put(PlannedKeyValues.MOVE4_ID, event.getMove4Id()); contentValues.put(PlannedKeyValues.IV_HP, event.getIvHP()); contentValues.put(PlannedKeyValues.IV_ATT, event.getIvAtt()); contentValues.put(PlannedKeyValues.IV_DEF, event.getIvDef()); contentValues.put(PlannedKeyValues.IV_SATT, event.getIvSAtt()); contentValues.put(PlannedKeyValues.IV_SDEF, event.getIvSDef()); contentValues.put(PlannedKeyValues.IV_SPD, event.getIvSpd()); contentValues.put(PlannedKeyValues.EV_HP, event.getEvHP()); contentValues.put(PlannedKeyValues.EV_ATT, event.getEvAtt()); contentValues.put(PlannedKeyValues.EV_DEF, event.getEvDef()); contentValues.put(PlannedKeyValues.EV_SATT, event.getEvSAtt()); contentValues.put(PlannedKeyValues.EV_SDEF, event.getEvSDef()); contentValues.put(PlannedKeyValues.EV_SPD, event.getEvSpd()); contentValues.put(PlannedKeyValues.NOTE, event.getNotes()); if (event.isNewSave()) { Uri uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, contentValues); Log.d(TAG, "Added a planned Pokemon with ID of " + uri.getLastPathSegment()); } else { int columnsChanged = getContentResolver().update(TinapaContentProvider.PLANNED_POKEMON_URI, contentValues, "planned_pokemons.id == " + event.getPlannedId(), null); Log.d(TAG, "A total of " + columnsChanged + "columns changed for updating " + event.getPlannedId()); onBackPressed(); } } @Subscribe public void deletePlannedPokemon(DeletePlannedPokemonEvent event) { getContentResolver().delete(TinapaContentProvider.PLANNED_POKEMON_URI, event.getPlannedId(), null); Log.d(TAG, "The column for " + event.getPlannedId() + " was deleted."); onBackPressed(); } @Subscribe public void openNewAddTeamFragment(StartNewTeamEvent event) { TeamAddDialogFragment.newInstance("").show(getFragmentManager(), TeamAddDialogFragment.TAG); } @Subscribe public void saveTeam(SaveTeamEvent event) { boolean addingTeam = TextUtils.isEmpty(event.getTeamId()); ContentValues teamValues = new ContentValues(); teamValues.put(TeamKeyValues.TEAM_NAME, event.getTeamName()); ContentValues pokemon1Values = new ContentValues(); pokemon1Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon1SpeciesId()); pokemon1Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon1AbilityId()); pokemon1Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon1ItemId()); pokemon1Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon1NatureId()); pokemon1Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon1Move1Id()); pokemon1Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon1Move2Id()); pokemon1Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon1Move3Id()); pokemon1Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon1Move4Id()); pokemon1Values.put(PlannedKeyValues.IV_HP, event.getPokemon1IvHp()); pokemon1Values.put(PlannedKeyValues.IV_ATT, event.getPokemon1IvAtt()); pokemon1Values.put(PlannedKeyValues.IV_DEF, event.getPokemon1IvDef()); pokemon1Values.put(PlannedKeyValues.IV_SATT, event.getPokemon1IvSAtt()); pokemon1Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon1IvSDef()); pokemon1Values.put(PlannedKeyValues.IV_SPD, event.getPokemon1IvSpd()); pokemon1Values.put(PlannedKeyValues.EV_HP, event.getPokemon1EvHp()); pokemon1Values.put(PlannedKeyValues.EV_ATT, event.getPokemon1EvAtt()); pokemon1Values.put(PlannedKeyValues.EV_DEF, event.getPokemon1EvDef()); pokemon1Values.put(PlannedKeyValues.EV_SATT, event.getPokemon1EvSAtt()); pokemon1Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon1EvSDef()); pokemon1Values.put(PlannedKeyValues.EV_SPD, event.getPokemon1EvSpd()); pokemon1Values.put(PlannedKeyValues.NOTE, event.getPokemon1Notes()); Uri pokemon1Uri; String pokemon1Id = ""; if (addingTeam) { pokemon1Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon1Values); pokemon1Id = pokemon1Uri.getLastPathSegment(); } else { // TODO } ContentValues pokemon2Values = new ContentValues(); pokemon2Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon2SpeciesId()); pokemon2Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon2AbilityId()); pokemon2Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon2ItemId()); pokemon2Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon2NatureId()); pokemon2Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon2Move1Id()); pokemon2Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon2Move2Id()); pokemon2Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon2Move3Id()); pokemon2Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon2Move4Id()); pokemon2Values.put(PlannedKeyValues.IV_HP, event.getPokemon2IvHp()); pokemon2Values.put(PlannedKeyValues.IV_ATT, event.getPokemon2IvAtt()); pokemon2Values.put(PlannedKeyValues.IV_DEF, event.getPokemon2IvDef()); pokemon2Values.put(PlannedKeyValues.IV_SATT, event.getPokemon2IvSAtt()); pokemon2Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon2IvSDef()); pokemon2Values.put(PlannedKeyValues.IV_SPD, event.getPokemon2IvSpd()); pokemon2Values.put(PlannedKeyValues.EV_HP, event.getPokemon2EvHp()); pokemon2Values.put(PlannedKeyValues.EV_ATT, event.getPokemon2EvAtt()); pokemon2Values.put(PlannedKeyValues.EV_DEF, event.getPokemon2EvDef()); pokemon2Values.put(PlannedKeyValues.EV_SATT, event.getPokemon2EvSAtt()); pokemon2Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon2EvSDef()); pokemon2Values.put(PlannedKeyValues.EV_SPD, event.getPokemon2EvSpd()); pokemon2Values.put(PlannedKeyValues.NOTE, event.getPokemon2Notes()); Uri pokemon2Uri; String pokemon2Id = ""; if (addingTeam) { pokemon2Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon2Values); pokemon2Id = pokemon2Uri.getLastPathSegment(); } else { // TODO } ContentValues pokemon3Values = new ContentValues(); pokemon3Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon3SpeciesId()); pokemon3Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon3AbilityId()); pokemon3Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon3ItemId()); pokemon3Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon3NatureId()); pokemon3Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon3Move1Id()); pokemon3Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon3Move2Id()); pokemon3Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon3Move3Id()); pokemon3Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon3Move4Id()); pokemon3Values.put(PlannedKeyValues.IV_HP, event.getPokemon3IvHp()); pokemon3Values.put(PlannedKeyValues.IV_ATT, event.getPokemon3IvAtt()); pokemon3Values.put(PlannedKeyValues.IV_DEF, event.getPokemon3IvDef()); pokemon3Values.put(PlannedKeyValues.IV_SATT, event.getPokemon3IvSAtt()); pokemon3Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon3IvSDef()); pokemon3Values.put(PlannedKeyValues.IV_SPD, event.getPokemon3IvSpd()); pokemon3Values.put(PlannedKeyValues.EV_HP, event.getPokemon3EvHp()); pokemon3Values.put(PlannedKeyValues.EV_ATT, event.getPokemon3EvAtt()); pokemon3Values.put(PlannedKeyValues.EV_DEF, event.getPokemon3EvDef()); pokemon3Values.put(PlannedKeyValues.EV_SATT, event.getPokemon3EvSAtt()); pokemon3Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon3EvSDef()); pokemon3Values.put(PlannedKeyValues.EV_SPD, event.getPokemon3EvSpd()); pokemon3Values.put(PlannedKeyValues.NOTE, event.getPokemon3Notes()); Uri pokemon3Uri; String pokemon3Id = ""; if (addingTeam) { pokemon3Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon3Values); pokemon3Id = pokemon3Uri.getLastPathSegment(); } else { // TODO } ContentValues pokemon4Values = new ContentValues(); pokemon4Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon4SpeciesId()); pokemon4Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon4AbilityId()); pokemon4Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon4ItemId()); pokemon4Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon4NatureId()); pokemon4Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon4Move1Id()); pokemon4Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon4Move2Id()); pokemon4Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon4Move3Id()); pokemon4Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon4Move4Id()); pokemon4Values.put(PlannedKeyValues.IV_HP, event.getPokemon4IvHp()); pokemon4Values.put(PlannedKeyValues.IV_ATT, event.getPokemon4IvAtt()); pokemon4Values.put(PlannedKeyValues.IV_DEF, event.getPokemon4IvDef()); pokemon4Values.put(PlannedKeyValues.IV_SATT, event.getPokemon4IvSAtt()); pokemon4Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon4IvSDef()); pokemon4Values.put(PlannedKeyValues.IV_SPD, event.getPokemon4IvSpd()); pokemon4Values.put(PlannedKeyValues.EV_HP, event.getPokemon4EvHp()); pokemon4Values.put(PlannedKeyValues.EV_ATT, event.getPokemon4EvAtt()); pokemon4Values.put(PlannedKeyValues.EV_DEF, event.getPokemon4EvDef()); pokemon4Values.put(PlannedKeyValues.EV_SATT, event.getPokemon4EvSAtt()); pokemon4Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon4EvSDef()); pokemon4Values.put(PlannedKeyValues.EV_SPD, event.getPokemon4EvSpd()); pokemon4Values.put(PlannedKeyValues.NOTE, event.getPokemon4Notes()); Uri pokemon4Uri; String pokemon4Id = ""; if (addingTeam) { pokemon4Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon4Values); pokemon4Id = pokemon4Uri.getLastPathSegment(); } else { // TODO } ContentValues pokemon5Values = new ContentValues(); pokemon5Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon5SpeciesId()); pokemon5Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon5AbilityId()); pokemon5Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon5ItemId()); pokemon5Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon5NatureId()); pokemon5Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon5Move1Id()); pokemon5Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon5Move2Id()); pokemon5Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon5Move3Id()); pokemon5Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon5Move4Id()); pokemon5Values.put(PlannedKeyValues.IV_HP, event.getPokemon5IvHp()); pokemon5Values.put(PlannedKeyValues.IV_ATT, event.getPokemon5IvAtt()); pokemon5Values.put(PlannedKeyValues.IV_DEF, event.getPokemon5IvDef()); pokemon5Values.put(PlannedKeyValues.IV_SATT, event.getPokemon5IvSAtt()); pokemon5Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon5IvSDef()); pokemon5Values.put(PlannedKeyValues.IV_SPD, event.getPokemon5IvSpd()); pokemon5Values.put(PlannedKeyValues.EV_HP, event.getPokemon5EvHp()); pokemon5Values.put(PlannedKeyValues.EV_ATT, event.getPokemon5EvAtt()); pokemon5Values.put(PlannedKeyValues.EV_DEF, event.getPokemon5EvDef()); pokemon5Values.put(PlannedKeyValues.EV_SATT, event.getPokemon5EvSAtt()); pokemon5Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon5EvSDef()); pokemon5Values.put(PlannedKeyValues.EV_SPD, event.getPokemon5EvSpd()); pokemon5Values.put(PlannedKeyValues.NOTE, event.getPokemon5Notes()); Uri pokemon5Uri; String pokemon5Id = ""; if (addingTeam) { pokemon5Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon5Values); pokemon5Id = pokemon5Uri.getLastPathSegment(); } else { // TODO } ContentValues pokemon6Values = new ContentValues(); pokemon6Values.put(PlannedKeyValues.POKEMON_ID, event.getPokemon6SpeciesId()); pokemon6Values.put(PlannedKeyValues.ABILITY_ID, event.getPokemon6AbilityId()); pokemon6Values.put(PlannedKeyValues.ITEM_ID, event.getPokemon6ItemId()); pokemon6Values.put(PlannedKeyValues.NATURE_ID, event.getPokemon6NatureId()); pokemon6Values.put(PlannedKeyValues.MOVE1_ID, event.getPokemon6Move1Id()); pokemon6Values.put(PlannedKeyValues.MOVE2_ID, event.getPokemon6Move2Id()); pokemon6Values.put(PlannedKeyValues.MOVE3_ID, event.getPokemon6Move3Id()); pokemon6Values.put(PlannedKeyValues.MOVE4_ID, event.getPokemon6Move4Id()); pokemon6Values.put(PlannedKeyValues.IV_HP, event.getPokemon6IvHp()); pokemon6Values.put(PlannedKeyValues.IV_ATT, event.getPokemon6IvAtt()); pokemon6Values.put(PlannedKeyValues.IV_DEF, event.getPokemon6IvDef()); pokemon6Values.put(PlannedKeyValues.IV_SATT, event.getPokemon6IvSAtt()); pokemon6Values.put(PlannedKeyValues.IV_SDEF, event.getPokemon6IvSDef()); pokemon6Values.put(PlannedKeyValues.IV_SPD, event.getPokemon6IvSpd()); pokemon6Values.put(PlannedKeyValues.EV_HP, event.getPokemon6EvHp()); pokemon6Values.put(PlannedKeyValues.EV_ATT, event.getPokemon6EvAtt()); pokemon6Values.put(PlannedKeyValues.EV_DEF, event.getPokemon6EvDef()); pokemon6Values.put(PlannedKeyValues.EV_SATT, event.getPokemon6EvSAtt()); pokemon6Values.put(PlannedKeyValues.EV_SDEF, event.getPokemon6EvSDef()); pokemon6Values.put(PlannedKeyValues.EV_SPD, event.getPokemon6EvSpd()); pokemon6Values.put(PlannedKeyValues.NOTE, event.getPokemon6Notes()); Uri pokemon6Uri; String pokemon6Id = ""; if (addingTeam) { pokemon6Uri = getContentResolver().insert(TinapaContentProvider.PLANNED_POKEMON_URI, pokemon6Values); pokemon6Id = pokemon6Uri.getLastPathSegment(); } else { // TODO } teamValues.put(TeamKeyValues.POKEMON1_PLANNED_ID, pokemon1Id); teamValues.put(TeamKeyValues.POKEMON2_PLANNED_ID, pokemon2Id); teamValues.put(TeamKeyValues.POKEMON3_PLANNED_ID, pokemon3Id); teamValues.put(TeamKeyValues.POKEMON4_PLANNED_ID, pokemon4Id); teamValues.put(TeamKeyValues.POKEMON5_PLANNED_ID, pokemon5Id); teamValues.put(TeamKeyValues.POKEMON6_PLANNED_ID, pokemon6Id); if (addingTeam) { getContentResolver().insert(TinapaContentProvider.PLANNED_TEAM_URI, teamValues); } else { // TODO Update } } @Subscribe public void teamListSelected(TeamListSelectedEvent event) { String teamId = event.getTeamId(); FrameLayout fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment2); if (fragmentView == null) { fragmentView = (FrameLayout) findViewById(R.id.mainActivityFragment1); } FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(fragmentView.getId(), TeamAddDialogFragment.newInstance(teamId), TEAM_DETAILS_FRAGMENT); ft.addToBackStack("TeamDetails"); ft.commit(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); ActionBar actionBar = getActionBar(); if (actionBar != null) { outState.putInt(SAVE_STATE_SELECTED_TAB_INDEX, actionBar.getSelectedNavigationIndex()); } else { Log.e(TAG, "ActionBar is null for some reason."); } } private static class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment mFragment; private final String mTag; public TabListener(String tag, Fragment fragment) { this.mTag = tag; this.mFragment = fragment; } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { ft.replace(R.id.mainActivityFragment1, mFragment, mTag); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // TODO: Probably not needed. ft.remove(mFragment); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // Do nothing. } } }
{ "content_hash": "416cf28118ca7db2bfddfba9fe6c3452", "timestamp": "", "source": "github", "line_count": 651, "max_line_length": 390, "avg_line_length": 52.40706605222734, "alnum_prop": 0.7082979159949585, "repo_name": "DJ0Hybrid/TINAPA", "id": "5065df19be05188a4fa565b4f78ada7a5923ef72", "size": "34117", "binary": false, "copies": "1", "ref": "refs/heads/feature/development", "path": "TINAPA/src/main/java/com/tinapaproject/tinapa/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "303630" }, { "name": "Ruby", "bytes": "2906" } ], "symlink_target": "" }
jQuery Plugin Starter === This is my starter structure for a generic *jQuery plugin*. It makes use of several technologies as described below. ###Use: In every file you'll see a piece of commented code. That's the instructions for each file. In others you'll see *UPPERCASED-WORDS* and those one you should change to fit your needs like the name of the plugin, version, your GitHub user, the repository URL and so. Files should be new names too (*your-jquery-plugin-name.js*) and they're commanded in `Gruntfile.js` so change names there there too, it's clearly identified. demo -- Folder that holds the demo for this plugin. The basic files are: - **index.html**: the demo page - **css/style.css**: gives CSS styles to the demo page. Now it is a plain .css but you can add your pre-processor of choice. - **images**: If you need add images to your demo, otherwise just delete this folder. - **js/**: In case you need libraries/plugins you should add them here (for example, jquery.min.js). dist -- Files that are ready for production, minified and packed versions. The minified one is called directly from `demo/index.html`. - **your-jquery-plugin-name.js** *(&#9888; rename this)* - **your-jquery-plugin-name.min.js** *(&#9888; rename this)* src -- Your plugin as you code it and fully commented. Then this file will be added to a workflow and prepared for production. - **your-jquery-plugin-name.js** *(&#9888; rename this)* your-jquery-plugin-name.json -- This JSON file holds many configuration texts, basically to identify your plugin and generate the final files. *(&#9888; rename this and look inside)* Gruntfile.js -- File that commands **GruntJS** tasks and take care of several behaviors: - **meta**: add a commented piece of text in the top of the generated JS files. - **concat**: combine JS files. *(&#9888; change name here)* - **jshint**: looks for improvements in the JS code. *(&#9888; hange name here)* - **uglify**: minify code to a **.min.js** file. *(&#9888; change name here)* - **watch**: using [Livereload](https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei) watch for changes in HTML/JS files and reload the browser if there is any. There are 2 main tasks: > **default**: concats and minifies the file, from `/src` to `/dist`. *Use*: $ grunt or: $ grunt watch > **testjs**: very helpful, run this one everytime you think you have a working demo. It looks for errors and improvements in your jQuery code and shows suggestions. *Use*: $ grunt testjs package.json -- Take care of the **NodeJS** packages needed by **GruntJS**, as decribed before. You can install them using: $ npm install and if you need more (for example a CSS pre-processor to write your demo) just add them using: $ npm install grunt-libraryname --save-dev The basic ones are: - grunt - grunt-cli - grunt-contrib-concat - grunt-contrib-jshint - grunt-contrib-uglify - grunt-contrib-watch README.MD -- This file, you should overwrite it and document your own plugin. LICENSE -- I use [MIT](http://opensource.org/licenses/MIT) by default, but it's up to you. Any piece of working code should have a license. [Choose one](http://en.wikipedia.org/wiki/Comparison_of_free_and_open-source_software_licenses#General_comparison).
{ "content_hash": "c673ade680c4a6d8cd1945dad6335e4b", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 264, "avg_line_length": 33.66326530612245, "alnum_prop": 0.7305244013337375, "repo_name": "juanbrujo/jquery-plugin-starter", "id": "4278b578a4039ea442df14a826f062e80b116637", "size": "3299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "45" }, { "name": "HTML", "bytes": "602" }, { "name": "JavaScript", "bytes": "2033" } ], "symlink_target": "" }
<?php namespace Magento\Framework\App\Test\Unit\Config\Initial; use Magento\Framework\Filesystem; class ReaderTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ protected $objectManager; /** * @var \Magento\Framework\App\Config\Initial\Reader */ protected $model; /** * @var \Magento\Framework\Config\FileResolverInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $fileResolverMock; /** * @var \Magento\Framework\App\Config\Initial\Converter|\PHPUnit_Framework_MockObject_MockObject */ protected $converterMock; /** * @var string */ protected $filePath; /** * @var \Magento\Framework\Config\ValidationStateInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $validationStateMock; /** * @var \Magento\Framework\App\Config\Initial\SchemaLocator|\PHPUnit_Framework_MockObject_MockObject */ protected $schemaLocatorMock; /** * @var \Magento\Framework\Config\DomFactory|\PHPUnit_Framework_MockObject_MockObject */ protected $domFactoryMock; protected function setUp() { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->filePath = __DIR__ . '/_files/'; $this->fileResolverMock = $this->getMock('Magento\Framework\Config\FileResolverInterface'); $this->converterMock = $this->getMock('Magento\Framework\App\Config\Initial\Converter'); $this->schemaLocatorMock = $this->getMock( 'Magento\Framework\App\Config\Initial\SchemaLocator', [], [], '', false ); $this->validationStateMock = $this->getMock('Magento\Framework\Config\ValidationStateInterface'); $this->validationStateMock->expects($this->any()) ->method('isValidationRequired') ->will($this->returnValue(true)); $this->domFactoryMock = $this->getMock('Magento\Framework\Config\DomFactory', [], [], '', false); } public function testConstructor() { $this->createModelAndVerifyConstructor(); } /** * @covers \Magento\Framework\App\Config\Initial\Reader::read */ public function testReadNoFiles() { $this->createModelAndVerifyConstructor(); $this->fileResolverMock->expects($this->at(0)) ->method('get') ->with('config.xml', 'global') ->will($this->returnValue([])); $this->assertEquals([], $this->model->read()); } /** * @covers \Magento\Framework\App\Config\Initial\Reader::read */ public function testReadValidConfig() { $this->createModelAndVerifyConstructor(); $this->prepareDomFactoryMock(); $testXmlFilesList = [ file_get_contents($this->filePath . 'initial_config1.xml'), file_get_contents($this->filePath . 'initial_config2.xml'), ]; $expectedConfig = ['data' => [], 'metadata' => []]; $this->fileResolverMock->expects($this->at(0)) ->method('get') ->with('config.xml', 'global') ->will($this->returnValue($testXmlFilesList)); $this->converterMock->expects($this->once()) ->method('convert') ->with($this->anything()) ->will($this->returnValue($expectedConfig)); $this->assertEquals($expectedConfig, $this->model->read()); } private function prepareDomFactoryMock() { $validationStateMock = $this->validationStateMock; $this->domFactoryMock->expects($this->once()) ->method('createDom') ->willReturnCallback( function ($arguments) use ($validationStateMock) { return new \Magento\Framework\Config\Dom( $arguments['xml'], $validationStateMock, [], null, $arguments['schemaFile'] ); } ); } /** * @covers \Magento\Framework\App\Config\Initial\Reader::read * @expectedException \Magento\Framework\Exception\LocalizedException * @expectedExceptionMessageRegExp /Invalid XML in file \w+/ */ public function testReadInvalidConfig() { $this->createModelAndVerifyConstructor(); $this->prepareDomFactoryMock(); $testXmlFilesList = [ file_get_contents($this->filePath . 'invalid_config.xml'), file_get_contents($this->filePath . 'initial_config2.xml'), ]; $expectedConfig = ['data' => [], 'metadata' => []]; $this->fileResolverMock->expects($this->at(0)) ->method('get') ->with('config.xml', 'global') ->will($this->returnValue($testXmlFilesList)); $this->converterMock->expects($this->never()) ->method('convert') ->with($this->anything()) ->will($this->returnValue($expectedConfig)); $this->model->read(); } private function createModelAndVerifyConstructor() { $schemaFile = $this->filePath . 'config.xsd'; $this->schemaLocatorMock->expects($this->once())->method('getSchema')->will($this->returnValue($schemaFile)); $this->model = $this->objectManager->getObject( 'Magento\Framework\App\Config\Initial\Reader', [ 'fileResolver' => $this->fileResolverMock, 'converter' => $this->converterMock, 'schemaLocator' => $this->schemaLocatorMock, 'domFactory' => $this->domFactoryMock ] ); } }
{ "content_hash": "8064ad4b3c43e6499fd9337970d432ea", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 117, "avg_line_length": 33.69491525423729, "alnum_prop": 0.5841716968477532, "repo_name": "j-froehlich/magento2_wk", "id": "f2a0638e958f310af293e62e785e8528424809a4", "size": "6072", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/framework/App/Test/Unit/Config/Initial/ReaderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
package org.apache.lens.cli; import static org.testng.Assert.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.*; import javax.ws.rs.BadRequestException; import javax.xml.datatype.DatatypeFactory; import org.apache.lens.api.APIResult; import org.apache.lens.api.metastore.*; import org.apache.lens.api.query.QueryHandle; import org.apache.lens.api.query.QueryStatus; import org.apache.lens.cli.commands.LensCubeCommands; import org.apache.lens.cli.commands.LensQueryCommands; import org.apache.lens.client.LensClient; import org.apache.lens.driver.hive.TestHiveDriver; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.Path; import org.testng.annotations.Test; import lombok.extern.slf4j.Slf4j; /** * The Class TestLensQueryCommands. */ @Slf4j public class TestLensQueryCommands extends LensCliApplicationTest { /** The client. */ private LensClient client; /** The explain plan. */ private static String explainPlan = "TOK_QUERY\n" + " TOK_FROM\n" + " TOK_TABREF\n" + " TOK_TABNAME\n" + " local_dim_table\n" + " test_dim\n" + " TOK_INSERT\n" + " TOK_DESTINATION\n" + " TOK_DIR\n" + " TOK_TMP_FILE\n" + " TOK_SELECT\n" + " TOK_SELEXPR\n" + " .\n" + " TOK_TABLE_OR_COL\n" + " test_dim\n" + " id\n" + " TOK_SELEXPR\n" + " .\n" + " TOK_TABLE_OR_COL\n" + " test_dim\n" + " name\n" + " TOK_WHERE\n" + " =\n" + " .\n" + " TOK_TABLE_OR_COL\n" + " test_dim\n" + " dt\n" + " 'latest'"; private File resDir; /** * Test query commands. * * @throws Exception the exception */ @Test public void testQueryCommands() throws Exception { client = new LensClient(); client.setConnectionParam("lens.query.enable.persistent.resultset.indriver", "false"); setup(client); LensQueryCommands qCom = new LensQueryCommands(); qCom.setClient(client); resDir = new File("target/results"); assertTrue(resDir.exists() || resDir.mkdirs()); testExecuteSyncQuery(qCom); testExecuteAsyncQuery(qCom); testSyncResults(qCom); testExplainQuery(qCom); testExplainFailQuery(qCom); testPreparedQuery(qCom); testShowPersistentResultSet(qCom); testPurgedFinishedResultSet(qCom); testFailPreparedQuery(qCom); // run all query commands with query metrics enabled. client = new LensClient(); client.setConnectionParam("lens.query.enable.persistent.resultset.indriver", "false"); client.setConnectionParam("lens.query.enable.metrics.per.query", "true"); qCom.setClient(client); String result = qCom.getAllPreparedQueries("all", "", -1, -1); assertEquals(result, "No prepared queries"); testExecuteSyncQuery(qCom); testExecuteAsyncQuery(qCom); testSyncResults(qCom); testExplainQuery(qCom); testExplainFailQuery(qCom); testPreparedQuery(qCom); testShowPersistentResultSet(qCom); testPurgedFinishedResultSet(qCom); testFailPreparedQuery(qCom); } /** * Test prepared query. * * @param qCom the q com * @throws Exception the exception */ private void testPreparedQuery(LensQueryCommands qCom) throws Exception { long submitTime = System.currentTimeMillis(); String sql = "cube select id, name from test_dim"; String result = qCom.getAllPreparedQueries("testPreparedName", "all", submitTime, Long.MAX_VALUE); assertEquals(result, "No prepared queries"); final String qh = qCom.prepare(sql, "testPreparedName"); result = qCom.getAllPreparedQueries("testPreparedName", "all", submitTime, System.currentTimeMillis()); assertEquals(qh, result); result = qCom.getPreparedStatus(qh); assertTrue(result.contains("User query:cube select id, name from test_dim")); assertTrue(result.contains(qh)); result = qCom.executePreparedQuery(qh, false, "testPrepQuery1"); log.warn("XXXXXX Prepared query sync result is " + result); assertTrue(result.contains("1\tfirst")); String handle = qCom.executePreparedQuery(qh, true, "testPrepQuery2"); log.debug("Perpared query handle is " + handle); while (!client.getQueryStatus(handle).finished()) { Thread.sleep(5000); } String status = qCom.getStatus(handle); log.debug("Prepared Query Status is " + status); assertTrue(status.contains("Status : SUCCESSFUL")); result = qCom.getQueryResults(handle, null, true); log.debug("Prepared Query Result is " + result); assertTrue(result.contains("1\tfirst")); // Fetch again. result = qCom.getQueryResults(handle, null, true); log.debug("Prepared Query Result is " + result); assertTrue(result.contains("1\tfirst")); result = qCom.destroyPreparedQuery(qh); log.debug("destroy result is " + result); assertEquals("Successfully destroyed " + qh, result); result = qCom.getAllPreparedQueries("testPreparedName", "all", submitTime, Long.MAX_VALUE); assertEquals(result, "No prepared queries"); final String qh2 = qCom.explainAndPrepare(sql, "testPrepQuery3"); assertTrue(qh2.contains(explainPlan)); String handles = qCom.getAllPreparedQueries("testPrepQuery3", "all", -1, Long.MAX_VALUE); assertFalse(handles.contains("No prepared queries"), handles); String handles2 = qCom.getAllPreparedQueries("testPrepQuery3", "all", -1, submitTime - 1); assertFalse(handles2.contains(qh), handles2); result = qCom.destroyPreparedQuery(handles); assertEquals("Successfully destroyed " + handles, result); } /** * Test fail prepared query. * * @param qCom the q com * @throws Exception the exception */ private void testFailPreparedQuery(LensQueryCommands qCom) throws Exception { client = new LensClient(); client.setConnectionParam("hive.exec.driver.run.hooks", TestHiveDriver.FailHook.class.getCanonicalName()); qCom.setClient(client); String sql = "cube select id, name from test_dim"; final String result = qCom.explainAndPrepare(sql, "testFailPrepared"); assertTrue(result.contains("Explain FAILED:Error while processing statement: FAILED: Hive Internal Error:" + " java.lang.ClassNotFoundException(org.apache.lens.driver.hive.TestHiveDriver.FailHook)")); } /** * Test explain query. * * @param qCom the q com * @throws Exception the exception */ private void testExplainQuery(LensQueryCommands qCom) throws Exception { String sql = "cube select id, name from test_dim"; String result = qCom.explainQuery(sql, null); log.debug(result); assertTrue(result.contains(explainPlan)); } /** * Test explain fail query. * * @param qCom the q com * @throws Exception the exception */ private void testExplainFailQuery(LensQueryCommands qCom) throws Exception { String sql = "cube select id2, name from test_dim"; String result = qCom.explainQuery(sql, null); log.debug(result); assertTrue(result.contains("Explain FAILED:")); result = qCom.explainAndPrepare(sql, ""); assertTrue(result.contains("Explain FAILED:")); } /** * Test execute async query. * * @param qCom the q com * @throws Exception the exception */ private void testExecuteAsyncQuery(LensQueryCommands qCom) throws Exception { System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); String sql = "cube select id,name from test_dim"; long submitTime = System.currentTimeMillis(); String qh = qCom.executeQuery(sql, true, "testQuery1"); String user = qCom.getClient().getLensStatement(new QueryHandle(UUID.fromString(qh))) .getQuery().getSubmittedUser(); String result = qCom.getAllQueries("", "testQuery1", user, -1, Long.MAX_VALUE); // this is because previous query has run two query handle will be there assertTrue(result.contains(qh), result); assertTrue(result.contains("Total number of queries")); String[] resultSplits = result.split("\n"); // assert on the number of queries assertEquals(String.valueOf(resultSplits.length - 1), resultSplits[resultSplits.length - 1].split(": ")[1]); QueryStatus queryStatus = client.getQueryStatus(qh); while (!queryStatus.finished()) { if (queryStatus.launched()) { String details = qCom.getDetails(qh); assertTrue(details.contains("driverQuery")); } Thread.sleep(1000); queryStatus = client.getQueryStatus(qh); } // Check that query name searching is 'ilike' String result2 = qCom.getAllQueries("", "query", "all", -1, Long.MAX_VALUE); assertTrue(result2.contains(qh), result2); assertTrue(qCom.getStatus(qh).contains("Status : SUCCESSFUL")); String details = qCom.getDetails(qh); assertTrue(details.contains("driverQuery")); result = qCom.getQueryResults(qh, null, true); assertTrue(result.contains("1\tfirst")); downloadResult(qCom, qh, result); // re-download should also succeed downloadResult(qCom, qh, result); // Kill query is not tested as there is no deterministic way of killing a query result = qCom.getAllQueries("SUCCESSFUL", "", "all", -1, Long.MAX_VALUE); assertTrue(result.contains(qh), result); result = qCom.getAllQueries("FAILED", "", "all", -1, Long.MAX_VALUE); if (!result.contains("No queries")) { // Make sure valid query handles are returned String[] handles = StringUtils.split(result, "\n"); for (String handle : handles) { if (!handle.contains("Total number of queries")) { QueryHandle.fromString(handle.trim()); } } } String queryName = client.getLensStatement(new QueryHandle(UUID.fromString(qh))).getQuery().getQueryName(); assertTrue("testQuery1".equalsIgnoreCase(queryName), queryName); result = qCom.getAllQueries("", "", "", submitTime, System.currentTimeMillis()); assertTrue(result.contains(qh), result); result = qCom.getAllQueries("", "fooBar", "all", submitTime, System.currentTimeMillis()); assertTrue(result.contains("No queries"), result); result = qCom.getAllQueries("SUCCESSFUL", "", "all", submitTime, System.currentTimeMillis()); assertTrue(result.contains(qh)); result = qCom.getAllQueries("SUCCESSFUL", "", "all", submitTime - 5000, submitTime - 1); // should not give query since its not in the range assertFalse(result.contains(qh)); try { // Should fail with bad request since fromDate > toDate result = qCom.getAllQueries("SUCCESSFUL", "", "all", submitTime + 5000, submitTime); fail("Call should have failed with BadRequestException, instead got " + result); } catch (BadRequestException exc) { // pass } System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); } private void downloadResult(LensQueryCommands qCom, String qh, String expected) throws IOException { assertTrue(qCom.getQueryResults(qh, resDir, true).contains("Saved")); assertEquals(readFile(resDir.getAbsolutePath() + File.separator + qh + ".csv").trim(), expected.trim()); } private String readFile(String path) throws FileNotFoundException { return new Scanner(new File(path)).useDelimiter("\\Z").next(); } /** * Sets the up. * * @param client the new up * @throws Exception the exception */ public void setup(LensClient client) throws Exception { LensCubeCommands command = new LensCubeCommands(); command.setClient(client); log.debug("Starting to test cube commands"); URL cubeSpec = TestLensQueryCommands.class.getClassLoader().getResource("sample-cube.xml"); command.createCube(new File(cubeSpec.toURI())); TestLensDimensionCommands.createDimension(); TestLensDimensionTableCommands.addDim1Table("dim_table", "dim_table.xml", "local"); // Add partition URL dataDir = TestLensQueryCommands.class.getClassLoader().getResource("dim2-part"); XPartition xp = new XPartition(); xp.setFactOrDimensionTableName("dim_table"); xp.setLocation(new Path(dataDir.toURI()).toString()); xp.setUpdatePeriod(XUpdatePeriod.HOURLY); XTimePartSpec timePart = new XTimePartSpec(); XTimePartSpecElement partElement = new XTimePartSpecElement(); partElement.setKey("dt"); partElement.setValue(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar())); timePart.getPartSpecElement().add(partElement); xp.setTimePartitionSpec(timePart); APIResult result = client.addPartitionToDim("dim_table", "local", xp); assertEquals(result.getStatus(), APIResult.Status.SUCCEEDED); } /** * Test execute sync query. * * @param qCom the q com */ private void testExecuteSyncQuery(LensQueryCommands qCom) { String sql = "cube select id,name from test_dim"; String result = qCom.executeQuery(sql, false, "testQuery2"); assertTrue(result.contains("1\tfirst"), result); } /** * Test show persistent result set. * * @param qCom the q com * @throws Exception the exception */ private void testShowPersistentResultSet(LensQueryCommands qCom) throws Exception { System.out.println("@@PERSISTENT_RESULT_TEST-------------"); client.setConnectionParam("lens.query.enable.persistent.resultset.indriver", "true"); String query = "cube select id,name from test_dim"; try { String result = qCom.executeQuery(query, false, "testQuery3"); System.out.println("@@ RESULT " + result); assertNotNull(result); assertFalse(result.contains("Failed to get resultset")); } catch (Exception exc) { log.error("Exception not expected while getting resultset.", exc); fail("Exception not expected: " + exc.getMessage()); } System.out.println("@@END_PERSISTENT_RESULT_TEST-------------"); } /** * Test execute sync results. * * @param qCom the q com */ private void testSyncResults(LensQueryCommands qCom) { String sql = "cube select id,name from test_dim"; String qh = qCom.executeQuery(sql, true, "testQuery4"); String result = qCom.getQueryResults(qh, null, false); assertTrue(result.contains("1\tfirst"), result); } /** * Test purged finished result set. * * @param qCom the q com */ private void testPurgedFinishedResultSet(LensQueryCommands qCom) { System.out.println("@@START_FINISHED_PURGED_RESULT_TEST-------------"); client.setConnectionParam("lens.server.max.finished.queries", "0"); client.setConnectionParam("lens.query.enable.persistent.resultset", "true"); String query = "cube select id,name from test_dim"; try { String qh = qCom.executeQuery(query, true, "testQuery"); while (!client.getQueryStatus(qh).finished()) { Thread.sleep(5000); } assertTrue(qCom.getStatus(qh).contains("Status : SUCCESSFUL")); String result = qCom.getQueryResults(qh, null, true); System.out.println("@@ RESULT " + result); assertNotNull(result); // This is to check for positive processing time assertFalse(result.contains("(-")); } catch (Exception exc) { log.error("Exception not expected while purging resultset.", exc); fail("Exception not expected: " + exc.getMessage()); } System.out.println("@@END_FINISHED_PURGED_RESULT_TEST-------------"); } }
{ "content_hash": "4b7a5bdf90177e9cbe70ad876c1580ad", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 119, "avg_line_length": 38.383663366336634, "alnum_prop": 0.6740826723415232, "repo_name": "Flipkart/incubator-lens", "id": "7a437a1239a541f975faeeb10fdf3609dc956b4c", "size": "16315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lens-cli/src/test/java/org/apache/lens/cli/TestLensQueryCommands.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "10377" }, { "name": "Java", "bytes": "4402254" }, { "name": "JavaScript", "bytes": "282078" }, { "name": "Shell", "bytes": "14027" } ], "symlink_target": "" }
package com.github.nest.arcteryx.validation.oval; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Car { @NotNull private String manufacturer; @NotNull @Size(min = 2, max = 14) private String licensePlate; @Min(2) private int seatCount; public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } // getters and setters ... public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getLicensePlate() { return licensePlate; } public void setLicensePlate(String licensePlate) { this.licensePlate = licensePlate; } public int getSeatCount() { return seatCount; } public void setSeatCount(int seatCount) { this.seatCount = seatCount; } }
{ "content_hash": "9c72845460f7a07f87154f725690e0f5", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 70, "avg_line_length": 20.333333333333332, "alnum_prop": 0.7155255544840887, "repo_name": "bradwoo8621/nest-old", "id": "08ea07aec7e5fe3a63383ac803c570f53b3fb4f9", "size": "1037", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "arcteryx-validation-oval/src/test/java/com/github/nest/arcteryx/validation/oval/Car.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2434" }, { "name": "Java", "bytes": "1314670" }, { "name": "JavaScript", "bytes": "59671" } ], "symlink_target": "" }
namespace blink { // The "appeal" of a breakpoint. Higher is better. The perfect appeal is when // we're not violating any rules. As we violate rule after rule, appeal will // decrease. When figuring out where to break, a layout algorithm will use the // breakpoint with the highest appeal (first priority) that has progressed the // furthest through the content (second priority). The list here is sorted by // rule violation severity, i.e. reverse appeal. enum NGBreakAppeal { // We're attempting to break at a really undesirable place. This is not a // valid class A, B or C breakpoint [1]. The only requirement we're satisfying // is to not slice monolithic content. // // [1] https://www.w3.org/TR/css-break-3/#possible-breaks kBreakAppealLastResort, // The worst thing we're violating is an avoid* value of break-before, // break-after, or break-inside. kBreakAppealViolatingBreakAvoid, // The only thing we're violating is orphans and/or widows requirements. kBreakAppealViolatingOrphansAndWidows, // We're not violating anything. This is a perfect break location. Note that // forced breaks are always perfect, since they trump everything else. kBreakAppealPerfect, }; // Keep this one in sync with the above enum. const int kNGBreakAppealBitsNeeded = 2; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BREAK_APPEAL_H_
{ "content_hash": "90401bfeb621d776b78ece9f575e77ea", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 80, "avg_line_length": 40.94117647058823, "alnum_prop": 0.7471264367816092, "repo_name": "chromium/chromium", "id": "b4d2717c2229bef7d63304bfe4a8583734b37de5", "size": "1675", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "third_party/blink/renderer/core/layout/ng/ng_break_appeal.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package no.ssb.vtl.script; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import no.ssb.vtl.connectors.Connector; import no.ssb.vtl.model.Component; import no.ssb.vtl.model.DataPoint; import no.ssb.vtl.model.DataStructure; import no.ssb.vtl.model.Dataset; import no.ssb.vtl.model.StaticDataset; import no.ssb.vtl.model.VTLObject; import no.ssb.vtl.model.VtlOrdering; import no.ssb.vtl.parser.VTLLexer; import no.ssb.vtl.script.support.VTLPrintStream; import org.antlr.v4.runtime.Vocabulary; import org.apache.maven.artifact.versioning.ComparableVersion; import org.junit.Test; import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptException; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static no.ssb.vtl.model.Component.Role; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class VTLScriptEngineTest { private Dataset dataset = mock(Dataset.class); private Connector connector = mock(Connector.class); private ScriptEngine engine = new VTLScriptEngine(connector); private Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); @Test public void testKeywords() { Map<String, Set<String>> keywords = ((VTLScriptEngine) engine).getVTLKeywords(); Set<String> keywordsList = keywords.values() .stream() .flatMap(Collection::stream) .collect(Collectors.toSet()); Set<String> keywordsFromLexer = IntStream.range(0, VTLLexer.VOCABULARY.getMaxTokenType()) .mapToObj(VTLLexer.VOCABULARY::getLiteralName) .filter(Objects::nonNull) .map(s -> s.replaceAll("'", "")) .collect(Collectors.toSet()); Sets.SetView<String> symmetricDifference = Sets.symmetricDifference(keywordsList, keywordsFromLexer); System.out.println("Missing in keywords: " + Sets.difference(keywordsFromLexer, keywordsList)); System.out.println("Missing in lexer: " + Sets.difference(keywordsList, keywordsFromLexer)); // Will fail if a new keyword is added in the grammar or list of keywords without updating // the test. assertThat(symmetricDifference).containsExactlyInAnyOrder( "time_aggregate", "exists_in_all", "match_characters", "timeshift", "join", "flow_to_stock", "identifier", "string_from_date", "subscript", "transcode", "setdiff", "current_date", "measure", "extract", "eval", "concatenation", "unique", "true", "exists_in", "func_dep", "symdiff", "attribute", "fill_time_series", "intersect", "not_exists_in_all", "false", "any", "lenght", "stock_to_flow", "not_exists_in", "aggregatefunctions", "alterdataset", "||", "<=", "<>", "measures", "(", ")", "*", "+", ",", "-", ".", "/", "condition", "not_valid", ":", "<", "=", ">", ">=", "implicit", ":=", "role", "errorlevel", "valid", "[", "]", "errorcode", "prod", "length", "{", "}" ); Vocabulary vocabulary = VTLLexer.VOCABULARY; for (int i = 0; i < vocabulary.getMaxTokenType(); i++) { System.out.printf( "[%s] litName: %s, symName: %s, dispName:%s\n", i, vocabulary.getLiteralName(i), vocabulary.getSymbolicName(i), vocabulary.getDisplayName(i) ); } } @Test public void testVersion() { assertThat(new ComparableVersion("0.1.9")).isLessThan(new ComparableVersion("0.1.9-1")); } @Test public void testAssignment() throws Exception { bindings.put("ds1", dataset); engine.eval("ds2 := ds1"); assertThat(bindings).containsKey("ds2"); Object ds2 = bindings.get("ds2"); assertThat(ds2).isInstanceOf(Dataset.class); assertThat(ds2).isSameAs(dataset); } @Test public void testEscapedAssignment() throws Exception { bindings.put("ds1", dataset); engine.eval("'1escapedDs2' := ds1"); assertThat(bindings).containsKey("1escapedDs2"); Object ds2 = bindings.get("1escapedDs2"); assertThat(ds2).isInstanceOf(Dataset.class); assertThat(ds2).isSameAs(dataset); } @Test public void testEscapedExpression() throws Exception { bindings.put("123escaped-ds1", dataset); engine.eval("ds2 := '123escaped-ds1'"); assertThat(bindings).containsKey("ds2"); Object ds2 = bindings.get("ds2"); assertThat(ds2).isInstanceOf(Dataset.class); assertThat(ds2).isSameAs(dataset); } @Test public void testJoinAssignment() throws ScriptException { Dataset simpleDataset = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, String.class) .addComponent("me", Role.MEASURE, Long.class) .addPoints("id", 0L) .build(); bindings.put("ds", simpleDataset); engine.eval("/* join assignment */" + "res := [ds] {" + " assigned := me + 1" + "}"); assertThat(bindings).containsKey("res"); Object res = bindings.get("res"); assertThat(res).isInstanceOf(Dataset.class); assertThat(((Dataset) res).getDataStructure()).containsKeys("assigned"); assertThat(((Dataset) res).getData()).containsExactly( DataPoint.create("id", 0L, +1L) ); } @Test public void testJoinEscapedAssignment() throws ScriptException { Dataset simpleDataset = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, String.class) .addComponent("me", Role.MEASURE, Long.class) .addPoints("id", 0L) .build(); bindings.put("ds", simpleDataset); engine.eval("/* join assignment */" + "res := [ds] {" + " '123escaped-assigned' := me + 1" + "}"); assertThat(bindings).containsKey("res"); Object res = bindings.get("res"); assertThat(res).isInstanceOf(Dataset.class); assertThat(((Dataset) res).getDataStructure()).containsKeys("123escaped-assigned"); assertThat(((Dataset) res).getData()).containsExactly( DataPoint.create("id", 0L, 1L) ); } @Test public void testJoinEscapedExpression() throws ScriptException { Dataset simpleDataset = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, String.class) .addComponent("123escaped-me", Role.MEASURE, Long.class) .addPoints("id", 0L) .build(); bindings.put("ds", simpleDataset); engine.eval("/* join assignment */" + "res := [ds] {" + " assigned := '123escaped-me' + 1" + "}"); assertThat(bindings).containsKey("res"); Object res = bindings.get("res"); assertThat(res).isInstanceOf(Dataset.class); assertThat(((Dataset) res).getDataStructure()).containsKeys("assigned"); assertThat(((Dataset) res).getData()).containsExactly( DataPoint.create("id", 0L, 1L) ); } @Test public void testAssignmentLiterals() throws Exception { StaticDataset dataset = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addPoints("1") .build(); bindings.put("t1", dataset); engine.eval("/* test */\n" + "resultat := [t1] {\n" + " testFloat := 1.0," + " testInteger := 1," + " testString := \"test string\",\n" + " testString2 := \"test \"\"escaped\"\" string\",\n" + " testBoolean := true" + "}"); assertThat(bindings).containsKey("resultat"); assertThat(bindings.get("resultat")).isInstanceOf(Dataset.class); Dataset resultat = (Dataset) bindings.get("resultat"); assertThat(resultat.getDataStructure()) .describedAs("data structure of resultat") .containsOnlyKeys( "id1", "testFloat", "testInteger", "testString", "testString2", "testBoolean" ); assertThat(resultat.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", 1.0d, 1L, "test string", "test \"escaped\" string", true ); } @Test public void testGet() throws Exception { when(connector.canHandle(anyString())).thenReturn(true); when(connector.getDataset(anyString())).thenReturn(dataset); bindings.put("ds1", dataset); engine.eval("ds2 := get(\"todo\")"); assertThat(bindings).containsKeys("ds2"); assertThat(bindings.get("ds2")).isInstanceOf(Dataset.class); } @Test public void testPut() throws Exception { when(connector.canHandle(anyString())).thenReturn(true); when(connector.putDataset(anyString(), any())).thenReturn(dataset); engine.eval("ds1 := put(\"todo\")"); assertThat(bindings).contains(entry("ds1", dataset)); } @Test public void testSimpleJoin() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.MEASURE, String.class) .addPoints("1", "1", -50L, 1.5D, "attr1-1") .addPoints("2", "2", 100L, 0.123456789, "attr1-2") .build(); Dataset ds2 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at2", Role.MEASURE, String.class) .addPoints("1", "1", 30L, -1.0D, "attr2-1") .addPoints("2", "2", -40L, 0.987654321, "attr2-2") .build(); bindings.put("ds1", ds1); bindings.put("ds2", ds2); engine.eval("" + "ds3 := [ds1, ds2] {" + " at := at1 || at2," + " m1 := ds1.m1 + ds2.m1," + " m2 := ds1.m2 + ds2.m2," + " keep at, m1, m2" + "}" + ""); assertThat(bindings).containsKey("ds3"); assertThat(bindings.get("ds3")).isInstanceOf(Dataset.class); Dataset ds3 = (Dataset) bindings.get("ds3"); assertThat(ds3.getDataStructure()) .describedAs("data structure of d3") .containsOnlyKeys( "id2", "m1", "m2", "id1", "at" ); assertThat(ds3.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", "1", "attr1-1" + "attr2-1", (-50L + 30), 0.5D, "2", "2", "attr1-2" + "attr2-2", 60L, 1.11111111D ); } @Test public void testJoin() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.MEASURE, String.class) .addPoints("1", "1", 0L, 0.0, "attr1-1") .addPoints("1", "2", 10L, 200.0, "attr1-2") .build(); Dataset ds2 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at2", Role.MEASURE, String.class) .addPoints("1", "1", 30L, 40.0, "attr2-1") .addPoints("1", "2", 0L, 0.0, "attr2-2") .build(); bindings.put("ds1", ds1); bindings.put("ds2", ds2); engine.eval("" + "ds3 := [ds1, ds2]{" + // id1, id2, ds1.m1, ds1.m2, d2.m1, d2.m2, at1, at2 " filter id1 = \"1\" and ds2.m1 = 30 or ds1.m1 = 10," + //TODO: precedence " ident := ds1.m1 + ds2.m2 - ds1.m2 - ds2.m1," + // id1, id2, ds1.m1, ds1.m2, ds2.m1, ds2.m2, at1, at2, ident " keep ident, ds1.m1, ds2.m1, ds2.m2," + // id1, id2, ds1.m1, ds2.m1, ds2.m2 , ident " boolTest := (ds1.m1 = 10)," + // id1, id2, ds1.m1, ds2.m1, ds2.m2 , ident, boolTest " drop ds2.m1," + // id1, id2, ds1.m1, , ds2.m2 , ident, boolTest " rename id1 to renamedId1, ds1.m1 to m1, ds2.m2 to m2" + // renamedId1, id2, m1, m2, ident, boolTest "}" + ""); assertThat(bindings).containsKey("ds3"); assertThat(bindings.get("ds3")).isInstanceOf(Dataset.class); Dataset ds3 = (Dataset) bindings.get("ds3"); assertThat(ds3.getDataStructure()) .describedAs("data structure of d3") .containsOnlyKeys( "renamedId1", "id2", "m2", "m1", "ident", "boolTest" ); assertThat(ds3.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", "1", 0L, 40.0, 10.0, false, "1", "2", 10L, 0.0, -190.0, true ); } @Test public void testJoinFold() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Long.class) .addComponent("123-m3", Role.MEASURE, Long.class) .addPoints("1", 101L, 102L, 103L) .addPoints("2", 201L, 202L, 203L) .addPoints("3", 301L, 302L, 303L) .build(); bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " total := ds1.m1 + ds1.m2 + ds1.'123-m3'," + " fold ds1.m1, m2, ds1.'123-m3', total to type, '123-value'" + "}" ); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("type", Role.IDENTIFIER), entry("123-value", Role.MEASURE) ); assertThat(ds2.getData()).flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", "m1", 101L, "1", "m2", 102L, "1", "123-m3", 103L, "1", "total", 101L + 102L + 103L, "2", "m1", 201L, "2", "m2", 202L, "2", "123-m3", 203L, "2", "total", 201L + 202L + 203L, "3", "m1", 301L, "3", "m2", 302L, "3", "123-m3", 303L, "3", "total", 301L + 302L + 303L ); } @Test public void testBoolean() throws Exception { List<List<VTLObject>> data = Lists.newArrayList(); data.add( Lists.newArrayList(VTLObject.of("1"), VTLObject.of(1L), VTLObject.of(2D)) ); Dataset ds1 = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, String.class) .addComponent("integerMeasure", Role.MEASURE, Long.class) .addComponent("float", Role.MEASURE, Double.class) .addPoints("1", 1L, 2D) .build(); // TODO: Add test that check that we can compare float and integer in VTL. bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " lessThan := ds1.integerMeasure < 2," + " lessOrEqual := ds1.integerMeasure <= 2," + " moreThan := ds1.integerMeasure > 2," + " moreOrEqual := ds1.integerMeasure >= 2," + " equal := ds1.integerMeasure = 2" + "}" ); DataPoint point = ((Dataset) bindings.get("ds2")).getData().findFirst().get(); assertThat(point) .extracting(VTLObject::get) .containsExactly("1", 1L, 2D, true, true, false, false, false); } @Test public void testJoinUnfold() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.MEASURE, String.class) .addPoints("1", "one", 101L, 1.1, "attr1") .addPoints("1", "two", 102L, 1.1, "attr2") .addPoints("2", "one", 201L, 1.1, "attr2") .addPoints("2", "two", 202L, 1.1, "attr2") .build(); bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " unfold id2, ds1.m1 to \"one\", \"two\"," + " onePlusTwo := one + two" + "}" ); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("one", Role.MEASURE), entry("two", Role.MEASURE), entry("onePlusTwo", Role.MEASURE) ); assertThat(ds2.getData()).flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", 101L, 102L, 101L + 102L, "2", 201L, 202L, 201L + 202L ); } @Test public void testRename() throws Exception { dataset = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("me1", Role.MEASURE, String.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .build(); bindings.put("ds1", dataset); engine.eval("ds2 := ds1[rename id1 as id3]" + " [rename id3 as id1]" + " [rename id1 as id1m role MEASURE," + " me1 as me1a role ATTRIBUTE," + " at1 as at1i role IDENTIFIER]"); assertThat(bindings).containsKey("ds2"); Dataset result = (Dataset) bindings.get("ds2"); assertThat(result.getDataStructure().getRoles()).contains( entry("id1m", Role.MEASURE), entry("me1a", Role.ATTRIBUTE), entry("at1i", Role.IDENTIFIER) ); } @Test public void testCheckSingleRule() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("kommune_nr", Role.IDENTIFIER, String.class) .addComponent("periode", Role.IDENTIFIER, String.class) .addComponent("kostragruppe", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints("0101", "2015", "EKG14", 100L, "attr1") .addPoints("0101", "2015", "EKG15", 110L, "attr4") .addPoints("0111", "2014", "EKG14", 101L, "attr2") .addPoints("9000", "2014", "EKG14", 102L, "attr3") .build(); Dataset dsCodeList2 = StaticDataset.create() .addComponent("code", Role.IDENTIFIER, String.class) .addComponent("name", Role.MEASURE, String.class) .addComponent("period", Role.IDENTIFIER, String.class) .addPoints("0101", "Halden 2010-2013", "2010") .addPoints("0101", "Halden 2010-2013", "2011") .addPoints("0101", "Halden 2010-2013", "2012") .addPoints("0101", "Halden", "2013") .addPoints("0101", "Halden", "2014") .addPoints("0101", "Halden", "2015") .addPoints("0101", "Halden", "2016") .addPoints("0101", "Halden", "2017") .addPoints("0111", "Hvaler", "2015") .addPoints("0111", "Hvaler", "2016") .addPoints("0111", "Hvaler", "2017") .addPoints("1001", "Kristiansand", "2013") .addPoints("1001", "Kristiansand", "2014") .addPoints("1001", "Kristiansand", "2015") .build(); Dataset dsCodeList3 = StaticDataset.create() .addComponent("code", Role.IDENTIFIER, String.class) .addComponent("name", Role.MEASURE, String.class) .addComponent("period", Role.IDENTIFIER, String.class) .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2010") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2011") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2012") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2013") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2014") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2015") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2016") .addPoints("EKG14", "Bergen, Trondheim og Stavanger", "2017") .addPoints("EKG15", "Oslo kommune", "2016") .addPoints("EKG15", "Oslo kommune", "2017") .build(); bindings.put("ds1", ds1); bindings.put("ds2", dsCodeList2); bindings.put("ds3", dsCodeList3); VTLPrintStream out = new VTLPrintStream(System.out); engine.eval("" + "ds2r := [ds2]{rename code to kommune_nr, period to periode}" + "dsBoolean0 := [outer ds1, ds2r]{" + " ds2_CONDITION := name is not null," + " rename name to ds2_name," + " kommune_nr_RESULTAT := ds2_CONDITION" + "}" + "ds3r := [ds3]{rename code to kostragruppe, period to periode}" + "dsBoolean1 := [outer ds1, ds3r]{" + " ds3_CONDITION := name is not null," + " rename name to ds3_name," + " kostragruppe_RESULTAT := ds3_CONDITION" + "}" + "dsBoolean3 := [dsBoolean0, dsBoolean1]{" + " filter true" + "}" + "ds4invalid := check(dsBoolean3, not_valid, measures, errorcode(\"TEST_ERROR_CODE\"))" + "ds4valid := check(dsBoolean3, valid, measures)" ); out.println("dsBoolean0"); out.println(bindings.get("dsBoolean0")); out.println("dsBoolean1"); out.println(bindings.get("dsBoolean1")); out.println("dsBoolean3"); out.println(bindings.get("dsBoolean3")); out.println("ds4invalid"); out.println(bindings.get("ds4invalid")); assertThat(bindings).containsKey("ds4invalid"); assertThat(bindings).containsKey("ds4valid"); Dataset ds3invalid = (Dataset) bindings.get("ds4invalid"); Dataset ds3valid = (Dataset) bindings.get("ds4valid"); //not checking for other measures and attributes since they are //not necessary for validation assertThat(ds3invalid.getDataStructure().getRoles()).contains( entry("kommune_nr", Component.Role.IDENTIFIER), entry("periode", Component.Role.IDENTIFIER), entry("kostragruppe", Component.Role.IDENTIFIER), entry("errorcode", Component.Role.ATTRIBUTE), entry("kommune_nr_RESULTAT", Component.Role.MEASURE), entry("kostragruppe_RESULTAT", Component.Role.MEASURE) ); assertThat(ds3valid.getDataStructure().getRoles()).contains( entry("kommune_nr", Component.Role.IDENTIFIER), entry("periode", Component.Role.IDENTIFIER), entry("kostragruppe", Component.Role.IDENTIFIER), entry("errorcode", Component.Role.ATTRIBUTE), entry("kommune_nr_RESULTAT", Component.Role.MEASURE), entry("kostragruppe_RESULTAT", Component.Role.MEASURE) ); // Should only contain the "non valid" rows. DataStructure ds3InvalidDataStruct = ds3invalid.getDataStructure(); List<DataPoint> ds3InvalidDataPoints = ds3invalid.getData().collect(Collectors.toList()); assertThat(ds3InvalidDataPoints).hasSize(3); //using for loop as data points come in random order Map<Component, VTLObject> map; for (DataPoint dp : ds3InvalidDataPoints) { map = ds3InvalidDataStruct.asMap(dp); if (map.get(ds3InvalidDataStruct.get("kommune_nr")).get().equals("0101")) { assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr")).get()).isEqualTo("0101"); assertThat(map.get(ds3InvalidDataStruct.get("periode")).get()).isEqualTo("2015"); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe")).get()).isEqualTo("EKG15"); assertThat(map.get(ds3InvalidDataStruct.get("errorcode")).get()).isEqualTo("TEST_ERROR_CODE"); assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr_RESULTAT")).get()).isEqualTo(true); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe_RESULTAT")).get()).isEqualTo(false); } else if (map.get(ds3InvalidDataStruct.get("kommune_nr")).get().equals("9000")) { assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr")).get()).isEqualTo("9000"); assertThat(map.get(ds3InvalidDataStruct.get("periode")).get()).isEqualTo("2014"); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe")).get()).isEqualTo("EKG14"); assertThat(map.get(ds3InvalidDataStruct.get("errorcode")).get()).isEqualTo("TEST_ERROR_CODE"); assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr_RESULTAT")).get()).isEqualTo(false); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe_RESULTAT")).get()).isEqualTo(true); } else if (map.get(ds3InvalidDataStruct.get("kommune_nr")).get().equals("0111")) { assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr")).get()).isEqualTo("0111"); assertThat(map.get(ds3InvalidDataStruct.get("periode")).get()).isEqualTo("2014"); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe")).get()).isEqualTo("EKG14"); assertThat(map.get(ds3InvalidDataStruct.get("errorcode")).get()).isEqualTo("TEST_ERROR_CODE"); assertThat(map.get(ds3InvalidDataStruct.get("kommune_nr_RESULTAT")).get()).isEqualTo(false); assertThat(map.get(ds3InvalidDataStruct.get("kostragruppe_RESULTAT")).get()).isEqualTo(true); } } // Should only contain the "valid" rows. DataStructure ds3ValidDataStruct = ds3valid.getDataStructure(); List<DataPoint> ds3ValidDataPoints = ds3valid.getData().collect(Collectors.toList()); assertThat(ds3ValidDataPoints).hasSize(1); map = ds3ValidDataStruct.asMap(ds3ValidDataPoints.get(0)); assertThat(map.get(ds3ValidDataStruct.get("kommune_nr")).get()).isEqualTo("0101"); assertThat(map.get(ds3ValidDataStruct.get("periode")).get()).isEqualTo("2015"); assertThat(map.get(ds3ValidDataStruct.get("kostragruppe")).get()).isEqualTo("EKG14"); assertThat(map.get(ds3ValidDataStruct.get("errorcode")).get()).isNull(); assertThat(map.get(ds3ValidDataStruct.get("kommune_nr_RESULTAT")).get()).isEqualTo(true); assertThat(map.get(ds3ValidDataStruct.get("kostragruppe_RESULTAT")).get()).isEqualTo(true); } @Test public void testNvlAsClause() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, String.class) .addPoints("1", 1L, null) .addPoints("2", null, "str2") .addPoints("3", null, null) .build(); bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " m11 := nvl(m1 , 0), " + " m22 := nvl(ds1.m2, \"constant\"), " + " drop m1, m2 " + "}" ); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("m11", Role.MEASURE), entry("m22", Role.MEASURE) ); assertThat(ds2.getDataStructure().getTypes()).containsOnly( entry("id1", String.class), // TODO: Should be VTLString. entry("m11", Long.class), entry("m22", String.class) ); assertThat(ds2.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactlyInAnyOrder( "1", 1L, "constant", "2", 0L, "str2", "3", 0L, "constant" ); } @Test(expected = ScriptException.class) public void testNvlAsClauseNotEqualTypes() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addPoints("1", null) .build(); bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " m11 := nvl(m1 , \"constant\") " + "}" ); } @Test public void testDateFromStringAsClause() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, String.class) .addPoints("1", "2017") .addPoints("2", null) .build(); bindings.put("ds1", ds1); engine.eval("ds2 := [ds1] {" + " m11 := date_from_string(m1, \"YYYY\"), " + " drop m1 " + "}" ); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("m11", Role.MEASURE) ); assertThat(ds2.getDataStructure().getTypes()).containsOnly( entry("id1", String.class), entry("m11", Instant.class) ); assertThat(ds2.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()).toInstant(), "2", null ); } @Test(expected = ScriptException.class) public void testDateFromStringAsClauseUnsupportedFormat() throws Exception { engine.eval("test := date_from_string(\"string\", \"YYYYSN\")"); } @Test(expected = ScriptException.class) public void testDateFromStringAsClauseInputNotStringType() throws Exception { engine.eval("test := date_from_string(123, \"YYYY\")"); } @Test public void testAggregationAvg() throws ScriptException { StaticDataset ds = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, String.class) .addComponent("sign", Role.IDENTIFIER, String.class) .addComponent("withnulls", Role.IDENTIFIER, Boolean.class) .addComponent("integerMeasure", Role.MEASURE, Long.class) .addComponent("floatMeasure", Role.MEASURE, Double.class) .addPoints("id", "pos", false, 0L, 0D) .addPoints("id", "pos", false, 1L, 1D) .addPoints("id", "pos", false, 2L, 2D) .addPoints("id", "pos", false, 4L, 4D) .addPoints("id", "neg", false, -0L, -0D) .addPoints("id", "neg", false, -1L, -1D) .addPoints("id", "neg", false, -2L, -2D) .addPoints("id", "neg", false, -4L, -4D) .addPoints("id", "pos", true, null, null) .addPoints("id", "pos", true, 1L, 1D) .addPoints("id", "pos", true, 2L, 2D) .addPoints("id", "pos", true, 4L, 4D) .addPoints("id", "neg", true, null, null) .addPoints("id", "neg", true, -1L, -1D) .addPoints("id", "neg", true, -2L, -2D) .addPoints("id", "neg", true, -4L, -4D) .build(); bindings.put("ds", ds); engine.eval("result := avg(ds) along id"); assertThat(bindings).containsKeys("result"); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getData()).containsExactlyInAnyOrder( DataPoint.create("pos", false, 1.75D, 1.75D), DataPoint.create("pos", true, 2.3333333333333335, 2.3333333333333335), DataPoint.create("neg", false, -1.75D, -1.75D), DataPoint.create("neg", true, -2.3333333333333335, -2.3333333333333335) ); assertThat(result.getData(VtlOrdering.using(result).asc("withnulls").build()).get()).containsExactlyInAnyOrder( DataPoint.create("pos", false, 1.75D, 1.75D), DataPoint.create("neg", false, -1.75D, -1.75D), DataPoint.create("pos", true, 2.3333333333333335, 2.3333333333333335), DataPoint.create("neg", true, -2.3333333333333335, -2.3333333333333335) ); } @Test public void testAggregationSumGroupBy() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, Long.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints(1L, "one", 101L, 1.1, "attr1") .addPoints(1L, "two", 102L, 1.1, "attr2") .addPoints(2L, "one", 201L, 1.1, "attr2") .addPoints(2L, "two", 202L, 1.1, "attr2") .addPoints(2L, "two-null", null, null, "attr2") .build(); bindings.put("ds1", ds1); engine.eval("ds2 := sum(ds1.m1) group by id1"); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("m1", Role.MEASURE) ); assertThat(ds2.getDataStructure().getTypes()).containsOnly( entry("id1", Long.class), entry("m1", Long.class) ); assertThat(ds2.getData()).flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( 1L, 101L + 102L, 2L, 201L + 202L ); } @Test public void testIfThenElse() throws ScriptException { StaticDataset dataset = StaticDataset.create() .addComponent("id", Role.IDENTIFIER, Long.class) .addComponent("m1", Role.MEASURE, Boolean.class) .addComponent("m2", Role.MEASURE, Boolean.class) .addPoints(1L, false, false) .addPoints(2L, false, true) .addPoints(3L, true, false) .addPoints(4L, true, false) .build(); bindings.put("ds", dataset); engine.eval("result := [ds] { " + " test1 := if m1 then 1 elseif m2 then 2 else null," + " test2 := if m1 then 1 elseif m2 then null else 2," + " test3 := if m1 then null elseif m2 then 2 else 3," + " keep test1, test2, test3" + "}"); Dataset result = (Dataset) bindings.get("result"); assertThat(result).isNotNull(); assertThat(result.getDataStructure().getTypes().values()) .containsOnly(Long.class); assertThat(result.getData()).extracting(dataPoint -> Lists.transform(dataPoint, VTLObject::get)) .containsExactlyInAnyOrder( Arrays.asList(1L, null, 2L, 3L), Arrays.asList(2L, 2L, null, 2L), Arrays.asList(3L, 1L, 1L, null), Arrays.asList(4L, 1L, 1L, null) ); } @Test public void testAggregationSumAlong() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, Long.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints(1L, "one", 101L, "attr1") .addPoints(1L, "two", 102L, "attr2") .addPoints(2L, "one", 201L, "attr2") .addPoints(2L, "two", 202L, "attr2") .addPoints(2L, "two-null", null, "attr2") .build(); bindings.put("ds1", ds1); engine.eval("ds2 := sum(ds1) along id2"); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("m1", Role.MEASURE) ); assertThat(ds2.getDataStructure().getTypes()).containsOnly( entry("id1", Long.class), entry("m1", Long.class) ); assertThat(ds2.getData()).flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( 1L, 101L + 102L, 2L, 201L + 202L ); } @Test public void testAggregationMultiple() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, Long.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints(1L, "one", 101L, 1.1d, "attr1") .addPoints(1L, "two", 102L, 1.2d, "attr2") .addPoints(2L, "one", 201L, 2.1d, "attr2") .addPoints(2L, "two", 202L, 2.2d, "attr2") .addPoints(2L, "two-null", null, null, "attr2") .build(); bindings.put("ds1", ds1); engine.eval("ds2 := sum(ds1) group by id1"); assertThat(bindings).containsKey("ds2"); Dataset ds2 = (Dataset) bindings.get("ds2"); assertThat(ds2.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("m1", Role.MEASURE), entry("m2", Role.MEASURE) ); assertThat(ds2.getDataStructure().getTypes()).containsOnly( entry("id1", Long.class), entry("m1", Long.class), entry("m2", Double.class) ); assertThat(ds2.getData()).flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( 1L, 203L, 1.1d + 1.2d, 2L, 403L, 2.1d + 2.2d ); } @Test public void testUnion() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.MEASURE, String.class) .addPoints("1", 10L, 20D, "attr1-1") .addPoints("2", 100L, 200D, "attr1-2") .build(); Dataset ds2 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.MEASURE, String.class) .addPoints("3", 30L, 40D, "attr2-1") .addPoints("4", 300L, 400D, "attr2-2") .build(); bindings.put("ds1", ds1); bindings.put("ds2", ds2); engine.eval("" + "ds3 := union(ds1, ds2)"); assertThat(bindings).containsKey("ds3"); assertThat(bindings.get("ds3")).isInstanceOf(Dataset.class); Dataset ds3 = (Dataset) bindings.get("ds3"); assertThat(ds3.getDataStructure()) .describedAs("data structure of d3") .containsOnlyKeys( "id1", "m1", "m2", "at1" ); assertThat(ds3.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", 10L, 20D, "attr1-1", "2", 100L, 200D, "attr1-2", "3", 30L, 40D, "attr2-1", "4", 300L, 400D, "attr2-2" ); } @Test public void testUnionWithFilter() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addPoints("1", 10L, 20D) .addPoints("2", 100L, 200D) .build(); Dataset ds2 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints("3", 30L, 40D, "attr1-1") .addPoints("4", 300L, 400D, "attr1-2") .build(); bindings.put("ds1", ds1); bindings.put("ds2", ds2); engine.eval( "ds3 := union(ds1, ds2)" + "ds4 := [ds3]{" + "filter at1 = \"attr1-2\"" + " or m1 = 10" + "}" + ""); assertThat(bindings).containsKey("ds3"); assertThat(bindings).containsKey("ds4"); assertThat(bindings.get("ds3")).isInstanceOf(Dataset.class); assertThat(bindings.get("ds4")).isInstanceOf(Dataset.class); Dataset ds3 = (Dataset) bindings.get("ds3"); assertThat(ds3.getDataStructure()) .describedAs("data structure of d3") .containsOnlyKeys( "id1", "m1", "m2", "at1" ); Dataset ds4 = (Dataset) bindings.get("ds4"); assertThat(ds4.getDataStructure()) .describedAs("data structure of d4") .containsOnlyKeys( "id1", "m1", "m2", "at1" ); Stream<DataPoint> data = ds3.getData(); assertThat(data) .containsExactlyInAnyOrder( DataPoint.create("1", 10L, 20D, null), DataPoint.create("2", 100L, 200D, null), DataPoint.create("3", 30L, 40D, "attr1-1"), DataPoint.create("4", 300L, 400D, "attr1-2") ); assertThat(ds4.getData()) .containsExactlyInAnyOrder( DataPoint.create("1", 10L, 20D, null), DataPoint.create("4", 300L, 400D, "attr1-2") ); } @Test public void testMultipleUnions() throws Exception { Dataset ds1 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addPoints("1", 10L, 20D) .addPoints("2", 100L, 200D) .build(); Dataset ds2 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at1", Role.ATTRIBUTE, String.class) .addPoints("3", 30L, 40D, "attr1-1") .addPoints("4", 300L, 400D, "attr1-2") .build(); Dataset ds3 = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("m1", Role.MEASURE, Long.class) .addComponent("m2", Role.MEASURE, Double.class) .addComponent("at2", Role.ATTRIBUTE, String.class) .addPoints("5", 50L, 60D, "attr2-1") .addPoints("6", 500L, 600D, "attr2-2") .build(); bindings.put("ds1", ds1); bindings.put("ds2", ds2); bindings.put("ds3", ds3); engine.eval( "ds4 := union(ds1, ds2, ds3)" + "ds5 := union(ds2, ds3, ds1)" + "ds6 := union(ds3, ds1, ds2)"); assertThat(bindings).containsKey("ds4"); assertThat(bindings).containsKey("ds5"); assertThat(bindings).containsKey("ds6"); assertThat(bindings.get("ds4")).isInstanceOf(Dataset.class); assertThat(bindings.get("ds5")).isInstanceOf(Dataset.class); assertThat(bindings.get("ds6")).isInstanceOf(Dataset.class); Dataset ds4 = (Dataset) bindings.get("ds4"); assertThat(ds4.getDataStructure()) .describedAs("data structure of d4") .containsOnlyKeys( "id1", "m1", "m2", "at1", "at2" ); Dataset ds5 = (Dataset) bindings.get("ds5"); assertThat(ds5.getDataStructure()) .describedAs("data structure of ds5") .containsOnlyKeys( "id1", "m1", "m2", "at1", "at2" ); Dataset ds6 = (Dataset) bindings.get("ds6"); assertThat(ds6.getDataStructure()) .describedAs("data structure of ds6") .containsOnlyKeys( "id1", "m1", "m2", "at1", "at2" ); assertThat(ds4.getData()) .containsExactlyInAnyOrder( DataPoint.create("1", 10L, 20D, null, null), DataPoint.create("2", 100L, 200D, null, null), DataPoint.create("3", 30L, 40D, "attr1-1", null), DataPoint.create("4", 300L, 400D, "attr1-2", null), DataPoint.create("5", 50L, 60D, null, "attr2-1"), DataPoint.create("6", 500L, 600D, null, "attr2-2") ); assertThat(ds5.getData()) .containsExactlyInAnyOrder( DataPoint.create("1", 10L, 20D, null, null), DataPoint.create("2", 100L, 200D, null, null), DataPoint.create("3", 30L, 40D, "attr1-1", null), DataPoint.create("4", 300L, 400D, "attr1-2", null), DataPoint.create("5", 50L, 60D, null, "attr2-1"), DataPoint.create("6", 500L, 600D, null, "attr2-2") ); assertThat(ds6.getData()) .containsExactlyInAnyOrder( DataPoint.create("1", 10L, 20D, null, null), DataPoint.create("2", 100L, 200D, null, null), DataPoint.create("3", 30L, 40D, "attr1-1", null), DataPoint.create("4", 300L, 400D, "attr1-2", null), DataPoint.create("5", 50L, 60D, null, "attr2-1"), DataPoint.create("6", 500L, 600D, null, "attr2-2") ); assertThat(ds6.getData()) .flatExtracting(input -> input) .extracting(VTLObject::get) .containsExactly( "1", 10L, 20D, null, null, "2", 100L, 200D, null, null, "3", 30L, 40D, "attr1-1", null, "4", 300L, 400D, "attr1-2", null, "5", 50L, 60D, null, "attr2-1", "6", 500L, 600D, null, "attr2-2" ); } @Test public void testOuterJoinWithMultipleIds() throws ScriptException { createMultipleIdDatasets(); VTLPrintStream out = new VTLPrintStream(System.out); engine.eval("result := [outer a,b] {\n" + " rename a.integerMeasure to a,\n" + " rename b.integerMeasure to b\n" + "}"); out.println(bindings.get("result")); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); assertThat(result.getData()).containsExactlyInAnyOrder( DataPoint.create("id1-1", "id2-1", 1, 1), DataPoint.create("id1-2", "id2-1", 2, 2), DataPoint.create("id1-3", "id2-1", 7, null), DataPoint.create("id1-1", "id2-2", 1, null), DataPoint.create("id1-2", "id2-2", 2, null), DataPoint.create("id1-1", "id2-3", null, 1), DataPoint.create("id1-2", "id2-3", null, 2) ); } @Test public void testInnerJoinWithMultipleIds() throws ScriptException { createMultipleIdDatasets(); VTLPrintStream out = new VTLPrintStream(System.out); engine.eval("result := [a,b] {\n" + " rename a.integerMeasure to a,\n" + " rename b.integerMeasure to b\n" + "}"); out.println(bindings.get("result")); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); assertThat(result.getData()).containsExactlyInAnyOrder( DataPoint.create("id1-1", "id2-1", 1, 1), DataPoint.create("id1-2", "id2-1", 2, 2) ); } @Test public void testInnerJoinWithMultipleRenames() throws ScriptException { createMultipleIdDatasets(); engine.eval("result := [a,b] {\n" + " rename a.integerMeasure to a, b.integerMeasure to b\n" + "}"); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); // Test different renames engine.eval("result := [a,b] {\n" + " rename a.integerMeasure to tmpA, b.integerMeasure to tmpB,\n" + " rename tmpA to a, tmpB to b\n" + "}"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); } @Test public void testInnerJoinOnSingleIdentifier() throws ScriptException { createMultipleIdDatasets(); VTLPrintStream out = new VTLPrintStream(System.out); engine.eval("result := [a,b on id1] {\n" + " rename id1 to commonId,\n" + " rename a.integerMeasure to a,\n" + " rename b.integerMeasure to b\n" + "}"); out.println(bindings.get("result")); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("commonId", Role.IDENTIFIER), entry("a_id2", Role.IDENTIFIER), entry("b_id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); assertThat(result.getData()).containsExactlyInAnyOrder( DataPoint.create("id1-1", "id2-1", 1, "id2-1", 1), DataPoint.create("id1-1", "id2-1", 1, "id2-3", 1), DataPoint.create("id1-1", "id2-2", 1, "id2-1", 1), DataPoint.create("id1-1", "id2-2", 1, "id2-3", 1), DataPoint.create("id1-2", "id2-1", 2, "id2-1", 2), DataPoint.create("id1-2", "id2-1", 2, "id2-3", 2), DataPoint.create("id1-2", "id2-2", 2, "id2-1", 2), DataPoint.create("id1-2", "id2-2", 2, "id2-3", 2) ); } @Test public void testOuterJoinOnSingleIdentifier() throws ScriptException { createMultipleIdDatasets(); VTLPrintStream out = new VTLPrintStream(System.out); engine.eval("result := [outer a,b on id1] {\n" + " rename a.integerMeasure to a,\n" + " rename b.integerMeasure to b\n" + "}"); out.println(bindings.get("result")); Dataset result = (Dataset) bindings.get("result"); assertThat(result.getDataStructure().getRoles()).containsOnly( entry("id1", Role.IDENTIFIER), entry("a_id2", Role.IDENTIFIER), entry("b_id2", Role.IDENTIFIER), entry("a", Role.MEASURE), entry("b", Role.MEASURE) ); } private void createMultipleIdDatasets() { StaticDataset a = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("integerMeasure", Role.MEASURE, Long.class) .addPoints("id1-1", "id2-1", 1L) .addPoints("id1-2", "id2-1", 2L) .addPoints("id1-3", "id2-1", 7L) .addPoints("id1-1", "id2-2", 1L) .addPoints("id1-2", "id2-2", 2L) .build(); StaticDataset b = StaticDataset.create() .addComponent("id1", Role.IDENTIFIER, String.class) .addComponent("id2", Role.IDENTIFIER, String.class) .addComponent("integerMeasure", Role.MEASURE, Long.class) .addPoints("id1-1", "id2-1", 1L) .addPoints("id1-2", "id2-1", 2L) .addPoints("id1-1", "id2-3", 1L) .addPoints("id1-2", "id2-3", 2L) .build(); bindings.put("a", a); bindings.put("b", b); } }
{ "content_hash": "32149cbeddd74397c066d28534334677", "timestamp": "", "source": "github", "line_count": 1454, "max_line_length": 147, "avg_line_length": 40.670563961485556, "alnum_prop": 0.5150587638454384, "repo_name": "statisticsnorway/java-vtl", "id": "908bef5940a00144f1dc5f0c754e316b8fcf457e", "size": "59912", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "java-vtl-script/src/test/java/no/ssb/vtl/script/VTLScriptEngineTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11682" }, { "name": "CSS", "bytes": "31704" }, { "name": "GAP", "bytes": "30394" }, { "name": "HTML", "bytes": "14373" }, { "name": "Java", "bytes": "1245403" }, { "name": "JavaScript", "bytes": "47079" }, { "name": "Shell", "bytes": "1823" } ], "symlink_target": "" }
package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.spring.cloud.ribbon.client.ServerLocationApp; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreetingApplication.class) public class SpringContextIntegrationTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } }
{ "content_hash": "7360fc8893f2fb31c473dc326ede2f1d", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 68, "avg_line_length": 28.41176470588235, "alnum_prop": 0.8178053830227743, "repo_name": "csc19601128/misc-examples", "id": "0f544b3ed15d9b6c5b2bcc370b30db531d15b8e5", "size": "483", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "baeldung-tutorial/spring-cloud/spring-cloud-zookeeper/Greeting/src/test/baeldung/SpringContextIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17973" }, { "name": "CSS", "bytes": "137172" }, { "name": "Dockerfile", "bytes": "4886" }, { "name": "Go", "bytes": "8864" }, { "name": "Groovy", "bytes": "745" }, { "name": "HCL", "bytes": "470" }, { "name": "HTML", "bytes": "27741" }, { "name": "Java", "bytes": "965152" }, { "name": "JavaScript", "bytes": "2304210" }, { "name": "Perl", "bytes": "1432" }, { "name": "Python", "bytes": "13020" }, { "name": "Rich Text Format", "bytes": "810" }, { "name": "Roff", "bytes": "2683772" }, { "name": "Ruby", "bytes": "9372" }, { "name": "Scala", "bytes": "276" }, { "name": "Shell", "bytes": "96991" }, { "name": "TSQL", "bytes": "15572" }, { "name": "TypeScript", "bytes": "14500" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_45) on Tue May 12 14:55:48 CEST 2015 --> <title>service.composite</title> <meta name="date" content="2015-05-12"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="service.composite"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../service/client/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../service/messagingservice/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../index.html?service/composite/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;service.composite</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../service/composite/CompositeService.html" title="class in service.composite">CompositeService</a></td> <td class="colLast"> <div class="block">Providing an abstraction to create composite services</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../service/composite/CompositeServiceClient.html" title="class in service.composite">CompositeServiceClient</a></td> <td class="colLast"> <div class="block">Providing support for remotely accessing a composite service</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../service/composite/SDCache.html" title="class in service.composite">SDCache</a></td> <td class="colLast"> <div class="block">Cache for available services</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../service/client/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../service/messagingservice/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../index.html?service/composite/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "45242a185f15a7902ea09e3f697ca674", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 149, "avg_line_length": 33.98076923076923, "alnum_prop": 0.6445953593661573, "repo_name": "musman/RSP", "id": "e3b221cbcb608192c7fbde048d90907f1668fa9b", "size": "5301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ResearchServicePlatform/doc/service/composite/package-summary.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12808" }, { "name": "HTML", "bytes": "6379935" }, { "name": "Java", "bytes": "763595" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-multinomials: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.2 / mathcomp-multinomials - 1.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-multinomials <small> 1.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-03 10:13:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-03 10:13:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.2 Formal proof management system dune 3.4.1 Fast, portable, and opinionated build system ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/math-comp/multinomials-ssr&quot; bug-reports: &quot;https://github.com/math-comp/multinomials-ssr/issues&quot; dev-repo: &quot;git+https://github.com/math-comp/multinomials.git&quot; license: &quot;CeCILL-B&quot; authors: [&quot;Pierre-Yves Strub&quot;] build: [ [make &quot;INSTMODE=global&quot; &quot;config&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/SsrMultinomials&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6&quot; &amp; &lt; &quot;1.8.0~&quot;} &quot;coq-mathcomp-algebra&quot; {&gt;= &quot;1.6&quot; &amp; &lt; &quot;1.8.0~&quot;} &quot;coq-mathcomp-bigenough&quot; {&gt;= &quot;1.0.0&quot; &amp; &lt; &quot;1.1.0~&quot;} &quot;coq-mathcomp-finmap&quot; {&gt;= &quot;1.0.0&quot; &amp; &lt; &quot;1.1.0~&quot;} ] tags: [ &quot;keyword:multinomials&quot; &quot;keyword:monoid algebra&quot; &quot;category:Math/Algebra/Multinomials&quot; &quot;category:Math/Algebra/Monoid algebra&quot; &quot;date:2016&quot; &quot;logpath:SsrMultinomials&quot; ] synopsis: &quot;A multivariate polynomial library for the Mathematical Components Library&quot; flags: light-uninstall url { src: &quot;https://github.com/math-comp/multinomials/archive/1.1.tar.gz&quot; checksum: &quot;md5=e22b275b1687878d2bdc9b6922d9fde5&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-multinomials.1.1 coq.8.15.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.2). The following dependencies couldn&#39;t be met: - coq-mathcomp-multinomials -&gt; coq-mathcomp-ssreflect &lt; 1.8.0~ -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-multinomials.1.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "8cd2dbf15d24dcf45565b34fc69c9b17", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 159, "avg_line_length": 41.548022598870055, "alnum_prop": 0.5489529507750884, "repo_name": "coq-bench/coq-bench.github.io", "id": "42c887595e1f12c7362001ed82da22501a255e52", "size": "7379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.15.2/mathcomp-multinomials/1.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#include "cartographer/mapping/internal/optimization/optimization_problem_3d.h" #include <algorithm> #include <array> #include <cmath> #include <iterator> #include <map> #include <memory> #include <string> #include <vector> #include "Eigen/Core" #include "absl/memory/memory.h" #include "cartographer/common/internal/ceres_solver_options.h" #include "cartographer/common/math.h" #include "cartographer/common/time.h" #include "cartographer/mapping/internal/3d/imu_integration.h" #include "cartographer/mapping/internal/3d/rotation_parameterization.h" #include "cartographer/mapping/internal/optimization/ceres_pose.h" #include "cartographer/mapping/internal/optimization/cost_functions/acceleration_cost_function_3d.h" #include "cartographer/mapping/internal/optimization/cost_functions/landmark_cost_function_3d.h" #include "cartographer/mapping/internal/optimization/cost_functions/rotation_cost_function_3d.h" #include "cartographer/mapping/internal/optimization/cost_functions/spa_cost_function_3d.h" #include "cartographer/transform/timestamped_transform.h" #include "cartographer/transform/transform.h" #include "ceres/ceres.h" #include "ceres/jet.h" #include "ceres/rotation.h" #include "glog/logging.h" namespace cartographer { namespace mapping { namespace optimization { namespace { using LandmarkNode = ::cartographer::mapping::PoseGraphInterface::LandmarkNode; using TrajectoryData = ::cartographer::mapping::PoseGraphInterface::TrajectoryData; // For odometry. std::unique_ptr<transform::Rigid3d> Interpolate( const sensor::MapByTime<sensor::OdometryData>& map_by_time, const int trajectory_id, const common::Time time) { const auto it = map_by_time.lower_bound(trajectory_id, time); if (it == map_by_time.EndOfTrajectory(trajectory_id)) { return nullptr; } if (it == map_by_time.BeginOfTrajectory(trajectory_id)) { if (it->time == time) { return absl::make_unique<transform::Rigid3d>(it->pose); } return nullptr; } const auto prev_it = std::prev(it); return absl::make_unique<transform::Rigid3d>( Interpolate(transform::TimestampedTransform{prev_it->time, prev_it->pose}, transform::TimestampedTransform{it->time, it->pose}, time) .transform); } // For fixed frame pose. std::unique_ptr<transform::Rigid3d> Interpolate( const sensor::MapByTime<sensor::FixedFramePoseData>& map_by_time, const int trajectory_id, const common::Time time) { const auto it = map_by_time.lower_bound(trajectory_id, time); if (it == map_by_time.EndOfTrajectory(trajectory_id) || !it->pose.has_value()) { return nullptr; } if (it == map_by_time.BeginOfTrajectory(trajectory_id)) { if (it->time == time) { return absl::make_unique<transform::Rigid3d>(it->pose.value()); } return nullptr; } const auto prev_it = std::prev(it); if (prev_it->pose.has_value()) { return absl::make_unique<transform::Rigid3d>( Interpolate(transform::TimestampedTransform{prev_it->time, prev_it->pose.value()}, transform::TimestampedTransform{it->time, it->pose.value()}, time) .transform); } return nullptr; } // Selects a trajectory node closest in time to the landmark observation and // applies a relative transform from it. transform::Rigid3d GetInitialLandmarkPose( const LandmarkNode::LandmarkObservation& observation, const NodeSpec3D& prev_node, const NodeSpec3D& next_node, const CeresPose& prev_node_pose, const CeresPose& next_node_pose) { const double interpolation_parameter = common::ToSeconds(observation.time - prev_node.time) / common::ToSeconds(next_node.time - prev_node.time); const std::tuple<std::array<double, 4>, std::array<double, 3>> rotation_and_translation = InterpolateNodes3D( prev_node_pose.rotation(), prev_node_pose.translation(), next_node_pose.rotation(), next_node_pose.translation(), interpolation_parameter); return transform::Rigid3d::FromArrays(std::get<0>(rotation_and_translation), std::get<1>(rotation_and_translation)) * observation.landmark_to_tracking_transform; } void AddLandmarkCostFunctions( const std::map<std::string, LandmarkNode>& landmark_nodes, const MapById<NodeId, NodeSpec3D>& node_data, MapById<NodeId, CeresPose>* C_nodes, std::map<std::string, CeresPose>* C_landmarks, ceres::Problem* problem, double huber_scale) { for (const auto& landmark_node : landmark_nodes) { // Do not use landmarks that were not optimized for localization. for (const auto& observation : landmark_node.second.landmark_observations) { const std::string& landmark_id = landmark_node.first; const auto& begin_of_trajectory = node_data.BeginOfTrajectory(observation.trajectory_id); // The landmark observation was made before the trajectory was created. if (observation.time < begin_of_trajectory->data.time) { continue; } // Find the trajectory nodes before and after the landmark observation. auto next = node_data.lower_bound(observation.trajectory_id, observation.time); // The landmark observation was made, but the next trajectory node has // not been added yet. if (next == node_data.EndOfTrajectory(observation.trajectory_id)) { continue; } if (next == begin_of_trajectory) { next = std::next(next); } auto prev = std::prev(next); // Add parameter blocks for the landmark ID if they were not added before. CeresPose* prev_node_pose = &C_nodes->at(prev->id); CeresPose* next_node_pose = &C_nodes->at(next->id); if (!C_landmarks->count(landmark_id)) { const transform::Rigid3d starting_point = landmark_node.second.global_landmark_pose.has_value() ? landmark_node.second.global_landmark_pose.value() : GetInitialLandmarkPose(observation, prev->data, next->data, *prev_node_pose, *next_node_pose); C_landmarks->emplace( landmark_id, CeresPose(starting_point, nullptr /* translation_parametrization */, absl::make_unique<ceres::QuaternionParameterization>(), problem)); // Set landmark constant if it is frozen. if (landmark_node.second.frozen) { problem->SetParameterBlockConstant( C_landmarks->at(landmark_id).translation()); problem->SetParameterBlockConstant( C_landmarks->at(landmark_id).rotation()); } } problem->AddResidualBlock( LandmarkCostFunction3D::CreateAutoDiffCostFunction( observation, prev->data, next->data), new ceres::HuberLoss(huber_scale), prev_node_pose->rotation(), prev_node_pose->translation(), next_node_pose->rotation(), next_node_pose->translation(), C_landmarks->at(landmark_id).rotation(), C_landmarks->at(landmark_id).translation()); } } } } // namespace OptimizationProblem3D::OptimizationProblem3D( const optimization::proto::OptimizationProblemOptions& options) : options_(options) {} OptimizationProblem3D::~OptimizationProblem3D() {} void OptimizationProblem3D::AddImuData(const int trajectory_id, const sensor::ImuData& imu_data) { imu_data_.Append(trajectory_id, imu_data); } void OptimizationProblem3D::AddOdometryData( const int trajectory_id, const sensor::OdometryData& odometry_data) { odometry_data_.Append(trajectory_id, odometry_data); } void OptimizationProblem3D::AddFixedFramePoseData( const int trajectory_id, const sensor::FixedFramePoseData& fixed_frame_pose_data) { fixed_frame_pose_data_.Append(trajectory_id, fixed_frame_pose_data); } void OptimizationProblem3D::AddTrajectoryNode(const int trajectory_id, const NodeSpec3D& node_data) { node_data_.Append(trajectory_id, node_data); trajectory_data_[trajectory_id]; } void OptimizationProblem3D::SetTrajectoryData( int trajectory_id, const TrajectoryData& trajectory_data) { trajectory_data_[trajectory_id] = trajectory_data; } void OptimizationProblem3D::InsertTrajectoryNode(const NodeId& node_id, const NodeSpec3D& node_data) { node_data_.Insert(node_id, node_data); trajectory_data_[node_id.trajectory_id]; } void OptimizationProblem3D::TrimTrajectoryNode(const NodeId& node_id) { imu_data_.Trim(node_data_, node_id); odometry_data_.Trim(node_data_, node_id); fixed_frame_pose_data_.Trim(node_data_, node_id); node_data_.Trim(node_id); if (node_data_.SizeOfTrajectoryOrZero(node_id.trajectory_id) == 0) { trajectory_data_.erase(node_id.trajectory_id); } } void OptimizationProblem3D::AddSubmap( const int trajectory_id, const transform::Rigid3d& global_submap_pose) { submap_data_.Append(trajectory_id, SubmapSpec3D{global_submap_pose}); } void OptimizationProblem3D::InsertSubmap( const SubmapId& submap_id, const transform::Rigid3d& global_submap_pose) { submap_data_.Insert(submap_id, SubmapSpec3D{global_submap_pose}); } void OptimizationProblem3D::TrimSubmap(const SubmapId& submap_id) { submap_data_.Trim(submap_id); } void OptimizationProblem3D::SetMaxNumIterations( const int32 max_num_iterations) { options_.mutable_ceres_solver_options()->set_max_num_iterations( max_num_iterations); } void OptimizationProblem3D::Solve( const std::vector<Constraint>& constraints, const std::map<int, PoseGraphInterface::TrajectoryState>& trajectories_state, const std::map<std::string, LandmarkNode>& landmark_nodes) { if (node_data_.empty()) { // Nothing to optimize. return; } std::set<int> frozen_trajectories; for (const auto& it : trajectories_state) { if (it.second == PoseGraphInterface::TrajectoryState::FROZEN) { frozen_trajectories.insert(it.first); } } ceres::Problem::Options problem_options; ceres::Problem problem(problem_options); const auto translation_parameterization = [this]() -> std::unique_ptr<ceres::LocalParameterization> { return options_.fix_z_in_3d() ? absl::make_unique<ceres::SubsetParameterization>( 3, std::vector<int>{2}) : nullptr; }; // Set the starting point. CHECK(!submap_data_.empty()); MapById<SubmapId, CeresPose> C_submaps; MapById<NodeId, CeresPose> C_nodes; std::map<std::string, CeresPose> C_landmarks; bool first_submap = true; for (const auto& submap_id_data : submap_data_) { const bool frozen = frozen_trajectories.count(submap_id_data.id.trajectory_id) != 0; if (first_submap) { first_submap = false; // Fix the first submap of the first trajectory except for allowing // gravity alignment. C_submaps.Insert( submap_id_data.id, CeresPose(submap_id_data.data.global_pose, translation_parameterization(), absl::make_unique<ceres::AutoDiffLocalParameterization< ConstantYawQuaternionPlus, 4, 2>>(), &problem)); problem.SetParameterBlockConstant( C_submaps.at(submap_id_data.id).translation()); } else { C_submaps.Insert( submap_id_data.id, CeresPose(submap_id_data.data.global_pose, translation_parameterization(), absl::make_unique<ceres::QuaternionParameterization>(), &problem)); } if (frozen) { problem.SetParameterBlockConstant( C_submaps.at(submap_id_data.id).rotation()); problem.SetParameterBlockConstant( C_submaps.at(submap_id_data.id).translation()); } } for (const auto& node_id_data : node_data_) { const bool frozen = frozen_trajectories.count(node_id_data.id.trajectory_id) != 0; C_nodes.Insert( node_id_data.id, CeresPose(node_id_data.data.global_pose, translation_parameterization(), absl::make_unique<ceres::QuaternionParameterization>(), &problem)); if (frozen) { problem.SetParameterBlockConstant(C_nodes.at(node_id_data.id).rotation()); problem.SetParameterBlockConstant( C_nodes.at(node_id_data.id).translation()); } } // Add cost functions for intra- and inter-submap constraints. for (const Constraint& constraint : constraints) { problem.AddResidualBlock( SpaCostFunction3D::CreateAutoDiffCostFunction(constraint.pose), // Loop closure constraints should have a loss function. constraint.tag == Constraint::INTER_SUBMAP ? new ceres::HuberLoss(options_.huber_scale()) : nullptr /* loss function */, C_submaps.at(constraint.submap_id).rotation(), C_submaps.at(constraint.submap_id).translation(), C_nodes.at(constraint.node_id).rotation(), C_nodes.at(constraint.node_id).translation()); } // Add cost functions for landmarks. AddLandmarkCostFunctions(landmark_nodes, node_data_, &C_nodes, &C_landmarks, &problem, options_.huber_scale()); // Add constraints based on IMU observations of angular velocities and // linear acceleration. if (!options_.fix_z_in_3d()) { for (auto node_it = node_data_.begin(); node_it != node_data_.end();) { const int trajectory_id = node_it->id.trajectory_id; const auto trajectory_end = node_data_.EndOfTrajectory(trajectory_id); if (frozen_trajectories.count(trajectory_id) != 0) { // We skip frozen trajectories. node_it = trajectory_end; continue; } TrajectoryData& trajectory_data = trajectory_data_.at(trajectory_id); problem.AddParameterBlock(trajectory_data.imu_calibration.data(), 4, new ceres::QuaternionParameterization()); if (!options_.use_online_imu_extrinsics_in_3d()) { problem.SetParameterBlockConstant( trajectory_data.imu_calibration.data()); } CHECK(imu_data_.HasTrajectory(trajectory_id)); const auto imu_data = imu_data_.trajectory(trajectory_id); CHECK(imu_data.begin() != imu_data.end()); auto imu_it = imu_data.begin(); auto prev_node_it = node_it; for (++node_it; node_it != trajectory_end; ++node_it) { const NodeId first_node_id = prev_node_it->id; const NodeSpec3D& first_node_data = prev_node_it->data; prev_node_it = node_it; const NodeId second_node_id = node_it->id; const NodeSpec3D& second_node_data = node_it->data; if (second_node_id.node_index != first_node_id.node_index + 1) { continue; } // Skip IMU data before the node. while (std::next(imu_it) != imu_data.end() && std::next(imu_it)->time <= first_node_data.time) { ++imu_it; } auto imu_it2 = imu_it; const IntegrateImuResult<double> result = IntegrateImu( imu_data, first_node_data.time, second_node_data.time, &imu_it); const auto next_node_it = std::next(node_it); const common::Time first_time = first_node_data.time; const common::Time second_time = second_node_data.time; const common::Duration first_duration = second_time - first_time; if (next_node_it != trajectory_end && next_node_it->id.node_index == second_node_id.node_index + 1) { const NodeId third_node_id = next_node_it->id; const NodeSpec3D& third_node_data = next_node_it->data; const common::Time third_time = third_node_data.time; const common::Duration second_duration = third_time - second_time; const common::Time first_center = first_time + first_duration / 2; const common::Time second_center = second_time + second_duration / 2; const IntegrateImuResult<double> result_to_first_center = IntegrateImu(imu_data, first_time, first_center, &imu_it2); const IntegrateImuResult<double> result_center_to_center = IntegrateImu(imu_data, first_center, second_center, &imu_it2); // 'delta_velocity' is the change in velocity from the point in time // halfway between the first and second poses to halfway between // second and third pose. It is computed from IMU data and still // contains a delta due to gravity. The orientation of this vector is // in the IMU frame at the second pose. const Eigen::Vector3d delta_velocity = (result.delta_rotation.inverse() * result_to_first_center.delta_rotation) * result_center_to_center.delta_velocity; problem.AddResidualBlock( AccelerationCostFunction3D::CreateAutoDiffCostFunction( options_.acceleration_weight() / common::ToSeconds(first_duration + second_duration), delta_velocity, common::ToSeconds(first_duration), common::ToSeconds(second_duration)), nullptr /* loss function */, C_nodes.at(second_node_id).rotation(), C_nodes.at(first_node_id).translation(), C_nodes.at(second_node_id).translation(), C_nodes.at(third_node_id).translation(), &trajectory_data.gravity_constant, trajectory_data.imu_calibration.data()); } problem.AddResidualBlock( RotationCostFunction3D::CreateAutoDiffCostFunction( options_.rotation_weight() / common::ToSeconds(first_duration), result.delta_rotation), nullptr /* loss function */, C_nodes.at(first_node_id).rotation(), C_nodes.at(second_node_id).rotation(), trajectory_data.imu_calibration.data()); } // Force gravity constant to be positive. problem.SetParameterLowerBound(&trajectory_data.gravity_constant, 0, 0.0); } } if (options_.fix_z_in_3d()) { // Add penalties for violating odometry (if available) and changes between // consecutive nodes. for (auto node_it = node_data_.begin(); node_it != node_data_.end();) { const int trajectory_id = node_it->id.trajectory_id; const auto trajectory_end = node_data_.EndOfTrajectory(trajectory_id); if (frozen_trajectories.count(trajectory_id) != 0) { node_it = trajectory_end; continue; } auto prev_node_it = node_it; for (++node_it; node_it != trajectory_end; ++node_it) { const NodeId first_node_id = prev_node_it->id; const NodeSpec3D& first_node_data = prev_node_it->data; prev_node_it = node_it; const NodeId second_node_id = node_it->id; const NodeSpec3D& second_node_data = node_it->data; if (second_node_id.node_index != first_node_id.node_index + 1) { continue; } // Add a relative pose constraint based on the odometry (if available). const std::unique_ptr<transform::Rigid3d> relative_odometry = CalculateOdometryBetweenNodes(trajectory_id, first_node_data, second_node_data); if (relative_odometry != nullptr) { problem.AddResidualBlock( SpaCostFunction3D::CreateAutoDiffCostFunction(Constraint::Pose{ *relative_odometry, options_.odometry_translation_weight(), options_.odometry_rotation_weight()}), nullptr /* loss function */, C_nodes.at(first_node_id).rotation(), C_nodes.at(first_node_id).translation(), C_nodes.at(second_node_id).rotation(), C_nodes.at(second_node_id).translation()); } // Add a relative pose constraint based on consecutive local SLAM poses. const transform::Rigid3d relative_local_slam_pose = first_node_data.local_pose.inverse() * second_node_data.local_pose; problem.AddResidualBlock( SpaCostFunction3D::CreateAutoDiffCostFunction( Constraint::Pose{relative_local_slam_pose, options_.local_slam_pose_translation_weight(), options_.local_slam_pose_rotation_weight()}), nullptr /* loss function */, C_nodes.at(first_node_id).rotation(), C_nodes.at(first_node_id).translation(), C_nodes.at(second_node_id).rotation(), C_nodes.at(second_node_id).translation()); } } } // Add fixed frame pose constraints. std::map<int, CeresPose> C_fixed_frames; for (auto node_it = node_data_.begin(); node_it != node_data_.end();) { const int trajectory_id = node_it->id.trajectory_id; const auto trajectory_end = node_data_.EndOfTrajectory(trajectory_id); if (!fixed_frame_pose_data_.HasTrajectory(trajectory_id)) { node_it = trajectory_end; continue; } const TrajectoryData& trajectory_data = trajectory_data_.at(trajectory_id); bool fixed_frame_pose_initialized = false; for (; node_it != trajectory_end; ++node_it) { const NodeId node_id = node_it->id; const NodeSpec3D& node_data = node_it->data; const std::unique_ptr<transform::Rigid3d> fixed_frame_pose = Interpolate(fixed_frame_pose_data_, trajectory_id, node_data.time); if (fixed_frame_pose == nullptr) { continue; } const Constraint::Pose constraint_pose{ *fixed_frame_pose, options_.fixed_frame_pose_translation_weight(), options_.fixed_frame_pose_rotation_weight()}; if (!fixed_frame_pose_initialized) { transform::Rigid3d fixed_frame_pose_in_map; if (trajectory_data.fixed_frame_origin_in_map.has_value()) { fixed_frame_pose_in_map = trajectory_data.fixed_frame_origin_in_map.value(); } else { fixed_frame_pose_in_map = node_data.global_pose * constraint_pose.zbar_ij.inverse(); } C_fixed_frames.emplace( std::piecewise_construct, std::forward_as_tuple(trajectory_id), std::forward_as_tuple( transform::Rigid3d( fixed_frame_pose_in_map.translation(), Eigen::AngleAxisd( transform::GetYaw(fixed_frame_pose_in_map.rotation()), Eigen::Vector3d::UnitZ())), nullptr, absl::make_unique<ceres::AutoDiffLocalParameterization< YawOnlyQuaternionPlus, 4, 1>>(), &problem)); fixed_frame_pose_initialized = true; } problem.AddResidualBlock( SpaCostFunction3D::CreateAutoDiffCostFunction(constraint_pose), options_.fixed_frame_pose_use_tolerant_loss() ? new ceres::TolerantLoss( options_.fixed_frame_pose_tolerant_loss_param_a(), options_.fixed_frame_pose_tolerant_loss_param_b()) : nullptr, C_fixed_frames.at(trajectory_id).rotation(), C_fixed_frames.at(trajectory_id).translation(), C_nodes.at(node_id).rotation(), C_nodes.at(node_id).translation()); } } // Solve. ceres::Solver::Summary summary; ceres::Solve( common::CreateCeresSolverOptions(options_.ceres_solver_options()), &problem, &summary); if (options_.log_solver_summary()) { LOG(INFO) << summary.FullReport(); for (const auto& trajectory_id_and_data : trajectory_data_) { const int trajectory_id = trajectory_id_and_data.first; const TrajectoryData& trajectory_data = trajectory_id_and_data.second; if (trajectory_id != 0) { LOG(INFO) << "Trajectory " << trajectory_id << ":"; } LOG(INFO) << "Gravity was: " << trajectory_data.gravity_constant; const auto& imu_calibration = trajectory_data.imu_calibration; LOG(INFO) << "IMU correction was: " << common::RadToDeg(2. * std::acos(std::abs(imu_calibration[0]))) << " deg (" << imu_calibration[0] << ", " << imu_calibration[1] << ", " << imu_calibration[2] << ", " << imu_calibration[3] << ")"; } } // Store the result. for (const auto& C_submap_id_data : C_submaps) { submap_data_.at(C_submap_id_data.id).global_pose = C_submap_id_data.data.ToRigid(); } for (const auto& C_node_id_data : C_nodes) { node_data_.at(C_node_id_data.id).global_pose = C_node_id_data.data.ToRigid(); } for (const auto& C_fixed_frame : C_fixed_frames) { trajectory_data_.at(C_fixed_frame.first).fixed_frame_origin_in_map = C_fixed_frame.second.ToRigid(); } for (const auto& C_landmark : C_landmarks) { landmark_data_[C_landmark.first] = C_landmark.second.ToRigid(); } } std::unique_ptr<transform::Rigid3d> OptimizationProblem3D::CalculateOdometryBetweenNodes( const int trajectory_id, const NodeSpec3D& first_node_data, const NodeSpec3D& second_node_data) const { if (odometry_data_.HasTrajectory(trajectory_id)) { const std::unique_ptr<transform::Rigid3d> first_node_odometry = Interpolate(odometry_data_, trajectory_id, first_node_data.time); const std::unique_ptr<transform::Rigid3d> second_node_odometry = Interpolate(odometry_data_, trajectory_id, second_node_data.time); if (first_node_odometry != nullptr && second_node_odometry != nullptr) { const transform::Rigid3d relative_odometry = first_node_odometry->inverse() * (*second_node_odometry); return absl::make_unique<transform::Rigid3d>(relative_odometry); } } return nullptr; } } // namespace optimization } // namespace mapping } // namespace cartographer
{ "content_hash": "9ce17ab3458d5b7c2757c37bcdd64089", "timestamp": "", "source": "github", "line_count": 613, "max_line_length": 100, "avg_line_length": 42.46982055464927, "alnum_prop": 0.6395866943228087, "repo_name": "googlecartographer/cartographer", "id": "fca36d1cdd66e56a0059455eec684bc739442ddd", "size": "26642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cartographer/mapping/internal/optimization/optimization_problem_3d.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "936" }, { "name": "C", "bytes": "739" }, { "name": "C++", "bytes": "1964554" }, { "name": "CMake", "bytes": "38986" }, { "name": "Lua", "bytes": "10222" }, { "name": "Python", "bytes": "29086" }, { "name": "Shell", "bytes": "12686" }, { "name": "XSLT", "bytes": "1985" } ], "symlink_target": "" }
package com.simplefooddeliveryapp; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "SimpleFoodDeliveryApp"; } }
{ "content_hash": "8770849891ab6132e9dca934cdba3cfe", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 73, "avg_line_length": 25.8, "alnum_prop": 0.7183462532299741, "repo_name": "RobertoNovelo/SimpleFoodDeliveryApp", "id": "ab0e34202b23dba68cfcb1dead69e6e80aefef11", "size": "387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/app/src/main/java/com/simplefooddeliveryapp/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1590" }, { "name": "Java", "bytes": "1533" }, { "name": "JavaScript", "bytes": "6051" }, { "name": "Objective-C", "bytes": "4446" }, { "name": "Python", "bytes": "1752" } ], "symlink_target": "" }
// CHECKSTYLE:OFF package org.jfrog.hudson.plugins.artifactory; import org.jvnet.localizer.Localizable; import org.jvnet.localizer.ResourceBundleHolder; @SuppressWarnings({ "", "PMD" }) public class Messages { private final static ResourceBundleHolder holder = ResourceBundleHolder.get(Messages.class); /** * Allows the user to promote a build * */ public static String permission_promote() { return holder.format("permission.promote"); } /** * Allows the user to promote a build * */ public static Localizable _permission_promote() { return new Localizable(holder, "permission.promote"); } /** * Allows the user to run release builds * */ public static String permission_release() { return holder.format("permission.release"); } /** * Allows the user to run release builds * */ public static Localizable _permission_release() { return new Localizable(holder, "permission.release"); } /** * Artifactory * */ public static String permission_group() { return holder.format("permission.group"); } /** * Artifactory * */ public static Localizable _permission_group() { return new Localizable(holder, "permission.group"); } }
{ "content_hash": "5542752db8ed44ca99667b7506980f49", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 96, "avg_line_length": 21.25, "alnum_prop": 0.6161764705882353, "repo_name": "hudson3-plugins/hudson-artifactory-plugin", "id": "424bead852ecbb0fbc1daddea88dd01ae90930a0", "size": "1360", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/jfrog/hudson/plugins/artifactory/Messages.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "206900" }, { "name": "Shell", "bytes": "11354" } ], "symlink_target": "" }
import { SaoPaulo } from "../../"; export = SaoPaulo;
{ "content_hash": "701cfee36e1f44d49036b190ccc687f9", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 18.333333333333332, "alnum_prop": 0.5818181818181818, "repo_name": "georgemarshall/DefinitelyTyped", "id": "ab062913183993fdaee7fc725ae2a4e7cf1b1a0c", "size": "55", "binary": false, "copies": "30", "ref": "refs/heads/master", "path": "types/carbon__pictograms-react/lib/sao-paulo/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16338312" }, { "name": "Ruby", "bytes": "40" }, { "name": "Shell", "bytes": "73" }, { "name": "TypeScript", "bytes": "17728346" } ], "symlink_target": "" }
"""Manages daemontools-like services inside the container. For each application container there may be multiple services defined, which are controlled by skarnet.org s6 supervision suite. Application container is started in chrooted environment, and the root directory structure:: / /services/ foo/ bar/ Application container is started with the supervisor monitoring the services directory using 'svscan /services'. The svscan become the container 'init' - parent to all processes inside container. Treadmill will put svscan inside relevant cgroup hierarchy and subsystems. Once started, services are added by created subdirectory for each service. The following files are created in each directory: - run - app.sh The run file is executed by s6-supervise. The run file will perform the following actions: - setuidgid - change execution context to the proid - softlimit - part of the suite, set process limits - setlock ../../<app.name> - this will create a lock monitored by Treadmill, so that Treadmill is notified when the app exits. - exec app.sh All services will be started by Treadmill runtime using 's6-svc' utility. Each service will be started with 'svc -o' (run once) option, and Treadmill will be responsible for restart and maintaining restart count. """ from __future__ import absolute_import import glob import logging import os import stat import subprocess import time import jinja2 from . import fs from . import utils from . import subproc _LOGGER = logging.getLogger(__name__) EXEC_MODE = (stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) JINJA2_ENV = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) # s6-svc exits 111 if it cannot send a command. ERR_COMMAND = 111 # s6-svc exits 100 if no s6-supervise process is running on servicedir. ERR_NO_SUP = 100 def create_service(app_root, user, home, shell, service, runcmd, env=None, down=True, envdirs=None, as_root=True, template=None): """Initializes service directory. Creates run, finish scripts as well as log directory with appropriate run script. """ real_svc_dir = os.path.join(app_root, service) fs.mkdir_safe(real_svc_dir) with open(os.path.join(real_svc_dir, 'app_start'), 'w') as f: f.write(runcmd) if template is None: template = 'supervisor.run' cmd = '/services/{0}/app_start'.format(service) if envdirs is None: envdirs = [] utils.create_script(os.path.join(real_svc_dir, 'run'), template, service=service, user=user, home=home, shell=shell, cmd=cmd, env=env, envdirs=envdirs, as_root=as_root) utils.create_script(os.path.join(real_svc_dir, 'finish'), 'supervisor.finish', service=service, user=user, cmds=[]) if down: with open(os.path.join(real_svc_dir, 'down'), 'w'): pass def exec_root_supervisor(directory): """Execs svscan in the directory.""" subproc.exec_pid1(['s6-svscan', directory]) def start_service(app_root, service, once=True): """Starts a service in the app_root/services/service directory.""" if once: opt = '-o' else: opt = '-u' subprocess.call(['s6-svc', opt, os.path.join(app_root, service)]) def stop_service(app_root, service): """Stops the service and do not restart it.""" subprocess.call(['s6-svc', '-d', os.path.join(app_root, service)]) def kill_service(app_root, service, signal='TERM'): """Send the service the specified signal.""" signal_opts = dict([ ('STOP', '-p'), ('CONT', '-c'), ('HUP', '-h'), ('ALRM', '-a'), ('INT', '-i'), ('TERM', '-t'), ('KILL', '-k') ]) if signal not in signal_opts: utils.fatal('Unsupported signal: %s', signal) opt = signal_opts[signal] subprocess.call(['s6-svc', opt, os.path.join(app_root, service)]) def is_supervisor_running(app_root, service): """Checks if the supervisor is running.""" # svok returns 0 if supervisor is running. try: subproc.check_call(['s6-svok', os.path.join(app_root, service)], stderr=subprocess.STDOUT) return True except subprocess.CalledProcessError, err: _LOGGER.info('exit code: %d, %s', err.returncode, err.cmd) if err.output: _LOGGER.info(err.output) return False def is_running(app_root, service): """Checks if the service is running.""" return bool(get_pid(app_root, service)) def get_pid(app_root, service): """Returns pid of the service or None if the service is not running.""" output = subproc.check_output(['s6-svstat', os.path.join(app_root, service)]) return _parse_state(output).get('pid', None) def _parse_state(state): """Parses svstat output into dict. The dict will have the following attributes: - state - 'up'/'down' - intended - original state of the service when it was created. - since - time when state transition changed. - pid - pid of the process or None if state is down. """ # The structure of the output is: # # up (pid $pid) $sec seconds # up (pid $pid) $sec seconds, normally down # down $sec seconds # down $sec seconds, normally down state = state.strip() tokens = state.split(' ') actual = tokens[0] intended = actual pid = None since = int(time.time()) if actual == 'up': # remove extra ) pid = int(tokens[2][:-1]) # TODO: check if it can output time in hours (hope not). since = since - int(tokens[3]) if tokens[-1] == 'down': intended = 'down' elif actual == 'down': since = since - int(tokens[1]) if tokens[-1] == 'up': intended = 'up' return {'pid': pid, 'since': since, 'state': actual, 'intended': intended} def get_state(svcroot): """Checks the state of services under given root.""" services = glob.glob(os.path.join(svcroot, '*')) services_state = {} for service in services: state = subproc.check_output(['s6-svstat', service]) services_state[os.path.basename(service)] = _parse_state(state) return services_state def _service_wait(svcroot, up_opt, any_all_opt, timeout=0, subset=None): """Given services directory, wait for services to be in given state.""" services = glob.glob(os.path.join(svcroot, '*')) if subset is not None: services = [svc for svc in services if os.path.basename(svc) in subset] if not services: return cmdline = ['s6-svwait', up_opt, '-t', str(timeout), any_all_opt] + services # This will block until service status changes or timeout expires. subproc.check_call(cmdline) def wait_all_up(svcroot, timeout=0, subset=None): """Waits for services to be up.""" _service_wait(svcroot, up_opt='-u', any_all_opt='-a', timeout=timeout, subset=subset) def wait_all_down(svcroot, timeout=0, subset=None): """Waits for services to be up.""" _service_wait(svcroot, up_opt='-d', any_all_opt='-a', timeout=timeout, subset=subset) def wait_any_up(svcroot, timeout=0, subset=None): """Waits for services to be up.""" _service_wait(svcroot, up_opt='-u', any_all_opt='-o', timeout=timeout, subset=subset) def wait_any_down(svcroot, timeout=0, subset=None): """Waits for services to be up.""" _service_wait(svcroot, up_opt='-d', any_all_opt='-o', timeout=timeout, subset=subset) def create_environ_dir(env_dir, env): """Create environment directory for s6-envdir.""" fs.mkdir_safe(env_dir) for key, value in env.iteritems(): with open(os.path.join(env_dir, key), 'w+') as f: if value is not None: f.write(str(value))
{ "content_hash": "973562100245c186393416782135d92e", "timestamp": "", "source": "github", "line_count": 274, "max_line_length": 79, "avg_line_length": 30.204379562043794, "alnum_prop": 0.612010633156114, "repo_name": "toenuff/treadmill", "id": "d7c71261a57b51d583339596060afd20a337a04f", "size": "8276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/python/treadmill/supervisor.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Prolog", "bytes": "19323" }, { "name": "Python", "bytes": "1511919" }, { "name": "Shell", "bytes": "29014" } ], "symlink_target": "" }
package org.kaazing.k3po.driver.internal.control; import static org.kaazing.k3po.driver.internal.control.ControlMessage.Kind.DISPOSE; import java.util.Objects; public class DisposeMessage extends ControlMessage { @Override public int hashCode() { return Objects.hashCode(getKind()); } @Override public boolean equals(Object obj) { return (this == obj) || (obj instanceof DisposeMessage) && equalTo((DisposeMessage) obj); } @Override public Kind getKind() { return DISPOSE; } }
{ "content_hash": "4bae481ff11fc2f594c70cf39642690d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 97, "avg_line_length": 22.666666666666668, "alnum_prop": 0.6838235294117647, "repo_name": "dpwspoon/k3po", "id": "b96ac78b678631d1109dccd370301bd5534086ba", "size": "1171", "binary": false, "copies": "6", "ref": "refs/heads/develop", "path": "driver/src/main/java/org/kaazing/k3po/driver/internal/control/DisposeMessage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "15289" }, { "name": "Groovy", "bytes": "7958" }, { "name": "Java", "bytes": "2898362" }, { "name": "Shell", "bytes": "5109" } ], "symlink_target": "" }
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} {-# OPTIONS -Wall #-} module Main(main) where import qualified Data.Text.IO as T import Data.Typeable import Language.Paraiso.Annotation (Annotation) import Language.Paraiso.Name import Language.Paraiso.Generator (generateIO) import qualified Language.Paraiso.Generator.Native as Native import Language.Paraiso.OM import Language.Paraiso.OM.Builder import Language.Paraiso.OM.Builder.Boolean import Language.Paraiso.OM.DynValue import Language.Paraiso.OM.PrettyPrint import qualified Language.Paraiso.OM.Realm as Rlm import qualified Language.Paraiso.OM.Reduce as Reduce import Language.Paraiso.Optimization import Language.Paraiso.Prelude import Language.Paraiso.Tensor -- a dynamic representation for a local static value (an array) intDV :: DynValue intDV = DynValue{realm = Rlm.Local, typeRep = typeOf (0::Int)} -- a dynamic representation for a global static value (a single-point variable) intGDV :: DynValue intGDV = DynValue{realm = Rlm.Global, typeRep = typeOf (0::Int)} -- the list of static variables for this machine lifeVars :: [Named DynValue] lifeVars = [Named (mkName "population") intGDV] ++ [Named (mkName "generation") intGDV] ++ [Named (mkName "cell") intDV] -- adjacency vectors in Conway's game of Life adjVecs :: [Vec2 Int] adjVecs = zipWith (\x y -> Vec :~ x :~ y) [-1, 0, 1,-1, 1,-1, 0, 1] [-1,-1,-1, 0, 0, 1, 1, 1] -- R-pentomino pattern r5mino :: [Vec2 Int] r5mino = zipWith (\x y -> Vec :~ x :~ y) [ 1, 2, 0, 1, 1] [ 0, 0, 1, 1, 2] bind :: (Functor f, Monad m) => f a -> f (m a) bind = fmap return buildProceed :: Builder Vec2 Int Annotation () buildProceed = do -- load a Local variable called "cell." cell <- bind $ load Rlm.TLocal (undefined::Int) $ mkName "cell" -- load a Global variable called "generation." gen <- bind $ load Rlm.TGlobal (undefined::Int) $ mkName "generation" -- create a list of cell patterns, each shifted by an element of adjVects. neighbours <- fmap (map return) $ forM adjVecs (\v -> shift v cell) -- add them all. num <- bind $ foldl1 (+) neighbours -- The rule of Conway's game of Life. isAlive <- bind $ (cell `eq` 0) && (num `eq` 3) || (cell `eq` 1) && (num `ge` 2) && (num `le` 3) -- create the new cell state based on the judgement. newCell <- bind $ select isAlive (1::BuilderOf Rlm.TLocal Int) 0 -- count the number of alive cells and store it into "population." store (mkName "population") $ reduce Reduce.Sum newCell -- increment the generation. store (mkName "generation") $ gen + 1 -- store the new cell state. store (mkName "cell") $ newCell buildInit :: Builder Vec2 Int Annotation () buildInit = do -- create the current coordinate vector. coord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Int) axis) -- load the size of the simulation region size <- sequenceA $ compose (\axis -> bind $ loadSize Rlm.TLocal (0::Int) axis) halfSize <- sequenceA $ compose (\axis -> bind $ (size!axis) `div` 2) -- if the current coordinate equals one of the elements in r5mino, you are alive. alive <- bind $ foldl1 (||) [agree (coord - halfSize) point | point <- r5mino ] -- create the initial cell state based on the judgement. cell <- bind $ select alive (1::BuilderOf Rlm.TLocal Int) 0 -- store the initial states. store (mkName "cell") $ cell store (mkName "population") $ reduce Reduce.Sum cell store (mkName "generation") $ (0::BuilderOf Rlm.TGlobal Int) where agree coord point = foldl1 (&&) $ compose (\i -> coord!i `eq` imm (point!i)) -- compose the machine. myOM :: OM Vec2 Int Annotation myOM = optimize O3 $ makeOM (mkName "Life") [] lifeVars [(mkName "init" , buildInit), (mkName "proceed", buildProceed) ] genSetup :: Native.Setup Vec2 Int genSetup = (Native.defaultSetup $ Vec :~ 128 :~ 128) { Native.directory = "./dist/" } main :: IO () main = do -- output the intermediate state. T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM -- generate the library _ <- generateIO genSetup myOM return ()
{ "content_hash": "aa78e584f07fcfc4982c6ed1da08f7bc", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 85, "avg_line_length": 30.728571428571428, "alnum_prop": 0.6473733147373315, "repo_name": "nushio3/Paraiso", "id": "100a68675f872b88abc6c4bb2710389f0defb23c", "size": "4302", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples-old/Life-exampled/LifeMain.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3820" }, { "name": "C++", "bytes": "586056" }, { "name": "Cuda", "bytes": "557601" }, { "name": "Haskell", "bytes": "415151" }, { "name": "Makefile", "bytes": "6312" }, { "name": "Ruby", "bytes": "35353" }, { "name": "Shell", "bytes": "1757" }, { "name": "TeX", "bytes": "49440" } ], "symlink_target": "" }
<div class="row search-nav"> <div class="col-sm-4" ng-include="'app/search/ar-search-nav-toolbar.inc.html'" ></div> <div class="col-sm-4 text-center" ng-include="'app/search/ar-search-nav-pagination.inc.html'"></div> <div class="col-sm-4 text-right" ng-include="'app/search/ar-search-nav-order-menu.inc.html'" ></div> </div>
{ "content_hash": "9c62c5902ae718f9a913314bbc40f368", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 104, "avg_line_length": 48.42857142857143, "alnum_prop": 0.6696165191740413, "repo_name": "dainst/arachnefrontend", "id": "d50e82c1c9f8bfb4751c4908efc802fdb83a1135", "size": "339", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/search/ar-search-nav.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2124" }, { "name": "HTML", "bytes": "286157" }, { "name": "JavaScript", "bytes": "954490" }, { "name": "SCSS", "bytes": "43945" } ], "symlink_target": "" }
using System; using System.Composition; namespace Microsoft.CodeAnalysis.SolutionCrawler { // [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportIncrementalAnalyzerProviderAttribute : Attribute // ExportAttribute { public bool HighPriorityForActiveFile { get; } public string Name { get; } public string[] WorkspaceKinds { get; } public ExportIncrementalAnalyzerProviderAttribute(params string[] workspaceKinds) // : base(typeof(IIncrementalAnalyzerProvider)) { // TODO: this will be removed once closed side changes are in. this.WorkspaceKinds = workspaceKinds ?? throw new ArgumentNullException(nameof(workspaceKinds)); this.Name = "Unknown"; this.HighPriorityForActiveFile = false; } public ExportIncrementalAnalyzerProviderAttribute(string name, string[] workspaceKinds) // : base(typeof(IIncrementalAnalyzerProvider)) { this.WorkspaceKinds = workspaceKinds; this.Name = name ?? throw new ArgumentNullException(nameof(name)); this.HighPriorityForActiveFile = false; } public ExportIncrementalAnalyzerProviderAttribute(bool highPriorityForActiveFile, string name, string[] workspaceKinds) : this(name, workspaceKinds) { this.HighPriorityForActiveFile = highPriorityForActiveFile; } } }
{ "content_hash": "891ec0dc9e65d21ffef911859f977479", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 127, "avg_line_length": 38.71052631578947, "alnum_prop": 0.6798096532970768, "repo_name": "akrisiun/roslyn", "id": "03d3f62b40942cf40cb3f5f95f957f535bdaaf15", "size": "1633", "binary": false, "copies": "1", "ref": "refs/heads/dev16", "path": "src/Workspaces/Core/Portable/SolutionCrawler/ExportIncrementalAnalyzerProviderAttribute.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "14082" }, { "name": "C#", "bytes": "95237424" }, { "name": "C++", "bytes": "5392" }, { "name": "F#", "bytes": "3632" }, { "name": "Groovy", "bytes": "10903" }, { "name": "Makefile", "bytes": "3294" }, { "name": "PowerShell", "bytes": "105924" }, { "name": "Shell", "bytes": "8363" }, { "name": "Visual Basic", "bytes": "72868606" } ], "symlink_target": "" }
classdef LayerNoising < LayerBase % the non-linearity in a network y_i = f(x_i) properties actfunc gradfunc state droprate testing fixedmask end methods function L = LayerNoising(droprate) L.name = ['Noising']; L.droprate = droprate; L.params = []; L.testing = 0; end function output=forward(self, input) self.input = input; if ~self.testing if self.fixedmask rng(1) end self.state = 1*(rand(size(input))>self.droprate); self.output = self.state.*input; else self.output = (1-self.droprate)*input; end output=self.output; end function dLdin = backward(self, dfdo) dLdin = dfdo .* self.state; self.grad = []; end end end
{ "content_hash": "5eaac30931355f8b995cc300d40a06f9", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 65, "avg_line_length": 24.51219512195122, "alnum_prop": 0.4537313432835821, "repo_name": "sidaw/nnmat", "id": "adbe2fc253607bee9850800e4c448d263ccd74a9", "size": "1005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/layers/LayerNoising.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9687" }, { "name": "M", "bytes": "2047" }, { "name": "Mathematica", "bytes": "669" }, { "name": "Matlab", "bytes": "214564" } ], "symlink_target": "" }
var apex_restrict_shuttle_values = { toggleOption: function( option, show ) { jQuery( option ).toggle( show ); if( show ) { if( jQuery( option ).parent( 'span.toggleOption' ).length ) jQuery( option ).unwrap( ); } else { if( jQuery( option ).parent( 'span.toggleOption' ).length == 0 ) jQuery( option ).wrap( '<span class="toggleOption" style="display: none;" />' ); } }, restrict_values: function ( search_item, shuttle_item ) { console.log('perform Restrict shuttle values'); var search = apex.item(search_item).getValue(); search = search.toLowerCase(); search_words = search.split(' '); console.log('search_words=' , search_words ); var items_hidden = false; $('#'+shuttle_item+'_LEFT option').each( function() { var text = $(this).text().toLowerCase(); var visible = true; if ( search.length > 0 ) { for ( i = 0; i < search_words.length; i++) { if ( text.indexOf(search_words[i]) < 0 ) { visible = false; } } } if ( visible ) { apex_restrict_shuttle_values.toggleOption(this,true); } else { apex_restrict_shuttle_values.toggleOption(this,false); items_hidden = true; } } ); if ( items_hidden ) { $('#'+shuttle_item+'_MOVE_ALL').addClass('apex_disabled'); } else { $('#'+shuttle_item+'_MOVE_ALL').removeClass('apex_disabled'); } }, // function that gets called from plugin doIt: function() { // plugin attributes var daThis = this; var shuttle_item = daThis.affectedElements[0].id; var search_item = daThis.action.attribute01; // Logging var vLogging = true; if (vLogging) { console.log('Restrict Shuttle Values: search_item=' , search_item); console.log('Restrict Shuttle Values: shuttle_item=', shuttle_item); } apex_restrict_shuttle_values.restrict_values(search_item,shuttle_item); } };
{ "content_hash": "d83b7f330c1011d67b8fae4f5f45b92b", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 92, "avg_line_length": 29.569444444444443, "alnum_prop": 0.5481446688586191, "repo_name": "dickdral/apex-restrict-shuttle-values", "id": "bc014bf4cd6f7d0b10f9ae52c9e1e9a90309fd92", "size": "2254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/js/apex_restrict_shuttle_values.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2254" }, { "name": "SQLPL", "bytes": "9447" } ], "symlink_target": "" }
#pragma warning disable 0472 using System; using System.Text; using System.IO; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Xml.Serialization; using BLToolkit.Aspects; using BLToolkit.DataAccess; using BLToolkit.EditableObjects; using BLToolkit.Data; using BLToolkit.Data.DataProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using bv.common.Configuration; using bv.common.Enums; using bv.common.Core; using bv.model.BLToolkit; using bv.model.Model; using bv.model.Helpers; using bv.model.Model.Extenders; using bv.model.Model.Core; using bv.model.Model.Handlers; using bv.model.Model.Validators; using eidss.model.Core; using eidss.model.Enums; namespace eidss.model.Schema { [XmlType(AnonymousType = true)] public abstract partial class OrganizationLookup : EditableObject<OrganizationLookup> , IObject , IDisposable , ILookupUsage { [MapField(_str_idfInstitution), NonUpdatable, PrimaryKey] public abstract Int64 idfInstitution { get; set; } [LocalizedDisplayName(_str_name)] [MapField(_str_name)] public abstract String name { get; set; } protected String name_Original { get { return ((EditableValue<String>)((dynamic)this)._name).OriginalValue; } } protected String name_Previous { get { return ((EditableValue<String>)((dynamic)this)._name).PreviousValue; } } [LocalizedDisplayName(_str_FullName)] [MapField(_str_FullName)] public abstract String FullName { get; set; } protected String FullName_Original { get { return ((EditableValue<String>)((dynamic)this)._fullName).OriginalValue; } } protected String FullName_Previous { get { return ((EditableValue<String>)((dynamic)this)._fullName).PreviousValue; } } [LocalizedDisplayName(_str_idfsOfficeName)] [MapField(_str_idfsOfficeName)] public abstract Int64? idfsOfficeName { get; set; } protected Int64? idfsOfficeName_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsOfficeName).OriginalValue; } } protected Int64? idfsOfficeName_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsOfficeName).PreviousValue; } } [LocalizedDisplayName(_str_idfsOfficeAbbreviation)] [MapField(_str_idfsOfficeAbbreviation)] public abstract Int64? idfsOfficeAbbreviation { get; set; } protected Int64? idfsOfficeAbbreviation_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsOfficeAbbreviation).OriginalValue; } } protected Int64? idfsOfficeAbbreviation_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsOfficeAbbreviation).PreviousValue; } } [LocalizedDisplayName(_str_blnHuman)] [MapField(_str_blnHuman)] public abstract Boolean? blnHuman { get; set; } protected Boolean? blnHuman_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnHuman).OriginalValue; } } protected Boolean? blnHuman_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnHuman).PreviousValue; } } [LocalizedDisplayName(_str_blnVet)] [MapField(_str_blnVet)] public abstract Boolean? blnVet { get; set; } protected Boolean? blnVet_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnVet).OriginalValue; } } protected Boolean? blnVet_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnVet).PreviousValue; } } [LocalizedDisplayName(_str_blnLivestock)] [MapField(_str_blnLivestock)] public abstract Boolean? blnLivestock { get; set; } protected Boolean? blnLivestock_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnLivestock).OriginalValue; } } protected Boolean? blnLivestock_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnLivestock).PreviousValue; } } [LocalizedDisplayName(_str_blnAvian)] [MapField(_str_blnAvian)] public abstract Boolean? blnAvian { get; set; } protected Boolean? blnAvian_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnAvian).OriginalValue; } } protected Boolean? blnAvian_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnAvian).PreviousValue; } } [LocalizedDisplayName(_str_blnVector)] [MapField(_str_blnVector)] public abstract Boolean? blnVector { get; set; } protected Boolean? blnVector_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnVector).OriginalValue; } } protected Boolean? blnVector_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnVector).PreviousValue; } } [LocalizedDisplayName(_str_blnSyndromic)] [MapField(_str_blnSyndromic)] public abstract Boolean? blnSyndromic { get; set; } protected Boolean? blnSyndromic_Original { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnSyndromic).OriginalValue; } } protected Boolean? blnSyndromic_Previous { get { return ((EditableValue<Boolean?>)((dynamic)this)._blnSyndromic).PreviousValue; } } [LocalizedDisplayName(_str_intHACode)] [MapField(_str_intHACode)] public abstract Int32? intHACode { get; set; } protected Int32? intHACode_Original { get { return ((EditableValue<Int32?>)((dynamic)this)._intHACode).OriginalValue; } } protected Int32? intHACode_Previous { get { return ((EditableValue<Int32?>)((dynamic)this)._intHACode).PreviousValue; } } [LocalizedDisplayName(_str_idfsSite)] [MapField(_str_idfsSite)] public abstract Int64? idfsSite { get; set; } protected Int64? idfsSite_Original { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsSite).OriginalValue; } } protected Int64? idfsSite_Previous { get { return ((EditableValue<Int64?>)((dynamic)this)._idfsSite).PreviousValue; } } [LocalizedDisplayName(_str_strOrganizationID)] [MapField(_str_strOrganizationID)] public abstract String strOrganizationID { get; set; } protected String strOrganizationID_Original { get { return ((EditableValue<String>)((dynamic)this)._strOrganizationID).OriginalValue; } } protected String strOrganizationID_Previous { get { return ((EditableValue<String>)((dynamic)this)._strOrganizationID).PreviousValue; } } [LocalizedDisplayName(_str_intRowStatus)] [MapField(_str_intRowStatus)] public abstract Int32 intRowStatus { get; set; } protected Int32 intRowStatus_Original { get { return ((EditableValue<Int32>)((dynamic)this)._intRowStatus).OriginalValue; } } protected Int32 intRowStatus_Previous { get { return ((EditableValue<Int32>)((dynamic)this)._intRowStatus).PreviousValue; } } #region Set/Get values #region filed_info definifion protected class field_info { internal string _name; internal string _formname; internal string _type; internal Func<OrganizationLookup, object> _get_func; internal Action<OrganizationLookup, string> _set_func; internal Action<OrganizationLookup, OrganizationLookup, CompareModel> _compare_func; } internal const string _str_Parent = "Parent"; internal const string _str_IsNew = "IsNew"; internal const string _str_idfInstitution = "idfInstitution"; internal const string _str_name = "name"; internal const string _str_FullName = "FullName"; internal const string _str_idfsOfficeName = "idfsOfficeName"; internal const string _str_idfsOfficeAbbreviation = "idfsOfficeAbbreviation"; internal const string _str_blnHuman = "blnHuman"; internal const string _str_blnVet = "blnVet"; internal const string _str_blnLivestock = "blnLivestock"; internal const string _str_blnAvian = "blnAvian"; internal const string _str_blnVector = "blnVector"; internal const string _str_blnSyndromic = "blnSyndromic"; internal const string _str_intHACode = "intHACode"; internal const string _str_idfsSite = "idfsSite"; internal const string _str_strOrganizationID = "strOrganizationID"; internal const string _str_intRowStatus = "intRowStatus"; private static readonly field_info[] _field_infos = { new field_info { _name = _str_idfInstitution, _formname = _str_idfInstitution, _type = "Int64", _get_func = o => o.idfInstitution, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64(val); if (o.idfInstitution != newval) o.idfInstitution = newval; }, _compare_func = (o, c, m) => { if (o.idfInstitution != c.idfInstitution || o.IsRIRPropChanged(_str_idfInstitution, c)) m.Add(_str_idfInstitution, o.ObjectIdent + _str_idfInstitution, o.ObjectIdent2 + _str_idfInstitution, o.ObjectIdent3 + _str_idfInstitution, "Int64", o.idfInstitution == null ? "" : o.idfInstitution.ToString(), o.IsReadOnly(_str_idfInstitution), o.IsInvisible(_str_idfInstitution), o.IsRequired(_str_idfInstitution)); } }, new field_info { _name = _str_name, _formname = _str_name, _type = "String", _get_func = o => o.name, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.name != newval) o.name = newval; }, _compare_func = (o, c, m) => { if (o.name != c.name || o.IsRIRPropChanged(_str_name, c)) m.Add(_str_name, o.ObjectIdent + _str_name, o.ObjectIdent2 + _str_name, o.ObjectIdent3 + _str_name, "String", o.name == null ? "" : o.name.ToString(), o.IsReadOnly(_str_name), o.IsInvisible(_str_name), o.IsRequired(_str_name)); } }, new field_info { _name = _str_FullName, _formname = _str_FullName, _type = "String", _get_func = o => o.FullName, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.FullName != newval) o.FullName = newval; }, _compare_func = (o, c, m) => { if (o.FullName != c.FullName || o.IsRIRPropChanged(_str_FullName, c)) m.Add(_str_FullName, o.ObjectIdent + _str_FullName, o.ObjectIdent2 + _str_FullName, o.ObjectIdent3 + _str_FullName, "String", o.FullName == null ? "" : o.FullName.ToString(), o.IsReadOnly(_str_FullName), o.IsInvisible(_str_FullName), o.IsRequired(_str_FullName)); } }, new field_info { _name = _str_idfsOfficeName, _formname = _str_idfsOfficeName, _type = "Int64?", _get_func = o => o.idfsOfficeName, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsOfficeName != newval) o.idfsOfficeName = newval; }, _compare_func = (o, c, m) => { if (o.idfsOfficeName != c.idfsOfficeName || o.IsRIRPropChanged(_str_idfsOfficeName, c)) m.Add(_str_idfsOfficeName, o.ObjectIdent + _str_idfsOfficeName, o.ObjectIdent2 + _str_idfsOfficeName, o.ObjectIdent3 + _str_idfsOfficeName, "Int64?", o.idfsOfficeName == null ? "" : o.idfsOfficeName.ToString(), o.IsReadOnly(_str_idfsOfficeName), o.IsInvisible(_str_idfsOfficeName), o.IsRequired(_str_idfsOfficeName)); } }, new field_info { _name = _str_idfsOfficeAbbreviation, _formname = _str_idfsOfficeAbbreviation, _type = "Int64?", _get_func = o => o.idfsOfficeAbbreviation, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsOfficeAbbreviation != newval) o.idfsOfficeAbbreviation = newval; }, _compare_func = (o, c, m) => { if (o.idfsOfficeAbbreviation != c.idfsOfficeAbbreviation || o.IsRIRPropChanged(_str_idfsOfficeAbbreviation, c)) m.Add(_str_idfsOfficeAbbreviation, o.ObjectIdent + _str_idfsOfficeAbbreviation, o.ObjectIdent2 + _str_idfsOfficeAbbreviation, o.ObjectIdent3 + _str_idfsOfficeAbbreviation, "Int64?", o.idfsOfficeAbbreviation == null ? "" : o.idfsOfficeAbbreviation.ToString(), o.IsReadOnly(_str_idfsOfficeAbbreviation), o.IsInvisible(_str_idfsOfficeAbbreviation), o.IsRequired(_str_idfsOfficeAbbreviation)); } }, new field_info { _name = _str_blnHuman, _formname = _str_blnHuman, _type = "Boolean?", _get_func = o => o.blnHuman, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnHuman != newval) o.blnHuman = newval; }, _compare_func = (o, c, m) => { if (o.blnHuman != c.blnHuman || o.IsRIRPropChanged(_str_blnHuman, c)) m.Add(_str_blnHuman, o.ObjectIdent + _str_blnHuman, o.ObjectIdent2 + _str_blnHuman, o.ObjectIdent3 + _str_blnHuman, "Boolean?", o.blnHuman == null ? "" : o.blnHuman.ToString(), o.IsReadOnly(_str_blnHuman), o.IsInvisible(_str_blnHuman), o.IsRequired(_str_blnHuman)); } }, new field_info { _name = _str_blnVet, _formname = _str_blnVet, _type = "Boolean?", _get_func = o => o.blnVet, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnVet != newval) o.blnVet = newval; }, _compare_func = (o, c, m) => { if (o.blnVet != c.blnVet || o.IsRIRPropChanged(_str_blnVet, c)) m.Add(_str_blnVet, o.ObjectIdent + _str_blnVet, o.ObjectIdent2 + _str_blnVet, o.ObjectIdent3 + _str_blnVet, "Boolean?", o.blnVet == null ? "" : o.blnVet.ToString(), o.IsReadOnly(_str_blnVet), o.IsInvisible(_str_blnVet), o.IsRequired(_str_blnVet)); } }, new field_info { _name = _str_blnLivestock, _formname = _str_blnLivestock, _type = "Boolean?", _get_func = o => o.blnLivestock, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnLivestock != newval) o.blnLivestock = newval; }, _compare_func = (o, c, m) => { if (o.blnLivestock != c.blnLivestock || o.IsRIRPropChanged(_str_blnLivestock, c)) m.Add(_str_blnLivestock, o.ObjectIdent + _str_blnLivestock, o.ObjectIdent2 + _str_blnLivestock, o.ObjectIdent3 + _str_blnLivestock, "Boolean?", o.blnLivestock == null ? "" : o.blnLivestock.ToString(), o.IsReadOnly(_str_blnLivestock), o.IsInvisible(_str_blnLivestock), o.IsRequired(_str_blnLivestock)); } }, new field_info { _name = _str_blnAvian, _formname = _str_blnAvian, _type = "Boolean?", _get_func = o => o.blnAvian, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnAvian != newval) o.blnAvian = newval; }, _compare_func = (o, c, m) => { if (o.blnAvian != c.blnAvian || o.IsRIRPropChanged(_str_blnAvian, c)) m.Add(_str_blnAvian, o.ObjectIdent + _str_blnAvian, o.ObjectIdent2 + _str_blnAvian, o.ObjectIdent3 + _str_blnAvian, "Boolean?", o.blnAvian == null ? "" : o.blnAvian.ToString(), o.IsReadOnly(_str_blnAvian), o.IsInvisible(_str_blnAvian), o.IsRequired(_str_blnAvian)); } }, new field_info { _name = _str_blnVector, _formname = _str_blnVector, _type = "Boolean?", _get_func = o => o.blnVector, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnVector != newval) o.blnVector = newval; }, _compare_func = (o, c, m) => { if (o.blnVector != c.blnVector || o.IsRIRPropChanged(_str_blnVector, c)) m.Add(_str_blnVector, o.ObjectIdent + _str_blnVector, o.ObjectIdent2 + _str_blnVector, o.ObjectIdent3 + _str_blnVector, "Boolean?", o.blnVector == null ? "" : o.blnVector.ToString(), o.IsReadOnly(_str_blnVector), o.IsInvisible(_str_blnVector), o.IsRequired(_str_blnVector)); } }, new field_info { _name = _str_blnSyndromic, _formname = _str_blnSyndromic, _type = "Boolean?", _get_func = o => o.blnSyndromic, _set_func = (o, val) => { var newval = ParsingHelper.ParseBooleanNullable(val); if (o.blnSyndromic != newval) o.blnSyndromic = newval; }, _compare_func = (o, c, m) => { if (o.blnSyndromic != c.blnSyndromic || o.IsRIRPropChanged(_str_blnSyndromic, c)) m.Add(_str_blnSyndromic, o.ObjectIdent + _str_blnSyndromic, o.ObjectIdent2 + _str_blnSyndromic, o.ObjectIdent3 + _str_blnSyndromic, "Boolean?", o.blnSyndromic == null ? "" : o.blnSyndromic.ToString(), o.IsReadOnly(_str_blnSyndromic), o.IsInvisible(_str_blnSyndromic), o.IsRequired(_str_blnSyndromic)); } }, new field_info { _name = _str_intHACode, _formname = _str_intHACode, _type = "Int32?", _get_func = o => o.intHACode, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt32Nullable(val); if (o.intHACode != newval) o.intHACode = newval; }, _compare_func = (o, c, m) => { if (o.intHACode != c.intHACode || o.IsRIRPropChanged(_str_intHACode, c)) m.Add(_str_intHACode, o.ObjectIdent + _str_intHACode, o.ObjectIdent2 + _str_intHACode, o.ObjectIdent3 + _str_intHACode, "Int32?", o.intHACode == null ? "" : o.intHACode.ToString(), o.IsReadOnly(_str_intHACode), o.IsInvisible(_str_intHACode), o.IsRequired(_str_intHACode)); } }, new field_info { _name = _str_idfsSite, _formname = _str_idfsSite, _type = "Int64?", _get_func = o => o.idfsSite, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt64Nullable(val); if (o.idfsSite != newval) o.idfsSite = newval; }, _compare_func = (o, c, m) => { if (o.idfsSite != c.idfsSite || o.IsRIRPropChanged(_str_idfsSite, c)) m.Add(_str_idfsSite, o.ObjectIdent + _str_idfsSite, o.ObjectIdent2 + _str_idfsSite, o.ObjectIdent3 + _str_idfsSite, "Int64?", o.idfsSite == null ? "" : o.idfsSite.ToString(), o.IsReadOnly(_str_idfsSite), o.IsInvisible(_str_idfsSite), o.IsRequired(_str_idfsSite)); } }, new field_info { _name = _str_strOrganizationID, _formname = _str_strOrganizationID, _type = "String", _get_func = o => o.strOrganizationID, _set_func = (o, val) => { var newval = ParsingHelper.ParseString(val); if (o.strOrganizationID != newval) o.strOrganizationID = newval; }, _compare_func = (o, c, m) => { if (o.strOrganizationID != c.strOrganizationID || o.IsRIRPropChanged(_str_strOrganizationID, c)) m.Add(_str_strOrganizationID, o.ObjectIdent + _str_strOrganizationID, o.ObjectIdent2 + _str_strOrganizationID, o.ObjectIdent3 + _str_strOrganizationID, "String", o.strOrganizationID == null ? "" : o.strOrganizationID.ToString(), o.IsReadOnly(_str_strOrganizationID), o.IsInvisible(_str_strOrganizationID), o.IsRequired(_str_strOrganizationID)); } }, new field_info { _name = _str_intRowStatus, _formname = _str_intRowStatus, _type = "Int32", _get_func = o => o.intRowStatus, _set_func = (o, val) => { var newval = ParsingHelper.ParseInt32(val); if (o.intRowStatus != newval) o.intRowStatus = newval; }, _compare_func = (o, c, m) => { if (o.intRowStatus != c.intRowStatus || o.IsRIRPropChanged(_str_intRowStatus, c)) m.Add(_str_intRowStatus, o.ObjectIdent + _str_intRowStatus, o.ObjectIdent2 + _str_intRowStatus, o.ObjectIdent3 + _str_intRowStatus, "Int32", o.intRowStatus == null ? "" : o.intRowStatus.ToString(), o.IsReadOnly(_str_intRowStatus), o.IsInvisible(_str_intRowStatus), o.IsRequired(_str_intRowStatus)); } }, new field_info() }; #endregion private string _getType(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? "" : i._type; } private object _getValue(string name) { var i = _field_infos.FirstOrDefault(n => n._name == name); return i == null ? null : i._get_func(this); } private void _setValue(string name, string val) { var i = _field_infos.FirstOrDefault(n => n._name == name); if (i != null) i._set_func(this, val); } internal CompareModel _compare(IObject o, CompareModel ret) { if (ret == null) ret = new CompareModel(); if (o == null) return ret; OrganizationLookup obj = (OrganizationLookup)o; foreach (var i in _field_infos) if (i != null && i._compare_func != null) i._compare_func(this, obj, ret); return ret; } #endregion private BvSelectList _getList(string name) { return null; } protected CacheScope m_CS; protected Accessor _getAccessor() { return Accessor.Instance(m_CS); } private IObjectPermissions m_permissions = null; internal IObjectPermissions _permissions { get { return m_permissions; } set { m_permissions = value; } } internal string m_ObjectName = "OrganizationLookup"; #region Parent and Clone supporting [XmlIgnore] public IObject Parent { get { return m_Parent; } set { m_Parent = value; /*OnPropertyChanged(_str_Parent);*/ } } private IObject m_Parent; internal void _setParent() { } partial void Cloned(); partial void ClonedWithSetup(); public override object Clone() { var ret = base.Clone() as OrganizationLookup; ret.Cloned(); ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret._setParent(); if (this.IsDirty && !ret.IsDirty) ret.SetChange(); else if (!this.IsDirty && ret.IsDirty) ret.RejectChanges(); return ret; } public IObject CloneWithSetup(DbManagerProxy manager, bool bRestricted = false) { var ret = base.Clone() as OrganizationLookup; ret.m_Parent = this.Parent; ret.m_IsMarkedToDelete = this.m_IsMarkedToDelete; ret.m_IsForcedToDelete = this.m_IsForcedToDelete; ret.m_IsNew = this.IsNew; ret.m_ObjectName = this.m_ObjectName; Accessor.Instance(null)._SetupLoad(manager, ret, true); ret.ClonedWithSetup(); ret.DeepAcceptChanges(); ret._setParent(); ret._permissions = _permissions; return ret; } public OrganizationLookup CloneWithSetup() { using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance)) { return CloneWithSetup(manager) as OrganizationLookup; } } #endregion #region IObject implementation public object Key { get { return idfInstitution; } } public string KeyName { get { return "idfInstitution"; } } public string ToStringProp { get { return ToString(); } } private bool m_IsNew; public bool IsNew { get { return m_IsNew; } } [XmlIgnore] [LocalizedDisplayName("HasChanges")] public bool HasChanges { get { return IsDirty ; } } public new void RejectChanges() { base.RejectChanges(); } public void DeepRejectChanges() { RejectChanges(); } public void DeepAcceptChanges() { AcceptChanges(); } private bool m_bForceDirty; public override void AcceptChanges() { m_bForceDirty = false; base.AcceptChanges(); } [XmlIgnore] [LocalizedDisplayName("IsDirty")] public override bool IsDirty { get { return m_bForceDirty || base.IsDirty; } } public void SetChange() { m_bForceDirty = true; } public void DeepSetChange() { SetChange(); } public bool MarkToDelete() { return _Delete(false); } public string ObjectName { get { return m_ObjectName; } } public string ObjectIdent { get { return ObjectName + "_" + Key.ToString() + "_"; } } public string ObjectIdent2 { get { return ObjectIdent; } } public string ObjectIdent3 { get { return ObjectIdent; } } public IObjectAccessor GetAccessor() { return _getAccessor(); } public IObjectPermissions GetPermissions() { return _permissions; } private IObjectEnvironment _environment; public IObjectEnvironment Environment { get { return _environment; } set { _environment = value; } } public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } public bool IsReadOnly(string name) { return _isReadOnly(name); } public bool IsInvisible(string name) { return _isInvisible(name); } public bool IsRequired(string name) { return _isRequired(m_isRequired, name); } public bool IsHiddenPersonalData(string name) { return _isHiddenPersonalData(name); } public string GetType(string name) { return _getType(name); } public object GetValue(string name) { return _getValue(name); } public void SetValue(string name, string val) { _setValue(name, val); } public CompareModel Compare(IObject o) { return _compare(o, null); } public BvSelectList GetList(string name) { return _getList(name); } public event ValidationEvent Validation; public event ValidationEvent ValidationEnd; public event AfterPostEvent AfterPost; public Dictionary<string, string> GetFieldTags(string name) { return null; } #endregion private bool IsRIRPropChanged(string fld, OrganizationLookup c) { return IsReadOnly(fld) != c.IsReadOnly(fld) || IsInvisible(fld) != c.IsInvisible(fld) || IsRequired(fld) != c._isRequired(m_isRequired, fld); } public override string ToString() { return new Func<OrganizationLookup, string>(c => c.name)(this); } public OrganizationLookup() { } partial void Changed(string fieldName); partial void Created(DbManagerProxy manager); partial void Loaded(DbManagerProxy manager); partial void Deleted(); partial void ParsedFormCollection(NameValueCollection form); private bool m_IsForcedToDelete; [LocalizedDisplayName("IsForcedToDelete")] public bool IsForcedToDelete { get { return m_IsForcedToDelete; } } private bool m_IsMarkedToDelete; [LocalizedDisplayName("IsMarkedToDelete")] public bool IsMarkedToDelete { get { return m_IsMarkedToDelete; } } public void _SetupMainHandler() { PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(OrganizationLookup_PropertyChanged); } public void _RevokeMainHandler() { PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(OrganizationLookup_PropertyChanged); } private void OrganizationLookup_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { (sender as OrganizationLookup).Changed(e.PropertyName); } public bool ForceToDelete() { return _Delete(true); } internal bool _Delete(bool isForceDelete) { if (!_ValidateOnDelete()) return false; _DeletingExtenders(); m_IsMarkedToDelete = true; m_IsForcedToDelete = m_IsForcedToDelete ? m_IsForcedToDelete : isForceDelete; OnPropertyChanged("IsMarkedToDelete"); _DeletedExtenders(); Deleted(); return true; } private bool _ValidateOnDelete(bool bReport = true) { return true; } private void _DeletingExtenders() { OrganizationLookup obj = this; } private void _DeletedExtenders() { OrganizationLookup obj = this; } public bool OnValidation(ValidationModelException ex) { if (Validation != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); Validation(this, args); return args.Continue; } return false; } public bool OnValidationEnd(ValidationModelException ex) { if (ValidationEnd != null) { var args = new ValidationEventArgs(ex.MessageId, ex.FieldName, ex.PropertyName, ex.Pars, ex.ValidatorType, ex.Obj, ex.ShouldAsk); ValidationEnd(this, args); return args.Continue; } return false; } public void OnAfterPost() { if (AfterPost != null) { AfterPost(this, EventArgs.Empty); } } public FormSize FormSize { get { return FormSize.Undefined; } } private bool _isInvisible(string name) { return false; } private bool _isReadOnly(string name) { return ReadOnly; } private bool m_readOnly; private bool _readOnly { get { return m_readOnly; } set { m_readOnly = value; } } internal Dictionary<string, Func<OrganizationLookup, bool>> m_isRequired; private bool _isRequired(Dictionary<string, Func<OrganizationLookup, bool>> isRequiredDict, string name) { if (isRequiredDict != null && isRequiredDict.ContainsKey(name)) return isRequiredDict[name](this); return false; } public void AddRequired(string name, Func<OrganizationLookup, bool> func) { if (m_isRequired == null) m_isRequired = new Dictionary<string, Func<OrganizationLookup, bool>>(); if (!m_isRequired.ContainsKey(name)) m_isRequired.Add(name, func); } internal Dictionary<string, Func<OrganizationLookup, bool>> m_isHiddenPersonalData; private bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData != null && m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name](this); return false; } public void AddHiddenPersonalData(string name, Func<OrganizationLookup, bool> func) { if (m_isHiddenPersonalData == null) m_isHiddenPersonalData = new Dictionary<string, Func<OrganizationLookup, bool>>(); if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, func); } #region IDisposable Members private bool bIsDisposed; ~OrganizationLookup() { Dispose(); } public void Dispose() { if (!bIsDisposed) { bIsDisposed = true; } } #endregion #region ILookupUsage Members public void ReloadLookupItem(DbManagerProxy manager, string lookup_object) { } #endregion public void ParseFormCollection(NameValueCollection form, bool bParseLookups = true, bool bParseRelations = true) { if (bParseLookups) { _field_infos.Where(i => i._type == "Lookup").ToList().ForEach(a => { if (form[ObjectIdent + a._formname] != null) a._set_func(this, form[ObjectIdent + a._formname]);} ); } _field_infos.Where(i => i._type != "Lookup" && i._type != "Child" && i._type != "Relation" && i._type != null) .ToList().ForEach(a => { if (form.AllKeys.Contains(ObjectIdent + a._formname)) a._set_func(this, form[ObjectIdent + a._formname]);} ); if (bParseRelations) { } ParsedFormCollection(form); } #region Accessor public abstract partial class Accessor : DataAccessor<OrganizationLookup> , IObjectAccessor , IObjectMeta , IObjectValidator , IObjectCreator , IObjectCreator<OrganizationLookup> { #region IObjectAccessor public string KeyName { get { return "idfInstitution"; } } #endregion private delegate void on_action(OrganizationLookup obj); private static Accessor g_Instance = CreateInstance<Accessor>(); private CacheScope m_CS; public static Accessor Instance(CacheScope cs) { if (cs == null) return g_Instance; lock(cs) { object acc = cs.Get(typeof (Accessor)); if (acc != null) { return acc as Accessor; } Accessor ret = CreateInstance<Accessor>(); ret.m_CS = cs; cs.Add(typeof(Accessor), ret); return ret; } } [InstanceCache(typeof(BvCacheAspect))] public virtual List<OrganizationLookup> SelectLookupList(DbManagerProxy manager , Int64? ID , Int32? intHACode ) { return _SelectList(manager , ID , intHACode , null, null ); } public static string GetLookupTableName(string method) { return "Organization"; } public virtual List<OrganizationLookup> SelectList(DbManagerProxy manager , Int64? ID , Int32? intHACode ) { return _SelectList(manager , ID , intHACode , delegate(OrganizationLookup obj) { } , delegate(OrganizationLookup obj) { } ); } private List<OrganizationLookup> _SelectList(DbManagerProxy manager , Int64? ID , Int32? intHACode , on_action loading, on_action loaded ) { try { MapResultSet[] sets = new MapResultSet[1]; List<OrganizationLookup> objs = new List<OrganizationLookup>(); sets[0] = new MapResultSet(typeof(OrganizationLookup), objs); manager .SetSpCommand("spOrganization_SelectLookup" , manager.Parameter("@ID", ID) , manager.Parameter("@intHACode", intHACode) , manager.Parameter("@LangID", ModelUserContext.CurrentLanguage) ) .ExecuteResultSet(sets); foreach(var obj in objs) { obj.m_CS = m_CS; if (loading != null) loading(obj); _SetupLoad(manager, obj); if (loaded != null) loaded(obj); } return objs; } catch(DataException e) { throw DbModelException.Create(e); } } internal void _SetupLoad(DbManagerProxy manager, OrganizationLookup obj, bool bCloning = false) { if (obj == null) return; // loading extenters - begin // loading extenters - end if (!bCloning) { } _LoadLookups(manager, obj); obj._setParent(); // loaded extenters - begin // loaded extenters - end _SetupHandlers(obj); _SetupChildHandlers(obj, null); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); obj._SetupMainHandler(); obj.AcceptChanges(); } internal void _SetPermitions(IObjectPermissions permissions, OrganizationLookup obj) { if (obj != null) { obj._permissions = permissions; if (obj._permissions != null) { } } } private OrganizationLookup _CreateNew(DbManagerProxy manager, IObject Parent, int? HACode, on_action creating, on_action created, bool isFake = false) { try { OrganizationLookup obj = OrganizationLookup.CreateInstance(); obj.m_CS = m_CS; obj.m_IsNew = true; obj.Parent = Parent; if (creating != null) creating(obj); // creating extenters - begin // creating extenters - end _LoadLookups(manager, obj); _SetupHandlers(obj); _SetupChildHandlers(obj, null); obj._SetupMainHandler(); obj._setParent(); // created extenters - begin // created extenters - end if (created != null) created(obj); obj.Created(manager); _SetPermitions(obj._permissions, obj); _SetupRequired(obj); _SetupPersonalDataRestrictions(obj); return obj; } catch(DataException e) { throw DbModelException.Create(e); } } public OrganizationLookup CreateNewT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public IObject CreateNew(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null); } public OrganizationLookup CreateFakeT(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public IObject CreateFake(DbManagerProxy manager, IObject Parent, int? HACode = null) { return _CreateNew(manager, Parent, HACode, null, null, true); } public OrganizationLookup CreateWithParamsT(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } public IObject CreateWithParams(DbManagerProxy manager, IObject Parent, List<object> pars) { return _CreateNew(manager, Parent, null, null, null); } private void _SetupChildHandlers(OrganizationLookup obj, object newobj) { } private void _SetupHandlers(OrganizationLookup obj) { } private void _LoadLookups(DbManagerProxy manager, OrganizationLookup obj) { } public bool Post(DbManagerProxy manager, IObject obj, bool bChildObject = false) { throw new NotImplementedException(); } protected ValidationModelException ChainsValidate(OrganizationLookup obj) { return null; } protected bool ChainsValidate(OrganizationLookup obj, bool bRethrowException) { ValidationModelException ex = ChainsValidate(obj); if (ex != null) { if (bRethrowException) throw ex; if (!obj.OnValidation(ex)) { obj.OnValidationEnd(ex); return false; } } return true; } public bool Validate(DbManagerProxy manager, IObject obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { return Validate(manager, obj as OrganizationLookup, bPostValidation, bChangeValidation, bDeepValidation, bRethrowException); } public bool Validate(DbManagerProxy manager, OrganizationLookup obj, bool bPostValidation, bool bChangeValidation, bool bDeepValidation, bool bRethrowException = false) { if (!ChainsValidate(obj, bRethrowException)) return false; return true; } private void _SetupRequired(OrganizationLookup obj) { } private void _SetupPersonalDataRestrictions(OrganizationLookup obj) { } #region IObjectMeta public int? MaxSize(string name) { return Meta.Sizes.ContainsKey(name) ? (int?)Meta.Sizes[name] : null; } public bool RequiredByField(string name, IObject obj) { return Meta.RequiredByField.ContainsKey(name) ? Meta.RequiredByField[name](obj as OrganizationLookup) : false; } public bool RequiredByProperty(string name, IObject obj) { return Meta.RequiredByProperty.ContainsKey(name) ? Meta.RequiredByProperty[name](obj as OrganizationLookup) : false; } public List<SearchPanelMetaItem> SearchPanelMeta { get { return Meta.SearchPanelMeta; } } public List<GridMetaItem> GridMeta { get { return Meta.GridMeta; } } public List<ActionMetaItem> Actions { get { return Meta.Actions; } } public string DetailPanel { get { return "OrganizationLookupDetail"; } } public string HelpIdWin { get { return ""; } } public string HelpIdWeb { get { return ""; } } public string HelpIdHh { get { return ""; } } #endregion } #region Meta public static class Meta { public static string spSelect = "spOrganization_SelectLookup"; public static string spCount = ""; public static string spPost = ""; public static string spInsert = ""; public static string spUpdate = ""; public static string spDelete = ""; public static string spCanDelete = ""; public static Dictionary<string, int> Sizes = new Dictionary<string, int>(); public static Dictionary<string, Func<OrganizationLookup, bool>> RequiredByField = new Dictionary<string, Func<OrganizationLookup, bool>>(); public static Dictionary<string, Func<OrganizationLookup, bool>> RequiredByProperty = new Dictionary<string, Func<OrganizationLookup, bool>>(); public static List<SearchPanelMetaItem> SearchPanelMeta = new List<SearchPanelMetaItem>(); public static List<GridMetaItem> GridMeta = new List<GridMetaItem>(); public static List<ActionMetaItem> Actions = new List<ActionMetaItem>(); private static Dictionary<string, List<Func<bool>>> m_isHiddenPersonalData = new Dictionary<string, List<Func<bool>>>(); internal static bool _isHiddenPersonalData(string name) { if (m_isHiddenPersonalData.ContainsKey(name)) return m_isHiddenPersonalData[name].Aggregate(false, (s,c) => s | c()); return false; } private static void AddHiddenPersonalData(string name, Func<bool> func) { if (!m_isHiddenPersonalData.ContainsKey(name)) m_isHiddenPersonalData.Add(name, new List<Func<bool>>()); m_isHiddenPersonalData[name].Add(func); } static Meta() { Sizes.Add(_str_name, 2000); Sizes.Add(_str_FullName, 2000); Sizes.Add(_str_strOrganizationID, 100); Actions.Add(new ActionMetaItem( "Create", ActionTypes.Create, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, Accessor.Instance(null).CreateWithParams(manager, c, pars)), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCreate_Id", "add", /*from BvMessages*/"tooltipCreate_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipCreate_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Save", ActionTypes.Save, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<OrganizationLookup>().Post(manager, (OrganizationLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strSave_Id", "Save", /*from BvMessages*/"tooltipSave_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipSave_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Ok", ActionTypes.Ok, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(ObjectAccessor.PostInterface<OrganizationLookup>().Post(manager, (OrganizationLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipOK_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipOK_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Cancel", ActionTypes.Cancel, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(true, c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strCancel_Id", "", /*from BvMessages*/"tooltipCancel_Id", /*from BvMessages*/"strOK_Id", "", /*from BvMessages*/"tooltipCancel_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, null, null, null, false )); Actions.Add(new ActionMetaItem( "Delete", ActionTypes.Delete, false, String.Empty, String.Empty, (manager, c, pars) => new ActResult(((OrganizationLookup)c).MarkToDelete() && ObjectAccessor.PostInterface<OrganizationLookup>().Post(manager, (OrganizationLookup)c), c), null, new ActionMetaItem.VisualItem( /*from BvMessages*/"strDelete_Id", "Delete_Remove", /*from BvMessages*/"tooltipDelete_Id", /*from BvMessages*/"", "", /*from BvMessages*/"tooltipDelete_Id", ActionsAlignment.Right, ActionsPanelType.Main, ActionsAppType.All ), false, null, null, (o, p, r) => r && !o.IsNew && !o.HasChanges, null, null, false )); _SetupPersonalDataRestrictions(); } private static void _SetupPersonalDataRestrictions() { } } #endregion #endregion } }
{ "content_hash": "62349ed8c7aa94968ac0b3a1c7ea563c", "timestamp": "", "source": "github", "line_count": 1237, "max_line_length": 200, "avg_line_length": 44.92724333063864, "alnum_prop": 0.512280701754386, "repo_name": "EIDSS/EIDSS-Legacy", "id": "78bee7cdc7fa9626946d133d9c11cfcf122e54f2", "size": "55577", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EIDSS v6/eidss.model/Schema/OrganizationLookup.model.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "256377" }, { "name": "Batchfile", "bytes": "30009" }, { "name": "C#", "bytes": "106160789" }, { "name": "CSS", "bytes": "833586" }, { "name": "HTML", "bytes": "7507" }, { "name": "Java", "bytes": "2188690" }, { "name": "JavaScript", "bytes": "17000221" }, { "name": "PLSQL", "bytes": "2499" }, { "name": "PLpgSQL", "bytes": "6422" }, { "name": "Pascal", "bytes": "159898" }, { "name": "PowerShell", "bytes": "339522" }, { "name": "Puppet", "bytes": "3758" }, { "name": "SQLPL", "bytes": "12198" }, { "name": "Smalltalk", "bytes": "301266" }, { "name": "Visual Basic", "bytes": "20819564" }, { "name": "XSLT", "bytes": "4253600" } ], "symlink_target": "" }
<html> <head> <meta charset="ISO8859-1"> <title>Typo.js English Test Suite</title> <link rel="stylesheet" href="lib/qunit.css" type="text/css" media="screen" /> <script type="text/javascript" src="lib/jquery-1.9.1.js"></script> <script type="text/javascript" src="lib/qunit.js"></script> <script type="text/javascript" src="../typo/typo.js"></script> <script type="text/javascript" src="english.js"></script> </head> <body> <h1 id="qunit-header">Typo.js English Test Suite</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> </body> </html>
{ "content_hash": "51c07bb288cf98533f5e32d184c912d3", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 79, "avg_line_length": 36.05555555555556, "alnum_prop": 0.6563944530046225, "repo_name": "yangli1990/Typo.js", "id": "15d8f241384109d775400a0e541097ef9b9b1224", "size": "649", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/english.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4525" }, { "name": "HTML", "bytes": "3656" }, { "name": "JavaScript", "bytes": "80914" } ], "symlink_target": "" }
package org.burroloco.butcher.fixture.http; import edge.org.apache.commons.io.IOUtilsStatic; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_OK; public class StringHandler extends AbstractHandler { private List<HttpRequest> requests = new ArrayList<HttpRequest>(); IOUtilsStatic io; // OK ThrowsCount { public void handle(String s, Request r, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String payload = getPayload(req); requests.add(new HttpRequest(r.getParameterMap(), payload)); if (error(req)) handleError(resp); else resp.setStatus(SC_OK); r.setHandled(true); } // } private String getPayload(HttpServletRequest req) throws IOException { ServletInputStream is = req.getInputStream(); byte[] data = io.toByteArray(is); return new String(data, "UTF-8"); } private boolean error(HttpServletRequest req) { StringBuffer b = req.getRequestURL(); String url = b.toString(); return url.contains("error"); } private void handleError(HttpServletResponse resp) { resp.setStatus(SC_INTERNAL_SERVER_ERROR); } public List<HttpRequest> getRequests() { return requests; } }
{ "content_hash": "413e9d86faa09aa4a6179b9616f4e34b", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 78, "avg_line_length": 31.526315789473685, "alnum_prop": 0.6917084028937117, "repo_name": "dbastin/donkey", "id": "d09bfddbb2867b4b7bd393e236802d2623314b3a", "size": "1797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/test/org/burroloco/butcher/fixture/http/StringHandler.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2577" }, { "name": "Java", "bytes": "289490" }, { "name": "Shell", "bytes": "2801" }, { "name": "XSLT", "bytes": "7541" } ], "symlink_target": "" }
title: Setting Up PatternFly author: ajolicoeur layout: page --- <div class="row"> <div class="col-md-12"> <h2>Directly introduce PatternFly with CDN provider</h2> </div> </div> <div class="row"> <div class="col-md-12"> <p> If you want to try out the components provided by PatternFly in a fast way. Just use these <a href="https://cdnjs.com/libraries/patternfly" target="top">PatternFly</a> CDN links. </p> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <pre class="prettyprint"> <code class="language-html">{% escape_html %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/patternfly/3.24.0/css/patternfly.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/patternfly/3.24.0/css/patternfly-additions.min.css"> </head> <body> <div class="container"> <!-- Just enjoy various PatternFly components --> <div class="alert alert-success"> <span class="pficon pficon-ok"></span> <strong>Great job!</strong> This is really working out <a href="#" class="alert-link">great for us</a>. </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/patternfly/3.24.0/css/patternfly.min.css"></script> </body> </html> {% endescape_html %}</code> </pre> </div> </div> <div class="row"> <div class="col-md-12"> <h2>Setting Up PatternFly with npm</h2> </div> </div> <div class="row"> <div class="col-md-12"> <h3>Step 1: Prerequisites</h3> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <p>Before you build up web apps with npm and PatternFly, there are a few things that you have to do first:</p> <ul> <li>Make sure that you have node.js installed.</li> <li><kbd>mkdir myProject && cd myProject</kbd></li> <li>Type <kbd>npm init</kbd> to create package.json file.</li> </ul> </div> </div> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <h3>Step 2: Install PatternFly</h3> <p> <kbd> npm install patternfly --save </kbd> </p> <p>This will download and write to node_modules PatternFly and its dependency libraries.</p> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <h3>Step 3: Apply PatternFly in your project</h3> <p>Now we can include the necessary assets by directly specifying their path inside the node_modules folder.</p> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <pre class="prettyprint"> <code class="language-html">{% escape_html %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="/node_modules/patternfly/dist/css/patternfly.css"> <link rel="stylesheet" type="text/css" href="/node_modules/patternfly/dist/css/patternfly-additions.css"> </head> <body> <div class="container"> <!-- Just enjoy various PatternFly components --> <div class="alert alert-success"> <span class="pficon pficon-ok"></span> <strong>Great job!</strong> This is really working out <a href="#" class="alert-link">great for us</a>. </div> </div> <script src="/node_modules/jquery/dist/jquery.js"></script> <script src="/node_modules/bootstrap/dist/js/bootstrap.js"></script> </body> </html> {% endescape_html %}</code> </pre> </div> </div> <br/> <div class="well"> <p> For any questions, reach out to us on our <a href="mailto:[email protected]">mailing list</a>, <a href="https://gitter.im/patternfly/patternfly?utm_source=share-link&utm_medium=link&utm_campaign=share-link" target="top">Gitter</a> or on <a href="https://webchat.freenode.net/" target="top">Freenode</a> at #patternfly. </p> </div>
{ "content_hash": "5f4988194d33a67a07ebbd4c2e3602c7", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 326, "avg_line_length": 34.94827586206897, "alnum_prop": 0.6502220029600395, "repo_name": "bleathem/patternfly-org", "id": "ffbba44bbc6ddc0cf576038ec9af7bc21f4801ce", "size": "4058", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/get-started/setup/index.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31714" }, { "name": "HTML", "bytes": "78343" }, { "name": "JavaScript", "bytes": "16495" }, { "name": "Ruby", "bytes": "4113" }, { "name": "Shell", "bytes": "397" } ], "symlink_target": "" }
'use strict'; var _jsx2 = require('babel-runtime/helpers/jsx'); var _jsx3 = _interopRequireDefault(_jsx2); var _s = require('./s'); var _s2 = _interopRequireDefault(_s); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _enzyme = require('enzyme'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _ref = (0, _jsx3.default)(_s2.default, { type: 'strikethrough' }, void 0, 'Don\u2019t read this!'); var _ref2 = (0, _jsx3.default)(_s2.default, { type: 'bold' }, void 0, 'You should read this!'); var _ref3 = (0, _jsx3.default)(_s2.default, { type: 'underline' }, void 0, 'This text is underlined!'); var _ref4 = (0, _jsx3.default)(_s2.default, { type: 'italic' }, void 0, 'This text is italicized!'); describe('<S />', function () { test('should underline text when specified', function () { var context = { styles: { components: { s: { strikethrough: { color: '#ff0' } } } } }; var wrapper = (0, _enzyme.mount)(_ref, { context: context }); expect(wrapper).toMatchSnapshot(); }); test('should bold text when specified', function () { var context = { styles: { components: { s: { bold: { color: '#ff0' } } } } }; var wrapper = (0, _enzyme.mount)(_ref2, { context: context }); expect(wrapper).toMatchSnapshot(); }); test('should underline text when specified', function () { var context = { styles: { components: { s: { underline: { color: '#ff0' } } } } }; var wrapper = (0, _enzyme.mount)(_ref3, { context: context }); expect(wrapper).toMatchSnapshot(); }); test('should italicize text when specified', function () { var context = { styles: { components: { s: { italic: { color: '#ff0' } } } } }; var wrapper = (0, _enzyme.mount)(_ref4, { context: context }); expect(wrapper).toMatchSnapshot(); }); });
{ "content_hash": "443b7848769ce63681424edabb8bd5d4", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 95, "avg_line_length": 21.87878787878788, "alnum_prop": 0.5272391505078485, "repo_name": "waywaaard/spectacle", "id": "afcebe2cf132e237f6fe1e82ae2a988a13df2987", "size": "2166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/components/s.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18410" }, { "name": "HTML", "bytes": "845" }, { "name": "JavaScript", "bytes": "331797" } ], "symlink_target": "" }
{% extends 'contents/_base.html' %} {% load i18n %} {% block title %}Events Overview{% endblock title %} {% block content %} {% url 'page' path='events/sprints' as events_sprint_url %} {% url 'page' path='events/tutorials' as events_tutorial_url %} {% url 'page' path='events/open-spaces' as events_openspaces_url %} {% url 'page' path='events/keynotes' as events_keynote_url %} {% url 'events_talk_list' as events_talk_list_url %} <h1>Events Overview</h1> <h2>Keynotes</h2> <p>PyCon Taiwan invites four speakers to give keynote speeches during the three-day conference. Each keynote speaker is considered one of the most important figures in their respective fields. They share their professional experience and the image of their domain’s future.</p> <p>More information about <em>keynotes</em> can be found on the <a href="{{ events_keynote_url }}">{% trans 'Keynotes' %}</a> page.</p> <h2>Talks</h2> <p>The three conference days are packed with talks about Python by speakers from Taiwan and around the world. The talks will be either 30- or 45-minute long. Three tracks of talks will be delivered simultaneously, all with different topics and difficulties. We suggest you to make a schedule beforehand, and choose what you want ot listen based on your interests. Many people take notes on the program schedule before the meeting so they don’t run to wrong places.</p> <p>More information about <em>talk</em> can be found on the <a href="{{ events_talk_list_url }}">{% trans 'Talks' %}</a> page.</p> <h2>Tutorials</h2> <p>Tutorial are events held as part of the main conference, but attendees need to register separately in order to join. They are either half- or one-day (three or six hours) events held to help participants better understand talks during the conference, or get their hands on more Python applications.</p> <p>More information about <em>tutorials</em> can be found on the <a href="{{ events_tutorial_url }}">{% trans 'Tutorials' %}</a> page.</p> <h2>Lightning Talks</h2> <p>Lightning talks are held at the end of each conference day. It’s known for its fast-paced nature that allows only 5 minutes for each talk, including setup. If you would like to give a lightning talk, please write down your name and the subject on a piece of paper, and put it into the jar near the registration desk. We will announce in each noon the list of talks for the day.</p> <h2>Open Spaces</h2> <p>Open Spaces are held both in parallel with the main conference, and during a dedicated slot at the three day of the conference. The schedule is created just-in-time by the attendees. If you would like to host an Open Space event, please use an Open Space card found in your goodies bag, fill it and pin it on the Open Space board.</p> <p>More information about <em>Open Spaces</em> can be found on the <a href="{{ events_openspaces_url }}">{% trans 'Open Spaces' %}</a> page.</p> <h2>Job Fair</h2> <p>Job Fair is a career expo for Python developers. During the Job Fair session, our sponsors will take turns introduce themselves on the stage and promote their job openings. For attendees that are looking for a career, this is a great opportunity for you to interact with the sponsors or submit your rèsumè!</p> {% endblock content %}
{ "content_hash": "ae4e3da286a3e93a00bcd6cfe771bd81", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 468, "avg_line_length": 61.56603773584906, "alnum_prop": 0.7416487894575544, "repo_name": "pycontw/pycontw2016", "id": "81ddf2997ebaeeb5448cf2c31c0fc1c17a875a12", "size": "3271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/templates/pycontw-2019/contents/en/events/overview.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "236762" }, { "name": "HTML", "bytes": "605550" }, { "name": "JavaScript", "bytes": "24923" }, { "name": "Python", "bytes": "479686" }, { "name": "Shell", "bytes": "389" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>zsearch-trees: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.0 / zsearch-trees - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> zsearch-trees <small> 8.6.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-07-14 04:23:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-14 04:23:34 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/zsearch-trees&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/ZSearchTrees&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: binary search trees&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;category: Miscellaneous/Extracted Programs/Data structures&quot; ] authors: [ &quot;Pierre Castéran&quot; ] bug-reports: &quot;https://github.com/coq-contribs/zsearch-trees/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/zsearch-trees.git&quot; synopsis: &quot;Binary Search Trees&quot; description: &quot;Algorithms for collecting, searching, inserting and deleting elements in binary search trees on Z&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/zsearch-trees/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=fca201467e21f6c236d51b3801924ce7&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-zsearch-trees.8.6.0 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-zsearch-trees -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zsearch-trees.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "9c39c31f3c9f820c789bbc32a33645db", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 191, "avg_line_length": 42.224242424242426, "alnum_prop": 0.5457155160040189, "repo_name": "coq-bench/coq-bench.github.io", "id": "b1363d89592f82d6b5f9f480d162e80be7803559", "size": "6970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/extra-dev/8.10.0/zsearch-trees/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
class PagesController < HighVoltage::PagesController layout :layout_for_page protected def layout_for_page 'application' end end
{ "content_hash": "237e33c38a3fe84fa4e17942b4f8ec51", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 17.625, "alnum_prop": 0.7588652482269503, "repo_name": "dynamicguy/person-log", "id": "c81c4bc47497e3a639bb6c3b4827456aa5cbe520", "size": "141", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/pages_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "55646" }, { "name": "JavaScript", "bytes": "1831164" }, { "name": "PHP", "bytes": "11546" }, { "name": "Perl", "bytes": "8021" }, { "name": "Ruby", "bytes": "262893" }, { "name": "Shell", "bytes": "9" } ], "symlink_target": "" }
namespace com{ namespace haxepunk{ Void Graphic_obj::__construct() { HX_STACK_PUSH("Graphic::new","com/haxepunk/Graphic.hx",60); { HX_STACK_LINE(61) this->active = false; HX_STACK_LINE(62) this->set_visible(true); HX_STACK_LINE(63) this->x = this->y = (int)0; HX_STACK_LINE(64) this->scrollX = this->scrollY = (int)1; HX_STACK_LINE(65) this->relative = true; HX_STACK_LINE(66) this->_scroll = true; HX_STACK_LINE(67) this->_point = ::flash::geom::Point_obj::__new(null(),null()); HX_STACK_LINE(68) this->set_layer((int)10); } ; return null(); } Graphic_obj::~Graphic_obj() { } Dynamic Graphic_obj::__CreateEmpty() { return new Graphic_obj; } hx::ObjectPtr< Graphic_obj > Graphic_obj::__new() { hx::ObjectPtr< Graphic_obj > result = new Graphic_obj(); result->__construct(); return result;} Dynamic Graphic_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Graphic_obj > result = new Graphic_obj(); result->__construct(); return result;} int Graphic_obj::set_layer( int value){ HX_STACK_PUSH("Graphic::set_layer","com/haxepunk/Graphic.hx",115); HX_STACK_THIS(this); HX_STACK_ARG(value,"value"); HX_STACK_LINE(115) return this->layer = value; } HX_DEFINE_DYNAMIC_FUNC1(Graphic_obj,set_layer,return ) Void Graphic_obj::resume( ){ { HX_STACK_PUSH("Graphic::resume","com/haxepunk/Graphic.hx",110); HX_STACK_THIS(this); HX_STACK_LINE(110) this->active = true; } return null(); } HX_DEFINE_DYNAMIC_FUNC0(Graphic_obj,resume,(void)) Void Graphic_obj::pause( ){ { HX_STACK_PUSH("Graphic::pause","com/haxepunk/Graphic.hx",102); HX_STACK_THIS(this); HX_STACK_LINE(102) this->active = false; } return null(); } HX_DEFINE_DYNAMIC_FUNC0(Graphic_obj,pause,(void)) Void Graphic_obj::setEntity( ::com::haxepunk::Entity entity){ { HX_STACK_PUSH("Graphic::setEntity","com/haxepunk/Graphic.hx",93); HX_STACK_THIS(this); HX_STACK_ARG(entity,"entity"); HX_STACK_LINE(94) this->_entity = entity; HX_STACK_LINE(95) this->set_layer(( (((entity != null()))) ? int(entity->_layer) : int((int)10) )); } return null(); } HX_DEFINE_DYNAMIC_FUNC1(Graphic_obj,setEntity,(void)) Void Graphic_obj::render( ::flash::display::BitmapData target,::flash::geom::Point point,::flash::geom::Point camera){ { HX_STACK_PUSH("Graphic::render","com/haxepunk/Graphic.hx",90); HX_STACK_THIS(this); HX_STACK_ARG(target,"target"); HX_STACK_ARG(point,"point"); HX_STACK_ARG(camera,"camera"); } return null(); } HX_DEFINE_DYNAMIC_FUNC3(Graphic_obj,render,(void)) Void Graphic_obj::destroy( ){ { HX_STACK_PUSH("Graphic::destroy","com/haxepunk/Graphic.hx",82); HX_STACK_THIS(this); } return null(); } HX_DEFINE_DYNAMIC_FUNC0(Graphic_obj,destroy,(void)) Void Graphic_obj::update( ){ { HX_STACK_PUSH("Graphic::update","com/haxepunk/Graphic.hx",75); HX_STACK_THIS(this); } return null(); } HX_DEFINE_DYNAMIC_FUNC0(Graphic_obj,update,(void)) bool Graphic_obj::set_visible( bool value){ HX_STACK_PUSH("Graphic::set_visible","com/haxepunk/Graphic.hx",20); HX_STACK_THIS(this); HX_STACK_ARG(value,"value"); HX_STACK_LINE(20) return this->_visible = value; } HX_DEFINE_DYNAMIC_FUNC1(Graphic_obj,set_visible,return ) bool Graphic_obj::get_visible( ){ HX_STACK_PUSH("Graphic::get_visible","com/haxepunk/Graphic.hx",19); HX_STACK_THIS(this); HX_STACK_LINE(19) return this->_visible; } HX_DEFINE_DYNAMIC_FUNC0(Graphic_obj,get_visible,return ) Graphic_obj::Graphic_obj() { } void Graphic_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Graphic); HX_MARK_MEMBER_NAME(_visible,"_visible"); HX_MARK_MEMBER_NAME(_blit,"_blit"); HX_MARK_MEMBER_NAME(_entity,"_entity"); HX_MARK_MEMBER_NAME(_point,"_point"); HX_MARK_MEMBER_NAME(_scroll,"_scroll"); HX_MARK_MEMBER_NAME(layer,"layer"); HX_MARK_MEMBER_NAME(relative,"relative"); HX_MARK_MEMBER_NAME(scrollY,"scrollY"); HX_MARK_MEMBER_NAME(scrollX,"scrollX"); HX_MARK_MEMBER_NAME(y,"y"); HX_MARK_MEMBER_NAME(x,"x"); HX_MARK_MEMBER_NAME(active,"active"); HX_MARK_END_CLASS(); } void Graphic_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(_visible,"_visible"); HX_VISIT_MEMBER_NAME(_blit,"_blit"); HX_VISIT_MEMBER_NAME(_entity,"_entity"); HX_VISIT_MEMBER_NAME(_point,"_point"); HX_VISIT_MEMBER_NAME(_scroll,"_scroll"); HX_VISIT_MEMBER_NAME(layer,"layer"); HX_VISIT_MEMBER_NAME(relative,"relative"); HX_VISIT_MEMBER_NAME(scrollY,"scrollY"); HX_VISIT_MEMBER_NAME(scrollX,"scrollX"); HX_VISIT_MEMBER_NAME(y,"y"); HX_VISIT_MEMBER_NAME(x,"x"); HX_VISIT_MEMBER_NAME(active,"active"); } Dynamic Graphic_obj::__Field(const ::String &inName,bool inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"y") ) { return y; } if (HX_FIELD_EQ(inName,"x") ) { return x; } break; case 5: if (HX_FIELD_EQ(inName,"_blit") ) { return _blit; } if (HX_FIELD_EQ(inName,"pause") ) { return pause_dyn(); } if (HX_FIELD_EQ(inName,"layer") ) { return layer; } break; case 6: if (HX_FIELD_EQ(inName,"_point") ) { return _point; } if (HX_FIELD_EQ(inName,"resume") ) { return resume_dyn(); } if (HX_FIELD_EQ(inName,"render") ) { return render_dyn(); } if (HX_FIELD_EQ(inName,"update") ) { return update_dyn(); } if (HX_FIELD_EQ(inName,"active") ) { return active; } break; case 7: if (HX_FIELD_EQ(inName,"_entity") ) { return _entity; } if (HX_FIELD_EQ(inName,"_scroll") ) { return _scroll; } if (HX_FIELD_EQ(inName,"destroy") ) { return destroy_dyn(); } if (HX_FIELD_EQ(inName,"scrollY") ) { return scrollY; } if (HX_FIELD_EQ(inName,"scrollX") ) { return scrollX; } if (HX_FIELD_EQ(inName,"visible") ) { return get_visible(); } break; case 8: if (HX_FIELD_EQ(inName,"_visible") ) { return _visible; } if (HX_FIELD_EQ(inName,"relative") ) { return relative; } break; case 9: if (HX_FIELD_EQ(inName,"set_layer") ) { return set_layer_dyn(); } if (HX_FIELD_EQ(inName,"setEntity") ) { return setEntity_dyn(); } break; case 11: if (HX_FIELD_EQ(inName,"set_visible") ) { return set_visible_dyn(); } if (HX_FIELD_EQ(inName,"get_visible") ) { return get_visible_dyn(); } } return super::__Field(inName,inCallProp); } Dynamic Graphic_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp) { switch(inName.length) { case 1: if (HX_FIELD_EQ(inName,"y") ) { y=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"x") ) { x=inValue.Cast< Float >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"_blit") ) { _blit=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"layer") ) { if (inCallProp) return set_layer(inValue);layer=inValue.Cast< int >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"_point") ) { _point=inValue.Cast< ::flash::geom::Point >(); return inValue; } if (HX_FIELD_EQ(inName,"active") ) { active=inValue.Cast< bool >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"_entity") ) { _entity=inValue.Cast< ::com::haxepunk::Entity >(); return inValue; } if (HX_FIELD_EQ(inName,"_scroll") ) { _scroll=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"scrollY") ) { scrollY=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"scrollX") ) { scrollX=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"visible") ) { return set_visible(inValue); } break; case 8: if (HX_FIELD_EQ(inName,"_visible") ) { _visible=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"relative") ) { relative=inValue.Cast< bool >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Graphic_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_CSTRING("_visible")); outFields->push(HX_CSTRING("_blit")); outFields->push(HX_CSTRING("_entity")); outFields->push(HX_CSTRING("_point")); outFields->push(HX_CSTRING("_scroll")); outFields->push(HX_CSTRING("layer")); outFields->push(HX_CSTRING("relative")); outFields->push(HX_CSTRING("scrollY")); outFields->push(HX_CSTRING("scrollX")); outFields->push(HX_CSTRING("y")); outFields->push(HX_CSTRING("x")); outFields->push(HX_CSTRING("visible")); outFields->push(HX_CSTRING("active")); super::__GetFields(outFields); }; static ::String sStaticFields[] = { String(null()) }; static ::String sMemberFields[] = { HX_CSTRING("_visible"), HX_CSTRING("_blit"), HX_CSTRING("_entity"), HX_CSTRING("_point"), HX_CSTRING("_scroll"), HX_CSTRING("set_layer"), HX_CSTRING("resume"), HX_CSTRING("pause"), HX_CSTRING("setEntity"), HX_CSTRING("render"), HX_CSTRING("destroy"), HX_CSTRING("update"), HX_CSTRING("layer"), HX_CSTRING("relative"), HX_CSTRING("scrollY"), HX_CSTRING("scrollX"), HX_CSTRING("y"), HX_CSTRING("x"), HX_CSTRING("set_visible"), HX_CSTRING("get_visible"), HX_CSTRING("active"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Graphic_obj::__mClass,"__mClass"); }; static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Graphic_obj::__mClass,"__mClass"); }; Class Graphic_obj::__mClass; void Graphic_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("com.haxepunk.Graphic"), hx::TCanCast< Graphic_obj> ,sStaticFields,sMemberFields, &__CreateEmpty, &__Create, &super::__SGetClass(), 0, sMarkStatics, sVisitStatics); } void Graphic_obj::__boot() { } } // end namespace com } // end namespace haxepunk
{ "content_hash": "d0729fc90a8e3d28aed1518292f95f6b", "timestamp": "", "source": "github", "line_count": 329, "max_line_length": 134, "avg_line_length": 28.455927051671733, "alnum_prop": 0.6650288399914548, "repo_name": "DrSkipper/twogames", "id": "4ce2bf87d50f19901c16a5058b96ef7c3ea313fd", "size": "9872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/windows/cpp/obj/src/com/haxepunk/Graphic.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "3402052" }, { "name": "Haxe", "bytes": "66865" }, { "name": "JavaScript", "bytes": "60241" } ], "symlink_target": "" }
<archimate:BusinessProcess xmlns:archimate="http://www.archimatetool.com/archimate" name="Architecting Enterprise" id="3842b961-794b-4dd5-ba45-3fa699973065"/>
{ "content_hash": "55e830b0800b1c4640421f0cae6e7dfb", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 60, "avg_line_length": 42.75, "alnum_prop": 0.7602339181286549, "repo_name": "nfigay/archimagine", "id": "6282b0b52b87899749bb3e0b4ba39a58264faa0b", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "model/business/BusinessProcess_3842b961-794b-4dd5-ba45-3fa699973065.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
A music analysis
{ "content_hash": "2c0dd2e5af70d8626778c08713df4a0d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 16, "avg_line_length": 17, "alnum_prop": 0.8235294117647058, "repo_name": "DanielEpic/musicAnalysis-", "id": "1e3c67f1dc3556efb386e87b75597c9926d559ba", "size": "34", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Processing", "bytes": "41" } ], "symlink_target": "" }
// // ip/basic_resolver_entry.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_IP_BASIC_RESOLVER_ENTRY_HPP #define ASIO_IP_BASIC_RESOLVER_ENTRY_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <string> #include "asio/detail/push_options.hpp" namespace asio { namespace ip { /// An entry produced by a resolver. /** * The asio::ip::basic_resolver_entry class template describes an entry * as returned by a resolver. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename InternetProtocol> class basic_resolver_entry { public: /// The protocol type associated with the endpoint entry. typedef InternetProtocol protocol_type; /// The endpoint type associated with the endpoint entry. typedef typename InternetProtocol::endpoint endpoint_type; /// Default constructor. basic_resolver_entry() { } /// Construct with specified endpoint, host name and service name. basic_resolver_entry(const endpoint_type& ep, const std::string& host, const std::string& service) : endpoint_(ep), host_name_(host), service_name_(service) { } /// Get the endpoint associated with the entry. endpoint_type endpoint() const { return endpoint_; } /// Convert to the endpoint associated with the entry. operator endpoint_type() const { return endpoint_; } /// Get the host name associated with the entry. std::string host_name() const { return host_name_; } /// Get the host name associated with the entry. template <class Allocator> std::basic_string<char, std::char_traits<char>, Allocator> host_name( const Allocator& alloc = Allocator()) const { return std::basic_string<char, std::char_traits<char>, Allocator>( host_name_.c_str(), alloc); } /// Get the service name associated with the entry. std::string service_name() const { return service_name_; } /// Get the service name associated with the entry. template <class Allocator> std::basic_string<char, std::char_traits<char>, Allocator> service_name( const Allocator& alloc = Allocator()) const { return std::basic_string<char, std::char_traits<char>, Allocator>( service_name_.c_str(), alloc); } private: endpoint_type endpoint_; std::string host_name_; std::string service_name_; }; } // namespace ip } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IP_BASIC_RESOLVER_ENTRY_HPP
{ "content_hash": "f638bd9a3bb5afe8f8000653562ae4f6", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 79, "avg_line_length": 25.1875, "alnum_prop": 0.6767103863878058, "repo_name": "mojmir-svoboda/DbgToolkit", "id": "77da9e1ec20863f5a56e7ceff5195908b6e250a9", "size": "2821", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "3rd/asio/include/asio/ip/basic_resolver_entry.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "3960" }, { "name": "Batchfile", "bytes": "2926" }, { "name": "C", "bytes": "3527150" }, { "name": "C++", "bytes": "8094856" }, { "name": "CMake", "bytes": "240374" }, { "name": "HTML", "bytes": "330871" }, { "name": "M4", "bytes": "9332" }, { "name": "Makefile", "bytes": "221500" }, { "name": "PAWN", "bytes": "673" }, { "name": "Perl", "bytes": "36555" }, { "name": "Python", "bytes": "1459" }, { "name": "QMake", "bytes": "9561" }, { "name": "Scheme", "bytes": "6418020" }, { "name": "Shell", "bytes": "1747" }, { "name": "TeX", "bytes": "1961" }, { "name": "XSLT", "bytes": "77656" } ], "symlink_target": "" }
package networkmonitor.bolts.analyser; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseBasicBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import org.apache.log4j.Logger; import scala.collection.mutable.StringBuilder; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class UsageAnalyser extends BaseBasicBolt { /** * UsageAnalyser * Bolt that process very frequent data usage data from a resource. */ private static final long serialVersionUID = 1L; String topic; private static final Logger LOG = Logger.getLogger(UsageAnalyser.class); //Every bolt that implements this class must decide how they want to treat the data. public void treatData(String hostname, Double value, BasicOutputCollector collector){ if (value >= 0.7){ StringBuilder warningMessage = new StringBuilder("[" + hostname + "] ["+System.currentTimeMillis()+"] ["+ topic +"] is over the safe limit: " + (value*100) +"%."); System.err.println(warningMessage); writeOutputToFile(warningMessage.toString()); LOG.warn(warningMessage.toString()); } } public UsageAnalyser(String topic){ this.topic = topic; } public void execute(Tuple input, BasicOutputCollector collector) { String hostname = (String) input.getValue(0); Double value = input.getDouble(1); treatData(hostname, value, collector); } public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("treatedMessage")); } String getTopic(){ return topic; } void writeOutputToFile(String warningMessage){ String path = "./analytics/WARNINGS_LOG.txt"; //creating file object from given path File file = new File(path); //FileWriter second argument is for append if its true than FileWritter will //write bytes at the end of File (append) rather than beginning of file FileWriter fileWriter; try { fileWriter = new FileWriter(file,true); //Use BufferedWriter instead of FileWriter for better performance BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter); fileWriter.append(warningMessage+"\n"); //Don't forget to close Streams or Reader to free FileDescriptor associated with it bufferFileWriter.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
{ "content_hash": "25911bd69098dd24052bb4d022af05fe", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 166, "avg_line_length": 31.329113924050635, "alnum_prop": 0.7515151515151515, "repo_name": "joaojunior10/StormIDS", "id": "139422b4440d8f758016a58f542f6772939bdf34", "size": "2475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "StormEngine/src/main/java/networkmonitor/bolts/analyser/UsageAnalyser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "567161" }, { "name": "HTML", "bytes": "29212" }, { "name": "Java", "bytes": "312011" }, { "name": "JavaScript", "bytes": "28014" } ], "symlink_target": "" }
/* Place custom styles below */ div.input-group .form-control:last-child { border-bottom-right-radius: 4px; border-top-right-radius: 4px; }
{ "content_hash": "c2119a2863dab871438bc7f6aa22cdce", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 42, "avg_line_length": 29.6, "alnum_prop": 0.7027027027027027, "repo_name": "mauricionr/spPeoplePicker-ng-directive", "id": "caaa8e9172d76f30cc9aa773f05e90397b80a89c", "size": "150", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spPeoplePicker/Content/App.css", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "8239" }, { "name": "CSS", "bytes": "185" }, { "name": "JavaScript", "bytes": "12431" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>module Test::Unit::ExceptionHandler::ClassMethods - test-unit-3.3.0 Documentation</title> <script type="text/javascript"> var rdoc_rel_prefix = "../../../"; </script> <script src="../../../js/jquery.js"></script> <script src="../../../js/darkfish.js"></script> <link href="../../../css/fonts.css" rel="stylesheet"> <link href="../../../css/rdoc.css" rel="stylesheet"> <body id="top" role="document" class="module"> <nav role="navigation"> <div id="project-navigation"> <div id="home-section" role="region" title="Quick navigation" class="nav-section"> <h2> <a href="../../../index.html" rel="home">Home</a> </h2> <div id="table-of-contents-navigation"> <a href="../../../table_of_contents.html#pages">Pages</a> <a href="../../../table_of_contents.html#classes">Classes</a> <a href="../../../table_of_contents.html#methods">Methods</a> </div> </div> <div id="search-section" role="search" class="project-section initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <div id="search-field-wrapper"> <input id="search-field" role="combobox" aria-label="Search" aria-autocomplete="list" aria-controls="search-results" type="text" name="search" placeholder="Search" spellcheck="false" title="Type to search, Up and Down to navigate, Enter to load"> </div> <ul id="search-results" aria-label="Search Results" aria-busy="false" aria-expanded="false" aria-atomic="false" class="initially-hidden"></ul> </form> </div> </div> <div id="class-metadata"> <!-- Method Quickref --> <div id="method-list-section" class="nav-section"> <h3>Methods</h3> <ul class="link-list" role="directory"> <li ><a href="#method-i-exception_handler">#exception_handler</a> <li ><a href="#method-i-exception_handlers">#exception_handlers</a> <li ><a href="#method-i-unregister_exception_handler">#unregister_exception_handler</a> </ul> </div> </div> </nav> <main role="main" aria-labelledby="module-Test::Unit::ExceptionHandler::ClassMethods"> <h1 id="module-Test::Unit::ExceptionHandler::ClassMethods" class="module"> module Test::Unit::ExceptionHandler::ClassMethods </h1> <section class="description"> </section> <section id="5Buntitled-5D" class="documentation-section"> <section id="public-instance-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Instance Methods</h3> </header> <div id="method-i-exception_handler" class="method-detail "> <div class="method-heading"> <span class="method-name">exception_handler</span><span class="method-args">(*method_name_or_handlers, &block)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>@overload <a href="ClassMethods.html#method-i-exception_handler">#exception_handler</a>(method_name)</p> <pre>Add an exception handler method. @param method_name [Symbol] The method name that handles exception raised in tests. @return [void]</pre> <p>@overload <a href="ClassMethods.html#method-i-exception_handler">#exception_handler</a>(&amp;callback)</p> <pre>Add an exception handler. @yield [test, exception] Gives the test and the exception. @yieldparam test [Test::Unit::TestCase] The test where the exception is raised. @yieldparam exception [Exception] The exception that is raised in running the test. @yieldreturn [Boolean] Whether the handler handles the exception or not. The handler must return _true_ if the handler handles test exception, _false_ otherwise. @return [void]</pre> <p>This is a public API for developers who extend test-unit.</p> <div class="method-source-code" id="exception_handler-source"> <pre><span class="ruby-comment"># File lib/test/unit/exception-handler.rb, line 52</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">exception_handler</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">method_name_or_handlers</span>, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">block</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">block_given?</span> <span class="ruby-identifier">exception_handlers</span>.<span class="ruby-identifier">unshift</span>(<span class="ruby-identifier">block</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">method_name_or_handlers</span>.<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">method_name_or_handler</span><span class="ruby-operator">|</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">method_name_or_handler</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:call</span>) <span class="ruby-identifier">handler</span> = <span class="ruby-identifier">method_name_or_handler</span> <span class="ruby-identifier">exception_handlers</span>.<span class="ruby-identifier">unshift</span>(<span class="ruby-identifier">handler</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">method_name</span> = <span class="ruby-identifier">method_name_or_handler</span> <span class="ruby-identifier">attribute</span>(<span class="ruby-value">:exception_handler</span>, <span class="ruby-keyword">true</span>, {}, <span class="ruby-identifier">method_name</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-exception_handlers" class="method-detail "> <div class="method-heading"> <span class="method-name">exception_handlers</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="exception_handlers-source"> <pre><span class="ruby-comment"># File lib/test/unit/exception-handler.rb, line 25</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">exception_handlers</span> <span class="ruby-constant">ExceptionHandler</span>.<span class="ruby-identifier">exception_handlers</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-unregister_exception_handler" class="method-detail "> <div class="method-heading"> <span class="method-name">unregister_exception_handler</span><span class="method-args">(*method_name_or_handlers)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="unregister_exception_handler-source"> <pre><span class="ruby-comment"># File lib/test/unit/exception-handler.rb, line 68</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">unregister_exception_handler</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">method_name_or_handlers</span>) <span class="ruby-identifier">method_name_or_handlers</span>.<span class="ruby-identifier">each</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">method_name_or_handler</span><span class="ruby-operator">|</span> <span class="ruby-keyword">if</span> <span class="ruby-identifier">method_name_or_handler</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:call</span>) <span class="ruby-identifier">handler</span> = <span class="ruby-identifier">method_name_or_handler</span> <span class="ruby-identifier">exception_handlers</span>.<span class="ruby-identifier">delete</span>(<span class="ruby-identifier">handler</span>) <span class="ruby-keyword">else</span> <span class="ruby-identifier">method_name</span> = <span class="ruby-identifier">method_name_or_handler</span> <span class="ruby-identifier">attribute</span>(<span class="ruby-value">:exception_handler</span>, <span class="ruby-keyword">false</span>, {}, <span class="ruby-identifier">method_name</span>) <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </section> </section> </main> <footer id="validator-badges" role="contentinfo"> <p><a href="http://validator.w3.org/check/referer">Validate</a> <p>Generated by <a href="http://docs.seattlerb.org/rdoc/">RDoc</a> 4.2.1. <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>. </footer>
{ "content_hash": "cf202d25f83ff233458b904a6ba13d77", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 275, "avg_line_length": 36.591603053435115, "alnum_prop": 0.6363826014394492, "repo_name": "Celyagd/celyagd.github.io", "id": "808553ad43a08aa441347a87f3ee2d3a7795c2b6", "size": "9587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stakes-jekyll/doc/test-unit-3.3.0/rdoc/Test/Unit/ExceptionHandler/ClassMethods.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1375233" }, { "name": "C++", "bytes": "71485" }, { "name": "CMake", "bytes": "314" }, { "name": "CSS", "bytes": "168680" }, { "name": "HTML", "bytes": "7735250" }, { "name": "Java", "bytes": "134091" }, { "name": "JavaScript", "bytes": "196815" }, { "name": "PowerShell", "bytes": "238" }, { "name": "REXX", "bytes": "1941" }, { "name": "Ragel", "bytes": "56865" }, { "name": "Roff", "bytes": "3725" }, { "name": "Ruby", "bytes": "2708464" }, { "name": "Shell", "bytes": "842" }, { "name": "Yacc", "bytes": "7664" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- From: file:/C:/Users/Yvonne/AndroidStudioProjects/Sunshine-Version-2/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/values-fa/values-fa.xml --> <eat-comment/> <string msgid="4600421777120114993" name="abc_action_bar_home_description">"پیمایش به صفحه اصلی"</string> <string msgid="1594238315039666878" name="abc_action_bar_up_description">"پیمایش به بالا"</string> <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"گزینه‌های بیشتر"</string> <string msgid="4076576682505996667" name="abc_action_mode_done">"انجام شد"</string> <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"مشاهده همه"</string> <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"انتخاب برنامه"</string> <string msgid="3691816814315814921" name="abc_searchview_description_clear">"پاک کردن عبارت جستجو"</string> <string msgid="2550479030709304392" name="abc_searchview_description_query">"عبارت جستجو"</string> <string msgid="8264924765203268293" name="abc_searchview_description_search">"جستجو"</string> <string msgid="8928215447528550784" name="abc_searchview_description_submit">"ارسال عبارت جستجو"</string> <string msgid="893419373245838918" name="abc_searchview_description_voice">"جستجوی شفاهی"</string> <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"اشتراک‌گذاری با"</string> <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"‏اشتراک‌گذاری با %s"</string> </resources>
{ "content_hash": "f3b795c7b1e764cddb30f23533e2c920", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 186, "avg_line_length": 92.16666666666667, "alnum_prop": 0.75708257986739, "repo_name": "yallen011/Sunshine_Yallen011", "id": "d1bd3b2d6ea225027ee5a5f788da8cf2b2662000", "size": "1820", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/build/intermediates/res/debug/values-fa/values.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "484428" } ], "symlink_target": "" }
package br.com.senai.stayFilm.vizualizacao.viewModel; import br.com.senai.stayFilm.enumeration.Periodo; import br.com.senai.stayFilm.model.Atividade; import br.com.senai.stayFilm.model.Colaborador; public class AtividadeVisualizacaoViewModel { public AtividadeVisualizacaoViewModel(Atividade atividade) { setInstituicao(atividade.getInstituicao()); setAtividade(atividade.getAtividade()); setPeriodo(atividade.getPeriodo()); setColaborador(atividade.getColaborador()); } private String instituicao; private String atividade; private Periodo periodo; private Colaborador colaborador; public String getInstituicao() { return instituicao; } public void setInstituicao(String instituicao) { this.instituicao = instituicao; } public String getAtividade() { return atividade; } public void setAtividade(String atividade) { this.atividade = atividade; } public Periodo getPeriodo() { return periodo; } public void setPeriodo(Periodo periodo) { this.periodo = periodo; } public Colaborador getColaborador() { return colaborador; } public void setColaborador(Colaborador colaborador) { this.colaborador = colaborador; } }
{ "content_hash": "3b39ecf6b63c34d3cec0932ddd9861cb", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 61, "avg_line_length": 22.11320754716981, "alnum_prop": 0.7755972696245734, "repo_name": "GabrielaALopess/BackEnd-Stayfilm", "id": "d2a758c2d8c4721f75579adaef75dd40615cccc5", "size": "1172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/br/com/senai/stayFilm/vizualizacao/viewModel/AtividadeVisualizacaoViewModel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "187797" } ], "symlink_target": "" }
from time import sleep from usb import USBError from killerbee import KillerBee, kbutils from db import ZBScanDB from scanning import doScan GPS_FREQUENCY=3 #in seconds # GPS Poller def gpsdPoller(currentGPS): ''' @type currentGPS multiprocessing.Manager dict manager @arg currentGPS store relavent pieces of up-to-date GPS info ''' import gps gpsd = gps.gps() gpsd.poll() gpsd.stream() try: while True: gpsd.poll() if gpsd.fix.mode > 1: #1=NO_FIX, 2=FIX, 3=DGPS_FIX lat = gpsd.fix.latitude lng = gpsd.fix.longitude alt = gpsd.fix.altitude #print 'latitude ' , lat #print 'longitude ' , lng #TODO do we want to use the GPS time in any way? #print 'time utc ' , gpsd.utc,' + ', gpsd.fix.time #print 'altitude (m)' , alt currentGPS['lat'] = lat currentGPS['lng'] = lng currentGPS['alt'] = alt else: print "Waiting for a GPS fix." #TODO timeout lat/lng/alt values if too old...? sleep(GPS_FREQUENCY) except KeyboardInterrupt: print "Got KeyboardInterrupt in gpsdPoller, returning." return # startScan # Detects attached interfaces # Initiates scanning using doScan() def startScan(zbdb, currentGPS, verbose=False, dblog=False, agressive=False, include=[], ignore=None): try: kb = KillerBee() except USBError, e: if e.args[0].find('Operation not permitted') >= 0: print 'Error: Permissions error, try running using sudo.' else: print 'Error: USBError:', e return False except Exception, e: #print 'Error: Missing KillerBee USB hardware:', e print 'Error: Issue starting KillerBee instance:', e return False for kbdev in kbutils.devlist(gps=ignore, include=include): print 'Found device at %s: \'%s\'' % (kbdev[0], kbdev[1]) zbdb.store_devices( kbdev[0], #devid kbdev[1], #devstr kbdev[2]) #devserial kb.close() doScan(zbdb, currentGPS, verbose=verbose, dblog=dblog, agressive=agressive) return True
{ "content_hash": "237d9f82aef93c180f997e4972084c22", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 102, "avg_line_length": 32.267605633802816, "alnum_prop": 0.5800960279353994, "repo_name": "EastL/killerbee", "id": "3324baf344615e97b921a1ecc8cc507ea8c55e43", "size": "2385", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "killerbee/zbwardrive/zbwardrive.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1020567" }, { "name": "C++", "bytes": "277684" }, { "name": "Makefile", "bytes": "14328" }, { "name": "Objective-C", "bytes": "16282" }, { "name": "Python", "bytes": "423250" }, { "name": "Shell", "bytes": "773" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b279b68191c02872867a3cd55e8cd448", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "b1707d192bdf1a2c23ad0f6cc0c618831e0c8aed", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Crucifera/Crucifera cakile/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
layout: post title: "Installer heartbeat sous une redhat 5" date: 2009-02-06 18:46:00 aliases: [ node/35, 35-.*] author: "Tangui Morlier" --- Heartbeat est un outil bien pratique pour faire de la haute disponibilité. Malheureusement il n'est pas inclu dans une redhat 5. Voici comment l'installer via yum. OpenSuse met à disposition des packages pour de nombreuses distributions. Voici les commandes pour les inclures dans yum : $ su -c "wget -O /etc/yum.repos.d/linuxha.repo http://download.opensuse.org/repositories/server:/ha-clustering/RHEL_5/server:ha-clustering.repo" $ yum update [...] $ yum -y install heartbeat [...] Dans un prochain billet, j'expliquerai comme configurer heartbeat.
{ "content_hash": "b1180f1c161d83e95b818e3781081c8f", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 148, "avg_line_length": 34.333333333333336, "alnum_prop": 0.7350901525658807, "repo_name": "teymour/tutos.tangui.eu.org", "id": "abce1b0ff83ea8bd48215b753ab37a0cfff9d7ba", "size": "727", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2009-02-06-node35.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10081" }, { "name": "HTML", "bytes": "16471" }, { "name": "Makefile", "bytes": "149" }, { "name": "Perl", "bytes": "735" }, { "name": "Shell", "bytes": "347" } ], "symlink_target": "" }
import networkx as nx import cirq from recirq.qaoa.problems import random_plus_minus_1_weights, _validate_problem_graph, \ _graph_to_serializable_edgelist, _serialized_edgelist_to_graph, get_growing_subgraphs, \ get_all_hardware_grid_problems, HardwareGridProblem, get_all_sk_problems, SKProblem, \ get_all_3_regular_problems, ThreeRegularProblem import pytest import numpy as np def test_validate_problem_qubit_nodes(): def random_sk_model_with_qubit_nodes(n: int): graph = nx.complete_graph(n) graph = nx.relabel_nodes( graph, mapping={i: cirq.LineQubit(i) for i in range(n)}) return random_plus_minus_1_weights(graph) problem_graph = random_sk_model_with_qubit_nodes(n=3) with pytest.raises(ValueError) as e: _validate_problem_graph(problem_graph) assert e.match(r'Problem graph must have contiguous, 0-indexed integer nodes.*') def test_validate_problem_no_weight(): problem = nx.complete_graph(n=3) with pytest.raises(ValueError) as e: _validate_problem_graph(problem) assert e.match(r'Problem graph must have `weight` edge attributes.*') def test_graph_to_serializable_edgelist(): g = random_plus_minus_1_weights(nx.complete_graph(4), rs=np.random.RandomState(52)) edgelist = _graph_to_serializable_edgelist(g) assert isinstance(edgelist, list) assert isinstance(edgelist[0], tuple) assert len(edgelist) == 4 * 3 / 2 for n1, n2, w in edgelist: assert 0 <= n1 < 4 assert 0 <= n2 < 4 assert w in [-1, 1] def test_serialized_edgelist_to_graph(): edgelist = [ (0, 1, 1.0), (0, 2, -1.0), (0, 3, 1.0), (1, 2, 1.0), (1, 3, 1.0), (2, 3, -1.0) ] g = random_plus_minus_1_weights(nx.complete_graph(4), rs=np.random.RandomState(52)) assert nx.is_isomorphic(_serialized_edgelist_to_graph(edgelist), g) def test_get_growing_subgraphs(): device_graph = nx.grid_2d_graph(3, 3) device_graph = nx.relabel_nodes( device_graph, mapping={(r, c): cirq.GridQubit(r, c) for r, c in device_graph.nodes}) growing_subgraphs = get_growing_subgraphs(device_graph, central_qubit=cirq.GridQubit(1, 1)) assert set(growing_subgraphs.keys()) == set(range(2, 9 + 1)) for k, v in growing_subgraphs.items(): assert len(v) == k def test_random_plus_minus_1_weights(): g1 = nx.complete_graph(4) g2 = random_plus_minus_1_weights(g1, rs=np.random.RandomState(53)) assert g1 != g2 # makes a new graph assert nx.is_isomorphic(g1, g2, node_match=lambda x, y: x == y) assert not nx.is_isomorphic(g1, g2, edge_match=lambda x, y: x == y) for u, v, w in g2.edges.data('weight'): assert 0 <= u <= 4 assert 0 <= v <= 4 assert w in [-1, 1] def test_get_all_hardware_grid_problems(): device_graph = nx.grid_2d_graph(3, 3) device_graph = nx.relabel_nodes( device_graph, mapping={(r, c): cirq.GridQubit(r, c) for r, c in device_graph.nodes}) problems = get_all_hardware_grid_problems( device_graph, central_qubit=cirq.GridQubit(1, 1), n_instances=3, rs=np.random.RandomState(52)) keys_should_be = [(n, i) for n in range(2, 9 + 1) for i in range(3)] assert list(problems.keys()) == keys_should_be for (n, i), v in problems.items(): assert isinstance(v, HardwareGridProblem) assert len(v.graph.nodes) == n assert len(v.coordinates) == n for r, c in v.coordinates: assert 0 <= r < 3 assert 0 <= c < 3 def test_get_all_sk_problems(): problems = get_all_sk_problems( max_n_qubits=5, n_instances=3, rs=np.random.RandomState()) keys_should_be = [(n, i) for n in range(2, 5 + 1) for i in range(3)] assert list(problems.keys()) == keys_should_be for (n, i), problem in problems.items(): assert isinstance(problem, SKProblem) assert len(problem.graph.nodes) == n assert problem.graph.number_of_edges() == (n * (n - 1)) / 2 def test_get_all_3_regular_problems(): problems = get_all_3_regular_problems( max_n_qubits=8, n_instances=3, rs=np.random.RandomState()) keys_should_be = [(n, i) for n in range(4, 8 + 1) for i in range(3) if n * 3 % 2 == 0] assert list(problems.keys()) == keys_should_be for (n, i), problem in problems.items(): assert isinstance(problem, ThreeRegularProblem) assert set(degree for node, degree in problem.graph.degree) == {3}
{ "content_hash": "be6a686b151793738efa95dc7e50f11c", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 95, "avg_line_length": 38.563025210084035, "alnum_prop": 0.6214861625626498, "repo_name": "quantumlib/ReCirq", "id": "bc5b46af8c1e38d03f54c6cd0db4b1e443dd6585", "size": "5160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recirq/qaoa/problems_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "365" }, { "name": "Dockerfile", "bytes": "300" }, { "name": "Jupyter Notebook", "bytes": "22201" }, { "name": "Makefile", "bytes": "670" }, { "name": "Python", "bytes": "989707" }, { "name": "Shell", "bytes": "2189" } ], "symlink_target": "" }
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("SQLiteMigrator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLiteMigrator")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("39772849-d49b-4851-ae35-a944f7feb97f")] // 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")]
{ "content_hash": "c2283cf99fe118c38133406fefea4725", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.916666666666664, "alnum_prop": 0.7458957887223412, "repo_name": "reedcourty/dotnet2014", "id": "1d25cfbfa63bb08025e8a45659c3ce63de852f73", "size": "1404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solutions/pomodoro/SQLiteMigrator/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "32911" }, { "name": "C#", "bytes": "104478" }, { "name": "CSS", "bytes": "633" }, { "name": "F#", "bytes": "2673" }, { "name": "JavaScript", "bytes": "170489" } ], "symlink_target": "" }
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define*/ define(function (require, exports, module) { "use strict"; var LegacyFileImport = require("filesystem/impls/filer/lib/LegacyFileImport"), WebKitFileImport = require("filesystem/impls/filer/lib/WebKitFileImport"), FileSystemCache = require("filesystem/impls/filer/FileSystemCache"), BrambleStartupState = require("bramble/StartupState"), LiveDevMultiBrowser = require("LiveDevelopment/LiveDevMultiBrowser"), PreferencesManager = require("preferences/PreferencesManager"); /** * XXXBramble: the Drag and Drop and File APIs are a mess of incompatible * standards and implementations. This tries to deal with the fact that some * browsers allow you to drag-and-drop folders, and some don't. All * browsers we support will do file drag-and-drop, so we want to make sure * we always allow that. * * Currently, dragging folders works in Chrome (13), Edge, Firefox (50) * but not in IE, Opera, or Safari. * * See: * - https://html.spec.whatwg.org/#the-datatransferitem-interface * - https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer * - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList * - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem * - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry */ function chooseImportStrategy(source) { if(source instanceof FileList) { return LegacyFileImport.create(); } if(source instanceof DataTransfer) { if(window.DataTransferItem && window.DataTransferItem.prototype.webkitGetAsEntry && window.DataTransferItemList) { return WebKitFileImport.create(); } return LegacyFileImport.create(); } } // Support passing a DataTransfer object, or a FileList exports.import = function(source, parentPath, callback) { if(!(source instanceof FileList || source instanceof DataTransfer)) { callback(new Error("[Bramble] expected DataTransfer or FileList to FileImport.import()")); return; } var strategy = chooseImportStrategy(source); // pause live preview updates until all files have been imported PreferencesManager.set("livePreviewAutoReload", false); // If we are given a sub-dir within the project, use that. Otherwise use project root. parentPath = parentPath || BrambleStartupState.project("root"); return strategy.import(source, parentPath, function(err) { // enable live preview updates after all files have been imported PreferencesManager.set("livePreviewAutoReload", true); if(err) { return callback(err); } FileSystemCache.refresh(function() { LiveDevMultiBrowser.reload(); callback(); }); }); }; });
{ "content_hash": "a551c132cff608f5127c0485f273dcd8", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 102, "avg_line_length": 42.306666666666665, "alnum_prop": 0.6400882445635045, "repo_name": "mozilla/brackets", "id": "d2c1feec125e3480970e8e8577f11b6c1ac7814a", "size": "3173", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/filesystem/impls/filer/lib/FileImport.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2667" }, { "name": "CSS", "bytes": "469667" }, { "name": "Clojure", "bytes": "28" }, { "name": "HTML", "bytes": "2113746" }, { "name": "Hack", "bytes": "2646" }, { "name": "JavaScript", "bytes": "12982161" }, { "name": "Makefile", "bytes": "2186" }, { "name": "PHP", "bytes": "26150" }, { "name": "Ruby", "bytes": "9040" }, { "name": "Shell", "bytes": "13574" } ], "symlink_target": "" }
@class ZRSettingItem; @interface ZRSettingCell : UITableViewCell @property (nonatomic, strong) ZRSettingItem *item; + (instancetype)cellWitnTableView:(UITableView *)tableView; @property (nonatomic, strong) UIView *divider; @end
{ "content_hash": "0c68ae812f14c5ebd5895cd844288f19", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 59, "avg_line_length": 23.2, "alnum_prop": 0.7887931034482759, "repo_name": "singsengder/ZRShop", "id": "c464c5291ad189e1a931ba2d2d47f2833f37e436", "size": "389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ZRShop/ZRClass/ZRItms/ZRPerson/View/ZRSettingCell.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1963483" } ], "symlink_target": "" }
package family; import java.util.Collection; import java.util.ArrayList; public class Child extends Person { private Collection<Parent> parents; public Child() { parents = new ArrayList<Parent>(); } public Collection<Parent> getParents() { return parents; } public void setParents(Collection<Parent> parents) { this.parents = parents; } }
{ "content_hash": "ee690340cc645b6789c7cd81666df2d4", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 54, "avg_line_length": 17, "alnum_prop": 0.6397058823529411, "repo_name": "jinx/core", "id": "1df5d5f87bf2d87830e0b80e4c2ef2dd8585f869", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/family/ext/src/family/Child.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "12106" }, { "name": "Ruby", "bytes": "358121" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Copyright (c) 2015, <your name>. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="scaffolded-by" content="https://github.com/google/stagehand"> <title>Dart_Sudoku_2</title> <!-- Add to homescreen for Chrome on Android --> <meta name="mobile-web-app-capable" content="yes"> <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png"> <!-- Add to homescreen for Safari on iOS --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="Web Starter Kit"> <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png"> <!-- Tile icon for Win8 (144x144 + tile color) --> <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png"> <meta name="msapplication-TileColor" content="#3372DF"> <!-- example of using a paper element --> <link rel="import" href="packages/paper_elements/roboto.html"> <!-- example of your own custom element --> <link rel="import" href="packages/Dart_Sudoku_2/sudokuCell.html"> <link rel="import" href="packages/Dart_Sudoku_2/sudokuBlock.html"> <link rel="import" href="packages/Dart_Sudoku_2/sudokuBoard.html"> <link rel="stylesheet" href="styles.css"> </head> <body unresolved style="background: darkgray"> <sudoku-board></sudoku-board> <script type="application/dart">export 'package:polymer/init.dart';</script> </body> </html>
{ "content_hash": "ba0e9dab65dc6f536812136424f7255d", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 100, "avg_line_length": 37.333333333333336, "alnum_prop": 0.7020089285714286, "repo_name": "tkonya/Dart-Sudoku", "id": "09a12b571aef02d7fecd0c8ac5da8c56f8203e6c", "size": "1792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "423" }, { "name": "Dart", "bytes": "20457" }, { "name": "HTML", "bytes": "6115" } ], "symlink_target": "" }
EXP double Add(double x, double y); EXP double Substract(double x, double y); EXP double Multiply(double x, double y); EXP double Divide(double x, double y); EXP double Negate(double x); EXP double Sqrt(double x); EXP double Power(double x, double y);
{ "content_hash": "0ed06c3343874305ef9c033172db5205", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 41, "avg_line_length": 28.22222222222222, "alnum_prop": 0.7401574803149606, "repo_name": "SVss/SPP_5", "id": "90277028c7f9f83691411ae8141df79d6e8b514d", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CalculatorWcf/CalcLib/CalcLib.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "395" }, { "name": "C#", "bytes": "42200" }, { "name": "C++", "bytes": "510" } ], "symlink_target": "" }
(function(w, ng, angApp, plugin){ var registerCtrl = function($scope, $rootScope, $location, $http, $cookieStore){ window.scrollTo(0,0); //reset plugin fixed table footer $scope.urlBase = "http://localhost:3000/api/"; $scope.accessUserForm = {}; $scope.usuario = {email: '', password: ''}; this.validAccessUserForm = false; this.checkAcces = function(fnAccess){ var accessField = $scope.accessUserForm.userField, email = accessField.email.$viewValue, password = accessField.password.$viewValue; //NO campos vacios y formulario valido if( !plugin.isEmpty(email) && !plugin.isEmpty(password) && accessField.$valid ){ $scope.usuario = {email: email, password: password}; this.validAccessUserForm = false; this.accessApp(fnAccess); }else this.validAccessUserForm = true; }; // $rootScope permite usar las propieades fijadas a el en cualquier lugar de la aplicacion this.accessApp = function(accessType){ var urlLogin = $scope.urlBase, rootMsg, consoleInfo; switch(accessType){ case 'login': urlLogin += "sesiones/"; rootMsg = 'Acceso Correcto, sesion actualizada'; consoleInfo = 'Sesion actualizada, resetear el TimeStamp'; break; case 'registro': urlLogin += "usuarios/"; rootMsg = 'Es tu primera conexion al Servidor'; consoleInfo = 'Nuevo usuario registrado'; break; } $http.post(urlLogin, $scope.usuario) .success(function(data){ $rootScope.nombre = $scope.usuario.email; $rootScope.mensaje = rootMsg; console.info(consoleInfo); $cookieStore.put('sessionId', data); $cookieStore.put('sessionName', $scope.usuario.email.split('@')[0] ); $location.path('/'); }); }; }; angApp.controller("loginRegisterController", ['$scope', '$rootScope', '$location', '$http', '$cookieStore', registerCtrl]); }(window, window.angular, app, plugin));
{ "content_hash": "86d72c632a831091a4bc5cc9d4a17482", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 92, "avg_line_length": 34.25, "alnum_prop": 0.6668404588112617, "repo_name": "fernandoPalaciosGit/banca-personal-DAW", "id": "3f0f6580b07c96f497e9f41ff43834686ff9a9b2", "size": "1918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/appAccount/register/register.ctrl.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "27458" }, { "name": "HTML", "bytes": "48614" }, { "name": "JavaScript", "bytes": "82063" }, { "name": "PHP", "bytes": "45774" } ], "symlink_target": "" }
[GeoServer](http://geoserver.org) is an open source server for sharing geospatial data. This is a docker image that eases setting up a GeoServer running specifically for [GeoNode](https://github.com/GeoNode/geoserver-geonode-ext) with an additional separated data directory. The image is based on the official Tomcat 9 image ## Installation This image is available as a [trusted build on the docker hub](https://registry.hub.docker.com/r/geonode/geoserver/), and is the recommended method of installation. Simple pull the image from the docker hub. ```bash $ docker pull geonode/geoserver ``` Alternatively you can build the image locally ```bash $ git clone https://github.com/geonode/geoserver-docker.git $ cd geoserver-docker $ docker build -t "geonode/geoserver" . ``` ## Quick start You can quick start the image using the command line ```bash $ docker run --name "geoserver" -d -p 8080:8080 geonode/geoserver ``` Point your browser to `http://localhost:8080/geoserver` and login using GeoServer's default username and password: * Username: admin * Password: geoserver ## How to use different versions There are mainly two different versions of this image which are useful for running **GeoNode** with different authentication system types. These versions are released as specific tags for two authentication mechanisms: * **Cookie based authn**: [geonode/geoserver:2.9.x](https://hub.docker.com/r/geonode/geoserver/builds/) * **Oauth2 based authn**: [geonode/geoserver:2.9.x-oauth2](https://hub.docker.com/r/geonode/geoserver/builds/) You can declare what version to use along with the data directory tag corresponded to the same version. ## Configuration ### Data volume This GeoServer container keeps its configuration data at `/geoserver_data/data` which is exposed as volume in the dockerfile. The volume allows for stopping and starting new containers from the same image without losing all the data and custom configuration. You may want to map this volume to a directory on the host. It will also ease the upgrade process in the future. Volumes can be mounted by passing the `-v` flag to the docker run command: ```bash -v /your/host/data/path:/geoserver_data/data ``` ### Data volume container In case you are running Compose for automatically having GeoServer up and running then a data volume container will be mounted with a default preloaded *GEOSERVER_DATA_DIR* at the configuration data directory of the container. Make sure that the image from the repository [data-docker](https://github.com/GeoNode/data-docker) is available from the [GeoNode Docker Hub](https://hub.docker.com/u/geonode/) or has been built locally: ```bash docker build -t geonode/geoserver_data . ``` #### Persistance behavior If you run: ```bash docker-compose stop ``` Data are retained in the *GEOSERVER_DATA_DIR* and can then be mounted in a new GeoServer instance by running again: ```bash docker-compose up ``` If you run: ```bash docker-compose down ``` Data are completely gone but you can ever start from the base GeoServer Data Directory built for Geonode. #### Data directory versions There has to be a correspondence one-to-one between the data directory version and the tag of the GeoServer image used in the Docker compose file. So at the end you can consume these images below: * **2.9.x**: [geonode/geoserver_data:2.9.x](https://hub.docker.com/r/geonode/geoserver_data/builds/) * **2.9.x-oauth2**: [geonode/geoserver_data:2.9.x-oauth2](https://hub.docker.com/r/geonode/geoserver_data/builds/) ### Database GeoServer recommends the usage of a spatial database #### PostGIS container (PostgreSQL + GIS Extension) If you want to use a [PostGIS](http://postgis.org/) container, you can link it to this image. You're free to use any PostGIS container. An example with [kartooza/postgis](https://registry.hub.docker.com/u/kartoza/postgis/) image: ```bash $ docker run -d --name="postgis" kartoza/postgis ``` For further information see [kartooza/postgis](https://registry.hub.docker.com/u/kartoza/postgis/). Now start the GeoServer instance by adding the `--link` option to the docker run command: ```bash --link postgis:postgis ```
{ "content_hash": "690bf1721b0a07f2eb7894ee9b442729", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 226, "avg_line_length": 35.72649572649573, "alnum_prop": 0.7610047846889952, "repo_name": "PixelDragon/pixeldragon", "id": "eb35a33a9aa25033f8ff913f4025a8e349c281b6", "size": "4200", "binary": false, "copies": "1", "ref": "refs/heads/2.6c1.3", "path": "geoserver/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "175496" }, { "name": "HTML", "bytes": "12627" }, { "name": "JavaScript", "bytes": "516702" }, { "name": "Python", "bytes": "83594" }, { "name": "Shell", "bytes": "14593" } ], "symlink_target": "" }
describe("About Objects", function () { describe("Properties", function () { var meglomaniac; beforeEach(function () { meglomaniac = { mastermind: "Joker", henchwoman: "Harley" }; }); it("should confirm objects are collections of properties", function () { expect(meglomaniac.mastermind).toBe(FILL_ME_IN); }); it("should confirm that properties are case sensitive", function () { expect(meglomaniac.henchwoman).toBe(FILL_ME_IN); expect(meglomaniac.henchWoman).toBe(FILL_ME_IN); }); }); it("should know properties that are functions act like methods", function () { var meglomaniac = { mastermind : "Brain", henchman: "Pinky", battleCry: function (noOfBrains) { return "They are " + this.henchman + " and the" + Array(noOfBrains + 1).join(" " + this.mastermind); } }; battleCry = meglomaniac.battleCry(4); expect(FILL_ME_IN).toMatch(battleCry); }); it("should confirm that when a function is attached to an object, 'this' refers to the object", function () { var currentDate = new Date() var currentYear = (currentDate.getFullYear()); var meglomaniac = { mastermind: "James Wood", henchman: "Adam West", birthYear: 1970, calculateAge: function () { return currentYear - this.birthYear; } }; expect(currentYear).toBe(FILL_ME_IN); expect(meglomaniac.calculateAge()).toBe(FILL_ME_IN); }); describe("'in' keyword", function () { var meglomaniac; beforeEach(function () { meglomaniac = { mastermind: "The Monarch", henchwoman: "Dr Girlfriend", theBomb: true }; }); it("should have the bomb", function () { hasBomb = "theBomb" in meglomaniac; expect(hasBomb).toBe(FILL_ME_IN); }); it("should not have the detonator however", function () { hasDetonator = "theDetonator" in meglomaniac; expect(hasDetonator).toBe(FILL_ME_IN); }); }); it("should know that properties can be added and deleted", function () { var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" }; expect("secretary" in meglomaniac).toBe(FILL_ME_IN); meglomaniac.secretary = "Agent Smith"; expect("secretary" in meglomaniac).toBe(FILL_ME_IN); delete meglomaniac.henchman; expect("henchman" in meglomaniac).toBe(FILL_ME_IN); }); it("should use prototype to add to all objects", function () { function Circle(radius) { this.radius = radius; } var simpleCircle = new Circle(10); var colouredCircle = new Circle(5); colouredCircle.colour = "red"; expect(simpleCircle.colour).toBe(FILL_ME_IN); expect(colouredCircle.colour).toBe(FILL_ME_IN); Circle.prototype.describe = function () { return "This circle has a radius of: " + this.radius; }; expect(simpleCircle.describe()).toBe(FILL_ME_IN); expect(colouredCircle.describe()).toBe(FILL_ME_IN); }); });
{ "content_hash": "6206e00ca2bcef993f799305582135fc", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 111, "avg_line_length": 28.376146788990827, "alnum_prop": 0.6126737795021016, "repo_name": "nuclearsandwich/javascript-koans", "id": "ca537f17e9ead86ca750743f39613100d7c8bffb", "size": "3093", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "koans/AboutObjects.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
Ext.define('Siesta.Recorder.UI.RecorderPanel', { extend : 'Ext.panel.Panel', alias : 'widget.recorderpanel', layout : 'fit', buttonAlign : 'left', border : false, bodyBorder : false, newActionDefaults : { action : 'click' }, eventView : null, test : null, recorder : null, harness : null, domContainer : null, recorderConfig : null, initComponent : function () { var me = this; this.store = new Ext.data.Store({ proxy : 'memory', model : 'Siesta.Recorder.Model.Action' }); me.createToolbars(); me.items = this.eventView = new Siesta.Recorder.UI.EventView({ border : false, itemId : 'eventView', store : me.store, highlightTarget : Ext.Function.bind(me.highlightTarget, me) }); this.eventView.on({ beforeedit : function (ed, ctx) { if (ctx.column.dataIndex === 'target') { me.domContainer.startInspection(false); } } }); this.eventView.on({ afteredit : this.onAfterEventViewEdit, validateedit : this.onAfterEventViewEdit, canceledit : this.onAfterEventViewEdit, scope : this, buffer : 200 }); var recorder = me.recorder = me.recorder || new Siesta.Recorder.Recorder( this.recorderConfig || {} ); recorder.on("actionadd", this.onActionAdded, this) recorder.on("actionremove", this.onActionRemoved, this) recorder.on("actionupdate", this.onActionUpdated, this) recorder.on("clear", this.onRecorderClear, this) recorder.on("start", this.onRecorderStart, this) recorder.on("stop", this.onRecorderStop, this) me.callParent(); this.mon(Ext.getBody(), 'mousedown', this.onBodyMouseDown, this, { delegate : '.target-inspector-label' }) this.on('hide', function () { var eventView = me.getEventView(); if (eventView && eventView.editing) { eventView.editing.completeEdit(); } }); }, onAfterEventViewEdit : function () { if (!this.eventView.editing.getActiveEditor()) { this.hideHighlighter(); } }, onBodyMouseDown : function (e, t) { var focusedEl = document.activeElement; if (Ext.fly(focusedEl).up('.siesta-targeteditor')) { e.stopEvent(); e.preventDefault(); focusedEl.value = Ext.htmlDecode(t.innerHTML); } }, onRecorderStart : function () { /** * @event startrecord * Fires when a recording is started * @param {Siesta.Recorder.RecorderManager} this */ this.fireEvent('startrecord', this); this.addCls('recorder-recording'); }, onRecorderStop : function () { /** * @event stoprecord * Fires when a recording is stopped * @param {Siesta.Recorder.RecorderManager} this */ this.fireEvent('stoprecord', this); this.removeCls('recorder-recording'); }, hideHighlighter : function () { if (this.test) { this.domContainer.clearHighlight(); } }, highlightTarget : function (target) { if (!target) { // Pass no target => simply hide highlighter this.hideHighlighter(); return; } var test = this.test; if (!test) { this.hideHighlighter(); return { success : true } } var R = Siesta.Resource('Siesta.Recorder.UI.RecorderPanel'); var resolved, el try { resolved = this.test.normalizeElement(target, true, true, true); el = resolved.el } catch (e) { // sizzle may break on various characters in the query (=, $, etc) } finally { if (!el) { return { success : false, warning : R.get('queryMatchesNothing') } } } var warning = resolved.matchingMultiple ? R.get('queryMatchesMultiple') : '' if (test.isElementVisible(el)) { this.domContainer.highlightTarget(el, '<span class="target-inspector-label">' + target + '</span>'); } else { // If target was provided but no element could be located, return false so // caller can get a hint there is potential trouble warning = warning || R.get('noVisibleElsFound') } return { success : !warning, message : warning }; }, createToolbars : function () { var me = this; var R = Siesta.Resource('Siesta.Recorder.UI.RecorderPanel'); me.tbar = { cls : 'siesta-toolbar', height : 45, defaults : { scale : 'medium', tooltipType : 'title', scope : me }, items : [ { iconCls : 'recorder-tool-icon icon-record', action : 'recorder-start', cls : 'recorder-tool', whenIdle : true, tooltip : R.get('recordTooltip'), handler : me.onRecordClick }, { iconCls : 'recorder-tool-icon', glyph : 0xE624, cls : 'recorder-tool', action : 'recorder-stop', handler : me.stop, tooltip : R.get('stopTooltip') }, { iconCls : 'recorder-tool-icon', glyph : 0xE60F, action : 'recorder-play', cls : 'recorder-tool', handler : me.onPlayClick, tooltip : R.get('playTooltip') }, { iconCls : 'recorder-tool-icon', glyph : 0xE604, action : 'recorder-remove-all', cls : 'recorder-tool icon-clear', handler : function () { if (this.store.getCount() === 0) return; Ext.Msg.confirm(R.get('removeAllPromptTitle'), R.get('removeAllPromptMessage'), function (btn) { if (btn == 'yes') { // process text value and close... me.clear(); } this.close(); }); }, tooltip : R.get('clearTooltip') }, '->', { text : 'Generate code', action : 'recorder-generate-code', handler : function () { var win = new Ext.Window({ title : R.get('codeWindowTitle'), layout : 'fit', height : 400, width : 600, autoScroll : true, autoShow : true, constrain : true, closeAction : 'destroy', items : { xtype : 'jseditor', mode : 'text/javascript' } }); win.items.first().setValue('t.chain(\n ' + me.generateCodeForSteps().join(',\n\n ') + '\n);') } }, { text : '+', action : 'recorder-add-step', tooltip : R.get('addNewTooltip'), tooltipType : 'title', scope : me, handler : function () { if (!me.test) { Ext.Msg.alert(R.get('noTestDetected'), R.get('noTestStarted')); return; } var store = me.store; var grid = me.getEventView(); var selected = grid.getSelectionModel().selected.first(); var model = new store.model(new Siesta.Recorder.Action(this.newActionDefaults)); if (selected) { store.insert(store.indexOf(selected) + 1, model); } else { store.add(model); } grid.editing.startEdit(model, 0); } }, me.closeButton ] }; me.bbar = { xtype : 'component', cls : 'cheatsheet', height : 70, html : '<table><tr><td class="cheatsheet-type">CSS Query:</td><td class="cheatsheet-sample"> .x-btn</td></tr>' + '<tr><td class="cheatsheet-type">Component Query:</td><td class="cheatsheet-sample"> &gt;&gt;toolbar button</td></tr>' + '<tr><td class="cheatsheet-type">Composite Query:</td><td class="cheatsheet-sample"> toolbar =&gt; .x-btn</td></tr></table>' }; }, // Attach to a test (and optionally a specific iframe, only used for testing) attachTo : function (test, iframe) { var me = this; var doClear = me.test && me.test.url !== test.url; var recorder = this.recorder this.setTest(test); var recWindow = iframe ? iframe.contentWindow : test.scopeProvider.scope; if (recWindow) { me.recorder.attach(recWindow); } if (doClear) me.clear(); }, getEventView : function () { return this.eventView; }, onRecordClick : function () { var test = this.test; var R = Siesta.Resource('Siesta.Recorder.UI.RecorderPanel'); if (this.recorder && test && test.global) { this.attachTo(test); this.recorder.start(); } else { Ext.Msg.alert('Error', R.get('noTestStarted')) } }, onPlayClick : function () { var me = this; var test = this.test; if (me.recorder && test) { me.recorder.stop(); if (me.store.getCount() > 0) { var harness = this.harness; var testStartListener = function (ev, runningTestInstance) { if (runningTestInstance.url === test.url) { runningTestInstance.on('beforetestfinalizeearly', testFinalizeListener, null, { single : true }); } }; var testFinalizeListener = function (ev, test2) { // important, need to update our reference to the test me.setTest(test2); // Run test first, and before it ends - fire off the recorded steps test2.chain(me.generateSteps()); }; harness.on('teststart', testStartListener, null, { single : true }); harness.launch([harness.getScriptDescriptor(test.url)]); } } }, stop : function () { this.recorder.stop(); }, clear : function () { this.recorder.clear(); }, onRecorderClear : function () { this.store.removeAll(); }, setTest : function (test) { this.test = test; this.eventView.test = test; }, generateSteps : function (events) { var steps = []; var t = this.test; this.store.each(function (ev) { var step = ev.asStep(t); // Can be empty if the line is empty and hasn't been filled out yet if (step) steps.push(step); }, this); return steps; }, onActionAdded : function (event, action) { var actionModel = new Siesta.Recorder.Model.Action(action); this.store.add(actionModel) this.getEventView().scrollToBottom() }, onActionRemoved : function (event, action) { this.store.remove(this.store.getById(action.id)) this.getEventView().scrollToBottom() }, onActionUpdated : function (event, action) { var model = this.store.getById(action.id); model.callJoined('afterEdit', [['target', 'action', '__offset__']]) }, generateCodeForSteps : function () { var steps = []; this.store.each(function (ev) { var step = ev.asCode(); // Can be empty if the line is empty and hasn't been filled out yet if (step) steps.push(step); }, this); return steps; }, getActions : function (asJooseInstances) { var actionModels = this.store.getRange() return asJooseInstances ? Ext.Array.pluck(actionModels, 'data') : actionModels }, onDestroy : function () { this.recorder.stop(); this.callParent(arguments); } });
{ "content_hash": "7a0ccea740d63c09de1f6a32b62bc870", "timestamp": "", "source": "github", "line_count": 445, "max_line_length": 136, "avg_line_length": 30.34606741573034, "alnum_prop": 0.4668986966824645, "repo_name": "department-of-veterans-affairs/ChartReview", "id": "33e898dad4fe47e7e5fe7ef050ffee7de7e50e9d", "size": "13628", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web-app/js/siesta-3.0.1-lite/lib/Siesta/Recorder/UI/RecorderPanel.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "8940" }, { "name": "Batchfile", "bytes": "5644" }, { "name": "CSS", "bytes": "66560051" }, { "name": "Groovy", "bytes": "971171" }, { "name": "HTML", "bytes": "8227071" }, { "name": "Java", "bytes": "303250" }, { "name": "JavaScript", "bytes": "118825632" }, { "name": "PHP", "bytes": "374295" }, { "name": "Python", "bytes": "41730" }, { "name": "Ruby", "bytes": "34708" }, { "name": "SCSS", "bytes": "7725587" } ], "symlink_target": "" }
// // Copyright 2010-2017 Deveel // // 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. // using System; namespace Deveel.Data.Sql.Methods { /// <summary> /// Provides an interface for resolving methods defined in a system /// </summary> public interface IMethodResolver { /// <summary> /// Attempts to resolve a method defined in the underlying system /// from the specified invoke information. /// </summary> /// <param name="context">The context used to resolve the method</param> /// <param name="invoke">The information of the invocation to the method /// (the name of the method and the arguments).</param> /// <returns> /// Returns an instance of <see cref="SqlMethod"/> that corresponds to the /// given information in the context given, or <c>null</c> if it was not /// possible to resovle any method for the provided information. /// </returns> SqlMethod ResolveMethod(IContext context, Invoke invoke); } }
{ "content_hash": "4f43528e61d20e255702302c4fde36ff", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 78, "avg_line_length": 38.1025641025641, "alnum_prop": 0.7012113055181696, "repo_name": "deveel/deveeldb.core", "id": "55c776c55b34199732034c9f8678a6723b261099", "size": "1488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/DeveelDb.Core/Data/Sql/Methods/IMethodResolver.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "38869" }, { "name": "Batchfile", "bytes": "104" }, { "name": "C#", "bytes": "1162288" }, { "name": "PowerShell", "bytes": "102" }, { "name": "Shell", "bytes": "543" } ], "symlink_target": "" }
package com.lukedeighton.play.annotation import scala.annotation.StaticAnnotation class Display(value: String) extends StaticAnnotation
{ "content_hash": "2d7da5a717704bfe719bc2f49840ed96", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 53, "avg_line_length": 27.4, "alnum_prop": 0.8686131386861314, "repo_name": "LukeDeighton/play-validation", "id": "253b026d6b14a2481ed1f9c3e0d1fcdb7956a32d", "size": "137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/lukedeighton/play/annotation/Display.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "31164" } ], "symlink_target": "" }
+++ date = "2015-09-10" draft = true title = "Complementary Services" categories = [ "Price List" ] +++ ## Up to 2 hours for initial interview. $0.00 ## Up to 2 hours Consultation over Lunch $0.00
{ "content_hash": "53cf064a2772529b11ed55ca6ee68403", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 40, "avg_line_length": 11.105263157894736, "alnum_prop": 0.6255924170616114, "repo_name": "davsk/davsk.github.io", "id": "4494bb4d7d71bf6919c3649735704b4f4c551b36", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hugo/content/rates/rt00.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "251102" } ], "symlink_target": "" }
from __future__ import unicode_literals import collections import glob import io import os import platform import re import traceback import shlex import shutil import sys class PythonVersion2(object): """Python 2 version of code that must differ between Python 2 and 3.""" def __init__(self): import cgi self.cgi = cgi import HTMLParser self.html_parser = HTMLParser self.html_parser_init_kwargs = {} import htmlentitydefs self.html_entities = htmlentitydefs def html_escape(self, strng): """Escape HTML characters in a string.""" return self.cgi.escape(strng) def unicode(self, *args, **kwargs): """Return the Unicode version of a string.""" return unicode(*args, **kwargs) def unichr(self, *args, **kwargs): """Return the one character string of a Unicode character number.""" return unichr(*args, **kwargs) def to_unicode(self, strng): """Convert a utf-8 encoded string to a Unicode.""" if isinstance(strng, unicode): return strng else: return strng.decode('utf-8', 'replace') def to_str(self, strng): """Convert a Unicode to a utf-8 encoded string.""" return strng.encode('utf-8', 'replace') class PythonVersion3(object): """Python 3 version of code that must differ between Python 2 and 3.""" def __init__(self, minor): self.minor = minor import html self.html = html import html.parser self.html_parser = html.parser if self.minor >= 4: self.html_parser_init_kwargs = { 'convert_charrefs' : True } else: self.html_parser_init_kwargs = {} import html.entities self.html_entities = html.entities def html_escape(self, strng): """Escape HTML characters in a string.""" return self.html.escape(strng, quote=False) def unicode(self, *args, **kwargs): """Return the Unicode version of a string.""" return str(*args, **kwargs) def unichr(self, *args, **kwargs): """Return the one character string of a Unicode character number.""" return chr(*args, **kwargs) def to_unicode(self, strng): """Convert a utf-8 encoded string to unicode.""" if isinstance(strng, bytes): return strng.decode('utf-8', 'replace') else: return strng def to_str(self, strng): """Convert a Unicode to a utf-8 encoded string.""" return strng if sys.version_info.major >= 3: PYVER = PythonVersion3(sys.version_info.minor) else: PYVER = PythonVersion2() import weechat import potr SCRIPT_NAME = 'otr' SCRIPT_DESC = 'Off-the-Record messaging for IRC' SCRIPT_HELP = """{description} Quick start: Add an OTR item to the status bar by adding '[otr]' to the config setting weechat.bar.status.items. This will show you whether your current conversation is encrypted, authenticated and logged. /set otr.* for OTR status bar customization options. Start a private conversation with a friend who has OTR: /query yourpeer hi In the private chat buffer: /otr start If you have not authenticated your peer yet, follow the instructions for authentication. You can, at any time, see the current OTR session status and fingerprints with: /otr status View OTR policies for your peer: /otr policy View default OTR policies: /otr policy default Start/Stop log recording for the current OTR session: /otr log [start|stop] This will be reverted back to the previous log setting at the end of the session. To refresh the OTR session: /otr refresh To end your private conversation: /otr finish This script supports only OTR protocol version 2. """.format(description=SCRIPT_DESC) SCRIPT_AUTHOR = 'Matthew M. Boedicker' SCRIPT_LICENCE = 'GPL3' SCRIPT_VERSION = '1.8.0' OTR_DIR_NAME = 'otr' OTR_QUERY_RE = re.compile(r'\?OTR(\?|\??v[a-z\d]*\?)') POLICIES = { 'allow_v2' : 'allow OTR protocol version 2, effectively enable OTR ' 'since v2 is the only supported version', 'require_encryption' : 'refuse to send unencrypted messages when OTR is ' 'enabled', 'log' : 'enable logging of OTR conversations', 'send_tag' : 'advertise your OTR capability using the whitespace tag', 'html_escape' : 'escape HTML special characters in outbound messages', 'html_filter' : 'filter HTML in incoming messages', } READ_ONLY_POLICIES = { 'allow_v1' : False, } ACTION_PREFIX = '/me ' IRC_ACTION_RE = re.compile('^\x01ACTION (?P<text>.*)\x01$') PLAIN_ACTION_RE = re.compile('^'+ACTION_PREFIX+'(?P<text>.*)$') IRC_SANITIZE_TABLE = dict((ord(char), None) for char in '\n\r\x00') global otr_debug_buffer otr_debug_buffer = None # Patch potr.proto.TaggedPlaintext to not end plaintext tags in a space. # # When POTR adds OTR tags to plaintext it puts them at the end of the message. # The tags end in a space which gets stripped off by WeeChat because it # strips trailing spaces from commands. This causes OTR initiation to fail so # the following code adds an extra tab at the end of the plaintext tags if # they end in a space. # # The patched version also skips OTR tagging for CTCP messages because it # breaks the CTCP format. def patched__bytes__(self): # Do not tag CTCP messages. if self.msg.startswith(b'\x01') and \ self.msg.endswith(b'\x01'): return self.msg data = self.msg + potr.proto.MESSAGE_TAG_BASE for v in self.versions: data += potr.proto.MESSAGE_TAGS[v] if data.endswith(b' '): data += b'\t' return data potr.proto.TaggedPlaintext.__bytes__ = patched__bytes__ def command(buf, command_str): """Wrap weechat.command() with utf-8 encode.""" debug(command_str) weechat.command(buf, PYVER.to_str(command_str)) def privmsg(server, nick, message): """Send a private message to a nick.""" for line in message.splitlines(): command('', '/quote -server {server} PRIVMSG {nick} :{line}'.format( server=irc_sanitize(server), nick=irc_sanitize(nick), line=irc_sanitize(line))) def build_privmsg_in(fromm, target, msg): """Build inbound IRC PRIVMSG command.""" return ':{user} PRIVMSG {target} :{msg}'.format( user=irc_sanitize(fromm), target=irc_sanitize(target), msg=irc_sanitize(msg)) def build_privmsgs_in(fromm, target, msg, prefix=''): """Build an inbound IRC PRIVMSG command for each line in msg. If prefix is supplied, prefix each line of msg with it.""" cmd = [] for line in msg.splitlines(): cmd.append(build_privmsg_in(fromm, target, prefix+line)) return '\r\n'.join(cmd) def build_privmsg_out(target, msg): """Build outbound IRC PRIVMSG command(s).""" cmd = [] for line in msg.splitlines(): cmd.append('PRIVMSG {target} :{line}'.format( target=irc_sanitize(target), line=irc_sanitize(line))) return '\r\n'.join(cmd) def irc_sanitize(msg): """Remove NUL, CR and LF characters from msg. The (utf-8 encoded version of a) string returned from this function should be safe to use as an argument in an irc command.""" return PYVER.unicode(msg).translate(IRC_SANITIZE_TABLE) def prnt(buf, message): """Wrap weechat.prnt() with utf-8 encode.""" weechat.prnt(buf, PYVER.to_str(message)) def print_buffer(buf, message, level='info'): """Print message to buf with prefix, using color according to level.""" prnt(buf, '{prefix}\t{msg}'.format( prefix=get_prefix(), msg=colorize(message, 'buffer.{}'.format(level)))) def get_prefix(): """Returns configured message prefix.""" return weechat.string_eval_expression( config_string('look.prefix'), {}, {}, {}) def debug(msg): """Send a debug message to the OTR debug buffer.""" debug_option = weechat.config_get(config_prefix('general.debug')) global otr_debug_buffer if weechat.config_boolean(debug_option): if not otr_debug_buffer: otr_debug_buffer = weechat.buffer_new("OTR Debug", "", "", "debug_buffer_close_cb", "") weechat.buffer_set(otr_debug_buffer, 'title', 'OTR Debug') weechat.buffer_set(otr_debug_buffer, 'localvar_set_no_log', '1') prnt(otr_debug_buffer, ('{script} debug\t{text}'.format( script=SCRIPT_NAME, text=PYVER.unicode(msg) ))) def debug_buffer_close_cb(data, buf): """Set the OTR debug buffer to None.""" global otr_debug_buffer otr_debug_buffer = None return weechat.WEECHAT_RC_OK def current_user(server_name): """Get the nick and server of the current user on a server.""" return irc_user(info_get('irc_nick', server_name), server_name) def irc_user(nick, server): """Build an IRC user string from a nick and server.""" return '{nick}@{server}'.format( nick=nick.lower(), server=server) def isupport_value(server, feature): """Get the value of an IRC server feature.""" args = '{server},{feature}'.format(server=server, feature=feature) return info_get('irc_server_isupport_value', args) def is_a_channel(channel, server): """Return true if a string has an IRC channel prefix.""" prefixes = \ tuple(isupport_value(server, 'CHANTYPES')) + \ tuple(isupport_value(server, 'STATUSMSG')) # If the server returns nothing for CHANTYPES and STATUSMSG use # default prefixes. if not prefixes: prefixes = ('#', '&', '+', '!', '@') return channel.startswith(prefixes) # Exception class for PRIVMSG parsing exceptions. class PrivmsgParseException(Exception): pass def parse_irc_privmsg(message, server): """Parse an IRC PRIVMSG command and return a dictionary. Either the to_channel key or the to_nick key will be set depending on whether the message is to a nick or a channel. The other will be None. Example input: :nick!user@host PRIVMSG #weechat :message here Output: {'from': 'nick!user@host', 'from_nick': 'nick', 'to': '#weechat', 'to_channel': '#weechat', 'to_nick': None, 'text': 'message here'} """ weechat_result = weechat.info_get_hashtable( 'irc_message_parse', dict(message=message)) if weechat_result['command'].upper() == 'PRIVMSG': target, text = PYVER.to_unicode( weechat_result['arguments']).split(' ', 1) if text.startswith(':'): text = text[1:] result = { 'from': PYVER.to_unicode(weechat_result['host']), 'to' : target, 'text': text, } if weechat_result['host']: result['from_nick'] = PYVER.to_unicode(weechat_result['nick']) else: result['from_nick'] = '' if is_a_channel(target, server): result['to_channel'] = target result['to_nick'] = None else: result['to_channel'] = None result['to_nick'] = target return result else: raise PrivmsgParseException(message) def has_otr_end(msg): """Return True if the message is the end of an OTR message.""" return msg.endswith('.') or msg.endswith(',') def first_instance(objs, klass): """Return the first object in the list that is an instance of a class.""" for obj in objs: if isinstance(obj, klass): return obj def config_prefix(option): """Add the config prefix to an option and return the full option name.""" return '{script}.{option}'.format( script=SCRIPT_NAME, option=option) def config_color(option): """Get the color of a color config option.""" return weechat.color(weechat.config_color(weechat.config_get( config_prefix('color.{}'.format(option))))) def config_string(option): """Get the string value of a config option with utf-8 decode.""" return PYVER.to_unicode(weechat.config_string( weechat.config_get(config_prefix(option)))) def buffer_get_string(buf, prop): """Wrap weechat.buffer_get_string() with utf-8 encode/decode.""" if buf is not None: encoded_buf = PYVER.to_str(buf) else: encoded_buf = None return PYVER.to_unicode(weechat.buffer_get_string( encoded_buf, PYVER.to_str(prop))) def buffer_is_private(buf): """Return True if a buffer is private.""" return buffer_get_string(buf, 'localvar_type') == 'private' def info_get(info_name, arguments): """Wrap weechat.info_get() with utf-8 encode/decode.""" return PYVER.to_unicode(weechat.info_get( PYVER.to_str(info_name), PYVER.to_str(arguments))) def msg_irc_from_plain(msg): """Transform a plain-text message to irc format. This will replace lines that start with /me with the respective irc command.""" return PLAIN_ACTION_RE.sub('\x01ACTION \g<text>\x01', msg) def msg_plain_from_irc(msg): """Transform an irc message to plain-text. Any ACTION found will be rewritten as /me <text>.""" return IRC_ACTION_RE.sub(ACTION_PREFIX + r'\g<text>', msg) def default_peer_args(args, buf): """Get the nick and server of a remote peer from command arguments or a buffer. args is the [nick, server] slice of arguments from a command. If these are present, return them. If args is empty and the buffer buf is private, return the remote nick and server of buf.""" result = None, None if len(args) == 2: result = tuple(args) else: if buffer_is_private(buf): result = ( buffer_get_string(buf, 'localvar_channel'), buffer_get_string(buf, 'localvar_server')) return result def format_default_policies(): """Return current default policies formatted as a string for the user.""" buf = io.StringIO() buf.write('Current default OTR policies:\n') for policy, desc in sorted(POLICIES.items()): buf.write(' {policy} ({desc}) : {value}\n'.format( policy=policy, desc=desc, value=config_string('policy.default.{}'.format(policy)))) buf.write('Change default policies with: /otr policy default NAME on|off') return buf.getvalue() def to_bytes(strng): """Convert a python str or unicode to bytes.""" return strng.encode('utf-8', 'replace') def colorize(msg, color): """Colorize each line of msg using color.""" result = [] colorstr = config_color(color) for line in msg.splitlines(): result.append('{color}{msg}'.format( color=colorstr, msg=line)) return '\r\n'.join(result) def accounts(): """Return a list of all IrcOtrAccounts sorted by name.""" result = [] for key_path in glob.iglob(os.path.join(OTR_DIR, '*.key3')): key_name, _ = os.path.splitext(os.path.basename(key_path)) result.append(ACCOUNTS[key_name]) return sorted(result, key=lambda account: account.name) def show_account_fingerprints(): """Print all account names and their fingerprints to the core buffer.""" table_formatter = TableFormatter() for account in accounts(): table_formatter.add_row([ account.name, str(account.getPrivkey())]) print_buffer('', table_formatter.format()) def show_peer_fingerprints(grep=None): """Print peer names and their fingerprints to the core buffer. If grep is passed in, show all peer names containing that substring.""" trust_descs = { '' : 'unverified', 'smp' : 'SMP verified', 'verified' : 'verified', } table_formatter = TableFormatter() for account in accounts(): for peer, peer_data in sorted(account.trusts.items()): for fingerprint, trust in sorted(peer_data.items()): if grep is None or grep in peer: table_formatter.add_row([ peer, account.name, potr.human_hash(fingerprint), trust_descs[trust], ]) print_buffer('', table_formatter.format()) def private_key_file_path(account_name): """Return the private key file path for an account.""" return os.path.join(OTR_DIR, '{}.key3'.format(account_name)) def read_private_key(key_file_path): """Return the private key in a private key file.""" debug(('read private key', key_file_path)) with open(key_file_path, 'rb') as key_file: return potr.crypt.PK.parsePrivateKey(key_file.read())[0] class AccountDict(collections.defaultdict): """Dictionary that adds missing keys as IrcOtrAccount instances.""" def __missing__(self, key): debug(('add account', key)) self[key] = IrcOtrAccount(key) return self[key] class Assembler(object): """Reassemble fragmented OTR messages. This does not deal with OTR fragmentation, which is handled by potr, but fragmentation of received OTR messages that are too large for IRC. """ def __init__(self): self.clear() def add(self, data): """Add data to the buffer.""" self.value += data def clear(self): """Empty the buffer.""" self.value = '' def is_done(self): """Return True if the buffer is a complete message.""" return self.is_query() or \ not to_bytes(self.value).startswith(potr.proto.OTRTAG) or \ has_otr_end(self.value) def get(self): """Return the current value of the buffer and empty it.""" result = self.value self.clear() return result def is_query(self): """Return true if the buffer is an OTR query.""" return OTR_QUERY_RE.search(self.value) class IrcContext(potr.context.Context): """Context class for OTR over IRC.""" def __init__(self, account, peername): super(IrcContext, self).__init__(account, peername) self.peer_nick, self.peer_server = peername.split('@', 1) self.in_assembler = Assembler() self.in_otr_message = False self.in_smp = False self.smp_question = False def policy_config_option(self, policy): """Get the option name of a policy option for this context.""" return config_prefix('.'.join([ 'policy', self.peer_server, self.user.nick, self.peer_nick, policy.lower()])) def getPolicy(self, key): """Get the value of a policy option for this context.""" key_lower = key.lower() if key_lower in READ_ONLY_POLICIES: result = READ_ONLY_POLICIES[key_lower] elif key_lower == 'send_tag' and self.no_send_tag(): result = False else: option = weechat.config_get( PYVER.to_str(self.policy_config_option(key))) if option == '': option = weechat.config_get( PYVER.to_str(self.user.policy_config_option(key))) if option == '': option = weechat.config_get(config_prefix('.'.join( ['policy', self.peer_server, key_lower]))) if option == '': option = weechat.config_get( config_prefix('policy.default.{}'.format(key_lower))) result = bool(weechat.config_boolean(option)) debug(('getPolicy', key, result)) return result def inject(self, msg, appdata=None): """Send a message to the remote peer.""" if isinstance(msg, potr.proto.OTRMessage): msg = PYVER.unicode(msg) else: msg = PYVER.to_unicode(msg) debug(('inject', msg, 'len {}'.format(len(msg)), appdata)) privmsg(self.peer_server, self.peer_nick, msg) def setState(self, newstate): """Handle state transition.""" debug(('state', self.state, newstate)) if self.is_encrypted(): if newstate == potr.context.STATE_ENCRYPTED: self.print_buffer( 'Private conversation has been refreshed.', 'success') elif newstate == potr.context.STATE_FINISHED: self.print_buffer( '{peer} has ended the private conversation. You should do ' 'the same:\n/otr finish'.format(peer=self.peer_nick)) elif newstate == potr.context.STATE_ENCRYPTED: # unencrypted => encrypted trust = self.getCurrentTrust() # Disable logging before any proof of OTR activity is generated. # This is necessary when the session is started automatically, and # not by /otr start. if not self.getPolicy('log'): self.previous_log_level = self.disable_logging() else: self.previous_log_level = self.get_log_level() if self.is_logged(): self.hint( 'You have enabled the recording to disk of OTR ' 'conversations. By doing this you are potentially ' 'putting yourself and your correspondent in danger. ' 'Please consider disabling this policy with ' '"/otr policy default log off". To disable logging ' 'for this OTR session, use "/otr log stop"') if trust is None: fpr = str(self.getCurrentKey()) self.print_buffer('New fingerprint: {}'.format(fpr), 'warning') self.setCurrentTrust('') if bool(trust): self.print_buffer( 'Authenticated secured OTR conversation started.', 'success') else: self.print_buffer( 'Unauthenticated secured OTR conversation started.', 'warning') self.hint(self.verify_instructions()) if self.state != potr.context.STATE_PLAINTEXT and \ newstate == potr.context.STATE_PLAINTEXT: self.print_buffer('Private conversation ended.') # If we altered the logging value, restore it. if self.previous_log_level is not None: self.restore_logging(self.previous_log_level) super(IrcContext, self).setState(newstate) def maxMessageSize(self, appdata=None): """Return the max message size for this context.""" # remove 'PRIVMSG <nick> :' from max message size result = self.user.maxMessageSize - 10 - len(self.peer_nick) debug('max message size {}'.format(result)) return result def buffer(self): """Get the buffer for this context.""" return info_get( 'irc_buffer', '{server},{nick}'.format( server=self.peer_server, nick=self.peer_nick )) def print_buffer(self, msg, level='info'): """Print a message to the buffer for this context. level is used to colorize the message.""" buf = self.buffer() # add [nick] prefix if we have only a server buffer for the query if self.peer_nick and not buffer_is_private(buf): msg = '[{nick}] {msg}'.format( nick=self.peer_nick, msg=msg) print_buffer(buf, msg, level) def hint(self, msg): """Print a message to the buffer but only when hints are enabled.""" hints_option = weechat.config_get(config_prefix('general.hints')) if weechat.config_boolean(hints_option): self.print_buffer(msg, 'hint') def smp_finish(self, message=False, level='info'): """Reset SMP state and send a message to the user.""" self.in_smp = False self.smp_question = False self.user.saveTrusts() if message: self.print_buffer(message, level) def handle_tlvs(self, tlvs): """Handle SMP states.""" if tlvs: smp1q = first_instance(tlvs, potr.proto.SMP1QTLV) smp3 = first_instance(tlvs, potr.proto.SMP3TLV) smp4 = first_instance(tlvs, potr.proto.SMP4TLV) if first_instance(tlvs, potr.proto.SMPABORTTLV): debug('SMP aborted by peer') self.smp_finish('SMP aborted by peer.', 'warning') elif self.in_smp and not self.smpIsValid(): debug('SMP aborted') self.smp_finish('SMP aborted.', 'error') elif first_instance(tlvs, potr.proto.SMP1TLV): debug('SMP1') self.in_smp = True self.print_buffer( """Peer has requested SMP verification. Respond with: /otr smp respond <secret>""") elif smp1q: debug(('SMP1Q', smp1q.msg)) self.in_smp = True self.smp_question = True self.print_buffer( """Peer has requested SMP verification: {msg} Respond with: /otr smp respond <answer>""".format( msg=PYVER.to_unicode(smp1q.msg))) elif first_instance(tlvs, potr.proto.SMP2TLV): if not self.in_smp: debug('Received unexpected SMP2') self.smp_finish() else: debug('SMP2') self.print_buffer('SMP progressing.') elif smp3 or smp4: if smp3: debug('SMP3') elif smp4: debug('SMP4') if self.smpIsSuccess(): if self.smp_question: self.smp_finish('SMP verification succeeded.', 'success') if not self.is_verified: self.print_buffer( """You may want to authenticate your peer by asking your own question: /otr smp ask <'question'> 'secret'""") else: self.smp_finish('SMP verification succeeded.', 'success') else: self.smp_finish('SMP verification failed.', 'error') def verify_instructions(self): """Generate verification instructions for user.""" return """You can verify that this contact is who they claim to be in one of the following ways: 1) Verify each other's fingerprints using a secure channel: Your fingerprint : {your_fp} {peer}'s fingerprint : {peer_fp} then use the command: /otr trust {peer_nick} {peer_server} 2) SMP pre-shared secret that you both know: /otr smp ask {peer_nick} {peer_server} 'secret' 3) SMP pre-shared secret that you both know with a question: /otr smp ask {peer_nick} {peer_server} <'question'> 'secret' Note: You can safely omit specifying the peer and server when executing these commands from the appropriate conversation buffer """.format( your_fp=self.user.getPrivkey(), peer=self.peer, peer_nick=self.peer_nick, peer_server=self.peer_server, peer_fp=potr.human_hash( self.crypto.theirPubkey.cfingerprint()), ) def is_encrypted(self): """Return True if the conversation with this context's peer is currently encrypted.""" return self.state == potr.context.STATE_ENCRYPTED def is_verified(self): """Return True if this context's peer is verified.""" return bool(self.getCurrentTrust()) def format_policies(self): """Return current policies for this context formatted as a string for the user.""" buf = io.StringIO() buf.write('Current OTR policies for {peer}:\n'.format( peer=self.peer)) for policy, desc in sorted(POLICIES.items()): buf.write(' {policy} ({desc}) : {value}\n'.format( policy=policy, desc=desc, value='on' if self.getPolicy(policy) else 'off')) buf.write('Change policies with: /otr policy NAME on|off') return buf.getvalue() def is_logged(self): """Return True if conversations with this context's peer are currently being logged to disk.""" infolist = weechat.infolist_get('logger_buffer', '', '') buf = self.buffer() result = False while weechat.infolist_next(infolist): if weechat.infolist_pointer(infolist, 'buffer') == buf: result = bool(weechat.infolist_integer(infolist, 'log_enabled')) break weechat.infolist_free(infolist) return result def get_log_level(self): """Return the current logging level for this context's peer or -1 if the buffer uses the default log level of weechat.""" infolist = weechat.infolist_get('logger_buffer', '', '') buf = self.buffer() if not weechat.config_get(self.get_logger_option_name(buf)): result = -1 else: result = 0 while weechat.infolist_next(infolist): if weechat.infolist_pointer(infolist, 'buffer') == buf: result = weechat.infolist_integer(infolist, 'log_level') break weechat.infolist_free(infolist) return result def get_logger_option_name(self, buf): """Returns the logger config option for the specified buffer.""" name = buffer_get_string(buf, 'name') plugin = buffer_get_string(buf, 'plugin') return 'logger.level.{plugin}.{name}'.format( plugin=plugin, name=name) def disable_logging(self): """Return the previous logger level and set the buffer logger level to 0. If it was already 0, return None.""" # If previous_log_level has not been previously set, return the level # we detect now. if not hasattr(self, 'previous_log_level'): previous_log_level = self.get_log_level() if self.is_logged(): weechat.command(self.buffer(), '/mute logger disable') self.print_buffer( 'Logs have been temporarily disabled for the session. They will be restored upon finishing the OTR session.') return previous_log_level # If previous_log_level was already set, it means we already altered it # and that we just detected an already modified logging level. # Return the pre-existing value so it doesn't get lost, and we can # restore it later. else: return self.previous_log_level def restore_logging(self, previous_log_level): """Restore the log level of the buffer.""" buf = self.buffer() if (previous_log_level >= 0) and (previous_log_level < 10): self.print_buffer( 'Restoring buffer logging value to: {}'.format( previous_log_level), 'warning') weechat.command(buf, '/mute logger set {}'.format( previous_log_level)) if previous_log_level == -1: logger_option_name = self.get_logger_option_name(buf) self.print_buffer( 'Restoring buffer logging value to default', 'warning') weechat.command(buf, '/mute unset {}'.format( logger_option_name)) del self.previous_log_level def msg_convert_in(self, msg): """Transform incoming OTR message to IRC format. This includes stripping html, converting plain-text ACTIONs and character encoding conversion. Only character encoding is changed if context is unencrypted.""" msg = PYVER.to_unicode(msg) if not self.is_encrypted(): return msg if self.getPolicy('html_filter'): try: msg = IrcHTMLParser.parse(msg) except PYVER.html_parser.HTMLParseError: pass return msg_irc_from_plain(msg) def msg_convert_out(self, msg): """Convert an outgoing IRC message to be sent over OTR. This includes escaping html, converting ACTIONs to plain-text and character encoding conversion Only character encoding is changed if context is unencrypted.""" if self.is_encrypted(): msg = msg_plain_from_irc(msg) if self.getPolicy('html_escape'): msg = PYVER.html_escape(msg) # potr expects bytes to be returned return to_bytes(msg) def no_send_tag(self): """Skip OTR whitespace tagging to bots and services. Any nicks matching the otr.general.no_send_tag_regex config setting will not be tagged. """ no_send_tag_regex = config_string('general.no_send_tag_regex') debug(('no_send_tag', no_send_tag_regex, self.peer_nick)) if no_send_tag_regex: return re.match(no_send_tag_regex, self.peer_nick, re.IGNORECASE) def __repr__(self): return PYVER.to_str(('<{} {:x} peer_nick={c.peer_nick} ' 'peer_server={c.peer_server}>').format( self.__class__.__name__, id(self), c=self)) class IrcOtrAccount(potr.context.Account): """Account class for OTR over IRC.""" contextclass = IrcContext PROTOCOL = 'irc' MAX_MSG_SIZE = 415 def __init__(self, name): super(IrcOtrAccount, self).__init__( name, IrcOtrAccount.PROTOCOL, IrcOtrAccount.MAX_MSG_SIZE) self.nick, self.server = self.name.split('@', 1) # IRC messages cannot have newlines, OTR query and "no plugin" text # need to be one message self.defaultQuery = self.defaultQuery.replace("\n", ' ') self.key_file_path = private_key_file_path(name) self.fpr_file_path = os.path.join(OTR_DIR, '{}.fpr'.format(name)) self.load_trusts() def load_trusts(self): """Load trust data from the fingerprint file.""" if os.path.exists(self.fpr_file_path): with open(self.fpr_file_path) as fpr_file: for line in fpr_file: debug(('load trust check', line)) context, account, protocol, fpr, trust = \ PYVER.to_unicode(line[:-1]).split('\t') if account == self.name and \ protocol == IrcOtrAccount.PROTOCOL: debug(('set trust', context, fpr, trust)) self.setTrust(context, fpr, trust) def loadPrivkey(self): """Load key file. If no key file exists, load the default key. If there is no default key, a new key will be generated automatically by potr.""" debug(('load private key', self.key_file_path)) if os.path.exists(self.key_file_path): return read_private_key(self.key_file_path) else: default_key = config_string('general.defaultkey') if default_key: default_key_path = private_key_file_path(default_key) if os.path.exists(default_key_path): shutil.copyfile(default_key_path, self.key_file_path) return read_private_key(self.key_file_path) def savePrivkey(self): """Save key file.""" debug(('save private key', self.key_file_path)) with open(self.key_file_path, 'wb') as key_file: key_file.write(self.getPrivkey().serializePrivateKey()) def saveTrusts(self): """Save trusts.""" with open(self.fpr_file_path, 'w') as fpr_file: for uid, trusts in self.trusts.items(): for fpr, trust in trusts.items(): debug(('trust write', uid, self.name, IrcOtrAccount.PROTOCOL, fpr, trust)) fpr_file.write(PYVER.to_str('\t'.join( (uid, self.name, IrcOtrAccount.PROTOCOL, fpr, trust)))) fpr_file.write('\n') def end_all_private(self): """End all currently encrypted conversations.""" for context in self.ctxs.values(): if context.is_encrypted(): context.disconnect() def policy_config_option(self, policy): """Get the option name of a policy option for this account.""" return config_prefix('.'.join([ 'policy', self.server, self.nick, policy.lower()])) class IrcHTMLParser(PYVER.html_parser.HTMLParser): """A simple HTML parser that throws away anything but newlines and links""" @staticmethod def parse(data): """Create a temporary IrcHTMLParser and parse a single string""" parser = IrcHTMLParser(**PYVER.html_parser_init_kwargs) parser.feed(data) parser.close() return parser.result def reset(self): """Forget all state, called from __init__""" PYVER.html_parser.HTMLParser.reset(self) self.result = '' self.linktarget = '' self.linkstart = 0 def handle_starttag(self, tag, attrs): """Called when a start tag is encountered""" if tag == 'br': self.result += '\n' elif tag == 'a': attrs = dict(attrs) if 'href' in attrs: self.result += '[' self.linktarget = attrs['href'] self.linkstart = len(self.result) def handle_endtag(self, tag): """Called when an end tag is encountered""" if tag == 'a': if self.linktarget: if self.result[self.linkstart:] == self.linktarget: self.result += ']' else: self.result += ']({})'.format(self.linktarget) self.linktarget = '' def handle_data(self, data): """Called for character data (i.e. text)""" self.result += data def handle_entityref(self, name): """Called for entity references, such as &amp;""" try: self.result += PYVER.unichr( PYVER.html_entities.name2codepoint[name]) except KeyError: self.result += '&{};'.format(name) def handle_charref(self, name): """Called for character references, such as &#39;""" try: if name.startswith('x'): self.result += PYVER.unichr(int(name[1:], 16)) else: self.result += PYVER.unichr(int(name)) except ValueError: self.result += '&#{};'.format(name) class TableFormatter(object): """Format lists of string into aligned tables.""" def __init__(self): self.rows = [] self.max_widths = None def add_row(self, row): """Add a row to the table.""" self.rows.append(row) row_widths = [ len(s) for s in row ] if self.max_widths is None: self.max_widths = row_widths else: self.max_widths = list(map(max, self.max_widths, row_widths)) def format(self): """Return the formatted table as a string.""" return '\n'.join([ self.format_row(row) for row in self.rows ]) def format_row(self, row): """Format a single row as a string.""" return ' |'.join( [ s.ljust(self.max_widths[i]) for i, s in enumerate(row) ]) def message_in_cb(data, modifier, modifier_data, string): """Incoming message callback""" debug(('message_in_cb', data, modifier, modifier_data, string)) parsed = parse_irc_privmsg( PYVER.to_unicode(string), PYVER.to_unicode(modifier_data)) debug(('parsed message', parsed)) # skip processing messages to public channels if parsed['to_channel']: return string server = PYVER.to_unicode(modifier_data) from_user = irc_user(parsed['from_nick'], server) local_user = current_user(server) context = ACCOUNTS[local_user].getContext(from_user) context.in_assembler.add(parsed['text']) result = '' if context.in_assembler.is_done(): try: msg, tlvs = context.receiveMessage( # potr expects bytes to_bytes(context.in_assembler.get())) debug(('receive', msg, tlvs)) if msg: result = PYVER.to_str(build_privmsgs_in( parsed['from'], parsed['to'], context.msg_convert_in(msg))) context.handle_tlvs(tlvs) except potr.context.ErrorReceived as err: context.print_buffer('Received OTR error: {}'.format( PYVER.to_unicode(err.args[0].error)), 'error') except potr.context.NotEncryptedError: context.print_buffer( 'Received encrypted data but no private session established.', 'warning') except potr.context.NotOTRMessage: result = string except potr.context.UnencryptedMessage as err: result = PYVER.to_str(build_privmsgs_in( parsed['from'], parsed['to'], PYVER.to_unicode( msg_plain_from_irc(err.args[0])), 'Unencrypted message received: ')) weechat.bar_item_update(SCRIPT_NAME) return result def message_out_cb(data, modifier, modifier_data, string): """Outgoing message callback.""" result = '' # If any exception is raised in this function, WeeChat will not send the # outgoing message, which could be something that the user intended to be # encrypted. This paranoid exception handling ensures that the system # fails closed and not open. try: debug(('message_out_cb', data, modifier, modifier_data, string)) parsed = parse_irc_privmsg( PYVER.to_unicode(string), PYVER.to_unicode(modifier_data)) debug(('parsed message', parsed)) # skip processing messages to public channels if parsed['to_channel']: return string server = PYVER.to_unicode(modifier_data) to_user = irc_user(parsed['to_nick'], server) local_user = current_user(server) context = ACCOUNTS[local_user].getContext(to_user) is_query = OTR_QUERY_RE.search(parsed['text']) parsed_text_bytes = to_bytes(parsed['text']) is_otr_message = \ parsed_text_bytes[:len(potr.proto.OTRTAG)] == potr.proto.OTRTAG if is_otr_message and not is_query: if not has_otr_end(parsed['text']): debug('in OTR message') context.in_otr_message = True else: debug('complete OTR message') result = string elif context.in_otr_message: if has_otr_end(parsed['text']): context.in_otr_message = False debug('in OTR message end') result = string else: debug(('context send message', parsed['text'], parsed['to_nick'], server)) if context.policyOtrEnabled() and \ not context.is_encrypted() and \ not is_query and \ context.getPolicy('require_encryption'): context.print_buffer( 'Your message will not be sent, because policy requires an ' 'encrypted connection.', 'error') context.hint( 'Wait for the OTR connection or change the policy to allow ' 'clear-text messages:\n' '/policy set require_encryption off') try: ret = context.sendMessage( potr.context.FRAGMENT_SEND_ALL, context.msg_convert_out(parsed['text'])) if ret: debug(('sendMessage returned', ret)) result = PYVER.to_str( build_privmsg_out( parsed['to_nick'], PYVER.to_unicode(ret) )) except potr.context.NotEncryptedError as err: if err.args[0] == potr.context.EXC_FINISHED: context.print_buffer( """Your message was not sent. End your private conversation:\n/otr finish""", 'error') else: raise weechat.bar_item_update(SCRIPT_NAME) except: try: print_buffer('', traceback.format_exc(), 'error') print_buffer('', 'Versions: {versions}'.format( versions=dependency_versions()), 'error') context.print_buffer( 'Failed to send message. See core buffer for traceback.', 'error') except: pass return result def shutdown(): """Script unload callback.""" debug('shutdown') weechat.config_write(CONFIG_FILE) for account in ACCOUNTS.values(): account.end_all_private() free_all_config() weechat.bar_item_remove(OTR_STATUSBAR) return weechat.WEECHAT_RC_OK def command_cb(data, buf, args): """Parse and dispatch WeeChat OTR commands.""" result = weechat.WEECHAT_RC_ERROR try: arg_parts = [PYVER.to_unicode(arg) for arg in shlex.split(args)] except: debug("Command parsing error.") return result if len(arg_parts) in (1, 3) and arg_parts[0] in ('start', 'refresh'): nick, server = default_peer_args(arg_parts[1:3], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) # We need to wall disable_logging() here so that no OTR-related # buffer messages get logged at any point. disable_logging() will # be called again when effectively switching to encrypted, but # the previous_log_level we set here will be preserved for later # restoring. if not context.getPolicy('log'): context.previous_log_level = context.disable_logging() else: context.previous_log_level = context.get_log_level() context.hint('Sending OTR query... Please await confirmation of the OTR session being started before sending a message.') if not context.getPolicy('send_tag'): context.hint( 'To try OTR on all conversations with {peer}: /otr policy send_tag on'.format( peer=context.peer)) privmsg(server, nick, '?OTR?') result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 3) and arg_parts[0] in ('finish', 'end'): nick, server = default_peer_args(arg_parts[1:3], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.disconnect() result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 3) and arg_parts[0] == 'status': nick, server = default_peer_args(arg_parts[1:3], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if context.is_encrypted(): context.print_buffer( 'This conversation is encrypted.', 'success') context.print_buffer("Your fingerprint is: {}".format( context.user.getPrivkey())) context.print_buffer("Your peer's fingerprint is: {}".format( potr.human_hash(context.crypto.theirPubkey.cfingerprint()))) if context.is_verified(): context.print_buffer( "The peer's identity has been verified.", 'success') else: context.print_buffer( "You have not verified the peer's identity yet.", 'warning') else: context.print_buffer( "This current conversation is not encrypted.", 'warning') result = weechat.WEECHAT_RC_OK elif len(arg_parts) in range(2, 7) and arg_parts[0] == 'smp': action = arg_parts[1] if action == 'respond': # Check if nickname and server are specified if len(arg_parts) == 3: nick, server = default_peer_args([], buf) secret = arg_parts[2] elif len(arg_parts) == 5: nick, server = default_peer_args(arg_parts[2:4], buf) secret = arg_parts[4] else: return weechat.WEECHAT_RC_ERROR if secret: secret = PYVER.to_str(secret) context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.smpGotSecret(secret) result = weechat.WEECHAT_RC_OK elif action == 'ask': question = None secret = None # Nickname and server are not specified # Check whether it's a simple challenge or a question/answer request if len(arg_parts) == 3: nick, server = default_peer_args([], buf) secret = arg_parts[2] elif len(arg_parts) == 4: nick, server = default_peer_args([], buf) secret = arg_parts[3] question = arg_parts[2] # Nickname and server are specified # Check whether it's a simple challenge or a question/answer request elif len(arg_parts) == 5: nick, server = default_peer_args(arg_parts[2:4], buf) secret = arg_parts[4] elif len(arg_parts) == 6: nick, server = default_peer_args(arg_parts[2:4], buf) secret = arg_parts[5] question = arg_parts[4] else: return weechat.WEECHAT_RC_ERROR context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if secret: secret = PYVER.to_str(secret) if question: question = PYVER.to_str(question) try: context.smpInit(secret, question) except potr.context.NotEncryptedError: context.print_buffer( 'There is currently no encrypted session with {}.'.format( context.peer), 'error') else: if question: context.print_buffer('SMP challenge sent...') else: context.print_buffer('SMP question sent...') context.in_smp = True result = weechat.WEECHAT_RC_OK elif action == 'abort': # Nickname and server are not specified if len(arg_parts) == 2: nick, server = default_peer_args([], buf) # Nickname and server are specified elif len(arg_parts) == 4: nick, server = default_peer_args(arg_parts[2:4], buf) else: return weechat.WEECHAT_RC_ERROR context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if context.in_smp: try: context.smpAbort() except potr.context.NotEncryptedError: context.print_buffer( 'There is currently no encrypted session with {}.'.format( context.peer), 'error') else: debug('SMP aborted') context.smp_finish('SMP aborted.') result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 3) and arg_parts[0] == 'trust': nick, server = default_peer_args(arg_parts[1:3], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if context.crypto.theirPubkey is not None: context.setCurrentTrust('verified') context.print_buffer('{peer} is now authenticated.'.format( peer=context.peer)) weechat.bar_item_update(SCRIPT_NAME) else: context.print_buffer( 'No fingerprint for {peer}. Start an OTR conversation first: /otr start'.format( peer=context.peer), 'error') result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 3) and arg_parts[0] == 'distrust': nick, server = default_peer_args(arg_parts[1:3], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if context.crypto.theirPubkey is not None: context.setCurrentTrust('') context.print_buffer( '{peer} is now de-authenticated.'.format( peer=context.peer)) weechat.bar_item_update(SCRIPT_NAME) else: context.print_buffer( 'No fingerprint for {peer}. Start an OTR conversation first: /otr start'.format( peer=context.peer), 'error') result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 2) and arg_parts[0] == 'log': nick, server = default_peer_args([], buf) if len(arg_parts) == 1: if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if context.is_encrypted(): if context.is_logged(): context.print_buffer( 'This conversation is currently being logged.', 'warning') result = weechat.WEECHAT_RC_OK else: context.print_buffer( 'This conversation is currently NOT being logged.') result = weechat.WEECHAT_RC_OK else: context.print_buffer( 'OTR LOG: Not in an OTR session', 'error') result = weechat.WEECHAT_RC_OK else: print_buffer('', 'OTR LOG: Not in an OTR session', 'error') result = weechat.WEECHAT_RC_OK if len(arg_parts) == 2: if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) if arg_parts[1] == 'start' and \ not context.is_logged() and \ context.is_encrypted(): if context.previous_log_level is None: context.previous_log_level = context.get_log_level() context.print_buffer('From this point on, this conversation will be logged. Please keep in mind that by doing so you are potentially putting yourself and your interlocutor at risk. You can disable this by doing /otr log stop', 'warning') weechat.command(buf, '/mute logger set 9') result = weechat.WEECHAT_RC_OK elif arg_parts[1] == 'stop' and \ context.is_logged() and \ context.is_encrypted(): if context.previous_log_level is None: context.previous_log_level = context.get_log_level() weechat.command(buf, '/mute logger set 0') context.print_buffer('From this point on, this conversation will NOT be logged ANYMORE.') result = weechat.WEECHAT_RC_OK elif not context.is_encrypted(): context.print_buffer( 'OTR LOG: Not in an OTR session', 'error') result = weechat.WEECHAT_RC_OK else: # Don't need to do anything. result = weechat.WEECHAT_RC_OK else: print_buffer('', 'OTR LOG: Not in an OTR session', 'error') elif len(arg_parts) in (1, 2, 3, 4) and arg_parts[0] == 'policy': if len(arg_parts) == 1: nick, server = default_peer_args([], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.print_buffer(context.format_policies()) else: prnt('', format_default_policies()) result = weechat.WEECHAT_RC_OK elif len(arg_parts) == 2 and arg_parts[1].lower() == 'default': nick, server = default_peer_args([], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.print_buffer(format_default_policies()) else: prnt('', format_default_policies()) result = weechat.WEECHAT_RC_OK elif len(arg_parts) == 3 and arg_parts[1].lower() in POLICIES: nick, server = default_peer_args([], buf) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) policy_var = context.policy_config_option(arg_parts[1].lower()) command('', '/set {policy} {value}'.format( policy=policy_var, value=arg_parts[2])) context.print_buffer(context.format_policies()) result = weechat.WEECHAT_RC_OK elif len(arg_parts) == 4 and \ arg_parts[1].lower() == 'default' and \ arg_parts[2].lower() in POLICIES: nick, server = default_peer_args([], buf) policy_var = "otr.policy.default." + arg_parts[2].lower() command('', '/set {policy} {value}'.format( policy=policy_var, value=arg_parts[3])) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.print_buffer(format_default_policies()) else: prnt('', format_default_policies()) result = weechat.WEECHAT_RC_OK elif len(arg_parts) in (1, 2) and arg_parts[0] == 'fingerprint': if len(arg_parts) == 1: show_account_fingerprints() result = weechat.WEECHAT_RC_OK elif len(arg_parts) == 2: if arg_parts[1] == 'all': show_peer_fingerprints() else: show_peer_fingerprints(grep=arg_parts[1]) result = weechat.WEECHAT_RC_OK return result def otr_statusbar_cb(data, item, window): """Update the statusbar.""" if window: buf = weechat.window_get_pointer(window, 'buffer') else: # If the bar item is in a root bar that is not in a window, window # will be empty. buf = weechat.current_buffer() result = '' if buffer_is_private(buf): local_user = irc_user( buffer_get_string(buf, 'localvar_nick'), buffer_get_string(buf, 'localvar_server')) remote_user = irc_user( buffer_get_string(buf, 'localvar_channel'), buffer_get_string(buf, 'localvar_server')) context = ACCOUNTS[local_user].getContext(remote_user) encrypted_str = config_string('look.bar.state.encrypted') unencrypted_str = config_string('look.bar.state.unencrypted') authenticated_str = config_string('look.bar.state.authenticated') unauthenticated_str = config_string('look.bar.state.unauthenticated') logged_str = config_string('look.bar.state.logged') notlogged_str = config_string('look.bar.state.notlogged') bar_parts = [] if context.is_encrypted(): if encrypted_str: bar_parts.append(''.join([ config_color('status.encrypted'), encrypted_str, config_color('status.default')])) if context.is_verified(): if authenticated_str: bar_parts.append(''.join([ config_color('status.authenticated'), authenticated_str, config_color('status.default')])) elif unauthenticated_str: bar_parts.append(''.join([ config_color('status.unauthenticated'), unauthenticated_str, config_color('status.default')])) if context.is_logged(): if logged_str: bar_parts.append(''.join([ config_color('status.logged'), logged_str, config_color('status.default')])) elif notlogged_str: bar_parts.append(''.join([ config_color('status.notlogged'), notlogged_str, config_color('status.default')])) elif unencrypted_str: bar_parts.append(''.join([ config_color('status.unencrypted'), unencrypted_str, config_color('status.default')])) result = config_string('look.bar.state.separator').join(bar_parts) if result: result = '{color}{prefix}{result}'.format( color=config_color('status.default'), prefix=config_string('look.bar.prefix'), result=result) return result def bar_config_update_cb(data, option): """Callback for updating the status bar when its config changes.""" weechat.bar_item_update(SCRIPT_NAME) return weechat.WEECHAT_RC_OK def policy_completion_cb(data, completion_item, buf, completion): """Callback for policy tab completion.""" for policy in POLICIES: weechat.hook_completion_list_add( completion, policy, 0, weechat.WEECHAT_LIST_POS_SORT) return weechat.WEECHAT_RC_OK def policy_create_option_cb(data, config_file, section, name, value): """Callback for creating a new policy option when the user sets one that doesn't exist.""" weechat.config_new_option( config_file, section, name, 'boolean', '', '', 0, 0, value, value, 0, '', '', '', '', '', '') return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED def logger_level_update_cb(data, option, value): """Callback called when any logger level changes.""" weechat.bar_item_update(SCRIPT_NAME) return weechat.WEECHAT_RC_OK def buffer_switch_cb(data, signal, signal_data): """Callback for buffer switched. Used for updating the status bar item when it is in a root bar. """ weechat.bar_item_update(SCRIPT_NAME) return weechat.WEECHAT_RC_OK def buffer_closing_cb(data, signal, signal_data): """Callback for buffer closed. It closes the OTR session when the buffer is about to be closed. """ result = weechat.WEECHAT_RC_ERROR nick, server = default_peer_args([], signal_data) if nick is not None and server is not None: context = ACCOUNTS[current_user(server)].getContext( irc_user(nick, server)) context.disconnect() result = weechat.WEECHAT_RC_OK return result def init_config(): """Set up configuration options and load config file.""" global CONFIG_FILE CONFIG_FILE = weechat.config_new(SCRIPT_NAME, 'config_reload_cb', '') global CONFIG_SECTIONS CONFIG_SECTIONS = {} CONFIG_SECTIONS['general'] = weechat.config_new_section( CONFIG_FILE, 'general', 0, 0, '', '', '', '', '', '', '', '', '', '') for option, typ, desc, default in [ ('debug', 'boolean', 'OTR script debugging', 'off'), ('hints', 'boolean', 'Give helpful hints how to use this script and how to stay secure while using OTR (recommended)', 'on'), ('defaultkey', 'string', 'default private key to use for new accounts (nick@server)', ''), ('no_send_tag_regex', 'string', 'do not OTR whitespace tag messages to nicks matching this regex ' '(case insensitive)', '^(alis|chanfix|global|.+serv|\*.+)$'), ]: weechat.config_new_option( CONFIG_FILE, CONFIG_SECTIONS['general'], option, typ, desc, '', 0, 0, default, default, 0, '', '', '', '', '', '') CONFIG_SECTIONS['color'] = weechat.config_new_section( CONFIG_FILE, 'color', 0, 0, '', '', '', '', '', '', '', '', '', '') for option, desc, default, update_cb in [ ('status.default', 'status bar default color', 'default', 'bar_config_update_cb'), ('status.encrypted', 'status bar encrypted indicator color', 'green', 'bar_config_update_cb'), ('status.unencrypted', 'status bar unencrypted indicator color', 'lightred', 'bar_config_update_cb'), ('status.authenticated', 'status bar authenticated indicator color', 'green', 'bar_config_update_cb'), ('status.unauthenticated', 'status bar unauthenticated indicator color', 'lightred', 'bar_config_update_cb'), ('status.logged', 'status bar logged indicator color', 'lightred', 'bar_config_update_cb'), ('status.notlogged', 'status bar not logged indicator color', 'green', 'bar_config_update_cb'), ('buffer.hint', 'text color for hints', 'lightblue', ''), ('buffer.info', 'text color for informational messages', 'default', ''), ('buffer.success', 'text color for success messages', 'lightgreen', ''), ('buffer.warning', 'text color for warnings', 'yellow', ''), ('buffer.error', 'text color for errors', 'lightred', ''), ]: weechat.config_new_option( CONFIG_FILE, CONFIG_SECTIONS['color'], option, 'color', desc, '', 0, 0, default, default, 0, '', '', update_cb, '', '', '') CONFIG_SECTIONS['look'] = weechat.config_new_section( CONFIG_FILE, 'look', 0, 0, '', '', '', '', '', '', '', '', '', '') for option, desc, default, update_cb in [ ('bar.prefix', 'prefix for OTR status bar item', 'OTR:', 'bar_config_update_cb'), ('bar.state.encrypted', 'shown in status bar when conversation is encrypted', 'SEC', 'bar_config_update_cb'), ('bar.state.unencrypted', 'shown in status bar when conversation is not encrypted', '!SEC', 'bar_config_update_cb'), ('bar.state.authenticated', 'shown in status bar when peer is authenticated', 'AUTH', 'bar_config_update_cb'), ('bar.state.unauthenticated', 'shown in status bar when peer is not authenticated', '!AUTH', 'bar_config_update_cb'), ('bar.state.logged', 'shown in status bar when peer conversation is being logged to disk', 'LOG', 'bar_config_update_cb'), ('bar.state.notlogged', 'shown in status bar when peer conversation is not being logged to disk', '!LOG', 'bar_config_update_cb'), ('bar.state.separator', 'separator for states in the status bar', ',', 'bar_config_update_cb'), ('prefix', 'prefix used for messages from otr (note: content is evaluated, see /help eval)', '${color:default}:! ${color:brown}otr${color:default} !:', ''), ]: weechat.config_new_option( CONFIG_FILE, CONFIG_SECTIONS['look'], option, 'string', desc, '', 0, 0, default, default, 0, '', '', update_cb, '', '', '') CONFIG_SECTIONS['policy'] = weechat.config_new_section( CONFIG_FILE, 'policy', 1, 1, '', '', '', '', '', '', 'policy_create_option_cb', '', '', '') for option, desc, default in [ ('default.allow_v2', 'default allow OTR v2 policy', 'on'), ('default.require_encryption', 'default require encryption policy', 'off'), ('default.log', 'default enable logging to disk', 'off'), ('default.send_tag', 'default send tag policy', 'off'), ('default.html_escape', 'default HTML escape policy', 'off'), ('default.html_filter', 'default HTML filter policy', 'on'), ]: weechat.config_new_option( CONFIG_FILE, CONFIG_SECTIONS['policy'], option, 'boolean', desc, '', 0, 0, default, default, 0, '', '', '', '', '', '') weechat.config_read(CONFIG_FILE) def config_reload_cb(data, config_file): """/reload callback to reload config from file.""" free_all_config() init_config() return weechat.WEECHAT_CONFIG_READ_OK def free_all_config(): """Free all config options, sections and config file.""" for section in CONFIG_SECTIONS.values(): weechat.config_section_free_options(section) weechat.config_section_free(section) weechat.config_free(CONFIG_FILE) def create_dir(): """Create the OTR subdirectory in the WeeChat config directory if it does not exist.""" if not os.path.exists(OTR_DIR): weechat.mkdir_home(OTR_DIR_NAME, 0o700) def git_info(): """If this script is part of a git repository return the repo state.""" result = None script_dir = os.path.dirname(os.path.realpath(__file__)) git_dir = os.path.join(script_dir, '.git') if os.path.isdir(git_dir): import subprocess try: result = PYVER.to_unicode(subprocess.check_output([ 'git', '--git-dir', git_dir, '--work-tree', script_dir, 'describe', '--dirty', '--always', ])).lstrip('v').rstrip() except (OSError, subprocess.CalledProcessError): pass return result def weechat_version_ok(): """Check if the WeeChat version is compatible with this script. If WeeChat version < 0.4.2 log an error to the core buffer and return False. Otherwise return True. """ weechat_version = weechat.info_get('version_number', '') or 0 if int(weechat_version) < 0x00040200: error_message = ( '{script_name} requires WeeChat version >= 0.4.2. The current ' 'version is {current_version}.').format( script_name=SCRIPT_NAME, current_version=weechat.info_get('version', '')) prnt('', error_message) return False else: return True SCRIPT_VERSION = git_info() or SCRIPT_VERSION def dependency_versions(): """Return a string containing the versions of all dependencies.""" return ('weechat-otr {script_version}, ' 'potr {potr_major}.{potr_minor}.{potr_patch}-{potr_sub}, ' 'Python {python_version}, ' 'WeeChat {weechat_version}' ).format( script_version=SCRIPT_VERSION, potr_major=potr.VERSION[0], potr_minor=potr.VERSION[1], potr_patch=potr.VERSION[2], potr_sub=potr.VERSION[3], python_version=platform.python_version(), weechat_version=weechat.info_get('version', '')) def excepthook(typ, value, traceback): sys.stderr.write('Versions: ') sys.stderr.write(dependency_versions()) sys.stderr.write('\n') sys.__excepthook__(typ, value, traceback) sys.excepthook = excepthook if weechat.register( SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENCE, SCRIPT_DESC, 'shutdown', ''): if weechat_version_ok(): init_config() OTR_DIR = os.path.join(info_get('weechat_dir', ''), OTR_DIR_NAME) create_dir() ACCOUNTS = AccountDict() weechat.hook_modifier('irc_in_privmsg', 'message_in_cb', '') weechat.hook_modifier('irc_out_privmsg', 'message_out_cb', '') weechat.hook_command( SCRIPT_NAME, SCRIPT_HELP, 'start [NICK SERVER] || ' 'refresh [NICK SERVER] || ' 'finish [NICK SERVER] || ' 'end [NICK SERVER] || ' 'status [NICK SERVER] || ' 'smp ask [NICK SERVER] [QUESTION] SECRET || ' 'smp respond [NICK SERVER] SECRET || ' 'smp abort [NICK SERVER] || ' 'trust [NICK SERVER] || ' 'distrust [NICK SERVER] || ' 'log [on|off] || ' 'policy [POLICY on|off] || ' 'fingerprint [SEARCH|all]', '', 'start %(nick) %(irc_servers) %-||' 'refresh %(nick) %(irc_servers) %-||' 'finish %(nick) %(irc_servers) %-||' 'end %(nick) %(irc_servers) %-||' 'status %(nick) %(irc_servers) %-||' 'smp ask|respond %(nick) %(irc_servers) %-||' 'smp abort %(nick) %(irc_servers) %-||' 'trust %(nick) %(irc_servers) %-||' 'distrust %(nick) %(irc_servers) %-||' 'log on|off %-||' 'policy %(otr_policy) on|off %-||' 'fingerprint all %-||', 'command_cb', '') weechat.hook_completion( 'otr_policy', 'OTR policies', 'policy_completion_cb', '') weechat.hook_config('logger.level.irc.*', 'logger_level_update_cb', '') weechat.hook_signal('buffer_switch', 'buffer_switch_cb', '') weechat.hook_signal('buffer_closing', 'buffer_closing_cb', '') OTR_STATUSBAR = weechat.bar_item_new( SCRIPT_NAME, 'otr_statusbar_cb', '') weechat.bar_item_update(SCRIPT_NAME)
{ "content_hash": "5d0f4728cae7d2bc00ffd394e0a7420d", "timestamp": "", "source": "github", "line_count": 2035, "max_line_length": 257, "avg_line_length": 36.54103194103194, "alnum_prop": 0.5681069377765227, "repo_name": "darnir/dotfiles", "id": "404e96ab6c7bb035cc8021ccb7c679e28c13c20a", "size": "75565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Packages/IRC/weechat/python/otr.py", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "10536" }, { "name": "Awk", "bytes": "298" }, { "name": "JavaScript", "bytes": "27272" }, { "name": "Lua", "bytes": "47043" }, { "name": "Perl", "bytes": "178998" }, { "name": "Python", "bytes": "146548" }, { "name": "Shell", "bytes": "89222" }, { "name": "Vim script", "bytes": "81696" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline' 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> <link rel="stylesheet" type="text/css" href="css/index.css"> <title>Charades Boss!</title> <script type="text/javascript" src="js/data.js"></script> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript" src="js/react.js"></script> </head> <body> </body> <script type="text/javascript" src="js/app.js"></script> </html>
{ "content_hash": "38f7114ac6aff81c3f06ed7627ad7da9", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 192, "avg_line_length": 52.64705882352941, "alnum_prop": 0.641340782122905, "repo_name": "shiningweb/charades-boss", "id": "58dd73b52fa14499866eca65edf04c8da88f4231", "size": "895", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "www/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3621" }, { "name": "HTML", "bytes": "2316" }, { "name": "Java", "bytes": "6311" }, { "name": "JavaScript", "bytes": "6754" }, { "name": "Objective-C", "bytes": "4012" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Prodr. 24. 1788 #### Original name null ### Remarks null
{ "content_hash": "e06fd711c2c01521ab58f4bbb587375a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.076923076923077, "alnum_prop": 0.6875, "repo_name": "mdoering/backbone", "id": "f5972a8518cd69a7dbc50e3eb6ef2929e66be4d8", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Digitaria/Digitaria nuda/ Syn. Milium digitatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <relativePath>../seava.mod.ad</relativePath> <groupId>ro.seava.mod.ad</groupId> <artifactId>seava.mod.ad</artifactId> <version>2.0.0-SNAPSHOT</version> </parent> <artifactId>seava.mod.ad.business.api</artifactId> <name>AD - Business API</name> <description>AD module business layer interfaces.</description> <packaging>jar</packaging> <!-- ===================== Dependencies ===================== --> <dependencies> <!-- Internal --> <dependency> <groupId>ro.seava.lib.j4e</groupId> <artifactId>seava.j4e.api</artifactId> <version>2.0.0-SNAPSHOT</version> <type>jar</type> </dependency> <dependency> <groupId>ro.seava.lib.j4e</groupId> <artifactId>seava.j4e.domain</artifactId> <version>2.0.0-SNAPSHOT</version> <type>jar</type> </dependency> <dependency> <groupId>ro.seava.mod.ad</groupId> <artifactId>seava.mod.ad.domain</artifactId> <version>2.0.0-SNAPSHOT</version> <type>jar</type> </dependency> <!-- External --> <dependency> <groupId>javax.validation</groupId> <artifactId>com.springsource.javax.validation</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>org.eclipse.persistence.jpa</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.transaction</artifactId> </dependency> </dependencies> </project>
{ "content_hash": "ad9047310e786aef1242f7294869b3a6", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 104, "avg_line_length": 30.125, "alnum_prop": 0.6961733517750115, "repo_name": "seava/seava.mod.ad", "id": "e120499545ed0115d0d80d0af47961fdc8163d1d", "size": "2169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "seava.mod.ad.business.api/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "511817" }, { "name": "JavaScript", "bytes": "46698" }, { "name": "Shell", "bytes": "396" } ], "symlink_target": "" }
package jscover.report; import jscover.util.IoUtils; import jscover.util.ReflectionUtils; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.internal.matchers.TypeSafeMatcher; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; import java.util.TreeMap; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class JSONDataSaverTest { private JSONDataSaver jsonDataSaver = new JSONDataSaver(); private @Mock JSONDataMerger jsonDataMerger; private IoUtils ioUtils = IoUtils.getInstance(); private File destDir = new File("target"); private File jsonFile = new File(destDir,"jscoverage.json"); @Before public void setUp() { ReflectionUtils.setField(jsonDataSaver, "jsonDataMerger", jsonDataMerger); } @After public void tearDown() { jsonFile.delete(); } @Test public void shouldSaveData() { jsonDataSaver.saveJSONData(destDir, "data", null); String json = ioUtils.loadFromFileSystem(new File(destDir, "jscoverage.json")); assertThat(json, equalTo("data")); } @Test public void shouldSaveAndMergeData() { ioUtils.copy("json1", jsonFile);//Force merge SortedMap<String, FileData> map = new TreeMap<String, FileData>(); given(jsonDataMerger.mergeJSONCoverageData("json1", "json2")).willReturn(map); given(jsonDataMerger.toJSON(map)).willReturn("jsonMerged"); jsonDataSaver.saveJSONData(destDir, "json2", null); String json = ioUtils.loadFromFileSystem(jsonFile); assertThat(json, equalTo("jsonMerged")); } @Test public void shouldSaveAndIncludeUnloadedJS() { List<ScriptLinesAndSource> unloadJSData = new ArrayList<ScriptLinesAndSource>(); SortedMap<String, FileData> jsonMap = new TreeMap<String, FileData>(); final String loadedKey = "/loaded.js"; FileData fileData = new FileData(loadedKey, null, null, null); jsonMap.put(loadedKey, fileData); SortedMap<String, FileData> emptyJsonMap = new TreeMap<String, FileData>(); final String unloadedKey = "/unloaded.js"; FileData emptyFileData = new FileData(unloadedKey, null, null, null); emptyJsonMap.put(unloadedKey, emptyFileData); given(jsonDataMerger.createEmptyJSON(unloadJSData)).willReturn(emptyJsonMap); given(jsonDataMerger.jsonToMap("json1")).willReturn(jsonMap); Matcher<SortedMap<String, FileData>> arrayMatcher = new TypeSafeMatcher<SortedMap<String,FileData>>() { @Override public boolean matchesSafely(SortedMap<String, FileData> map) { return map.size() == 2 && map.containsKey(loadedKey) && map.containsKey(unloadedKey); } public void describeTo(Description description) { } }; given(jsonDataMerger.toJSON(argThat(arrayMatcher))).willReturn("jsonMerged"); jsonDataSaver.saveJSONData(destDir, "json1", unloadJSData); String json = ioUtils.loadFromFileSystem(jsonFile); assertThat(json, equalTo("jsonMerged")); } }
{ "content_hash": "d48ef4ae293eca08da81696d853b28a9", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 111, "avg_line_length": 36.336633663366335, "alnum_prop": 0.6863760217983651, "repo_name": "alfiethomas/datafilters", "id": "ffa6fd94217fc3a1ac980817367dd7a8d2767d6f", "size": "22049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/JSCover-0.1.1/src/test/java/jscover/report/JSONDataSaverTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "76632" }, { "name": "Java", "bytes": "1829941" }, { "name": "JavaScript", "bytes": "1066782" }, { "name": "PHP", "bytes": "65572" }, { "name": "Shell", "bytes": "2017" }, { "name": "XSLT", "bytes": "8933" } ], "symlink_target": "" }
<?php namespace CitasBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="citas") * @ORM\Entity(repositoryClass="CitasBundle\Repository\CitasRepository") */ class Citas { /** * @ORM\Id * @ORM\Column(name="codigo_citas_pk", type="integer", length=10) * @ORM\GeneratedValue(strategy="AUTO") */ private $codigoCitasPk; /** * @ORM\Column(name="hora_cita", type="time", nullable=true) */ private $horaCita; /** * @ORM\Column(name="dia_cita", type="date", nullable=true) */ private $diaCita; /** * @ORM\Column(name="start", type="string", nullable=true) */ private $start; /** * @ORM\Column(name="end", type="string", nullable=true) */ private $end; /** * @ORM\Column(name="asunto_cita", type="string", length=200, nullable=true) */ private $asuntoCita; /** * @ORM\Column(name="codigo_cliente_fk", type="integer", nullable=true, length=10) */ private $codigoClienteFk; /** * @ORM\Column(name="codigo_empleado_fk", type="integer", nullable=true, length=10 ) */ private $codigoEmpleadoFk; /** * @ORM\ManyToOne(targetEntity="\GeneralBundle\Entity\Cliente", inversedBy="clientesRel") * @ORM\JoinColumn(name="codigo_cliente_fk", referencedColumnName="codigo_cliente_pk") */ protected $clienteRel; /** * @ORM\ManyToOne(targetEntity="\EmpleadoBundle\Entity\Empleado", inversedBy="empleadoRel") * @ORM\JoinColumn(name="codigo_empleado_fk", referencedColumnName="codigo_empleado_pk") */ protected $empleadoRel; /** * Get codigoCitasPk * * @return integer */ public function getCodigoCitasPk() { return $this->codigoCitasPk; } /** * Set horaCita * * @param \DateTime $horaCita * * @return Citas */ public function setHoraCita($horaCita) { $this->horaCita = $horaCita; return $this; } /** * Get horaCita * * @return \DateTime */ public function getHoraCita() { return $this->horaCita; } /** * Set diaCita * * @param \DateTime $diaCita * * @return Citas */ public function setDiaCita($diaCita) { $this->diaCita = $diaCita; return $this; } /** * Get diaCita * * @return \DateTime */ public function getDiaCita() { return $this->diaCita; } /** * Set asuntoCita * * @param string $asuntoCita * * @return Citas */ public function setAsuntoCita($asuntoCita) { $this->asuntoCita = $asuntoCita; return $this; } /** * Get asuntoCita * * @return string */ public function getAsuntoCita() { return $this->asuntoCita; } /** * Set codigoClienteFk * * @param integer $codigoClienteFk * * @return Citas */ public function setCodigoClienteFk($codigoClienteFk) { $this->codigoClienteFk = $codigoClienteFk; return $this; } /** * Get codigoClienteFk * * @return integer */ public function getCodigoClienteFk() { return $this->codigoClienteFk; } /** * Set codigoEmpleadoFk * * @param integer $codigoEmpleadoFk * * @return Citas */ public function setCodigoEmpleadoFk($codigoEmpleadoFk) { $this->codigoEmpleadoFk = $codigoEmpleadoFk; return $this; } /** * Get codigoEmpleadoFk * * @return integer */ public function getCodigoEmpleadoFk() { return $this->codigoEmpleadoFk; } /** * Set clienteRel * * @param \GeneralBundle\Entity\Cliente $clienteRel * * @return Citas */ public function setClienteRel(\GeneralBundle\Entity\Cliente $clienteRel = null) { $this->clienteRel = $clienteRel; return $this; } /** * Get clienteRel * * @return \GeneralBundle\Entity\Cliente */ public function getClienteRel() { return $this->clienteRel; } /** * Set empleadoRel * * @param \EmpleadoBundle\Entity\Empleado $empleadoRel * * @return Citas */ public function setEmpleadoRel(\EmpleadoBundle\Entity\Empleado $empleadoRel = null) { $this->empleadoRel = $empleadoRel; return $this; } /** * Get empleadoRel * * @return \EmpleadoBundle\Entity\Empleado */ public function getEmpleadoRel() { return $this->empleadoRel; } /** * Set start * * @param string $start * * @return Citas */ public function setStart($start) { $this->start = $start; return $this; } /** * Get start * * @return string */ public function getStart() { return $this->start; } /** * Set end * * @param string $end * * @return Citas */ public function setEnd($end) { $this->end = $end; return $this; } /** * Get end * * @return string */ public function getEnd() { return $this->end; } }
{ "content_hash": "c199994bcb9658c82598553ca38294d9", "timestamp": "", "source": "github", "line_count": 295, "max_line_length": 95, "avg_line_length": 18.189830508474575, "alnum_prop": 0.538948937756243, "repo_name": "pipeospina1320/agendacitas", "id": "5611c834526071cbab85f0799873a573ff76a61b", "size": "5366", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CitasBundle/Entity/Citas.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "236158" }, { "name": "HTML", "bytes": "258779" }, { "name": "JavaScript", "bytes": "607353" }, { "name": "PHP", "bytes": "611747" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: attached.qrc Example File (declarative/cppextensions/referenceexamples/attached/attached.qrc)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">attached.qrc Example File</h1> <span class="small-subtitle">declarative/cppextensions/referenceexamples/attached/attached.qrc</span> <!-- $$$declarative/cppextensions/referenceexamples/attached/attached.qrc-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> &lt;!DOCTYPE RCC&gt;&lt;RCC version=&quot;1.0&quot;&gt; &lt;qresource&gt; &lt;file&gt;example.qml&lt;/file&gt; &lt;/qresource&gt; &lt;/RCC&gt;</pre> </div> <!-- @@@declarative/cppextensions/referenceexamples/attached/attached.qrc --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
{ "content_hash": "5f0ba0122fabaa657bc9a51e22090990", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 221, "avg_line_length": 46.14975845410628, "alnum_prop": 0.5619177221815137, "repo_name": "stephaneAG/PengPod700", "id": "5d58c39dda59858bd2f31627633dd1e803d939ff", "size": "9553", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "QtEsrc/backup_qt/qt-everywhere-opensource-src-4.8.5/doc/html/declarative-cppextensions-referenceexamples-attached-attached-qrc.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "167426" }, { "name": "Batchfile", "bytes": "25368" }, { "name": "C", "bytes": "3755463" }, { "name": "C#", "bytes": "9282" }, { "name": "C++", "bytes": "177871700" }, { "name": "CSS", "bytes": "600936" }, { "name": "GAP", "bytes": "758872" }, { "name": "GLSL", "bytes": "32226" }, { "name": "Groff", "bytes": "106542" }, { "name": "HTML", "bytes": "273585110" }, { "name": "IDL", "bytes": "1194" }, { "name": "JavaScript", "bytes": "435912" }, { "name": "Makefile", "bytes": "289373" }, { "name": "Objective-C", "bytes": "1898658" }, { "name": "Objective-C++", "bytes": "3222428" }, { "name": "PHP", "bytes": "6074" }, { "name": "Perl", "bytes": "291672" }, { "name": "Prolog", "bytes": "102468" }, { "name": "Python", "bytes": "22546" }, { "name": "QML", "bytes": "3580408" }, { "name": "QMake", "bytes": "2191574" }, { "name": "Scilab", "bytes": "2390" }, { "name": "Shell", "bytes": "116533" }, { "name": "TypeScript", "bytes": "42452" }, { "name": "Visual Basic", "bytes": "8370" }, { "name": "XQuery", "bytes": "25094" }, { "name": "XSLT", "bytes": "252382" } ], "symlink_target": "" }
package chatapp_test import ( "github.com/crawsible/crawsibot/chatapp" "github.com/crawsible/crawsibot/chatapp/mocks" "github.com/crawsible/crawsibot/config" "github.com/crawsible/crawsibot/eventinterp/event" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("JoinChannelApp", func() { var app *chatapp.JoinChannelApp Describe("#BeginChatting", func() { var ( fakeRegistrar *mocks.FakeRegistrar eventCh chan *event.Event fakeSender *mocks.FakeSender cfg *config.Config ) BeforeEach(func() { eventCh = make(chan *event.Event, 1) fakeRegistrar = &mocks.FakeRegistrar{EnrollForEventsReturnChan: eventCh} fakeSender = &mocks.FakeSender{} cfg = &config.Config{Channel: "somechannel"} app = &chatapp.JoinChannelApp{} app.BeginChatting(fakeRegistrar, fakeSender, cfg) }) It("enrolls with its registrar for login and channeljoin messages", func() { Expect(fakeRegistrar.EnrollForEventsCalls).To(Equal(1)) Expect(fakeRegistrar.EnrollForEventsTypes).To(Equal([]event.Type{event.Login, event.ChannelJoin})) }) It("sets its EventCh with the chan provided by its registrar", func() { Expect(app.EventCh).NotTo(Receive()) eventCh <- &event.Event{} Expect(app.EventCh).To(Receive()) }) Context("when receiving a login message over the event channel", func() { It("sends the appropriate channel-joining params to the provided sender", func() { Consistently(fakeSender.SendCalls).Should(Equal(0)) app.EventCh <- &event.Event{Type: event.Login} Eventually(fakeSender.SendCalls).Should(Equal(1)) Expect(fakeSender.SendCmd).To(Equal("JOIN")) Expect(fakeSender.SendFprms).To(Equal("#somechannel")) Expect(fakeSender.SendPrms).To(Equal("")) }) }) Context("before sending its join command", func() { It("doesn't respond to channeljoin messages", func() { app.EventCh <- &event.Event{Type: event.ChannelJoin} Consistently(fakeSender.SendCalls).Should(Equal(0)) }) }) Context("after sending its join command", func() { BeforeEach(func() { Consistently(fakeSender.SendCalls).Should(Equal(0)) app.EventCh <- &event.Event{Type: event.Login} Eventually(fakeSender.SendCalls).Should(Equal(1)) }) Context("when receiving a channeljoin for the correct channel", func() { var channeljoinData map[string]string BeforeEach(func() { channeljoinData = map[string]string{ "joinedChannel": "somechannel", } app.EventCh <- &event.Event{event.ChannelJoin, channeljoinData} }) It("announces its arrival", func() { Eventually(fakeSender.SendCalls).Should(Equal(2)) Expect(fakeSender.SendCmd).To(Equal("PRIVMSG")) Expect(fakeSender.SendFprms).To(Equal("#somechannel")) Expect(fakeSender.SendPrms).To(Equal("COME WITH ME IF YOU WANT TO LIVE.")) }) It("stops listening on the channel", func() { Eventually(fakeSender.SendCalls).Should(Equal(2)) Expect(fakeRegistrar.UnsubscribeCalls).To(Equal(1)) Expect(fakeRegistrar.UnsubscribeChan).To(Equal(app.EventCh)) }) }) }) }) })
{ "content_hash": "854b5a4771bcd990cb00729f372aacc7", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 101, "avg_line_length": 32.16494845360825, "alnum_prop": 0.6977564102564102, "repo_name": "crawsible/crawsibot", "id": "35f1dcf71d92b9a65f77803d5eff6e85ad3b6170", "size": "3120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chatapp/join_channel_app_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "53013" } ], "symlink_target": "" }
using RestSharp; using System.Collections.Generic; using System.Linq; namespace pillowsharp.Middleware.Default { public class RestSharpResponse : RestResponse { private IRestResponse restSharpResponse = null; public RestSharpResponse(IRestResponse Response) { restSharpResponse = Response; this.Content = restSharpResponse.Content; this.ResponseCode = restSharpResponse.StatusCode; this.RawBytes = restSharpResponse.RawBytes; var cookies = new List<SimpleCookie>(); foreach(var restCookie in Response.Cookies) { cookies.Add(new SimpleCookie() { Name = restCookie.Name, Value = restCookie.Value }); } this.Cookies = cookies; this.Header = new List<KeyValuePair<string, string>>(); foreach (var header in Response.Headers.Where(h => h.Type == ParameterType.HttpHeader)) { this.Header.Add(new KeyValuePair<string, string>(header.Name, header.Value?.ToString())); } } } }
{ "content_hash": "e136f52c5b48adb75405cc0003297c6d", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 105, "avg_line_length": 34.53125, "alnum_prop": 0.6190045248868778, "repo_name": "Dev-Owl/pillowsharp", "id": "24a9d0b03fb9d6b22e02416aea9646af79758b75", "size": "1107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/libary/Middleware/Default/RestSharpResponse.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "789" }, { "name": "C#", "bytes": "157747" }, { "name": "Shell", "bytes": "928" } ], "symlink_target": "" }
layout: article categories: tutorials otstutorials title: What is Arbor? summary: An introduction to our workflow software comments: true image: teaser: arbor-400x250.jpg --- <h2>What is Arbor?</h2> Arbor is a software package for phylogenetic comparative analyses. Our main website is: <a href="http://www.arborworkflows.com/">www.arborworkflows.com</a> <h2>When will Arbor be available?</h2> Right now! And Arbor's functionality continues to grow. <h2>What will Arbor be able to do for me?</h2> To start out with, Arbor will be able to do the most common comparative analyses, including: - Phylogenetic signal - Ancestral state reconstruction - Independent contrasts - Comparative model fitting (e.g. Mk, threshold, and continuous character models) - PGLS - Fitting Birth-death models - Community phylogenetics - BiSSE / MuSSE / QuaSSE / GeoSSE - Analyses of cospeciation We are building up towards more complicated analyses. <h2>What is an Arbor workflow?</h2> Phylogenetic trees are increasingly [available](http://blog.opentreeoflife.org), and can be used for a wide range of analyses, including studies of speciation, trait evolution, range size evolution, and many other things. Phylogenetic comparative methods have been developing rapidly in recent years. Most analyses are currently done in R, and a number of useful packages are available (e.g. ape, diversitree, geiger, caper, phytools, [and others](http://cran.r-project.org/web/views/Phylogenetics.html)). Arbor seeks to enable end-users to carry out these analyses by building workflows. Building an Arbor workflow will have more in common with making something out of legos than with computer programming. For example, the figure below shows a mockup of an Arbor workflow to calculate phylogenetic independent contrasts (PICs). End users will import a phylogenetic tree and some traits data - perhaps from their local computer, or maybe from a remote source like [Open Tree of Life](https://tree.opentreeoflife.org/opentree/argus/) or [Encyclopedia of Life](http://eol.org). The workflow below then allows the user to connect a few steps together to calculate PICs and use them to test for a correlation between two traits. ![PIC workflow]({{ site.baseurl }}/assets/simple_pic_workflow.jpg) **A sample workflow for calculating phylogenetic independent contrasts (PICs) to test for an evolutionary correlation between two traits.** The PIC workflow above is simple, but Arbor will enable more complex analyses as well. For example, imagine you are interested in analyzing geographic range evolution in your group of species. ![Web workflow]({{ site.baseurl }}/assets/cartoon_workflow.png) **A more complex workflow that uses data from web services to combine ecological niche models, Lagrange, and phylogenetic comparative analyses.** The workflow above shows how you might use Arbor to link phylogenetic, trait, and geographic data together in a comprehensive set of comparative analyses. If you want to get an idea of other examples of workflow software in biology, you can check out other examples like [Galaxy](https://usegalaxy.org/) and the [iPlant Discovery Environment](http://www.cyverse.org/discovery-environment). <h2>How can I participate in the project?</h2> You can follow our blog, visit our main site, and find our code on github. We will also be hosting a series of hackathons to be announced at a later date.
{ "content_hash": "609e3fe6b848268935a0583fa8ecbe05", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 636, "avg_line_length": 57.91525423728814, "alnum_prop": 0.7863623061164764, "repo_name": "arborworkflows/arborworkflows.github.com", "id": "722c46da6eda2ad2a70a31d1f5fcda7551797b9f", "size": "3421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/tutorials/2015-05-21-what-is-arbor.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "119006" }, { "name": "HTML", "bytes": "944396" }, { "name": "JavaScript", "bytes": "16633" }, { "name": "R", "bytes": "26" }, { "name": "Ruby", "bytes": "2978" }, { "name": "Shell", "bytes": "216" } ], "symlink_target": "" }
#import <Foundation/Foundation.h> #import "Video.h" #include "gif_lib.h" @interface GifVideo : Video { // gif state GifFileType *gifinfo; int transindex; int disposal; bool trans; bool bestQuality; bool readingFrame; unsigned int current_frame; } // Overrides - (id)initWithSource:(VideoSource*)source inContext:(EAGLContext*)ctx; - (void)frameClipScale:(float*)scale; - (CGSize)frameSize; - (bool)drawFrame:(VideoWorkerFrame_t*)current_frame andDisposal:(bool)updateDisposal; - (void)flushState; @end
{ "content_hash": "cd0d5c68f5c8d9bab9f51f7d24fabe47", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 86, "avg_line_length": 19.607142857142858, "alnum_prop": 0.6994535519125683, "repo_name": "jamesu/glgif", "id": "484bbbe4205564e3c0fad1b348e03b3fb988cdd4", "size": "1717", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "glgif/GifVideo.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "114712" }, { "name": "Objective-C", "bytes": "67250" } ], "symlink_target": "" }
<?php namespace AW\AnimalsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class AWAnimalsBundle extends Bundle { }
{ "content_hash": "b48bdf524e5c8f71f37c499b40d95b51", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 47, "avg_line_length": 14, "alnum_prop": 0.8015873015873016, "repo_name": "guillaumebaduel/aw", "id": "352b10d5b6b5dd5d2216f0c647f65e105af583b2", "size": "126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AW/AnimalsBundle/AWAnimalsBundle.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3606" }, { "name": "HTML", "bytes": "4970" }, { "name": "PHP", "bytes": "58736" } ], "symlink_target": "" }
package gopass.gui; import java.awt.Font; import javax.swing.JScrollPane; import javax.swing.JTextArea; /** * A pane for displaying information * * @author Jason Mey * @version 1.0 */ @SuppressWarnings("serial") public class InfoPane extends JScrollPane { /** The main text area of the pane */ public JTextArea textArea; /** * Creates a blank pane * * @param rows * the number of rows for the text area * @param cols * the number of columns for the text area */ public InfoPane(int rows, int cols) { super(); textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setColumns(cols); textArea.setRows(rows); this.setViewportView(textArea); this .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); this .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } /** * Adds the information to the text area in the pane * * @param info * the string of information */ public void setInfo(String info) { textArea.setText(info); } /** * Sets the font of the text area * * @param font * the new font to use */ public void setTextFont(Font font) { textArea.setFont(font); } /** * Move the scroll bar to the top */ public void toTop() { // Moving the caret to the start moves the bar textArea.setCaretPosition(0); } }
{ "content_hash": "da7547f88527830def1bec131a1254d2", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 74, "avg_line_length": 20.885714285714286, "alnum_prop": 0.6703146374829001, "repo_name": "chessnerd/GoPass", "id": "47a3df4d239c3b3739154998007195638790ce7c", "size": "1462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gopass/gui/InfoPane.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "53139" } ], "symlink_target": "" }
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DvsPortExitedPassthruEvent complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DvsPortExitedPassthruEvent"> * &lt;complexContent> * &lt;extension base="{urn:vim25}DvsEvent"> * &lt;sequence> * &lt;element name="portKey" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="runtimeInfo" type="{urn:vim25}DVPortStatus" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DvsPortExitedPassthruEvent", propOrder = { "portKey", "runtimeInfo" }) public class DvsPortExitedPassthruEvent extends DvsEvent { @XmlElement(required = true) protected String portKey; protected DVPortStatus runtimeInfo; /** * Gets the value of the portKey property. * * @return * possible object is * {@link String } * */ public String getPortKey() { return portKey; } /** * Sets the value of the portKey property. * * @param value * allowed object is * {@link String } * */ public void setPortKey(String value) { this.portKey = value; } /** * Gets the value of the runtimeInfo property. * * @return * possible object is * {@link DVPortStatus } * */ public DVPortStatus getRuntimeInfo() { return runtimeInfo; } /** * Sets the value of the runtimeInfo property. * * @param value * allowed object is * {@link DVPortStatus } * */ public void setRuntimeInfo(DVPortStatus value) { this.runtimeInfo = value; } }
{ "content_hash": "7c334a8ab84476a0b70402f3cd3f902a", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 95, "avg_line_length": 24.142857142857142, "alnum_prop": 0.5798816568047337, "repo_name": "jdgwartney/vsphere-ws", "id": "cf8b401ff478bc48aa1e5d92c180a579ef50b294", "size": "2197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/JAXWS/samples/com/vmware/vim25/DvsPortExitedPassthruEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1349" }, { "name": "C#", "bytes": "775222" }, { "name": "C++", "bytes": "14040" }, { "name": "CSS", "bytes": "48826" }, { "name": "Java", "bytes": "13417097" }, { "name": "JavaScript", "bytes": "24681" }, { "name": "Shell", "bytes": "9982" }, { "name": "Smalltalk", "bytes": "14906" } ], "symlink_target": "" }
http://stackoverflow.com/questions/19298782/themeing-a-spree-installation-causing-a-deface-nightmare # monologue-markdown This is a simple extension that will change [Monologue](https://github.com/jipiboily/monologue)'s default editor to EpicEditor which will let you use Markdown instead of a WYSIWYG edit. IMPORTANT: this README is for Monologue 0.3.X. ## Install on a brand new Monologue installation This is simple, you just have to add this file to your `Gemfile` after Monologue: gem "monologue-markdown", github: "tetuyoko/monologue-markdown" Then run this: bundle exec rake monologue_markdown:install:migrations bundle exec rake db:migrate ## Install on an already existing Monologue installation You do the same as for a new Monologue installation, but, keep in mind that only new posts will have EpicEditor enabled. All the posts that existed before will still be using the WYSIWYG editor. ## For Code Highlighting sudo easy_install Pygments ## Notes There are [Deface](https://github.com/railsdog/deface/) overrides with this project. You might want to (read: "should") turn it off on production. If you do, you can add a Capistrano task to precompile them or precompile them locally. [Read more about this here.](https://github.com/railsdog/deface/#production--precompiling)
{ "content_hash": "61e21dc6506ecd33e440443f51a353d6", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 234, "avg_line_length": 41.0625, "alnum_prop": 0.7808219178082192, "repo_name": "shozawa/monologue-markdown", "id": "2493ebe8b1f341e756d782227eb4a6e7ead94bb4", "size": "1402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14392" }, { "name": "HTML", "bytes": "27217" }, { "name": "JavaScript", "bytes": "1269" }, { "name": "Ruby", "bytes": "24607" } ], "symlink_target": "" }
function model = dnetUpdateOutputWeights(model) % DNETUPDATEOUTPUTWEIGHTS Do an M-step (update parameters) on an Density Network model. % FORMAT % DESC updates the parameters of a Density Network model. % ARG model : the model which is to be updated. % RETURN model : the model with updated parameters. % % SEEALSO : dnetCreate, dnetUpdateBeta % % COPYRIGHT : Neil D. Lawrence, 2008 % GPMAT if model.basisStored G = sparseDiag(sum(model.w, 1)'); Phi = [model.Phi ones(model.M, 1)]; A = pdinv(Phi'*G*Phi+model.alpha/model.beta*speye(size(Phi, 2)))*Phi'*model.w'*model.y; model.A = A(1:size(model.Phi, 2), :); model.b = A(end, :); model.mapping = modelSetOutputWeights(model.mapping, model.A, model.b); end
{ "content_hash": "dc2aeb34bfda685c13822655e02e828d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 91, "avg_line_length": 32.30434782608695, "alnum_prop": 0.6890982503364738, "repo_name": "lawrennd/GPmat", "id": "9a482b4b0fda9e52e7f4db2d82a62070a7531ef8", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "matlab/dnetUpdateOutputWeights.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "12748" }, { "name": "HTML", "bytes": "73506" }, { "name": "M", "bytes": "1415" }, { "name": "Matlab", "bytes": "6289181" }, { "name": "TeX", "bytes": "49872" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserManager.Core.Applications.Aggregate { public class Permission { public Guid Id { get; set; } public string Code { get; set; } public string Description { get; set; } } }
{ "content_hash": "18dbcc71e89846adcd9d21cb96f1dcf3", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 49, "avg_line_length": 22.466666666666665, "alnum_prop": 0.6824925816023739, "repo_name": "kendarorg/ECQRSFramrework", "id": "06d204cfdee6fdbd69184f4cda3a7cd8301c8412", "size": "1846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ECQRSFramrework/Samples/UsersManager/UserManager.Applications/Aggregate/Permission.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "4640" }, { "name": "Batchfile", "bytes": "15745" }, { "name": "C#", "bytes": "952683" }, { "name": "CSS", "bytes": "63070" }, { "name": "HTML", "bytes": "51743" }, { "name": "JavaScript", "bytes": "295334" } ], "symlink_target": "" }
.icons{ background-image: url('../images/icon/icons.png'); background-size: 659px 345px; background-repeat: no-repeat; display: inline-block; vertical-align: middle; } .icons.icon-dola{ width: 40px; height: 65px; background-position: -510px 0; } .icons.icon-time{ width: 65px; height: 65px; background-position: -441px 0; } .icons.icon-doc-active{ width: 85px; height: 108px; background-position: 0 0; } .icons.icon-onepay{ background-position: -440px -231px; width: 80px; height: 38px; } .icons.icon-visa{ background-position: 0 -231px; width: 105px; height: 36px; } .icons.icon-mestacard{ background-position: -118px -231px; width: 85px; height: 40px; } .icons.icon-visa-verified{ background-position: -204px -231px; width: 95px; height: 40px; } .icons.icon-mestacard-sourecode{ background-position: -325px -231px; width: 110px; height: 40px; } .icons.icon-add{ background-position: -327px -121px; width: 33px; height: 33px; } .icons.icon-avatar{ width: 52px; height: 63px; background-position: 0 -161px; } .icons.icon-avatar-1{ width: 50px; height: 63px; background-position: -57px -161px; } .icons.icon-avatar-2{ width: 53px; height: 63px; background-position: -110px -161px; } .icons.icon-avatar-3{ width: 53px; height: 63px; background-position: -165px -161px; } .icons.icon-avatar-active, .icons.icon-avatar:hover{ width: 52px; height: 63px; background-position: -220px -161px; } .icons.icon-avatar-active-1, .icons.icon-avatar-1:hover{ width: 50px; height: 63px; background-position: -276px -161px; } .icons.icon-avatar-active-2{ width: 53px; height: 63px; background-position: -331px -161px; } .icons.icon-avatar-active-3{ width: 53px; height: 63px; background-position: -384px -161px; } .icons.icon-facebook-active{ width: 40px; height: 40px; background-position: 0 -119px; } .icons.icon-twitter{ width: 40px; height: 40px; background-position: -199px -119px; } .icons.icon-google{ width: 40px; height: 40px; background-position: -240px -119px; } .icon-photographer{ background-image: url('../images/jobs/photograper.png'); background-repeat: no-repeat; display: inline-block; vertical-align: middle; width: 70px; height: 54px; } /*edit profile personal*/ .icon-education-progress{ background-position: -140px bottom; height: 65px; width: 65px; } .icon-workdone-progress{ background-position: -70px bottom; height: 65px; width: 65px; } .icon-work-progress{ background-position: 0 bottom; height: 65px; width: 65px; } /*icon jobs*/ .job-software{ background-position: 0 0; } .job-sof-other{ background-position: -70px 0; } .job-camera{ background-position: -140px 0; } .job-internet{ background-position: -210px 0; } .job-dev-game{ background-position: -280px 0; } .job-dev-software{ background-position: -350px 0; } .job-dev-website{ background-position: -420px 0; } .job-tester{ background-position: -490px 0; } .job-project-manager{ background-position: -560px 0; } .job-id-Hardware{ background-position: -630px 0; } .job-domain-hosting{ background-position: -700px 0; } .job-app-mobile{ background-position: -770px 0; } .job-design-other{ background-position: 0px -70px; } .job-packaging-label{ background-position: -70px -70px; } .job-catalogue{ background-position: -140px -70px; } .job-booth-posm-salekit{ background-position: -210px -70px; } .job-brochure-profile{ background-position: -280px -70px; } .job-design-web-app{ background-position: -350px -70px; } .job-architecture{ background-position: -420px -70px; } .job-card-calendar{ background-position: -490px -70px; } .job-design-logo{ background-position: -560px -70px; } .job-poster-banner-flyer{ background-position: -630px -70px; } .job-design-fashion{ background-position: -700px -70px; } .job-design-video{ background-position: -770px -70px; } .job-doctor{ background-position: 0px -140px; } .job-moving-relocation{ background-position: -70px -140px; } .job-homeserve-other{ background-position: -140px -140px; } .job-teacher-painter-assistant{ background-position: -210px -140px; } .job-house-maid{ background-position: -280px -140px; } .job-gardening-locksmith{ background-position: -350px -140px; } .job-repair-power-water{ background-position: -420px -140px; } .job-repair-consumer-electronics{ background-position: -490px -140px; } .job-cleaner-protect-guard-driver{ background-position: -560px -140px; } .job-themed-plaster-masonry-glass-aluminum{ background-position: -630px -140px; } .job-unclog-drain-concrete{ background-position: -700px -140px; } .job-construction-interior-exterior{ background-position: -770px -140px; } .job-content-editor{ background-position: 0px -210px; } .job-translation{ background-position: -70px -210px; } .job-content-other{ background-position: -140px -210px; } .job-translating-directly{ background-position: -210px -210px; } .job-writer-blog{ background-position: -280px -210px; } .job-writer-pr-advertising{ background-position: -350px -210px; } .job-writer-resumes-cvs{ background-position: -420px -210px; } .job-rriter-content-website{ background-position: -490px -210px; } .job-strategy-marketing-plan{ background-position: 0px -280px; } .job-banner-advertising{ background-position: -70px -280px; } .job-marketing-other{ background-position: -140px -280px; } .job-email-marketing{ background-position: -210px -280px; } .job-market-surveys{ background-position: -280px -280px; } .job-sem{ background-position: -350px -280px; } .job-seo{ background-position: -420px -280px; } .job-smm{ background-position: -490px -280px; } .job-performing-group-pg{ background-position: 0px -350px; } .job-equipment-event{ background-position: -70px -350px; } .job-event-other{ background-position: -140px -350px; } .job-organizing-performance{ background-position: -210px -350px; } .job-organization-bidding{ background-position: -280px -350px; } .job-organization-seminars{ background-position: -350px -350px; } .job-organization-exhibitions{ background-position: -420px -350px; } .job-Costumes{ background-position: -490px -350px; } .job-cleaning-other{ background-position: 0px -420px; } .job-cleaning-aquarium{ background-position: -70px -420px; } .job-industrial-hygienist{ background-position: -140px -420px; } .job-cleaning-house{ background-position: -210px -420px; } .job-cleaning-office{ background-position: -280px -420px; } .job-waste-treatment{ background-position: -350px -420px; } .job-edit-image{ background-position: 0px -490px; } .job-photographer{ background-position: -70px -490px; } .job-photo-other{ background-position: -140px -490px; } .job-model-photo{ background-position: -210px -490px; } .job-cameraman{ background-position: -280px -490px; }
{ "content_hash": "cd48f063342c81479064d8024ea15bbe", "timestamp": "", "source": "github", "line_count": 373, "max_line_length": 60, "avg_line_length": 19.327077747989275, "alnum_prop": 0.6774864752392842, "repo_name": "huynhtuvinh87/cms", "id": "50336bd4b1322241350e7cbfa14ae26ba4859a94", "size": "7209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/web/css/icon.css", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "131274" }, { "name": "ApacheConf", "bytes": "411" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "442223" }, { "name": "HTML", "bytes": "41838" }, { "name": "Java", "bytes": "1522686" }, { "name": "JavaScript", "bytes": "2168050" }, { "name": "PHP", "bytes": "857903" }, { "name": "Shell", "bytes": "3308" } ], "symlink_target": "" }
package org.apache.tiles.portlet.context; import java.io.IOException; import java.util.Collections; import java.util.Locale; import java.util.Map; import javax.portlet.PortletContext; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.apache.tiles.context.TilesRequestContext; import org.apache.tiles.util.TilesIOException; /** * Portlet-based TilesApplicationContext implementation. * * @version $Rev$ $Date$ */ public class PortletTilesRequestContext extends PortletTilesApplicationContext implements TilesRequestContext { /** * <p>The lazily instantiated <code>Map</code> of header name-value * combinations (immutable).</p> */ private Map<String, String> header = null; /** * <p>The lazily instantitated <code>Map</code> of header name-values * combinations (immutable).</p> */ private Map<String, String[]> headerValues = null; /** * <p>The <code>PortletRequest</code> for this request.</p> */ protected PortletRequest request = null; /** * <p>The lazily instantiated <code>Map</code> of request scope * attributes.</p> */ private Map<String, Object> requestScope = null; /** * <p>The <code>PortletResponse</code> for this request.</p> */ protected PortletResponse response = null; /** * <p>The lazily instantiated <code>Map</code> of session scope * attributes.</p> */ private Map<String, Object> sessionScope = null; /** * <p>Indicates whether the request is an ActionRequest or RenderRequest. */ private boolean isRenderRequest; /** * <p>The lazily instantiated <code>Map</code> of request * parameter name-value.</p> */ protected Map<String, String> param = null; /** * <p>The lazily instantiated <code>Map</code> of request * parameter name-values.</p> */ protected Map<String, String[]> paramValues = null; /** * Creates a new instance of PortletTilesRequestContext. * * @param context The portlet context to use. * @param request The request object to use. * @param response The response object to use. */ public PortletTilesRequestContext(PortletContext context, PortletRequest request, PortletResponse response) { super(context); initialize(request, response); } /** * <p>Initialize (or reinitialize) this {@link PortletTilesRequestContext} instance * for the specified Portlet API objects.</p> * * @param request The <code>PortletRequest</code> for this request * @param response The <code>PortletResponse</code> for this request */ public void initialize(PortletRequest request, PortletResponse response) { // Save the specified Portlet API object references this.request = request; this.response = response; // Perform other setup as needed this.isRenderRequest = false; if (request != null) { if (request instanceof RenderRequest) { isRenderRequest = true; } } } /** * <p>Release references to allocated resources acquired in * <code>initialize()</code> of via subsequent processing. After this * method is called, subsequent calls to any other method than * <code>initialize()</code> will return undefined results.</p> */ public void release() { // Release references to allocated collections header = null; headerValues = null; param = null; paramValues = null; requestScope = null; sessionScope = null; // Release references to Portlet API objects context = null; request = null; response = null; super.release(); } /** * <p>Return the {@link PortletRequest} for this context.</p> * * @return The used portlet request. */ public PortletRequest getRequest() { return (this.request); } /** * <p>Return the {@link PortletResponse} for this context.</p> * * @return The used portlet response. */ public PortletResponse getResponse() { return (this.response); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public Map<String, String> getHeader() { if ((header == null) && (request != null)) { header = Collections.EMPTY_MAP; } return (header); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public Map<String, String[]> getHeaderValues() { if ((headerValues == null) && (request != null)) { headerValues = Collections.EMPTY_MAP; } return (headerValues); } /** {@inheritDoc} */ public Map<String, String> getParam() { if ((param == null) && (request != null)) { param = new PortletParamMap(request); } return (param); } /** {@inheritDoc} */ public Map<String, String[]> getParamValues() { if ((paramValues == null) && (request != null)) { paramValues = new PortletParamValuesMap(request); } return (paramValues); } /** {@inheritDoc} */ public Map<String, Object> getRequestScope() { if ((requestScope == null) && (request != null)) { requestScope = new PortletRequestScopeMap(request); } return (requestScope); } /** {@inheritDoc} */ public Map<String, Object> getSessionScope() { if ((sessionScope == null) && (request != null)) { sessionScope = new PortletSessionScopeMap(request.getPortletSession()); } return (sessionScope); } /** {@inheritDoc} */ public void dispatch(String path) throws IOException { include(path); } /** {@inheritDoc} */ public void include(String path) throws IOException { if (isRenderRequest) { try { PortletRequestDispatcher rd = context.getRequestDispatcher(path); if (rd == null) { throw new IOException( "No portlet request dispatcher returned for path '" + path + "'"); } rd.include((RenderRequest) request, (RenderResponse) response); } catch (PortletException e) { throw new TilesIOException( "PortletException while including path '" + path + "'.", e); } } } /** {@inheritDoc} */ public Locale getRequestLocale() { if (request != null) { return request.getLocale(); } else { return null; } } /** {@inheritDoc} */ public boolean isUserInRole(String role) { return request.isUserInRole(role); } }
{ "content_hash": "871c574bf4c32e725f520b68064b3e61", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 111, "avg_line_length": 28.46825396825397, "alnum_prop": 0.5873989406189016, "repo_name": "brettryan/tiles", "id": "7383cb1a8f4dace6de5e77f459bf97417f6b19ef", "size": "7990", "binary": false, "copies": "1", "ref": "refs/heads/TILES_2_0_X", "path": "tiles-core/src/main/java/org/apache/tiles/portlet/context/PortletTilesRequestContext.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseNullPropagation { internal abstract class AbstractUseNullPropagationCodeFixProvider< TSyntaxKind, TExpressionSyntax, TConditionalExpressionSyntax, TBinaryExpressionSyntax, TInvocationExpression, TMemberAccessExpression, TConditionalAccessExpression, TElementAccessExpression> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax where TBinaryExpressionSyntax : TExpressionSyntax where TInvocationExpression : TExpressionSyntax where TMemberAccessExpression : TExpressionSyntax where TConditionalAccessExpression : TExpressionSyntax where TElementAccessExpression : TExpressionSyntax { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseNullPropagationDiagnosticId); protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return SpecializedTasks.EmptyTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var generator = editor.Generator; var root = editor.OriginalRoot; foreach (var diagnostic in diagnostics) { var conditionalExpression = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); var conditionalPart = root.FindNode(diagnostic.AdditionalLocations[1].SourceSpan); var whenPart = root.FindNode(diagnostic.AdditionalLocations[2].SourceSpan); syntaxFacts.GetPartsOfConditionalExpression( conditionalExpression, out var condition, out var whenTrue, out var whenFalse); var whenPartIsNullable = diagnostic.Properties.ContainsKey(UseNullPropagationConstants.WhenPartIsNullable); editor.ReplaceNode(conditionalExpression, (c, g) => { syntaxFacts.GetPartsOfConditionalExpression( c, out var currentCondition, out var currentWhenTrue, out var currentWhenFalse); var currentWhenPartToCheck = whenPart == whenTrue ? currentWhenTrue : currentWhenFalse; var match = AbstractUseNullPropagationDiagnosticAnalyzer< TSyntaxKind, TExpressionSyntax, TConditionalExpressionSyntax, TBinaryExpressionSyntax, TInvocationExpression, TMemberAccessExpression, TConditionalAccessExpression, TElementAccessExpression>.GetWhenPartMatch(syntaxFacts, conditionalPart, currentWhenPartToCheck); if (match == null) { return c; } var newNode = CreateConditionalAccessExpression( syntaxFacts, g, whenPartIsNullable, currentWhenPartToCheck, match, c); newNode = newNode.WithTriviaFrom(c); return newNode; }); } return SpecializedTasks.EmptyTask; } private SyntaxNode CreateConditionalAccessExpression( ISyntaxFactsService syntaxFacts, SyntaxGenerator generator, bool whenPartIsNullable, SyntaxNode whenPart, SyntaxNode match, SyntaxNode currentConditional) { if (whenPartIsNullable) { if (match.Parent is TMemberAccessExpression memberAccess) { var nameNode = syntaxFacts.GetNameOfMemberAccessExpression(memberAccess); syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); var comparer = syntaxFacts.StringComparer; if (arity == 0 && comparer.Equals(name, nameof(Nullable<int>.Value))) { // They're calling ".Value" off of a nullable. Because we're moving to ?. // we want to remove the .Value as well. i.e. we should generate: // // goo?.Bar() not goo?.Value.Bar(); return CreateConditionalAccessExpression( syntaxFacts, generator, whenPart, match, memberAccess.Parent, currentConditional); } } } return CreateConditionalAccessExpression( syntaxFacts, generator, whenPart, match, match.Parent, currentConditional); } private SyntaxNode CreateConditionalAccessExpression( ISyntaxFactsService syntaxFacts, SyntaxGenerator generator, SyntaxNode whenPart, SyntaxNode match, SyntaxNode matchParent, SyntaxNode currentConditional) { var memberAccess = matchParent as TMemberAccessExpression; if (memberAccess != null) { return whenPart.ReplaceNode(memberAccess, generator.ConditionalAccessExpression( match, generator.MemberBindingExpression( syntaxFacts.GetNameOfMemberAccessExpression(memberAccess)))); } var elementAccess = matchParent as TElementAccessExpression; if (elementAccess != null) { return whenPart.ReplaceNode(elementAccess, generator.ConditionalAccessExpression( match, generator.ElementBindingExpression( syntaxFacts.GetArgumentListOfElementAccessExpression(elementAccess)))); } return currentConditional; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Use_null_propagation, createChangedDocument) { } } } }
{ "content_hash": "19b91dcd4c08138afc20c410ddb3fa85", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 161, "avg_line_length": 46.37888198757764, "alnum_prop": 0.631578947368421, "repo_name": "kelltrick/roslyn", "id": "fbc872466011797c385f42f70716785f2e4930c9", "size": "7469", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Features/Core/Portable/UseNullPropagation/AbstractUseNullPropagationCodeFixProvider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9590" }, { "name": "C#", "bytes": "95787857" }, { "name": "C++", "bytes": "5392" }, { "name": "F#", "bytes": "3632" }, { "name": "Groovy", "bytes": "11258" }, { "name": "PowerShell", "bytes": "122379" }, { "name": "Shell", "bytes": "10862" }, { "name": "Visual Basic", "bytes": "73279455" } ], "symlink_target": "" }
namespace sf1r { namespace Recommend { const Parser::iterator& Parser::begin() { return ++it_; } const Parser::iterator& Parser::end() const { static Parser::iterator it(NULL, -1); return it; } const Parser::iterator& Parser::iterator::operator++() { if (p_->next()) { uuid_++; return *this; } else { uuid_ = -1; return *this; //return p_->end(); } } const UserQuery& Parser::iterator::operator*() const { return p_->get(); } const UserQuery* Parser::iterator::operator->() const { return &(p_->get()); } bool Parser::iterator::operator== (const Parser::iterator& other) const { return uuid_ == other.uuid_; } bool Parser::iterator::operator!= (const Parser::iterator& other) const { return uuid_ != other.uuid_; } } }
{ "content_hash": "db56178b4346ee14f473a66724d456d8", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 71, "avg_line_length": 15.73076923076923, "alnum_prop": 0.5843520782396088, "repo_name": "izenecloud/sf1r-lite", "id": "095e951fed6c11320bd977b309a5fecc9ffa02d2", "size": "858", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/core/mining-manager/query-recommendation/parser/Parser.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1785" }, { "name": "C", "bytes": "246141" }, { "name": "C++", "bytes": "3916418" }, { "name": "Makefile", "bytes": "260" }, { "name": "Python", "bytes": "25450" }, { "name": "Ruby", "bytes": "5785" }, { "name": "Shell", "bytes": "6684" } ], "symlink_target": "" }
package auth import "time" type mockClock struct { now *time.Time } func (c mockClock) Now() time.Time { return *c.now }
{ "content_hash": "7734dba7ad87cc90672c0eadce95505b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 36, "avg_line_length": 11.454545454545455, "alnum_prop": 0.6825396825396826, "repo_name": "mtlynch/gofn-prosper", "id": "2b6737e6c76a74a1703faff97e52d1c8fa6e1399", "size": "126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "prosper/auth/mock_clock.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "258537" }, { "name": "Shell", "bytes": "217" } ], "symlink_target": "" }
 #include <aws/elastic-inference/model/AcceleratorType.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ElasticInference { namespace Model { AcceleratorType::AcceleratorType() : m_acceleratorTypeNameHasBeenSet(false), m_memoryInfoHasBeenSet(false), m_throughputInfoHasBeenSet(false) { } AcceleratorType::AcceleratorType(JsonView jsonValue) : m_acceleratorTypeNameHasBeenSet(false), m_memoryInfoHasBeenSet(false), m_throughputInfoHasBeenSet(false) { *this = jsonValue; } AcceleratorType& AcceleratorType::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("acceleratorTypeName")) { m_acceleratorTypeName = jsonValue.GetString("acceleratorTypeName"); m_acceleratorTypeNameHasBeenSet = true; } if(jsonValue.ValueExists("memoryInfo")) { m_memoryInfo = jsonValue.GetObject("memoryInfo"); m_memoryInfoHasBeenSet = true; } if(jsonValue.ValueExists("throughputInfo")) { Aws::Utils::Array<JsonView> throughputInfoJsonList = jsonValue.GetArray("throughputInfo"); for(unsigned throughputInfoIndex = 0; throughputInfoIndex < throughputInfoJsonList.GetLength(); ++throughputInfoIndex) { m_throughputInfo.push_back(throughputInfoJsonList[throughputInfoIndex].AsObject()); } m_throughputInfoHasBeenSet = true; } return *this; } JsonValue AcceleratorType::Jsonize() const { JsonValue payload; if(m_acceleratorTypeNameHasBeenSet) { payload.WithString("acceleratorTypeName", m_acceleratorTypeName); } if(m_memoryInfoHasBeenSet) { payload.WithObject("memoryInfo", m_memoryInfo.Jsonize()); } if(m_throughputInfoHasBeenSet) { Aws::Utils::Array<JsonValue> throughputInfoJsonList(m_throughputInfo.size()); for(unsigned throughputInfoIndex = 0; throughputInfoIndex < throughputInfoJsonList.GetLength(); ++throughputInfoIndex) { throughputInfoJsonList[throughputInfoIndex].AsObject(m_throughputInfo[throughputInfoIndex].Jsonize()); } payload.WithArray("throughputInfo", std::move(throughputInfoJsonList)); } return payload; } } // namespace Model } // namespace ElasticInference } // namespace Aws
{ "content_hash": "1a7c69b9e1b19fbfd5d584dc2ec8fd38", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 122, "avg_line_length": 23.925531914893618, "alnum_prop": 0.7492218763895064, "repo_name": "aws/aws-sdk-cpp", "id": "b711b15af921b382b741b12e12ff19603e01da1e", "size": "2368", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-elastic-inference/source/model/AcceleratorType.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
from weioLib.weioIO import * from weioUserApi import *
{ "content_hash": "22894c8817cc53e4616c2bf7ba7ff30a", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 28, "avg_line_length": 18.666666666666668, "alnum_prop": 0.7857142857142857, "repo_name": "nodesign/weioMinima", "id": "3e875adcbe59ffce06eeed54e3e496024f02f7da", "size": "2495", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "weioLib/weio.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "273353" } ], "symlink_target": "" }
<?php namespace Pico\LeagueBundle\Entity; use Doctrine\ORM\EntityRepository; /** * SportRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class SportRepository extends EntityRepository { }
{ "content_hash": "22c8e80162f73db80513d932419550b4", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 68, "avg_line_length": 17.266666666666666, "alnum_prop": 0.7606177606177607, "repo_name": "PicoPlan/PicoPlanApp", "id": "5bcf61c920e5df227d45c4ac2b82d39349f46753", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Pico/LeagueBundle/Entity/SportRepository.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "860" }, { "name": "CSS", "bytes": "678505" }, { "name": "ColdFusion", "bytes": "2253" }, { "name": "HTML", "bytes": "140011" }, { "name": "JavaScript", "bytes": "441362" }, { "name": "PHP", "bytes": "158624" }, { "name": "Ruby", "bytes": "3675" } ], "symlink_target": "" }