text
stringlengths
1
1.05M
package io.opensphere.kml.marshal; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.io.Writer; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.sax.SAXSource; import org.apache.log4j.Logger; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import de.micromata.opengis.kml.v_2_2_0.Kml; import io.opensphere.core.util.lang.StringUtilities; import io.opensphere.core.util.xml.WrappedXMLReader; import io.opensphere.kml.gx.Track; /** * Handles marshalling and unmarshling kml files. * */ public final class KmlMarshaller { /** * Used to log messages. */ private static final Logger LOGGER = Logger.getLogger(KmlMarshaller.class); /** * The instance of this class. */ private static KmlMarshaller ourInstance; /** * The jaxb context. */ private JAXBContext myContext; /** * Used to write out to kml format. */ private Marshaller myMarshaller; /** * Used to read in kml formatted data. */ private Unmarshaller myUnmarshaller; /** * Gets the instance of this class. * * @return The instance of this class. */ public static synchronized KmlMarshaller getInstance() { if (ourInstance == null) { ourInstance = new KmlMarshaller(); } return ourInstance; } /** * Private constructor. */ private KmlMarshaller() { try { myContext = JAXBContext.newInstance(Kml.class, Track.class); myMarshaller = myContext.createMarshaller(); myMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); myMarshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespaceMapper()); myUnmarshaller = myContext.createUnmarshaller(); } catch (JAXBException e) { LOGGER.error(e.getMessage(), e); } } /** * Marhsals the kml to the specified file. * * @param kml The kml to marshal. * @param filename The file to write to. * @return True upon success, false otherwise. * @throws FileNotFoundException If the file does not exist. */ public boolean marshal(Kml kml, final File filename) throws FileNotFoundException { boolean isSuccess = false; try (OutputStream out = new FileOutputStream(filename)) { myMarshaller.marshal(kml, out); isSuccess = true; } catch (JAXBException | IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; } /** * Marhsals the kml to the specified node. * * @param kml The kml to marshal. * @param node The node. * @return True upon success, false otherwise. */ public boolean marshal(Kml kml, Node node) { boolean isSuccess = false; try { myMarshaller.marshal(kml, node); isSuccess = true; } catch (JAXBException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; } /** * Marshalls the kml object to the writer. * * @param kml The kml to write. * @param writer Used to output the marhalled data. * @return True upon success false otherwise. */ public boolean marshal(Kml kml, final Writer writer) { boolean isSuccess = true; try { myMarshaller.marshal(kml, writer); } catch (JAXBException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; } /** * Unmarshals the file into a kml object. * * @param file The kml formatted file. * @return The kml object. * @throws FileNotFoundException if the files not found. */ public Kml unmarshal(File file) throws FileNotFoundException { Kml kml = null; try (FileInputStream fileStream = new FileInputStream(file)) { InputStreamReader reader = new InputStreamReader(fileStream, StringUtilities.DEFAULT_CHARSET); InputSource input = new InputSource(reader); kml = unmarshal(input); } catch (IOException e) { LOGGER.error(e, e); } return kml; } /** * Unmarshals the kml content string. * * @param kmlContent The kml formatted string to unmarshal. * @return The kml object. */ public Kml unmarshal(String kmlContent) { InputSource input = new InputSource(new StringReader(kmlContent)); return unmarshal(input); } /** * Unmarshals the input into a kml object. * * @param input The kml formatted data. * @return A kml object. */ private Kml unmarshal(InputSource input) { Kml jaxbRootElement = null; SAXSource saxSource; try { saxSource = new SAXSource(new WrappedXMLReader(false, handler -> new NamespaceFilterHandler(handler)), input); jaxbRootElement = (Kml)myUnmarshaller.unmarshal(saxSource); } catch (ParserConfigurationException | SAXException | JAXBException e) { LOGGER.error(e.getMessage(), e); } return jaxbRootElement; } }
<gh_stars>1-10 'use strict'; var jasmine = require('jasmine'); var mockery = require('mockery'); var request = require('supertest'); var express = require('express'); var finish_test = require('../supertest-jasmine'); describe('route config tests', function () { var app; //csrf mockery var mockCsrfProtectionContainer = { mockCsrfProtection: function (req, res, next) { next(); } }; var mockCsurf = function () { return mockCsrfProtectionContainer.mockCsrfProtection; }; beforeEach(function () { mockery.enable({ useCleanCache: true }); mockery.warnOnUnregistered(false); mockery.warnOnReplace(false); mockery.registerMock('csurf', mockCsurf); app = express(); }); afterEach(function () { mockery.disable(); }); afterAll(function () { mockery.deregisterAll(); }); describe('home controller routes', function () { var indexBody = 'called home controller index'; var logoutBody = 'called home controller logout'; var loginBody = 'called home controller login'; var logoutFormBody = 'called home controller logoutform'; var mockHomeController; var mockGithub beforeEach(function () { mockHomeController = {}; mockHomeController.ensureLoggedIn = function (req, res, next) { next(); }; mockHomeController.login = function (req, res, next) { res.status(200).send(loginBody); } mockHomeController.index = function (req, res, next) { res.status(200).send(indexBody); }; mockHomeController.logout = function (req, res, next) { res.status(200).send(logoutBody); }; mockHomeController.logoutform = function (req, res, next) { res.status(200).send(logoutFormBody); }; mockery.registerMock('../controllers/homecontroller', mockHomeController); }); it('/', function (done) { mockHomeController.index = function (req, res, next) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockHomeController.index).toHaveBeenCalled(); res.status(200).send(indexBody); }; spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); spyOn(mockHomeController, 'index').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/') .expect(200) .expect(indexBody) .end(finish_test(done)); }); it('/login', function (done) { mockHomeController.logout = function (req, res, next) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.login).toHaveBeenCalled(); res.status(200).send(loginBody); }; spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); spyOn(mockHomeController, 'login').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/login') .expect(200) .expect(loginBody) .end(finish_test(done)); }); it('/logout', function (done) { mockHomeController.logout = function (req, res, next) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.logout).toHaveBeenCalled(); res.status(200).send(logoutBody); }; spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); spyOn(mockHomeController, 'logout').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .post('/logout') .expect(200) .expect(logoutBody) .end(finish_test(done)); }); it('/logoutform', function (done) { mockHomeController.logoutForm = function (req, res, next) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.logoutForm).toHaveBeenCalled(); res.status(200).send(logoutFormBody); }; spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); spyOn(mockHomeController, 'logoutform').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/logoutform') .expect(200) .expect(logoutFormBody) .end(finish_test(done)); }); }); describe('github signin routes', function () { var doLoginBody = 'called doLogin'; var completeLoginBody = 'called completeLogin'; var mockGithub; beforeEach(function () { mockGithub = {}; mockGithub.doLogin = function (req, res, next) { res.status(200).send(doLoginBody); }; mockGithub.completeLogin = function (req, res, next) { res.status(200).send(completeLoginBody); }; mockery.registerMock('../controllers/githublogincontroller', mockGithub); spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); }); it('/login', function (done) { spyOn(mockGithub, 'doLogin').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .post('/login') .expect(200) .expect(doLoginBody) .expect(function (res) { expect(mockGithub.doLogin).toHaveBeenCalled(); expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/login/github', function (done) { spyOn(mockGithub, 'doLogin').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/login/github') .expect(200) .expect(doLoginBody) .expect(function (res) { expect(mockGithub.doLogin).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/oauth/github', function (done) { spyOn(mockGithub, 'doLogin').and.callFake(function (req, res, next) { next(); }); spyOn(mockGithub, 'completeLogin').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/oauth/github') .expect(200) .expect(completeLoginBody) .expect(function (res) { expect(mockGithub.doLogin).toHaveBeenCalled(); expect(mockGithub.completeLogin).toHaveBeenCalled(); }) .end(finish_test(done)); }); }); describe('threat model routes', function () { var reposBody = 'called repos'; var branchesBody = 'called banches'; var modelsBody = 'called models'; var modelBody = 'called model'; var deleteBody = 'called delete'; var createBody = 'create'; var updateBody = 'update'; var mockThreatModel = {}; var mockHomeController = {}; beforeEach(function () { mockHomeController.ensureLoggedIn = function (req, res, next) { next(); }; mockHomeController.login = function () { }; mockHomeController.index = function () { }; mockHomeController.logout = function () { }; mockHomeController.logoutform = function () { }; mockThreatModel.repos = function (req, res, next) { res.status(200).send(reposBody); }; mockThreatModel.branches = function (req, res, next) { res.status(200).send(branchesBody); }; mockThreatModel.models = function (req, res, next) { res.status(200).send(modelsBody); }; mockThreatModel.model = function (req, res, next) { res.status(200).send(modelBody); }; mockThreatModel.deleteModel = function (req, res, next) { res.status(200).send(deleteBody); }; mockThreatModel.create = function (req, res, next) { res.status(200).send(createBody); }; mockThreatModel.update = function (req, res, next) { res.status(200).send(updateBody); }; mockery.registerMock('../controllers/threatmodelcontroller', mockThreatModel); mockery.registerMock('../controllers/homecontroller', mockHomeController); spyOn(mockCsrfProtectionContainer, 'mockCsrfProtection').and.callThrough(); }); it('/threatmodel/repos', function (done) { spyOn(mockThreatModel, 'repos').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/threatmodel/repos') .expect(200) .expect(reposBody) .expect(function (res) { expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.repos).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/threatmodel/org/repo/branches', function (done) { spyOn(mockThreatModel, 'branches').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/threatmodel/org/repo/branches') .expect(200) .expect(branchesBody) .expect(function (res) { expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.branches).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/threatmodel/org/repo/branch/models', function (done) { spyOn(mockThreatModel, 'models').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/threatmodel/org/repo/branch/models') .expect(200) .expect(modelsBody) .expect(function (res) { expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.models).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/threatmodel/org/repo/branch/model/data', function (done) { spyOn(mockThreatModel, 'model').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .get('/threatmodel/org/repo/branch/model/data') .expect(200) .expect(modelBody) .expect(function (res) { expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.model).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('DELETE /threatmodel/org/repo/branch/model', function (done) { spyOn(mockThreatModel, 'deleteModel').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .delete('/threatmodel/org/repo/branch/model') .expect(200) .expect(deleteBody) .expect(function (res) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.deleteModel).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/threatmodel/org/repo/branch/model/create', function (done) { spyOn(mockThreatModel, 'create').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .put('/threatmodel/org/repo/branch/model/create') .expect(200) .expect(createBody) .expect(function (res) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.create).toHaveBeenCalled(); }) .end(finish_test(done)); }); it('/threatmodel/org/repo/branch/model/update', function (done) { spyOn(mockThreatModel, 'update').and.callThrough(); spyOn(mockHomeController, 'ensureLoggedIn').and.callThrough(); require('../../../td/config/routes.config')(app); request(app) .put('/threatmodel/org/repo/branch/model/update') .expect(200) .expect(updateBody) .expect(function (res) { expect(mockCsrfProtectionContainer.mockCsrfProtection).toHaveBeenCalled(); expect(mockHomeController.ensureLoggedIn).toHaveBeenCalled(); expect(mockThreatModel.update).toHaveBeenCalled(); }) .end(finish_test(done)); }); }) });
/* * Copyright (c) 2013, 2015 Oracle and/or its affiliates. All rights reserved. This * code is released under a tri EPL/GPL/LGPL license. You can use it, * redistribute it and/or modify it under the terms of the: * * Eclipse Public License version 1.0 * GNU General Public License version 2 * GNU Lesser General Public License version 2.1 */ package org.jruby.truffle.nodes.core; import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.NodeUtil; import com.oracle.truffle.api.source.SourceSection; import org.jruby.truffle.runtime.DebugOperations; import org.jruby.truffle.runtime.RubyCallStack; import org.jruby.truffle.runtime.RubyContext; import org.jruby.truffle.runtime.backtrace.Backtrace; import org.jruby.truffle.runtime.core.RubyArray; import org.jruby.truffle.runtime.core.RubyHash; import org.jruby.truffle.runtime.core.RubyNilClass; import org.jruby.truffle.runtime.core.RubyString; @CoreClass(name = "Truffle::Debug") public abstract class TruffleDebugNodes { @CoreMethod(names = "dump_call_stack", onSingleton = true) public abstract static class DumpCallStackNode extends CoreMethodNode { public DumpCallStackNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public DumpCallStackNode(DumpCallStackNode prev) { super(prev); } @Specialization public RubyNilClass dumpCallStack() { notDesignedForCompilation(); for (String line : Backtrace.DEBUG_FORMATTER.format(getContext(), null, RubyCallStack.getBacktrace(this))) { System.err.println(line); } return getContext().getCoreLibrary().getNilObject(); } } @CoreMethod(names = "flush_stdout", onSingleton = true) public abstract static class FlushStdoutNode extends CoreMethodNode { public FlushStdoutNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public FlushStdoutNode(FlushStdoutNode prev) { super(prev); } @Specialization public RubyNilClass flush() { getContext().getRuntime().getOut().flush(); return getContext().getCoreLibrary().getNilObject(); } } @CoreMethod(names = "full_tree", onSingleton = true) public abstract static class FullTreeNode extends CoreMethodNode { public FullTreeNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public FullTreeNode(FullTreeNode prev) { super(prev); } @Specialization public RubyString fullTree() { notDesignedForCompilation(); return getContext().makeString(NodeUtil.printTreeToString(Truffle.getRuntime().getCallerFrame().getCallNode().getRootNode())); } } @CoreMethod(names = "java_class_of", onSingleton = true, required = 1) public abstract static class JavaClassOfNode extends CoreMethodNode { public JavaClassOfNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public JavaClassOfNode(JavaClassOfNode prev) { super(prev); } @Specialization public RubyString javaClassOf(Object value) { notDesignedForCompilation(); return getContext().makeString(value.getClass().getName()); } } @CoreMethod(names = "dump_string", onSingleton = true, required = 1) public abstract static class DumpStringNode extends CoreMethodNode { public DumpStringNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public DumpStringNode(DumpStringNode prev) { super(prev); } @Specialization public RubyString dumpString(RubyString string) { notDesignedForCompilation(); final StringBuilder builder = new StringBuilder(); builder.append("\""); for (byte b : string.getBytes().unsafeBytes()) { builder.append(String.format("\\x%02x", b)); } builder.append("\""); return getContext().makeString(builder.toString()); } } @CoreMethod(names = "source_attribution_tree", onSingleton = true) public abstract static class SourceAttributionTreeNode extends CoreMethodNode { public SourceAttributionTreeNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public SourceAttributionTreeNode(SourceAttributionTreeNode prev) { super(prev); } @Specialization public RubyString sourceAttributionTree() { notDesignedForCompilation(); return getContext().makeString(NodeUtil.printSourceAttributionTree(Truffle.getRuntime().getCallerFrame().getCallNode().getRootNode())); } } @CoreMethod(names = "storage_class", onSingleton = true, required = 1) public abstract static class StorageClassNode extends CoreMethodNode { public StorageClassNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public StorageClassNode(StorageClassNode prev) { super(prev); } @Specialization public RubyString storageClass(RubyArray array) { notDesignedForCompilation(); if (array.getStore() == null) { return getContext().makeString("null"); } else { return getContext().makeString(array.getStore().getClass().getName()); } } @Specialization public RubyString storageClass(RubyHash hash) { notDesignedForCompilation(); if (hash.getStore() == null) { return getContext().makeString("null"); } else { return getContext().makeString(hash.getStore().getClass().getName()); } } } @CoreMethod(names = "panic", onSingleton = true) public abstract static class PanicNode extends CoreMethodNode { public PanicNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public PanicNode(PanicNode prev) { super(prev); } @Specialization public RubyNilClass doPanic() { DebugOperations.panic(getContext(), this, null); return getContext().getCoreLibrary().getNilObject(); } } @CoreMethod(names = "parse_tree", onSingleton = true) public abstract static class ParseTreeNode extends CoreMethodNode { public ParseTreeNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public ParseTreeNode(ParseTreeNode prev) { super(prev); } @Specialization public Object parseTree(VirtualFrame frame) { notDesignedForCompilation(); final org.jruby.ast.Node parseTree = RubyCallStack.getCallingMethod(frame).getSharedMethodInfo().getParseTree(); if (parseTree == null) { return getContext().getCoreLibrary().getNilObject(); } else { return getContext().makeString(parseTree.toString(true, 0)); } } } @CoreMethod(names = "tree", onSingleton = true) public abstract static class TreeNode extends CoreMethodNode { public TreeNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public TreeNode(TreeNode prev) { super(prev); } @Specialization public RubyString tree() { notDesignedForCompilation(); return getContext().makeString(NodeUtil.printCompactTreeToString(Truffle.getRuntime().getCallerFrame().getCallNode().getRootNode())); } } }
# # Enables local Python package installation. # # Authors: # Sorin Ionescu <sorin.ionescu@gmail.com> # Sebastian Wiesner <lunaryorn@googlemail.com> # # Load manually installed pyenv into the shell session. if [[ -s "$HOME/.pyenv/bin/pyenv" ]]; then path=("$HOME/.pyenv/bin" $path) eval "$(pyenv init - --no-rehash)" # Load package manager installed pyenv into the shell session. elif (( $+commands[pyenv] )); then eval "$(pyenv init - --no-rehash)" # Prepend PEP 370 per user site packages directory, which defaults to # ~/Library/Python on Mac OS X and ~/.local elsewhere, to PATH. The # path can be overridden using PYTHONUSERBASE. else if [[ -n "$PYTHONUSERBASE" ]]; then path=($PYTHONUSERBASE/bin $path) elif [[ "$OSTYPE" == darwin* ]]; then path=($HOME/Library/Python/*/bin(N) $path) else # This is subject to change. path=($HOME/.local/bin $path) fi fi # Return if requirements are not found. if (( ! $+commands[python] && ! $+commands[pyenv] )); then return 1 fi # Load virtualenvwrapper into the shell session. if (( $+commands[virtualenvwrapper.sh] )); then # Set the directory where virtual environments are stored. export WORKON_HOME="$HOME/.virtualenvs" # Disable the virtualenv prompt. VIRTUAL_ENV_DISABLE_PROMPT=1 source "$commands[virtualenvwrapper.sh]" fi # # Aliases # alias py='python'
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useState, forwardRef, Ref, useImperativeHandle, useRef, } from "react"; // import _debounce from 'lodash/debounce'; // import React, { useMemo, useCallback } from "react"; // import "./all.css"; import styles from "./styles.module.css"; // import { CoreStyledComponent, coreStyledCss } from '@remirror/styles/emotion'; // import { css } from "@emotion/css"; // import jsx from "refractor/lang/jsx"; // import typescript from "refractor/lang/typescript"; import { ExtensionPriority, // StateUpdateLifecycleParameter, getThemeVar, } from "remirror"; import { BlockquoteExtension, BoldExtension, BulletListExtension, CodeBlockExtension, CodeExtension, // DropCursorExtension, EmojiExtension, HardBreakExtension, HeadingExtension, HorizontalRuleExtension, // ImageExtension, ItalicExtension, LinkExtension, ListItemExtension, MarkdownExtension, OrderedListExtension, PlaceholderExtension, StrikeExtension, // TableExtension, TrailingNodeExtension, } from "remirror/extensions"; import { ComponentItem, EditorComponent, EmojiPopupComponent, Remirror, ThemeProvider, Toolbar, ToolbarItemUnion, useActive, useAttrs, useChainedCommands, useCommands, useCurrentSelection, useHelpers, useRemirror, useRemirrorContext, } from "@remirror/react"; // import { AllStyledComponent } from '@remirror/styles/emotion'; import type { EditorState, Transaction } from "@remirror/core-types"; import type { Handler } from "@remirror/core-types"; // import { ProsemirrorDevTools } from "@remirror/dev"; // import data from 'svgmoji/emoji.json'; import { FigcaptionExtension } from "./fig-extension"; import { MarkdownLinkExtension, useFloatingLinkState } from "./link-extension"; import { FloatingLinkToolbar } from "./link-toolbar"; // export default { title: 'Editors / Markdown' }; const Menubar = () => { const chain = useChainedCommands(); const active = useActive(); // const activeLink = active.link(); const { isEditing, linkPositioner, clickEdit, onRemove, submitHref, href, setHref, cancelHref, } = useFloatingLinkState(); const toolbarItems: ToolbarItemUnion[] = useMemo( () => [ { type: ComponentItem.ToolbarGroup, label: "Heading Formatting", items: [ { type: ComponentItem.ToolbarCommandButton, commandName: "toggleHeading", display: "icon", attrs: { level: 2 }, }, { type: ComponentItem.ToolbarMenu, items: [ { type: ComponentItem.MenuGroup, role: "radio", items: [ { type: ComponentItem.MenuCommandPane, commandName: "toggleHeading", attrs: { level: 3 }, }, { type: ComponentItem.MenuCommandPane, commandName: "toggleHeading", attrs: { level: 4 }, }, ], }, ], }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleBold", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleItalic", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleStrike", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleBlockquote", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleBulletList", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleOrderedList", display: "icon", }, { type: ComponentItem.ToolbarCommandButton, commandName: "toggleCodeBlock", display: "icon", }, { type: ComponentItem.ToolbarButton, label: "---", onClick() { chain // Begin a chain .insertHorizontalRule() .focus() .run(); // A chain must always be terminated with `.run()` }, }, { type: ComponentItem.ToolbarButton, icon: "linkM", onClick() { // console.log("linkM onClick:"); // clickEdit(); const linkUrl = window.prompt("link url:"); if (linkUrl) chain // Begin a chain .insertHtml(`<a href="${linkUrl}">${linkUrl}</a>`) .focus() .run(); // A chain must always be terminated with `.run()` }, }, { type: ComponentItem.ToolbarButton, icon: "imageLine", onClick() { // console.log("imageLine onClick:"); const imgUrl = window.prompt("image url:"); if (imgUrl) chain // Begin a chain .insertHtml(`<img src="${imgUrl}" />`) .focus() .run(); // A chain must always be terminated with `.run()` }, }, ], // separator: 'end', }, ], [chain] // [clickEdit, onRemove, activeLink] ); return <Toolbar items={toolbarItems} refocusEditor label="Top Toolbar" />; }; export interface EditorRef { setContent: (content: any) => void; // getContent: () => any; getJSON: () => any; getMarkdown: () => any; } export interface EditorProps { placeholder?: string; initialContent?: string; editorUpdate?: ({ content }: { content: string }) => void; // editorUpload?: (params: Params) => Promise<ResultData>; enableToolbar?: boolean; hint?: React.ReactNode; editable?: boolean; editorRef?: Ref<EditorRef>; } const ImperativeHandle = forwardRef((_: unknown, ref: Ref<EditorRef>) => { const { setContent } = useRemirrorContext({ autoUpdate: true, }); const { getJSON, getMarkdown } = useHelpers(); // Expose content handling to outside useImperativeHandle(ref, () => ({ setContent, // getContent, getJSON, getMarkdown, })); return <></>; }); /** * The editor which is used to create the annotation. Supports formatting. */ export const RichMarkdownEditor: React.FC<EditorProps> = ({ placeholder, initialContent, editorUpdate, children, enableToolbar = true, hint, editorRef, editable = false, }) => { /* const linkExtension = useMemo(() => { const extension = new LinkExtension({ autoLink: true }); extension.addHandler('onClick', (_, data) => { console.log(`You clicked link: ${JSON.stringify(data)}`); return true; }); return extension; }, []); */ /* const markdownExtension = useMemo(() => { const extension = new MarkdownExtension({ copyAsMarkdown: false }); return extension; }, []); */ const extensions = useCallback( () => [ new PlaceholderExtension({ placeholder }), // new LinkExtension(), // linkExtension, new MarkdownLinkExtension({ autoLink: true }), // { openLinkOnClick: true } /* new EmojiExtension({ // data, plainText: true, // moji: 'noto' }), */ // new LinkExtension({ autoLink: true }), new BoldExtension(), new StrikeExtension(), // new ImageExtension(), new FigcaptionExtension(), // new DropCursorExtension(), new ItalicExtension(), new HeadingExtension(), new HorizontalRuleExtension(), new BlockquoteExtension(), new BulletListExtension({ enableSpine: true }), new OrderedListExtension(), new ListItemExtension({ priority: ExtensionPriority.High, enableCollapsible: true, }), new CodeExtension(), new CodeBlockExtension({ // supportedLanguages: [jsx, typescript], }), new TrailingNodeExtension(), // new TableExtension(), // markdownExtension, new MarkdownExtension({ copyAsMarkdown: false }), /** * `HardBreakExtension` allows us to create a newline inside paragraphs. * e.g. in a list item */ new HardBreakExtension(), ], [placeholder] ); const { manager, state, setState, onChange: originalOnChange, } = useRemirror({ extensions, stringHandler: "markdown", content: initialContent, }); const changeHandler: Handler<(arg0: any) => void> = ({ tr, state, }: { tr: Transaction; state: EditorState; }) => { if (tr?.docChanged) { // console.log("before onChange:", parameter); editorUpdate?.({ content: manager.store.helpers.getMarkdown() }); // markdownExtension.getMarkdown() } // Update the state to the latest value. setState(state); // return originalOnChange(parameter) }; return ( // <AllStyledComponent> <ThemeProvider> <Remirror manager={manager} autoFocus state={state} onChange={changeHandler} classNames={[styles.remirror]} > {enableToolbar ? <Menubar /> : <></>} {hint} <EditorComponent /> <FloatingLinkToolbar /> {/* <EmojiPopupComponent /> */} {children} {/* <ProsemirrorDevTools /> */} <ImperativeHandle ref={editorRef} /> </Remirror> </ThemeProvider> // </AllStyledComponent> ); };
import torch from collections import namedtuple from PIL import Image from torchvision import models from utils import style_transform class SlicedVGG16(torch.nn.Module): def __init__(self, requires_grad=False): super(SlicedVGG16, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() for x in range(4): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(4, 9): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(9, 16): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(16, 23): self.slice4.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1_2 = h h = self.slice2(h) h_relu2_2 = h h = self.slice3(h) h_relu3_3 = h h = self.slice4(h) h_relu4_3 = h vgg_outputs = namedtuple("VggOutputs", ["relu1_2", "relu2_2", "relu3_3", "relu4_3"]) out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3) return out class FeatureExtractor(): def __init__(self, style_img_path: str, batch_size: int): self._style_img_path = style_img_path self._batch_size = batch_size self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self._fe = SlicedVGG16(requires_grad=False).to(self._device) self._l2_loss = torch.nn.MSELoss().to(self._device) self._gram_style = self._load_style() def get_content_loss(self, images_original, images_transformed, content_weight: float): # Extract features features_original = self._fe(images_original) features_transformed = self._fe(images_transformed) # Compute content loss as MSE between features content_loss = content_weight * self._l2_loss(features_transformed.relu2_2, features_original.relu2_2) return content_loss def get_style_loss(self, images_transformed, style_weight: float): style_loss = 0 features_transformed = self._fe(images_transformed) for ft_y, gm_s in zip(features_transformed, self._gram_style): gm_y = self._gram_matrix(ft_y) style_loss += self._l2_loss(gm_y, gm_s[: self._batch_size, :, :]) # images.size(0) style_loss *= style_weight return style_loss def _load_style(self): # Load style image style = style_transform()(Image.open(self._style_img_path)) style = style.repeat(self._batch_size, 1, 1, 1).to(self._device) # Extract style features features_style = self._fe(style) gram_style = [self._gram_matrix(y) for y in features_style] return gram_style def _gram_matrix(self, y): """ Returns the gram matrix of y (used to compute style loss) """ (b, c, h, w) = y.size() features = y.view(b, c, w * h) features_t = features.transpose(1, 2) gram = features.bmm(features_t) / (c * h * w) return gram
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { environment } from '../../../../../environments/environment.prod'; import { SubscriberService } from '../../../../shared/subscriber.service'; @Component({ selector: 'ngx-subscriber-certificate', templateUrl: './subscriber-certificate.component.html', styleUrls: ['./subscriber-certificate.component.css'] }) export class SubscriberCertificateComponent implements OnInit { useExistingCss: boolean; styleName: string; SubscriberNameEn:string; SubscriberDate:Date; FinishedDate:Date; EstimateNameEn:string; TrainerName:string; SubscriberId: any; English: boolean; LevelEng: any; SubscriberNameAr: any; EstimateNameAr: any; TrainerNameEn:any; LevelDesc: any; LevelNo:any; SubscriberLevelCode:any; constructor(private service:SubscriberService,private activeRoute:ActivatedRoute) { } ngOnInit() { this.useExistingCss = true; if (environment.production) { this.useExistingCss = true; const elements = document.getElementsByTagName('link'); for (let index = 0; index < elements.length; index++) { if (elements[index].href.startsWith(document.baseURI)) { this.styleName += elements[index].href + ','; } } this.styleName = this.styleName.slice(0, -1); } if(this.activeRoute.snapshot.url[0].path=="certificate") { this.English=true; } else { this.English=false; } this.getSubscriber(); } getSubscriber(){ this.SubscriberId=this.activeRoute.snapshot.paramMap.get('id'); this.service.getOneFinished(this.SubscriberId).subscribe((res:any)=>{ console.log(res) this.EstimateNameEn=res.EstimateNameEn; this.EstimateNameAr=res.EstimateNameAr; this.TrainerName=res.TrainerName; this.TrainerNameEn=res.TrainerNameEn; this.LevelEng=res.LevelEng; this.LevelNo=res.LevelNo; this.LevelDesc=res.LevelDesc; this.SubscriberDate=res.SubscriberLevelDate; this.FinishedDate=res.FinishedDate; this.SubscriberNameEn=res.SubscriberNameEn; this.SubscriberNameAr=res.SubscriberNameAr; this.SubscriberLevelCode=res.SubscriberLevelCode; }) } }
class Image { private $url; public function __construct($url) { $this->url = $url; } public function getDimensions() { list($width, $height) = getimagesize($this->url); return $width . " x " . $height; } public function display() { echo "<img src='" . $this->url . "' alt='Image' />"; } } // Example usage $imageUrl = "https://example.com/image.jpg"; $image = new Image($imageUrl); echo $image->getDimensions(); // Output: e.g., "800 x 600" $image->display(); // Output: HTML code to display the image
#!/bin/bash #shellcheck disable=SC2034 test_name="ha_data_services_migrate" test_external_services=(ha_backend) test_diagnostics_filters="~iam-v2 ~purge" test_upgrades=true CURRENT_OLDEST_VERSION=20190501153509 OLD_MANIFEST_DIR="${A2_ROOT_DIR}/components/automate-deployment/testdata/old_manifests/" DEEP_UPGRADE_PATH="${OLD_MANIFEST_DIR}/${CURRENT_OLDEST_VERSION}.json" do_build() { do_build_default set_test_manifest "build.json" log_info "Installing harts" # We need to make sure the harts are installed so that the bundle creation works #shellcheck disable=SC2154 if ls "${test_hartifacts_path}"/*.hart then hab pkg install "${test_hartifacts_path}"/*.hart fi log_info "Creating initial airgap bundle" #shellcheck disable=SC2154 chef-automate airgap bundle create \ --manifest "${DEEP_UPGRADE_PATH}" \ bundle.aib log_info "Creating update airgap bundle" #shellcheck disable=SC2154 chef-automate airgap bundle create \ --manifest "$test_manifest_dir/build.json" \ --hartifacts "${test_hartifacts_path}" \ --override-origin "$HAB_ORIGIN" \ update.aib # Installation of the artifact should create /hab rm -rf /hab } do_deploy() { #shellcheck disable=SC2154 chef-automate deploy config.toml \ --airgap-bundle bundle.aib \ --admin-password chefautomate \ --accept-terms-and-mlsa } do_prepare_upgrade() { do_backup_default cp -r /var/opt/chef-automate/backups/automate-elasticsearch-data \ /services/ha_backend_backups/automate-elasticsearch-data chown -R hab:hab /services/ha_backend_backups/automate-elasticsearch-data do_prepare_restore_default } do_upgrade() { #shellcheck disable=SC2154 chef-automate backup restore --debug \ --airgap-bundle update.aib \ --patch-config /services/ha_backend.toml \ --no-check-version \ "$test_backup_id" }
<gh_stars>1-10 import { dispatcher } from 'react-fiber/dispatcher'; import { PASSIVE, HOOK } from 'react-fiber/effectTag'; export function useState(initValue) { return dispatcher.useReducer(null, initValue); } export function useReducer(reducer, initValue, initAction) { return dispatcher.useReducer(reducer, initValue, initAction); } export function useEffect(create, deps) { return dispatcher.useEffect(create, deps, PASSIVE, 'passive', 'unpassive'); } export function useLayoutEffect(create, deps) { return dispatcher.useEffect(create, deps, HOOK, 'layout', 'unlayout'); } export function useCallback(create, deps) { return dispatcher.useCallbackOrMemo(create, deps); } export function useMemo(create, deps) { return dispatcher.useCallbackOrMemo(create, deps, true); } export function useRef(initValue) { return dispatcher.useRef(initValue); } export function useContext(initValue) {//这个不对 return dispatcher.useContext(initValue); } export function useImperativeHandle(ref, create, deps) { return dispatcher.useImperativeHandle(ref, create, deps); }
def revenue(quantity, price): return quantity * price # Example usage: quantity = 10 price = 5.00 revenue = revenue(quantity, price) print(revenue) # 50.00
def number_of_ways(score): dp = [0 for i in range(score + 1)] dp[0] = 1 for i in range(3, score + 1): dp[i] += dp[i-3] for i in range(5, score + 1): dp[i] += dp[i-5] for i in range(10, score + 1): dp[i] += dp[i-10] return dp[score] # Driver code score = 20 print("Number of ways to reach %d is %d" % (score, number_of_ways(score)))
#!/usr/local/bin/bash # Write gateway IP for reference echo $route_vpn_gateway > /pia-info/route_info # Back up resolv.conf and create new on with PIA DNS cat /etc/resolv.conf > /pia-info/resolv_conf_backup echo "# Generated by /connect_to_openvpn_with_token.sh nameserver 10.0.0.241" > /etc/resolv.conf
<filename>ruoyi-cms/src/main/java/com/ruoyi/content/controller/ContentController.java package com.ruoyi.content.controller; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.annotation.SetFilePath; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.content.bo.ContentAddBo; import com.ruoyi.content.bo.ContentEditBo; import com.ruoyi.content.bo.ContentQueryBo; import com.ruoyi.content.service.IContentService; import com.ruoyi.content.vo.ContentVo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; /** * 内容Controller * * @author ruoyi * @date 2021-05-12 */ @Api(value = "内容控制器", tags = {"内容管理"}) @RequiredArgsConstructor(onConstructor_ = @Autowired) @RestController @RequestMapping("/content/content") public class ContentController extends BaseController { private final IContentService iContentService; /** * 查询内容列表 */ @ApiOperation("查询内容列表") @PreAuthorize("@ss.hasPermi('content:content:list')") @GetMapping("/list") public TableDataInfo<ContentVo> list(ContentQueryBo bo) { return iContentService.queryPageList(bo); } /** * 导出内容列表 */ @ApiOperation("导出内容列表") @PreAuthorize("@ss.hasPermi('content:content:export')") @Log(title = "内容", businessType = BusinessType.EXPORT) @GetMapping("/export") public AjaxResult<ContentVo> export(ContentQueryBo bo) { List<ContentVo> list = iContentService.queryList(bo); ExcelUtil<ContentVo> util = new ExcelUtil<ContentVo>(ContentVo.class); return util.exportExcel(list, "内容"); } /** * 获取内容详细信息 */ @ApiOperation("获取内容详细信息") @PreAuthorize("@ss.hasPermi('content:content:query')") @SetFilePath(name = {"banner","icon"}, pathValue = {"bannerPath","iconPath"}) @GetMapping("/{contentId}") public AjaxResult<ContentVo> getInfo(@PathVariable("contentId" ) Long contentId) { return AjaxResult.success(iContentService.queryById(contentId)); } /** * 新增内容 */ @ApiOperation("新增内容") @PreAuthorize("@ss.hasPermi('content:content:add')") @Log(title = "内容", businessType = BusinessType.INSERT) @PostMapping() public AjaxResult<Void> add(@RequestBody ContentAddBo bo) { return toAjax(iContentService.insertByAddBo(bo) ? 1 : 0); } /** * 修改内容 */ @ApiOperation("修改内容") @PreAuthorize("@ss.hasPermi('content:content:edit')") @Log(title = "内容", businessType = BusinessType.UPDATE) @PutMapping() public AjaxResult<Void> edit(@RequestBody ContentEditBo bo) { return toAjax(iContentService.updateByEditBo(bo) ? 1 : 0); } /** * 修改状态 */ @ApiOperation("修改内容") @PreAuthorize("@ss.hasPermi('content:content:edit')") @Log(title = "内容", businessType = BusinessType.UPDATE) @PutMapping("/editStatus") public AjaxResult<Void> editStatus(@RequestBody ContentEditBo bo) { return toAjax(iContentService.updateStatusByEditBo(bo) ? 1 : 0); } /** * 删除内容 */ @ApiOperation("删除内容") @PreAuthorize("@ss.hasPermi('content:content:remove')") @Log(title = "内容" , businessType = BusinessType.DELETE) @DeleteMapping("/{contentIds}") public AjaxResult<Void> remove(@PathVariable Long[] contentIds) { return toAjax(iContentService.deleteWithValidByIds(Arrays.asList(contentIds), true) ? 1 : 0); } }
package io.opensphere.core.data; import io.opensphere.core.data.util.DataModelCategory; /** * Interface for listeners interested in changes to data registry contents. * * @param <T> The type of the property values of interest to the listener. */ public interface DataRegistryListener<T> { /** * Method called when the registry is completely cleared. * * @param source the source of the operation * @see #valuesRemoved(DataModelCategory, long[], Iterable, Object) */ void allValuesRemoved(Object source); /** * Get if this listener needs the array of ids to be supplied with each * notification. If this returns <code>false</code>, the caller has the * option of passing an empty array as the {@code ids} parameter to the * notification calls. * * @return A boolean. */ boolean isIdArrayNeeded(); /** * Get if this listener would like the * {@link #valuesRemoved(DataModelCategory, long[], Iterable, Object)} * method called when objects are removed. Returning true from this method * will cause removing values to be slower. * * @return boolean */ boolean isWantingRemovedObjects(); /** * Method called after values are added to the registry. * * @param dataModelCategory The data model category for the added models. * @param ids The data registry ids for the added models. * @param newValues The new values, in the same order as the ids. * @param source the source of the operation */ void valuesAdded(DataModelCategory dataModelCategory, long[] ids, Iterable<? extends T> newValues, Object source); /** * Method called after values are removed from the registry. This method is * only called if there are removed values cached in memory. * <p> * This is <b>not</b> called if all values are removed! Be sure to implement * {@link #allValuesRemoved(Object)} as well. * * @param dataModelCategory The data model category for the removed models. * @param ids The data registry ids for the removed models. * @param removedValues The removed values. This will <b>only</b> provide * the values that are currently cached in memory. * @param source the source of the operation * @see #valuesRemoved(DataModelCategory, long[], Object) * @see #allValuesRemoved(Object) */ void valuesRemoved(DataModelCategory dataModelCategory, long[] ids, Iterable<? extends T> removedValues, Object source); /** * Method called after values are removed from the registry. * <p> * This is <b>not</b> called if all values are removed! Be sure to implement * {@link #allValuesRemoved(Object)} as well. * * @param dataModelCategory The data model category for the removed models. * @param ids The data registry ids for the removed models. * @param source the source of the operation * * @see #allValuesRemoved(Object) */ void valuesRemoved(DataModelCategory dataModelCategory, long[] ids, Object source); /** * Method called after values are updated in the registry. * * @param dataModelCategory The data model category for the updated models. * @param ids The data registry ids for the updated models. * @param newValues The new values, in the same order as the ids. * @param source the source of the operation */ void valuesUpdated(DataModelCategory dataModelCategory, long[] ids, Iterable<? extends T> newValues, Object source); }
#!/bin/sh SELF=$(basename $0) ID="$1" XFORM_PATH="$2" DB="${COUCH_URL-http://127.0.0.1:5984/medic}" _usage () { echo "" echo "Add a form to the system" echo "" echo "Usage: $SELF <form id> <path to xform>" echo "" echo "Examples: " echo "" echo "COUCH_URL=http://localhost:8000/medic $SELF registration /home/henry/forms/RegisterPregnancy.xml" exit } if [ -z "$ID" ]; then echo "Missing ID parameter." _usage exit 1 fi if [ ! -f "$XFORM_PATH" ]; then echo "Can't find XFORM_PATH" _usage exit 1 fi # create new doc rev=`curl -H "Content-Type: application/json" -X PUT -d '{"type":"form"}' "$DB/form:${ID}"` # exit if we don't see a rev property echo "$rev" | grep '"rev"' > /dev/null if [ $? != 0 ]; then echo "Failed to create doc: $rev" exit 1 fi rev=`echo "$rev" | sed 's/.*rev":"//' | sed 's/".*//g' | tr -d '\n' | tr -d '\r'` curl -f -X PUT -H "Content-Type: text/xml" \ --data-binary "@${XFORM_PATH}" \ "${DB}/form:${ID}/xml?rev=${rev}"
#!/bin/sh tar -xf rocksdb-6.22.1.tar.gz cd rocksdb-6.22.1/ mkdir build cd build export CFLAGS="-O3 -march=native" export CXXFLAGS="-O3 -march=native" cmake -DCMAKE_BUILD_TYPE=Release -DWITH_SNAPPY=ON .. make -j $NUM_CPU_CORES make db_bench echo $? > ~/install-exit-status if [[ ! -x db_bench ]] then # Unfortunately older GCC will emit error from these no-error echo "TRYING AGAIN WITH NO-ERROR BITS" rm -rf ~/rocksdb-6.22.1/build/* export CFLAGS="-O3 -march=native -Wno-error=deprecated-copy -Wno-error=pessimizing-move" export CXXFLAGS="-O3 -march=native -Wno-error=deprecated-copy -Wno-error=pessimizing-move" cmake -DCMAKE_BUILD_TYPE=Release -DWITH_SNAPPY=ON .. make -j $NUM_CPU_CORES make db_bench echo $? > ~/install-exit-status fi cd ~ echo "#!/bin/bash rm -rf /tmp/rocksdbtest-1000/dbbench/ cd rocksdb-6.22.1/build/ ./db_bench \$@ --threads \$NUM_CPU_CORES --duration 60 > \$LOG_FILE 2>&1 echo \$? > ~/test-exit-status " > rocksdb chmod +x rocksdb
<gh_stars>10-100 package meghal.developer.nightsight.project.ui.application; import android.app.Application; /** * Created by meghal on 2/7/16. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); } }
<reponame>ReneCapella/Pantry<gh_stars>1-10 require "application_system_test_case" class StoresTest < ApplicationSystemTestCase setup do @store = stores(:one) end test "visiting the index" do visit stores_url assert_selector "h1", text: "Stores" end test "should create store" do visit stores_url click_on "New store" fill_in "Name", with: @store.name click_on "Create Store" assert_text "Store was successfully created" click_on "Back" end test "should update Store" do visit store_url(@store) click_on "Edit this store", match: :first fill_in "Name", with: @store.name click_on "Update Store" assert_text "Store was successfully updated" click_on "Back" end test "should destroy Store" do visit store_url(@store) click_on "Destroy this store", match: :first assert_text "Store was successfully destroyed" end end
<reponame>martinholden-skillsoft/connector-qualification /*! connector-qualification.bundle.js - v1.1.2 - 2022-03-09T11:31:14+0000 */ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } var QUALIFICATION = QUALIFICATION || {}; QUALIFICATION.VERSION = '1.1.2'; QUALIFICATION.DATE = new Date('2022-03-09T11:31:14+0000'); // Source: node_modules/@ungap/global-this/index.js (function (Object) { (typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis)) !== 'object' && (this ? get() : (Object.defineProperty(Object.prototype, '_T_', { configurable: true, get: get }), _T_)); function get() { var global = this || self; global.globalThis = global; delete Object.prototype._T_; } })(Object); // Source: src/polyfill/qualtrics.js // Polyfill Qualtrics to allow testing if (typeof globalThis.Qualtrics == "undefined" || typeof globalThis.Qualtrics.SurveyEngine == "undefined") { (function () { globalThis.Qualtrics = {}; globalThis.Qualtrics.SurveyEngine = {}; globalThis.Qualtrics.SurveyEngine.getEmbeddedData = function (key) { var keyEQ = key + "="; var ca = document.cookie.split(";"); for (var i = 0, len = ca.length; i < len; i++) { var c = ca[i]; while (c.charAt(0) === " ") { c = c.substring(1, c.length); } if (c.indexOf(keyEQ) === 0) return JSON.parse(c.substring(keyEQ.length, c.length)); } return null; }; globalThis.Qualtrics.SurveyEngine.setEmbeddedData = function (key, value) { document.cookie = key + "=" + JSON.stringify(value) + "; path=/"; }; })(); } // Source: src/cornerstone.js QUALIFICATION.CORNERSTONE = function (window, document, Qualtrics, undefined) { /** * @typedef {Object} QUALIFICATION.validationrule.dependencies * @property {String[]} and An array of property names of an object to check (AND comparison) * @property {String[]} or An array of property names of an object to check (OR comparison) */ /** * The function called to validate the result, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.validationrule.run * @function * @param {String} answer The Qualtrics selectedChoice value, the text string * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.validationrule * @property {String} name The name of the validation rule * @property {String[]} validresponses An array of strings that answer is compared to determine if valid * @property {QUALIFICATION.validationrule.dependencies} dependencies The other values that must be true * @property {QUALIFICATION.validationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.validationrules * @type {Object.<string, QUALIFICATION.validationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics * @property {QUALIFICATION.validationrule[]} rules An array of validation rules */ /** * The function called to qualify the captured data, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.qualificationrule.run * @function * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.qualificationrule * @property {String} name The name of the validation rule * @property {QUALIFICATION.qualificationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.qualificationrules * @type {Object.<string, QUALIFICATION.qualificationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics or ALL to process on all * @property {QUALIFICATION.qualificationrule[]} rules An array of validation rules */ var validationRules = { QID4: [{ name: "edge", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID8: [{ name: "embeddedsaml", validresponses: ["Cornerstone Embedded SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersaml", validresponses: ["Other SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID35: [{ name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = answer.toLowerCase() !== "none of the above" && answer !== ""; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }] }; var qualificationRules = { ALL: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.edge && processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "edge_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.edge ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "embeddedsaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.embeddedsaml ? "PASSED" : processed.othersaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.othersaml && processed.othersamlid ? "PASSED" : processed.embeddedsaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }] }; /** * Get the validation rules * * @returns {QUALIFICATION.validationrules} rules The validation rules object * */ function getValidationRules() { return validationRules; } /** * Get the qualification rules * * @returns {QUALIFICATION.qualificationrules} rules The qualification rules object * */ function getQualificationRules() { return qualificationRules; } return { getValidationRules: getValidationRules, getQualificationRules: getQualificationRules }; }(window, document, Qualtrics, undefined); // Source: src/degreed.js QUALIFICATION.DEGREED = function (window, document, Qualtrics, undefined) { /** * @typedef {Object} QUALIFICATION.validationrule.dependencies * @property {String[]} and An array of property names of an object to check (AND comparison) * @property {String[]} or An array of property names of an object to check (OR comparison) */ /** * The function called to validate the result, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.validationrule.run * @function * @param {String} answer The Qualtrics selectedChoice value, the text string * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.validationrule * @property {String} name The name of the validation rule * @property {String[]} validresponses An array of strings that answer is compared to determine if valid * @property {QUALIFICATION.validationrule.dependencies} dependencies The other values that must be true * @property {QUALIFICATION.validationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.validationrules * @type {Object.<string, QUALIFICATION.validationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics * @property {QUALIFICATION.validationrule[]} rules An array of validation rules */ /** * The function called to qualify the captured data, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.qualificationrule.run * @function * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.qualificationrule * @property {String} name The name of the validation rule * @property {QUALIFICATION.qualificationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.qualificationrules * @type {Object.<string, QUALIFICATION.qualificationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics or ALL to process on all * @property {QUALIFICATION.qualificationrule[]} rules An array of validation rules */ var validationRules = { QID8: [{ name: "embeddedsaml", validresponses: ["Degreed SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersaml", validresponses: ["Other SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID35: [{ name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = answer.toLowerCase() !== "none of the above" && answer !== ""; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }] }; var qualificationRules = { ALL: [], QID8: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "embeddedsaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.embeddedsaml ? "PASSED" : processed.othersaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.othersaml && processed.othersamlid ? "PASSED" : processed.embeddedsaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }], QID35: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "embeddedsaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.embeddedsaml ? "PASSED" : processed.othersaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.othersaml && processed.othersamlid ? "PASSED" : processed.embeddedsaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }] }; /** * Get the validation rules * * @returns {QUALIFICATION.validationrules} rules The validation rules object * */ function getValidationRules() { return validationRules; } /** * Get the qualification rules * * @returns {QUALIFICATION.qualificationrules} rules The qualification rules object * */ function getQualificationRules() { return qualificationRules; } return { getValidationRules: getValidationRules, getQualificationRules: getQualificationRules }; }(window, document, Qualtrics, undefined); // Source: src/sabacloud.js QUALIFICATION.SABACLOUD = function (window, document, Qualtrics, undefined) { /** * @typedef {Object} QUALIFICATION.validationrule.dependencies * @property {String[]} and An array of property names of an object to check (AND comparison) * @property {String[]} or An array of property names of an object to check (OR comparison) */ /** * The function called to validate the result, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.validationrule.run * @function * @param {String} answer The Qualtrics selectedChoice value, the text string * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.validationrule * @property {String} name The name of the validation rule * @property {String[]} validresponses An array of strings that answer is compared to determine if valid * @property {QUALIFICATION.validationrule.dependencies} dependencies The other values that must be true * @property {QUALIFICATION.validationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.validationrules * @type {Object.<string, QUALIFICATION.validationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics * @property {QUALIFICATION.validationrule[]} rules An array of validation rules */ /** * The function called to qualify the captured data, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.qualificationrule.run * @function * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.qualificationrule * @property {String} name The name of the validation rule * @property {QUALIFICATION.qualificationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.qualificationrules * @type {Object.<string, QUALIFICATION.qualificationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics or ALL to process on all * @property {QUALIFICATION.qualificationrule[]} rules An array of validation rules */ var validationRules = { QID4: [{ name: "sass", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID35: [{ name: "othersamlid", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID42: [{ name: "itemconnector", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID43: [{ name: "xapi", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }] }; var qualificationRules = { ALL: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.sass && processed.saml && processed.itemconnector && processed.xapi ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "sass_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.sass ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.othersamlid ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "itemconnector_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.itemconnector ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "xapi_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.xapi ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }] }; /** * Get the validation rules * * @returns {QUALIFICATION.validationrules} rules The validation rules object * */ function getValidationRules() { return validationRules; } /** * Get the qualification rules * * @returns {QUALIFICATION.qualificationrules} rules The qualification rules object * */ function getQualificationRules() { return qualificationRules; } return { getValidationRules: getValidationRules, getQualificationRules: getQualificationRules }; }(window, document, Qualtrics, undefined); // Source: src/successfactors.js QUALIFICATION.SUCCESSFACTORS = function (window, document, Qualtrics, undefined) { /** * @typedef {Object} QUALIFICATION.validationrule.dependencies * @property {String[]} and An array of property names of an object to check (AND comparison) * @property {String[]} or An array of property names of an object to check (OR comparison) */ /** * The function called to validate the result, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.validationrule.run * @function * @param {String} answer The Qualtrics selectedChoice value, the text string * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.validationrule * @property {String} name The name of the validation rule * @property {String[]} validresponses An array of strings that answer is compared to determine if valid * @property {QUALIFICATION.validationrule.dependencies} dependencies The other values that must be true * @property {QUALIFICATION.validationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.validationrules * @type {Object.<string, QUALIFICATION.validationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics * @property {QUALIFICATION.validationrule[]} rules An array of validation rules */ /** * The function called to qualify the captured data, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.qualificationrule.run * @function * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.qualificationrule * @property {String} name The name of the validation rule * @property {QUALIFICATION.qualificationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.qualificationrules * @type {Object.<string, QUALIFICATION.qualificationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics or ALL to process on all * @property {QUALIFICATION.qualificationrule[]} rules An array of validation rules */ var validationRules = { QID4: [{ name: "sass", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID8: [{ name: "embeddedsaml", validresponses: ["SuccessFactors SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "iassaml", validresponses: ["SAP Cloud Identity Services - Identity Authentication (IAS)"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersaml", validresponses: ["Other SAML Identity Provider"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.iassaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID35: [{ name: "othersamlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = answer.toLowerCase() !== "no" && answer !== ""; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.embeddedsaml || processed.iassaml || processed.othersaml && processed.othersamlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID42: [{ name: "itemconnector", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID43: [{ name: "odataapi", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "learninghistoryconnector", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID49: [{ name: "learninghistoryconnector", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "odataapi", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }] }; var qualificationRules = { ALL: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.sass && processed.saml && processed.itemconnector && (processed.odataapi || processed.learninghistoryconnector) ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "sass_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.sass ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "embeddedsaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.embeddedsaml ? "PASSED" : processed.othersaml ? "N/A" : processed.iassaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "iassaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.iassaml ? "PASSED" : processed.othersaml ? "N/A" : processed.enbeddedsaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.othersaml && processed.othersamlid ? "PASSED" : processed.embeddedsaml ? "N/A" : processed.iassaml ? "N/A" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "itemconnector_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.itemconnector ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "odataapi_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.odataapi ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "learninghistoryconnector_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.learninghistoryconnector ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }], QID35: [{ name: "iassaml_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "embeddedsaml_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }], QID40: [{ name: "iassaml_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "othersaml_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }], QID43: [{ name: "learninghistoryconnector_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }], QID49: [{ name: "odataapi_qualification", run: function run() { var status = "N/A"; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }] }; /** * Get the validation rules * * @returns {QUALIFICATION.validationrules} rules The validation rules object * */ function getValidationRules() { return validationRules; } /** * Get the qualification rules * * @returns {QUALIFICATION.qualificationrules} rules The qualification rules object * */ function getQualificationRules() { return qualificationRules; } return { getValidationRules: getValidationRules, getQualificationRules: getQualificationRules }; }(window, document, Qualtrics, undefined); // Source: src/workday.js QUALIFICATION.WORKDAY = function (window, document, Qualtrics, undefined) { /** * @typedef {Object} QUALIFICATION.validationrule.dependencies * @property {String[]} and An array of property names of an object to check (AND comparison) * @property {String[]} or An array of property names of an object to check (OR comparison) */ /** * The function called to validate the result, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.validationrule.run * @function * @param {String} answer The Qualtrics selectedChoice value, the text string * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.validationrule * @property {String} name The name of the validation rule * @property {String[]} validresponses An array of strings that answer is compared to determine if valid * @property {QUALIFICATION.validationrule.dependencies} dependencies The other values that must be true * @property {QUALIFICATION.validationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.validationrules * @type {Object.<string, QUALIFICATION.validationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics * @property {QUALIFICATION.validationrule[]} rules An array of validation rules */ /** * The function called to qualify the captured data, this should set Qualtrics embedded data * and return true/false * @name QUALIFICATION.qualificationrule.run * @function * @returns {boolean} */ /** * @typedef {Object} QUALIFICATION.qualificationrule * @property {String} name The name of the validation rule * @property {QUALIFICATION.qualificationrule.run} run The function called to validate the result, this * should set Qualtrics embedded data and return * true/false */ /** * @typedef {Object} QUALIFICATION.qualificationrules * @type {Object.<string, QUALIFICATION.qualificationrule[]>} * @property {String} questionid The questionid (QID) for Qualtrics or ALL to process on all * @property {QUALIFICATION.qualificationrule[]} rules An array of validation rules */ var validationRules = { QID4: [{ name: "ccl", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "email", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }, { name: "samlidp", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }, { name: "samlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }], QID44: [{ name: "email", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "samlidp", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }, { name: "samlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData('processed_state') || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData('processed_state', processed); return status; } }], QID8: [{ name: "samlidp", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "samlid", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.samlidp && processed.samlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }], QID43: [{ name: "samlid", validresponses: ["Yes"], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; var answerstatus = false; if (this.validresponses.length != 0) { jQuery.each(this.validresponses, function (index, value) { answerstatus = value.toLowerCase() === answer.toLowerCase(); return !status; }); } else { answerstatus = true; } var andstatus = true; jQuery.each(this.dependencies.and, function (index, value) { andstatus = andstatus && processed[value]; }); var orstatus = true; jQuery.each(this.dependencies.or, function (index, value) { orstatus = orstatus || processed[value]; }); status = answerstatus && andstatus && orstatus; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }, { name: "saml", validresponses: [], dependencies: { and: [], or: [] }, run: function run(answer) { var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var status = false; status = processed.samlidp && processed.samlid; processed[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData("processed_state", processed); return status; } }] }; var qualificationRules = { ALL: [{ name: "qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.ccl && processed.email && processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "ccl_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.ccl ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "email_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.email ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "saml_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.saml ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "samlidp_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.samlidp ? "PASSED" : "FAILED"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }, { name: "samlid_qualification", run: function run() { var status = "N/A"; var processed = Qualtrics.SurveyEngine.getEmbeddedData("processed_state") || {}; var qualified = Qualtrics.SurveyEngine.getEmbeddedData("qualified_state") || {}; status = processed.samlidp ? processed.samlid ? "PASSED" : "FAILED" : "N/A"; qualified[this.name] = status; Qualtrics.SurveyEngine.setEmbeddedData(this.name, status); Qualtrics.SurveyEngine.setEmbeddedData("qualified_state", qualified); return status; } }] }; /** * Get the validation rules * * @returns {QUALIFICATION.validationrules} rules The validation rules object * */ function getValidationRules() { return validationRules; } /** * Get the qualification rules * * @returns {QUALIFICATION.qualificationrules} rules The qualification rules object * */ function getQualificationRules() { return qualificationRules; } return { getValidationRules: getValidationRules, getQualificationRules: getQualificationRules }; }(window, document, Qualtrics, undefined); //# sourceMappingURL=connector-qualification.bundle.js.map
#!/bin/sh build () { echo "Building project" cmake -H. -Bbuild -DCMAKE_BUILD_TYPE=Debug \ -DGEN_LANGUAGE_BINDINGS=ON \ -DGEN_CPP_BINDINGS=ON \ -DGEN_PYTHON_BINDINGS=OFF \ -DCMAKE_EXPORT_COMPILE_COMMANDS=YES \ -DCMAKE_VERBOSE_MAKEFILE=YES cmake --build build ln -sf build/compile_commands.json } install() { echo "Not implemented" } clean() { echo "Cleaning project" rm -rf build } pvs () { echo "Checking project with PVS" pvs-studio-analyzer analyze -a 36 \ -l ~/store/PVS-Studio.lic \ -e /opt/ngfw/include \ -o project.log plog-converter -a GA:1,2,3 -t tasklist -m cwe -o ga_results.tasks project.log plog-converter -a MISRA:1,2,3 -t tasklist -m misra -o misra_results.tasks project.log } ACTION="build" for i in "$@" do echo ">>$i" case $i in build) ACTION="build" ;; install) ACTION="install" ;; pvs) ACTION="pvs" ;; clean) ACTION="clean" ;; *) ;; esac done echo "Action ${ACTION}" if [ $ACTION = "build" ]; then build elif [ $ACTION = "install" ]; then install elif [ $ACTION = "clean" ]; then clean elif [ $ACTION = "pvs" ]; then pvs else echo "Unknown action!" fi
#!/bin/bash # Script that checks the code for errors. GOBIN=${GOBIN:="$GOPATH/bin"} function print_real_go_files { grep --files-without-match 'DO NOT EDIT!' $(find . -iname '*.go') --exclude=./vendor/* } function generate_markdown { echo "Generating Github markdown" oldpwd=$(pwd) for i in $(find . -iname 'doc.go' -not -path "*vendor/*"); do realdir=$(cd $(dirname ${i}) && pwd -P) package=${realdir##${GOPATH}/src/} echo "$package" cd ${dir} ${GOBIN}/godoc2ghmd -ex -file DOC.md ${package} ln -s DOC.md README.md 2> /dev/null # can fail cd ${oldpwd} done; } function generate { go get github.com/devnev/godoc2ghmd generate_markdown echo "returning $?" } function check { generate count=$(git diff --numstat | wc -l | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') echo $count if [ "$count" = "0" ]; then return 0 else echo "Your markdown docs seem to be out of sync with the package docs. Please run make and consult CONTRIBUTING.MD" return 1 fi } "$@"
<reponame>minyong-jeong/hello-algorithm import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] fibonacci = new int[n + 1]; fibonacci[0] = 0; fibonacci[1] = 1; for (int i = 2; i <= n; i++) { fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]; } System.out.println(fibonacci[n]); } }
<gh_stars>0 import "/src/scss/index.scss"; import { Modal,Alert,Tab } from 'bootstrap';
def remove_duplicates(nums): new_list = [] for num in nums: if num not in new_list: new_list.append(num) return new_list print(remove_duplicates([1,2,3,4,2,2,4]))
function handleMainCheckbox() { $('#restrict-elements').change(function (e) { e.preventDefault(); var radio = $(e.currentTarget); if (radio.is(':checked')) { $('.restricted-elements-list').css("display", "block"); } else { $('.restricted-elements-list').css("display", "none"); } }); $('#restrict-elements').trigger('change'); } function restrictionsMap(restrictions) { var map = {}; for (var i = 0; i < restrictions.length; i++) { map[restrictions[i]] = true; } return map; } function htmlRowName(name) { return "<h6 class=\"circuit-element-category\"> ".concat(name, " </h6>"); } function htmlInlineCheckbox(elementName, checked) { return '\n <div class="form-check form-check-inline"> \n <label class="form-check-label primary-checkpoint-container" id = "label-' .concat(elementName, '" for="checkbox-') .concat(elementName, '">') .concat('<input class="form-check-input element-restriction" type="checkbox" id="checkbox-') .concat(elementName, '" value="') .concat(elementName, '" ') .concat('>\n') .concat('<div class="primary-checkpoint"></div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') .concat(elementName, "</span></label>\n</div>"); } function generateRow(name, elements, restrictionMap) { var html = htmlRowName(name); for (var i = 0; i < elements.length; i++) { var element = elements[i]; var checked = restrictionMap[element] ? 'checked' : ''; html += htmlInlineCheckbox(element, checked); } return html; } function loadHtml(elementHierarchy, restrictionMap) { for (var i = 0; i < Object.entries(elementHierarchy).length; i++) { var category = Object.entries(elementHierarchy)[i]; var html = generateRow(category[0], category[1], restrictionMap); $('.restricted-elements-list').append(html); } } function loadRestrictions(restrictions) { handleMainCheckbox(); var _metadata = metadata; var elementHierarchy = _metadata.elementHierarchy; var restrictionMap = restrictionsMap(restrictions); loadHtml(elementHierarchy, restrictionMap); }
<filename>client/src/containers/AssetAdmin/AssetAdminBreadcrumb.js /* global alert, confirm */ import React from 'react'; import PropTypes from 'prop-types'; import i18n from 'i18n'; import { Component as PlainBreadcrumb } from 'components/Breadcrumb/Breadcrumb'; import { hasFilters } from 'components/Search/Search'; /** * Display a breadcrumb based on the current folder, bypassing the stateful Breadcrumb component. * @param {Object} folder Info about the current folder. * @param {Object} query Info about the current search query. * Used to figure out if looking at search results. * @param {Function} getUrl Method used to compute the URL for a given file or folder. * @param {Function} onBrowse Callback for when the user click on one of the breadcrumb element. * @param {Function} onFolderIcon Callback for when the user decide to edit the info for a folder. */ const AssetAdminBreadcrumb = ({ folder, query, getUrl, onBrowse, onFolderIcon }) => { // Simple wrapper method around onBrowse that suppress the event const handleClick = (...args) => (event) => { event.preventDefault(); onBrowse(...args); }; // Simple wrapper around getURL to make sure a callback has been provided const hrefBuilder = (...args) => getUrl && getUrl(...args); // Set root breadcrumb const breadcrumbs = [{ text: i18n._t('AssetAdmin.FILES', 'Files'), href: hrefBuilder(0, null, query), onClick: handleClick(0, null, query), }]; if (folder && folder.id) { // Add parent folders if (folder.parents) { folder.parents.forEach((parent) => { breadcrumbs.push({ text: parent.title, href: hrefBuilder(parent.id, null, query), onClick: handleClick(parent.id, null, query) }); }); } // Add current folder const icons = [ { className: 'icon font-icon-edit-list', onClick: (e) => { e.preventDefault(); onFolderIcon(); }, } ]; if (folder.hasRestrictedAccess) { icons.push( { nodeName: 'FileStatusIcon', hasRestrictedAccess: true, } ); } breadcrumbs.push({ text: folder.title, href: hrefBuilder(folder.id, null, query), onClick: handleClick(folder.id, null, query), icons }); } // Search leaf if there was a search entered if (hasFilters(query.filter)) { breadcrumbs.push({ text: i18n._t('LeftAndMain.SEARCHRESULTS', 'Search results'), }); } return <PlainBreadcrumb multiline crumbs={breadcrumbs} />; }; AssetAdminBreadcrumb.propTypes = { onBrowse: PropTypes.func, onFolderIcon: PropTypes.func, getUrl: PropTypes.func, query: PropTypes.shape({ sort: PropTypes.string, limit: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), page: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), filter: PropTypes.object, view: PropTypes.string, }), folder: PropTypes.shape({ id: PropTypes.number, title: PropTypes.string, parents: PropTypes.array, parentId: PropTypes.number, canView: PropTypes.bool, canEdit: PropTypes.bool, }), }; export default AssetAdminBreadcrumb;
<script type="text/javascript"> $(document).ready(function(){ var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])){ tem= /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE '+(tem[1] || ''); } if (M[1]=== 'Chrome'){ tem= ua.match(/\b(OPR|Edge)\/(\d+)/); if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera'); } M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]); alert(M.join(' ')); }); </script>
#!/usr/bin/python # Function to detect anagrams def detect_anagrams(words): # Iterate over the list of words for i in range(len(words)-1): # Create a list to store anagrams anagrams = [words[i]] # Iterate over the rest of the words for j in range(i + 1, len(words)): # Check if two words are anagrams if sorted(words[i]) == sorted(words[j]): anagrams.append(words[j]) # Check if anagrams were found if len(anagrams) > 1: print("The anagrams are: " + str(anagrams)) # Input words words = ["canoe", "fez", "act", "cat"] # Call the function detect_anagrams(words) """ The anagrams are: ['canoe', 'act'] The anagrams are: ['cat'] """
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.javafx.collections; import java.util.Collections; import java.util.List; import javafx.collections.ListChangeListener.Change; import javafx.collections.ObservableList; public abstract class NonIterableChange<E> extends Change<E> { private final int from; private final int to; private boolean invalid = true; protected NonIterableChange(int from, int to, ObservableList<E> list) { super(list); this.from = from; this.to = to; } @Override public int getFrom() { checkState(); return from; } @Override public int getTo() { checkState(); return to; } private static final int[] EMPTY_PERM = new int[0]; @Override protected int[] getPermutation() { checkState(); return EMPTY_PERM; } @Override public boolean next() { if (invalid) { invalid = false; return true; } return false; } @Override public void reset() { invalid = true; } public void checkState() { if (invalid) { throw new IllegalStateException("Invalid Change state: next() must be called before inspecting the Change."); } } @Override public String toString() { boolean oldInvalid = invalid; invalid = false; String ret; if (wasPermutated()) { ret = ChangeHelper.permChangeToString(getPermutation()); } else if (wasUpdated()) { ret = ChangeHelper.updateChangeToString(from, to); } else { ret = ChangeHelper.addRemoveChangeToString(from, to, getList(), getRemoved()); } invalid = oldInvalid; return "{ " + ret + " }"; } public static class GenericAddRemoveChange<E> extends NonIterableChange<E> { private final List<E> removed; public GenericAddRemoveChange(int from, int to, List<E> removed, ObservableList<E> list) { super(from, to, list); this.removed = removed; } @Override public List<E> getRemoved() { checkState(); return removed; } } public static class SimpleRemovedChange<E> extends NonIterableChange<E> { private final List<E> removed; public SimpleRemovedChange(int from, int to, E removed, ObservableList<E> list) { super(from, to, list); this.removed = Collections.singletonList(removed); } @Override public boolean wasRemoved() { checkState(); return true; } @Override public List<E> getRemoved() { checkState(); return removed; } } public static class SimpleAddChange<E> extends NonIterableChange<E> { public SimpleAddChange(int from, int to, ObservableList<E> list) { super(from, to, list); } @Override public boolean wasRemoved() { checkState(); return false; } @Override public List<E> getRemoved() { checkState(); return Collections.<E>emptyList(); } } public static class SimplePermutationChange<E> extends NonIterableChange<E>{ private final int[] permutation; public SimplePermutationChange(int from, int to, int[] permutation, ObservableList<E> list) { super(from, to, list); this.permutation = permutation; } @Override public List<E> getRemoved() { checkState(); return Collections.<E>emptyList(); } @Override protected int[] getPermutation() { checkState(); return permutation; } } public static class SimpleUpdateChange<E> extends NonIterableChange<E>{ public SimpleUpdateChange(int position, ObservableList<E> list) { this(position, position + 1, list); } public SimpleUpdateChange(int from, int to, ObservableList<E> list) { super(from, to, list); } @Override public List<E> getRemoved() { return Collections.<E>emptyList(); } @Override public boolean wasUpdated() { return true; } } }
#!/usr/bin/env bash shopt -s -o pipefail set -e # Exit on error PKG_NAME="flex" PKG_VERSION="2.5.39" TARBALL="${PKG_NAME}-${PKG_VERSION}.tar.bz2" SRC_DIR="${PKG_NAME}-${PKG_VERSION}" function showHelp() { echo -e "--------------------------------------------------------------------------------------------------------------" echo -e "Description: The Flex package contains a utility for generating programs that recognize patterns in text." echo -e "--------------------------------------------------------------------------------------------------------------" echo -e "" } function prepare() { ln -sv /sources/${TARBALL} ${TARBALL} } function unpack() { tar xf ${TARBALL} } function build() { ./configure --prefix=/usr make ${MAKE_PARALLEL} } function runTest() { if [ -f /usr/bin/bison ];then make ${MAKE_PARALLEL} check || true fi } function instal() { if [ ! -f /usr/bin/bison ]; then make ${MAKE_PARALLEL} install cat > /usr/bin/lex << "EOF" #!/bin/sh # Begin /usr/bin/lex exec /usr/bin/flex -l "$@" # End /usr/bin/lex EOF chmod -v 755 /usr/bin/lex fi } function clean() { rm -rf ${SRC_DIR} ${TARBALL} } # Run the installation procedure time { showHelp;clean;prepare;unpack;pushd ${SRC_DIR};build;[[ ${MAKE_TESTS} = TRUE ]] && runTest;instal;popd;clean; } # Verify installation if [ -f /usr/bin/flex ]; then touch ${DONE_DIR_BUILD_SYSTEM}/$(basename $(pwd)) fi
def sort_by_value(dictionary): sorted_tuples = sorted(dictionary.items(), key=lambda x: x[1]) return dict(sorted_tuples) result = sort_by_value(dictionary) print(result)
<reponame>wolfchinaliu/gameCenter package weixin.liuliangbao.jsonbean; import java.io.Serializable; import java.util.List; /** * Created by aa on 2015/11/26. */ public class MerchantInfoBean implements Serializable{ /** * code : 200 * message : 请求成功 * data : {"id":"3ec3d1f0-9285-11e5-ab18-0800276b5788","name":"商户名称","merchantLevel":"S级","merchantCode":"4646431","business_type":"餐饮","province":"河北","city":"保定","mallTotal":10,"mallOpened":2,"enterpriseName":"企业名称","phoneNumber":"17956452315","email":"<EMAIL>","status":"激活","account":"3ec3d1f0-9285-11e5-ab18-0800276b5789","accountName":"账户名称","countryFlowValue":1564.5,"countryFlowCardCount":1564.5,"provinceFlowValue":1564.5,"countryFlowUnit":"M","countryFlowCardUnit":"M","provinceFlowUnit":"M","provinceFlowCardUnit":"M"} */ private String code; private String message; /** * id : 3ec3d1f0-9285-11e5-ab18-0800276b5788 * name : 商户名称 * merchantLevel : S级 * merchantCode : 4646431 * business_type : 餐饮 * province : 河北 * city : 保定 * mallTotal : 10 * mallOpened : 2 * enterpriseName : 企业名称 * phoneNumber : 17956452315 * email : <EMAIL> * status : 激活 * account : 3ec3d1f0-9285-11e5-ab18-0800276b5789 * accountName : 账户名称 * countryFlowValue : 1564.5 * countryFlowCardCount : 1564.5 * provinceFlowValue : 1564.5 * countryFlowUnit : M * countryFlowCardUnit : M * provinceFlowUnit : M * provinceFlowCardUnit : M */ private List<DataEntity> data; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<DataEntity> getData() { return data; } public void setData( List<DataEntity> data) { this.data = data; } public static class DataEntity { private String id; private String name; private String merchantLevel; private String merchantCode; private String business_type; private String province; private String city; private int mallTotal; private int mallOpened; private String enterpriseName; private String phoneNumber; private String email; private String status; private String account; private String accountName; private double countryFlowValue; private double countryFlowCardValue; private double provinceFlowValue; private double provinceFlowCardValue; private String countryFlowUnit; private String countryFlowCardUnit; private String provinceFlowUnit; private String provinceFlowCardUnit; private String belongmerchant; private String flowType; private String paymentpwd; public String getPaymentpwd() { return paymentpwd; } public void setPaymentpwd(String paymentpwd) { this.paymentpwd = paymentpwd; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBelongmerchant() { return belongmerchant; } public void setBelongmerchant(String belongmerchant) { this.belongmerchant = belongmerchant; } public String getMerchantLevel() { return merchantLevel; } public void setMerchantLevel(String merchantLevel) { this.merchantLevel = merchantLevel; } public String getMerchantCode() { return merchantCode; } public void setMerchantCode(String merchantCode) { this.merchantCode = merchantCode; } public String getBusiness_type() { return business_type; } public void setBusiness_type(String business_type) { this.business_type = business_type; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getMallTotal() { return mallTotal; } public void setMallTotal(int mallTotal) { this.mallTotal = mallTotal; } public int getMallOpened() { return mallOpened; } public void setMallOpened(int mallOpened) { this.mallOpened = mallOpened; } public String getEnterpriseName() { return enterpriseName; } public void setEnterpriseName(String enterpriseName) { this.enterpriseName = enterpriseName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public double getCountryFlowValue() { return countryFlowValue; } public void setCountryFlowValue(double countryFlowValue) { this.countryFlowValue = countryFlowValue; } public double getCountryFlowCardValue() { return countryFlowCardValue; } public void setCountryFlowCardValue(double countryFlowCardValue) { this.countryFlowCardValue = countryFlowCardValue; } public double getProvinceFlowCardValue() { return provinceFlowCardValue; } public void setProvinceFlowCardValue(double provinceFlowCardValue) { this.provinceFlowCardValue = provinceFlowCardValue; } public double getProvinceFlowValue() { return provinceFlowValue; } public void setProvinceFlowValue(double provinceFlowValue) { this.provinceFlowValue = provinceFlowValue; } public String getCountryFlowUnit() { return countryFlowUnit; } public void setCountryFlowUnit(String countryFlowUnit) { this.countryFlowUnit = countryFlowUnit; } public String getCountryFlowCardUnit() { return countryFlowCardUnit; } public void setCountryFlowCardUnit(String countryFlowCardUnit) { this.countryFlowCardUnit = countryFlowCardUnit; } public String getProvinceFlowUnit() { return provinceFlowUnit; } public void setProvinceFlowUnit(String provinceFlowUnit) { this.provinceFlowUnit = provinceFlowUnit; } public String getProvinceFlowCardUnit() { return provinceFlowCardUnit; } public void setProvinceFlowCardUnit(String provinceFlowCardUnit) { this.provinceFlowCardUnit = provinceFlowCardUnit; } public String getFlowType() { return flowType; } public void setFlowType(String flowType) { this.flowType = flowType; } } }
public class StartTestingResponse { private String requestId; private String code; // Getters and setters for requestId and code public static StartTestingResponse unmarshall(StartTestingResponse startTestingResponse, UnmarshallerContext _ctx) { startTestingResponse.setRequestId(_ctx.stringValue("StartTestingResponse.RequestId")); startTestingResponse.setCode(_ctx.stringValue("StartTestingResponse.Code")); return startTestingResponse; } }
sentence = "This is my sentence" words = sentence.split() if len(words) % 2 == 0: middle_index = len(words) // 2 print(words[middle_index - 1] + " " + words[middle_index]) else: middle_index = len(words) // 2 print(words[middle_index])
<reponame>BrysonL/cs3240-labdemo print("oops i can't use git")
#!/bin/bash # 不正な引数(2つ以外の正の整数)が入力されている場合 if [ $# -ne 2 ]; then echo "引数の数は必ず2つを指定してください" exit 1 fi # 不正な引数(0以下の値)が入力されている場合 if [ $1 -lt 1 ]; then echo "最大公約数を求められません" exit 2 fi if [ $2 -lt 1 ]; then echo "最大公約数を求められません" exit 2 fi # 引数が2つの正の整数(自然数)である場合 # 大きい値をNUM1へ、小さい値をNUM2へ代入する if [ $1 -lt $2 ]; then NUM1=$2 NUM2=$1 else NUM1=$1 NUM2=$2 fi # 大きい値を小さい値で割った余りを出す RESULT=$(( ${NUM1} % ${NUM2} )) # 余りが0でなければ再計算する while [ ${RESULT} -ne 0 ] do # 余りを求める計算 RESULT=$(( ${NUM1} % ${NUM2} )) # 余りが0以外なら変数を入替えて0になるまで繰り返し再計算 if [ ${RESULT} -ne 0 ]; then NUM1=${NUM2} NUM2=${RESULT} fi done # 余りが0になったら答えを返して終了する echo 最大公約数は ${NUM2} です
module MongoProfiler class Caller attr_reader :file, :line, :method, :_caller def initialize(_caller) @_caller = _caller caller_head = project_callers[0].split ':' # i.e. "/Users/pablo/workspace/project/spec/mongo_profiler_spec.rb:7:in `new'", @file = caller_head[0] @line = caller_head[1].to_i @method = project_callers[0][/`.*'/][1..-2] end private def project_callers # skip gem/bundle entries @project_callers ||= _caller.reject do |entry| entry.include?('bundle/ruby') || entry.include?('gem/ruby') || entry.include?('rubies/ruby') || entry.include?('extensions/moped.rb') end end end end
/* * Copyright 2017-present Open Networking Foundation * * 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. */ package org.onosproject.evpnopenflow.rsc; import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.evpnopenflow.rsc.EvpnConstants.ID; import static org.onosproject.evpnopenflow.rsc.EvpnConstants.ID_CANNOT_BE_NULL; import static org.onosproject.evpnopenflow.rsc.EvpnConstants.VPN_INSTANCE_ID; import static org.onosproject.evpnopenflow.rsc.EvpnConstants.VPN_INSTANCE_ID_CANNOT_BE_NULL; /** * Default implementation of VPN port. */ public class DefaultVpnPort implements VpnPort { private final VpnPortId id; private final VpnInstanceId vpnInstanceId; /** * creates vpn port object. * * @param id vpn port id * @param vpnInstanceId vpn instance id */ public DefaultVpnPort(VpnPortId id, VpnInstanceId vpnInstanceId) { this.id = checkNotNull(id, ID_CANNOT_BE_NULL); this.vpnInstanceId = checkNotNull(vpnInstanceId, VPN_INSTANCE_ID_CANNOT_BE_NULL); } @Override public VpnPortId id() { return id; } @Override public VpnInstanceId vpnInstanceId() { return vpnInstanceId; } @Override public int hashCode() { return Objects.hash(id, vpnInstanceId); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DefaultVpnPort) { final DefaultVpnPort that = (DefaultVpnPort) obj; return Objects.equals(this.id, that.id) && Objects.equals(this.vpnInstanceId, that.vpnInstanceId); } return false; } @Override public String toString() { return toStringHelper(this).add(ID, id) .add(VPN_INSTANCE_ID, vpnInstanceId).toString(); } }
<reponame>jamesscottbrown/bionano-wetLabAccelerator<gh_stars>10-100 'use strict'; describe('Service: ProtocolHelper', function () { // load the service's module beforeEach(module('wetLabAccelerator')); // instantiate service var ProtocolHelper; beforeEach(inject(function (_ProtocolHelper_) { ProtocolHelper = _ProtocolHelper_; })); it('should do something', function () { expect(!!ProtocolHelper).toBe(true); }); });
package de.eimantas.eimantasbackend.repo; import de.eimantas.eimantasbackend.entities.Account; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.stream.Stream; public interface AccountRepository extends CrudRepository<Account, Long> { public Stream<Account> findByUserId(String userId); @Query("select acc.id from #{#entityName} acc") List<Long> getAllIds(); }
<gh_stars>1-10 // Copyright 2004-present Facebook. All Rights Reserved. #include <vector> #include <string> #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> #include <glog/logging.h> #include <osquery/core.h> #include <osquery/tables.h> #include <osquery/filesystem.h> namespace osquery { namespace tables { QueryData parseEtcHostsContent(const std::string& content) { QueryData results; for (const auto& i : split(content, "\n")) { auto line = split(i); if (line.size() == 0 || boost::starts_with(line[0], "#")) { continue; } Row r; r["address"] = line[0]; if (line.size() > 1) { std::vector<std::string> hostnames; for (int i = 1; i < line.size(); ++i) { hostnames.push_back(line[i]); } r["hostnames"] = boost::algorithm::join(hostnames, " "); } results.push_back(r); } return results; } QueryData genEtcHosts(QueryContext& context) { std::string content; auto s = osquery::readFile("/etc/hosts", content); if (s.ok()) { return parseEtcHostsContent(content); } else { LOG(ERROR) << "Error reading /etc/hosts: " << s.toString(); return {}; } } } }
<reponame>ptrkvsky/gsap-animation import styled from '@emotion/styled' import theme from '../../theme' const BlockProjects = styled('section')` display: grid; grid-column-gap: 40px; margin: 0 auto; padding-top: 20vw; width: ${theme.maxWidth}; max-width: 100%; grid-template-columns: 1fr 1fr 1fr; a { display: block; } ` export { BlockProjects }
<filename>src/main/java/ohtu/services/SuggestionService.java package ohtu.services; import java.util.ArrayList; import java.util.List; import ohtu.domain.Blog; import ohtu.domain.Book; import ohtu.domain.Podcast; import ohtu.domain.Suggestion; import ohtu.domain.Suggestable; import ohtu.domain.Type; import ohtu.domain.Video; import ohtu.data_access.InterfaceBlogDao; import ohtu.data_access.InterfaceBookDao; import ohtu.data_access.InterfaceVideoDao; import ohtu.data_access.InterfacePodcastDao; import ohtu.data_access.InterfaceSuggestionDao; import ohtu.data_access.InterfaceTagDao; import ohtu.domain.Tag; public class SuggestionService { private InterfaceSuggestionDao suggestionDao; private InterfaceBookDao bookDao; private InterfaceBlogDao blogDao; private InterfacePodcastDao podcastDao; private InterfaceVideoDao videoDao; private InterfaceTagDao tagDao; public SuggestionService(InterfaceSuggestionDao suggestionDao, InterfaceBookDao bookDao, InterfaceBlogDao blogDao, InterfacePodcastDao podcastDao, InterfaceVideoDao videoDao) { this.suggestionDao = suggestionDao; this.bookDao = bookDao; this.blogDao = blogDao; this.podcastDao = podcastDao; this.videoDao = videoDao; } public SuggestionService(InterfaceSuggestionDao suggestionDao, InterfaceBookDao bookDao, InterfaceBlogDao blogDao, InterfacePodcastDao podcastDao, InterfaceVideoDao videoDao, InterfaceTagDao tagDao) { this.suggestionDao = suggestionDao; this.bookDao = bookDao; this.blogDao = blogDao; this.podcastDao = podcastDao; this.videoDao = videoDao; this.tagDao = tagDao; } public List<Suggestion> listAllSuggestions() { return suggestionDao.listAll(); } public List<Book> findBookByCreator(String creator) { return bookDao.findByCreator(creator); } public Book findBookByISBN(String ISBN) { return bookDao.findByISBN(ISBN); } public List<Book> findBookByDescription(String description) { return bookDao.findByDescription(description); } public List<Book> findBookByTitle(String title) { return bookDao.findByTitle(title); } public Book findBookByTitleAndCreator(String title, String creator) { return bookDao.findByTitleAndCreator(title, creator); } public Blog findBlogByURL(String url) { return blogDao.findByUrl(url); } public Video findVideoByURL(String url) { return videoDao.findByUrl(url); } public Podcast findPodcastByURL(String url) { return podcastDao.findByUrl(url); } public List<Suggestion> findByTitle(String title) { return suggestionDao.findByTitle(title); } public void addBook(Book b) { bookDao.add(b); } public void addBlog(Blog b) { blogDao.add(b); } public void addVideo(Video v) { videoDao.add(v); } public void addPodcast(Podcast p) { podcastDao.add(p); } public void addSuggestable(Suggestable s) { Type t = s.getType(); switch (t) { case BOOK: bookDao.add((Book) s); break; case BLOG: blogDao.add((Blog) s); break; case VIDEO: videoDao.add((Video) s); break; case PODCAST: podcastDao.add((Podcast) s); break; } } public void updateSuggestable(Suggestable s) { Type t = s.getType(); switch (t) { case BOOK: bookDao.update((Book) s); break; case BLOG: blogDao.update((Blog) s); break; case VIDEO: videoDao.update((Video) s); break; case PODCAST: podcastDao.update((Podcast) s); break; } } public boolean addSuggestion(Suggestable suggestable, List<Tag> tags) { if (suggestable != null) { suggestionDao.add(new Suggestion(suggestable, tags)); return true; } return false; } public List<Suggestion> findByAll(String arg) { return suggestionDao.findByAll(arg); } public void removeSuggestion(Suggestion s) { suggestionDao.remove(s); if (!suggestionDao.containsSuggestionForSuggestable(s.getSuggestable())) { Type t = s .getType(); switch (t) { case BOOK: bookDao.remove((Book) s.getSuggestable()); break; case BLOG: blogDao.remove((Blog) s.getSuggestable()); break; case PODCAST: podcastDao.remove((Podcast) s.getSuggestable()); break; case VIDEO: videoDao.remove((Video) s.getSuggestable()); break; } } } public void editTag(Tag t, String newContent) { tagDao.edit(t, newContent); } public void addTagsForSuggestion(int id, List<Tag> tags) { this.tagDao.addTagsForSuggestion(id, tags); } public void fillWithExampleData() { List<Tag> tags = new ArrayList<>(); tags.add(new Tag("code")); tags.add(new Tag("agile")); Blog blog = new Blog("How to Increase Velocity", "<NAME>", "Increase code quality today to increase your velocity tomorrow.", "https://www.agilealliance.org/how-to-increase-velocity/", "Agile Alliance Blog"); addBlog(blog); addSuggestion(blog, tags); tags.clear(); tags.add(new Tag("joulu")); tags.add(new Tag("kalastus")); blog = new Blog("<NAME>", "Johanna", "Johanna kirjoittaa elämästään norjalaisen kalastajan vaimona ja kahden söpöliinin äitinä. Blogissa pohditaan, miten arki voi olla kaunista, esitellään päivän asuja ja ihania sisustusasioita – sekä välillä pohditaan syvällisiä.", "https://www.menaiset.fi/blogit/kalastajan-vaimo/joulun-kayttolahjoja", "Kalastajan vaimo"); addBlog(blog); addSuggestion(blog, tags); tags.clear(); tags.add(new Tag("agile")); tags.add(new Tag("software")); Book book = new Book("Clean Code: A Handbook of Agile Software Craftsmanship", "<NAME>", "Noted software expert <NAME> presents a revolutionary paradigm with Clean Code: A Handbook of Agile Software Craftsmanship", "978-951-98548-9-2"); addBook(book); addSuggestion(book, tags); tags.clear(); tags.add(new Tag("algorithms")); book = new Book("Introduction to Algorithms", "<NAME>, <NAME>, <NAME> and <NAME>", "The bible of algorithms. Widely used as a coursebook in CS curriculums.", "978-026-20338-4-8"); addBook(book); addSuggestion(book, tags); tags.clear(); tags.add(new Tag("help")); Podcast podcast = new Podcast("JRE #002 - MMA Show #2", "<NAME>" , "<NAME> help", "http://podcasts.joerogan.net/podcasts/mma-show-2", "The Joe Rogan Experience"); addPodcast(podcast); addSuggestion(podcast, tags); tags.clear(); tags.add(new Tag("history")); tags.add(new Tag("individualism")); podcast = new Podcast("#038 Revolution In The Age Of Anger (with <NAME>)", "<NAME>" , "Historian and novelist <NAME> joins me to talk about what he calls the ‘age of anger’ - a global pandemic of rage - and how the pursuit of progress and individualism has created a demoralised world.", "https://art19.com/shows/under-the-skin/episodes/ef646cc4-c1dd-486e-ab33-6da8d88a8c13", "Under The Skin"); addPodcast(podcast); addSuggestion(podcast, tags); tags.clear(); tags.add(new Tag("turing")); tags.add(new Tag("algorithms")); Video video = new Video("Turing Machine - Introduction (Part 1)", "Neso Academy", "TOC: Introduction to Turing Machine", "https://www.youtube.com/watch?v=PvLaPKPzq2I"); addVideo(video); addSuggestion(video, tags); tags.clear(); tags.add(new Tag("tietojenkäsittely")); video = new Video("Mitä tietojenkäsittely on?", "<NAME>", "Tietojenkäsittelytieteen laitoksen opettajat kertovat mitä tietojenkäsittely on, ja mihin olemme menossa.", "https://www.youtube.com/watch?v=q44xFlrKCTE"); addVideo(video); addSuggestion(video, tags); } }
#!/usr/bin/env bash # # 【 zenbuPortable 】 zenbuSummoner.command # Ver1.40.190419a # Concepted by TANAHASHI, Jiro (aka jtFuruhata) # Copyright (C) 2019 jtLab, Hokkaido Information University # summoner_usage () { echo "Usage:" echo " . zenbuSummoner.command [<id>]" echo " [.] zenbuSummoner.command [-k] [-r]" echo echo "Description:" echo " zenbuPortable SSH agent summoner/recaller" echo echo "Options:" echo " -k ... Unset key & Recall agent (only for Windows)" echo " Unset all keys when exec without ." echo " -r ... Unset key & Recall **ALL** agents (only for Windows)" echo " Unset all keys when exec without ." echo " <id> ... Use specific identity instead of .ssh/ssh_id" exit 1 } summoner_optKill=0 summoner_optRecall=0 while getopts "kr" options do case $options in k) # Recall agent summoner_optKill=1 ;; r) # Recall all agents summoner_optRecall=1 ;; esac done shift $((OPTIND - 1)) summoner_optID="$1" unset SSH_KEY summoner_result=0 addkey () { ssh-add $SSH_KEY } rmkey () { ssh-add -d $SSH_KEY } export -f addkey export -f rmkey echo "zenbuSummoner is recognizing status about SSH & Git" echo # # include zenbuEnv and portaleGitPortal if necessary if [ -z "$zenbuOSType" ]; then export dontSummonMe=true . `dirname $0`/zenbuEnv.sh; unset dontSummonMe fi # # check Git & SSH agent installation which git > /dev/null 2>&1; summoner_check_git=$? which ssh-agent > /dev/null 2>&1; summoner_check_ssh_agent=$? which ssh-add > /dev/null 2>&1; summoner_check_ssh_add=$? # ## check SSH agent status [ -z $SSH_AGENT_PID ]; summoner_check_PID=$? [ -z $SSH_AUTH_SOCK ]; summoner_check_SOCK=$? # ## preparing SSH envs if [ $(($summoner_check_ssh_agent+$summoner_check_ssh_add)) = 0 ]; then export SSH_HOME="$HOME/.ssh" export SSH_KEYS="$Tzenbu/.ssh" mkdir -p "$SSH_KEYS" if [ $(($summoner_optRecall+$summoner_optKill)) = 0 ]; then ## check $SSH_HOME/ssh_id if [ ! -z $summoner_optID ]; then export SSH_ID="$summoner_optID" echo "OpenSSH(Git) will attempt to use <id>: $SSH_ID" elif [ -e "$SSH_HOME/ssh_id" ]; then export SSH_ID="`cat $SSH_HOME/ssh_id`" echo "OpenSSH(Git) will attempt to use ssh_id: $SSH_ID" else echo "No Key Mode" unset SSH_ID fi if [ ! -z $SSH_ID ]; then if [ -e "$SSH_HOME/$SSH_ID" ]; then export SSH_KEY="$SSH_KEYS/$SSH_ID" cp -f "$SSH_HOME/$SSH_ID" "$SSH_KEY" chmod 700 "$SSH_KEY" > /dev/null 2>&1 if [ $? = 1 ]; then echo "** WARNING **" echo "Unable to chmod: check filesystem." unset SSH_ID unset SSH_KEY summoner_result=1 fi else echo "** WARNING **" echo " Missing ID file $SSH_ID: turn into No Key Mode" unset SSH_ID summoner_result=1 fi fi ## preparing placeholder if [ ! -e "$SSH_HOME/known_hosts" ]; then touch "$SSH_HOME/known_hosts"; fi if [ ! -e "$SSH_HOME/config" ]; then touch "$SSH_HOME/config"; fi ## check git config if [ $summoner_check_git = 0 ]; then git config --global core.sshCommand "ssh -T -o UserKnownHostsFile=$SSH_HOME/known_hosts -F $SSH_HOME/config -i $SSH_KEY" git config --global init.templatedir "$zenbuPathGit/share/git-core/templates" git config --global core.autoCRLF false summoner_gitname=`git config --global user.name` summoner_check_gitname=$? echo "Git user.name = $summoner_gitname" summoner_gitemail=`git config --global user.email` summoner_check_gitemail=$? echo "Git user.email = $summoner_gitemail" if [ $(($summoner_check_gitname+$summoner_check_gitemail)) -gt 0 ]; then echo "Notice: You shoud set up your name & email for Git:" echo " git config --global user.name \"Taro Yamada\"" echo " git config --global user.email \"tyamada@mygitid.info\"" fi else echo "** WARNING **" echo " Missing Git: we can't use Git." summoner_result=1 fi ## summon agent if necessary ssh-add -l > /dev/null 2>&1 summoner_ssh_add_l=$? # Could not open a connection -> summon agent if [ $summoner_ssh_add_l = 2 ]; then unset SSH_AGENT_PID unset SSH_AUTH_SOCK echo "Now Summoning SSH agent..." eval $(echo "$(ssh-agent)") else echo "SSH agent is already standing by you." fi # unset key & recall all agent (for windows) else if [ -z $SSK_KEY ]; then ssh-add -D else ssh-add -d $SSH_KEY rm -f $SSH_KEY unset SSH_KEY fi if [ $zenbuOSType == "win" ]; then if [ $summoner_optRecall = 1 ]; then ssh-recall-all else eval $(echo "$(ssh-agent -k)") fi unset SSH_AGENT_PID unset SSH_AUTH_SOCK fi fi # key list summoner_list="`ssh-add -l`" if [ $? = 0 ]; then echo "SSH agent key list:" echo "$summoner_list" else echo "SSH agent has no key." fi else echo "** WARNING **" echo " Missing OpenSSH: zenbuSummoner can't summon SSH agent." summoner_result=1 fi if [ ! -z $SSH_KEY ]; then echo echo "You may use 'addkey' and 'rmkey' command for SSH key operation." echo fi return $summoner_result > /dev/null 2>&1 if [ $? = 1 ]; then exit $summoner_result fi
import { Main } from '../../index.js'; import { SpriteSheet } from '../../z0/graphics/spritesheet.js'; import { Sprite2D } from '../../z0/graphics/sprite2d.js'; import * as VAR from '../../z0/var.js' import { TextureManager } from '../../z0/graphics/texturemanager.js'; import { Module } from '../../z0/tree/module.js'; import { BitmapText } from '../fonts/bitmaptext.js'; export class Tile extends Sprite2D { static spriteSheet; static initSpriteSheet(image) { this.spriteSheet = new SpriteSheet(image); this.spriteSheet.createFrame(400,400,1,1); for(let i = 0; i < 7; i++) { this.spriteSheet.createFrame(i * 64, 0, 32, 32) } } constructor(x, y, parent, layer = 5, size = Grid.size) { super(parent, TextureManager.sprites, x, y, size, size, 0, layer, Tile.spriteSheet) } } export class Grid { static DEAD = 0; static ALIVE_1 = 1; static ALIVE_2 = 2; static ALIVE_3 = 3; static size = 10; static width;// = VAR.canvas.width / Grid.size + Grid.size; static height;// = VAR.canvas.height / Grid.size + Grid.size; parent; static init() { this.width = VAR.canvas.width / Grid.size + 2; this.height = VAR.canvas.height / Grid.size + 2; } static data; a_1 = 0; a_2 = 0; a_3 = 0; tiles = [] buffer1 = [Grid.width]; buffer2 = [Grid.width]; usingBuffer1 = true; xLoc = Grid.size / 2 - Grid.size; yLoc = Grid.size / 2 - Grid.size; spriteOffset = 0; iterations = 0; constructor() { this.parent = new Module(null, 0, 0, 0) for(let i = 0; i < Grid.width; i++) { this.tiles.push([]) this.buffer1[i] = []; this.buffer2[i] = []; for(let j = 0; j < Grid.height; j++) { this.tiles[i][j] = new Tile(this.xLoc + i * Grid.size, this.yLoc + j * Grid.size, this.parent) this.tiles[i][j].setAlpha(0.5) this.buffer1[i][j] = Grid.DEAD; this.buffer2[i][j] = Grid.DEAD; } } this.buffer1[Grid.width - 24][Grid.height - 2] = Grid.ALIVE_3 this.buffer1[Grid.width - 50][Grid.height - 50] = Grid.ALIVE_1 this.buffer1[Grid.width - 80][Grid.height - 80] = Grid.ALIVE_1 this.buffer1[3][Grid.height - 50] = Grid.ALIVE_1 this.buffer1[Grid.width - 2][3] = Grid.ALIVE_1 this.buffer1[4][3] = Grid.ALIVE_2 this.buffer1[3][3] = Grid.ALIVE_2 this.buffer1[3][4] = Grid.ALIVE_2 this.buffer1[2][4] = Grid.ALIVE_2 this.buffer1[5][3] = Grid.ALIVE_2 this.buffer1[5][3] = Grid.ALIVE_2 this.buffer1[5][2] = Grid.ALIVE_2 this.buffer1[5][1] = Grid.ALIVE_2 } setValueAt(x, y, v) { x -= this.xLoc; y -= this.yLoc; x /= Grid.size; y /= Grid.size; x += .5; y += .5; x = Math.floor(x); y = Math.floor(y); if(x < 1 || x >= Grid.width) return; if(y < 1 || y >= Grid.height) return; this.buffer1[x][y] = v; this.buffer2[x][y] = v; this.tiles[x][y].setSprite(this.buffer1[x][y]); } steps = 0; update() { this.steps++; let next; next = []; for(let i = 0; i < Grid.width; i++) { next.push(new Int16Array(Grid.height)) for(let j = 0; j < Grid.height; j++) { next[i][j] = this.buffer1[i][j] } } let a_2_ind = 3; let a_3_ind = 3; if(this.steps > 50) { a_2_ind = this.a_1 < 50 ? 5 : 3; a_3_ind = this.a_2 < 50 ? 5 : 3; } else { a_2_ind = 3; a_3_ind = 3; } this.a_1 = 0; this.a_2 = 0; this.a_3 = 0; for(let i = 1; i < this.buffer1.length - 1; i++) { for(let j = 1; j < this.buffer1[0].length - 1; j++) { switch(this.buffer1[i][j]) { case Grid.DEAD: { let alive = [ 0,0,0 ] for(let k = i - 1; k < i + 2; k++) { for(let l = j - 1; l < j + 2; l++) { if(this.buffer1[k][l] > Grid.DEAD) { if(k == i && l == j) continue alive[this.buffer1[k][l]]++; } } } let max = 0, ind; for(let i = 0; i < alive.length; i++) { if(alive[i] > max) { max = alive[i] ind = i } } if(max == 2 || max == 4) { next[i][j] = ind; } } break; case Grid.ALIVE_1: { this.a_1++; let al = 0; for(let k = i - 1; k < i + 2; k++) { for(let l = j - 1; l < j + 2; l++) { if(this.buffer1[k][l] == Grid.ALIVE_3) { let c = (Math.cos((k * i + l * j + 11)) * 131 + this.steps) % 6 if(c > 4) next[k][l] = Grid.ALIVE_1 } else if(this.buffer1[k][l] == Grid.ALIVE_1) { if(k == i && l == j) continue al++; } } } // if(al < 1) { // next[i][j] = Grid.DEAD // } //else if(al > 4) { // next[i][j] = Grid.DEAD // } } break; case Grid.ALIVE_2: { this.a_2++; let al = 0; for(let k = i - 1; k < i + 2; k++) { for(let l = j - 1; l < j + 2; l++) { if(this.buffer1[k][l] == Grid.ALIVE_1) { let c = (Math.cos((k * i + l * j + 121) + this.steps) * 131) % 6 if(c > 4) next[k][l] = Grid.ALIVE_2 } else if(this.buffer1[k][l] == Grid.ALIVE_2) { if(k == i && l == j) continue al++; } } } if(al < 1) { next[i][j] = Grid.DEAD } else if(al > a_2_ind) { next[i][j] = Grid.DEAD } } break; case Grid.ALIVE_3: { this.a_3++; let al = 0; for(let k = i - 1; k < i + 2; k++) { for(let l = j - 1; l < j + 2; l++) { if(this.buffer1[k][l] == Grid.ALIVE_2) { let c = (Math.cos((k * i + l * j + 131)) * 531 + this.steps) % 6 if(c > 3) next[k][l] = Grid.ALIVE_3 } else if(this.buffer1[k][l] == Grid.ALIVE_3) { if(k == i && l == j) continue al++; } } } // if(al < 1) { // next[i][j] = Grid.DEAD // } else if(al > a_3_ind) { // next[i][j] = Grid.DEAD // } } break; } } } this.buffer1 = next; Grid.data = this.buffer1 } updateGraphics() { if(this.iterations > Main.STAGE_2_2) { this.spriteOffset = 4; } for(let i = 1; i < this.buffer1.length; i++) { for(let j = 1; j < this.buffer1[0].length ; j++) { this.tiles[i][j].setSprite(this.buffer1[i][j] + this.spriteOffset) } } } setAlpha(a) { for(let i = 1; i < this.buffer1.length; i++) { for(let j = 1; j < this.buffer1[0].length ; j++) { this.tiles[i][j].setAlpha(a); } } } } export class GridGroup { static mult = 10 static size = Grid.size * GridGroup.mult; parent; tiles = []; alpha = 1; xLoc = GridGroup.size / 2; yLoc = GridGroup.size / 2; static width; static height; static init() { this.width = VAR.canvas.width / GridGroup.size ; this.height = VAR.canvas.height / GridGroup.size; } constructor() { this.parent = new Module(null, 0, 0, 0); for(let i = 0; i < GridGroup.width; i++) { this.tiles.push([]) for(let j = 0; j < GridGroup.height; j++) { this.tiles[i][j] = new Tile(i * GridGroup.size + this.xLoc, j * GridGroup.size + this.yLoc, this.parent, 2, GridGroup.size); this.tiles[i][j].setAlpha(0.7) } } } updateGraphics() { let tiles = Grid.data; for(let i = 0; i < GridGroup.width; i++) { for(let j = 0; j < GridGroup.height; j++) { let x = i * GridGroup.mult; let y = j * GridGroup.mult; let arr = [0,0,0,0] for(let k = x; k < x + 10; k++) { for(let l = y; l < y + 10; l++) { arr[tiles[k][l] % 4]++; } } let max = 0; let ind = 0; for(let k = 1; k < arr.length; k++) { if(arr[k] > max) { max = arr[k] ind = k; } } this.tiles[i][j].setSprite(4+ ind) } } } setAlpha(a) { for(let i = 0; i < GridGroup.width; i++) { for(let j = 0; j < GridGroup.height; j++) { this.tiles[i][j].setAlpha(a); } } } } export class GridPath extends Module{ static spritesheet; static ALPHA_IDLE = 0.4; tiles = []; alpha = 1; xLoc = -Grid.size / 4; yLoc = -Grid.size / 4; width; height; static init() { this.width = VAR.canvas.width / Grid.size + Grid.size; this.height = VAR.canvas.height / Grid.size + Grid.size; } constructor(imageData) { super(null, 0, 0, 0); const WIDTH = 4; let index = 0; for(let i = 0, h = 0; i < Grid.height; i++, h++) { this.tiles.push([]) for(let j = 0, w = 0; j < Grid.width; j++, w++) { this.tiles[i][j] = imageData[index] == 0 ? new Path(this.xLoc + w * Grid.size, this.yLoc + h * Grid.size, this) : undefined; index += WIDTH; } } } getTileAt(y, x) { x -= this.xLoc; y -= this.yLoc; x /= Grid.size; y /= Grid.size; x += .5; y += .5; x = Math.floor(x); y = Math.floor(y); if(x < 0 || x >= Grid.height) return; if(y < 0 || y >= Grid.width) return; return this.tiles[x][y]; } setAlpha(a) { if(this.alpha != a) { for(let i = 0; i < this.tiles.length; i++) { for(let j = 0; j < this.tiles[0].length; j++) { if(this.tiles[i][j]) this.tiles[i][j].setAlpha(a); } } this.alpha = a; } } destroyPath(y, x) { x -= this.xLoc; y -= this.yLoc; x /= Grid.size; y /= Grid.size; x += .5; y += .5; x = Math.floor(x); y = Math.floor(y); if(x < 0 || x >= Grid.height) return; if(y < 0 || y >= Grid.width) return; if(this.tiles[x][y] != undefined) this.tiles[x][y].setVisible(false); this.tiles[x][y] = undefined; } } export class Path extends Sprite2D { static spriteSheet; static initSpriteSheet() { this.spriteSheet = new SpriteSheet(TextureManager.sprites); this.spriteSheet.createFrame(0,64,32,32); this.spriteSheet.createFrame(64,64,32,32); } constructor(x, y, parent) { super(parent, TextureManager.sprites, x, y, Grid.size, Grid.size, 0, 5, Path.spriteSheet) this.setSprite(Math.floor((Math.random() * 12231) % 2)); } } export class ElectionText extends BitmapText { constructor(x, y, size, index = 0) { super(null, x, y, TextureManager.font, 5, 7, size, size * (7/5), 14); if(index < 0) return; let s = new SpriteSheet(TextureManager.flag); s.createFrame(0, 128 * (index * 2), 256, 128); let xx = 100, yy = 50; if(index == 3) { xx *= 1.5; yy *= 1.5; } this.flag = new Sprite2D(this, TextureManager.flag, -100, 10, xx, yy, 0, 14, s); this.flag.setVisible(false); } setString(str) { super.setString(str); this.flag.setVisible(true); } }
<gh_stars>0 // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. package com.microsoft.accessibilityinsightsforandroidservice; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.deque.axe.android.AxeResult; import com.google.android.apps.common.testing.accessibility.framework.AccessibilityHierarchyCheckResult; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.AdditionalAnswers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ResultsV2ContainerSerializerTest { @Mock AxeResult axeResultMock; @Mock ATFARulesSerializer atfaRulesSerializer; @Mock ATFAResultsSerializer atfaResultsSerializer; @Mock GsonBuilder gsonBuilder; @Mock JsonWriter jsonWriter; @Mock Gson gson; final List<AccessibilityHierarchyCheckResult> atfaResults = Collections.emptyList(); final ResultsV2Container resultsV2Container = new ResultsV2Container(); TypeAdapter<ResultsV2Container> resultsContainerTypeAdapter; ResultsV2ContainerSerializer testSubject; @Before public void prepare() { doAnswer( AdditionalAnswers.answer( (Type type, TypeAdapter<ResultsV2Container> typeAdapter) -> { resultsContainerTypeAdapter = typeAdapter; return gsonBuilder; })) .when(gsonBuilder) .registerTypeAdapter(eq(ResultsV2Container.class), any()); when(gsonBuilder.create()).thenReturn(gson); resultsV2Container.AxeResult = axeResultMock; resultsV2Container.ATFAResults = atfaResults; testSubject = new ResultsV2ContainerSerializer(atfaRulesSerializer, atfaResultsSerializer, gsonBuilder); } @Test public void generatesExpectedJson() { AtomicReference<ResultsV2Container> resultsContainer = new AtomicReference<>(); doAnswer( AdditionalAnswers.answer( (ResultsV2Container container) -> { resultsContainer.set(container); return "Test String"; })) .when(gson) .toJson(any(ResultsV2Container.class)); testSubject.createResultsJson(axeResultMock, atfaResults); Assert.assertEquals(axeResultMock, resultsContainer.get().AxeResult); Assert.assertEquals(atfaResults, resultsContainer.get().ATFAResults); } @Test public void typeAdapterSerializes() throws IOException { String axeJson = "axe scan result"; String atfaRulesJson = "atfa rules"; String atfaJson = "atfa scan results"; when(axeResultMock.toJson()).thenReturn(axeJson); when(atfaRulesSerializer.serializeATFARules()).thenReturn(atfaRulesJson); when(atfaResultsSerializer.serializeATFAResults(atfaResults)).thenReturn(atfaJson); when(jsonWriter.name("AxeResults")).thenReturn(jsonWriter); when(jsonWriter.name("ATFARules")).thenReturn(jsonWriter); when(jsonWriter.name("ATFAResults")).thenReturn(jsonWriter); resultsContainerTypeAdapter.write(jsonWriter, resultsV2Container); verify(jsonWriter, times(1)).beginObject(); verify(jsonWriter, times(1)).jsonValue(axeJson); verify(jsonWriter, times(1)).jsonValue(atfaRulesJson); verify(jsonWriter, times(1)).jsonValue(atfaJson); verify(jsonWriter, times(1)).endObject(); verify(axeResultMock, times(1)).toJson(); } }
<reponame>rsuite/rsuite-icons // Generated by script, don't edit it please. import createSvgIcon from '../../createSvgIcon'; import GittipSvg from '@rsuite/icon-font/lib/legacy/Gittip'; const Gittip = createSvgIcon({ as: GittipSvg, ariaLabel: 'gittip', category: 'legacy', displayName: 'Gittip' }); export default Gittip;
<gh_stars>0 package org.museautomation.ui.settings; import javafx.stage.*; import org.museautomation.settings.*; import org.museautomation.ui.extend.components.*; import java.io.*; import java.util.*; /** * @author <NAME> (see LICENSE.txt for license details) */ public class StageSettings extends BaseSettingsFile { public void register(Stage stage) { _stage = stage; if (_width == 0) return; // don't apply until they've been saved from useful settings stage.setX(_x); stage.setY(_y); stage.setWidth(_width); stage.setHeight(_height); Closer.get().add(this); } @Override public void close() throws IOException { _x = _stage.getX(); _y = _stage.getY(); _width = _stage.getWidth(); _height = _stage.getHeight(); super.close(); } @SuppressWarnings("unused") // required for serialization public double getX() { return _x; } @SuppressWarnings("unused") // required for serialization public void setX(double x) { _x = x; } @SuppressWarnings("unused") // required for serialization public double getY() { return _y; } @SuppressWarnings("unused") // required for serialization public void setY(double y) { _y = y; } @SuppressWarnings("unused") // required for serialization public double getWidth() { return _width; } @SuppressWarnings("unused") // required for serialization public void setWidth(double width) { _width = width; } @SuppressWarnings("unused") // required for serialization public double getHeight() { return _height; } @SuppressWarnings("unused") // required for serialization public void setHeight(double height) { _height = height; } private transient Stage _stage; private double _x = 0; private double _y = 0; private double _width = 0; private double _height = 0; public static StageSettings get() { return get(FILENAME); } public static StageSettings get(String name) { StageSettings settings = SETTINGS.get(name); if (settings == null) { settings = (StageSettings) load(StageSettings.class, name, null); Closer.get().add(settings); SETTINGS.put(name, settings); } return settings; } private static Map<String, StageSettings> SETTINGS = new HashMap<>(); private final static String FILENAME = "Editor-stage.json"; }
<gh_stars>0 package xlpp import ( "encoding/binary" "fmt" "io" "sort" "strings" "time" ) // The following types are supported by this library: const ( // extended LPP types TypeInteger Type = 51 TypeString Type = 52 TypeBool Type = 53 TypeBoolTrue Type = 54 TypeBoolFalse Type = 55 TypeObject Type = 123 // '{' TypeEndOfObject Type = 0 // '}' TypeArray Type = 91 // '[' // TypeArrayOf Type = 92 // '[' TypeEndOfArray Type = 93 // '[' TypeFlags Type = 56 TypeBinary Type = 57 TypeNull Type = 58 ) // Special (reserved) channels for "Marker" types: const ( // special XLPP channels ChanDelay = 253 ChanActuators = 252 ChanActuatorsWithChannel = 251 ) // Null is a empty type. It holds no data. type Null struct{} // XLPPType for Null returns TypeNull func (v Null) XLPPType() Type { return TypeNull } func (v Null) String() string { return "null" } // ReadFrom reads the Null from the reader. func (v *Null) ReadFrom(r io.Reader) (n int64, err error) { return 0, nil } // WriteTo writes the Null to the writer. func (v Null) WriteTo(w io.Writer) (n int64, err error) { return 0, nil } //////////////////////////////////////////////////////////////////////////////// // Binary is a simple array of bytes. type Binary []byte // XLPPType for Binary returns TypeBinary. func (v Binary) XLPPType() Type { return TypeBinary } func (v Binary) String() string { return fmt.Sprintf("%X", []byte(v)) } // ReadFrom reads the Binary from the reader. func (v *Binary) ReadFrom(r io.Reader) (n int64, err error) { var brc byteReaderCounter brc.ByteReader = newByteReader(r) l, err := binary.ReadUvarint(&brc) if err != nil { return int64(brc.Count), err } *v = make(Binary, l) var m int m, err = io.ReadFull(r, *v) return int64(brc.Count + m), err } // WriteTo writes the Binary to the writer. func (v Binary) WriteTo(w io.Writer) (n int64, err error) { var buf [9]byte var m int m = binary.PutUvarint(buf[:], uint64(len(v))) n += int64(m) m, err = w.Write(buf[:m]) n += int64(m) if err == nil { m, err = w.Write(v) n += int64(m) } return } //////////////////////////////////////////////////////////////////////////////// // Bool is a boolean true/false. type Bool bool // XLPPType for Bool returns TypeBool. func (v Bool) XLPPType() Type { if v { return TypeBoolTrue } return TypeBoolFalse } func (v Bool) String() string { if v { return "true" } return "false" } // ReadFrom reads the Bool from the reader. func (v *Bool) ReadFrom(r io.Reader) (n int64, err error) { return 0, nil } // WriteTo writes the Bool to the writer. func (v Bool) WriteTo(w io.Writer) (n int64, err error) { return 0, nil } //////////////////////////////////////////////////////////////////////////////// // Integer is a simple integer value. type Integer int // XLPPType for Integer returns TypeInteger. func (v Integer) XLPPType() Type { return TypeInteger } func (v Integer) String() string { return fmt.Sprintf("%d", int(v)) } // ReadFrom reads the Integer from the reader. func (v *Integer) ReadFrom(r io.Reader) (n int64, err error) { var brc byteReaderCounter brc.ByteReader = newByteReader(r) i64, err := binary.ReadVarint(&brc) *v = Integer(i64) return int64(brc.Count), err } // WriteTo writes the Integer to the writer. func (v Integer) WriteTo(w io.Writer) (n int64, err error) { var buf [9]byte m := binary.PutVarint(buf[:], int64(v)) m, err = w.Write(buf[:m]) n = int64(m) return } //////////////////////////////////////////////////////////////////////////////// // String is a simple string value. type String string // XLPPType for String returns TypeString. func (v String) XLPPType() Type { return TypeString } func (v String) String() string { return fmt.Sprintf("%q", string(v)) } // ReadFrom reads the String from the reader. func (v *String) ReadFrom(r io.Reader) (n int64, err error) { buf := make([]byte, 0, 32) var brc byteReaderCounter brc.ByteReader = newByteReader(r) for { b, err := brc.ReadByte() if err != nil { return int64(brc.Count), err } if b == 0 { *v = String(buf) return int64(brc.Count), nil } buf = append(buf, b) } } // WriteTo writes the String to the writer. func (v String) WriteTo(w io.Writer) (n int64, err error) { var m int m, err = w.Write([]byte(v)) n += int64(m) if err == nil { m, err = w.Write([]byte{0}) n += int64(m) } return } //////////////////////////////////////////////////////////////////////////////// // Object is a simple key-value map. type Object map[string]Value // XLPPType for Object returns TypeObject. func (v Object) XLPPType() Type { return TypeObject } func (v Object) String() string { var b strings.Builder b.WriteByte('{') first := true for key, value := range v { if !first { b.WriteByte(',') } first = false b.WriteString(key) b.WriteByte(':') b.WriteByte(' ') b.WriteString(value.String()) } b.WriteByte('}') return b.String() } func (v Object) keys() []string { keys := make([]string, len(v)) i := 0 for key := range v { keys[i] = key i++ } sort.Strings(keys) return keys } // func (v Object) XLPPWriteHeadTo(w io.Writer) (n int64, err error) { // keys := v.keys() // var m int // m, err = w.Write([]byte{byte(len(v))}) // n += int64(m) // if err != nil { // return // } // for _, key := range keys { // var m int64 // m, err = String(key).WriteTo(w) // n += m // if err != nil { // return // } // } // return // } // func (v *Object) XLPPReadHeadFrom(r io.Reader) (n int64, err error) { // var buf [1]byte // var m int // m, err = r.Read(buf[:]) // n += int64(m) // if err != nil { // return // } // l := int(buf[0]) // *v = make(Object, l) // for i := 0; i < l; i++ { // var str String // var m int64 // m, err = str.ReadFrom(r) // n += m // if err != nil { // return // } // (*v)[string(str)] = nil // } // return // } // ReadFrom reads the Object from the reader. func (v *Object) ReadFrom(r io.Reader) (n int64, err error) { *v = make(Object) buf := make([]byte, 32) var brc byteReaderCounter brc.ByteReader = newByteReader(r) for { var key string { var b byte b, err = brc.ReadByte() if b == byte(TypeEndOfObject) { return } buf = buf[:0] for { if err != nil { return int64(brc.Count), err } if b == 0 { key = string(buf) break } buf = append(buf, b) b, err = brc.ReadByte() } } { var m int64 (*v)[key], m, err = read(r) n += m if err != nil { return } } } } // WriteTo writes the Object to the writer. func (v Object) WriteTo(w io.Writer) (n int64, err error) { keys := v.keys() for _, key := range keys { { var m int64 m, err = String(key).WriteTo(w) n += m if err != nil { return } } { var m int m, err = write(w, v[key]) n += int64(m) if err != nil { return } } } { var m int m, err = w.Write([]byte{byte(TypeEndOfObject)}) n += int64(m) if err != nil { return } } return } //////////////////////////////////////////////////////////////////////////////// // Array is a simple list of values. type Array []Value // XLPPType for Array returns TypeArray. func (v Array) XLPPType() Type { // if t := v.getItemType(); t != 0 { // return TypeArrayOf // } return TypeArray } func (v Array) String() string { var b strings.Builder b.WriteByte('[') first := true for _, t := range v { if !first { b.WriteByte(',') b.WriteByte(' ') } first = false b.WriteString(t.String()) } b.WriteByte(']') return b.String() } // func (v Array) getItemType() (t Type) { // if len(v) == 0 { // return 0 // } // for i, value := range v { // if i == 0 { // t = value.XLPPType() // } else { // if t != value.XLPPType() { // return 0 // } // } // } // return // } // ReadFrom reads the Array from the reader. func (v *Array) ReadFrom(r io.Reader) (n int64, err error) { *v = make(Array, 0, 8) for { var m int64 var i Value i, m, err = read(r) n += m if err != nil { return } if _, ok := i.(endOfArray); ok { return } *v = append(*v, i) } } // WriteTo writes the Array to the writer. func (v Array) WriteTo(w io.Writer) (n int64, err error) { { for _, value := range v { var m int m, err = write(w, value) n += int64(m) if err != nil { return } } } { var m int m, err = w.Write([]byte{byte(TypeEndOfArray)}) n += int64(m) if err != nil { return } } return } type endOfArray struct{} func (endOfArray) XLPPType() Type { return TypeEndOfArray } func (endOfArray) String() string { return "<end of array>" } func (endOfArray) ReadFrom(r io.Reader) (n int64, err error) { return 0, nil } func (endOfArray) WriteTo(w io.Writer) (n int64, err error) { return 0, nil } //////////////////////////////////////////////////////////////////////////////// // A Delay is not a Value, but a marker in XLPP data that puts values in a historical context. // All subsequent values have been measured at this Delay in the past. // You can use multiple Delays in one XLPP message, in which they will increment the total Delay. type Delay time.Duration // XLPPType for Delay returns 255. func (v Delay) XLPPType() Type { return 255 } // XLPPChannel for Delay returns the constant ChanDelay 253. func (v Delay) XLPPChannel() int { return ChanDelay } func (v Delay) String() string { return time.Duration(v).String() } func (v Delay) Hours() int { return int(time.Duration(v).Hours()) } func (v Delay) Minutes() int { return int(time.Duration(v).Minutes()) % 60 } func (v Delay) Seconds() int { return int(time.Duration(v).Seconds()) % 60 } // ReadFrom reads the Delay from the reader. func (v *Delay) ReadFrom(r io.Reader) (n int64, err error) { var b [3]byte n, err = readFrom(r, b[:]) *v = Delay(time.Hour)*Delay(b[0]) + Delay(time.Minute)*Delay(b[1]) + Delay(time.Second)*Delay(b[2]) return } // WriteTo writes the Delay to the writer. func (v Delay) WriteTo(w io.Writer) (n int64, err error) { m, err := w.Write([]byte{byte(v.Hours()), byte(v.Minutes()), byte(v.Seconds())}) return int64(m), err } //////////////////////////////////////////////////////////////////////////////// type Actuators []Type // XLPPType for Actuators returns 255. func (v Actuators) XLPPType() Type { return 255 } // XLPPChannel for Actuators returns the constant ChanActuators 252. func (v Actuators) XLPPChannel() int { return ChanActuators } func (v Actuators) String() string { var b strings.Builder b.WriteByte('[') first := true for _, t := range v { if !first { b.WriteByte(',') b.WriteByte(' ') } first = false fmt.Fprintf(&b, "0x%02X", int(t)) } b.WriteByte(']') return b.String() } // ReadFrom reads the Actuators from the reader. func (v *Actuators) ReadFrom(r io.Reader) (n int64, err error) { var b [1]byte n, err = readFrom(r, b[:]) if err != nil { return } var m int64 l := int(b[0]) *v = make(Actuators, l) for i := 0; i < l; i++ { m, err = readFrom(r, b[:]) if err != nil { return } n += m (*v)[i] = Type(b[0]) } return } // WriteTo writes the Actuators to the writer. func (v Actuators) WriteTo(w io.Writer) (n int64, err error) { d := make([]byte, len(v)+1) d[0] = byte(len(v)) for i, a := range v { d[i+1] = byte(a) } m, err := w.Write(d) return int64(m), err } //////////////////////////////////////////////////////////////////////////////// type Actuator struct { Channel int Type Type } type ActuatorsWithChannel []Actuator // XLPPType for ActuatorsWithChannel returns 255. func (v ActuatorsWithChannel) XLPPType() Type { return 255 } // ActuatorsWithChannel for Actuators returns the constant ChanActuators 251. func (v ActuatorsWithChannel) XLPPChannel() int { return ChanActuatorsWithChannel } func (v ActuatorsWithChannel) String() string { var b strings.Builder b.WriteByte('[') first := true for _, t := range v { if !first { b.WriteByte(',') b.WriteByte(' ') } first = false fmt.Fprintf(&b, "Chan %d: 0x%02X", int(t.Channel), int(t.Type)) } b.WriteByte(']') return b.String() } // ReadFrom reads the ActuatorsWithChannel from the reader. func (v *ActuatorsWithChannel) ReadFrom(r io.Reader) (n int64, err error) { var b [2]byte n, err = readFrom(r, b[:1]) if err != nil { return } var m int64 l := int(b[0]) *v = make(ActuatorsWithChannel, l) for i := 0; i < l; i++ { m, err = readFrom(r, b[:]) if err != nil { return } n += m (*v)[i] = Actuator{ Channel: int(b[0]), Type: Type(b[1]), } } return } // WriteTo writes the Actuators to the writer. func (v ActuatorsWithChannel) WriteTo(w io.Writer) (n int64, err error) { d := make([]byte, len(v)*2+1) d[0] = byte(len(v)) for i, a := range v { d[i*2+1] = byte(a.Channel) d[i*2+2] = byte(a.Type) } m, err := w.Write(d) return int64(m), err } //////////////////////////////////////////////////////////////////////////////// type byteReader struct { io.Reader } func newByteReader(r io.Reader) io.ByteReader { if br, ok := r.(io.ByteReader); ok { return br } return byteReader{Reader: r} } func (br byteReader) ReadByte() (byte, error) { var buf [1]byte _, err := br.Reader.Read(buf[:]) return buf[0], err } //////////////////// type byteReaderCounter struct { io.ByteReader Count int } func (br byteReaderCounter) ReadByte() (byte, error) { b, err := br.ByteReader.ReadByte() br.Count++ return b, err }
#!/bin/bash # Copyright 2020 Google LLC # # 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. # Find input files echo 'entries: { kind: INVERTER, name: "INV" input_names: "A" output_pin_list { pins { name: "ZN" function: "F" } } }' > "${TEST_TMPDIR}/fake_cell_library.textproto" echo 'module main(i, o); input i; output o; INV inv_0(.A(i), .ZN(o)); endmodule' > "${TEST_TMPDIR}/netlist.v" BINPATH=./xls/netlist/parse_netlist_main $BINPATH "${TEST_TMPDIR}/netlist.v" "${TEST_TMPDIR}/fake_cell_library.textproto" || exit -1 echo "PASS"
from django.db import models from fluent_contents.models import ContentItem class GistItem(ContentItem): contentitem_ptr = models.OneToOneField( ContentItem, parent_link=True, auto_created=True, primary_key=True, serialize=False, verbose_name='Content Item' ) gist_id = models.CharField( max_length=128, verbose_name='Gist number', help_text='Go to <a href="https://gist.github.com/" target="_blank">https://gist.github.com/</a> and copy the number of the Gist snippet you want to display.' ) filename = models.CharField( max_length=128, verbose_name='Gist filename', help_text='Leave the filename empty to display all files in the Gist.', blank=True ) class Meta: db_table = 'contentitem_gist_gistitem' verbose_name = 'GitHub Gist snippet' verbose_name_plural = 'GitHub Gist snippets'
SELECT strftime('%Y', signup_date) AS year, COUNT(*) FROM users GROUP BY year ORDER BY year DESC;
import Joi from 'joi'; export type WebSocketMessageId = | 'error' | 'get:models' | 'set:models' | 'new:model' | 'get:channels' | 'set:channels' | 'get:presets' | 'apply:presets' | 'get:info' | 'prv:path' | 'prv:template' | 'val:model' | 'gen:template' | 'gen:channel'; const WebSocketMessageIds: WebSocketMessageId[] = [ 'get:models', 'set:models', 'new:model', 'get:channels', 'set:channels', 'get:presets', 'apply:presets', 'get:info', 'prv:path', 'prv:template', 'val:model', 'gen:template', 'gen:channel', ]; export interface WebSocketMessage<T> { id: WebSocketMessageId; type?: string; tag?: string; data: T; } export const WebSocketMessageSchema = Joi.object({ id: Joi.string() .valid(...WebSocketMessageIds) .required(), type: Joi.string().valid('error', 'success'), tag: Joi.string(), data: Joi.any(), }); export interface IWebSocketHandler<I, O> { /** Denotes if the handler can handle this message */ canHandle(message: WebSocketMessage<I>): boolean; /** * Handle message. * Returns data if necessary, null otherwise */ handle(message: WebSocketMessage<I>): Promise<O>; /** Returns the JOi validator for the input payload */ validator(): Joi.Schema; }
import { e2eDatabaseTypeSetUp, e2eSetUp } from "testing"; import { BaseEntity, Column, Entity, getConnection, PrimaryGeneratedColumn } from "typeorm"; import { JsonTransformer } from "./json"; e2eDatabaseTypeSetUp("JsonTransformer", (options) => { class TestJson { public name!: string; } @Entity() class JsonTransformerTest extends BaseEntity { @PrimaryGeneratedColumn() public id!: number; @Column({ nullable: true, transformer: new JsonTransformer<TestJson>({ name: "test" }), type: "varchar", width: 255, }) public data!: TestJson; } @Entity() class NoDefaultValueTest extends BaseEntity { @PrimaryGeneratedColumn() public id!: number; @Column({ nullable: true, transformer: new JsonTransformer(), type: "varchar", width: 255, }) public data!: TestJson; } e2eSetUp({ entities: [JsonTransformerTest, NoDefaultValueTest], ...options }); it("should return undefined", async () => { const test = await NoDefaultValueTest.create({}).save(); expect(await NoDefaultValueTest.findOne(test.id)).toEqual({ data: undefined, id: 1, }); }); it("should return defaultValue", async () => { const test = await JsonTransformerTest.create().save(); expect(await JsonTransformerTest.findOne(test.id)).toEqual({ data: { name: "test", }, id: test.id, }); const rawQuery = await getConnection() .createQueryBuilder(JsonTransformerTest, "entity") .whereInIds(test.id) .getRawOne(); expect(rawQuery).toEqual({ entity_data: JSON.stringify({ name: "test" }), entity_id: 1, }); }); it("should return defaultValue", async () => { await JsonTransformerTest.create({ data: "{" as any, }).save(); expect(await JsonTransformerTest.findOne(1)).toEqual({ data: { name: "test", }, id: 1, }); }); });
public class SumEvenNumbers { public static int calculateSum(int start, int end) { int sum = 0; for (int i = start; i <= end; i++) { if (i % 2 == 0) { sum += i; } } return sum; } }
<filename>src/model/HeatPumpWaterToWaterEquationFitCooling.hpp /*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #ifndef MODEL_HEATPUMPWATERTOWATEREQUATIONFITCOOLING_HPP #define MODEL_HEATPUMPWATERTOWATEREQUATIONFITCOOLING_HPP #include "ModelAPI.hpp" #include "WaterToWaterComponent.hpp" #include "../utilities/core/Deprecated.hpp" namespace openstudio { namespace model { class HeatPumpWaterToWaterEquationFitHeating; class CurveQuadLinear; namespace detail { class HeatPumpWaterToWaterEquationFitCooling_Impl; } // namespace detail /** HeatPumpWaterToWaterEquationFitCooling is a WaterToWaterComponent that wraps the OpenStudio IDD object 'OS:HeatPump:WaterToWater:EquationFit:Cooling'. */ class MODEL_API HeatPumpWaterToWaterEquationFitCooling : public WaterToWaterComponent { public: /** @name Constructors and Destructors */ //@{ explicit HeatPumpWaterToWaterEquationFitCooling(const Model& model, const CurveQuadLinear& coolingCapacityCurve, const CurveQuadLinear& coolingCompressorPowerCurve); explicit HeatPumpWaterToWaterEquationFitCooling(const Model& model); virtual ~HeatPumpWaterToWaterEquationFitCooling() {} //@} static IddObjectType iddObjectType(); /** @name Getters */ //@{ boost::optional<double> referenceLoadSideFlowRate() const; /** Prior to EnergyPlus 8.7.0 this field was not autosizeable. To preserve backwards compatibility this method will return -999.0 in autosized models.**/ double ratedLoadSideFlowRate() const; bool isReferenceLoadSideFlowRateAutosized() const; boost::optional<double> referenceSourceSideFlowRate() const; /** Prior to EnergyPlus 8.7.0 this field was not autosizeable. To preserve backwards compatibility this method will return -999.0 in autosized models.**/ double ratedSourceSideFlowRate() const; bool isReferenceSourceSideFlowRateAutosized() const; /** In EnergyPlus 8.7.0 and above this field maps to the EnergyPlus field named "Reference Cooling Capacity" **/ boost::optional<double> ratedCoolingCapacity() const; bool isRatedCoolingCapacityAutosized() const; /** In EnergyPlus 8.7.0 and above this field maps to the EnergyPlus field named "Reference Cooling Power Consumption" **/ boost::optional<double> ratedCoolingPowerConsumption() const; bool isRatedCoolingPowerConsumptionAutosized() const; CurveQuadLinear coolingCapacityCurve() const; OS_DEPRECATED double coolingCapacityCoefficient1() const; OS_DEPRECATED double coolingCapacityCoefficient2() const; OS_DEPRECATED double coolingCapacityCoefficient3() const; OS_DEPRECATED double coolingCapacityCoefficient4() const; OS_DEPRECATED double coolingCapacityCoefficient5() const; CurveQuadLinear coolingCompressorPowerCurve() const; OS_DEPRECATED double coolingCompressorPowerCoefficient1() const; OS_DEPRECATED double coolingCompressorPowerCoefficient2() const; OS_DEPRECATED double coolingCompressorPowerCoefficient3() const; OS_DEPRECATED double coolingCompressorPowerCoefficient4() const; OS_DEPRECATED double coolingCompressorPowerCoefficient5() const; double referenceCoefficientofPerformance() const; double sizingFactor() const; boost::optional<HeatPumpWaterToWaterEquationFitHeating> companionHeatingHeatPump() const; //@} /** @name Setters */ //@{ bool setReferenceLoadSideFlowRate(double referenceLoadSideFlowRate); /** Synonym of setReferenceLoadSideFlowRate for backwards compatibility **/ bool setRatedLoadSideFlowRate(double ratedLoadSideFlowRate); void autosizeReferenceLoadSideFlowRate(); bool setReferenceSourceSideFlowRate(double referenceSourceSideFlowRate); /** Synonym of setReferenceLoadSideFlowRate for backwards compatibility **/ bool setRatedSourceSideFlowRate(double ratedSourceSideFlowRate); void autosizeReferenceSourceSideFlowRate(); /** In EnergyPlus 8.7.0 and above this field maps to the EnergyPlus field named "Reference Cooling Capacity" **/ bool setRatedCoolingCapacity(double ratedCoolingCapacity); void autosizeRatedCoolingCapacity(); /** In EnergyPlus 8.7.0 and above this field maps to the EnergyPlus field named "Reference Cooling Power Consumption" **/ bool setRatedCoolingPowerConsumption(double ratedCoolingPowerConsumption); void autosizeRatedCoolingPowerConsumption(); bool setCoolingCapacityCurve(const CurveQuadLinear& coolingCapacityCurve); OS_DEPRECATED bool setCoolingCapacityCoefficient1(double coolingCapacityCoefficient1); OS_DEPRECATED bool setCoolingCapacityCoefficient2(double coolingCapacityCoefficient2); OS_DEPRECATED bool setCoolingCapacityCoefficient3(double coolingCapacityCoefficient3); OS_DEPRECATED bool setCoolingCapacityCoefficient4(double coolingCapacityCoefficient4); OS_DEPRECATED bool setCoolingCapacityCoefficient5(double coolingCapacityCoefficient5); bool setCoolingCompressorPowerCurve(const CurveQuadLinear& coolingCompressorPowerCurve); OS_DEPRECATED bool setCoolingCompressorPowerCoefficient1(double coolingCompressorPowerCoefficient1); OS_DEPRECATED bool setCoolingCompressorPowerCoefficient2(double coolingCompressorPowerCoefficient2); OS_DEPRECATED bool setCoolingCompressorPowerCoefficient3(double coolingCompressorPowerCoefficient3); OS_DEPRECATED bool setCoolingCompressorPowerCoefficient4(double coolingCompressorPowerCoefficient4); OS_DEPRECATED bool setCoolingCompressorPowerCoefficient5(double coolingCompressorPowerCoefficient5); bool setReferenceCoefficientofPerformance(double referenceCoefficientofPerformance); bool setSizingFactor(double sizingFactor); bool setCompanionHeatingHeatPump(const HeatPumpWaterToWaterEquationFitHeating& companionHP); //@} /** @name Other */ //@{ boost::optional<double> autosizedReferenceLoadSideFlowRate() const; boost::optional<double> autosizedReferenceSourceSideFlowRate() const; boost::optional<double> autosizedRatedCoolingCapacity() const; boost::optional<double> autosizedRatedCoolingPowerConsumption() const; //@} protected: /// @cond typedef detail::HeatPumpWaterToWaterEquationFitCooling_Impl ImplType; explicit HeatPumpWaterToWaterEquationFitCooling(std::shared_ptr<detail::HeatPumpWaterToWaterEquationFitCooling_Impl> impl); friend class detail::HeatPumpWaterToWaterEquationFitCooling_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.HeatPumpWaterToWaterEquationFitCooling"); }; /** \relates HeatPumpWaterToWaterEquationFitCooling*/ typedef boost::optional<HeatPumpWaterToWaterEquationFitCooling> OptionalHeatPumpWaterToWaterEquationFitCooling; /** \relates HeatPumpWaterToWaterEquationFitCooling*/ typedef std::vector<HeatPumpWaterToWaterEquationFitCooling> HeatPumpWaterToWaterEquationFitCoolingVector; } // namespace model } // namespace openstudio #endif // MODEL_HEATPUMPWATERTOWATEREQUATIONFITCOOLING_HPP
package com.cannolicatfish.rankine.world.gen; import com.cannolicatfish.rankine.init.RankineFeatures; import com.cannolicatfish.rankine.init.WGConfig; import com.cannolicatfish.rankine.util.WorldgenUtils; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.Biome; import net.minecraft.world.gen.GenerationStage; import net.minecraft.world.gen.feature.*; import net.minecraftforge.event.world.BiomeLoadingEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import java.util.*; @Mod.EventBusSubscriber public class DecorationGen { private static List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> getTopLayerFeatures() { List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> TopLayer = new ArrayList<>(); new AbstractMap.SimpleEntry<>(RankineFeatures.SNOW_GEN, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.EXTREME_HILLS), true)); return TopLayer; } private static List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> getLocalModificationFeatures() { List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> LocalModifications = new ArrayList<>(); if (WGConfig.MISC.METEORITE_GEN.get()) { LocalModifications.add(new AbstractMap.SimpleEntry<>(RankineFeatures.METEORITE, WorldgenUtils.getBiomeNamesFromCategory(Collections.emptyList(), false))); } return LocalModifications; } private static List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> getVegetalDecorationFeatures() { if (WGConfig.MISC.RANKINE_FAUNA.get()) { return Arrays.asList( new AbstractMap.SimpleEntry<>(RankineFeatures.ELDERBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.FOREST, Biome.Category.PLAINS),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.POKEBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.FOREST, Biome.Category.TAIGA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.SNOWBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.EXTREME_HILLS, Biome.Category.ICY),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLUEBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.RIVER, Biome.Category.PLAINS),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.RASPBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.FOREST),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLACKBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.FOREST),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.CRANBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.SWAMP),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.STRAWBERRY_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.PLAINS),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.PINEAPPLE_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.JUNGLE),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BANANA_YUCCA_BUSH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.SAVANNA, Biome.Category.DESERT, Biome.Category.MESA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.ALOE_PLANT,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.SAVANNA, Biome.Category.DESERT, Biome.Category.MESA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.GOLDENROD_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.SAVANNA, Biome.Category.DESERT, Biome.Category.MESA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.RED_LILY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.SAVANNA, Biome.Category.DESERT, Biome.Category.MESA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.WHITE_LILY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.EXTREME_HILLS),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.ORANGE_LILY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.PLAINS),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLACK_MORNING_GLORY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.JUNGLE),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLUE_MORNING_GLORY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.JUNGLE),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.PURPLE_MORNING_GLORY_PATCH,WorldgenUtils.getBiomeNamesFromCategory(Arrays.asList(Biome.Category.TAIGA),true)), new AbstractMap.SimpleEntry<>(RankineFeatures.YELLOW_BIRCH_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.FOREST), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLACK_BIRCH_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.FOREST), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.EASTERN_HEMLOCK_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.TAIGA), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.CEDAR_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.TAIGA), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.COCONUT_PALM_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.BEACH), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.PINYON_PINE_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.SAVANNA), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BALSAM_FIR_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.SWAMP), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.DEAD_BALSAM_FIR_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.SWAMP), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.MAGNOLIA_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.RIVER), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.JUNIPER_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.SAVANNA), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.ERYTHRINA_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.MESA), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.MAPLE_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.PLAINS), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.BLACK_WALNUT_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.RIVER), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.CORK_OAK_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.MUSHROOM), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.SHARINGA_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.JUNGLE), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.CINNAMON_TREE, WorldgenUtils.getBiomeNamesFromCategory(Collections.singletonList(Biome.Category.JUNGLE), true)), new AbstractMap.SimpleEntry<>(RankineFeatures.SOIL_GEN, WorldgenUtils.getBiomeNamesFromCategory(Collections.emptyList(), false)) //new AbstractMap.SimpleEntry<>(RankineFeatures.ANIMAL_SPAWNER, WorldgenUtils.getBiomeNamesFromCategory(Collections.emptyList(), false)) ); } else { return Collections.emptyList(); } } @SubscribeEvent(priority = EventPriority.HIGH) public static void addBiomeFeatures(BiomeLoadingEvent event) { if (event.getName() != null) { List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> topLayerFeatures = getTopLayerFeatures(); for (AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>> entry : topLayerFeatures) { if (entry.getValue().contains(event.getName())) { event.getGeneration().withFeature(GenerationStage.Decoration.TOP_LAYER_MODIFICATION.ordinal(),entry::getKey); } } List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> localModificationFeatures = getLocalModificationFeatures(); for (AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>> entry : localModificationFeatures) { if (entry.getValue().contains(event.getName())) { event.getGeneration().withFeature(GenerationStage.Decoration.LOCAL_MODIFICATIONS.ordinal(),entry::getKey); } } List<AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>>> vegetalDecorationFeatures = getVegetalDecorationFeatures(); for (AbstractMap.SimpleEntry<ConfiguredFeature<?,?>,List<ResourceLocation>> entry : vegetalDecorationFeatures) { if (entry.getValue().contains(event.getName())) { event.getGeneration().withFeature(GenerationStage.Decoration.VEGETAL_DECORATION.ordinal(), entry::getKey); } } } } }
<reponame>vadi2/codeql public class NoMutualDependency { // Better: A new interface breaks the dependency // from the model to the view private interface ModelListener { void modelChanged(); } private static class BetterModel { private int i; private ModelListener listener; public int getI() { return i; } public void setI(int i) { this.i = i; if (listener != null) listener.modelChanged(); } public void setListener(ModelListener listener) { this.listener = listener; } } private static class BetterView implements ModelListener { private BetterModel model; public BetterView(BetterModel model) { this.model = model; } public void modelChanged() { System.out.println("Model Changed: " + model.getI()); } } public static void main(String[] args) { BadModel badModel = new BadModel(); BadView badView = new BadView(badModel); badModel.setView(badView); badModel.setI(23); badModel.setI(9); BetterModel betterModel = new BetterModel(); BetterView betterView = new BetterView(betterModel); betterModel.setListener(betterView); betterModel.setI(24); betterModel.setI(12); } }
import os def count_image_files(rootDir): image_extensions = (".jpg", ".png", ".gif", ".bmp") image_count = 0 for dirpath, _, filenames in os.walk(rootDir): for filename in filenames: if filename.lower().endswith(image_extensions): image_count += 1 return image_count
import java.util.ArrayList; import java.util.List; public class ContactManager { private List<ContactDetail> contactDetails; public ContactManager() { this.contactDetails = new ArrayList<>(); } public void addContactDetail(String name, String phoneNumber, String emailAddress) { ContactDetail newContact = new ContactDetail(name, phoneNumber, emailAddress); contactDetails.add(newContact); } public int getContactDetailCount() { return contactDetails.size(); } private static class ContactDetail { private String name; private String phoneNumber; private String emailAddress; public ContactDetail(String name, String phoneNumber, String emailAddress) { this.name = name; this.phoneNumber = phoneNumber; this.emailAddress = emailAddress; } } }
<gh_stars>1-10 module( "Pagecontainer" ); asyncTest( "hides loader and clears transition lock when page load fails", function() { expect( 3 ); $( document ).on( "pagecontainerloadfailed", function( event ) { // Prevent error message shown by default event.preventDefault(); setTimeout( function() { deepEqual( $.mobile.loading().is( ":visible" ), false, "Loader is hidden" ); $.testHelper.pageSequence([ function() { $( "#go-to-other-page" ).click(); }, function() { deepEqual( $.mobile.pageContainer.pagecontainer( "getActivePage" ) .attr( "id" ), "other-page", "The other page is the active page" ); $.mobile.back(); }, function() { deepEqual( $.mobile.pageContainer.pagecontainer( "getActivePage" ) .attr( "id" ), "start-page", "Returned to start page" ); start(); } ]); }, 500 ); }); $( "#go-to-nonexistent-page" ).click(); });
module.exports = { functions: require('./functions'), context: require('./context'), send: require('./send') };
<reponame>eSCT/oppfin package com.searchbox.core.search; public interface RetryElement { public boolean shouldRetry(); }
#!/usr/bin/env bash for x in $(ls /loadtest/gsim/schemas | perl -n -e'/(.*)\.json/ && print "$1 "'); do echo $x for a in 0 1 2 3 4 5 6 7 8 9 A B C D E F; do for b in 0 1 2 3 4 5 6 7 8 9 A B C D E F; do cat /loadtest/gsim/templates/$x.json | sed "s/#now/2018-10-16T12:01:21Z/" | sed "s/#mrid/${a}${b}C8D2B7-0EB3-4A6D-91BB-A7451649F2F6/" | curl -H "Content-Type: application/json" -X PUT -d @- http://lds:9090/ns/$x/${a}${b}C8D2B7-0EB3-4A6D-91BB-A7451649F2F6 >/dev/null 2>&1; done; done; done
<filename>src/main/scala/IPRepository/SEIDirectSyncRam/SEIDirectSyncRamRdFirst.scala package IPRepository.SEIDirectSyncRam import Interfaces.Immediate import chisel3._ import chisel3.util._ class SEIDirectSyncRamRdFirst(wrAddrWidth: Int, rdAddrWidth: Int, wrDataSize: Int, rdDataSize: Int) extends Module { private val RAM_WIDTH = wrDataSize * 8 private val RAM_DEPTH = Math.pow(2, rdAddrWidth).toInt private val RD_ADDR_WIDTH = rdAddrWidth private val RD_DATA_WIDTH = rdDataSize * 8 private val WR_ADDR_WIDTH = wrAddrWidth private val WR_DATA_WIDTH = wrDataSize * 8 private val WR_GROUP_COUNT = Math.pow(2, wrAddrWidth - rdAddrWidth).toInt val io = IO(new Bundle { val wr = new Bundle { val addr = Flipped(Immediate(UInt(WR_ADDR_WIDTH.W))) val data = Input(UInt(WR_DATA_WIDTH.W)) } val rd = new Bundle { val addr = Flipped(Immediate(UInt(RD_ADDR_WIDTH.W))) val data = Input(UInt(RD_DATA_WIDTH.W)) } }) val mem = SyncReadMem(RAM_DEPTH, Vec(WR_GROUP_COUNT, UInt(WR_DATA_WIDTH.W))) val wrMask: Vec[Bool] = Wire(Vec(WR_GROUP_COUNT, Bool())) val wrData: Vec[UInt] = Wire(Vec(WR_GROUP_COUNT, UInt(WR_DATA_WIDTH.W))) val rdData: Vec[UInt] = Wire(Vec(WR_GROUP_COUNT, UInt(WR_DATA_WIDTH.W))) val wrAddrHi: UInt = io.wr.addr.bits(wrAddrWidth - 1, wrAddrWidth - rdAddrWidth) val wrAddrLo: UInt = io.wr.addr.bits(wrAddrWidth - rdAddrWidth - 1, 0) for(i <- 0 until WR_GROUP_COUNT) { wrData(i) := io.wr.data wrMask(i) := 0.U } wrMask(wrAddrLo) := io.wr.addr.valid mem.write(wrAddrHi, wrData, wrMask) rdData := mem.read(io.rd.addr.bits, io.rd.addr.valid) io.rd.data := Cat(rdData.reverse) }
<gh_stars>1-10 package com.wpisen.trace.test.web.control; import com.alibaba.fastjson.JSONArray; import com.wpisen.trace.test.web.bean.User; import com.wpisen.trace.test.web.service.UserService; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Administrator on 2018/5/30. */ @WebServlet("/user") public class UserServlet extends HttpServlet { private WebApplicationContext context; private UserService userService; @Override public void init() throws ServletException { super.init(); context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); userService = context.getBean(UserService.class); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.getWriter().println("hello tuling trace .this is test page"); String name = request.getParameter("name"); String id = request.getParameter("id"); User user = userService.getUser(id, name); String result = JSONArray.toJSONString(user); response.getWriter().println(result); // request.getRequestDispatcher("/index.html").forward(request, response); response.getWriter().println("end-----"); } }
#!/bin/bash echo Indexing database please wait sudo -u postgres psql -d arweave <<EOF SET statement_timeout to 0; SET maintenance_work_mem TO '8GB'; SET max_parallel_maintenance_workers TO 16; COMMIT; SHOW statement_timeout; SHOW maintenance_work_mem; SHOW max_parallel_maintenance_workers; --- Block Indices --- Block Height Index CREATE INDEX "blocks_height" ON blocks USING BTREE ("height"); --- Blocks Mined At Index CREATE INDEX "blocks_mined_at" ON blocks USING BTREE ("mined_at"); --- Transaction Indices --- Transaction Height Index CREATE INDEX "transactions_height" ON transactions USING BTREE ("height"); --- Transaction Target Index CREATE INDEX "transactions_target" ON transactions USING BTREE ("target"); --- Transaction Owner Address Index CREATE INDEX "transactions_owner_address" ON transactions USING BTREE ("owner_address"); --- Transaction Namespace Index CREATE INDEX "index_namespace_transactions" ON transactions USING BTREE ("namespace"); --- Transaction Domain Index CREATE INDEX "index_domain_transactions" ON transactions USING BTREE ("domain"); --- Transaction App Index CREATE INDEX "index_app_transactions" ON transactions USING BTREE ("app"); --- Transaction App-Name Index CREATE INDEX "index_App-Name_transactions" ON transactions USING BTREE ("App-Name"); --- Transactions created_at index CREATE INDEX "transactions_created_at" ON transactions USING BTREE ("created_at"); --- Tag Indices --- Tag Transaction Id Index CREATE INDEX "tags_tx_id" ON tags USING BTREE ("tx_id"); --- Tag Name Index (under 64 characters) CREATE INDEX "tags_name" ON tags USING BTREE ("name") WHERE LENGTH("name") < 64; --- Tag Value Index (under 64 characters) CREATE INDEX "tags_value" ON tags USING BTREE ("value") WHERE LENGTH("value") < 64; --- Tag Name, Value Index (under 64 characters) CREATE INDEX "tags_name_value" ON tags USING BTREE ("name", "value") WHERE LENGTH("name") < 64 AND LENGTH("value") < 64; --- Tag Transaction Id, Name Index (under 64 characters) CREATE INDEX "tags_tx_id_name" ON tags USING BTREE ("tx_id", "name") WHERE LENGTH("name") < 64; --- Tag Name Index (under 128 chracters) CREATE INDEX "tags_name_128" ON tags USING BTREE ("name") WHERE LENGTH("name") > 64 AND LENGTH("name") < 128; --- Tag Value Index (under 128 chracters) CREATE INDEX "tags_value_128" ON tags USING BTREE ("value") WHERE LENGTH("value") > 64 AND LENGTH("value") < 128; --- Tag Name, Value Index (under 128 chracters) CREATE INDEX "tags_name_value_128" ON tags USING BTREE ("name", "value") WHERE LENGTH("name") > 64 AND LENGTH("name") < 128 AND LENGTH("value") > 64 AND LENGTH("value") < 128; --- Tag Transaction Id, Name Index (under 128 chracters) CREATE INDEX "tags_tx_id_name_128" ON tags USING BTREE ("tx_id", "name") WHERE LENGTH("name") > 64 AND LENGTH("name") < 128; --- Tag created_at CREATE INDEX "tags_created_at" ON tags USING BTREE ("created_at"); CREATE INDEX "tags_created_at_64" ON tags USING BTREE ("created_at") WHERE LENGTH("value") < 64; CREATE INDEX "tags_created_at_128" ON tags USING BTREE ("created_at") WHERE LENGTH("value") < 128; EOF echo Finished indexing database
#!/bin/bash docker build -t mekstrike-library -f library/Dockerfile . docker build -t mekstrike-importer -f library/importer/Dockerfile . docker build -t mekstrike-gamemaster -f gamemaster/Dockerfile . docker build -t mekstrike-armybuilder -f armybuilder/Dockerfile .
/* * * Copyright 2017 Asylo authors * * 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. * */ #include <signal.h> #include <pthread.h> #include <cstdlib> #include "absl/synchronization/mutex.h" #include "asylo/platform/arch/include/trusted/host_calls.h" #include "asylo/platform/arch/include/trusted/register_signal.h" #include "asylo/platform/core/trusted_global_state.h" #include "asylo/platform/posix/signal/signal_manager.h" extern "C" { // Registers a signal handler for |signum|. // // This method registers a signal handler in two parts: // * On the host-side, registers a signal-handling function that calls into the // enclave to handle the signal. // * Inside the enclave, registers the user-provided function |act| as the // actual signal handler. // // When a signal is subsequently invoked on the host, it will first be passed to // the host-side signal handler. The host-side signal handler will then enter // enclave to invoke the corresponding signal handler registered inside the // enclave. // Note that the behavior described above applies if either the enclave is run // in hardware mode, or it is run in simulation mode and the TCS is inactive. If // the enclave is run in simulation mode and TCS is active (i.e. a thread is // running inside the enclave), then this function will call the signal handler // registered inside the enclave directly. int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { if (signum == SIGILL) { errno = EINVAL; return -1; } asylo::SignalManager *signal_manager = asylo::SignalManager::GetInstance(); // Guards sigaction calls. This is to ensure that signal handlers are not // overwritten between the time sigaction gets |oldact| and sets |act|. static absl::Mutex sigaction_lock; { absl::MutexLock lock(&sigaction_lock); if (oldact) { if (signal_manager->GetSigAction(signum)) { oldact = const_cast<struct sigaction *>( signal_manager->GetSigAction(signum)); } else { oldact->sa_handler = SIG_DFL; } } signal_manager->SetSigAction(signum, *act); } sigset_t mask; sigemptyset(&mask); int flags = 0; if (act) { mask = act->sa_mask; flags = act->sa_flags; } if (flags & SA_RESETHAND) { signal_manager->SetResetOnHandle(signum); } const std::string enclave_name = asylo::GetEnclaveName(); // Pass a C string because enc_register_signal has C linkage. This string is // copied to untrusted memory when going across enclave boundary. return enc_register_signal(signum, mask, flags, enclave_name.c_str()); } // Sets the signal mask with |set|. // // This method sets the signal mask both inside the enclave and on the host. // If |how| is SIG_UNBLOCK, the signals to unblock are unblocked inside the // enclave first, then on the host. // If |how| is SIG_BLOCK, the signals to block are blocked on the host first, // then inside the enclave. // If |how| is SIG_SETMASK, |set| is separated to signals to block and to // unblock. The signals to unblock are processed inside the enclave first, then // on the host, and the signals to block are processed on the host first, then // inside the enclave. // |oldset| is set to the signal mask used inside the enclave prior to this // call. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset) { if (how != SIG_BLOCK && how != SIG_UNBLOCK && how != SIG_SETMASK) { errno = EINVAL; return -1; } asylo::SignalManager *signal_manager = asylo::SignalManager::GetInstance(); if (oldset) { *oldset = signal_manager->GetSignalMask(); } if (!set) { return 0; } sigset_t signals_to_block; sigemptyset(&signals_to_block); sigset_t signals_to_unblock; sigemptyset(&signals_to_unblock); if (how == SIG_BLOCK || how == SIG_SETMASK) { signals_to_block = *set; } if (how == SIG_UNBLOCK) { signals_to_unblock = *set; } else if (how == SIG_SETMASK) { signals_to_unblock = signal_manager->GetUnblockedSet(*set); } // Unblock signals inside the enclave before unblocking signals on the host. signal_manager->UnblockSignals(signals_to_unblock); // |oldset| is already filled with the signal mask inside the enclave. int res = enc_untrusted_sigprocmask(how, set, /*oldset=*/nullptr); // Block signals inside the enclave after the host. signal_manager->BlockSignals(signals_to_block); return res; } int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset) { return sigprocmask(how, set, oldset); } // Registers a signal handler for |signum| with |handler|. // // This method is a special case of sigaction. It calls sigaction with only // sa_handler in |act| field set. sighandler_t signal(int signum, sighandler_t handler) { struct sigaction act; act.sa_handler = handler; sigemptyset(&act.sa_mask); struct sigaction oldact; if (sigaction(signum, &act, &oldact)) { // Errno is set by sigaction. return SIG_ERR; } return oldact.sa_handler; } // Raise a signal to be handled. // // If a signal is raised inside an enclave, it exits the enclave and raises the // signal on the host. If a handler has been registered for this signal in the // enclave, the signal handler on the host enters the enclave to invoke the // registered handler. int raise(int sig) { return enc_untrusted_raise(sig); } } // extern "C"
<reponame>AntoAndGar/PFP import scala.language.implicitConversions class MyList[T](l:List[T]) { def getDup = l.groupBy(identity).filter(p => p._2.size > 1).map(_._1).toSet } object E1 { implicit def listToMyList[T](l:List[T]) = new MyList(l) }
<filename>extern/glow-extras/pipeline/glow-extras/pipeline/stages/implementations/AOStage.hh #pragma once #include <array> #include <string> #include <glow/common/shared.hh> #include <glow/fwd.hh> #include "../../Settings.hh" #include "../../fwd.hh" #include "../RenderStage.hh" #include "AO/AOGlobalBuffer.hh" namespace glow { namespace pipeline { GLOW_SHARED(class, AOStage); class AOStage : public RenderStage { private: // == Render Targets == SharedTextureRectangle mTargetLinearDepth; SharedTexture2DArray mTargetViewDepthArray; SharedTexture2D mTargetNormals; SharedTexture2DArray mTargetAoArray; SharedTexture2D mTargetAOZ; SharedTexture2D mTargetAOZ2; SharedTextureRectangle mTargetAoFinal; // == FBOs == SharedFramebuffer mFboLinDepth; std::array<SharedFramebuffer, 2> mFbosViewDepthArray; SharedFramebuffer mFboNormalReconstruct; SharedFramebuffer mFboLayeredCoarseAo; SharedFramebuffer mFboAOZ1; SharedFramebuffer mFboAOZ2; // == UBOs == SharedUniformBuffer mUboAOGlobal; detail::AOGlobalBuffer mBufferAOGlobal; std::array<SharedUniformBuffer, 16> mUbosAOPerPass; // == Shaders == SharedProgram mShaderLinearizeDepth; SharedProgram mShaderDeinterleavedDepth; SharedProgram mShaderReconstructNormals; SharedProgram mShaderCoarseAO; SharedProgram mShaderReinterleavedAO; SharedProgram mShaderBlurX; SharedProgram mShaderBlurY; // == Dependencies == SharedDepthPreStage mStageDepthPre; // == Samplers == SharedSampler mSamplerLinear; SharedSampler mSamplerNearest; protected: /// Called when the stage is supposed to run void onExecuteStage(RenderContext const& ctx, RenderCallback& rc) override; /// Called when a new frame begins void onBeginNewFrame(RenderPipeline& pipeline) override; public: AOStage(SharedDepthPreStage const& depthPreStage); SharedTextureRectangle const& getTargetAO() const { return mTargetAoFinal; } GLOW_GETTER(TargetLinearDepth); GLOW_GETTER(TargetNormals); StageType getType() const override { return StageType::Internal; } std::string name() const override { return "Ambient Occlusion"; } }; } }
<filename>src/backend/buildurl.ts export function buildUrl(name: string, params = {}) { function replaceParamsInUrl(template: string, values: { [key: string]: string }) { return template.replace(/\:(.*?)(\/|$)/g, (_, name, delimiter) => { return ((name in values) ? encodeURIComponent(values[name]) : '') + delimiter; }); } switch (name) { case 'home': return '/'; case 'notebook': return replaceParamsInUrl('/notebook/:name', params); case 'notebooknew': return '/api/notebook/new'; case 'notebooksetcontent': return replaceParamsInUrl('/api/notebook/:name/setcontent', params); case 'notebookexec': return replaceParamsInUrl('/api/notebook/:name/exec', params); case 'notebookstop': return replaceParamsInUrl('/api/notebook/:name/stop', params); case 'notebookrename': return replaceParamsInUrl('/api/notebook/:name/rename', params); } return undefined; }
#ifndef __JSONHELPER_H__ #define __JSONHELPER_H__ #include "jsoncpp/json/json.h" #include "MathGeoLib/include/MathGeoLib.h" class JsonHelper { public: JsonHelper() {}; void Fill(Json::Value&, const float3&) const; void Fill(float3&, const Json::Value&) const; }; #endif // !__JSONHELPER_H__
import React, { useState } from 'react'; import { createStore, persist } from 'easy-peasy'; import { createStoreModel } from 'hox'; const storeModel = { users: { items: [], add: (state, { payload }) => state.items.push(payload), remove: (state, { payload }) => state.items.filter(item => item !== payload) } }; const store = createStore(storeModel, { middleware: [persist()] }); function UserProfile({ username, email }) { const [edit, setEdit] = useState(false); const handleEdit = () => { setEdit(!edit); } return ( <div> <h1>{username}</h1> <p>{email}</p> <button onClick={handleEdit}>{edit ? 'Save' : 'Edit'}</button> </div> ); } export default createStoreModel(store, { component: UserProfile });
#!/bin/sh set -e apk update apk add build-base autoconf git automake libtool git clone --branch jq-1.6 https://github.com/stedolan/jq /tmp/jq WD=$(pwd) cd /tmp/jq git submodule update --init autoreconf -fi ./configure --with-oniguruma=builtin --disable-maintainer-mode make LDFLAGS=-all-static make install ldconfig || true cd $WD go build -o dist/alpine/docker-purge
#!/bin/sh main(){ echo $# } main # -> 0 main a # -> 1 main a b # -> 2
<reponame>kyokan/fnd package primitives import ( "errors" "fnd.localhost/handshake/encoding" "golang.org/x/crypto/blake2b" ) func HashName(name string) []byte { h, _ := blake2b.New256(nil) h.Write([]byte(name)) return h.Sum(nil) } func CreateBlind(value uint64, nonce []byte) ([]byte, error) { if len(nonce) != 32 { return nil, errors.New("nonce must be 32 bytes long") } h, _ := blake2b.New256(nil) _ = encoding.WriteUint64(h, value) h.Write(nonce) return h.Sum(nil), nil } const ( MaxNameLen = 63 ) var validCharset = []byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 4, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, } var blacklist = map[string]bool{ "example": true, "invalid": true, "local": true, "localhost": true, "test": true, } func ValidateName(name string) error { if len(name) == 0 { return errors.New("name must have nonzero length") } if len(name) > MaxNameLen { return errors.New("name over maximum length") } for i := 0; i < len(name); i++ { ch := name[i] if int(ch) > len(validCharset) { return errors.New("invalid character") } charType := validCharset[ch] switch charType { case 0: return errors.New("invalid character") case 1: continue case 2: return errors.New("name cannot contain capital letters") case 3: continue case 4: if i == 0 { return errors.New("name cannot start with a hyphen") } if i == len(name)-1 { return errors.New("name cannot end with a hyphen") } } } if blacklist[name] { return errors.New("name is blacklisted") } return nil }
# # COLORS RESET="\[\033[0;37m\]" RESET_STR=$(tput sgr0) CLEAR="\[${RESET_STR}\]" #ExtendedChars LEFT_CORNER="$(printf "\xe2\x95\xb0")" LEFT_SIDE="${LEFT_CORNER}" export COLORA="" export COLORB="" export COLORC="" export COLORD="" # Count some colors, make sure the val is initialized if [ -z $COLORINDEX ]; then export COLORINDEX=0 fi # Called at the beginning of `prompt_command` to cycle colors # `tput setaf <int>` returns a color string for 0-255 # `expr` does math in the shell! function getColor() { if [ $COLORINDEX -gt 252 ]; then COLORINDEX=0 fi COLORA=$(tput setaf ${COLORINDEX}) COLORB=$(tput setaf $(expr ${COLORINDEX} + 1)) COLORC=$(tput setaf $(expr ${COLORINDEX} + 2)) COLORD=$(tput setaf $(expr ${COLORINDEX} + 3)) COLORINDEX=$(expr ${COLORINDEX} + 4) return } # Set env vars for helper PS1s export GIT_PS1_SHOWCOLORHINTS=true export GIT_PS1_SHOWDIRTYSTATE=true export VIRTUAL_ENV_DISABLE_PROMPT=1 function venv() { venv="" if [[ -n "$VIRTUAL_ENV" ]]; then venv="[${VIRTUAL_ENV##*/}]" echo "${venv} " return fi } # Call venv() to see if there is a valid virtual env, and return the string VENV="\$(venv)" # Call getColor to cycle colors # call __git_ps1 with three arguments: # - Left side of prompt # - Right side of prompt # - printf formatted string that is returned by git_ps1 # # Displays, in order: # - Python VirtualEnv if enabled for the terminal session # - docker-machine configured machine for the terminal session export PROMPT_COMMAND='getColor; __git_ps1 "${LEFT_SIDE}\[${COLORA}\]${VENV}${DOCKER_MACHINE_NAME:+▷}${DOCKER_MACHINE_NAME}${DOCKER_MACHINE_NAME:+◁ }${CLEAR}\[${COLORB}\]($(date +%H:%M))${CLEAR} " "\[${COLORC}\]\W/\[${COLORD}\]> ${CLEAR}${CLEAR}" "${LEFT_CORNER}(%s) "' # Original source for these companion scripts: # - https://github.com/git/git/tree/master/contrib/completion # # If you're using a non-bash shell, explore the repo above. # This version of git-prompt.sh has some hacking in source "$HOME/scripts/git/git-prompt.sh" source "$HOME/scripts/git/git-completion.bash"
<gh_stars>0 "use strict"; const HTTPServer = require("./lib/HTTPServer"); const HTTPSServer = require("./lib/HTTPSServer"); const Session = require("./lib/router/Session"); const Static = require("./lib/router/Static"); const RequestLog = require("./lib/router/RequestLog"); const ServerError = require("./lib/router/ServerError"); const Upload = require("./lib/router/Upload"); const Form = require("./lib/router/Form"); const JSON = require("./lib/router/JSON"); const XML = require("./lib/router/XML"); module.exports = { HTTPServer: HTTPServer, HTTPSServer: HTTPSServer, Session: Session, Static: Static, RequestLog: RequestLog, ServerError: ServerError, Upload: Upload, Form: Form, JSON: JSON, XML: XML };
/* eslint-disable no-useless-escape */ import React from 'react'; import { Progress, Icon } from 'antd'; import commaNumber from 'comma-number'; import styled from 'styled-components'; import { withRouter, RouteComponentProps } from 'react-router-dom'; import { Card } from 'components/Basic/Card'; const HoldingWrapper = styled.div` width: 100%; height: 100%; border-radius: 20px; background-color: var(--color-bg-primary); padding: 27px 43px 39px; .title { font-size: 17px; font-weight: 900; color: var(--color-text-main); margin-bottom: 23px; } .holding-section { padding: 19px 0 30px; border-top: 1px solid var(--color-bg-active); .label { font-size: 16px; font-weight: normal; color: var(--color-text-secondary); } .value { font-size: 20px; font-weight: 900; color: var(--color-text-main); } .voting-count { font-size: 16px; font-weight: normal; color: var(--color-text-secondary); span { margin: 0 20px 0; } } } .ant-progress-inner { background-color: var(--color-bg-primary); } `; const format = commaNumber.bindWith(',', '.'); interface Props extends RouteComponentProps { address: string; holdingInfo: { balance?: string; delegateCount?: string; votes?: string; delegates?: string; }; } function Holding({ address, holdingInfo }: Props) { return ( <Card> <HoldingWrapper className="flex flex-column"> <div className="title">Holding</div> <div className="flex flex-column holding-section"> <div className="label">Venus Balance</div> <div className="value">{format(holdingInfo.balance || '0.0000')}</div> </div> <div className="flex flex-column holding-section"> <div className="flex align-center just-between"> <div className="label">Votes</div> <div className="flex align-center voting-count"> <Icon type="user" /> <span>{holdingInfo.delegateCount || 0}</span> </div> </div> <div className="value">{format(holdingInfo.votes || '0.0000')}</div> <Progress percent={100} strokeColor="var(--color-blue-hover)" strokeWidth={7} showInfo={false} /> </div> <div className="flex flex-column holding-section"> <div className="label">Delegating To</div> <div className="value"> {holdingInfo.delegates !== '0x0000000000000000000000000000000000000000' && holdingInfo.delegates !== address.toLowerCase() ? 'Delegated' : 'Undelegated'} </div> </div> </HoldingWrapper> </Card> ); } Holding.defaultProps = { address: '', holdingInfo: {}, }; export default withRouter(Holding);
<reponame>luomoxu/myreplication<gh_stars>100-1000 package myreplication type ( fieldList struct { } ) func (q *fieldList) writeServer(table string) *pack { pack := newPack() pack.WriteByte(_COM_FIELD_LIST) pack.writeStringNil(table) return pack }
package simulation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 17822번: 원판 돌리기 * * @see https://www.acmicpc.net/problem/17822/ * */ public class Boj17822 { private static int[][] circle; private static final int[][] DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; private static final int ROW = 0, COL = 1; private static class Query{ int x; int d; int k; public Query(int x, int d, int k) { this.x = x; this.d = d; this.k = k; } } private static class Pair{ int row; int col; public Pair(int row, int col) { this.row = row; this.col = col; } } public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int T = Integer.parseInt(st.nextToken()); circle = new int[N][M]; for(int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for(int j = 0; j < M; j++) { circle[i][j] = Integer.parseInt(st.nextToken()); } } Query[] q = new Query[T]; for(int i = 0; i < T; i++) { st = new StringTokenizer(br.readLine()); q[i] = new Query(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()) % M); } rotation(N, M, q); System.out.println(getSum()); } private static void rotation(int n, int m, Query[] query) { LinkedList<Pair> remove = new LinkedList<>(); for(Query q: query) { rotate(n, q); for(int row = 0; row < n; row++) { for(int col = 0; col < m; col++) { if(circle[row][col] == 0) continue; int current = circle[row][col]; boolean flag = false; for(final int[] DIRECTION: DIRECTIONS) { int nextRow = row + DIRECTION[ROW]; int nextCol = col + DIRECTION[COL]; if(nextRow < 0 || nextRow >= n) continue; if(nextCol < 0) nextCol += m; else if(nextCol >= m) nextCol %= m; if(current == circle[nextRow][nextCol]) { // save remove number remove.add(new Pair(nextRow, nextCol)); flag = true; } } if(flag) remove.add(new Pair(row, col)); } } if(remove.size() == 0) valueModify(); // if not get avg while(!remove.isEmpty()) { Pair p = remove.remove(); circle[p.row][p.col] = 0; } } } private static int getSum() { int sum = 0; for(int i = 0; i < circle.length; i++) { for(int j = 0; j < circle[i].length; j++) { sum += circle[i][j]; } } return sum; } private static void rotate(int n, Query q) { int loop = q.x; int time = loop; while(loop <= n) { // rotate each dishes int idx = loop - 1; if(q.d == 0) move(q.k, idx); // cw else move(-q.k, idx); // ccw loop += time; } } private static void move(int adder, int idx) { int[] tmp = new int[circle[idx].length]; for(int i = 0; i < circle[idx].length; i++) { int val = i + adder; val %= circle[idx].length; if(val < 0) val += circle[idx].length; tmp[val] = circle[idx][i]; // rotate position decision } for(int i = 0; i < circle[idx].length; i++) { circle[idx][i] = tmp[i]; } } private static void valueModify() { double avg = 0.0; int count = 0; for(int idx = 0; idx < circle.length; idx++) { // get sum for(int i = 0; i < circle[idx].length; i++) { if(circle[idx][i] == 0) continue; avg += circle[idx][i]; count++; } } avg /= count; for(int idx = 0; idx < circle.length; idx++) { for(int i = 0; i < circle[idx].length; i++) { if(circle[idx][i] == 0) continue; if(circle[idx][i] < avg) circle[idx][i]++; else if(circle[idx][i] > avg) circle[idx][i]--; } } } }
#!/bin/bash NUMTHREADS=$(nproc) export NUMTHREADS cd /vagrant cd msautotest python -m SimpleHTTPServer &> /dev/null & cd .. mkdir build_vagrant touch maplexer.l touch mapparser.y flex --nounistd -Pmsyy -i -omaplexer.c maplexer.l yacc -d -omapparser.c mapparser.y cd build_vagrant cmake -G "Unix Makefiles" -DWITH_CLIENT_WMS=1 \ -DWITH_CLIENT_WFS=1 -DWITH_KML=1 -DWITH_SOS=1 -DWITH_PHP=1 \ -DWITH_PYTHON=1 -DWITH_JAVA=0 -DWITH_THREAD_SAFETY=1 \ -DWITH_FCGI=0 -DWITH_EXEMPI=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DWITH_RSVG=1 -DWITH_CURL=1 -DWITH_FRIBIDI=1 -DWITH_HARFBUZZ=1 \ -DPROJ_INCLUDE_DIR=/vagrant/install-vagrant-proj-6/include_proj4_api_only -DPROJ_LIBRARY=/vagrant/install-vagrant-proj-6/lib/libproj.so.15 \ -DCMAKE_C_FLAGS="-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H -DPROJ_RENAME_SYMBOLS" -DCMAKE_CXX_FLAGS="-DACCEPT_USE_OF_DEPRECATED_PROJ_API_H -DPROJ_RENAME_SYMBOLS" \ .. make -j $NUMTHREADS sudo make install cd .. mkdir build_vagrant_proj6 cd build_vagrant_proj6 cmake -G "Unix Makefiles" -DWITH_CLIENT_WMS=1 \ -DWITH_CLIENT_WFS=1 -DWITH_KML=1 -DWITH_SOS=1 -DWITH_PHP=1 \ -DWITH_PYTHON=1 -DWITH_JAVA=0 -DWITH_THREAD_SAFETY=1 \ -DWITH_FCGI=0 -DWITH_EXEMPI=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DWITH_RSVG=1 -DWITH_CURL=1 -DWITH_FRIBIDI=1 -DWITH_HARFBUZZ=1 \ -DPROJ_INCLUDE_DIR=/vagrant/install-vagrant-proj-6/include -DPROJ_LIBRARY=/vagrant/install-vagrant-proj-6/lib/libproj.so.15 \ -DCMAKE_C_FLAGS="-DPROJ_RENAME_SYMBOLS" -DCMAKE_CXX_FLAGS="-DPROJ_RENAME_SYMBOLS" \ .. make -j $NUMTHREADS cd ..
#!/bin/bash -eu function check_exit_status() { if [ "$1" != 0 ]; then exit 1 fi } function check_equal_file() { local src local target src=$(shasum -a 256 "$1" | awk '{print $1}') target=$(shasum -a 256 "$2" | awk '{print $1}') test "${src}" = "${target}" } function check_file_existence() { test -f "$1" } function do_test() { shellcheck start_setting.sh check_exit_status $? shellcheck test.sh check_exit_status $? ./start_setting.sh check_exit_status $? check_equal_file zshrc ~/.zshrc check_exit_status $? check_equal_file vimrc ~/.vimrc check_exit_status $? check_file_existence ~/.zsh/completion/_docker check_exit_status $? check_file_existence ~/.zsh/completion/_docker-compose check_exit_status $? check_file_existence ~/.zsh/completion/git-prompt.sh check_exit_status $? check_file_existence ~/.gitconfig check_exit_status $? vint vimrc check_exit_status $? grunt zshlint check_exit_status $? } function main() { do_test do_test } main
def findPosition(array, givenValue): for i in range(len(array)): if array[i] == givenValue: return i return -1 position = findPosition(array, givenValue)
<filename>modules/coverage-report/src/test/java/org/jooby/hbs/HbsCustomFeature.java<gh_stars>0 package org.jooby.hbs; import org.jooby.Results; import org.jooby.test.ServerFeature; import org.junit.Test; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; public class HbsCustomFeature extends ServerFeature { { use(new Hbs().doWith((h, c) -> { h.with(new ClassPathTemplateLoader("/org/jooby/hbs", ".html")); })); get("/", req -> Results.html("index").put("model", req.param("model").value())); } @Test public void hbs() throws Exception { request() .get("/?model=jooby") .expect("<html><title>/org/jooby/hbs/index.html:index</title><body>jooby</body></html>"); } }
#!/bin/bash sudo systemctl reload-or-restart tezos-node.service # No longer needed in Ithaca # sudo systemctl reload-or-restart tezos-endorser.service sudo systemctl reload-or-restart tezos-accuser.service sudo systemctl reload-or-restart tezos-baker.service
<filename>md5/md5_test.go package md5 import ( "testing" ) func TestUnsaltedMD5PasswordEncode(t *testing.T) { encoded, err := NewUnsaltedMD5PasswordHasher().Encode("this-is-my-password") if err != nil { t.Fatalf("Encode error: %s", err) } expected := "d24c80177269fb85874b1361e6b71fb4" if encoded != expected { t.Fatalf("Encoded hash %s does not match %s.", encoded, expected) } } func TestUnsaltedMD5PasswordVerify1(t *testing.T) { valid, err := NewUnsaltedMD5PasswordHasher().Verify("this-is-my-password", "<PASSWORD>") if err != nil { t.Fatalf("Verify error: %s", err) } if !valid { t.Fatal("Password should be valid.") } } func TestUnsaltedMD5PasswordVerify2(t *testing.T) { valid, err := NewUnsaltedMD5PasswordHasher().Verify("this-is-my-password", "<PASSWORD>") if err != nil { t.Fatalf("Verify error: %s", err) } if !valid { t.Fatal("Password should be valid.") } } func TestMD5PasswordEncode(t *testing.T) { encoded, err := NewMD5PasswordHasher().Encode("this-is-my-password", "<PASSWORD>") if err != nil { t.Fatalf("Encode error: %s", err) } expected := "md5$NMxMaHPlUEr7$5b7913a35d0cfbbd3e5ef243<PASSWORD>" if encoded != expected { t.Fatalf("Encoded hash %s does not match %s.", encoded, expected) } } func TestMD5PasswordVerify(t *testing.T) { valid, err := NewMD5PasswordHasher().Verify("<PASSWORD>", "<PASSWORD>") if err != nil { t.Fatalf("Verify error: %s", err) } if !valid { t.Fatal("Password should be valid.") } }
#!/bin/sh # This script copies files from the nettle upstream, with necessary # adjustments for bundling in GnuTLS. set +e : ${srcdir=.} SRC=$srcdir/devel/nettle DST=$srcdir/lib/nettle/backport IMPORTS=" block-internal.h cfb.c cfb.h cmac.c cmac.h cmac-aes128.c cmac-aes256.c chacha-core-internal.c chacha-crypt.c chacha-internal.h chacha-poly1305.c chacha-poly1305.h chacha-set-key.c chacha-set-nonce.c chacha.h poly1305-internal.c poly1305-internal.h poly1305.h xts.c xts.h xts-aes128.c xts-aes256.c siv-cmac.c siv-cmac.h siv-cmac-aes128.c siv-cmac-aes256.c " PUBLIC=" aes.h bignum.h ctr.h des.h ecc-curve.h ecc.h macros.h memops.h memxor.h nettle-meta.h nettle-types.h " test -d $DST || mkdir $DST for f in $IMPORTS; do src=$SRC/$f dst=$DST/$f if test -f $src; then if test -f $dst; then echo "Replacing $dst (existing file backed up in $dst~)" mv $dst $dst~ else echo "Copying file $dst" fi cp $src $dst # Use <nettle/*.h> for public headers. for h in $PUBLIC; do p=$(echo $h | sed 's/\./\\./g') if grep '^#include "'$p'"' $dst 2>&1 >/dev/null; then sed 's!^#include "'$p'"!#include <nettle/'$h'>!' $dst > $dst-t && \ mv $dst-t $dst fi done # Remove unused <assert.h>. if grep '^#include <assert\.h>' $dst 2>&1 >/dev/null; then if ! grep 'assert *(' $dst 2>&1 >/dev/null; then sed '/^#include <assert\.h>/d' $dst > $dst-t && mv $dst-t $dst fi fi case $dst in *.h) # Rename header guard so as not to conflict with the public ones. if grep '^#ifndef NETTLE_.*_H\(_INCLUDED\)*' $dst 2>&1 >/dev/null; then g=$(sed -n 's/^#ifndef NETTLE_\(.*_H\(_INCLUDED\)*\)/\1/p' $dst) sed 's/\(NETTLE_'$g'\)/GNUTLS_LIB_NETTLE_BACKPORT_\1/' $dst > $dst-t && \ mv $dst-t $dst fi ;; esac case $dst in *.h) # Add prefix to function symbols avoid clashing with the public ones. sed -e 's/^#define \(.*\) nettle_\1/#define \1 gnutls_nettle_backport_\1/' \ -e 's/^#define _\(.*\) _nettle_\1/#define _\1 _gnutls_nettle_backport_\1/' \ -e 's/^#define \(.*\) _nettle_\1/#define \1 _gnutls_nettle_backport_\1/' \ $dst > $dst-t && \ mv $dst-t $dst ;; esac case $dst in */cfb.c | */cmac.c | */xts.c | */siv-cmac.c) sed \ -e 's/"nettle-internal\.h"/"nettle-alloca.h"/' \ $dst > $dst-t && mv $dst-t $dst ;; esac case $dst in */*.[ch]) sed \ -e '/^#include <nettle\/nettle-types\.h>/a\ #include "block8.h" ' \ $dst > $dst-t && mv $dst-t $dst ;; esac case $dst in */siv-cmac*.[ch]) sed \ -e '/^#include "cmac\.h"/ { i\ #ifdef HAVE_NETTLE_CMAC128_UPDATE\ #include <nettle/cmac.h>\ #else\ #include "cmac.h"\ #endif ; d }' \ $dst > $dst-t && mv $dst-t $dst ;; esac else echo "Error: $src not found" 1>&2 exit 1 fi done
int findMaxSumSubArray(int arr[], int n, int k) { int maxSum = 0; int winSum = 0; int winStart = 0; // Find the sum of first window of size k for (int i = 0; i < k; i++) winSum += arr[i]; // Slide the window for (int i = k; i < n; i++) { // Remove first element of previous window winSum -= arr[i - k]; // Add new element of current window winSum += arr[i]; // Update maximum window sum maxSum = Math.max(maxSum, winSum); } return maxSum; } int[] arr = {2, 1, 5, 1, 3, 2}; int k = 3; int maxSum = findMaxSumSubArray(arr, arr.length, k); System.out.println(maxSum); // 9
#!/bin/bash source activate /gs/hs0/tgb-deepmt/bugliarello.e/envs/volta seed=27 cd ../../../../code/volta python eval_task.py \ --bert_model bert-base-uncased --config_file config/ctrl_lxmert.json --tasks_config_file config_tasks/ctrl_test_tasks.yml \ --from_pretrained /gs/hs0/tgb-deepmt/bugliarello.e/checkpoints/mpre-unmasked/nlvr2/volta/ctrl_lxmert_s${seed}/NLVR2_ctrl_lxmert/pytorch_model_8.bin \ --task 12 \ --output_dir /gs/hs0/tgb-deepmt/bugliarello.e/results/mpre-unmasked/nlvr2/volta/ctrl_lxmert_s${seed} conda deactivate
// https://codeforces.com/contest/897/problem/A #include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; string s; cin >> s; for (int i = 0; i < m; i++) { int l, r; char c1, c2; cin >> l >> r >> c1 >> c2; for (int j = l - 1; j < r; j++) if (s[j] == c1) s[j] = c2; } cout << s << endl; }
require 'rails_helper' module Generators::Reports describe IrsTaxHousehold do subject { IrsTaxHousehold.new(tax_household, policy_ids) } let(:tax_household) { double(tax_household_members: tax_household_members, household: household) } let(:household) { double(family: family)} let(:family) { double } let(:tax_household_members) { [ member1 ] } let(:member1) { double(tax_filing_status: 'non_filer', family_member: family_member1) } let(:family_member1) { double(person: double) } let(:family_member2) { double(person: double) } let(:family_member3) { double(person: double) } let(:policy_ids) { [1234] } let(:policies) { [ double(subscriber: family_member2, id: 1234, enrollees: enrollees) ] } let(:enrollees) { [family_member1, family_member2, family_member3] } before(:each) do allow(subject).to receive(:find_policies).with(policy_ids).and_return(policies) end context 'when there is no tax_filer' do it 'should return primary as nil' do subject.build expect(subject.primary).to be_nil end end context 'when there is a single tax_filer' do let(:member1) { double(tax_filing_status: 'tax_filer', family_member: family_member1) } it 'should return tax_filer as primary' do subject.build expect(subject.primary).to eq(member1) end end context 'when there is a single tax_filer with dependents' do let(:member1) { double(tax_filing_status: 'tax_filer', family_member: family_member1) } let(:member2) { double(tax_filing_status: 'dependent', family_member: family_member2) } let(:member3) { double(tax_filing_status: 'dependent', family_member: family_member3) } let(:tax_household_members) { [ member1, member2, member3 ] } it 'should return primary and dependents' do subject.build expect(subject.primary).to eq(member1) expect(subject.dependents).to eq([member2, member3]) end end context 'when there are multiple tax filers' do let(:member1) { double(tax_filing_status: 'tax_filer', family_member: family_member1) } let(:member2) { double(tax_filing_status: 'tax_filer', family_member: family_member2) } let(:member3) { double(tax_filing_status: 'dependent', family_member: family_member3) } let(:tax_household_members) { [ member1, member2, member3 ] } context 'primary applicant matches with tax_filer' do let(:family) { double(primary_applicant: family_member2) } it 'should return primary applicant as tax primary' do allow(member1).to receive(:tax_filing_together?).and_return(true) allow(member2).to receive(:tax_filing_together?).and_return(true) subject.build expect(subject.primary).to eq(member2) expect(subject.spouse).to eq(member1) end end context 'primary applicant not matches with tax_filer' do let(:family) { double(primary_applicant: double) } it 'should return policy subscriber as primary' do allow(member1).to receive(:tax_filing_together?).and_return(true) allow(member2).to receive(:tax_filing_together?).and_return(true) subject.build expect(subject.primary).to eq(member2) expect(subject.spouse).to eq(member1) end end end context 'when there is a tax_filer and non_filer' do let(:member1) { double(tax_filing_status: 'tax_filer', family_member: family_member1) } let(:member2) { double(tax_filing_status: 'non_filer', family_member: family_member2) } let(:member3) { double(tax_filing_status: 'dependent', family_member: family_member3) } let(:tax_household_members) { [ member1, member2, member3 ] } let(:family_member1) { double(person: double, rel_code: 'self') } let(:family_member3) { double(person: double, rel_code: 'child') } context 'where non_filer has spouse relation ship on the policy' do let(:family_member2) { double(person: double, rel_code: 'spouse') } it 'should return primary, spouse and dependents' do subject.build expect(subject.primary).to eq(member1) expect(subject.spouse).to eq(member2) expect(subject.dependents).to eq([member3]) end end context 'where non_filer has self relationship on the policy' do let(:family_member2) { double(person: double, rel_code: 'self') } let(:family_member1) { double(person: double, rel_code: 'spouse') } it 'should return primary, spouse and dependents' do subject.build expect(subject.primary).to eq(member1) expect(subject.spouse).to eq(member2) expect(subject.dependents).to eq([member3]) end end context 'where non_filer has child relationship on the policy' do let(:family_member2) { double(person: double, rel_code: 'child') } it 'should return primary, spouse and dependents' do subject.build expect(subject.primary).to eq(member1) expect(subject.spouse).to be_nil expect(subject.dependents).to eq([member2, member3]) end end end end end
// Function to rotate a matrix by 90 degrees const rotate90Degree = (mat) => { // Transpose of Matrix for (let row = 0; row < mat.length; row ++) { for (let col = row + 1; col < mat[row].length; col ++) { // Swapping the elements [mat[row][col], mat[col][row]] = [mat[col][row], mat[row][col]] } } // Reverse each row for(let row = 0; row < mat.length; row ++) { mat[row].reverse(); } return mat; }; // Function to translate a matrix by (x, y) units const translateMatrix= (mat, x, y) => { for (let row = 0; row < mat.length; row ++) { for (let col = 0; col < mat[row].length; col ++) { // Translating the matrix by x y axis mat[row][col] += (x + y); } } return mat; }
#!/bin/bash # Copyright 2020 Google LLC # # 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 # # https://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. if [ "${TWINE_PASSWORD}" == "" ] then TWINE_PASSWORD=$(gcloud secrets versions access latest --secret="data-validation" --project=${PROJECT_ID}) fi python3 -m pip install --upgrade build setuptools twine wheel python3 -m build python3 -m twine upload dist/*
using System; using System.Net.Http; namespace YourNamespace { public class SlmGetLifecycleRequestDescriptor { private readonly Action<SlmGetLifecycleRequestDescriptor> _configure; internal SlmGetLifecycleRequestDescriptor(Action<SlmGetLifecycleRequestDescriptor> configure) => configure.Invoke(this); public SlmGetLifecycleRequestDescriptor() { } internal ApiUrls ApiUrls => ApiUrlsLookups.SnapshotLifecycleManagementGetLifecycle; protected HttpMethod HttpMethod => HttpMethod.Get; protected bool SupportsBody => false; public SlmGetLifecycleRequestDescriptor PolicyId(Elastic.Clients.Elasticsearch.Names? policy_id) { // Implement the logic to set the policy ID for the request // Example: this.PolicyId = policy_id; return this; } } // Placeholder for ApiUrlsLookups and Elastic.Clients.Elasticsearch.Names internal class ApiUrlsLookups { public static ApiUrls SnapshotLifecycleManagementGetLifecycle => new ApiUrls("https://example.com/api/slm/get-lifecycle"); } internal class ApiUrls { public string Url { get; } public ApiUrls(string url) { Url = url; } } }
SELECT c.CustomerName, SUM(o.OrderAmount) FROM Orders o INNER JOIN Customers c ON o.CustomerID = c.CustomerID GROUP BY c.CustomerName;
""" Visualize a comparison of revenue between two stores """ import matplotlib.pyplot as plt store_A_revenue = 20 store_B_revenue = 50 # Defining labels stores = ['Store A', 'Store B'] # Plotting a bar graph plt.bar(stores, [store_A_revenue, store_B_revenue]) # Naming the x-axis plt.xlabel('Stores') # Naming the y-axis plt.ylabel('Revenue') # Show the plot plt.show()
<gh_stars>1-10 import 'dotenv/config' const config = { app: { port: 4000 }, sendgridApiKey: process.env.SENDGRID_API_KEY, ipfsGatewayUri: process.env.IPFS_GATEWAY_URI || 'https://ipfs.infura.io', s3: { accessKeyId: process.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY, endpoint: process.env.S3_ENDPOINT }, powergate: { host: process.env.POWERGATE_HOST || 'http://localhost:6002', token: process.env.POWERGATE_TOKEN } } export default config